Programs & Examples On #Appserver

Could not load file or assembly 'CrystalDecisions.ReportAppServer.CommLayer, Version=13.0.2000.0

As I said in comment your crystaldecisions.reportappserver.commlayer.dll is not copied / present on your server. So for this you have to manually copy the dll and paste into you Bin folder

To copy a DLL from visual studio project follow the steps

1.Expand your Project's References hierarchy (Project should not be in debug mod)

2.Right Click on Particular Dll (in your case crystaldecisions.reportappserver.commlayer.dll) and select Properties and set 'Copy Local' attribute to TRUE

3 Build your project. The Dll should be there in your BIN Folder.

enter image description here

Spring Boot - Cannot determine embedded database driver class for database type NONE

Already enough of answers were posted. However, I'm posting what mistake i did and how i corrected it.

In my case, i had packaged my project as pom instead of jar

pom.xml:

...
 <packaging>pom</packaging>
...

Changed to:

...
 <packaging>jar</packaging>
...

It may helpful for someone with the same mistake.

How do I fix MSB3073 error in my post-build event?

In my case, the dll I was creating by building the project was still in use in the background. I killed the application and then xcopy worked fine as expected.

Unable to open debugger port in IntelliJ

Answer is pretty simple, I also faced the problem finally I got perfect solution. Create Debug Create Remote debug with following configuration Firstly run by debug. It gives you waitng for socket 5005 then run with remote debug

AppFabric installation failed because installer MSI returned with error code : 1603

I finally made it. I was able to install AppFabric for Win Server 2012 R2. I am not really sure what exact change made it worked. I saw and tried many many solutions from various websites but above solution of making changes to Registry - 'HKEY_CLASSES_ROOT'worked (please think twice before making changes to Registry on production environment - this was my demo environment so I just went ahead); I changed the temporary folder path but it did not worked first time. Then I deleted the registry entry and then uninstalled AppFabric 1.1 pre-installed instance from Control panel. Then I tried Installation and it worked. This also restored the Registry entry.

Could not load file or assembly CrystalDecisions.ReportAppServer.ClientDoc

It turns out the answer was ridiculously simple, but mystifying as to why it was necessary.

In the IIS Manager on the server, I set the application pool for my web application to not allow 32-bit assemblies.

It seems it assumes, on a 64-bit system, that you must want the 32 bit assembly. Bizarre.

Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect)

This error occurred for me when I was trying to update the same row from 2 different sessions. I updated a field in one browser while a second was open and had already stored the original object in its session. When I attempted to update from this second "stale" session I get the stale object error. In order to correct this I refetch my object to be updated from the database before I set the value to be updated, then save it as normal.

Crystal Reports 13 And Asp.Net 3.5

I had this same problem and resolved it by making sure all references to the previous version of crystal from the Web Config file, the server, and the publishing workstation were removed. Other than the full trust basically everything that user707217 did, I did and it worked for my upgraded Web application

(SC) DeleteService FAILED 1072

What I've done is go to this location in regedit:

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services

From here, you will see a folder for every service on your machine. Simply delete the folder for the service you wish, and you're done.

N.B: Stop the service before you try this.

Unloading classes in java?

Classes have an implicit strong reference to their ClassLoader instance, and vice versa. They are garbage collected as with Java objects. Without hitting the tools interface or similar, you can't remove individual classes.

As ever you can get memory leaks. Any strong reference to one of your classes or class loader will leak the whole thing. This occurs with the Sun implementations of ThreadLocal, java.sql.DriverManager and java.beans, for instance.

What is a stack trace, and how can I use it to debug my application errors?

I am posting this answer so the topmost answer (when sorted by activity) is not one that is just plain wrong.

What is a Stacktrace?

A stacktrace is a very helpful debugging tool. It shows the call stack (meaning, the stack of functions that were called up to that point) at the time an uncaught exception was thrown (or the time the stacktrace was generated manually). This is very useful because it doesn't only show you where the error happened, but also how the program ended up in that place of the code. This leads over to the next question:

What is an Exception?

An Exception is what the runtime environment uses to tell you that an error occurred. Popular examples are NullPointerException, IndexOutOfBoundsException or ArithmeticException. Each of these are caused when you try to do something that is not possible. For example, a NullPointerException will be thrown when you try to dereference a Null-object:

Object a = null;
a.toString();                 //this line throws a NullPointerException

Object[] b = new Object[5];
System.out.println(b[10]);    //this line throws an IndexOutOfBoundsException,
                              //because b is only 5 elements long
int ia = 5;
int ib = 0;
ia = ia/ib;                   //this line throws an  ArithmeticException with the 
                              //message "/ by 0", because you are trying to
                              //divide by 0, which is not possible.

How should I deal with Stacktraces/Exceptions?

At first, find out what is causing the Exception. Try googleing the name of the exception to find out, what is the cause of that exception. Most of the time it will be caused by incorrect code. In the given examples above, all of the exceptions are caused by incorrect code. So for the NullPointerException example you could make sure that a is never null at that time. You could, for example, initialise a or include a check like this one:

if (a!=null) {
    a.toString();
}

This way, the offending line is not executed if a==null. Same goes for the other examples.

Sometimes you can't make sure that you don't get an exception. For example, if you are using a network connection in your program, you cannot stop the computer from loosing it's internet connection (e.g. you can't stop the user from disconnecting the computer's network connection). In this case the network library will probably throw an exception. Now you should catch the exception and handle it. This means, in the example with the network connection, you should try to reopen the connection or notify the user or something like that. Also, whenever you use catch, always catch only the exception you want to catch, do not use broad catch statements like catch (Exception e) that would catch all exceptions. This is very important, because otherwise you might accidentally catch the wrong exception and react in the wrong way.

try {
    Socket x = new Socket("1.1.1.1", 6789);
    x.getInputStream().read()
} catch (IOException e) {
    System.err.println("Connection could not be established, please try again later!")
}

Why should I not use catch (Exception e)?

Let's use a small example to show why you should not just catch all exceptions:

int mult(Integer a,Integer b) {
    try {
        int result = a/b
        return result;
    } catch (Exception e) {
        System.err.println("Error: Division by zero!");
        return 0;
    }
}

What this code is trying to do is to catch the ArithmeticException caused by a possible division by 0. But it also catches a possible NullPointerException that is thrown if a or b are null. This means, you might get a NullPointerException but you'll treat it as an ArithmeticException and probably do the wrong thing. In the best case you still miss that there was a NullPointerException. Stuff like that makes debugging much harder, so don't do that.

TLDR

  1. Figure out what is the cause of the exception and fix it, so that it doesn't throw the exception at all.
  2. If 1. is not possible, catch the specific exception and handle it.

    • Never just add a try/catch and then just ignore the exception! Don't do that!
    • Never use catch (Exception e), always catch specific Exceptions. That will save you a lot of headaches.

python getoutput() equivalent in subprocess

Use subprocess.Popen:

import subprocess
process = subprocess.Popen(['ls', '-a'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = process.communicate()
print(out)

Note that communicate blocks until the process terminates. You could use process.stdout.readline() if you need the output before it terminates. For more information see the documentation.

Fix CSS hover on iPhone/iPad/iPod

Some people don't know about this. You can apply it on div:hover and working on iPhone .

Add the following css to the element with :hover effect

.mm {
    cursor: pointer;
}

List of macOS text editors and code editors

Textmate is state of the Art editor, but if someone is thinking about developing on several platforms without awkward memory eaters monsters like jedit, eclipse, netbeans etc take a look at geany (geany.org). It is free. The only problem the editor has not esthetic look and feel on Mac OS X :)

HQL "is null" And "!= null" on an Oracle column

No. You have to use is null and is not null in HQL.

Disable submit button ONLY after submit

Reading the comments, it seems that these solutions are not consistent across browsers. Decided then to think how I would have done this 10 years ago before the advent of jQuery and event function binding.

So here is my retro hipster solution:

<script type="text/javascript">
var _formConfirm_submitted = false;
</script>
<form name="frmConfirm" onsubmit="if( _formConfirm_submitted == false ){ _formConfirm_submitted = true;return true }else{ alert('your request is being processed!'); return false;  }" action="" method="GET">

<input type="submit" value="submit - but only once!"/>
</form>

The main point of difference is that I am relying on the ability to stop a form submitting through returning false on the submit handler, and I am using a global flag variable - which will make me go straight to hell!

But on the plus side, I cannot imagine any browser compatibility issues - hey, it would probably even work in Netscape!

Exit a Script On Error

Are you looking for exit?

This is the best bash guide around. http://tldp.org/LDP/abs/html/

In context:

if jarsigner -verbose -keystore $keyst -keystore $pass $jar_file $kalias
then
    echo $jar_file signed sucessfully
else
    echo ERROR: Failed to sign $jar_file. Please recheck the variables 1>&2
    exit 1 # terminate and indicate error
fi

...

Oracle SQL - select within a select (on the same table!)

This is precisely the sort of scenario where analytics come to the rescue.

Given this test data:

SQL> select * from employment_history
  2  order by Gc_Staff_Number
  3             , start_date
  4  /

GC_STAFF_NUMBER START_DAT END_DATE  C
--------------- --------- --------- -
           1111 16-OCT-09           Y
           2222 08-MAR-08 26-MAY-09 N
           2222 12-DEC-09           Y
           3333 18-MAR-07 08-MAR-08 N
           3333 01-JUL-09 21-MAR-09 N
           3333 30-JUL-10           Y

6 rows selected.

SQL> 

An inline view with an analytic LAG() function provides the right answer:

SQL> select Gc_Staff_Number
  2             , start_date
  3             , prev_end_date
  4  from   (
  5      select Gc_Staff_Number
  6             , start_date
  7             , lag (end_date) over (partition by Gc_Staff_Number
  8                                    order by start_date )
  9                  as prev_end_date
 10             , current_flag
 11      from employment_history
 12  )
 13  where current_flag = 'Y'
 14  /

GC_STAFF_NUMBER START_DAT PREV_END_
--------------- --------- ---------
           1111 16-OCT-09
           2222 12-DEC-09 26-MAY-09
           3333 30-JUL-10 21-MAR-09

SQL>

The inline view is crucial to getting the right result. Otherwise the filter on CURRENT_FLAG removes the previous rows.

Why am I getting error CS0246: The type or namespace name could not be found?

I had the same issue when I clone my project from Git and directly build the solution first time. Instead of that go to the local repository in file explorer and double click the solution file (.sln) solved my issue.

Content Type text/xml; charset=utf-8 was not supported by service

Again, I stress that namespace, svc name and contract must be correctly specified in web.config file:

 <service name="NAMESPACE.SvcFileName">
    <endpoint contract="NAMESPACE.IContractName" />
  </service>

Example:

<service name="MyNameSpace.FileService">
<endpoint contract="MyNameSpace.IFileService" />
</service>

(Unrelevant tags ommited in these samples)

Hide keyboard in react-native

We can use keyboard and tochablewithoutfeedback from react-native

const DismissKeyboard = ({ children }) => (
  <TouchableWithoutFeedback
    onPress={() => Keyboard.dismiss()}
  >
    {children}
  </TouchableWithoutFeedback>
);

And use it in this way:

const App = () => (
  <DismissKeyboard>
    <View style={styles.container}>
      <TextInput
        style={styles.input}
        placeholder="username"
        keyboardType="numeric"
      />
      <TextInput
        style={styles.input}
        placeholder="password"
      />
    </View>
  </DismissKeyboard>
);

I also explained here with source code.

What is a lambda (function)?

The question has been answered fully, I don't want to go into details. I want to share the usage when writing numerical computation in rust.

There is an example of a lambda(anonymous function)

let f = |x: f32| -> f32 { x * x - 2.0 };
let df = |x: f32| -> f32 { 2.0 * x };

When I was writing a module of Newton–Raphson method, it was used as first and second order derivative. (If you want to know what is Newton–Raphson method, please visit "https://en.wikipedia.org/wiki/Newton%27s_method".

The output as the following

println!("f={:.6}      df={:.6}", f(10.0), df(10.0))

f=98.000000       df=20.000000

How to pass the button value into my onclick event function?

You can pass the element into the function <input type="button" value="mybutton1" onclick="dosomething(this)">test by passing this. Then in the function you can access the value like this:

function dosomething(element) {
  console.log(element.value);
}

How to read the content of a file to a string in C?

Another, unfortunately highly OS-dependent, solution is memory mapping the file. The benefits generally include performance of the read, and reduced memory use as the applications view and operating systems file cache can actually share the physical memory.

POSIX code would look like this:

int fd = open("filename", O_RDONLY);
int len = lseek(fd, 0, SEEK_END);
void *data = mmap(0, len, PROT_READ, MAP_PRIVATE, fd, 0);

Windows on the other hand is little more tricky, and unfortunately I don't have a compiler in front of me to test, but the functionality is provided by CreateFileMapping() and MapViewOfFile().

Magento How to debug blank white screen

I too had the same problem, but solved after disabling the compiler and again reinstalling the extension. Disable of the compiler can be done by system-> configration-> tools-> compilation.. Here Disable the process... Good Luck

How to remove all numbers from string?

For Western Arabic numbers (0-9):

$words = preg_replace('/[0-9]+/', '', $words);

For all numerals including Western Arabic (e.g. Indian):

$words = '????';
$words = preg_replace('/\d+/u', '', $words);
var_dump($words); // string(0) ""
  • \d+ matches multiple numerals.
  • The modifier /u enables unicode string treatment. This modifier is important, otherwise the numerals would not match.

Using GZIP compression with Spring Boot/MVC/JavaConfig with RESTful

I had the same problem into my Spring Boot+Spring Data project when invoking to a @RepositoryRestResource.

The problem is the MIME type returned; which is application/hal+json. Adding it to the server.compression.mime-types property solved this problem for me.

Hope this helps to someone else!

How to resolve 'unrecognized selector sent to instance'?

Mine was something simple/stupid. Newbie mistake, for anyone that has converted their NSManagedObject to a normal NSObject.

I had:

@dynamic order_id;

when i should have had:

@synthesize order_id;

POST string to ASP.NET Web Api application - returns null

I use this code to post HttpRequests.

/// <summary>
        /// Post this message.
        /// </summary>
        /// <param name="url">URL of the document.</param>
        /// <param name="bytes">The bytes.</param>
        public T Post<T>(string url, byte[] bytes)
    {
        T item;
        var request = WritePost(url, bytes);

        using (var response = request.GetResponse() as HttpWebResponse)
        {
            item = DeserializeResponse<T>(response);
            response.Close();
        }

        return item;
    }

    /// <summary>
    /// Writes the post.
    /// </summary>
    /// <param name="url">The URL.</param>
    /// <param name="bytes">The bytes.</param>
    /// <returns></returns>
    private static HttpWebRequest WritePost(string url, byte[] bytes)
    {
        ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, errors) => true;

        HttpWebRequest request = (HttpWebRequest) WebRequest.Create(url);
        Stream stream = null;
        try
        {
            request.Headers.Clear();
            request.PreAuthenticate = true;
            request.Connection = null;
            request.Expect = null;
            request.KeepAlive = false;
            request.ContentLength = bytes.Length;
            request.Timeout = -1;
            request.Method = "POST";
            stream = request.GetRequestStream();
            stream.Write(bytes, 0, bytes.Length);
        }
        catch (Exception e)
        {
            GetErrorResponse(url, e);
        }
        finally
        {
            if (stream != null)
            {
                stream.Flush();
                stream.Close();
            }
        }
        return request;
    }

In regards to your code, try it without the content.Type (request.ContentType = "application/x-www-form-urlencoded";)

update

I believe the problem lies with how you are trying to retrieve the value. When you do a POST and send bytes via the Stream, they will not be passed into the action as a parameter. You'll need to retrieve the bytes via the stream on the server.

On the server, try getting the bytes from stream. The following code is what I use.

     /// <summary> Gets the body. </summary>
     /// <returns> The body. </returns>
     protected byte[] GetBytes()
     {
       byte[] bytes;
        using (var binaryReader = new BinaryReader(Request.InputStream))
        {
            bytes = binaryReader.ReadBytes(Request.ContentLength);
        }

         return bytes;
     }

Could not find main class HelloWorld

It looks that you had done all setup properly but there might be one area where it might be causing problem

Check the value of your "CLASSPATH" variable and make sure at the end you kept ;.

Note: ; is for end separator . is for including existing path at the end

Simple and clean way to convert JSON string to Object in Swift

For Swift 4, i wrote this extension using the Codable protocol:

struct Business: Codable {
    var id: Int
    var name: String
}

extension String {

    func parse<D>(to type: D.Type) -> D? where D: Decodable {

        let data: Data = self.data(using: .utf8)!

        let decoder = JSONDecoder()

        do {
            let _object = try decoder.decode(type, from: data)
            return _object

        } catch {
            return nil
        }
    }
}

var jsonString = "[\n" +
    "{\n" +
    "\"id\":72,\n" +
    "\"name\":\"Batata Cremosa\",\n" +
    "},\n" +
    "{\n" +
    "\"id\":183,\n" +
    "\"name\":\"Caldeirada de Peixes\",\n" +
    "},\n" +
    "{\n" +
    "\"id\":76,\n" +
    "\"name\":\"Batata com Cebola e Ervas\",\n" +
    "},\n" +
    "{\n" +
    "\"id\":56,\n" +
    "\"name\":\"Arroz de forma\",\n" +
"}]"

let businesses = jsonString.parse(to: [Business].self)

Speed comparison with Project Euler: C vs Python vs Erlang vs Haskell

In regards to Python optimization, in addition to using PyPy (for pretty impressive speed-ups with zero change to your code), you could use PyPy's translation toolchain to compile an RPython-compliant version, or Cython to build an extension module, both of which are faster than the C version in my testing, with the Cython module nearly twice as fast. For reference I include C and PyPy benchmark results as well:

C (compiled with gcc -O3 -lm)

% time ./euler12-c 
842161320

./euler12-c  11.95s 
 user 0.00s 
 system 99% 
 cpu 11.959 total

PyPy 1.5

% time pypy euler12.py
842161320
pypy euler12.py  
16.44s user 
0.01s system 
99% cpu 16.449 total

RPython (using latest PyPy revision, c2f583445aee)

% time ./euler12-rpython-c
842161320
./euler12-rpy-c  
10.54s user 0.00s 
system 99% 
cpu 10.540 total

Cython 0.15

% time python euler12-cython.py
842161320
python euler12-cython.py  
6.27s user 0.00s 
system 99% 
cpu 6.274 total

The RPython version has a couple of key changes. To translate into a standalone program you need to define your target, which in this case is the main function. It's expected to accept sys.argv as it's only argument, and is required to return an int. You can translate it by using translate.py, % translate.py euler12-rpython.py which translates to C and compiles it for you.

# euler12-rpython.py

import math, sys

def factorCount(n):
    square = math.sqrt(n)
    isquare = int(square)
    count = -1 if isquare == square else 0
    for candidate in xrange(1, isquare + 1):
        if not n % candidate: count += 2
    return count

def main(argv):
    triangle = 1
    index = 1
    while factorCount(triangle) < 1001:
        index += 1
        triangle += index
    print triangle
    return 0

if __name__ == '__main__':
    main(sys.argv)

def target(*args):
    return main, None

The Cython version was rewritten as an extension module _euler12.pyx, which I import and call from a normal python file. The _euler12.pyx is essentially the same as your version, with some additional static type declarations. The setup.py has the normal boilerplate to build the extension, using python setup.py build_ext --inplace.

# _euler12.pyx
from libc.math cimport sqrt

cdef int factorCount(int n):
    cdef int candidate, isquare, count
    cdef double square
    square = sqrt(n)
    isquare = int(square)
    count = -1 if isquare == square else 0
    for candidate in range(1, isquare + 1):
        if not n % candidate: count += 2
    return count

cpdef main():
    cdef int triangle = 1, index = 1
    while factorCount(triangle) < 1001:
        index += 1
        triangle += index
    print triangle

# euler12-cython.py
import _euler12
_euler12.main()

# setup.py
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext

ext_modules = [Extension("_euler12", ["_euler12.pyx"])]

setup(
  name = 'Euler12-Cython',
  cmdclass = {'build_ext': build_ext},
  ext_modules = ext_modules
)

I honestly have very little experience with either RPython or Cython, and was pleasantly surprised at the results. If you are using CPython, writing your CPU-intensive bits of code in a Cython extension module seems like a really easy way to optimize your program.

HTML: Changing colors of specific words in a string of text

<p style="font-size:14px; color:#538b01; font-weight:bold; font-style:italic;">
  Enter the competition by 
  <span style="color: #ff0000">January 30, 2011</span>
  and you could win up to $$$$ — including amazing 
  <span style="color: #0000a0">summer</span> 
  trips!
</p>

Or you may want to use CSS classes instead:

<html>
  <head>
    <style type="text/css">
      p { 
        font-size:14px; 
        color:#538b01; 
        font-weight:bold; 
        font-style:italic;
      }
      .date {
        color: #ff0000;
      }
      .season { /* OK, a bit contrived... */
        color: #0000a0;
      }
    </style>
  </head>
  <body>
    <p>
      Enter the competition by 
      <span class="date">January 30, 2011</span>
      and you could win up to $$$$ — including amazing 
      <span class="season">summer</span> 
      trips!
    </p>
  </body>
</html>

How to remove folders with a certain name

I had more than 100 files like

log-12
log-123
log-34
....

above answers did not work for me

but the following command helped me.

find . -name "log-*" -exec rm  -rf {} \;

i gave -type as . so it deletes both files and folders which starts with log-

and rm -rf deletes folders recursively even it has files.

if you want folders alone

find -type d -name "log-*" -exec rm  -rf {} \;

files alone

find -type f -name "log-*" -exec rm  -rf {} \;

Difference between "include" and "require" in php

As others pointed out, the only difference is that require throws a fatal error, and include - a catchable warning. As for which one to use, my advice is to stick to include. Why? because you can catch a warning and produce a meaningful feedback to end users. Consider

  // Example 1.
  // users see a standard php error message or a blank screen
  // depending on your display_errors setting
  require 'not_there'; 


  // Example 2.
  // users see a meaningful error message
  try {
      include 'not_there';
  } catch(Exception $e) {
     echo "something strange happened!";
  }

NB: for example 2 to work you need to install an errors-to-exceptions handler, as described here http://www.php.net/manual/en/class.errorexception.php

  function exception_error_handler($errno, $errstr, $errfile, $errline ) {
     throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
  }
  set_error_handler("exception_error_handler");   

How do I add a bullet symbol in TextView?

You may try BulletSpan as described in Android docs.

SpannableString string = new SpannableString("Text with\nBullet point");
string.setSpan(new BulletSpan(40, color, 20), 10, 22, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

Result

C# error: Use of unassigned local variable

A couple of different ways to solve the problem:

Just replace Environment.Exit with return. The compiler knows that return ends the method, but doesn't know that Environment.Exit does.

static void Main(string[] args) {
    if(args.Length != 0) {
       if(Byte.TryParse(args[0], out maxSize))
         queue = new Queue(){MaxSize = maxSize};
       else
         return;
    } else {
       return;   
}

Of course, you can really only get away with that because you're using 0 as your exit code in all cases. Really, you should return an int instead of using Environment.Exit. For this particular case, this would be my preferred method

static int Main(string[] args) {
    if(args.Length != 0) {
       if(Byte.TryParse(args[0], out maxSize))
         queue = new Queue(){MaxSize = maxSize};
       else
         return 1;
    } else {
       return 2;
    }
}

Initialize queue to null, which is really just a compiler trick that says "I'll figure out my own uninitialized variables, thank you very much". It's a useful trick, but I don't like it in this case - you have too many if branches to easily check that you're doing it properly. If you really wanted to do it this way, something like this would be clearer:

static void Main(string[] args) {
  Byte maxSize;
  Queue queue = null;

  if(args.Length == 0 || !Byte.TryParse(args[0], out maxSize)) {
     Environment.Exit(0);
  }
  queue = new Queue(){MaxSize = maxSize};

  for(Byte j = 0; j < queue.MaxSize; j++)
    queue.Insert(j);
  for(Byte j = 0; j < queue.MaxSize; j++)
    Console.WriteLine(queue.Remove());
}

Add a return statement after Environment.Exit. Again, this is more of a compiler trick - but is slightly more legit IMO because it adds semantics for humans as well (though it'll keep you from that vaunted 100% code coverage)

static void Main(String[] args) {
  if(args.Length != 0) {
     if(Byte.TryParse(args[0], out maxSize)) {
        queue = new Queue(){MaxSize = maxSize};
     } else {
        Environment.Exit(0);
        return;
     }
  } else { 
     Environment.Exit(0);
     return;
  }

  for(Byte j = 0; j < queue.MaxSize; j++)
     queue.Insert(j);
  for(Byte j = 0; j < queue.MaxSize; j++)
     Console.WriteLine(queue.Remove());
}

finding multiples of a number in Python

For the first ten multiples of 5, say

>>> [5*n for n in range(1,10+1)]
[5, 10, 15, 20, 25, 30, 35, 40, 45, 50]

if arguments is equal to this string, define a variable like this string

Don't forget about spaces:

source=""
samples=("")
if [ $1 = "country" ]; then
   source="country"
   samples="US Canada Mexico..."
else
  echo "try again"
fi

How do you send a Firebase Notification to all devices via CURL?

The most easiest way I came up with to send the push notification to all the devices is to subscribe them to a topic "all" and then send notification to this topic. Copy this in your main activity

FirebaseMessaging.getInstance().subscribeToTopic("all");

Now send the request as

{
   "to":"/topics/all",
   "data":
   {
      "title":"Your title",
      "message":"Your message"
      "image-url":"your_image_url"
   }
}

This might be inefficient or non-standard way, but as I mentioned above it's the easiest. Please do post if you have any better way to send a push notification to all the devices.

You can follow this tutorial if you're new to sending push notifications using Firebase Cloud Messaging Tutorial - Push Notifications using FCM


To send a message to a combination of topics, specify a condition, which is a boolean expression that specifies the target topics. For example, the following condition will send messages to devices that are subscribed to TopicA and either TopicB or TopicC:

{
   "data":
   {
      "title": "Your title",
      "message": "Your message"
      "image-url": "your_image_url"
   },
   "condition": "'TopicA' in topics && ('TopicB' in topics || 'TopicC' in topics)"
}

Read more about conditions and topics here on FCM documentation

Disable eslint rules for folder

The previous answers were in the right track, but the complete answer for this is going to Disabling rules only for a group of files, there you'll find the documentation needed to disable/enable rules for certain folders (Because in some cases you don't want to ignore the whole thing, only disable certain rules). Example:

{
    "env": {},
    "extends": [],
    "parser": "",
    "plugins": [],
    "rules": {},
    "overrides": [
      {
        "files": ["test/*.spec.js"], // Or *.test.js
        "rules": {
          "require-jsdoc": "off"
        }
      }
    ],
    "settings": {}
}

How can I select item with class within a DIV?

Try:

$('#mydiv').find('.myclass');

JS Fiddle demo.

Or:

$('.myclass','#mydiv');

JS Fiddle demo.

Or:

$('#mydiv .myclass');

JS Fiddle demo.

References:


Good to learn from the find() documentation:

The .find() and .children() methods are similar, except that the latter only travels a single level down the DOM tree.

HTTP 1.0 vs 1.1

A key compatibility issue is support for persistent connections. I recently worked on a server that "supported" HTTP/1.1, yet failed to close the connection when a client sent an HTTP/1.0 request. When writing a server that supports HTTP/1.1, be sure it also works well with HTTP/1.0-only clients.

Where do I find the line number in the Xcode editor?

To save $4.99 for a one time use and no dealing with HomeBrew and no counting empty lines.

  1. Open Terminal
  2. cd to your Xcode project
  3. Execute the following when inside your target project:

find . -name "*.swift" -print0 | xargs -0 wc -l

If you want to exclude pods:

find . -path ./Pods -prune -o -name "*.swift" -print0 ! -name "/Pods" | xargs -0 wc -l

If your project has objective c and swift:

find . -type d \( -path ./Pods -o -path ./Vendor \) -prune -o \( -iname \*.m -o -iname \*.mm -o -iname \*.h -o -iname \*.swift \) -print0 | xargs -0 wc -l

new Image(), how to know if image 100% loaded or not?

Using the Promise pattern:

function getImage(url){
        return new Promise(function(resolve, reject){
            var img = new Image()
            img.onload = function(){
                resolve(url)
            }
            img.onerror = function(){
                reject(url)
            }
            img.src = url
        })
    }

And when calling the function we can handle its response or error quite neatly.

getImage('imgUrl').then(function(successUrl){
    //do stufff
}).catch(function(errorUrl){
    //do stuff
})

High-precision clock in Python

On the same win10 OS system using "two distinct method approaches" there appears to be an approximate "500 ns" time difference. If you care about nanosecond precision check my code below.

The modifications of the code is based on code from user cod3monk3y and Kevin S.

OS: python 3.7.3 (default, date, time) [MSC v.1915 64 bit (AMD64)]

def measure1(mean):
    for i in range(1, my_range+1):
        x = time.time()
        
        td = x- samples1[i-1][2]
        if i-1 == 0:
            td = 0
        td = f'{td:.6f}'
        samples1.append((i, td, x))
        mean += float(td)
        print (mean)
        sys.stdout.flush()
        time.sleep(0.001)
    
    mean = mean/my_range
    
    return mean

def measure2(nr):
    t0 = time.time()
    t1 = t0
    while t1 == t0:
        t1 = time.time()
    td = t1-t0
    td = f'{td:.6f}'
    return (nr, td, t1, t0)

samples1 = [(0, 0, 0)]
my_range = 10
mean1    = 0.0
mean2    = 0.0

mean1 = measure1(mean1)

for i in samples1: print (i)

print ('...\n\n')

samples2 = [measure2(i) for i in range(11)]

for s in samples2:
    #print(f'time delta: {s:.4f} seconds')
    mean2 += float(s[1])
    print (s)
    
mean2 = mean2/my_range

print ('\nMean1 : ' f'{mean1:.6f}')
print ('Mean2 : ' f'{mean2:.6f}')

The measure1 results:

nr, td, t0
(0, 0, 0)
(1, '0.000000', 1562929696.617988)
(2, '0.002000', 1562929696.6199884)
(3, '0.001001', 1562929696.620989)
(4, '0.001001', 1562929696.62199)
(5, '0.001001', 1562929696.6229906)
(6, '0.001001', 1562929696.6239917)
(7, '0.001001', 1562929696.6249924)
(8, '0.001000', 1562929696.6259928)
(9, '0.001001', 1562929696.6269937)
(10, '0.001001', 1562929696.6279945)
...

The measure2 results:

nr, td , t1, t0
(0, '0.000500', 1562929696.6294951, 1562929696.6289947)
(1, '0.000501', 1562929696.6299958, 1562929696.6294951)
(2, '0.000500', 1562929696.6304958, 1562929696.6299958)
(3, '0.000500', 1562929696.6309962, 1562929696.6304958)
(4, '0.000500', 1562929696.6314962, 1562929696.6309962)
(5, '0.000500', 1562929696.6319966, 1562929696.6314962)
(6, '0.000500', 1562929696.632497, 1562929696.6319966)
(7, '0.000500', 1562929696.6329975, 1562929696.632497)
(8, '0.000500', 1562929696.633498, 1562929696.6329975)
(9, '0.000500', 1562929696.6339984, 1562929696.633498)
(10, '0.000500', 1562929696.6344984, 1562929696.6339984)

End result:

Mean1 : 0.001001 # (measure1 function)

Mean2 : 0.000550 # (measure2 function)

Re-ordering factor levels in data frame

Assuming your dataframe is mydf:

mydf$task <- factor(mydf$task, levels = c("up", "down", "left", "right", "front", "back"))

How to make a gap between two DIV within the same column

I'm assuming you want the two boxes in the sidebar to be next to each other horizontally, so something like this fiddle? That uses inline-block, or you could achieve the same thing by floating the boxes.

EDIT - I've amended the above fiddle to do what I think you want, though your question could really do with being clearer. Similar to @balexandre's answer, though I've used :nth-child(odd) instead. Both will work, or if support for older browsers is important you'll have to stick with another helper class.

How to set Java SDK path in AndroidStudio?

Click "use embedded JDK" on version Android Studio 3.2.1

click this box

How to count items in JSON object using command line?

The shortest expression is

curl 'http://…' | jq length

Python: instance has no attribute

Your class doesn't have a __init__(), so by the time it's instantiated, the attribute atoms is not present. You'd have to do C.setdata('something') so C.atoms becomes available.

>>> C = Residues()
>>> C.atoms.append('thing')

Traceback (most recent call last):
  File "<pyshell#84>", line 1, in <module>
    B.atoms.append('thing')
AttributeError: Residues instance has no attribute 'atoms'

>>> C.setdata('something')
>>> C.atoms.append('thing')   # now it works
>>> 

Unlike in languages like Java, where you know at compile time what attributes/member variables an object will have, in Python you can dynamically add attributes at runtime. This also implies instances of the same class can have different attributes.

To ensure you'll always have (unless you mess with it down the line, then it's your own fault) an atoms list you could add a constructor:

def __init__(self):
    self.atoms = []

jQuery won't parse my JSON from AJAX query

I had this issue and for a bit I used

eval('('+data+')')

to get the data returned in an object. but then later had other issues getting a 'missing ) in parenthetical' error and found out that jQuery has a function specifically for evaluating a string for a json structure:

$.parseJSON(data)

should do the trick. This is in addition to having your json string in the proper format of course..

How to get String Array from arrays.xml file

You can't initialize your testArray field this way, because the application resources still aren't ready.

Just change the code to:

package com.xtensivearts.episode.seven;

import android.app.ListActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;

public class Episode7 extends ListActivity {
    String[] mTestArray;

    /** Called when the activity is first created. */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Create an ArrayAdapter that will contain all list items
        ArrayAdapter<String> adapter;

        mTestArray = getResources().getStringArray(R.array.testArray);    

        /* Assign the name array to that adapter and 
        also choose a simple layout for the list items */ 
        adapter = new ArrayAdapter<String>(
            this,
            android.R.layout.simple_list_item_1,
            mTestArray);

        // Assign the adapter to this ListActivity
        setListAdapter(adapter);
    }
}

How to access command line arguments of the caller inside a function?

Ravi's comment is essentially the answer. Functions take their own arguments. If you want them to be the same as the command-line arguments, you must pass them in. Otherwise, you're clearly calling a function without arguments.

That said, you could if you like store the command-line arguments in a global array to use within other functions:

my_function() {
    echo "stored arguments:"
    for arg in "${commandline_args[@]}"; do
        echo "    $arg"
    done
}

commandline_args=("$@")

my_function

You have to access the command-line arguments through the commandline_args variable, not $@, $1, $2, etc., but they're available. I'm unaware of any way to assign directly to the argument array, but if someone knows one, please enlighten me!

Also, note the way I've used and quoted $@ - this is how you ensure special characters (whitespace) don't get mucked up.

Certificate is trusted by PC but not by Android

You have to create a crt bundle then it will be fine. You will be receiving three crt files. Use them all! If you only used the domain.crt then there will be warning on android but not on PC.

I am on nginx. I opened domain_name.crt and then opened positivesslca2.crt, select all and copy to the end of domain_name.crt. Then open AddTrustExternalCARoot.crt, copy to the end of domain_name.crt again. Then install the domain_name.crt

works good.

R: Comment out block of code

I use RStudio or Emacs and always use the editor shortcuts available to comment regions. If this is not a possibility then you could use Paul's answer but this only works if your code is syntactically correct.

Here is another dirty way I came up with, wrap it in scan() and remove the result. It does store the comment in memory for a short while so it will probably not work with very large comments. Best still is to just put # signs in front of every line (possibly with editor shortcuts).

foo <- scan(what="character")
These are comments
These are still comments
Can also be code:
x <- 1:10
One line must be blank

rm(foo)

Cannot ignore .idea/workspace.xml - keeps popping up

I had to:

  • remove the file from git
  • push the commit to all remotes
  • make sure all other committers updated from remote

Commands

git rm -f .idea/workspace.xml
git remote | xargs -L1 git push --all

Other committers should run

git pull

Base64 decode snippet in C++

A little variation with a more compact lookup table and using C++17 features:

std::string base64_decode(const std::string_view in) {
  // table from '+' to 'z'
  const uint8_t lookup[] = {
      62,  255, 62,  255, 63,  52,  53, 54, 55, 56, 57, 58, 59, 60, 61, 255,
      255, 0,   255, 255, 255, 255, 0,  1,  2,  3,  4,  5,  6,  7,  8,  9,
      10,  11,  12,  13,  14,  15,  16, 17, 18, 19, 20, 21, 22, 23, 24, 25,
      255, 255, 255, 255, 63,  255, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
      36,  37,  38,  39,  40,  41,  42, 43, 44, 45, 46, 47, 48, 49, 50, 51};
  static_assert(sizeof(lookup) == 'z' - '+' + 1);

  std::string out;
  int val = 0, valb = -8;
  for (uint8_t c : in) {
    if (c < '+' || c > 'z')
      break;
    c -= '+';
    if (lookup[c] >= 64)
      break;
    val = (val << 6) + lookup[c];
    valb += 6;
    if (valb >= 0) {
      out.push_back(char((val >> valb) & 0xFF));
      valb -= 8;
    }
  }
  return out;
}

If you don't have std::string_view, try instead std::experimental::string_view.

What is a callback URL in relation to an API?

If you use the callback URL, then the API can connect to the callback URL and send or receive some data. That means API can connect to you later (after API call).

Example

Diagram

  1. YOU send data using request to API
  2. API sends data using second request to YOU

Exact definition should be in API documentation.

JIRA JQL searching by date - is there a way of getting Today() (Date) instead of Now() (DateTime)

Check out startOfDay([offset]). That gets what you are looking for without the pesky time constraints and its built in as of 4.3.x. It also has variants like endOfDay, startOfWeek, startOfMonth, etc.

Javascript regular expression password validation having special characters

When you remake account password make shure it's 8-20 characters include numbers and special characters like ##/* characters like this then verify new password and re enter exact same and should solve the issues with the password verification

How to atomically delete keys matching a pattern using Redis

poor man's atomic mass-delete?

maybe you could set them all to EXPIREAT the same second - like a few minutes in the future - and then wait until that time and see them all "self-destruct" at the same time.

but I am not really sure how atomic that would be.

How to get the date and time values in a C program?

I'm getting the following error when compiling Adam Rosenfield's code on Windows. It turns out few things are missing from the code.

Error (Before)

C:\C\Codes>gcc time.c -o time
time.c:3:12: error: initializer element is not constant
 time_t t = time(NULL);
            ^
time.c:4:16: error: initializer element is not constant
 struct tm tm = *localtime(&t);
                ^
time.c:6:8: error: expected declaration specifiers or '...' before string constant
 printf("now: %d-%d-%d %d:%d:%d\n", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
        ^
time.c:6:36: error: expected declaration specifiers or '...' before 'tm'
 printf("now: %d-%d-%d %d:%d:%d\n", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
                                    ^
time.c:6:55: error: expected declaration specifiers or '...' before 'tm'
 printf("now: %d-%d-%d %d:%d:%d\n", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
                                                       ^
time.c:6:70: error: expected declaration specifiers or '...' before 'tm'
 printf("now: %d-%d-%d %d:%d:%d\n", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
                                                                      ^
time.c:6:82: error: expected declaration specifiers or '...' before 'tm'
 printf("now: %d-%d-%d %d:%d:%d\n", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
                                                                                  ^
time.c:6:94: error: expected declaration specifiers or '...' before 'tm'
 printf("now: %d-%d-%d %d:%d:%d\n", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
                                                                                              ^
time.c:6:105: error: expected declaration specifiers or '...' before 'tm'
 printf("now: %d-%d-%d %d:%d:%d\n", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
                                                                                                         ^
C:\C\Codes>

Solution

C:\C\Codes>more time.c
#include <stdio.h>
#include <time.h>

int main()
{
        time_t t = time(NULL);
        struct tm tm = *localtime(&t);

        printf("now: %d-%d-%d %d:%d:%d\n", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
}

C:\C\Codes>

Compiling

C:\C\Codes>gcc time.c -o time

C:\C\Codes>    

Final Output

C:\C\Codes>time
now: 2018-3-11 15:46:36

C:\C\Codes>

I hope this will helps others too

Using GSON to parse a JSON array

Gson gson = new Gson();
Wrapper[] arr = gson.fromJson(str, Wrapper[].class);

class Wrapper{
    int number;
    String title;       
}

Seems to work fine. But there is an extra , Comma in your string.

[
    { 
        "number" : "3",
        "title" : "hello_world"
    },
    { 
        "number" : "2",
        "title" : "hello_world"
    }
]

How to detect internet speed in JavaScript?

Well, this is 2017 so you now have Network Information API (albeit with a limited support across browsers as of now) to get some sort of estimate downlink speed information:

navigator.connection.downlink

This is effective bandwidth estimate in Mbits per sec. The browser makes this estimate from recently observed application layer throughput across recently active connections. Needless to say, the biggest advantage of this approach is that you need not download any content just for bandwidth/ speed calculation.

You can look at this and a couple of other related attributes here

Due to it's limited support and different implementations across browsers (as of Nov 2017), would strongly recommend read this in detail

Changing tab bar item image and text color iOS

Swift 5.3

let vc = UIViewController()
vc.tabBarItem.title = "sample"
vc.tabBarItem.image = UIImage(imageLiteralResourceName: "image.png").withRenderingMode(.alwaysOriginal)
vc.tabBarItem.selectedImage = UIImage(imageLiteralResourceName: "image.png").withRenderingMode(.alwaysOriginal)
        
// for text displayed below the tabBar item
UITabBarItem.appearance().setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.black], for: .selected)

PHP isset() with multiple parameters

You just need:

if (!empty($_POST['search_term']) && !empty($_POST['postcode']))

isset && !empty is redundant.

MySQL "incorrect string value" error when save unicode string in Django

You aren't trying to save unicode strings, you're trying to save bytestrings in the UTF-8 encoding. Make them actual unicode string literals:

user.last_name = u'Slatkevicius'

or (when you don't have string literals) decode them using the utf-8 encoding:

user.last_name = lastname.decode('utf-8')

PHP, display image with Header()

Browsers can often tell the image type by sniffing out the meta information of the image. Also, there should be a space in that header:

header('Content-type: image/png');

Using Mockito to test abstract classes

Assuming your test classes are in the same package (under a different source root) as your classes under test you can simply create the mock:

YourClass yourObject = mock(YourClass.class);

and call the methods you want to test just as you would any other method.

You need to provide expectations for each method that is called with the expectation on any concrete methods calling the super method - not sure how you'd do that with Mockito, but I believe it's possible with EasyMock.

All this is doing is creating a concrete instance of YouClass and saving you the effort of providing empty implementations of each abstract method.

As an aside, I often find it useful to implement the abstract class in my test, where it serves as an example implementation that I test via its public interface, although this does depend on the functionality provided by the abstract class.

Basic example for sharing text or image with UIActivityViewController in Swift

Share : Text

@IBAction func shareOnlyText(_ sender: UIButton) {
    let text = "This is the text....."
    let textShare = [ text ]
    let activityViewController = UIActivityViewController(activityItems: textShare , applicationActivities: nil)
    activityViewController.popoverPresentationController?.sourceView = self.view 
    self.present(activityViewController, animated: true, completion: nil)
}
}

Share : Image

@IBAction func shareOnlyImage(_ sender: UIButton) {
    let image = UIImage(named: "Product")
    let imageShare = [ image! ]
    let activityViewController = UIActivityViewController(activityItems: imageShare , applicationActivities: nil)
    activityViewController.popoverPresentationController?.sourceView = self.view 
    self.present(activityViewController, animated: true, completion: nil)
 }

Share : Text - Image - URL

   @IBAction func shareAll(_ sender: UIButton) {
    let text = "This is the text...."
    let image = UIImage(named: "Product")
    let myWebsite = NSURL(string:"https://stackoverflow.com/users/4600136/mr-javed-multani?tab=profile")
    let shareAll= [text , image! , myWebsite]
    let activityViewController = UIActivityViewController(activityItems: shareAll, applicationActivities: nil)
    activityViewController.popoverPresentationController?.sourceView = self.view 
    self.present(activityViewController, animated: true, completion: nil)
   }

enter image description here

What is the best way to generate a unique and short file name in Java

Combining other answers, why not use the ms timestamp with a random value appended; repeat until no conflict, which in practice will be almost never.

For example: File-ccyymmdd-hhmmss-mmm-rrrrrr.txt

java.security.cert.CertificateException: Certificates does not conform to algorithm constraints

Eclipse failed to connect to SVN https repositories (should also apply to any app using SSL/TLS).

svn: E175002: Connection has been shutdown: javax.net.ssl.SSLHandshakeException: java.security.cert.CertificateException: Certificates does not conform to algorithm constraints

The issue was caused by latest Java 8 OpenJDK update that disabled MD5 related algorithms. As a workaround until new certificates are issued (if ever), change the following keys at java.security file

WARNING
Keep in mind that this could have security implications as disabled algorithms are considered weak. As an alternative, the workaround can be applied on a JVM basis by a command line option to use an external java.security file with this changes, e.g.:
java -Djava.security.properties=/etc/sysconfig/noMD5.java.security
For Eclipse, add a line on eclipse.ini below -vmargs
-Djava.security.properties=/etc/sysconfig/noMD5.java.security

original keys

jdk.certpath.disabledAlgorithms=MD2, MD5, RSA keySize < 1024
jdk.tls.disabledAlgorithms=SSLv3, RC4, MD5withRSA, DH keySize < 768

change to

jdk.certpath.disabledAlgorithms=MD2, RSA keySize < 1024
jdk.tls.disabledAlgorithms=SSLv3, RC4, DH keySize < 768

java.security file is located in linux 64 at /usr/lib64/jvm/java/jre/lib/security/java.security

Manually type in a value in a "Select" / Drop-down HTML list?

I faced the same basic problem: trying to combine the functionality of a textbox and a select box which are fundamentally different things in the html spec.

The good news is that selectize.js does exactly this:

Selectize is the hybrid of a textbox and box. It's jQuery-based and it's useful for tagging, contact lists, country selectors, and so on.

Pass user defined environment variable to tomcat

For Unix & Mac systems, Go to /bin/setenv.sh inside tomcat folder

Add the below line

export JAVA_OPTS="$JAVA_OPTS -DAPP_MASTER_PASSWORD=mypass"

Now System.getProperty("APP_MASTER_PASSWORD") will return "mypass"

Toolbar Navigation Hamburger Icon missing

For that you just need write to some lines

   DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
   ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
   drawer.addDrawerListener(toggle);
   toggle.setDrawerIndicatorEnabled(true);
   toggle.syncState();

toggle.setDrawerIndicatorEnabled(true); if this is false make it true or remove this line

CSS: Position loading indicator in the center of the screen

Here is a solution using an overlay that inhibits along with material design spinner that you configure one time in your app and you can call it from anywhere.

app.component.html

(put this somewhere at the root level of your html)

<div class="overlay" [style.height.px]="height" [style.width.px]="width" *ngIf="message.plzWait$ | async">
        <mat-spinner class="plzWait"  mode="indeterminate"></mat-spinner>
</div>

app.component.css

.plzWait{
  position: relative;
  left: calc(50% - 50px);
  top:50%;

}
.overlay{
  position: absolute;
  top:0px;
  left:0px;
  width: 100%;
  height: 100%;
  background: black;
  opacity: .5;
  z-index: 999999;
}

app.component.ts

height = 0;
width = 0;
constructor(
    private message: MessagingService
  }
ngOnInit() {
    this.height = document.body.clientHeight;
    this.width = document.body.clientWidth;
  }

messaging.service.ts

import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';

@Injectable({
    providedIn: 'root',
  })
export class MessagingService {
    // Observable string sources
  private plzWaitObservable = new Subject<boolean>();


  // Public Observables you subscribe to
  public plzWait$ = this.plzWaitObservable.asObservable();

  public plzWait = (wait: boolean) => this.plzWaitObservable.next(wait);
}

Some other component

constructor(private message: MessagingService) { }
somefunction() {
    this.message.plzWait(true);
    setTimeout(() => {
            this.message.plzWait(false);
    }, 5000);
}

Move view with keyboard using Swift

i've read answers and solved my problem by this lines of code:

class ViewController: UIViewController, UITextFieldDelegate {

  @IBOutlet weak var titleField: UITextField!
  @IBOutlet weak var priceField: UITextField!
  @IBOutlet weak var detailsField: UTtextField!

  override func viewDidLoad() {
   super.viewDidLoad()
// Do not to forget to set the delegate otherwise the textFieldShouldReturn(_:)
// won't work and the keyboard will never be hidden.
   priceField.delegate = self
   titleField.delegate = self
   detailsField.delegate = self

   NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow),
 name: NSNotification.Name.UIKeyboardWillShow, object: nil)

   NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide),
 name: NSNotification.Name.UIKeyboardWillHide, object: nil)
  }

   func textFieldShouldReturn(_ textField: UITextField) -> Bool {
      self.view.endEditing(true)
      return false
   }

 func keyboardWillShow(notification: NSNotification) {
   var translation:CGFloat = 0
   if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
     if detailsField.isEditing{
       translation = CGFloat(-keyboardSize.height)
     }else if priceField.isEditing{
       translation = CGFloat(-keyboardSize.height / 3.8)
     }
   }
    UIView.animate(withDuration: 0.2) {
   self.view.transform = CGAffineTransform(translationX: 0, y: translation)
    }
  }


 func keyboardWillHide(notification: NSNotification) {
    UIView.animate(withDuration: 0.2) {
     self.view.transform = CGAffineTransform(translationX: 0, y: 0)
    } 
  }
}

I have a few UITextFields and want the view to move up differently depending on which textField is tapped.

How to set environment variables in Jenkins?

Normally you can configure Environment variables in Global properties in Configure System.

However for dynamic variables with shell substitution, you may want to create a script file in Jenkins HOME dir and execute it during the build. The SSH access is required. For example.

  1. Log-in as Jenkins: sudo su - jenkins or sudo su - jenkins -s /bin/bash
  2. Create a shell script, e.g.:

    echo 'export VM_NAME="$JOB_NAME"' > ~/load_env.sh
    echo "export AOEU=$(echo aoeu)" >> ~/load_env.sh
    chmod 750 ~/load_env.sh
    
  3. In Jenkins Build (Execute shell), invoke the script and its variables before anything else, e.g.

    source ~/load_env.sh
    

How to match a line not containing a word

This should work:

/^((?!PART).)*$/

If you only wanted to exclude it from the beginning of the line (I know you don't, but just FYI), you could use this:

/^(?!PART)/

Edit (by request): Why this pattern works

The (?!...) syntax is a negative lookahead, which I've always found tough to explain. Basically, it means "whatever follows this point must not match the regular expression /PART/." The site I've linked explains this far better than I can, but I'll try to break this down:

^         #Start matching from the beginning of the string.    
(?!PART)  #This position must not be followed by the string "PART".
.         #Matches any character except line breaks (it will include those in single-line mode).
$         #Match all the way until the end of the string.

The ((?!xxx).)* idiom is probably hardest to understand. As we saw, (?!PART) looks at the string ahead and says that whatever comes next can't match the subpattern /PART/. So what we're doing with ((?!xxx).)* is going through the string letter by letter and applying the rule to all of them. Each character can be anything, but if you take that character and the next few characters after it, you'd better not get the word PART.

The ^ and $ anchors are there to demand that the rule be applied to the entire string, from beginning to end. Without those anchors, any piece of the string that didn't begin with PART would be a match. Even PART itself would have matches in it, because (for example) the letter A isn't followed by the exact string PART.

Since we do have ^ and $, if PART were anywhere in the string, one of the characters would match (?=PART). and the overall match would fail. Hope that's clear enough to be helpful.

How do you implement a good profanity filter?

Regarding your "trick the system" subquestion, you can handle that by normalizing both the "bad word" list and the user-entered text before doing your search. e.g., Use a series of regexes (or tr if PHP has it) to convert [z$5] to "s", [4@] to "a", etc., then compare the normalized "bad word" list against the normalized text. Note that the normalization could potentially lead to additional false positives, although I can't think of any actual cases at the moment.

The larger challenge is to come up with something that will let people quote "The pen is mightier than the sword" while blocking "p e n i s".

Bootstrap - Uncaught TypeError: Cannot read property 'fn' of undefined

I went back to jquery-2.2.4.min.js and it works.

How to stop a vb script running in windows

Create a Name.bat file that has the following line in it.

taskkill /F /IM wscript.exe /T

Be sure not to overpower your processor. If you're running long scripts, your processor speed changes and script lines will override each other.

How do I round a double to two decimal places in Java?

Starting java 1.8 you can do more with lambda expressions & checks for null. Also, one below can handle Float or Double & variable number of decimal points (including 2 :-)).

public static Double round(Number src, int decimalPlaces) {

    return Optional.ofNullable(src)
            .map(Number::doubleValue)
            .map(BigDecimal::new)
            .map(dbl -> dbl.setScale(decimalPlaces, BigDecimal.ROUND_HALF_UP))
            .map(BigDecimal::doubleValue)
            .orElse(null);
}

Safest way to get last record ID from a table

Safest way will be to output or return the scope_identity() within the procedure inserting the row, and then retrieve the row based on that ID. Use of @@Identity is to be avoided since you can get the incorrect ID when triggers are in play.

Any technique of asking for the maximum value / top 1 suffers a race condition where 2 people adding at the same time, would then get the same ID back when they looked for the highest ID.

Add primary key to existing table

Try using this code:

ALTER TABLE `table name` 
    CHANGE COLUMN `column name` `column name` datatype NOT NULL, 
    ADD PRIMARY KEY (`column name`) ;

set environment variable in python script

You can add elements to your environment by using

os.environ['LD_LIBRARY_PATH'] = 'my_path'

and run subprocesses in a shell (that uses your os.environ) by using

subprocess.call('sqsub -np ' + var1 + '/homedir/anotherdir/executable', shell=True)

How can I get the size of an std::vector as an int?

In the first two cases, you simply forgot to actually call the member function (!, it's not a value) std::vector<int>::size like this:

#include <vector>

int main () {
    std::vector<int> v;
    auto size = v.size();
}

Your third call

int size = v.size();

triggers a warning, as not every return value of that function (usually a 64 bit unsigned int) can be represented as a 32 bit signed int.

int size = static_cast<int>(v.size());

would always compile cleanly and also explicitly states that your conversion from std::vector::size_type to int was intended.

Note that if the size of the vector is greater than the biggest number an int can represent, size will contain an implementation defined (de facto garbage) value.

How to run PyCharm in Ubuntu - "Run in Terminal" or "Run"?

For Pycharm CE 2018.3 and Ubuntu 18.04 with snap installation:

env BAMF_DESKTOP_FILE_HINT=/var/lib/snapd/desktop/applications/pycharm-community_pycharm-community.desktop /snap/bin/pycharm-community %f

I get this command from KDE desktop launch icon.

pychar-ce-command

Sorry for the language but I am a Spanish developer so I have my system in Spanish.

Hex-encoded String to Byte Array

Use:

str.getBytes("UTF-16LE");

Git Bash won't run my python files?

Here is the SOLUTION

If you get Response:

  1. bash: python: command not found OR
  2. bash: conda: command not found

To the following Commands: when you execute python or python -V conda or conda --version in your Git/Terminal window

Background: This is because you either

  1. Installed Python in a location on your C Drive (C:) which is not directly in your program files folder.
  2. Installed Python maybe on the D Drive (D:) and your computer by default searches for it on your C:
  3. You have been told to go to your environment variables (located if you do a search for environment variables on your machines start menu) and change the "Path" variable on your computer and this still does not fix the problem.

Solution:

  1. At the command prompt, paste this command export PATH="$PATH:/c/Python36". That will tell Windows where to find Python. (This assumes that you installed it in C:\Python36)

  2. If you installed python on your D drive, paste this command export PATH="$PATH:/d/Python36".

  3. Then at the command prompt, paste python or python -V and you will see the version of Python installed and now you should not get Python 3.6.5

  4. Assuming that it worked correctly you will want to set up git bash so that it always knows where to find python. To do that, enter the following command: echo 'export PATH="$PATH:/d/Python36"' > .bashrc

Permanent Solution

  1. Go to BASH RC Source File (located on C: / C Drive in “C:\Users\myname”)

  2. Make sure your BASH RC Source File is receiving direction from your Bash Profile Source File, you can do this by making sure that your BASH RC Source File contains this line of code: source ~/.bash_profile

  3. Go to BASH Profile Source File (located on C: / C Drive in “C:\Users\myname”)

  4. Enter line: export PATH="$PATH:/D/PROGRAMMING/Applications/PYTHON/Python365" (assuming this is the location where Python version 3.6.5 is installed)

  5. This should take care of the problem permanently. Now whenever you open your Git Bash Terminal Prompt and enter “python” or “python -V” it should return the python version

How does jQuery work when there are multiple elements with the same ID value?

Having 2 elements with the same ID is not valid html according to the W3C specification.

When your CSS selector only has an ID selector (and is not used on a specific context), jQuery uses the native document.getElementById method, which returns only the first element with that ID.

However, in the other two instances, jQuery relies on the Sizzle selector engine (or querySelectorAll, if available), which apparently selects both elements. Results may vary on a per browser basis.

However, you should never have two elements on the same page with the same ID. If you need it for your CSS, use a class instead.


If you absolutely must select by duplicate ID, use an attribute selector:

$('[id="a"]');

Take a look at the fiddle: http://jsfiddle.net/P2j3f/2/

Note: if possible, you should qualify that selector with a tag selector, like this:

$('span[id="a"]');

Best way to repeat a character in C#

The answer really depends on the complexity you want. For example, I want to outline all my indents with a vertical bar, so my indent string is determined as follows:

return new string(Enumerable.Range(0, indentSize*indent).Select(
  n => n%4 == 0 ? '|' : ' ').ToArray());

Convert a binary NodeJS Buffer to JavaScript ArrayBuffer

"From ArrayBuffer to Buffer" could be done this way:

var buffer = Buffer.from( new Uint8Array(ab) );

How to find out what character key is pressed?

document.onkeypress = function(event){
    alert(event.key)
}

numpy: most efficient frequency counts for unique values in an array

import pandas as pd
import numpy as np
x = np.array( [1,1,1,2,2,2,5,25,1,1] )
print(dict(pd.Series(x).value_counts()))

This gives you: {1: 5, 2: 3, 5: 1, 25: 1}

How to compare strings in Bash

Or, if you don't need else clause:

[ "$x" == "valid" ] && echo "x has the value 'valid'"

How can I format my grep output to show line numbers at the end of the line, and also the hit count?

Refer this link for linux command linux http://linuxcommand.org/man_pages/grep1.html

for displaying line no ,line of code and file use this command in your terminal or cmd, GitBash(Powered by terminal)

grep -irn "YourStringToBeSearch"

How do I test which class an object is in Objective-C?

To test if object is an instance of class a:

[yourObject isKindOfClass:[a class]]
// Returns a Boolean value that indicates whether the receiver is an instance of 
// given class or an instance of any class that inherits from that class.

or

[yourObject isMemberOfClass:[a class]]
// Returns a Boolean value that indicates whether the receiver is an instance of a 
// given class.

To get object's class name you can use NSStringFromClass function:

NSString *className = NSStringFromClass([yourObject class]);

or c-function from objective-c runtime api:

#import <objc/runtime.h>

/* ... */

const char* className = class_getName([yourObject class]);
NSLog(@"yourObject is a: %s", className);

EDIT: In Swift

if touch.view is UIPickerView {
    // touch.view is of type UIPickerView
}

When should I use uuid.uuid1() vs. uuid.uuid4() in python?

My team just ran into trouble using UUID1 for a database upgrade script where we generated ~120k UUIDs within a couple of minutes. The UUID collision led to violation of a primary key constraint.

We've upgraded 100s of servers but on our Amazon EC2 instances we ran into this issue a few times. I suspect poor clock resolution and switching to UUID4 solved it for us.

Xcode 4 - build output directory

If you have Xcode 4 Build Location setting set to "Place build products in derived data location (recommended), it should be located in ~/Library/Developer/Xcode/DerivedData. This directory will have your project in there as a directory, the project name will be appended with a bunch of generated letters so look carefully.

filter out multiple criteria using excel vba

Alternative using VBA's Filter function

As an innovative alternative to @schlebe 's recent answer, I tried to use the Filter function integrated in VBA, which allows to filter out a given search string setting the third argument to False. All "negative" search strings (e.g. A, B, C) are defined in an array. I read the criteria in column A to a datafield array and basicly execute a subsequent filtering (A - C) to filter these items out.

Code

Sub FilterOut()
Dim ws  As Worksheet
Dim rng As Range, i As Integer, n As Long, v As Variant
' 1) define strings to be filtered out in array
  Dim a()                    ' declare as array
  a = Array("A", "B", "C")   ' << filter out values
' 2) define your sheetname and range (e.g. criteria in column A)
  Set ws = ThisWorkbook.Worksheets("FilterOut")
  n = ws.Range("A" & ws.Rows.Count).End(xlUp).row
  Set rng = ws.Range("A2:A" & n)
' 3) hide complete range rows temporarily
  rng.EntireRow.Hidden = True
' 4) set range to a variant 2-dim datafield array
  v = rng
' 5) code array items by appending row numbers
  For i = 1 To UBound(v): v(i, 1) = v(i, 1) & "#" & i + 1: Next i
' 6) transform to 1-dim array and FILTER OUT the first search string, e.g. "A"
  v = Filter(Application.Transpose(Application.Index(v, 0, 1)), a(0), False, False)
' 7) filter out each subsequent search string, i.e. "B" and "C"
  For i = 1 To UBound(a): v = Filter(v, a(i), False, False): Next i
' 8) get coded row numbers via split function and unhide valid rows
  For i = LBound(v) To UBound(v)
      ws.Range("A" & Split(v(i) & "#", "#")(1)).EntireRow.Hidden = False
  Next i
End Sub

Getting the closest string match

If you're doing this in the context of a search engine or frontend against a database, you might consider using a tool like Apache Solr, with the ComplexPhraseQueryParser plugin. This combination allows you to search against an index of strings with the results sorted by relevance, as determined by Levenshtein distance.

We've been using it against a large collection of artists and song titles when the incoming query may have one or more typos, and it's worked pretty well (and remarkably fast considering the collections are in the millions of strings).

Additionally, with Solr, you can search against the index on demand via JSON, so you won't have to reinvent the solution between the different languages you're looking at.

Read file from resources folder in Spring Boot

See my answer here: https://stackoverflow.com/a/56854431/4453282

import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;

Use these 2 imports.

Declare

@Autowired
ResourceLoader resourceLoader;

Use this in some function

Resource resource=resourceLoader.getResource("classpath:preferences.json");

In your case, as you need the file you may use following

File file = resource.getFile()

Reference:http://frugalisminds.com/spring/load-file-classpath-spring-boot/ As already mentioned in previous answers don't use ResourceUtils it doesn't work after deployment of JAR, this will work in IDE as well as after deployment

How do I create a circle or square with just CSS - with a hollow center?

If you want your div to keep it's circular shape even if you change its width/height (using js for instance) set the radius to 50%. Example: css:

.circle {
    border-radius: 50%/50%; 
    width: 50px;
    height: 50px;
    background: black;
}

html:

<div class="circle"></div>

in angularjs how to access the element that triggered the event?

you can get easily like this first write event on element

ng-focus="myfunction(this)"

and in your js file like below

$scope.myfunction= function (msg, $event) {
    var el = event.target
    console.log(el);
}

I have used it as well.

os.path.dirname(__file__) returns empty

os.path.split(os.path.realpath(__file__))[0]

os.path.realpath(__file__)return the abspath of the current script; os.path.split(abspath)[0] return the current dir

Is the size of C "int" 2 bytes or 4 bytes?

#include <stdio.h>

int main(void) {
    printf("size of int: %d", (int)sizeof(int));
    return 0;
}

This returns 4, but it's probably machine dependant.

How do I escape a string inside JavaScript code inside an onClick handler?

Any good templating engine worth its salt will have an "escape quotes" function. Ours (also home-grown, where I work) also has a function to escape quotes for javascript. In both cases, the template variable is then just appended with _esc or _js_esc, depending on which you want. You should never output user-generated content to a browser that hasn't been escaped, IMHO.

How to use UIPanGestureRecognizer to move object? iPhone/iPad

if ([recognizer state] == UIGestureRecognizerStateChanged)    
{
    CGPoint translation1 = [recognizer translationInView:main_view];
    img12.center=CGPointMake(img12.center.x+translation1.x, img12.center.y+ translation1.y);
    [recognizer setTranslation:CGPointMake(0, 0) inView:main_view];

    recognizer.view.center=CGPointMake(recognizer.view.center.x+translation1.x, recognizer.view.center.y+ translation1.y);
}

-(void)move:(UIPanGestureRecognizer*)recognizer
{
    if ([recognizer state] == UIGestureRecognizerStateChanged)    
    {
        CGPoint translation = [recognizer translationInView:self.view];
        recognizer.view.center=CGPointMake(recognizer.view.center.x+translation.x, recognizer.view.center.y+ translation.y);
        [recognizer setTranslation:CGPointMake(0, 0) inView:self.view];
    }
}

contenteditable change events

In Angular 2+

<div contentEditable (input)="type($event)">
   Value
</div>

@Component({
  ...
})
export class ContentEditableComponent {

 ...

 type(event) {
   console.log(event.data) // <-- The pressed key
   console.log(event.path[0].innerHTML) // <-- The content of the div 
 }
}


Openstreetmap: embedding map in webpage (like Google Maps)

There is simple way to do it if you fear Javascript...I'm still learning. Open Street makes a simple Wordpress plugin you can customize. Add OSM Widget plugin.

This will be a filler until I figure out my Python Java concotion using coverter TIGER line files from the Census Bureau.

How to check if a string is a number?

if ( strlen(str) == strlen( itoa(atoi(str)) ) ) {
    //its an integer
}

As atoi converts string to number skipping letters other than digits, if there was no other than digits its string length has to be the same as the original. This solution is better than innumber() if the check is for integer.

Redirect stderr and stdout in Bash

In situations when you consider using things like exec 2>&1 I find easier to read if possible rewriting code using bash functions like this:

function myfunc(){
  [...]
}

myfunc &>mylog.log

Postgresql GROUP_CONCAT equivalent?

My sugestion in postgresql

SELECT cpf || ';' || nome || ';' || telefone  
FROM (
      SELECT cpf
            ,nome
            ,STRING_AGG(CONCAT_WS( ';' , DDD_1, TELEFONE_1),';') AS telefone 
      FROM (
            SELECT DISTINCT * 
            FROM temp_bd 
            ORDER BY cpf DESC ) AS y
      GROUP BY 1,2 ) AS x   

How to get the number of threads in a Java process

Get number of threads using jstack

jstack <PID> | grep 'java.lang.Thread.State' | wc -l

The result of the above code is quite different from top -H -p <PID> or ps -o nlwp <PID> because jstack gets only threads from created by the application.

In other words, jstack will not get GC threads

Get selected row item in DataGrid WPF

You can use the SelectedItem property to get the currently selected object, which you can then cast into the correct type. For instance, if your DataGrid is bound to a collection of Customer objects you could do this:

Customer customer = (Customer)myDataGrid.SelectedItem;

Alternatively you can bind SelectedItem to your source class or ViewModel.

<Grid DataContext="MyViewModel">
    <DataGrid ItemsSource="{Binding Path=Customers}"
              SelectedItem="{Binding Path=SelectedCustomer, Mode=TwoWay}"/>
</Grid>    

Using ConfigurationManager to load config from an arbitrary location

In addition to Ishmaeel's answer, the method OpenMappedMachineConfiguration() will always return a Configuration object. So to check to see if it loaded you should check the HasFile property where true means it came from a file.

Which Python memory profiler is recommended?

I'm developing a memory profiler for Python called memprof:

http://jmdana.github.io/memprof/

It allows you to log and plot the memory usage of your variables during the execution of the decorated methods. You just have to import the library using:

from memprof import memprof

And decorate your method using:

@memprof

This is an example on how the plots look like:

enter image description here

The project is hosted in GitHub:

https://github.com/jmdana/memprof

Unresponsive KeyListener for JFrame

You must add your keyListener to every component that you need. Only the component with the focus will send these events. For instance, if you have only one TextBox in your JFrame, that TextBox has the focus. So you must add a KeyListener to this component as well.

The process is the same:

myComponent.addKeyListener(new KeyListener ...);

Note: Some components aren't focusable like JLabel.

For setting them to focusable you need to:

myComponent.setFocusable(true);

Use of def, val, and var in scala

I'd start by the distinction that exists in Scala between def, val and var.

  • def - defines an immutable label for the right side content which is lazily evaluated - evaluate by name.

  • val - defines an immutable label for the right side content which is eagerly/immediately evaluated - evaluated by value.

  • var - defines a mutable variable, initially set to the evaluated right side content.

Example, def

scala> def something = 2 + 3 * 4 
something: Int
scala> something  // now it's evaluated, lazily upon usage
res30: Int = 14

Example, val

scala> val somethingelse = 2 + 3 * 5 // it's evaluated, eagerly upon definition
somethingelse: Int = 17

Example, var

scala> var aVariable = 2 * 3
aVariable: Int = 6

scala> aVariable = 5
aVariable: Int = 5

According to above, labels from def and val cannot be reassigned, and in case of any attempt an error like the below one will be raised:

scala> something = 5 * 6
<console>:8: error: value something_= is not a member of object $iw
       something = 5 * 6
       ^

When the class is defined like:

scala> class Person(val name: String, var age: Int)
defined class Person

and then instantiated with:

scala> def personA = new Person("Tim", 25)
personA: Person

an immutable label is created for that specific instance of Person (i.e. 'personA'). Whenever the mutable field 'age' needs to be modified, such attempt fails:

scala> personA.age = 44
personA.age: Int = 25

as expected, 'age' is part of a non-mutable label. The correct way to work on this consists in using a mutable variable, like in the following example:

scala> var personB = new Person("Matt", 36)
personB: Person = Person@59cd11fe

scala> personB.age = 44
personB.age: Int = 44    // value re-assigned, as expected

as clear, from the mutable variable reference (i.e. 'personB') it is possible to modify the class mutable field 'age'.

I would still stress the fact that everything comes from the above stated difference, that has to be clear in mind of any Scala programmer.

Coerce multiple columns to factors at once

You can use mutate_if (dplyr):

For example, coerce integer in factor:

mydata=structure(list(a = 1:10, b = 1:10, c = c("a", "a", "b", "b", 
"c", "c", "c", "c", "c", "c")), row.names = c(NA, -10L), class = c("tbl_df", 
"tbl", "data.frame"))

# A tibble: 10 x 3
       a     b c    
   <int> <int> <chr>
 1     1     1 a    
 2     2     2 a    
 3     3     3 b    
 4     4     4 b    
 5     5     5 c    
 6     6     6 c    
 7     7     7 c    
 8     8     8 c    
 9     9     9 c    
10    10    10 c   

Use the function:

library(dplyr)

mydata%>%
    mutate_if(is.integer,as.factor)

# A tibble: 10 x 3
       a     b c    
   <fct> <fct> <chr>
 1     1     1 a    
 2     2     2 a    
 3     3     3 b    
 4     4     4 b    
 5     5     5 c    
 6     6     6 c    
 7     7     7 c    
 8     8     8 c    
 9     9     9 c    
10    10    10 c    

Alternate table row color using CSS?

There is a fairly easy way to do this in PHP, if I understand your query, I assume that you code in PHP and you are using CSS and javascript to enhance the output.

The dynamic output from the database will carry a for loop to iterate through results which are then loaded into the table. Just add a function call to the like this:

echo "<tr style=".getbgc($i).">";  //this calls the function based on the iteration of the for loop.

then add the function to the page or library file:

function getbgc($trcount)
{

$blue="\"background-color: #EEFAF6;\"";
$green="\"background-color: #D4F7EB;\"";
$odd=$trcount%2;
    if($odd==1){return $blue;}
    else{return $green;}    

}

Now this will alternate dynamically between colors at each newly generated table row.

It's a lot easier than messing about with CSS that doesn't work on all browsers.

Hope this helps.

What's the difference between xsd:include and xsd:import?

Use xsd:include brings all declarations and definitions of an external schema document into the current schema.

Use xsd:import to bring in an XSD from a different namespace and used to build a new schema by extending existing schema documents..

Windows 7, 64 bit, DLL problems

I suggest also checking how much memory is currently being used.

It turns out that the inability to find these DLL files was the first symptom exhibited when trying to run a program (either run or debug) in Visual Studio.

After over a half hour with much head scratching, searching the web, running Process Monitor, and Task Manager, and depends, a completely different program that had been running since the beginning of time reported that "memory is low; try stopping some programs" or some such. After killing Firefox, Thunderbird, Process Monitor, and depends, everything worked again.

In python, what is the difference between random.uniform() and random.random()?

In random.random() the output lies between 0 & 1 , and it takes no input parameters

Whereas random.uniform() takes parameters , wherein you can submit the range of the random number. e.g.
import random as ra print ra.random() print ra.uniform(5,10)

OUTPUT:-
0.672485369423 7.9237539416

nodemon command is not recognized in terminal for node js server

You need to install it globally

npm install -g nodemon
# or if using yarn
yarn global add nodemon

And then it will be available on the path (I see now that you have tried this and it didn't work, your path may be messed up)

If you want to use the locally installed version, rather than installing globally then you can create a script in your package.json

"scripts": {
    "serve": "nodemon server.js"
  },

and then use

npm run serve

optionally if using yarn

# without adding serve in package.json
yarn run nodemon server.js
# with serve script in package.json
yarn run serve

npm will then look in your local node_modules folder before looking for the command in your global modules

PHP file_get_contents() and setting request headers

Here is what worked for me (Dominic was just one line short).

$url = "";

$options = array(
  'http'=>array(
    'method'=>"GET",
    'header'=>"Accept-language: en\r\n" .
              "Cookie: foo=bar\r\n" .  // check function.stream-context-create on php.net
              "User-Agent: Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B334b Safari/531.21.102011-10-16 20:23:10\r\n" // i.e. An iPad 
  )
);

$context = stream_context_create($options);
$file = file_get_contents($url, false, $context);

Select option padding not working in chrome

You should be targeting select for your CSS instead of select option.

select { 
padding: 10px;
margin: 0;
-webkit-border-radius:4px;
-moz-border-radius:4px;
border-radius:4px;
}

View this article Styling Select Box with CSS3 for more styling options.

Convert string to Boolean in javascript

Depends on what you see as false in a string.

Empty string, the word false, 0, should all those be false or is only empty false or only the word false.

You probably need to buid your own method to test the string and return true or false to be 100 % sure that it does what you need.

How to calculate Date difference in Hive

If you need the difference in seconds (i.e.: you're comparing dates with timestamps, and not whole days), you can simply convert two date or timestamp strings in the format 'YYYY-MM-DD HH:MM:SS' (or specify your string date format explicitly) using unix_timestamp(), and then subtract them from each other to get the difference in seconds. (And can then divide by 60.0 to get minutes, or by 3600.0 to get hours, etc.)

Example:

UNIX_TIMESTAMP('2017-12-05 10:01:30') - UNIX_TIMESTAMP('2017-12-05 10:00:00') AS time_diff -- This will return 90 (seconds). Unix_timestamp converts string dates into BIGINTs. 

More on what you can do with unix_timestamp() here, including how to convert strings with different date formatting: https://cwiki.apache.org/confluence/display/Hive/LanguageManual+UDF#LanguageManualUDF-DateFunctions

Can I recover a branch after its deletion in Git?

The top voted solution does actually more than requested:

git checkout <sha>
git checkout -b <branch>

or

git checkout -b <branch> <sha>

move you to the new branch together with all recent changes you might have forgot to commit. This may not be your intention, especially when in the "panic mode" after losing the branch.

A cleaner (and simpler) solution seems to be the one-liner (after you found the <sha> with git reflog):

git branch <branch> <sha>

Now neither your current branch nor uncommited changes are affected. Instead only a new branch will be created all the way up to the <sha>.

If it is not the tip, it'll still work and you get a shorter branch, then you can retry with new <sha> and new branch name until you get it right.

Finally you can rename the successfully restored branch into what it was named or anything else:

git branch -m <restored branch> <final branch>

Needless to say, the key to success was to find the right commit <sha>, so name your commits wisely :)

Android view pager with page indicator

Here are a few things you need to do:

1-Download the library if you haven't already done that.

2- Import into Eclipse.

3- Set you project to use the library: Project-> Properties -> Android -> Scroll down to Library section, click Add... and select viewpagerindicator.

4- Now you should be able to import com.viewpagerindicator.TitlePageIndicator.

Now about implementing this without using fragments:

In the sample that comes with viewpagerindicatior, you can see that the library is being used with a ViewPager which has a FragmentPagerAdapter.

But in fact the library itself is Fragment independant. It just needs a ViewPager. So just use a PagerAdapter instead of a FragmentPagerAdapter and you're good to go.

How to delete selected text in the vi editor

If you want to delete using line numbers you can use:

:startingline, last line d

Example:

:7,20 d

This example will delete line 7 to 20.

How to remove border of drop down list : CSS

You could simply use:

select {
    border: none;
    outline: none;
    scroll-behavior: smooth;
}

As the drop down list border is non editable you can not do anything with that but surely this will fix your initial outlook.

How to solve this java.lang.NoClassDefFoundError: org/apache/commons/io/output/DeferredFileOutputStream?

just put all apache comons jar and file upload jar in lib folder of tomcat

Difference between Select Unique and Select Distinct

  1. Unique was the old syntax while Distinct is the new syntax,which is now the Standard sql.
  2. Unique creates a constraint that all values to be inserted must be different from the others. An error can be witnessed if one tries to enter a duplicate value. Distinct results in the removal of the duplicate rows while retrieving data.
  3. Example: SELECT DISTINCT names FROM student ;

    CREATE TABLE Persons ( Id varchar NOT NULL UNIQUE, Name varchar(20) );

Laravel-5 how to populate select box from database with id value and name value

Laravel 5.*

In your controller:

$items= Items::pluck('name', 'id')->toArray();
return view('your view', compact('items', $items));

In your view:

{{ Form::select('organization_id', $items, null, []) }}

jQuery Uncaught TypeError: Property '$' of object [object Window] is not a function

My favorite no-conflict-friendly construct:

jQuery(function($) {
  // ...
});

Calling jQuery with a function pointer is a shortcut for $(document).ready(...)

Or as we say in coffeescript:

jQuery ($) ->
  # code here

font-weight is not working properly?

i was also facing the same issue, I resolved it by after selecting the Google's font that i was using, then I clicked on (Family-Selected) minimized tab and then clicked on "CUSTOMIZE" button. Then I selected the font weights that I want and then embedded the updated link in my html..

Regular expression to validate US phone numbers?

The easiest way to match both

^\([0-9]{3}\)[0-9]{3}-[0-9]{4}$

and

^[0-9]{3}-[0-9]{3}-[0-9]{4}$

is to use alternation ((...|...)): specify them as two mostly-separate options:

^(\([0-9]{3}\)|[0-9]{3}-)[0-9]{3}-[0-9]{4}$

By the way, when Americans put the area code in parentheses, we actually put a space after that; for example, I'd write (123) 123-1234, not (123)123-1234. So you might want to write:

^(\([0-9]{3}\) |[0-9]{3}-)[0-9]{3}-[0-9]{4}$

(Though it's probably best to explicitly demonstrate the format that you expect phone numbers to be in.)

How to disable all div content

the simpleset solution

look at my selector

$myForm.find('#fieldsetUserInfo input:disabled').prop("disabled", false);

the fieldsetUserInfo is div contains all inputs I want to disabled or Enable

hope this helps you

How to set a parameter in a HttpServletRequest?

The most upvoted solution generally works but for Spring and/or Spring Boot, the values will not wire to parameters in controller methods annotated with @RequestParam unless you specifically implemented getParameterValues(). I combined the solution(s) here and from this blog:

import java.util.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

public class MutableHttpRequest extends HttpServletRequestWrapper {

    private final Map<String, String[]> mutableParams = new HashMap<>();

    public MutableHttpRequest(final HttpServletRequest request) {
        super(request);
    }

    public MutableHttpRequest addParameter(String name, String value) {
        if (value != null)
            mutableParams.put(name, new String[] { value });

        return this;
    }

    @Override
    public String getParameter(final String name) {
        String[] values = getParameterMap().get(name);

        return Arrays.stream(values)
                .findFirst()
                .orElse(super.getParameter(name));
    }

    @Override
    public Map<String, String[]> getParameterMap() {
        Map<String, String[]> allParameters = new HashMap<>();
        allParameters.putAll(super.getParameterMap());
        allParameters.putAll(mutableParams);

        return Collections.unmodifiableMap(allParameters);
    }

    @Override
    public Enumeration<String> getParameterNames() {
        return Collections.enumeration(getParameterMap().keySet());
    }

    @Override
    public String[] getParameterValues(final String name) {
        return getParameterMap().get(name);
    }
}

note that this code is not super-optimized but it works.

How to refresh a Page using react-route Link

To refresh page you don't need react-router, simple js:

window.location.reload();

To re-render view in React component, you can just fire update with props/state.

Best way to find the intersection of multiple sets?

If you don't have Python 2.6 or higher, the alternative is to write an explicit for loop:

def set_list_intersection(set_list):
  if not set_list:
    return set()
  result = set_list[0]
  for s in set_list[1:]:
    result &= s
  return result

set_list = [set([1, 2]), set([1, 3]), set([1, 4])]
print set_list_intersection(set_list)
# Output: set([1])

You can also use reduce:

set_list = [set([1, 2]), set([1, 3]), set([1, 4])]
print reduce(lambda s1, s2: s1 & s2, set_list)
# Output: set([1])

However, many Python programmers dislike it, including Guido himself:

About 12 years ago, Python aquired lambda, reduce(), filter() and map(), courtesy of (I believe) a Lisp hacker who missed them and submitted working patches. But, despite of the PR value, I think these features should be cut from Python 3000.

So now reduce(). This is actually the one I've always hated most, because, apart from a few examples involving + or *, almost every time I see a reduce() call with a non-trivial function argument, I need to grab pen and paper to diagram what's actually being fed into that function before I understand what the reduce() is supposed to do. So in my mind, the applicability of reduce() is pretty much limited to associative operators, and in all other cases it's better to write out the accumulation loop explicitly.

Can I use complex HTML with Twitter Bootstrap's Tooltip?

Another solution to avoid inserting html into data-title is to create independant div with tooltip html content, and refer to this div when creating your tooltip :

<!-- Tooltip link -->
<p><span class="tip" data-tip="my-tip">Hello world</span></p>

<!-- Tooltip content -->
<div id="my-tip" class="tip-content hidden">
    <h2>Tip title</h2>
    <p>This is my tip content</p>
</div>

<script type="text/javascript">
    $(document).ready(function () {
        // Tooltips
        $('.tip').each(function () {
            $(this).tooltip(
            {
                html: true,
                title: $('#' + $(this).data('tip')).html()
            });
        });
    });
</script>

This way you can create complex readable html content, and activate as many tooltips as you want.

live demo here on codepen

increase font size of hyperlink text html

you can add class in anchor tag also like below

.a_class {font-size: 100px} 

How to access parameters in a RESTful POST method

Your @POST method should be accepting a JSON object instead of a string. Jersey uses JAXB to support marshaling and unmarshaling JSON objects (see the jersey docs for details). Create a class like:

@XmlRootElement
public class MyJaxBean {
    @XmlElement public String param1;
    @XmlElement public String param2;
}

Then your @POST method would look like the following:

@POST @Consumes("application/json")
@Path("/create")
public void create(final MyJaxBean input) {
    System.out.println("param1 = " + input.param1);
    System.out.println("param2 = " + input.param2);
}

This method expects to receive JSON object as the body of the HTTP POST. JAX-RS passes the content body of the HTTP message as an unannotated parameter -- input in this case. The actual message would look something like:

POST /create HTTP/1.1
Content-Type: application/json
Content-Length: 35
Host: www.example.com

{"param1":"hello","param2":"world"}

Using JSON in this way is quite common for obvious reasons. However, if you are generating or consuming it in something other than JavaScript, then you do have to be careful to properly escape the data. In JAX-RS, you would use a MessageBodyReader and MessageBodyWriter to implement this. I believe that Jersey already has implementations for the required types (e.g., Java primitives and JAXB wrapped classes) as well as for JSON. JAX-RS supports a number of other methods for passing data. These don't require the creation of a new class since the data is passed using simple argument passing.


HTML <FORM>

The parameters would be annotated using @FormParam:

@POST
@Path("/create")
public void create(@FormParam("param1") String param1,
                   @FormParam("param2") String param2) {
    ...
}

The browser will encode the form using "application/x-www-form-urlencoded". The JAX-RS runtime will take care of decoding the body and passing it to the method. Here's what you should see on the wire:

POST /create HTTP/1.1
Host: www.example.com
Content-Type: application/x-www-form-urlencoded;charset=UTF-8
Content-Length: 25

param1=hello&param2=world

The content is URL encoded in this case.

If you do not know the names of the FormParam's you can do the following:

@POST @Consumes("application/x-www-form-urlencoded")
@Path("/create")
public void create(final MultivaluedMap<String, String> formParams) {
    ...
}

HTTP Headers

You can using the @HeaderParam annotation if you want to pass parameters via HTTP headers:

@POST
@Path("/create")
public void create(@HeaderParam("param1") String param1,
                   @HeaderParam("param2") String param2) {
    ...
}

Here's what the HTTP message would look like. Note that this POST does not have a body.

POST /create HTTP/1.1
Content-Length: 0
Host: www.example.com
param1: hello
param2: world

I wouldn't use this method for generalized parameter passing. It is really handy if you need to access the value of a particular HTTP header though.


HTTP Query Parameters

This method is primarily used with HTTP GETs but it is equally applicable to POSTs. It uses the @QueryParam annotation.

@POST
@Path("/create")
public void create(@QueryParam("param1") String param1,
                   @QueryParam("param2") String param2) {
    ...
}

Like the previous technique, passing parameters via the query string does not require a message body. Here's the HTTP message:

POST /create?param1=hello&param2=world HTTP/1.1
Content-Length: 0
Host: www.example.com

You do have to be particularly careful to properly encode query parameters on the client side. Using query parameters can be problematic due to URL length restrictions enforced by some proxies as well as problems associated with encoding them.


HTTP Path Parameters

Path parameters are similar to query parameters except that they are embedded in the HTTP resource path. This method seems to be in favor today. There are impacts with respect to HTTP caching since the path is what really defines the HTTP resource. The code looks a little different than the others since the @Path annotation is modified and it uses @PathParam:

@POST
@Path("/create/{param1}/{param2}")
public void create(@PathParam("param1") String param1,
                   @PathParam("param2") String param2) {
    ...
}

The message is similar to the query parameter version except that the names of the parameters are not included anywhere in the message.

POST /create/hello/world HTTP/1.1
Content-Length: 0
Host: www.example.com

This method shares the same encoding woes that the query parameter version. Path segments are encoded differently so you do have to be careful there as well.


As you can see, there are pros and cons to each method. The choice is usually decided by your clients. If you are serving FORM-based HTML pages, then use @FormParam. If your clients are JavaScript+HTML5-based, then you will probably want to use JAXB-based serialization and JSON objects. The MessageBodyReader/Writer implementations should take care of the necessary escaping for you so that is one fewer thing that can go wrong. If your client is Java based but does not have a good XML processor (e.g., Android), then I would probably use FORM encoding since a content body is easier to generate and encode properly than URLs are. Hopefully this mini-wiki entry sheds some light on the various methods that JAX-RS supports.

Note: in the interest of full disclosure, I haven't actually used this feature of Jersey yet. We were tinkering with it since we have a number of JAXB+JAX-RS applications deployed and are moving into the mobile client space. JSON is a much better fit that XML on HTML5 or jQuery-based solutions.

Watching variables in SSIS during debug

Visual Studio 2013: Yes to both adding to the watch windows during debugging and dragging variables or typing them in without "user::". But before any of that would work I also needed to go to Tools > Options, then Debugging > General and had to scroll right down to the bottom of the right hand pane to be able to tick "Use Managed Compatibility Mode". Then I had to stop and restart debugging. Finally the above advice worked. Many thanks to the above and to this article: Visual Studio 2015 Debugging: Can't expand local variables?

How to compare DateTime without time via LINQ?

The .Date answer is misleading since you get the error mentioned before. Another way to compare, other than mentioned DbFunctions.TruncateTime, may also be:

DateTime today = DateTime.Now.date;
var q = db.Games.Where(t => SqlFunctions.DateDiff("dayofyear", today, t.StartDate) <= 0
      && SqlFunctions.DateDiff("year", today, t.StartDate) <= 0)

It looks better(more readable) in the generated SQL query. But I admit it looks worse in the C# code XD. I was testing something and it seemed like TruncateTime was not working for me unfortunately the fault was between keyboard and chair, but in the meantime I found this alternative.

Make Bootstrap 3 Tabs Responsive

enter image description here

There is a new one: http://hayatbiralem.com/blog/2015/05/15/responsive-bootstrap-tabs/

And also Codepen sample available here: http://codepen.io/hayatbiralem/pen/KpzjOL

No needs plugin. It uses just a little css and jquery.

Here's a sample tabs markup:

<ul class="nav nav-tabs nav-tabs-responsive">
    <li class="active">
        <a href="#tab1" data-toggle="tab">
            <span class="text">Tab 1</span>
        </a>
    </li>
    <li class="next">
        <a href="#tab2" data-toggle="tab">
            <span class="text">Tab 2</span>
        </a>
    </li>
    <li>
        <a href="#tab3" data-toggle="tab">
            <span class="text">Tab 3</span>
        </a>
    </li>
    ...
</ul>

.. and jQuery codes are also here:

(function($) {

  'use strict';

  $(document).on('show.bs.tab', '.nav-tabs-responsive [data-toggle="tab"]', function(e) {
    var $target = $(e.target);
    var $tabs = $target.closest('.nav-tabs-responsive');
    var $current = $target.closest('li');
    var $parent = $current.closest('li.dropdown');
        $current = $parent.length > 0 ? $parent : $current;
    var $next = $current.next();
    var $prev = $current.prev();
    var updateDropdownMenu = function($el, position){
      $el
        .find('.dropdown-menu')
        .removeClass('pull-xs-left pull-xs-center pull-xs-right')
        .addClass( 'pull-xs-' + position );
    };

    $tabs.find('>li').removeClass('next prev');
    $prev.addClass('prev');
    $next.addClass('next');

    updateDropdownMenu( $prev, 'left' );
    updateDropdownMenu( $current, 'center' );
    updateDropdownMenu( $next, 'right' );
  });

})(jQuery);

How to split a dataframe string column into two columns?

If you want to split a string into more than two columns based on a delimiter you can omit the 'maximum splits' parameter.
You can use:

df['column_name'].str.split('/', expand=True)

This will automatically create as many columns as the maximum number of fields included in any of your initial strings.

How many times a substring occurs

def count_substring(string, sub_string):
    inc = 0
    for i in range(0, len(string)):
        slice_object = slice(i,len(sub_string)+i)
        count = len(string[slice_object])
        if(count == len(sub_string)):
            if(sub_string == string[slice_object]):
                inc = inc + 1
    return inc

if __name__ == '__main__':
    string = input().strip()
    sub_string = input().strip()

    count = count_substring(string, sub_string)
    print(count)

How can I create C header files

Header files can contain any valid C code, since they are injected into the compilation unit by the pre-processor prior to compilation.

If a header file contains a function, and is included by multiple .c files, each .c file will get a copy of that function and create a symbol for it. The linker will complain about the duplicate symbols.

It is technically possible to create static functions in a header file for inclusion in multiple .c files. Though this is generally not done because it breaks from the convention that code is found in .c files and declarations are found in .h files.

See the discussions in C/C++: Static function in header file, what does it mean? for more explanation.

Counter in foreach loop in C#

This is only true if you're iterating through an array; what if you were iterating through a different kind of collection that has no notion of accessing by index? In the array case, the easiest way to retain the index is to simply use a vanilla for loop.

Disabled href tag

HTML:

<a href="/" class="btn-disabled" disabled="disabled">123n</a>

CSS:

.btn-disabled,
.btn-disabled[disabled] {
  opacity: .4;
  cursor: default !important;
  pointer-events: none;
}

How to get the type of a variable in MATLAB?

class() function is the equivalent of typeof()

You can also use isa() to check if a variable is of a particular type. If you want to be even more specific, you can use ischar(), isfloat(), iscell(), etc.

How can I clear the Scanner buffer in Java?

You can't explicitly clear Scanner's buffer. Internally, it may clear the buffer after a token is read, but that's an implementation detail outside of the porgrammers' reach.

Returning http status code from Web Api controller

For ASP.NET Web Api 2, this post from MS suggests to change the method's return type to IHttpActionResult. You can then return a built in IHttpActionResult implementation like Ok, BadRequest, etc (see here) or return your own implementation.

For your code, it could be done like:

public IHttpActionResult GetUser(int userId, DateTime lastModifiedAtClient)
{
    var user = new DataEntities().Users.First(p => p.Id == userId);
    if (user.LastModified <= lastModifiedAtClient)
    {
        return StatusCode(HttpStatusCode.NotModified);
    }
    return Ok(user);
}

How can I get date in application run by node.js?

You would use the javascript date object:

MDN documentation for the Date object

var d = new Date();

CSS3 Box Shadow on Top, Left, and Right Only

#div:before {
 content:"";
 position:absolute;
 width:100%;
 background:#fff;
 height:38px;
 top:1px;
 right:-5px;
}

Java - get the current class name?

Try,

String className = this.getClass().getSimpleName();

This will work as long as you don't use it in a static method.

What do hjust and vjust do when making a plot using ggplot?

The value of hjust and vjust are only defined between 0 and 1:

  • 0 means left-justified
  • 1 means right-justified

Source: ggplot2, Hadley Wickham, page 196

(Yes, I know that in most cases you can use it beyond this range, but don't expect it to behave in any specific way. This is outside spec.)

hjust controls horizontal justification and vjust controls vertical justification.

An example should make this clear:

td <- expand.grid(
    hjust=c(0, 0.5, 1),
    vjust=c(0, 0.5, 1),
    angle=c(0, 45, 90),
    text="text"
)

ggplot(td, aes(x=hjust, y=vjust)) + 
    geom_point() +
    geom_text(aes(label=text, angle=angle, hjust=hjust, vjust=vjust)) + 
    facet_grid(~angle) +
    scale_x_continuous(breaks=c(0, 0.5, 1), expand=c(0, 0.2)) +
    scale_y_continuous(breaks=c(0, 0.5, 1), expand=c(0, 0.2))

enter image description here


To understand what happens when you change the hjust in axis text, you need to understand that the horizontal alignment for axis text is defined in relation not to the x-axis, but to the entire plot (where this includes the y-axis text). (This is, in my view, unfortunate. It would be much more useful to have the alignment relative to the axis.)

DF <- data.frame(x=LETTERS[1:3],y=1:3)
p <- ggplot(DF, aes(x,y)) + geom_point() + 
    ylab("Very long label for y") +
    theme(axis.title.y=element_text(angle=0))


p1 <- p + theme(axis.title.x=element_text(hjust=0)) + xlab("X-axis at hjust=0")
p2 <- p + theme(axis.title.x=element_text(hjust=0.5)) + xlab("X-axis at hjust=0.5")
p3 <- p + theme(axis.title.x=element_text(hjust=1)) + xlab("X-axis at hjust=1")

library(ggExtra)
align.plots(p1, p2, p3)

enter image description here


To explore what happens with vjust aligment of axis labels:

DF <- data.frame(x=c("a\na","b","cdefghijk","l"),y=1:4)
p <- ggplot(DF, aes(x,y)) + geom_point()

p1 <- p + theme(axis.text.x=element_text(vjust=0, colour="red")) + 
        xlab("X-axis labels aligned with vjust=0")
p2 <- p + theme(axis.text.x=element_text(vjust=0.5, colour="red")) + 
        xlab("X-axis labels aligned with vjust=0.5")
p3 <- p + theme(axis.text.x=element_text(vjust=1, colour="red")) + 
        xlab("X-axis labels aligned with vjust=1")


library(ggExtra)
align.plots(p1, p2, p3)

enter image description here

C++ unordered_map using a custom class type as the key

check the following link https://www.geeksforgeeks.org/how-to-create-an-unordered_map-of-user-defined-class-in-cpp/ for more details.

  • the custom class must implement the == operator
  • must create a hash function for the class (for primitive types like int and also types like string the hash function is predefined)

"R cannot be resolved to a variable"?

for me, the best solution to suggest to people that have problems with the "R" file would be to try the next steps (order doesn't matter) :

  1. update ADT & SDK , Eclipse and Java (both 1.6 and the latest one).

    EDIT: now the ADT supports Java 1.7 . link here.

  2. remove gen folder , and create it again .

  3. do a clean-project.

  4. right click the project and choose android-tools -> fix-project-properties .

  5. right click the project and choose properties -> java-build-path -> order-and-export. make sure the order is :

    • Android 4.4 (always the latest version)

    • Android private libraries

    • android dependencies

    • your library project/s if needed

    • yourAppProject/gen

    • yourAppProject/src

  6. make sure all files in the res folder's subfolders have names that are ok : only lowercase letters, digits and underscore ("_") .

  7. always make sure the targetSdk is pointed to the latest API (currently 19) , and set it in the project.properties file

  8. try to run Lint and read its warnings. they might help you out.

  9. make sure your project compiles on 1.6 java and not a different version.

  10. restart eclipse.

How can I make a list of lists in R?

The example creates a list of named lists in a loop.

  MyList <- list()
  for (aName in c("name1", "name2")){
    MyList[[aName]] <- list(aName)
  }
  MyList[["name1"]]
  MyList[["name2"]]

To add another list named "name3" do write:

  MyList$name3 <- list(1, 2, 3)

Reading/writing an INI file

Here is my own version, using regular expressions. This code assumes that each section name is unique - if however this is not true - it makes sense to replace Dictionary with List. This function supports .ini file commenting, starting from ';' character. Section starts normally [section], and key value pairs also comes normally "key = value". Same assumption as for sections - key name is unique.

/// <summary>
/// Loads .ini file into dictionary.
/// </summary>
public static Dictionary<String, Dictionary<String, String>> loadIni(String file)
{
    Dictionary<String, Dictionary<String, String>> d = new Dictionary<string, Dictionary<string, string>>();

    String ini = File.ReadAllText(file);

    // Remove comments, preserve linefeeds, if end-user needs to count line number.
    ini = Regex.Replace(ini, @"^\s*;.*$", "", RegexOptions.Multiline);

    // Pick up all lines from first section to another section
    foreach (Match m in Regex.Matches(ini, "(^|[\r\n])\\[([^\r\n]*)\\][\r\n]+(.*?)(\\[([^\r\n]*)\\][\r\n]+|$)", RegexOptions.Singleline))
    {
        String sectionName = m.Groups[2].Value;
        Dictionary<String, String> lines = new Dictionary<String, String>();

        // Pick up "key = value" kind of syntax.
        foreach (Match l in Regex.Matches(ini, @"^\s*(.*?)\s*=\s*(.*?)\s*$", RegexOptions.Multiline))
        {
            String key = l.Groups[1].Value;
            String value = l.Groups[2].Value;

            // Open up quotation if any.
            value = Regex.Replace(value, "^\"(.*)\"$", "$1");

            if (!lines.ContainsKey(key))
                lines[key] = value;
        }

        if (!d.ContainsKey(sectionName))
            d[sectionName] = lines;
    }

    return d;
}

Javascript - How to extract filename from a file input control

Assuming your <input type="file" > has an id of upload this should hopefully do the trick:

var fullPath = document.getElementById('upload').value;
if (fullPath) {
    var startIndex = (fullPath.indexOf('\\') >= 0 ? fullPath.lastIndexOf('\\') : fullPath.lastIndexOf('/'));
    var filename = fullPath.substring(startIndex);
    if (filename.indexOf('\\') === 0 || filename.indexOf('/') === 0) {
        filename = filename.substring(1);
    }
    alert(filename);
}

iFrame src change event detection?

The iframe always keeps the parent page, you should use this to detect in which page you are in the iframe:

Html code:

<iframe id="iframe" frameborder="0" scrolling="no" onload="resizeIframe(this)" width="100%" src="www.google.com"></iframe>

Js:

    function resizeIframe(obj) {
        alert(obj.contentWindow.location.pathname);
    }

How to write data to a JSON file using Javascript

Unfortunatelly, today (September 2018) you can not find cross-browser solution for client side file writing.

For example: in some browser like a Chrome we have today this possibility and we can write with FileSystemFileEntry.createWriter() with client side call, but according to the docu:

This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it.


For IE (but not MS Edge) we could use ActiveX too, but this is only for this client.

If you want update your JSON file cross-browser you have to use server and client side together.

The client side script

On client side you can make a request to the server and then you have to read the response from server. Or you could read a file with FileReader too. For the cross-browser writing to the file you have to have some server (see below on server part).

var xhr = new XMLHttpRequest(),
    jsonArr,
    method = "GET",
    jsonRequestURL = "SOME_PATH/jsonFile/";

xhr.open(method, jsonRequestURL, true);
xhr.onreadystatechange = function()
{
    if(xhr.readyState == 4 && xhr.status == 200)
    {
        // we convert your JSON into JavaScript object
        jsonArr = JSON.parse(xhr.responseText);

        // we add new value:
        jsonArr.push({"nissan": "sentra", "color": "green"});

        // we send with new request the updated JSON file to the server:
        xhr.open("POST", jsonRequestURL, true);
        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        // if you want to handle the POST response write (in this case you do not need it):
        // xhr.onreadystatechange = function(){ /* handle POST response */ };
        xhr.send("jsonTxt="+JSON.stringify(jsonArr));
        // but on this place you have to have a server for write updated JSON to the file
    }
};
xhr.send(null);

Server side scripts

You can use a lot of different servers, but I would like to write about PHP and Node.js servers.

By using searching machine you could find "free PHP Web Hosting*" or "free Node.js Web Hosting". For PHP server I would recommend 000webhost.com and for Node.js I would recommend to see and to read this list.

PHP server side script solution

The PHP script for reading and writing from JSON file:

<?php

// This PHP script must be in "SOME_PATH/jsonFile/index.php"

$file = 'jsonFile.txt';

if($_SERVER['REQUEST_METHOD'] === 'POST')
// or if(!empty($_POST))
{
    file_put_contents($file, $_POST["jsonTxt"]);
    //may be some error handeling if you want
}
else if($_SERVER['REQUEST_METHOD'] === 'GET')
// or else if(!empty($_GET))
{
    echo file_get_contents($file);
    //may be some error handeling if you want
}
?>

Node.js server side script solution

I think that Node.js is a little bit complex for beginner. This is not normal JavaScript like in browser. Before you start with Node.js I would recommend to read one from two books:

The Node.js script for reading and writing from JSON file:

var http = require("http"),
    fs = require("fs"),
    port = 8080,
    pathToJSONFile = '/SOME_PATH/jsonFile.txt';

http.createServer(function(request, response)
{
    if(request.method == 'GET')
    {
        response.writeHead(200, {"Content-Type": "application/json"});
        response.write(fs.readFile(pathToJSONFile, 'utf8'));
        response.end();
    }
    else if(request.method == 'POST')
    {
        var body = [];

        request.on('data', function(chunk)
        {
            body.push(chunk);
        });

        request.on('end', function()
        {
            body = Buffer.concat(body).toString();
            var myJSONdata = body.split("=")[1];
            fs.writeFileSync(pathToJSONFile, myJSONdata); //default: 'utf8'
        });
    }
}).listen(port);

Related links for Node.js:

How can I concatenate two arrays in Java?

Using Stream in Java 8:

String[] both = Stream.concat(Arrays.stream(a), Arrays.stream(b))
                      .toArray(String[]::new);

Or like this, using flatMap:

String[] both = Stream.of(a, b).flatMap(Stream::of)
                      .toArray(String[]::new);

To do this for a generic type you have to use reflection:

@SuppressWarnings("unchecked")
T[] both = Stream.concat(Arrays.stream(a), Arrays.stream(b)).toArray(
    size -> (T[]) Array.newInstance(a.getClass().getComponentType(), size));

Removing empty rows of a data file in R

I assume you want to remove rows that are all NAs. Then, you can do the following :

data <- rbind(c(1,2,3), c(1, NA, 4), c(4,6,7), c(NA, NA, NA), c(4, 8, NA)) # sample data
data
     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    1   NA    4
[3,]    4    6    7
[4,]   NA   NA   NA
[5,]    4    8   NA

data[rowSums(is.na(data)) != ncol(data),]
     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    1   NA    4
[3,]    4    6    7
[4,]    4    8   NA

If you want to remove rows that have at least one NA, just change the condition :

data[rowSums(is.na(data)) == 0,]
     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    4    6    7

grep for multiple strings in file on different lines (ie. whole file, not line based search)?

You can do this really easily with ack:

ack -l 'cats' | ack -xl 'dogs'
  • -l: return a list of files
  • -x: take the files from STDIN (the previous search) and only search those files

And you can just keep piping until you get just the files you want.

How to specify names of columns for x and y when joining in dplyr?

This feature has been added in dplyr v0.3. You can now pass a named character vector to the by argument in left_join (and other joining functions) to specify which columns to join on in each data frame. With the example given in the original question, the code would be:

left_join(test_data, kantrowitz, by = c("first_name" = "name"))

CSS two div width 50% in one line with line break in file

Give this parent DIV font-size:0. Write like this:

<div style="font-size:0">
  <div style="width:50%; display:inline-table;font-size:15px">A</div>
  <div style="width:50%; display:inline-table;font-size:15px">B</div>
</div>

Deep cloning objects

Here a solution fast and easy that worked for me without relaying on Serialization/Deserialization.

public class MyClass
{
    public virtual MyClass DeepClone()
    {
        var returnObj = (MyClass)MemberwiseClone();
        var type = returnObj.GetType();
        var fieldInfoArray = type.GetRuntimeFields().ToArray();

        foreach (var fieldInfo in fieldInfoArray)
        {
            object sourceFieldValue = fieldInfo.GetValue(this);
            if (!(sourceFieldValue is MyClass))
            {
                continue;
            }

            var sourceObj = (MyClass)sourceFieldValue;
            var clonedObj = sourceObj.DeepClone();
            fieldInfo.SetValue(returnObj, clonedObj);
        }
        return returnObj;
    }
}

EDIT: requires

    using System.Linq;
    using System.Reflection;

That's How I used it

public MyClass Clone(MyClass theObjectIneededToClone)
{
    MyClass clonedObj = theObjectIneededToClone.DeepClone();
}

Image overlay on responsive sized images bootstrap

If i understand your question you want to have the overlay just over the image and not cover everything?

I'd set the parent DIV (i renamed in content in the jsfiddle) position to relative, as the overlay should be positioned relative to this div not the window.

.content
{
  position: relative;
}

I did some pocking around and updated your fiddle to just have the overlay sized to the img which (I think) is what you want, let me know anyway :) http://jsfiddle.net/b9Vyw/

Can you nest html forms?

The second form will be ignored, see the snippet from WebKit for example:

bool HTMLParser::formCreateErrorCheck(Token* t, RefPtr<Node>& result)
{
    // Only create a new form if we're not already inside one.
    // This is consistent with other browsers' behavior.
    if (!m_currentFormElement) {
        m_currentFormElement = new HTMLFormElement(formTag, m_document);
        result = m_currentFormElement;
        pCloserCreateErrorCheck(t, result);
    }
    return false;
}

Best way to store a key=>value array in JavaScript?

If I understood you correctly:

var hash = {};
hash['bob'] = 123;
hash['joe'] = 456;

var sum = 0;
for (var name in hash) {
    sum += hash[name];
}
alert(sum); // 579

Checking if sys.argv[x] is defined

I use this - it never fails:

startingpoint = 'blah'
if sys.argv[1:]:
   startingpoint = sys.argv[1]

Radio Buttons "Checked" Attribute Not Working

Radio inputs must be inside of a form for 'checked' to work.

A non well formed numeric value encountered

This error occurs when you perform calculations with variables that use letters combined with numbers (alphanumeric), for example 24kb, 886ab ...

I had the error in the following function

function get_config_bytes($val) {
    $val = trim($val);
    $last = strtolower($val[strlen($val)-1]);       
    switch($last) {
        case 'g':
            $val *= 1024;
        case 'm':
            $val *= 1024;
        case 'k':
            $val *= 1024;
    }
    return $this->fix_integer_overflow($val);
}

The application uploads images but it didn't work, it showed the following warning:

enter image description here

Solution: The intval() function extracts the integer value of a variable with alphanumeric data and creates a new variable with the same value but converted to an integer with the intval() function. Here is the code:

function get_config_bytes($val) {
    $val = trim($val);
    $last = strtolower($val[strlen($val)-1]);
    $intval = intval(trim($val));
    switch($last) {
        case 'g':
            $intval *= 1024;
        case 'm':
            $intval *= 1024;
        case 'k':
            $intval *= 1024;
    }
    return $this->fix_integer_overflow($intval);
}

ORA-06508: PL/SQL: could not find program unit being called

Based on previous answers. I resolved my issue by removing global variable at package level to procedure, since there was no impact in my case.

Original script was

create or replace PACKAGE BODY APPLICATION_VALIDATION AS 

V_ERROR_NAME varchar2(200) := '';

PROCEDURE  APP_ERROR_X47_VALIDATION (   PROCESS_ID IN VARCHAR2 ) AS BEGIN
     ------ rules for validation... END APP_ERROR_X47_VALIDATION ;

/* Some more code
*/

END APPLICATION_VALIDATION; /

Rewritten the same without global variable V_ERROR_NAME and moved to procedure under package level as

Modified Code

create or replace PACKAGE BODY APPLICATION_VALIDATION AS

PROCEDURE  APP_ERROR_X47_VALIDATION (   PROCESS_ID IN VARCHAR2 ) AS

**V_ERROR_NAME varchar2(200) := '';** 

BEGIN
     ------ rules for validation... END APP_ERROR_X47_VALIDATION ;

/* Some more code
*/

END APPLICATION_VALIDATION; /

How can bcrypt have built-in salts?

This is from PasswordEncoder interface documentation from Spring Security,

 * @param rawPassword the raw password to encode and match
 * @param encodedPassword the encoded password from storage to compare with
 * @return true if the raw password, after encoding, matches the encoded password from
 * storage
 */
boolean matches(CharSequence rawPassword, String encodedPassword);

Which means, one will need to match rawPassword that user will enter again upon next login and matches it with Bcrypt encoded password that's stores in database during previous login/registration.

want current date and time in "dd/MM/yyyy HH:mm:ss.SS" format

Use:

 System.out.println("Current date in Date Format: " + sdf.format(date));

Extract string between two strings in java

I have answered this question here: https://stackoverflow.com/a/38238785/1773972

Basically use

StringUtils.substringBetween(str, "<%=", "%>");

This requirs using "Apache commons lang" library: https://mvnrepository.com/artifact/org.apache.commons/commons-lang3/3.4

This library has a lot of useful methods for working with string, you will really benefit from exploring this library in other areas of your java code !!!

How Can I Set the Default Value of a Timestamp Column to the Current Timestamp with Laravel Migrations?

Use Paulo Freitas suggestion instead.


Until Laravel fixes this, you can run a standard database query after the Schema::create have been run.

    Schema::create("users", function($table){
        $table->increments('id');
        $table->string('email', 255);
        $table->string('given_name', 100);
        $table->string('family_name', 100);
        $table->timestamp('joined');
        $table->enum('gender', ['male', 'female', 'unisex'])->default('unisex');
        $table->string('timezone', 30)->default('UTC');
        $table->text('about');
    });
    DB::statement("ALTER TABLE ".DB::getTablePrefix()."users CHANGE joined joined TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL");

It worked wonders for me.

Pointtype command for gnuplot

You first have to tell Gnuplot to use a style that uses points, e.g. with points or with linespoints. Try for example:

plot sin(x) with points

Output:

Now try:

plot sin(x) with points pointtype 5

Output:

You may also want to look at the output from the test command which shows you the capabilities of the current terminal. Here are the capabilities for my pngairo terminal:

Convert Mongoose docs to json

model.find({Branch:branch},function (err, docs){
  if (err) res.send(err)

  res.send(JSON.parse(JSON.stringify(docs)))
});

how to clear the screen in python

If you mean the screen where you have that interpreter prompt >>> you can do CTRL+L on Bash shell can help. Windows does not have equivalent. You can do

import os
os.system('cls')  # on windows

or

os.system('clear')  # on linux / os x

What's the difference between implementation and compile in Gradle?

  • implementation: mostly we use implementation configuration. It hides the internal dependency of the module to its consumer to avoid accidental use of any transitive dependency, hence faster compilation and less recompilation.

  • api: must be used very carefully, since it leaks the to consumer’s compile classpath, hence misusing of api could lead to dependency pollution.

  • compileOnly: when we don’t need any dependency at runtime, since compileOnly dependency won’t become the part of the final build. we will get a smaller build size.

  • runtimeOnly: when we want to change or swap the behaviour of the library at runtime (in final build).

I have created a post with an in-depth understanding of each one with Working Example: source code

https://medium.com/@gauraw.negi/how-gradle-dependency-configurations-work-underhood-e934906752e5

Gradle configurations

Java POI : How to read Excel cell value and not the formula computing it?

There is an alternative command where you can get the raw value of a cell where formula is put on. It's returns type is String. Use:

cell.getRawValue();

LaTeX: Multiple authors in a two-column article

What about using a tabular inside \author{}, just like in IEEE macros:

\documentclass{article}
\begin{document}
\title{Hello, World}
\author{
\begin{tabular}[t]{c@{\extracolsep{8em}}c} 
I. M. Author  & M. Y. Coauthor \\
My Department & Coauthor Department \\ 
My Institute & Coauthor Institute \\
email, address & email, address
\end{tabular}
}
\maketitle    
\end{document}

This will produce two columns authors with any documentclass.

Results:

enter image description here

keycloak Invalid parameter: redirect_uri

What worked for me was adding wildchar '*'. Although for production builds, I am going to be more specific with the value of this field. But for dev purposes you can do this.

enter image description here

Setting available under, keycloak admin console -> Realm_Name -> Cients -> Client_Name.

EDIT: DO NOT DO THIS IN PRODUCTION. Doing so creates a large security flaw.

Get push notification while App in foreground iOS

Best Approach for this is to add UNUserNotificationCenterDelegate in AppDelegate by using extension AppDelegate: UNUserNotificationCenterDelegate That extension tells the app to be able to get notification when in use

And implement this method

func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        completionHandler(.alert)
    }

This method will be called on the delegate only if the application is in the Foreground.

So The final Implementation:

extension AppDelegate: UNUserNotificationCenterDelegate {
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        completionHandler(.alert)
    }
}

And To call this you must set the delegate in AppDelegate in didFinishLaunchingWithOptions add this line

UNUserNotificationCenter.current().delegate = self

You can modify

completionHandler(.alert) 

with

completionHandler([.alert, .badge, .sound]))

select the TOP N rows from a table

From SQL Server 2012 you can use a native pagination in order to have semplicity and best performance:

https://docs.microsoft.com/en-us/sql/t-sql/queries/select-order-by-clause-transact-sql?view=sql-server-ver15#using-offset-and-fetch-to-limit-the-rows-returned

Your query become:

SELECT * FROM Reflow  
WHERE ReflowProcessID = somenumber
ORDER BY ID DESC;
OFFSET 20 ROWS  
FETCH NEXT 20 ROWS ONLY;  

HTTP GET with request body

You have a list of options which are far better than using a request body with GET.

Let' assume you have categories and items for each category. Both to be identified by an id ("catid" / "itemid" for the sake of this example). You want to sort according to another parameter "sortby" in a specific "order". You want to pass parameters for "sortby" and "order":

You can:

  1. Use query strings, e.g. example.com/category/{catid}/item/{itemid}?sortby=itemname&order=asc
  2. Use mod_rewrite (or similar) for paths: example.com/category/{catid}/item/{itemid}/{sortby}/{order}
  3. Use individual HTTP headers you pass with the request
  4. Use a different method, e.g. POST, to retrieve a resource.

All have their downsides, but are far better than using a GET with a body.

How to get JSON response from http.Get

The results from json.Unmarshal (into var data interface{}) do not directly match your Go type and variable declarations. For example,

package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "net/http"
    "os"
)

type Tracks struct {
    Toptracks []Toptracks_info
}

type Toptracks_info struct {
    Track []Track_info
    Attr  []Attr_info
}

type Track_info struct {
    Name       string
    Duration   string
    Listeners  string
    Mbid       string
    Url        string
    Streamable []Streamable_info
    Artist     []Artist_info
    Attr       []Track_attr_info
}

type Attr_info struct {
    Country    string
    Page       string
    PerPage    string
    TotalPages string
    Total      string
}

type Streamable_info struct {
    Text      string
    Fulltrack string
}

type Artist_info struct {
    Name string
    Mbid string
    Url  string
}

type Track_attr_info struct {
    Rank string
}

func get_content() {
    // json data
    url := "http://ws.audioscrobbler.com/2.0/?method=geo.gettoptracks&api_key=c1572082105bd40d247836b5c1819623&format=json&country=Netherlands"
    url += "&limit=1" // limit data for testing
    res, err := http.Get(url)
    if err != nil {
        panic(err.Error())
    }
    body, err := ioutil.ReadAll(res.Body)
    if err != nil {
        panic(err.Error())
    }
    var data interface{} // TopTracks
    err = json.Unmarshal(body, &data)
    if err != nil {
        panic(err.Error())
    }
    fmt.Printf("Results: %v\n", data)
    os.Exit(0)
}

func main() {
    get_content()
}

Output:

Results: map[toptracks:map[track:map[name:Get Lucky (feat. Pharrell Williams) listeners:1863 url:http://www.last.fm/music/Daft+Punk/_/Get+Lucky+(feat.+Pharrell+Williams) artist:map[name:Daft Punk mbid:056e4f3e-d505-4dad-8ec1-d04f521cbb56 url:http://www.last.fm/music/Daft+Punk] image:[map[#text:http://userserve-ak.last.fm/serve/34s/88137413.png size:small] map[#text:http://userserve-ak.last.fm/serve/64s/88137413.png size:medium] map[#text:http://userserve-ak.last.fm/serve/126/88137413.png size:large] map[#text:http://userserve-ak.last.fm/serve/300x300/88137413.png size:extralarge]] @attr:map[rank:1] duration:369 mbid: streamable:map[#text:1 fulltrack:0]] @attr:map[country:Netherlands page:1 perPage:1 totalPages:500 total:500]]]

Find Locked Table in SQL Server

sp_lock

When reading sp_lock information, use the OBJECT_NAME( ) function to get the name of a table from its ID number, for example:

SELECT object_name(16003073)

EDIT :

There is another proc provided by microsoft which reports objects without the ID translation : http://support.microsoft.com/kb/q255596/

Getting time span between two times in C#?

Another way ( longer ) In VB.net [ Say 2300 Start and 0700 Finish next day ]

If tsStart > tsFinish Then

                            ' Take Hours difference and adjust accordingly
                            tsDifference = New TimeSpan((24 - tsStart.Hours) + tsFinish.Hours, 0, 0)

                            ' Add Minutes to Difference
                            tsDifference = tsDifference.Add(New TimeSpan(0, Math.Abs(tsStart.Minutes - tsFinish.Minutes), 0))


                            ' Add Seonds to Difference
                            tsDifference = tsDifference.Add(New TimeSpan(0, 0, Math.Abs(tsStart.Seconds - tsFinish.Seconds)))

How can I take a screenshot with Selenium WebDriver?

Python

webdriver.get_screenshot_as_file(filepath)

The above method will take a screenshot and also store it as a file in the location provided as a parameter.

Two models in one view in ASP MVC 3

Just create a single view Model with all the needed information in it, normaly what I do is create a model for every view so I can be specific on every view, either that or make a parent model and inherit it. OR make a model which includes both the views.

Personally I would just add them into one model but thats the way I do it:

public class xViewModel
{
    public int PersonID { get; set; }
    public string PersonName { get; set; }
    public int OrderID { get; set; }
    public int TotalSum { get; set; }
}

@model project.Models.Home.xViewModel

@using(Html.BeginForm())
{
    @Html.EditorFor(x => x.PersonID)
    @Html.EditorFor(x => x.PersonName)
    @Html.EditorFor(x => x.OrderID)
    @Html.EditorFor(x => x.TotalSum)
}

Passing parameter using onclick or a click binding with KnockoutJS

A generic answer on how to handle click events with KnockoutJS...

Not a straight up answer to the question as asked, but probably an answer to the question most Googlers landing here have: use the click binding from KnockoutJS instead of onclick. Like this:

_x000D_
_x000D_
function Item(parent, txt) {_x000D_
  var self = this;_x000D_
  _x000D_
  self.doStuff = function(data, event) {_x000D_
    console.log(data, event);_x000D_
    parent.log(parent.log() + "\n  data = " + ko.toJSON(data));_x000D_
  };_x000D_
  _x000D_
  self.doOtherStuff = function(customParam, data, event) {_x000D_
    console.log(data, event);_x000D_
    parent.log(parent.log() + "\n  data = " + ko.toJSON(data) + ", customParam = " + customParam);_x000D_
  };_x000D_
  _x000D_
  self.txt = ko.observable(txt);_x000D_
}_x000D_
_x000D_
function RootVm(items) {_x000D_
  var self = this;_x000D_
  _x000D_
  self.doParentStuff = function(data, event) {_x000D_
    console.log(data, event);_x000D_
    self.log(self.log() + "\n  data = " + ko.toJSON(data));_x000D_
  };_x000D_
  _x000D_
  self.items = ko.observableArray([_x000D_
    new Item(self, "John Doe"),_x000D_
    new Item(self, "Marcus Aurelius")_x000D_
  ]);_x000D_
  self.log = ko.observable("Started logging...");_x000D_
}_x000D_
_x000D_
ko.applyBindings(new RootVm());
_x000D_
.parent { background: rgba(150, 150, 200, 0.5); padding: 2px; margin: 5px; }_x000D_
button { margin: 2px 0; font-family: consolas; font-size: 11px; }_x000D_
pre { background: #eee; border: 1px solid #ccc; padding: 5px; }
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.0/knockout-min.js"></script>_x000D_
_x000D_
<div data-bind="foreach: items">_x000D_
  <div class="parent">_x000D_
    <span data-bind="text: txt"></span><br>_x000D_
    <button data-bind="click: doStuff">click: doStuff</button><br>_x000D_
    <button data-bind="click: $parent.doParentStuff">click: $parent.doParentStuff</button><br>_x000D_
    <button data-bind="click: $root.doParentStuff">click: $root.doParentStuff</button><br>_x000D_
    <button data-bind="click: function(data, event) { $parent.log($parent.log() + '\n  data = ' + ko.toJSON(data)); }">click: function(data, event) { $parent.log($parent.log() + '\n  data = ' + ko.toJSON(data)); }</button><br>_x000D_
    <button data-bind="click: doOtherStuff.bind($data, 'test 123')">click: doOtherStuff.bind($data, 'test 123')</button><br>_x000D_
    <button data-bind="click: function(data, event) { doOtherStuff('test 123', $data, event); }">click: function(data, event) { doOtherStuff($data, 'test 123', event); }</button><br>_x000D_
  </div>_x000D_
</div>_x000D_
_x000D_
Click log:_x000D_
<pre data-bind="text: log"></pre>
_x000D_
_x000D_
_x000D_


**A note about the actual question...*

The actual question has one interesting bit:

// Uh oh! Modifying the DOM....
place.innerHTML = "somthing"

Don't do that! Don't modify the DOM like that when using an MVVM framework like KnockoutJS, especially not the piece of the DOM that is your own parent. If you would do this the button would disappear (if you replace your parent's innerHTML you yourself will be gone forever ever!).

Instead, modify the View Model in your handler instead, and have the View respond. For example:

_x000D_
_x000D_
function RootVm() {_x000D_
  var self = this;_x000D_
  self.buttonWasClickedOnce = ko.observable(false);_x000D_
  self.toggle = function(data, event) {_x000D_
    self.buttonWasClickedOnce(!self.buttonWasClickedOnce());_x000D_
  };_x000D_
}_x000D_
_x000D_
ko.applyBindings(new RootVm());
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.0/knockout-min.js"></script>_x000D_
_x000D_
<div>_x000D_
  <div  data-bind="visible: !buttonWasClickedOnce()">_x000D_
    <button data-bind="click: toggle">Toggle!</button>_x000D_
  </div>_x000D_
  <div data-bind="visible: buttonWasClickedOnce">_x000D_
    Can be made visible with toggle..._x000D_
    <button data-bind="click: toggle">Untoggle!</button>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

List of phone number country codes

There is a fairly well maintained repo on github that has a CSV (with semicolon delimiters), XML, and JSON source of countries, country codes, and other information.

In Python, how do I determine if an object is iterable?

def is_iterable(x):
    try:
        0 in x
    except TypeError:
        return False
    else:
        return True

This will say yes to all manner of iterable objects, but it will say no to strings in Python 2. (That's what I want for example when a recursive function could take a string or a container of strings. In that situation, asking forgiveness may lead to obfuscode, and it's better to ask permission first.)

import numpy

class Yes:
    def __iter__(self):
        yield 1;
        yield 2;
        yield 3;

class No:
    pass

class Nope:
    def __iter__(self):
        return 'nonsense'

assert is_iterable(Yes())
assert is_iterable(range(3))
assert is_iterable((1,2,3))   # tuple
assert is_iterable([1,2,3])   # list
assert is_iterable({1,2,3})   # set
assert is_iterable({1:'one', 2:'two', 3:'three'})   # dictionary
assert is_iterable(numpy.array([1,2,3]))
assert is_iterable(bytearray("not really a string", 'utf-8'))

assert not is_iterable(No())
assert not is_iterable(Nope())
assert not is_iterable("string")
assert not is_iterable(42)
assert not is_iterable(True)
assert not is_iterable(None)

Many other strategies here will say yes to strings. Use them if that's what you want.

import collections
import numpy

assert isinstance("string", collections.Iterable)
assert isinstance("string", collections.Sequence)
assert numpy.iterable("string")
assert iter("string")
assert hasattr("string", '__getitem__')

Note: is_iterable() will say yes to strings of type bytes and bytearray.

  • bytes objects in Python 3 are iterable True == is_iterable(b"string") == is_iterable("string".encode('utf-8')) There is no such type in Python 2.
  • bytearray objects in Python 2 and 3 are iterable True == is_iterable(bytearray(b"abc"))

The O.P. hasattr(x, '__iter__') approach will say yes to strings in Python 3 and no in Python 2 (no matter whether '' or b'' or u''). Thanks to @LuisMasuelli for noticing it will also let you down on a buggy __iter__.

How can I store HashMap<String, ArrayList<String>> inside a list?

class Student{
    //instance variable or data members.

    Map<Integer, List<Object>> mapp = new HashMap<Integer, List<Object>>();
    Scanner s1 = new Scanner(System.in);
    String name = s1.nextLine();
    int regno ;
    int mark1;
    int mark2;
    int total;
    List<Object> list = new ArrayList<Object>();
    mapp.put(regno,list); //what wrong in this part?
    list.add(mark1);
    list.add(mark2);**
    //String mark2=mapp.get(regno)[2];
}