Programs & Examples On #Texture packing

How to check if an int is a null

An int is not null, it may be 0 if not initialized.

If you want an integer to be able to be null, you need to use Integer instead of int.

Integer id;
String name;

public Integer getId() { return id; }

Besides the statement if(person.equals(null)) can't be true, because if person is null, then a NullPointerException will be thrown. So the correct expression is if (person == null)

How to set thymeleaf th:field value from other variable

You could approach this method.

Instead of using th:field use html id & name. Set value using th:value

<input class="form-control"
           type="text"
           th:value="${client.name}" id="clientName" name="clientName" />

Hope this will help you

Android simple alert dialog

No my friend its very simple, try using this:

AlertDialog alertDialog = new AlertDialog.Builder(AlertDialogActivity.this).create();
alertDialog.setTitle("Alert Dialog");
alertDialog.setMessage("Welcome to dear user.");
alertDialog.setIcon(R.drawable.welcome);

alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "OK", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int which) {
        Toast.makeText(getApplicationContext(), "You clicked on OK", Toast.LENGTH_SHORT).show();
    }
});

alertDialog.show();

This tutorial shows how you can create custom dialog using xml and then show them as an alert dialog.

How to create number input field in Flutter?

You can try this:

TextFormField(
     keyboardType: TextInputType.number,
     decoration: InputDecoration(
              prefixIcon: Text("Enter your number: ")
     ),
     initialValue: "5",
     onSaved: (input) => _value = num.tryParse(input),
),

Fast and simple String encrypt/decrypt in JAVA

Java - encrypt / decrypt user name and password from a configuration file

Code from above link

DESKeySpec keySpec = new DESKeySpec("Your secret Key phrase".getBytes("UTF8"));
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey key = keyFactory.generateSecret(keySpec);
sun.misc.BASE64Encoder base64encoder = new BASE64Encoder();
sun.misc.BASE64Decoder base64decoder = new BASE64Decoder();
.........

// ENCODE plainTextPassword String
byte[] cleartext = plainTextPassword.getBytes("UTF8");      

Cipher cipher = Cipher.getInstance("DES"); // cipher is not thread safe
cipher.init(Cipher.ENCRYPT_MODE, key);
String encryptedPwd = base64encoder.encode(cipher.doFinal(cleartext));
// now you can store it 
......

// DECODE encryptedPwd String
byte[] encrypedPwdBytes = base64decoder.decodeBuffer(encryptedPwd);

Cipher cipher = Cipher.getInstance("DES");// cipher is not thread safe
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] plainTextPwdBytes = (cipher.doFinal(encrypedPwdBytes));

how to set the default value to the drop down list control?

if you know the index of the item of default value,just

lstDepartment.SelectedIndex = 1;//the second item

or if you know the value you want to set, just

lstDepartment.SelectedValue = "the value you want to set";

Node.js: Difference between req.query[] and req.params

req.params contains route parameters (in the path portion of the URL), and req.query contains the URL query parameters (after the ? in the URL).

You can also use req.param(name) to look up a parameter in both places (as well as req.body), but this method is now deprecated.

Appending a vector to a vector

While saying "the compiler can reserve", why rely on it? And what about automatic detection of move semantics? And what about all that repeating of the container name with the begins and ends?

Wouldn't you want something, you know, simpler?

(Scroll down to main for the punchline)

#include <type_traits>
#include <vector>
#include <iterator>
#include <iostream>

template<typename C,typename=void> struct can_reserve: std::false_type {};

template<typename T, typename A>
struct can_reserve<std::vector<T,A>,void>:
    std::true_type
{};

template<int n> struct secret_enum { enum class type {}; };
template<int n>
using SecretEnum = typename secret_enum<n>::type;

template<bool b, int override_num=1>
using EnableFuncIf = typename std::enable_if< b, SecretEnum<override_num> >::type;
template<bool b, int override_num=1>
using DisableFuncIf = EnableFuncIf< !b, -override_num >;

template<typename C, EnableFuncIf< can_reserve<C>::value >... >
void try_reserve( C& c, std::size_t n ) {
  c.reserve(n);
}
template<typename C, DisableFuncIf< can_reserve<C>::value >... >
void try_reserve( C& c, std::size_t ) { } // do nothing

template<typename C,typename=void>
struct has_size_method:std::false_type {};
template<typename C>
struct has_size_method<C, typename std::enable_if<std::is_same<
  decltype( std::declval<C>().size() ),
  decltype( std::declval<C>().size() )
>::value>::type>:std::true_type {};

namespace adl_aux {
  using std::begin; using std::end;
  template<typename C>
  auto adl_begin(C&&c)->decltype( begin(std::forward<C>(c)) );
  template<typename C>
  auto adl_end(C&&c)->decltype( end(std::forward<C>(c)) );
}
template<typename C>
struct iterable_traits {
    typedef decltype( adl_aux::adl_begin(std::declval<C&>()) ) iterator;
    typedef decltype( adl_aux::adl_begin(std::declval<C const&>()) ) const_iterator;
};
template<typename C> using Iterator = typename iterable_traits<C>::iterator;
template<typename C> using ConstIterator = typename iterable_traits<C>::const_iterator;
template<typename I> using IteratorCategory = typename std::iterator_traits<I>::iterator_category;

template<typename C, EnableFuncIf< has_size_method<C>::value, 1>... >
std::size_t size_at_least( C&& c ) {
    return c.size();
}

template<typename C, EnableFuncIf< !has_size_method<C>::value &&
  std::is_base_of< std::random_access_iterator_tag, IteratorCategory<Iterator<C>> >::value, 2>... >
std::size_t size_at_least( C&& c ) {
    using std::begin; using std::end;
  return end(c)-begin(c);
};
template<typename C, EnableFuncIf< !has_size_method<C>::value &&
  !std::is_base_of< std::random_access_iterator_tag, IteratorCategory<Iterator<C>> >::value, 3>... >
std::size_t size_at_least( C&& c ) {
  return 0;
};

template < typename It >
auto try_make_move_iterator(It i, std::true_type)
-> decltype(make_move_iterator(i))
{
    return make_move_iterator(i);
}
template < typename It >
It try_make_move_iterator(It i, ...)
{
    return i;
}


#include <iostream>
template<typename C1, typename C2>
C1&& append_containers( C1&& c1, C2&& c2 )
{
  using std::begin; using std::end;
  try_reserve( c1, size_at_least(c1) + size_at_least(c2) );

  using is_rvref = std::is_rvalue_reference<C2&&>;
  c1.insert( end(c1),
             try_make_move_iterator(begin(c2), is_rvref{}),
             try_make_move_iterator(end(c2), is_rvref{}) );

  return std::forward<C1>(c1);
}

struct append_infix_op {} append;
template<typename LHS>
struct append_on_right_op {
  LHS lhs;
  template<typename RHS>
  LHS&& operator=( RHS&& rhs ) {
    return append_containers( std::forward<LHS>(lhs), std::forward<RHS>(rhs) );
  }
};

template<typename LHS>
append_on_right_op<LHS> operator+( LHS&& lhs, append_infix_op ) {
  return { std::forward<LHS>(lhs) };
}
template<typename LHS,typename RHS>
typename std::remove_reference<LHS>::type operator+( append_on_right_op<LHS>&& lhs, RHS&& rhs ) {
  typename std::decay<LHS>::type retval = std::forward<LHS>(lhs.lhs);
  return append_containers( std::move(retval), std::forward<RHS>(rhs) );
}

template<typename C>
void print_container( C&& c ) {
  for( auto&& x:c )
    std::cout << x << ",";
  std::cout << "\n";
};

int main() {
  std::vector<int> a = {0,1,2};
  std::vector<int> b = {3,4,5};
  print_container(a);
  print_container(b);
  a +append= b;
  const int arr[] = {6,7,8};
  a +append= arr;
  print_container(a);
  print_container(b);
  std::vector<double> d = ( std::vector<double>{-3.14, -2, -1} +append= a );
  print_container(d);
  std::vector<double> c = std::move(d) +append+ a;
  print_container(c);
  print_container(d);
  std::vector<double> e = c +append+ std::move(a);
  print_container(e);
  print_container(a);
}

hehe.

Now with move-data-from-rhs, append-array-to-container, append forward_list-to-container, move-container-from-lhs, thanks to @DyP's help.

Note that the above does not compile in clang thanks to the EnableFunctionIf<>... technique. In clang this workaround works.

Why use String.Format?

One reason it is not preferable to write the string like 'string +"Value"+ string' is because of Localization. In cases where localization is occurring we want the localized string to be correctly formatted, which could be very different from the language being coded in.

For example we need to show the following error in different languages:

MessageBox.Show(String.Format(ErrorManager.GetError("PIDV001").Description, proposalvalue.ProposalSource)

where

'ErrorCollector.GetError("ERR001").ErrorDescription' returns a string like "Your ID {0} is not valid". This message must be localized in many languages. In that case we can't use + in C#. We need to follow string.format.

Pandas: Setting no. of max rows

Personally, I like setting the options directly with an assignment statement as it is easy to find via tab completion thanks to iPython. I find it hard to remember what the exact option names are, so this method works for me.

For instance, all I have to remember is that it begins with pd.options

pd.options.<TAB>

enter image description here

Most of the options are available under display

pd.options.display.<TAB>

enter image description here

From here, I usually output what the current value is like this:

pd.options.display.max_rows
60

I then set it to what I want it to be:

pd.options.display.max_rows = 100

Also, you should be aware of the context manager for options, which temporarily sets the options inside of a block of code. Pass in the option name as a string followed by the value you want it to be. You may pass in any number of options in the same line:

with pd.option_context('display.max_rows', 100, 'display.max_columns', 10):
    some pandas stuff

You can also reset an option back to its default value like this:

pd.reset_option('display.max_rows')

And reset all of them back:

pd.reset_option('all')

It is still perfectly good to set options via pd.set_option. I just find using the attributes directly is easier and there is less need for get_option and set_option.

Detect if an element is visible with jQuery

if($('#testElement').is(':visible')){
    //what you want to do when is visible
}

How to get PID of process I've just started within java program?

I believe the only portable way to do this, is to run a (child) process through another (parent) Java process, which will inform me the actual PID of the parent process. The child process could be anything.

The code of this wrapper is

package com.panayotis.wrapper;

import java.io.File;
import java.io.IOException;
import java.lang.management.ManagementFactory;

public class Main {
    public static void main(String[] args) throws IOException, InterruptedException {
        System.out.println(ManagementFactory.getRuntimeMXBean().getName().split("@")[0]);
        ProcessBuilder pb = new ProcessBuilder(args);
        pb.directory(new File(System.getProperty("user.dir")));
        pb.redirectInput(ProcessBuilder.Redirect.INHERIT);
        pb.redirectOutput(ProcessBuilder.Redirect.INHERIT);
        pb.redirectError(ProcessBuilder.Redirect.INHERIT);
        pb.start().waitFor();
    }
}

To use it, create a jar file with just this one, and call it with command arguments this:

String java = System.getProperty("java.home") + separator + "bin" + separator + "java.exe";
String jar_wrapper = "path\\of\\wrapper.jar";

String[] args = new String[]{java, "-cp", jar_wrapper, "com.panayotis.wrapper.Main", actual_exec_args...);

How to get name of the computer in VBA?

You can do like this:

Sub Get_Environmental_Variable()

Dim sHostName As String
Dim sUserName As String

' Get Host Name / Get Computer Name    
sHostName = Environ$("computername")

' Get Current User Name    
sUserName = Environ$("username")

End Sub

What does double question mark (??) operator mean in PHP

It's the "null coalescing operator", added in php 7.0. The definition of how it works is:

It returns its first operand if it exists and is not NULL; otherwise it returns its second operand.

So it's actually just isset() in a handy operator.

Those two are equivalent1:

$foo = $bar ?? 'something';
$foo = isset($bar) ? $bar : 'something';

Documentation: http://php.net/manual/en/language.operators.comparison.php#language.operators.comparison.coalesce

In the list of new PHP7 features: http://php.net/manual/en/migration70.new-features.php#migration70.new-features.null-coalesce-op

And original RFC https://wiki.php.net/rfc/isset_ternary


EDIT: As this answer gets a lot of views, little clarification:

1There is a difference: In case of ??, the first expression is evaluated only once, as opposed to ? :, where the expression is first evaluated in the condition section, then the second time in the "answer" section.

equivalent to push() or pop() for arrays?

You can use Arrays.copyOf() with a little reflection to make a nice helper function.

public class ArrayHelper {
    public static <T> T[] push(T[] arr, T item) {
        T[] tmp = Arrays.copyOf(arr, arr.length + 1);
        tmp[tmp.length - 1] = item;
        return tmp;
    }

    public static <T> T[] pop(T[] arr) {
        T[] tmp = Arrays.copyOf(arr, arr.length - 1);
        return tmp;
    }
}

Usage:

String[] items = new String[]{"a", "b", "c"};

items = ArrayHelper.push(items, "d");
items = ArrayHelper.push(items, "e");

items = ArrayHelper.pop(items);

Results

Original: a,b,c

Array after push calls: a,b,c,d,e

Array after pop call: a,b,c,d

Watching variables in SSIS during debug

Drag the variable from Variables pane to Watch pane and voila!

How can I get the corresponding table header (th) from a table cell (td)?

Pure JavaScript's solution:

var index = Array.prototype.indexOf.call(your_td.parentNode.children, your_td)
var corresponding_th = document.querySelector('#your_table_id th:nth-child(' + (index+1) + ')')

Arrays with different datatypes i.e. strings and integers. (Objectorientend)

Notice the repetition of Book in Booknumber (int), Booktitle (string), Booklanguage (string), Bookprice (int)- it screams for a class type.

class Book {
  int number;
  String title;
  String language;
  int price;
}

Now you can simply have:

Book[] books = new Books[3];

If you want arrays, you can declare it as object array an insert Integer and String into it:

Object books[3][4]

Iterating through a List Object in JSP

 <c:forEach items="${sessionScope.empL}" var="emp">
            <tr>
                <td>Employee ID: <c:out value="${emp.eid}"/></td>
                <td>Employee Pass: <c:out value="${emp.ename}"/></td>  
            </tr>
        </c:forEach>

subsampling every nth entry in a numpy array

You can use numpy's slicing, simply start:stop:step.

>>> xs
array([1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4])
>>> xs[1::4]
array([2, 2, 2])

This creates a view of the the original data, so it's constant time. It'll also reflect changes to the original array and keep the whole original array in memory:

>>> a
array([1, 2, 3, 4, 5])
>>> b = a[::2]         # O(1), constant time
>>> b[:] = 0           # modifying the view changes original array
>>> a                  # original array is modified
array([0, 2, 0, 4, 0])

so if either of the above things are a problem, you can make a copy explicitly:

>>> a
array([1, 2, 3, 4, 5])
>>> b = a[::2].copy()  # explicit copy, O(n)
>>> b[:] = 0           # modifying the copy
>>> a                  # original is intact
array([1, 2, 3, 4, 5])

This isn't constant time, but the result isn't tied to the original array. The copy also contiguous in memory, which can make some operations on it faster.

Including external jar-files in a new jar-file build with Ant

This is a classpath issue when running an executable jar as follows:

java -jar myfile.jar

One way to fix the problem is to set the classpath on the java command line as follows, adding the missing log4j jar:

java -cp myfile.jar:log4j.jar:otherjar.jar com.abc.xyz.MyMainClass

Of course the best solution is to add the classpath into the jar manifest so that the we can use the "-jar" java option:

<jar jarfile="myfile.jar">
    ..
    ..
    <manifest>
       <attribute name="Main-Class" value="com.abc.xyz.MyMainClass"/>
       <attribute name="Class-Path" value="log4j.jar otherjar.jar"/>
    </manifest>
</jar>

The following answer demonstrates how you can use the manifestclasspath to automate the seeting of the classpath manifest entry

Cannot find Main Class in File Compiled With Ant

Center align a column in twitter bootstrap

I tried the approaches given above, but these methods fail when dynamically the height of the content in one of the cols increases, it basically pushes the other cols down.

for me the basic table layout solution worked.

// Apply this to the enclosing row
.row-centered {
  text-align: center;
  display: table-row;
}
// Apply this to the cols within the row
.col-centered {
  display: table-cell;
  float: none;
  vertical-align: top;
}

How can I pad an int with leading zeros when using cout << operator?

In C++20 you'll be able to do:

std::cout << std::format("{:03}", 25); // prints 025

In the meantime you can use the {fmt} library, std::format is based on.

Disclaimer: I'm the author of {fmt} and C++20 std::format.

How is Docker different from a virtual machine?

There are a lot of nice technical answers here that clearly discuss the differences between VMs and containers as well as the origins of Docker.

For me the fundamental difference between VMs and Docker is how you manage the promotion of your application.

With VMs you promote your application and its dependencies from one VM to the next DEV to UAT to PRD.

  1. Often these VM's will have different patches and libraries.
  2. It is not uncommon for multiple applications to share a VM. This requires managing configuration and dependencies for all the applications.
  3. Backout requires undoing changes in the VM. Or restoring it if possible.

With Docker the idea is that you bundle up your application inside its own container along with the libraries it needs and then promote the whole container as a single unit.

  1. Except for the kernel the patches and libraries are identical.
  2. As a general rule there is only one application per container which simplifies configuration.
  3. Backout consists of stopping and deleting the container.

So at the most fundamental level with VMs you promote the application and its dependencies as discrete components whereas with Docker you promote everything in one hit.

And yes there are issues with containers including managing them although tools like Kubernetes or Docker Swarm greatly simplify the task.

Understanding Fragment's setRetainInstance(boolean)

SetRetainInstance(true) allows the fragment sort of survive. Its members will be retained during configuration change like rotation. But it still may be killed when the activity is killed in the background. If the containing activity in the background is killed by the system, it's instanceState should be saved by the system you handled onSaveInstanceState properly. In another word the onSaveInstanceState will always be called. Though onCreateView won't be called if SetRetainInstance is true and fragment/activity is not killed yet, it still will be called if it's killed and being tried to be brought back.

Here are some analysis of the android activity/fragment hope it helps. http://ideaventure.blogspot.com.au/2014/01/android-activityfragment-life-cycle.html

CMake does not find Visual C++ compiler

Those stumbling with this on Visual Studio 2017: there is a feature related to CMake that needs to be selected and installed together with the relevant compiler toolsets. See the screenshot below.

Visaul C++ tools for CMake must be installed

Is Python faster and lighter than C++?

All the slowest (>100x) usages of Python on the shootout are scientific operations that require high GFlop/s count. You should NOT use python for those anyways. The correct way to use python is to import a module that does those calculations, and then go have a relaxing afternoon with your family. That is the pythonic way :)

Copy a file in a sane, safe and efficient way

Copy a file in a sane way:

#include <fstream>

int main()
{
    std::ifstream  src("from.ogv", std::ios::binary);
    std::ofstream  dst("to.ogv",   std::ios::binary);

    dst << src.rdbuf();
}

This is so simple and intuitive to read it is worth the extra cost. If we were doing it a lot, better to fall back on OS calls to the file system. I am sure boost has a copy file method in its filesystem class.

There is a C method for interacting with the file system:

#include <copyfile.h>

int
copyfile(const char *from, const char *to, copyfile_state_t state, copyfile_flags_t flags);

How do I (or can I) SELECT DISTINCT on multiple columns?

I want to select the distinct values from one column 'GrondOfLucht' but they should be sorted in the order as given in the column 'sortering'. I cannot get the distinct values of just one column using

Select distinct GrondOfLucht,sortering
from CorWijzeVanAanleg
order by sortering

It will also give the column 'sortering' and because 'GrondOfLucht' AND 'sortering' is not unique, the result will be ALL rows.

use the GROUP to select the records of 'GrondOfLucht' in the order given by 'sortering

SELECT        GrondOfLucht
FROM            dbo.CorWijzeVanAanleg
GROUP BY GrondOfLucht, sortering
ORDER BY MIN(sortering)

Converting a PDF to PNG

My solution is much simpler and more direct. At least it works that way on my PC (with the following specs):

me@home: my.folder$ uname -a
Linux home 3.2.0-54-generic-pae #82-Ubuntu SMP Tue Sep 10 20:29:22 UTC 2013 i686 i686 i386 GNU/Linux

with

me@home: my.folder$ convert --version
Version: ImageMagick 6.6.9-7 2012-08-17 Q16 http://www.imagemagick.org
Copyright: Copyright (C) 1999-2011 ImageMagick Studio LLC
Features: OpenMP

So, here's what I run on my file.pdf:

me@home: my.folder$ convert -density 300 -quality 100 file.pdf file.png

Convert String to Carbon

Why not try using the following:

$dateTimeString = $aDateString." ".$aTimeString;
$dueDateTime = Carbon::createFromFormat('Y-m-d H:i:s', $dateTimeString, 'Europe/London');   

Print to the same line and not a new line?

In Python 3.3+ you don’t need sys.stdout.flush(). print(string, end='', flush=True) works.

So

print('foo', end='')
print('\rbar', end='', flush=True)

will overwrite ‘foo’ with ‘bar’.

How to create a new figure in MATLAB?

figure;
plot(something);

or

figure(2);
plot(something);
...
figure(3);
plot(something else);
...

etc.

How can I rename a project folder from within Visual Studio?

Go to the .sln file, right click, open with Notepad++ (or any editor; Notepad++ is the fastest), find the path, change it.

How to generate unique IDs for form labels in React?

For the usual usages of label and input, it's just easier to wrap input into a label like this:

import React from 'react'

const Field = props => (
  <label>
    <span>{props.label}</span>
    <input type="text"/>
  </label>
)      

It's also makes it possible in checkboxes/radiobuttons to apply padding to root element and still getting feedback of click on input.

java.sql.SQLException: Incorrect string value: '\xF0\x9F\x91\xBD\xF0\x9F...'

I faced the same issue and solved it by setting the Collation to utf8_general_ci for each column.

Java, looping through result set

List<String> sids = new ArrayList<String>();
List<String> lids = new ArrayList<String>();

String query = "SELECT rlink_id, COUNT(*)"
             + "FROM dbo.Locate  "
             + "GROUP BY rlink_id ";

Statement stmt = yourconnection.createStatement();
try {
    ResultSet rs4 = stmt.executeQuery(query);

    while (rs4.next()) {
        sids.add(rs4.getString(1));
        lids.add(rs4.getString(2));
    }
} finally {
    stmt.close();
}

String show[] = sids.toArray(sids.size());
String actuate[] = lids.toArray(lids.size());

How to get a jqGrid selected row cells value

First you can get the rowid of the selected row with respect of getGridParam method and 'selrow' as the parameter and then you can use getCell to get the cell value from the corresponding column:

var myGrid = $('#list'),
    selRowId = myGrid.jqGrid ('getGridParam', 'selrow'),
    celValue = myGrid.jqGrid ('getCell', selRowId, 'columnName');

The 'columnName' should be the same name which you use in the 'name' property of the colModel. If you need values from many column of the selected row you can use getRowData instead of getCell.

Text-decoration: none not working

Add a specific class for all the links :

html :

<a class="class1 class2 noDecoration"> text </a>

in css :

.noDecoration {
  text-decoration: none;
}

How do I POST JSON data with cURL?

For Windows, having a single quote for the -d value did not work for me, but it did work after changing to double quote. Also I needed to escape double quotes inside curly brackets.

That is, the following did not work:

curl -i -X POST -H "Content-Type: application/json" -d '{"key":"val"}' http://localhost:8080/appname/path

But the following worked:

curl -i -X POST -H "Content-Type: application/json" -d "{\"key\":\"val\"}" http://localhost:8080/appname/path

Understanding CUDA grid dimensions, block dimensions and threads organization (simple explanation)

Hardware

If a GPU device has, for example, 4 multiprocessing units, and they can run 768 threads each: then at a given moment no more than 4*768 threads will be really running in parallel (if you planned more threads, they will be waiting their turn).

Software

threads are organized in blocks. A block is executed by a multiprocessing unit. The threads of a block can be indentified (indexed) using 1Dimension(x), 2Dimensions (x,y) or 3Dim indexes (x,y,z) but in any case xyz <= 768 for our example (other restrictions apply to x,y,z, see the guide and your device capability).

Obviously, if you need more than those 4*768 threads you need more than 4 blocks. Blocks may be also indexed 1D, 2D or 3D. There is a queue of blocks waiting to enter the GPU (because, in our example, the GPU has 4 multiprocessors and only 4 blocks are being executed simultaneously).

Now a simple case: processing a 512x512 image

Suppose we want one thread to process one pixel (i,j).

We can use blocks of 64 threads each. Then we need 512*512/64 = 4096 blocks (so to have 512x512 threads = 4096*64)

It's common to organize (to make indexing the image easier) the threads in 2D blocks having blockDim = 8 x 8 (the 64 threads per block). I prefer to call it threadsPerBlock.

dim3 threadsPerBlock(8, 8);  // 64 threads

and 2D gridDim = 64 x 64 blocks (the 4096 blocks needed). I prefer to call it numBlocks.

dim3 numBlocks(imageWidth/threadsPerBlock.x,  /* for instance 512/8 = 64*/
              imageHeight/threadsPerBlock.y); 

The kernel is launched like this:

myKernel <<<numBlocks,threadsPerBlock>>>( /* params for the kernel function */ );       

Finally: there will be something like "a queue of 4096 blocks", where a block is waiting to be assigned one of the multiprocessors of the GPU to get its 64 threads executed.

In the kernel the pixel (i,j) to be processed by a thread is calculated this way:

uint i = (blockIdx.x * blockDim.x) + threadIdx.x;
uint j = (blockIdx.y * blockDim.y) + threadIdx.y;

AngularJS - get element attributes values

You just can use doStuff($event) in your markup and get the data-attribute values via currentTarget.getAttribute("data-id")) in angular. HTML:

<div ng-controller="TestCtrl">
    <button data-id="345" ng-click="doStuff($event)">Button</button>
</div>

JS:

var app = angular.module("app", []);
app.controller("TestCtrl", function ($scope) {
    $scope.doStuff = function (item) {
        console.log(item.currentTarget);
        console.log(item.currentTarget.getAttribute("data-id"));
    };
});

Forked your initial jsfiddle: http://jsfiddle.net/9mmd1zht/116/

How to kill all active and inactive oracle sessions for user

BEGIN
  FOR r IN (select sid,serial# from v$session where username='user')
  LOOP
      EXECUTE IMMEDIATE 'alter system kill session ''' || r.sid  || ',' 
        || r.serial# || ''' immediate';
  END LOOP;
END;

This should work - I just changed your script to add the immediate keyword. As the previous answers pointed out, the kill session only marks the sessions for killing; it does not do so immediately but later when convenient.

From your question, it seemed you are expecting to see the result immediately. So immediate keyword is used to force this.

Resolve Javascript Promise outside function scope

I wrote a small lib for this. https://www.npmjs.com/package/@inf3rno/promise.exposed

I used the factory method approach others wrote, but I overrode the then, catch, finally methods too, so you can resolve the original promise by those as well.

Resolving Promise without executor from outside:

const promise = Promise.exposed().then(console.log);
promise.resolve("This should show up in the console.");

Racing with the executor's setTimeout from outside:

const promise = Promise.exposed(function (resolve, reject){
    setTimeout(function (){
        resolve("I almost fell asleep.")
    }, 100000);
}).then(console.log);

setTimeout(function (){
    promise.resolve("I don't want to wait that much.");
}, 100);

There is a no-conflict mode if you don't want to pollute the global namespace:

const createExposedPromise = require("@inf3rno/promise.exposed/noConflict");
const promise = createExposedPromise().then(console.log);
promise.resolve("This should show up in the console.");

Django CSRF check failing with an Ajax POST request

I have a solution. in my JS I have two functions. First to get Cookies (ie. csrftoken):

function getCookie(name) {
let cookieValue = null;
if (document.cookie && document.cookie !== '') {
    const cookies = document.cookie.split(';');
    for (let i = 0; i < cookies.length; i++) {
        const cookie = cookies[i].trim();
        // Does this cookie string begin with the name we want?
        if (cookie.substring(0, name.length + 1) === (name + '=')) {
            cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
            break;
        }
    }
}
return cookieValue;

}

Second one is my ajax function. in this case it's for login and in fact doesn't return any thing, just pass values to set a session:

function LoginAjax() {


    //get scrftoken:
    const csrftoken = getCookie('csrftoken');

    var req = new XMLHttpRequest();
    var userName = document.getElementById("Login-Username");
    var password = document.getElementById("Login-Password");

    req.onreadystatechange = function () {
        if (this.readyState == 4 && this.status == 200) {            
            //read response loggedIn JSON show me if user logged in or not
            var respond = JSON.parse(this.responseText);            
            alert(respond.loggedIn);

        }
    }

    req.open("POST", "login", true);

    //following header set scrftoken to resolve problem
    req.setRequestHeader('X-CSRFToken', csrftoken);

    req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    req.send("UserName=" + userName.value + "&Password=" + password.value);
}

HTML Input="file" Accept Attribute File Type (CSV)

Well this is embarrassing... I found the solution I was looking for and it couldn't be simpler. I used the following code to get the desired result. Hope this helps someone in the future. Thanks everyone for your help.

<input id="fileSelect" type="file" accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel" />  

Valid Accept Types:

For CSV files (.csv), use:

<input type="file" accept=".csv" />

For Excel Files 97-2003 (.xls), use:

<input type="file" accept="application/vnd.ms-excel" />

For Excel Files 2007+ (.xlsx), use:

<input type="file" accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" />

For Text Files (.txt) use:

<input type="file" accept="text/plain" />

For Image Files (.png/.jpg/etc), use:

<input type="file" accept="image/*" />

For HTML Files (.htm,.html), use:

<input type="file" accept="text/html" />

For Video Files (.avi, .mpg, .mpeg, .mp4), use:

<input type="file" accept="video/*" />

For Audio Files (.mp3, .wav, etc), use:

<input type="file" accept="audio/*" />

For PDF Files, use:

<input type="file" accept=".pdf" /> 

DEMO:
http://jsfiddle.net/dirtyd77/LzLcZ/144/


NOTE:

If you are trying to display Excel CSV files (.csv), do NOT use:

  • text/csv
  • application/csv
  • text/comma-separated-values (works in Opera only).

If you are trying to display a particular file type (for example, a WAV or PDF), then this will almost always work...

 <input type="file" accept=".FILETYPE" />

Convert InputStream to BufferedReader

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

How can I String.Format a TimeSpan object with a custom format in .NET?

The Substring method works perfectly when you only want the Hours:Minutes:Seconds. It's simple, clean code and easy to understand.

    var yourTimeSpan = DateTime.Now - DateTime.Now.AddMinutes(-2);

    var formatted = yourTimeSpan.ToString().Substring(0,8);// 00:00:00 

    Console.WriteLine(formatted);

Inserting values to SQLite table in Android

public class TestingData extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    SQLiteDatabase db;
    db = openOrCreateDatabase(
        "TestingData.db"
        , SQLiteDatabase.CREATE_IF_NECESSARY
        , null
        );
 }

}

then see this link link

Could not load file or assembly 'log4net, Version=1.2.10.0, Culture=neutral, PublicKeyToken=692fbea5521e1304'

For this specific error, I installed version 20 of Crystal Report and it solved my problem: https://www.tektutorialshub.com/crystal-reports/crystal-reports-download-for-visual-studio/#Service-Pack-16

You can also download the file alone using the following link https://www.nuget.org/api/v2/package/log4net/1.2.10 rename the file to .zip and extract it.

How to write hello world in assembler under Windows?

Unless you call some function this is not at all trivial. (And, seriously, there's no real difference in complexity between calling printf and calling a win32 api function.)

Even DOS int 21h is really just a function call, even if its a different API.

If you want to do it without help you need to talk to your video hardware directly, likely writing bitmaps of the letters of "Hello world" into a framebuffer. Even then the video card is doing the work of translating those memory values into DisplayPort/HDMI/DVI/VGA signals.

Note that, really, none of this stuff all the way down to the hardware is any more interesting in ASM than in C. A "hello world" program boils down to a function call. One nice thing about ASM is that you can use any ABI you want fairly easily; you just need to know what that ABI is.

Getting one value from a tuple

You can write

i = 5 + tup()[0]

Tuples can be indexed just like lists.

The main difference between tuples and lists is that tuples are immutable - you can't set the elements of a tuple to different values, or add or remove elements like you can from a list. But other than that, in most situations, they work pretty much the same.

jQuery: get the file name selected from <input type="file" />

The simplest way is to simply use the following line of jquery, using this you don't get the /fakepath nonsense, you straight up get the file that was uploaded:

$('input[type=file]')[0].files[0]; // This gets the file
$('#idOfFileUpload')[0].files[0]; // This gets the file with the specified id

Some other useful commands are:

To get the name of the file:

$('input[type=file]')[0].files[0].name; // This gets the file name

To get the type of the file:

If I were to upload a PNG, it would return image/png

$("#imgUpload")[0].files[0].type

To get the size (in bytes) of the file:

$("#imgUpload")[0].files[0].size

Also you don't have to use these commands on('change', you can get the values at any time, for instance you may have a file upload and when the user clicks upload, you simply use the commands I listed.

Find something in column A then show the value of B for that row in Excel 2010

Assuming

source data range is A1:B100.
query cell is D1 (here you will input Police or Fire).
result cell is E1

Formula in E1 = VLOOKUP(D1, A1:B100, 2, FALSE)

How to check if a variable is an integer in JavaScript?

The 'accepted' answer is wrong (as some comments below point out). this modification can make it work:

if (data.toString() === parseInt(data, 10).toString())
    alert("data is a valid integer")
else
    alert("data is not a valid integer")

Check if checkbox is checked with jQuery

Actually, according to jsperf.com, The DOM operations are fastest, then $().prop() followed by $().is()!!

Here are the syntaxes :

var checkbox = $('#'+id);
/* OR var checkbox = $("input[name=checkbox1]"); whichever is best */

/* The DOM way - The fastest */
if(checkbox[0].checked == true)
   alert('Checkbox is checked!!');

/* Using jQuery .prop() - The second fastest */
if(checkbox.prop('checked') == true)
   alert('Checkbox is checked!!');

/* Using jQuery .is() - The slowest in the lot */
if(checkbox.is(':checked') == true)
   alert('Checkbox is checked!!');

I personally prefer .prop(). Unlike .is(), It can also be used to set the value.

urllib and "SSL: CERTIFICATE_VERIFY_FAILED" Error

ln -s /usr/local/share/certs/ca-root-nss.crt /etc/ssl/cert.pem

(FreeBSD 10.1)

How to get the current taxonomy term ID (not the slug) in WordPress?

Just copy paste below code!

This will print your current taxonomy name and description(optional)

<?php 
   $tax = $wp_query->get_queried_object();
   echo ''. $tax->name . '';
   echo "<br>";
   echo ''. $tax->description .''; 
?>

Python - difference between two strings

What you are asking for is a specialized form of compression. xdelta3 was designed for this particular kind of compression, and there's a python binding for it, but you could probably get away with using zlib directly. You'd want to use zlib.compressobj and zlib.decompressobj with the zdict parameter set to your "base word", e.g. afrykanerskojezyczny.

Caveats are zdict is only supported in python 3.3 and higher, and it's easiest to code if you have the same "base word" for all your diffs, which may or may not be what you want.

How can I enable the MySQLi extension in PHP 7?

Let's use

mysqli_connect

instead of

mysql_connect

because mysql_connect isn't supported in PHP 7.

Printing to the console in Google Apps Script?

In a google script project you can create html files (example: index.html) or gs files (example:code.gs). The .gs files are executed on the server and you can use Logger.log as @Peter Herrman describes. However if the function is created in a .html file it is being executed on the user's browser and you can use console.log. The Chrome browser console can be viewed by Ctrl Shift J on Windows/Linux or Cmd Opt J on Mac

If you want to use Logger.log on an html file you can use a scriptlet to call the Logger.log function from the html file. To do so you would insert <? Logger.log(something) ?> replacing something with whatever you want to log. Standard scriptlets, which use the syntax <? ... ?>, execute code without explicitly outputting content to the page.

How to extract HTTP response body from a Python requests call?

Your code is correct. I tested:

r = requests.get("http://www.google.com")
print(r.content)

And it returned plenty of content. Check the url, try "http://www.google.com". Cheers!

Downloading a Google font and setting up an offline site that uses it

The other answers are not wrong, but I found this to be the fastest way.

  1. Download the zip file from Google fonts and unzip it.
  2. Upload the font files 3 at a time to http://www.fontsquirrel.com/tools/webfont-generator
  3. Download the results.

Results contain all font formats: woff, svg, ttf, eot.

AND as an added bonus they generate the css file for you too!

Outputting data from unit test in Python

We use the logging module for this.

For example:

import logging
class SomeTest( unittest.TestCase ):
    def testSomething( self ):
        log= logging.getLogger( "SomeTest.testSomething" )
        log.debug( "this= %r", self.this )
        log.debug( "that= %r", self.that )
        # etc.
        self.assertEquals( 3.14, pi )

if __name__ == "__main__":
    logging.basicConfig( stream=sys.stderr )
    logging.getLogger( "SomeTest.testSomething" ).setLevel( logging.DEBUG )
    unittest.main()

That allows us to turn on debugging for specific tests which we know are failing and for which we want additional debugging information.

My preferred method, however, isn't to spend a lot of time on debugging, but spend it writing more fine-grained tests to expose the problem.

Make install, but not to default directories?

make DESTDIR=./new/customized/path install

This quick command worked for me for opencv release 3.2.0 installation on Ubuntu 16. DESTDIR path can be relative as well as absolute.

Such redirection can also be useful in case user does not have admin privileges as long as DESTDIR location has right access for the user. e.g /home//

Android - R cannot be resolved to a variable

check your R directory ...sometimes if a file name is not all lower case and has special characters you can get this error. Im using eclipse and it only accepts file names a-z0-9_.

Datagridview full row selection but get single cell value

You can do like this:

private void datagridview1_SelectionChanged(object sender, EventArgs e)
{
  if (datagridview1.SelectedCells.Count > 0)
  {
    int selectedrowindex = datagridview1.SelectedCells[0].RowIndex;
    DataGridViewRow selectedRow = datagridview1.Rows[selectedrowindex];  
    string cellValue = Convert.ToString(selectedRow.Cells["enter column name"].Value);           
  }
}

Writing unit tests in Python: How do I start?

If you're brand new to using unittests, the simplest approach to learn is often the best. On that basis along I recommend using py.test rather than the default unittest module.

Consider these two examples, which do the same thing:

Example 1 (unittest):

import unittest

class LearningCase(unittest.TestCase):
    def test_starting_out(self):
        self.assertEqual(1, 1)

def main():
    unittest.main()

if __name__ == "__main__":
    main()

Example 2 (pytest):

def test_starting_out():
    assert 1 == 1

Assuming that both files are named test_unittesting.py, how do we run the tests?

Example 1 (unittest):

cd /path/to/dir/
python test_unittesting.py

Example 2 (pytest):

cd /path/to/dir/
py.test

Extracting specific columns in numpy array

One more thing you should pay attention to when selecting columns from N-D array using a list like this:

data[:,:,[1,9]]

If you are removing a dimension (by selecting only one row, for example), the resulting array will be (for some reason) permuted. So:

print data.shape            # gives [10,20,30]
selection = data[1,:,[1,9]]
print selection.shape       # gives [2,20] instead of [20,2]!!

What is AndroidX?

Android provides a couple of different library sets. One is called the Android support Library, and the other is called AndroidX. Selecting "Use android.* artifacts" indicates that we want to use AndroidX.

How do I line up 3 divs on the same row?

See my code

_x000D_
_x000D_
.float-left {_x000D_
    float:left;_x000D_
    width:300px; // or 33% for equal width independent of parent width_x000D_
}
_x000D_
<div>_x000D_
    <h2 align="center">San Andreas: Multiplayer</h2>_x000D_
    <div align="center" class="float-left">CONTENT OF COLUMN ONE GOES HERE</div>_x000D_
    <div align="center" class="float-left">CONTENT OF COLUMN TWO GOES HERE</div>_x000D_
    <div align="center" class="float-left">CONTENT OF COLUMN THREE GOES HERE</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Counting the number of True Booleans in a Python List

I prefer len([b for b in boollist if b is True]) (or the generator-expression equivalent), as it's quite self-explanatory. Less 'magical' than the answer proposed by Ignacio Vazquez-Abrams.

Alternatively, you can do this, which still assumes that bool is convertable to int, but makes no assumptions about the value of True: ntrue = sum(boollist) / int(True)

Compute elapsed time

Hope this will help:

<!doctype html public "-//w3c//dtd html 3.2//en">
<html>
    <head>
        <title>compute elapsed time in JavaScript</title>

        <script type="text/javascript">

            function display_c (start) {
                window.start = parseFloat(start);
                var end = 0 // change this to stop the counter at a higher value
                var refresh = 1000; // Refresh rate in milli seconds
                if( window.start >= end ) {
                    mytime = setTimeout( 'display_ct()',refresh )
                } else {
                    alert("Time Over ");
                }
            }

            function display_ct () {
                // Calculate the number of days left
                var days = Math.floor(window.start / 86400);
                // After deducting the days calculate the number of hours left
                var hours = Math.floor((window.start - (days * 86400 ))/3600)
                // After days and hours , how many minutes are left
                var minutes = Math.floor((window.start - (days * 86400 ) - (hours *3600 ))/60)
                // Finally how many seconds left after removing days, hours and minutes.
                var secs = Math.floor((window.start - (days * 86400 ) - (hours *3600 ) - (minutes*60)))

                var x = window.start + "(" + days + " Days " + hours + " Hours " + minutes + " Minutes and " + secs + " Secondes " + ")";

                document.getElementById('ct').innerHTML = x;
                window.start = window.start - 1;

                tt = display_c(window.start);
            }

            function stop() {
                clearTimeout(mytime);
            }

        </script>

    </head>

    <body>

        <input type="button" value="Start Timer" onclick="display_c(86501);"/> | <input type="button" value="End Timer" onclick="stop();"/>
        <span id='ct' style="background-color: #FFFF00"></span>

    </body>
</html>

Check last modified date of file in C#

Just use File.GetLastWriteTime. There's a sample on that page showing how to use it.

How to check for null/empty/whitespace values with a single test?

As in Oracle you can use NVL function in MySQL you can use IFNULL(columnaName, newValue) to achieve your desired result as in this example

SELECT column_name from table_name WHERE IFNULL(column_name,'') NOT LIKE '%_%';

How do I remove quotes from a string?

str_replace('"', "", $string);
str_replace("'", "", $string);

I assume you mean quotation marks?

Otherwise, go for some regex, this will work for html quotes for example:

preg_replace("/<!--.*?-->/", "", $string);

C-style quotes:

preg_replace("/\/\/.*?\n/", "\n", $string);

CSS-style quotes:

preg_replace("/\/*.*?\*\//", "", $string);

bash-style quotes:

preg-replace("/#.*?\n/", "\n", $string);

Etc etc...

Parameter "stratify" from method "train_test_split" (scikit Learn)

This stratify parameter makes a split so that the proportion of values in the sample produced will be the same as the proportion of values provided to parameter stratify.

For example, if variable y is a binary categorical variable with values 0 and 1 and there are 25% of zeros and 75% of ones, stratify=y will make sure that your random split has 25% of 0's and 75% of 1's.

How can I get current date in Android?

You can use the SimpleDateFormat class for formatting date in your desired format.

Just check this link where you get an idea for your example.

For example:

String dateStr = "04/05/2010"; 
 
SimpleDateFormat curFormater = new SimpleDateFormat("dd/MM/yyyy"); 
Date dateObj = curFormater.parse(dateStr); 
SimpleDateFormat postFormater = new SimpleDateFormat("MMMM dd, yyyy"); 
 
String newDateStr = postFormater.format(dateObj); 

Update:

The detailed example is here, I would suggest you go through this example and understand the concept of SimpleDateFormat class.

Final Solution:

Date c = Calendar.getInstance().getTime();
System.out.println("Current time => " + c);

SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yyyy", Locale.getDefault());
String formattedDate = df.format(c);

Delete all data rows from an Excel table (apart from the first)

I suggest first clearcontents, then resize Table:

Sub DeleteTableRows(ByRef Table As ListObject)

     Dim R               As Range

On Error Resume Next

    Table.DataBodyRange.ClearContents
    Set R = Table.Range.Rows(1).Resize(2)
    Table.Resize R

On Error GoTo 0

End Sub

SQL (MySQL) vs NoSQL (CouchDB)

Here's a quote from a recent blog post from Dare Obasanjo.

SQL databases are like automatic transmission and NoSQL databases are like manual transmission. Once you switch to NoSQL, you become responsible for a lot of work that the system takes care of automatically in a relational database system. Similar to what happens when you pick manual over automatic transmission. Secondly, NoSQL allows you to eke more performance out of the system by eliminating a lot of integrity checks done by relational databases from the database tier. Again, this is similar to how you can get more performance out of your car by driving a manual transmission versus an automatic transmission vehicle.

However the most notable similarity is that just like most of us can’t really take advantage of the benefits of a manual transmission vehicle because the majority of our driving is sitting in traffic on the way to and from work, there is a similar harsh reality in that most sites aren’t at Google or Facebook’s scale and thus have no need for a Bigtable or Cassandra.

To which I can add only that switching from MySQL, where you have at least some experience, to CouchDB, where you have no experience, means you will have to deal with a whole new set of problems and learn different concepts and best practices. While by itself this is wonderful (I am playing at home with MongoDB and like it a lot), it will be a cost that you need to calculate when estimating the work for that project, and brings unknown risks while promising unknown benefits. It will be very hard to judge if you can do the project on time and with the quality you want/need to be successful, if it's based on a technology you don't know.

Now, if you have on the team an expert in the NoSQL field, then by all means take a good look at it. But without any expertise on the team, don't jump on NoSQL for a new commercial project.

Update: Just to throw some gasoline in the open fire you started, here are two interesting articles from people on the SQL camp. :-)

I Can't Wait for NoSQL to Die (original article is gone, here's a copy)
Fighting The NoSQL Mindset, Though This Isn't an anti-NoSQL Piece
Update: Well here is an interesting article about NoSQL
Making Sense of NoSQL

Check if a PHP cookie exists and if not set its value

Answer

You can't according to the PHP manual:

Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE or $HTTP_COOKIE_VARS arrays.

This is because cookies are sent in response headers to the browser and the browser must then send them back with the next request. This is why they are only available on the second page load.

Work around

But you can work around it by also setting $_COOKIE when you call setcookie():

if(!isset($_COOKIE['lg'])) {
    setcookie('lg', 'ro');
    $_COOKIE['lg'] = 'ro';
}
echo $_COOKIE['lg'];

What is the volatile keyword useful for?

Volatile does following.

1> Read and write of volatile variables by different threads are always from memory, not from thread's own cache or cpu register. So each thread always deals with the latest value. 2> When 2 different threads work with same instance or static variables in heap, one may see other's actions as out of order. See jeremy manson's blog on this. But volatile helps here.

Following fully running code shows how a number of threads can execute in predefined order and print outputs without using synchronized keyword.

thread 0 prints 0
thread 1 prints 1
thread 2 prints 2
thread 3 prints 3
thread 0 prints 0
thread 1 prints 1
thread 2 prints 2
thread 3 prints 3
thread 0 prints 0
thread 1 prints 1
thread 2 prints 2
thread 3 prints 3

To achieve this we may use the following full fledged running code.

public class Solution {
    static volatile int counter = 0;
    static int print = 0;
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Thread[] ths = new Thread[4];
        for (int i = 0; i < ths.length; i++) {
            ths[i] = new Thread(new MyRunnable(i, ths.length));
            ths[i].start();
        }
    }
    static class MyRunnable implements Runnable {
        final int thID;
        final int total;
        public MyRunnable(int id, int total) {
            thID = id;
            this.total = total;
        }
        @Override
        public void run() {
            // TODO Auto-generated method stub
            while (true) {
                if (thID == counter) {
                    System.out.println("thread " + thID + " prints " + print);
                    print++;
                    if (print == total)
                        print = 0;
                    counter++;
                    if (counter == total)
                        counter = 0;
                } else {
                    try {
                        Thread.sleep(30);
                    } catch (InterruptedException e) {
                        // log it
                    }
                }
            }
        }
    }
}

The following github link has a readme, which gives proper explanation. https://github.com/sankar4git/volatile_thread_ordering

How to deal with ModalDialog using selenium webdriver?

Nope, Model window needs to be handle by javaScriptExecutor,Because majorly model window made up of window model, This will works once model appeared then control take a place into model and click the expected element.

have to import javascriptexector

like below,

Javascriptexecutor js =(Javascriptexecutor).driver;
js.executescript(**<element to be clicked>**);

User GETDATE() to put current date into SQL variable

Just use GetDate() not Select GetDate()

DECLARE @LastChangeDate as date 
SET @LastChangeDate = GETDATE() 

but if it's SQL Server, you can also initialize in same step as declaration...

DECLARE @LastChangeDate date = getDate()

How to define servlet filter order of execution using annotations in WAR

The Servlet 3.0 spec doesn't seem to provide a hint on how a container should order filters that have been declared via annotations. It is clear how about how to order filters via their declaration in the web.xml file, though.

Be safe. Use the web.xml file order filters that have interdependencies. Try to make your filters all order independent to minimize the need to use a web.xml file.

How do you keep parents of floated elements from collapsing?

One of the most well known solutions is a variation of your solution number 3 that uses a pseudo element instead of a non-semantic html element.

It goes something like this...

.cf:after {
    content: " ";
    display: block;
    visibility: hidden;
    height: 0;
    clear: both;
}

You place that in your stylesheet, and all you need is to add the class 'cf' to the element containing the floats.

What I use is another variation which comes from Nicolas Gallagher.

It does the same thing, but it's shorter, looks neater, and maybe used to accomplish another thing that's pretty useful - preventing the child elements' margins from collapsing with it's parents' (but for that you do need something else - read more about it here http://nicolasgallagher.com/micro-clearfix-hack/ ).

.cf:after {
    content: " ";
    display: table;
    clear: float;
}

The real difference between "int" and "unsigned int"

The problem is that you invoked Undefined Behaviour.


When you invoke UB anything can happen.

The assignments are ok; there is an implicit conversion in the first line

int x = 0xFFFFFFFF;
unsigned int y = 0xFFFFFFFF;

However, the call to printf, is not ok

printf("%d, %d, %u, %u", x, y, x, y);

It is UB to mismatch the % specifier and the type of the argument.
In your case you specify 2 ints and 2 unsigned ints in this order by provide 1 int, 1 unsigned int, 1 int, and 1 unsigned int.


Don't do UB!

How to convert a String to a Date using SimpleDateFormat?

Very Simple Example is.

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MM-yyyy");
                Date date = new Date();
                Date date1 = new Date();
            try {
                System.out.println("Date1:   "+date1);
                System.out.println("date" + date);

                date = simpleDateFormat.parse("01-01-2013");
                date1 = simpleDateFormat.parse("06-15-2013");

                System.out.println("Date1 is:"+date1);
                System.out.println("date" + date);

            } catch (Exception e) {
                System.out.println(e.getMessage());
            }

Python: Fetch first 10 results from a list

The itertools module has lots of great stuff in it. So if a standard slice (as used by Levon) does not do what you want, then try the islice function:

from itertools import islice
l = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
iterator = islice(l, 10)
for item in iterator:
    print item

get string value from HashMap depending on key name

If you will use Generics and define your map as

Map<String,String> map = new HashMap<String,String>();

then fetching value as

 String s = map.get("keyStr"); 

you wont be required to typecast the map.get() or call toString method to get String value

How to retrieve the current version of a MySQL database management system (DBMS)?

Here two more methods:

Linux: Mysql view version: from PHP

From a PHP function, we can see the version used:

mysql_get_server_info ([resource $ link_identifier = NULL]): string

Linux: Mysql view version: Package version

For RedHat / CentOS operating systems:

rpm -qa | grep mysql

For Debian / Ubuntu operating systems:

rpm -qa | grep mysql

Extracted from: https://www.sysadmit.com/2019/03/linux-mysql-ver-version.html

How do I assert my exception message with JUnit Test annotation?

In JUnit 4.13 you can do:

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThrows;

...

@Test
void exceptionTesting() {
  IllegalArgumentException exception = assertThrows(
    IllegalArgumentException.class, 
    () -> { throw new IllegalArgumentException("a message"); }
  );

  assertEquals("a message", exception.getMessage());
}

This also works in JUnit 5 but with different imports:

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;

...

Real-world examples of recursion

I have a system that uses pure tail recursion in a few places to simulate a state machine.

User Control - Custom Properties

Just add public properties to the user control.

You can add [Category("MyCategory")] and [Description("A property that controls the wossname")] attributes to make it nicer, but as long as it's a public property it should show up in the property panel.

Placeholder Mixin SCSS/CSS

Why not something like this?

It uses a combination of lists, iteration, and interpolation.

@mixin placeholder ($rules) {

  @each $rule in $rules {
    ::-webkit-input-placeholder,
    :-moz-placeholder,
    ::-moz-placeholder,
    :-ms-input-placeholder {
      #{nth($rule, 1)}: #{nth($rule, 2)};
    }  
  }
}

$rules: (('border', '1px solid red'),
         ('color', 'green'));

@include placeholder( $rules );

Find all files with name containing string

The -maxdepth option should be before the -name option, like below.,

find . -maxdepth 1 -name "string" -print

Eclipse java debugging: source not found

this worked for me

right click on project -> Properties -> Deployment Assembly -> add your jar

How to change the docker image installation directory?

Don't use a symbolic Link to move the docker folder to /mnt (for example). This may cause in trouble with the docker rm command.

Better use the -g Option for docker. On Ubuntu you can set it permanently in /etc/default/docker.io. Enhance or replace the DOCKER_OPTS Line.

Here an example: `DOCKER_OPTS="-g /mnt/somewhere/else/docker/"

How to trust a apt repository : Debian apt-get update error public key is not available: NO_PUBKEY <id>

I had the same problem of "gpg: keyserver timed out" with a couple of different servers. Finally, it turned out that I didn't need to do that manually at all. On a Debian system, the simple solution which fixed it was just (as root or precede with sudo):

aptitude install debian-archive-keyring

In case it is some other keyring you need, check out

apt-cache search keyring | grep debian

My squeeze system shows all these:

debian-archive-keyring       - GnuPG archive keys of the Debian archive
debian-edu-archive-keyring   - GnuPG archive keys of the Debian Edu archive
debian-keyring               - GnuPG keys of Debian Developers
debian-ports-archive-keyring - GnuPG archive keys of the debian-ports archive
emdebian-archive-keyring     - GnuPG archive keys for the emdebian repository

Java code for getting current time

new Date().getTime() is bugged.

    Date date = new Date();
    System.out.println(date);
    System.out.println(date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds());
    long t1 = date.getTime();
    System.out.println((t1 / 1000 / 60 / 60) % 24 + ":" + (t1 / 1000 / 60) % 60 + ":" + (t1 / 1000) % 60);
    long t2 = System.currentTimeMillis();
    System.out.println((t2 / 1000 / 60 / 60) % 24 + ":" + (t2 / 1000 / 60) % 60 + ":" + (t2 / 1000) % 60);

It returns me the wrong time millis. System.currentTimeMillis() too. Since I ask the Date instance to tell me the corresponding time millis it must return the matching ones not others from a different time zone. Funny how deprecated methods are the only ones which return correct values.

Excel VBA code to copy a specific string to clipboard

If the url is in a cell in your workbook, you can simply copy the value from that cell:

Private Sub CommandButton1_Click()
    Sheets("Sheet1").Range("A1").Copy
End Sub

(Add a button by using the developer tab. Customize the ribbon if it isn't visible.)

If the url isn't in the workbook, you can use the Windows API. The code that follows can be found here: http://support.microsoft.com/kb/210216

After you've added the API calls below, change the code behind the button to copy to the clipboard:

Private Sub CommandButton1_Click()
    ClipBoard_SetData ("http:\\stackoverflow.com")
End Sub

Add a new module to your workbook and paste in the following code:

Option Explicit

Declare Function GlobalUnlock Lib "kernel32" (ByVal hMem As Long) _
   As Long
Declare Function GlobalLock Lib "kernel32" (ByVal hMem As Long) _
   As Long
Declare Function GlobalAlloc Lib "kernel32" (ByVal wFlags As Long, _
   ByVal dwBytes As Long) As Long
Declare Function CloseClipboard Lib "User32" () As Long
Declare Function OpenClipboard Lib "User32" (ByVal hwnd As Long) _
   As Long
Declare Function EmptyClipboard Lib "User32" () As Long
Declare Function lstrcpy Lib "kernel32" (ByVal lpString1 As Any, _
   ByVal lpString2 As Any) As Long
Declare Function SetClipboardData Lib "User32" (ByVal wFormat _
   As Long, ByVal hMem As Long) As Long

Public Const GHND = &H42
Public Const CF_TEXT = 1
Public Const MAXSIZE = 4096

Function ClipBoard_SetData(MyString As String)
   Dim hGlobalMemory As Long, lpGlobalMemory As Long
   Dim hClipMemory As Long, X As Long

   ' Allocate moveable global memory.
   '-------------------------------------------
   hGlobalMemory = GlobalAlloc(GHND, Len(MyString) + 1)

   ' Lock the block to get a far pointer
   ' to this memory.
   lpGlobalMemory = GlobalLock(hGlobalMemory)

   ' Copy the string to this global memory.
   lpGlobalMemory = lstrcpy(lpGlobalMemory, MyString)

   ' Unlock the memory.
   If GlobalUnlock(hGlobalMemory) <> 0 Then
      MsgBox "Could not unlock memory location. Copy aborted."
      GoTo OutOfHere2
   End If

   ' Open the Clipboard to copy data to.
   If OpenClipboard(0&) = 0 Then
      MsgBox "Could not open the Clipboard. Copy aborted."
      Exit Function
   End If

   ' Clear the Clipboard.
   X = EmptyClipboard()

   ' Copy the data to the Clipboard.
   hClipMemory = SetClipboardData(CF_TEXT, hGlobalMemory)

OutOfHere2:

   If CloseClipboard() = 0 Then
      MsgBox "Could not close Clipboard."
   End If

End Function

Modulo operator in Python

you should use fmod(a,b)

While abs(x%y) < abs(y) is true mathematically, for floats it may not be true numerically due to roundoff.

For example, and assuming a platform on which a Python float is an IEEE 754 double-precision number, in order that -1e-100 % 1e100 have the same sign as 1e100, the computed result is -1e-100 + 1e100, which is numerically exactly equal to 1e100.

Function fmod() in the math module returns a result whose sign matches the sign of the first argument instead, and so returns -1e-100 in this case. Which approach is more appropriate depends on the application.

where x = a%b is used for integer modulo

Can't Autowire @Repository annotated interface in Spring Boot

In SpringBoot, the JpaRepository are not auto-enabled by default. You have to explicitly add

@EnableJpaRepositories("packages")
@EntityScan("packages")

How do I determine scrollHeight?

Correct ways in jQuery are -

  • $('#test').prop('scrollHeight') OR
  • $('#test')[0].scrollHeight OR
  • $('#test').get(0).scrollHeight

pass array to method Java

public static void main(String[] args) {

    int[] A=new int[size];
      //code for take input in array
      int[] C=sorting(A); //pass array via method
      //and then print array

    }
public static int[] sorting(int[] a) {
     //code for work with array 
     return a; //retuen array
}

Parsing query strings on Android

public static Map <String, String> parseQueryString (final URL url)
        throws UnsupportedEncodingException
{
    final Map <String, String> qps = new TreeMap <String, String> ();
    final StringTokenizer pairs = new StringTokenizer (url.getQuery (), "&");
    while (pairs.hasMoreTokens ())
    {
        final String pair = pairs.nextToken ();
        final StringTokenizer parts = new StringTokenizer (pair, "=");
        final String name = URLDecoder.decode (parts.nextToken (), "ISO-8859-1");
        final String value = URLDecoder.decode (parts.nextToken (), "ISO-8859-1");
        qps.put (name, value);
    }
    return qps;
}

Allowed memory size of X bytes exhausted

PHP's config can be set in multiple places:

  1. master system php.ini (usually in /etc somewhere)
  2. somewhere in Apache's configuration (httpd.conf or a per-site .conf file, via php_value)
  3. CLI & CGI can have a different php.ini (use the command php -i | grep memory_limit to check the CLI conf)
  4. local .htaccess files (also php_value)
  5. in-script (via ini_set())

In PHPinfo's output, the "Master" value is the compiled-in default value, and the "Local" value is what's actually in effect. It can be either unchanged from the default, or overridden in any of the above locations.

Also note that PHP generally has different .ini files for command-line and webserver-based operation. Checking phpinfo() from the command line will report different values than if you'd run it in a web-based script.

RegExp in TypeScript

I think you want to test your RegExp in TypeScript, so you have to do like this:

var trigger = "2",
    regexp = new RegExp('^[1-9]\d{0,2}$'),
    test = regexp.test(trigger);
alert(test + ""); // will display true

You should read MDN Reference - RegExp, the RegExp object accepts two parameters pattern and flags which is nullable(can be omitted/undefined). To test your regex you have to use the .test() method, not passing the string you want to test inside the declaration of your RegExp!

Why test + ""? Because alert() in TS accepts a string as argument, it is better to write it this way. You can try the full code here.

Numbering rows within groups in a data frame

Using the rowid() function in data.table:

> set.seed(100)  
> df <- data.frame(cat = c(rep("aaa", 5), rep("bbb", 5), rep("ccc", 5)), val = runif(15))
> df <- df[order(df$cat, df$val), ]  
> df$num <- data.table::rowid(df$cat)
> df
   cat        val num
4  aaa 0.05638315   1
2  aaa 0.25767250   2
1  aaa 0.30776611   3
5  aaa 0.46854928   4
3  aaa 0.55232243   5
10 bbb 0.17026205   1
8  bbb 0.37032054   2
6  bbb 0.48377074   3
9  bbb 0.54655860   4
7  bbb 0.81240262   5
13 ccc 0.28035384   1
14 ccc 0.39848790   2
11 ccc 0.62499648   3
15 ccc 0.76255108   4
12 ccc 0.88216552   5

How do I get some variable from another class in Java?

You never call varsObject.setNum();

How to solve java.lang.OutOfMemoryError trouble in Android

Few hints to handle such error/exception for Android Apps:

  1. Activities & Application have methods like:

    • onLowMemory
    • onTrimMemory Handle these methods to watch on memory usage.
  2. tag in Manifest can have attribute 'largeHeap' set to TRUE, which requests more heap for App sandbox.

  3. Managing in-memory caching & disk caching:

    • Images and other data could have been cached in-memory while app running, (locally in activities/fragment and globally); should be managed or removed.
  4. Use of WeakReference, SoftReference of Java instance creation , specifically to files.

  5. If so many images, use proper library/data structure which can manage memory, use samling of images loaded, handle disk-caching.

  6. Handle OutOfMemory exception

  7. Follow best practices for coding

    • Leaking of memory (Don't hold everything with strong reference)
  8. Minimize activity stack e.g. number of activities in stack (Don't hold everything on context/activty)

    • Context makes sense, those data/instances not required out of scope (activity and fragments), hold them into appropriate context instead global reference-holding.
  9. Minimize the use of statics, many more singletons.

  10. Take care of OS basic memory fundametals

    • Memory fragmentation issues
  11. Involk GC.Collect() manually sometimes when you are sure that in-memory caching no more needed.

How to get the day name from a selected date?

I use this Extension Method:

public static string GetDayName(this DateTime date)
{
    string _ret = string.Empty; //Only for .NET Framework 4++
    var culture = new System.Globalization.CultureInfo("es-419"); //<- 'es-419' = Spanish (Latin America), 'en-US' = English (United States)
    _ret = culture.DateTimeFormat.GetDayName(date.DayOfWeek); //<- Get the Name     
    _ret = culture.TextInfo.ToTitleCase(_ret.ToLower()); //<- Convert to Capital title
    return _ret;
}

How to reduce the space between <p> tags?

<style type="text/css">
 p {margin-bottom: -1em;  margin-top: 0em;} 
</style>

This completely worked for me. Paragraphs were right below each other. When I used 0em for both the margins, there was still some space left in between the lines. I went for Developer tools in my browser, tried with -1em and it worked.

Passing data between view controllers

Swift 5

Well Matt Price's answer is perfectly fine for passing data, but I am going to rewrite it, in the latest Swift version because I believe new programmers find it quit challenging due to new syntax and methods/frameworks, as original post is in Objective-C.

There are multiple options for passing data between view controllers.

  1. Using Navigation Controller Push
  2. Using Segue
  3. Using Delegate
  4. Using Notification Observer
  5. Using Block

I am going to rewrite his logic in Swift with the latest iOS framework


Passing Data through Navigation Controller Push: From ViewControllerA to ViewControllerB

Step 1. Declare variable in ViewControllerB

var isSomethingEnabled = false

Step 2. Print Variable in ViewControllerB' ViewDidLoad method

override func viewDidLoad() {
    super.viewDidLoad()
    // Print value received through segue, navigation push
    print("Value of 'isSomethingEnabled' from ViewControllerA: ", isSomethingEnabled)
}

Step 3. In ViewControllerA Pass Data while pushing through Navigation Controller

if let viewControllerB = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "ViewControllerB") as? ViewControllerB {
    viewControllerB.isSomethingEnabled = true
    if let navigator = navigationController {
        navigator.pushViewController(viewControllerB, animated: true)
    }
}

So here is the complete code for:

ViewControllerA

import UIKit

class ViewControllerA: UIViewController  {

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    // MARK: Passing data through navigation PushViewController
    @IBAction func goToViewControllerB(_ sender: Any) {

        if let viewControllerB = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "ViewControllerB") as? ViewControllerB {
            viewControllerB.isSomethingEnabled = true
            if let navigator = navigationController {
                navigator.pushViewController(viewControllerB, animated: true)
            }
        }
    }
}

ViewControllerB

import UIKit

class ViewControllerB: UIViewController {

    // MARK:  - Variable for Passing Data through Navigation push
    var isSomethingEnabled = false

    override func viewDidLoad() {
        super.viewDidLoad()
        // Print value received through navigation push
        print("Value of 'isSomethingEnabled' from ViewControllerA: ", isSomethingEnabled)
    }
}

Passing Data through Segue: From ViewControllerA to ViewControllerB

Step 1. Create Segue from ViewControllerA to ViewControllerB and give Identifier = showDetailSegue in Storyboard as shown below

enter image description here

Step 2. In ViewControllerB Declare a viable named isSomethingEnabled and print its value.

Step 3. In ViewControllerA pass isSomethingEnabled's value while passing Segue

So here is the complete code for:

ViewControllerA

import UIKit

class ViewControllerA: UIViewController  {

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    // MARK:  - - Passing Data through Segue  - -
    @IBAction func goToViewControllerBUsingSegue(_ sender: Any) {
        performSegue(withIdentifier: "showDetailSegue", sender: nil)
    }

    // Segue Delegate Method
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if (segue.identifier == "showDetailSegue") {
            let controller = segue.destination as? ViewControllerB
            controller?.isSomethingEnabled = true//passing data
        }
    }
}

ViewControllerB

import UIKit

class ViewControllerB: UIViewController {
    var isSomethingEnabled = false

    override func viewDidLoad() {
        super.viewDidLoad()
        // Print value received through segue
        print("Value of 'isSomethingEnabled' from ViewControllerA: ", isSomethingEnabled)
    }
}

Passing Data through Delegate: From ViewControllerB to ViewControllerA

Step 1. Declare Protocol ViewControllerBDelegate in the ViewControllerB file, but outside the class

protocol ViewControllerBDelegate: NSObjectProtocol {

    // Classes that adopt this protocol MUST define
    // this method -- and hopefully do something in
    // that definition.
    func addItemViewController(_ controller: ViewControllerB?, didFinishEnteringItem item: String?)
}

Step 2. Declare Delegate variable instance in ViewControllerB

var delegate: ViewControllerBDelegate?

Step 3. Send data for delegate inside viewDidLoad method of ViewControllerB

delegate?.addItemViewController(self, didFinishEnteringItem: "Data for ViewControllerA")

Step 4. Confirm ViewControllerBDelegate in ViewControllerA

class ViewControllerA: UIViewController, ViewControllerBDelegate  {
// to do
}

Step 5. Confirm that you will implement a delegate in ViewControllerA

if let viewControllerB = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "ViewControllerB") as? ViewControllerB {
    viewControllerB.delegate = self//confirming delegate
    if let navigator = navigationController {
        navigator.pushViewController(viewControllerB, animated: true)
    }
}

Step 6. Implement delegate method for receiving data in ViewControllerA

func addItemViewController(_ controller: ViewControllerB?, didFinishEnteringItem item: String?) {
    print("Value from ViewControllerB's Delegate", item!)
}

So here is the complete code for:

ViewControllerA

import UIKit

class ViewControllerA: UIViewController, ViewControllerBDelegate  {

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    // Delegate method
    func addItemViewController(_ controller: ViewControllerB?, didFinishEnteringItem item: String?) {
        print("Value from ViewControllerB's Delegate", item!)
    }

    @IBAction func goToViewControllerForDelegate(_ sender: Any) {

        if let viewControllerB = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "ViewControllerB") as? ViewControllerB {
            viewControllerB.delegate = self
            if let navigator = navigationController {
                navigator.pushViewController(viewControllerB, animated: true)
            }
        }
    }
}

ViewControllerB

import UIKit

//Protocol decleare
protocol ViewControllerBDelegate: NSObjectProtocol {
    // Classes that adopt this protocol MUST define
    // this method -- and hopefully do something in
    // that definition.
    func addItemViewController(_ controller: ViewControllerB?, didFinishEnteringItem item: String?)
}

class ViewControllerB: UIViewController {
    var delegate: ViewControllerBDelegate?

    override func viewDidLoad() {
        super.viewDidLoad()
        // MARK:  - - - -  Set Data for Passing Data through Delegate  - - - - - -
        delegate?.addItemViewController(self, didFinishEnteringItem: "Data for ViewControllerA")
    }
}

Passing Data through Notification Observer: From ViewControllerB to ViewControllerA

Step 1. Set and post data in the notification observer in ViewControllerB

let objToBeSent = "Test Message from Notification"
        NotificationCenter.default.post(name: Notification.Name("NotificationIdentifier"), object: objToBeSent)

Step 2. Add Notification Observer in ViewControllerA

NotificationCenter.default.addObserver(self, selector: #selector(self.methodOfReceivedNotification(notification:)), name: Notification.Name("NotificationIdentifier"), object: nil)

Step 3. Receive Notification data value in ViewControllerA

@objc func methodOfReceivedNotification(notification: Notification) {
    print("Value of notification: ", notification.object ?? "")
}

So here is the complete code for:

ViewControllerA

import UIKit

class ViewControllerA: UIViewController{

    override func viewDidLoad() {
        super.viewDidLoad()

        // Add observer in controller(s) where you want to receive data
        NotificationCenter.default.addObserver(self, selector: #selector(self.methodOfReceivedNotification(notification:)), name: Notification.Name("NotificationIdentifier"), object: nil)
    }

    // MARK: Method for receiving Data through Post Notification
    @objc func methodOfReceivedNotification(notification: Notification) {
        print("Value of notification: ", notification.object ?? "")
    }
}

ViewControllerB

import UIKit

class ViewControllerB: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        // MARK:Set data for Passing Data through Post Notification
        let objToBeSent = "Test Message from Notification"
        NotificationCenter.default.post(name: Notification.Name("NotificationIdentifier"), object: objToBeSent)
    }
}

Passing Data through Block: From ViewControllerB to ViewControllerA

Step 1. Declare block in ViewControllerB

var authorizationCompletionBlock:((Bool)->())? = {_ in}

Step 2. Set data in block in ViewControllerB

if authorizationCompletionBlock != nil
{
    authorizationCompletionBlock!(true)
}

Step 3. Receive block data in ViewControllerA

// Receiver Block
controller!.authorizationCompletionBlock = { isGranted in
    print("Data received from Block is: ", isGranted)
}

So here is the complete code for:

ViewControllerA

import UIKit

class ViewControllerA: UIViewController  {

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    // MARK:Method for receiving Data through Block
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if (segue.identifier == "showDetailSegue") {
            let controller = segue.destination as? ViewControllerB
            controller?.isSomethingEnabled = true

            // Receiver Block
            controller!.authorizationCompletionBlock = { isGranted in
                print("Data received from Block is: ", isGranted)
            }
        }
    }
}

ViewControllerB

import UIKit

class ViewControllerB: UIViewController {

    // MARK: Variable for Passing Data through Block
    var authorizationCompletionBlock:((Bool)->())? = {_ in}

    override func viewDidLoad() {
        super.viewDidLoad()

        // MARK: Set data for Passing Data through Block
        if authorizationCompletionBlock != nil
        {
            authorizationCompletionBlock!(true)
        }
    }
}

You can find complete sample Application at my GitHub Please let me know if you have any question(s) on this.

Regex - how to match everything except a particular pattern

If you want to match a word A in a string and not to match a word B. For example: If you have a text:

1. I have a two pets - dog and a cat
2. I have a pet - dog

If you want to search for lines of text that HAVE a dog for a pet and DOESN'T have cat you can use this regular expression:

^(?=.*?\bdog\b)((?!cat).)*$

It will find only second line:

2. I have a pet - dog

Change hover color on a button with Bootstrap customization

This is the correct way to change btn color.

 .btn-primary:not(:disabled):not(.disabled).active, 
    .btn-primary:not(:disabled):not(.disabled):active, 
    .show>.btn-primary.dropdown-toggle{
        color: #fff;
        background-color: #F7B432;
        border-color: #F7B432;
    }

twitter bootstrap autocomplete dropdown / combobox with Knockoutjs

Does the basic HTML5 datalist work? It's clean and you don't have to play around with the messy third party code. W3SCHOOL tutorial

The MDN Documentation is very eloquent and features examples.

Best way to get hostname with php

The accepted answer gethostname() may infact give you inaccurate value as in my case

gethostname()         = my-macbook-pro     (incorrect)
$_SERVER['host_name'] = mysite.git         (correct)

The value from gethostname() is obvsiously wrong. Be careful with it.

Update as corrected by the comment

Host name gives you computer name, not website name, my bad. My result on local machine is

gethostname()         = my-macbook-pro     (which is my machine name)
$_SERVER['host_name'] = mysite.git         (which is my website name)

Exiting out of a FOR loop in a batch file?

You could simply use echo on and you will see that goto :eof or even exit /b doesn't work as expected.

The code inside of the loop isn't executed anymore, but the loop is expanded for all numbers to the end.
That's why it's so slow.

The only way to exit a FOR /L loop seems to be the variant of exit like the exsample of Wimmel, but this isn't very fast nor useful to access any results from the loop.

This shows 10 expansions, but none of them will be executed

echo on
for /l %%n in (1,1,10) do (
  goto :eof
  echo %%n
)

Get DateTime.Now with milliseconds precision

DateTime.Now.ToString("ddMMyyyyhhmmssffff")

UIView Infinite 360 degree rotation animation?

for xamarin ios:

public static void RotateAnimation (this UIView view, float duration=1, float rotations=1, float repeat=int.MaxValue)
{
    var rotationAnimation = CABasicAnimation.FromKeyPath ("transform.rotation.z");
    rotationAnimation.To = new NSNumber (Math.PI * 2.0 /* full rotation*/ * 1 * 1);
    rotationAnimation.Duration = 1;
    rotationAnimation.Cumulative = true;
    rotationAnimation.RepeatCount = int.MaxValue;
    rotationAnimation.RemovedOnCompletion = false;
    view.Layer.AddAnimation (rotationAnimation, "rotationAnimation");
}

Rollback to an old Git commit in a public repo

The original poster states:

The best answer someone could give me was to use git revert X times until I reach the desired commit.

So let's say I want to revert back to a commit that's 20 commits old, I'd have to run it 20 times.

Is there an easier way to do this?

I can't use reset cause this repo is public.

It's not necessary to use git revert X times. git revert can accept a commit range as an argument, so you only need to use it once to revert a range of commits. For example, if you want to revert the last 20 commits:

git revert --no-edit HEAD~20..

The commit range HEAD~20.. is short for HEAD~20..HEAD, and means "start from the 20th parent of the HEAD commit, and revert all commits after it up to HEAD".

That will revert that last 20 commits, assuming that none of those are merge commits. If there are merge commits, then you cannot revert them all in one command, you'll need to revert them individually with

git revert -m 1 <merge-commit>

Note also that I've tested using a range with git revert using git version 1.9.0. If you're using an older version of git, using a range with git revert may or may not work.

In this case, git revert is preferred over git checkout.

Note that unlike this answer that says to use git checkout, git revert will actually remove any files that were added in any of the commits that you're reverting, which makes this the correct way to revert a range of revisions.

Documentation

Generator expressions vs. list comprehensions

Python 3.7:

List comprehensions are faster.

enter image description here

Generators are more memory efficient. enter image description here

As all others have said, if you're looking to scale infinite data, you'll need a generator eventually. For relatively static small and medium-sized jobs where speed is necessary, a list comprehension is best.

INNER JOIN same table

Perhaps this should be the select (if I understand the question correctly)

select user.user_fname, user.user_lname, parent.user_fname, parent.user_lname
... As before

Selecting the last value of a column

I was playing with the code given by @tinfini, and thought people might benefit from what I think is a slightly more elegant solution (note I don't think scripts worked quite the same way when he created the original answer)...

//Note that this function assumes a single column of values, it will 
//not  function properly if given a multi-dimensional array (if the 
//cells that are captured are not in a single row).

function LastInRange(values) 
{
  for (index = values.length - 1; values[index] == "" && index > 0; index--) {}
  return String(values[index]);
}

In usage it would look like this:

=LastInRange(D2:D)

How to find out if you're using HTTPS without $_SERVER['HTTPS']

If you don't have control of the web server & don't know which variables have been set, upload this php to find out:

<?php
echo "<br>1 ".$_SERVER["HTTPS"];
echo "<br>2 ".$_SERVER["SERVER_PORT"];
echo "<br>3 ".$_SERVER["HTTP_X_FORWARDED_PROTO"];
echo "<br>4 ".$_SERVER["HTTP_X_FORWARDED_SSL"];
echo "<br>5 ".$_SERVER["HTTP_HTTPS"];
echo "<br>6 ".$_SERVER["REQUEST_SCHEME"];
?>

<html>
<body>
<br>
Just cruising
</body>
</html>

parse html string with jquery

I'm not a 100% sure, but won't

$(data)

produce a jquery object with a DOM for that data, not connected anywhere? Or if it's already parsed as a DOM, you could just go $("#myImg", data), or whatever selector suits your needs.

EDIT
Rereading your question it appears your 'data' is already a DOM, which means you could just go (assuming there's only an img in your DOM, otherwise you'll need a more precise selector)

$("img", data).attr ("src")

if you want to access the src-attribute. If your data is just text, it would probably work to do

$("img", $(data)).attr ("src")

How to get input textfield values when enter key is pressed in react js?

html

<input id="something" onkeyup="key_up(this)" type="text">

script

function key_up(e){
    var enterKey = 13; //Key Code for Enter Key
    if (e.which == enterKey){
        //Do you work here
    }
}

Next time, Please try providing some code.

How can I ask the Selenium-WebDriver to wait for few seconds in Java?

Thread.Sleep(5000);

This did help me but InterruptedException exception needs to be taken care of. So better surround it with try and catch:

try {
    Thread.Sleep(5000);
} catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

OR

Add throws declaration:

public class myClass {
    public static void main(String[] args) throws InterruptedException
    { ... }

I would prefer the second one since one can then use sleep() as many times as it wants and avoid the repetition of try and catch block every time wherever sleep() has been used.

Pods stuck in Terminating status

If --grace-period=0 is not working then you can do:

kubectl delete pods <pod> --grace-period=0 --force

How to grep and replace

Be very careful when using find and sed in a git repo! If you don't exclude the binary files you can end up with this error:

error: bad index file sha1 signature 
fatal: index file corrupt

To solve this error you need to revert the sed by replacing your new_string with your old_string. This will revert your replaced strings, so you will be back to the beginning of the problem.

The correct way to search for a string and replace it is to skip find and use grep instead in order to ignore the binary files:

sed -ri -e "s/old_string/new_string/g" $(grep -Elr --binary-files=without-match "old_string" "/files_dir")

Credits for @hobs

When should you use 'friend' in C++?

To do TDD many times I've used 'friend' keyword in C++.
Can a friend know everything about me?

No, its only a one way friendship :`(

Sending and receiving UDP packets?

The receiver must set port of receiver to match port set in sender DatagramPacket. For debugging try listening on port > 1024 (e.g. 8000 or 9000). Ports < 1024 are typically used by system services and need admin access to bind on such a port.

If the receiver sends packet to the hard-coded port it's listening to (e.g. port 57) and the sender is on the same machine then you would create a loopback to the receiver itself. Always use the port specified from the packet and in case of production software would need a check in any case to prevent such a case.

Another reason a packet won't get to destination is the wrong IP address specified in the sender. UDP unlike TCP will attempt to send out a packet even if the address is unreachable and the sender will not receive an error indication. You can check this by printing the address in the receiver as a precaution for debugging.

In the sender you set:

 byte [] IP= { (byte)192, (byte)168, 1, 106 };
 InetAddress address = InetAddress.getByAddress(IP);

but might be simpler to use the address in string form:

 InetAddress address = InetAddress.getByName("192.168.1.106");

In other words, you set target as 192.168.1.106. If this is not the receiver then you won't get the packet.

Here's a simple UDP Receiver that works :

import java.io.IOException;
import java.net.*;

public class Receiver {

    public static void main(String[] args) {
        int port = args.length == 0 ? 57 : Integer.parseInt(args[0]);
        new Receiver().run(port);
    }

    public void run(int port) {    
      try {
        DatagramSocket serverSocket = new DatagramSocket(port);
        byte[] receiveData = new byte[8];
        String sendString = "polo";
        byte[] sendData = sendString.getBytes("UTF-8");

        System.out.printf("Listening on udp:%s:%d%n",
                InetAddress.getLocalHost().getHostAddress(), port);     
        DatagramPacket receivePacket = new DatagramPacket(receiveData,
                           receiveData.length);

        while(true)
        {
              serverSocket.receive(receivePacket);
              String sentence = new String( receivePacket.getData(), 0,
                                 receivePacket.getLength() );
              System.out.println("RECEIVED: " + sentence);
              // now send acknowledgement packet back to sender     
              DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length,
                   receivePacket.getAddress(), receivePacket.getPort());
              serverSocket.send(sendPacket);
        }
      } catch (IOException e) {
              System.out.println(e);
      }
      // should close serverSocket in finally block
    }
}

How to vertically align text with icon font?

You can use this property : vertical-align:middle;

.selector-class { 
    float:left;
    vertical-align:middle; 
} 

How do I create dynamic variable names inside a loop?

In regards to iterative variable names, I like making dynamic variables using Template literals. Every Tom, Dick, and Harry uses the array-style, which is fine. Until you're working with arrays and dynamic variables, oh boy! Eye-bleed overload. Since Template literals have limited support right now, eval() is even another option.

v0 = "Variable Naught";
v1 = "Variable One";

for(i = 0; i < 2; i++)
{//console.log(i) equivalent is console.log(`${i}`)
  dyV = eval(`v${i}`);
  console.log(`v${i}`); /* => v0;   v1;  */      
  console.log(dyV);  /* => Variable Naught; Variable One;  */
}

When I was hacking my way through the APIs I made this little looping snippet to see behavior depending on what was done with the Template literals compared to say, Ruby. I liked Ruby's behavior more; needing to use eval() to get the value is kind of lame when you're used to getting it automatically.

_0 = "My first variable"; //Primitive
_1 = {"key_0":"value_0"}; //Object
_2 = [{"key":"value"}]    //Array of Object(s)


for (i = 0; i < 3; i++)
{
  console.log(`_${i}`);           /*  var
                                   * =>   _0  _1  _2  */

  console.log(`"_${i}"`);         /*  var name in string  
                                   * => "_0"  "_1"  "_2"  */

  console.log(`_${i}` + `_${i}`); /*  concat var with var
                                   * => _0_0  _1_1  _2_2  */

  console.log(eval(`_${i}`));     /*  eval(var)
                                   * => My first variable
                                        Object {key_0: "value_0"}
                                        [Object]  */
}

How to schedule a periodic task in Java?

my servlet contains this as a code how to keep this in scheduler if a user presses accept

if(bt.equals("accept")) {
    ScheduledExecutorService scheduler=Executors.newScheduledThreadPool(1);
    String lat=request.getParameter("latlocation");
    String lng=request.getParameter("lnglocation");
    requestingclass.updatelocation(lat,lng);
}

Is there a way to use max-width and height for a background image?

It looks like you're trying to scale the background image? There's a great article in the reference bellow where you can use css3 to achieve this.

And if I miss-read the question then I humbly accept the votes down. (Still good to know though)

Please consider the following code:

#some_div_or_body { 
   background: url(images/bg.jpg) no-repeat center center fixed; 
   -webkit-background-size: cover;
   -moz-background-size: cover;
   -o-background-size: cover;
   background-size: cover;
}

This will work on all major browsers, of course it doesn't come easy on IE. There are some workarounds however such as using Microsoft's filters:

filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='.myBackground.jpg', sizingMethod='scale');
-ms-filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='myBackground.jpg', sizingMethod='scale')";

There are some alternatives that can be used with a little bit peace of mind by using jQuery:

HTML

<img src="images/bg.jpg" id="bg" alt="">

CSS

#bg { position: fixed; top: 0; left: 0; }
.bgwidth { width: 100%; }
.bgheight { height: 100%; }

jQuery:

 $(window).load(function() {    

var theWindow        = $(window),
    $bg              = $("#bg"),
    aspectRatio      = $bg.width() / $bg.height();

function resizeBg() {

    if ( (theWindow.width() / theWindow.height()) < aspectRatio ) {
        $bg
            .removeClass()
            .addClass('bgheight');
    } else {
        $bg
            .removeClass()
            .addClass('bgwidth');
    }

}

theWindow.resize(resizeBg).trigger("resize");

});

I hope this helps!

Src: Perfect Full Page Background Image

how to overlap two div in css?

check this fiddle , and if you want to move the overlapped div you set its position to absolute then change it's top and left values

Pagination on a list using ng-repeat

If you have not too much data, you can definitely do pagination by just storing all the data in the browser and filtering what's visible at a certain time.

Here's a simple pagination example: http://jsfiddle.net/2ZzZB/56/

That example was on the list of fiddles on the angular.js github wiki, which should be helpful: https://github.com/angular/angular.js/wiki/JsFiddle-Examples

EDIT: http://jsfiddle.net/2ZzZB/16/ to http://jsfiddle.net/2ZzZB/56/ (won't show "1/4.5" if there is 45 results)

White space at top of page

Aside from the css reset, I also added the following to the css of my div container and that fixed it.

position: relative;
top: -22px; 

Do I need to convert .CER to .CRT for Apache SSL certificates? If so, how?

Here is one case that worked for me if we need to convert .cer to .crt, though both of them are contextually same

openssl pkcs12 -in identity.p12 -nokeys -out mycertificate.crt

where we should have a valid private key (identity.p12) PKCS 12 format, this one i generated from keystore (.jks file) provided by CA (Certification Authority) who created my certificate.

C subscripted value is neither array nor pointer nor vector when assigning an array element value

The problem is that arr is not (declared as) a 2D array, and you are treating it as if it were 2D.

how to create a login page when username and password is equal in html

<html>
    <head>
        <title>Login page</title>
    </head>
    <body>
        <h1>Simple Login Page</h1>
        <form name="login">
            Username<input type="text" name="userid"/>
            Password<input type="password" name="pswrd"/>
            <input type="button" onclick="check(this.form)" value="Login"/>
            <input type="reset" value="Cancel"/>
        </form>
        <script language="javascript">
            function check(form) { /*function to check userid & password*/
                /*the following code checkes whether the entered userid and password are matching*/
                if(form.userid.value == "myuserid" && form.pswrd.value == "mypswrd") {
                    window.open('target.html')/*opens the target page while Id & password matches*/
                }
                else {
                    alert("Error Password or Username")/*displays error message*/
                }
            }
        </script>
    </body>
</html>

WCF change endpoint address at runtime

We store our URLs in a database and load them at runtime.

public class ServiceClientFactory<TChannel> : ClientBase<TChannel> where TChannel : class
{
    public TChannel Create(string url)
    {
        this.Endpoint.Address = new EndpointAddress(new Uri(url));
        return this.Channel;
    }
}

Implementation

var client = new ServiceClientFactory<yourServiceChannelInterface>().Create(newUrl);

Prime numbers between 1 to 100 in C Programming Language

#include <stdio.h>
#include <conio.h>
int main()
{
    int i,j;
    int b=0;
    for (i=2;i<=100;i++){
        for (j=2;j<=i;j++){
            if (i%j==0){
                break;
            }
        }
        if (i==j)
            print f("\n%d",j);
    }
    getch ();
}

Cannot find the declaration of element 'beans'

I had this issue and the root cause turned out to be white-space (shown as dots below) after the www.springframework.org/schema/beans reference in xsi:schemaLocation, i.e.

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="
http://www.springframework.org/schema/beans....
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd">

Skip first line(field) in loop using CSV file?

There are many ways to skip the first line. In addition to those said by Bakuriu, I would add:

with open(filename, 'r') as f:
    next(f)
    for line in f:

and:

with open(filename,'r') as f:
    lines = f.readlines()[1:]

Insert node at a certain position in a linked list C++

I had some problems with the insertion process just like you, so here is the code how I have solved the problem:

void add_by_position(int data, int pos)
  {
        link *node = new link;
        link *linker = head;

        node->data = data;
        for (int i = 0; i < pos; i++){
            linker = linker->next;
        }
        node->next = linker;
        linker = head;
        for (int i = 0; i < pos - 1; i++){
            linker = linker->next;
        }
        linker->next = node;
        boundaries++;
    }

Stack array using pop() and push()

Better solution for your Stack implementation

import java.util.List;
import java.util.ArrayList;
public class IntegerStack 

{

    private List<Integer> stack;

    public IntegerStack(int SIZE) 
    {
        stack = new ArrayList<Integer>(SIZE);
    }

    public void push(int i) 
    {

       stack.add(0,i);
     }

     public int pop() 
     { 
        if(!stack.isEmpty()){
           int i= stack.get(0);
           stack.remove(0);
           return i;
        } else{
           return -1;// Or any invalid value
        }
     }

     public int peek()
     {
        if(!stack.isEmpty()){
           return stack.get(0);
        } else{
           return -1;// Or any invalid value
        }
     }


     public boolean isEmpty() 
     {
       stack.isEmpty();
     }

 }

If you have to use Array... Here are problems in your code and possible solutions

import java.util.Arrays;
public class IntegerStack 
{

    private int stack [];
    private int top; 

    public IntegerStack(int SIZE) 
   {
    stack = new int [SIZE];
    top = -1; // top should be 0. If you keep it as -1, problems will arise when SIZE is passed as 0. 
    // In your push method -1==0 will be false and your code will try to add the invalid element to Stack .. 
     /**Solution top=0; */
    }

public void push(int i) 
{
    if (top == stack.length)
    {
        extendStack();
    }

       stack[top]= i;
        top++;

}

public int pop() 
{
    top --; // here you are reducing the top before giving the Object back 
   /*Solution 
      if(!isEmpty()){
      int value = stack[top];
       top --;
     return value; 
    } else{
      return -1;// OR invalid value
    }
   */
    return stack[top];
}

public int peek()
{
    return stack[top]; // Problem when stack is empty or size is 0
    /*Solution 
       if(!isEmpty()){
         return stack[top];
       }else{
         return -1;// Or any invalid value
       }
    */


}


public boolean isEmpty() 
{
    if ( top == -1); // problem... we changed top to 0 above so here it need to check if its 0 and there should be no semicolon after the if statement
   /* Solution if(top==0) */
    {
        return true;
    }
}

private void extendStack()
{

    int [] copy = Arrays.copyOf(stack, stack.length); // The second parameter in Arrays.copyOf has no changes, so there will be no change in array length.
  /*Solution  
    stack=Arrays.copyOf(stack, stack.length+1); 
   */
     }

     }

Best way to check that element is not present using Selenium WebDriver with java

    WebElement element = driver.findElement(locator);

    Assert.assertFalse(element.isDisplayed());

The assertion will pass if the element is not present, otherwise it will fail.

Generate random password string with requirements in javascript

Here's a way to create a flexible generator that allows you to add some rules:

function generatePassword(length, rules) {
    if (!length || length == undefined) {
        length = 8;
    }

    if (!rules || rules == undefined) {
        rules = [
            {chars: "abcdefghijklmnopqrstuvwxyz", min: 3},  // As least 3 lowercase letters
            {chars: "ABCDEFGHIJKLMNOPQRSTUVWXYZ", min: 2},  // At least 2 uppercase letters
            {chars: "0123456789", min: 2},                  // At least 2 digits
            {chars: "!@#$&*?|%+-_./:;=()[]{}", min: 1}      // At least 1 special char
        ];
    }

    var allChars = "", allMin = 0;
    rules.forEach(function(rule) {
        allChars += rule.chars;
        allMin += rule.min;
    });
    if (length < allMin) {
        length = allMin;
    }
    rules.push({chars: allChars, min: length - allMin});
    
    var pswd = "";
    rules.forEach(function(rule) {
        if (rule.min > 0) {
            pswd += shuffleString(rule.chars, rule.min);
        }
    });
    
    return shuffleString(pswd);
}

function shuffleString(str, maxlength) {
    var shuffledString = str.split('').sort(function(){return 0.5-Math.random()}).join('');
    if (maxlength > 0) {
        shuffledString = shuffledString.substr(0, maxlength);
    }
    return shuffledString;
}

var pswd = generatePassword(15, [
  {chars: "abcdefghijklmnopqrstuvwxyz", min: 4},  // As least 4 lowercase letters
  {chars: "ABCDEFGHIJKLMNOPQRSTUVWXYZ", min: 1},  // At least 1 uppercase letters
  {chars: "0123456789", min: 3},                  // At least 3 digits
  {chars: "!@#$&*?|%+-_./:;=()[]{}", min: 2}      // At least 2 special chars
]);

console.log(pswd, pswd.length);

Failed to decode downloaded font, OTS parsing error: invalid version tag + rails 4

I am using ASP.NET with IIS and it turns out I just needed to add the MIME-type to IIS: '.woff2' / 'application/font-woff'

React - Display loading screen while DOM is rendering?

The goal

When the html page is rendered, display a spinner immediately (while React loads), and hide it after React is ready.

Since the spinner is rendered in pure HTML/CSS (outside of the React domain), React shouldn't control the showing/hiding process directly, and the implementation should be transparent to React.

Solution 1 - the :empty pseudo-class

Since you render react into a DOM container - <div id="app"></div>, you can add a spinner to that container, and when react will load and render, the spinner will disappear.

You can't add a DOM element (a div for example) inside the react root, since React will replace the contents of the container as soon as ReactDOM.render() is called. Even if you render null, the content would still be replaced by a comment - <!-- react-empty: 1 -->. This means that if you want to display the loader while the main component mounts, data is loading, but nothing is actually rendered, a loader markup placed inside the container (<div id="app"><div class="loader"></div></div> for example) would not work.

A workaround is to add the spinner class to the react container, and use the :empty pseudo class. The spinner will be visible, as long as nothing is rendered into the container (comments don't count). As soon as react renders something other than comment, the loader will disappear.

Example 1

In the example you can see a component that renders null until it's ready. The container is the loader as well - <div id="app" class="app"></div>, and the loader's class will only work if it's :empty (see comments in code):

_x000D_
_x000D_
class App extends React.Component {_x000D_
  state = {_x000D_
    loading: true_x000D_
  };_x000D_
_x000D_
  componentDidMount() {_x000D_
    // this simulates an async action, after which the component will render the content_x000D_
    demoAsyncCall().then(() => this.setState({ loading: false }));_x000D_
  }_x000D_
  _x000D_
  render() {_x000D_
    const { loading } = this.state;_x000D_
    _x000D_
    if(loading) { // if your component doesn't have to wait for an async action, remove this block _x000D_
      return null; // render null when app is not ready_x000D_
    }_x000D_
    _x000D_
    return (_x000D_
      <div>I'm the app</div>_x000D_
    ); _x000D_
  }_x000D_
}_x000D_
_x000D_
function demoAsyncCall() {_x000D_
  return new Promise((resolve) => setTimeout(() => resolve(), 2500));_x000D_
}_x000D_
_x000D_
ReactDOM.render(_x000D_
  <App />,_x000D_
  document.getElementById('app')_x000D_
);
_x000D_
.loader:empty {_x000D_
  position: absolute;_x000D_
  top: calc(50% - 4em);_x000D_
  left: calc(50% - 4em);_x000D_
  width: 6em;_x000D_
  height: 6em;_x000D_
  border: 1.1em solid rgba(0, 0, 0, 0.2);_x000D_
  border-left: 1.1em solid #000000;_x000D_
  border-radius: 50%;_x000D_
  animation: load8 1.1s infinite linear;_x000D_
}_x000D_
_x000D_
@keyframes load8 {_x000D_
  0% {_x000D_
    transform: rotate(0deg);_x000D_
  }_x000D_
  100% {_x000D_
    transform: rotate(360deg);_x000D_
  }_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.1/react.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.1/react-dom.js"></script>_x000D_
_x000D_
<div id="app" class="loader"></div> <!-- add class loader to container -->
_x000D_
_x000D_
_x000D_

Example 2

A variation on using the :empty pseudo class to show/hide a selector, is setting the spinner as a sibling element to the app container, and showing it as long as the container is empty using the adjacent sibling combinator (+):

_x000D_
_x000D_
class App extends React.Component {_x000D_
  state = {_x000D_
    loading: true_x000D_
  };_x000D_
_x000D_
  componentDidMount() {_x000D_
    // this simulates an async action, after which the component will render the content_x000D_
    demoAsyncCall().then(() => this.setState({ loading: false }));_x000D_
  }_x000D_
  _x000D_
  render() {_x000D_
    const { loading } = this.state;_x000D_
    _x000D_
    if(loading) { // if your component doesn't have to wait for async data, remove this block _x000D_
      return null; // render null when app is not ready_x000D_
    }_x000D_
    _x000D_
    return (_x000D_
      <div>I'm the app</div>_x000D_
    ); _x000D_
  }_x000D_
}_x000D_
_x000D_
function demoAsyncCall() {_x000D_
  return new Promise((resolve) => setTimeout(() => resolve(), 2500));_x000D_
}_x000D_
_x000D_
ReactDOM.render(_x000D_
  <App />,_x000D_
  document.getElementById('app')_x000D_
);
_x000D_
#app:not(:empty) + .sk-cube-grid {_x000D_
  display: none;_x000D_
}_x000D_
_x000D_
.sk-cube-grid {_x000D_
  width: 40px;_x000D_
  height: 40px;_x000D_
  margin: 100px auto;_x000D_
}_x000D_
_x000D_
.sk-cube-grid .sk-cube {_x000D_
  width: 33%;_x000D_
  height: 33%;_x000D_
  background-color: #333;_x000D_
  float: left;_x000D_
  animation: sk-cubeGridScaleDelay 1.3s infinite ease-in-out;_x000D_
}_x000D_
_x000D_
.sk-cube-grid .sk-cube1 {_x000D_
  animation-delay: 0.2s;_x000D_
}_x000D_
_x000D_
.sk-cube-grid .sk-cube2 {_x000D_
  animation-delay: 0.3s;_x000D_
}_x000D_
_x000D_
.sk-cube-grid .sk-cube3 {_x000D_
  animation-delay: 0.4s;_x000D_
}_x000D_
_x000D_
.sk-cube-grid .sk-cube4 {_x000D_
  animation-delay: 0.1s;_x000D_
}_x000D_
_x000D_
.sk-cube-grid .sk-cube5 {_x000D_
  animation-delay: 0.2s;_x000D_
}_x000D_
_x000D_
.sk-cube-grid .sk-cube6 {_x000D_
  animation-delay: 0.3s;_x000D_
}_x000D_
_x000D_
.sk-cube-grid .sk-cube7 {_x000D_
  animation-delay: 0s;_x000D_
}_x000D_
_x000D_
.sk-cube-grid .sk-cube8 {_x000D_
  animation-delay: 0.1s;_x000D_
}_x000D_
_x000D_
.sk-cube-grid .sk-cube9 {_x000D_
  animation-delay: 0.2s;_x000D_
}_x000D_
_x000D_
@keyframes sk-cubeGridScaleDelay {_x000D_
  0%,_x000D_
  70%,_x000D_
  100% {_x000D_
    transform: scale3D(1, 1, 1);_x000D_
  }_x000D_
  35% {_x000D_
    transform: scale3D(0, 0, 1);_x000D_
  }_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.1/react.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.1/react-dom.js"></script>_x000D_
_x000D_
<div id="app"></div>_x000D_
<!-- add class loader to container -->_x000D_
_x000D_
<div class="sk-cube-grid">_x000D_
  <div class="sk-cube sk-cube1"></div>_x000D_
  <div class="sk-cube sk-cube2"></div>_x000D_
  <div class="sk-cube sk-cube3"></div>_x000D_
  <div class="sk-cube sk-cube4"></div>_x000D_
  <div class="sk-cube sk-cube5"></div>_x000D_
  <div class="sk-cube sk-cube6"></div>_x000D_
  <div class="sk-cube sk-cube7"></div>_x000D_
  <div class="sk-cube sk-cube8"></div>_x000D_
  <div class="sk-cube sk-cube9"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_


Solution 2 - Pass spinner "handlers" as props

To have a more fine grained control over the spinners display state, create two functions showSpinner and hideSpinner, and pass them to the root container via props. The functions can manipulate the DOM, or do whatever needed to control the spinner. In this way, React is not aware of the "outside world", nor needs to control the DOM directly. You can easily replace the functions for testing, or if you need to change the logic, and you can pass them to other components in the React tree.

Example 1

_x000D_
_x000D_
const loader = document.querySelector('.loader');_x000D_
_x000D_
// if you want to show the loader when React loads data again_x000D_
const showLoader = () => loader.classList.remove('loader--hide');_x000D_
_x000D_
const hideLoader = () => loader.classList.add('loader--hide');_x000D_
_x000D_
class App extends React.Component {_x000D_
  componentDidMount() {_x000D_
    this.props.hideLoader();_x000D_
  }_x000D_
  _x000D_
  render() {   _x000D_
    return (_x000D_
      <div>I'm the app</div>_x000D_
    ); _x000D_
  }_x000D_
}_x000D_
_x000D_
// the setTimeout simulates the time it takes react to load, and is not part of the solution_x000D_
setTimeout(() => _x000D_
  // the show/hide functions are passed as props_x000D_
  ReactDOM.render(_x000D_
    <App_x000D_
      hideLoader={hideLoader}_x000D_
      showLoader={showLoader} _x000D_
      />,_x000D_
    document.getElementById('app')_x000D_
  )_x000D_
, 1000);
_x000D_
.loader {_x000D_
  position: absolute;_x000D_
  top: calc(50% - 4em);_x000D_
  left: calc(50% - 4em);_x000D_
  width: 6em;_x000D_
  height: 6em;_x000D_
  border: 1.1em solid rgba(0, 0, 0, 0.2);_x000D_
  border-left: 1.1em solid #000000;_x000D_
  border-radius: 50%;_x000D_
  animation: load8 1.1s infinite linear;_x000D_
  transition: opacity 0.3s;_x000D_
}_x000D_
_x000D_
.loader--hide {_x000D_
  opacity: 0;_x000D_
}_x000D_
_x000D_
@keyframes load8 {_x000D_
  0% {_x000D_
    transform: rotate(0deg);_x000D_
  }_x000D_
  100% {_x000D_
    transform: rotate(360deg);_x000D_
  }_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.1/react.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.1/react-dom.js"></script>_x000D_
_x000D_
<div id="app"></div>_x000D_
_x000D_
<div class="loader"></div>
_x000D_
_x000D_
_x000D_

Example 2 - hooks

This example uses the useEffect hook to hide the spinner after the component mounts.

_x000D_
_x000D_
const { useEffect } = React;_x000D_
_x000D_
const loader = document.querySelector('.loader');_x000D_
_x000D_
// if you want to show the loader when React loads data again_x000D_
const showLoader = () => loader.classList.remove('loader--hide');_x000D_
_x000D_
const hideLoader = () => loader.classList.add('loader--hide');_x000D_
_x000D_
const App = ({ hideLoader }) => {_x000D_
  useEffect(hideLoader, []);_x000D_
  _x000D_
  return (_x000D_
    <div>I'm the app</div>_x000D_
  ); _x000D_
}_x000D_
_x000D_
// the setTimeout simulates the time it takes react to load, and is not part of the solution_x000D_
setTimeout(() => _x000D_
  // the show/hide functions are passed as props_x000D_
  ReactDOM.render(_x000D_
    <App_x000D_
      hideLoader={hideLoader}_x000D_
      showLoader={showLoader} _x000D_
      />,_x000D_
    document.getElementById('app')_x000D_
  )_x000D_
, 1000);
_x000D_
.loader {_x000D_
  position: absolute;_x000D_
  top: calc(50% - 4em);_x000D_
  left: calc(50% - 4em);_x000D_
  width: 6em;_x000D_
  height: 6em;_x000D_
  border: 1.1em solid rgba(0, 0, 0, 0.2);_x000D_
  border-left: 1.1em solid #000000;_x000D_
  border-radius: 50%;_x000D_
  animation: load8 1.1s infinite linear;_x000D_
  transition: opacity 0.3s;_x000D_
}_x000D_
_x000D_
.loader--hide {_x000D_
  opacity: 0;_x000D_
}_x000D_
_x000D_
@keyframes load8 {_x000D_
  0% {_x000D_
    transform: rotate(0deg);_x000D_
  }_x000D_
  100% {_x000D_
    transform: rotate(360deg);_x000D_
  }_x000D_
}
_x000D_
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>_x000D_
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>_x000D_
_x000D_
<div id="app"></div>_x000D_
_x000D_
<div class="loader"></div>
_x000D_
_x000D_
_x000D_

Add a new line to a text file in MS-DOS

  • I always use copy con to write text, It so easy to write a long text
  • Example:

    C:\COPY CON [drive:][path][File name]

    .... Content

    F6

    1 file(s) is copied

jquery datatables hide column

take look at my solution

I have this HTML table Head

<thead>
    <tr>
        <th style="width: 20%">@L("Id")</th>
        <th style="width: 20%">@L("IdentityNumber")</th>
        <th style="width: 20%">@L("Name")</th>
        <th style="width: 20%">@L("MobileNumber")</th>
        <th style="width: 20%">@L("RegistrationStatus")</th>
        <th style="width: 20%">@L("RegistrationStatusId")</th>
        <th style="width: 20%; text-align: center;" data-hide="phone">@L("Actions")</th>
    </tr>
</thead>

and my Ajax request returned something like this

enter image description here

so I want to hide Id index [0] and RegistrationStatusId index [5]

$(document).ready(function() {
    $('#example').dataTable( {
        "columnDefs": [
            { "aTargets": [0, 5], "sClass": "invisible"},// here is the tricky part
        ]
    });
});

I hope this would help you

Swap x and y axis without manually swapping values

Using Excel 2010 x64. XY plot: I could not see no tabs (it is late and I am probably tired blind, 250 limit?). Here is what worked for me:

Swap the data columns, to end with X_data in column A and Y_data in column B.

My original data had Y_data in column A and X_data in column B, and the graph was rotated 90deg clockwise. I was suffering. Then it hit me: an Excel XY plot literally wants {x,y} pairs, i.e. X_data in first column and Y_data in second column. But it does not tell you this right away. For me an XY plot means Y=f(X) plotted.

How do you clear the SQL Server transaction log?

To my experience on most SQL Servers there is no backup of the transaction log. Full backups or differential backups are common practice, but transaction log backups are really seldom. So the transaction log file grows forever (until the disk is full). In this case the recovery model should be set to "simple". Don't forget to modify the system databases "model" and "tempdb", too.

A backup of the database "tempdb" makes no sense, so the recovery model of this db should always be "simple".

Type Checking: typeof, GetType, or is?

if (c is UserControl) c.Enabled = enable;

Unnamed/anonymous namespaces vs. static functions

I recently began replacing static keywords with anonymous namespaces in my code but immediately ran into a problem where the variables in the namespace were no longer available for inspection in my debugger. I was using VC60, so I don't know if that is a non-issue with other debuggers. My workaround was to define a 'module' namespace, where I gave it the name of my cpp file.

For example, in my XmlUtil.cpp file, I define a namespace XmlUtil_I { ... } for all of my module variables and functions. That way I can apply the XmlUtil_I:: qualification in the debugger to access the variables. In this case, the _I distinguishes it from a public namespace such as XmlUtil that I may want to use elsewhere.

I suppose a potential disadvantage of this approach compared to a truly anonymous one is that someone could violate the desired static scope by using the namespace qualifier in other modules. I don't know if that is a major concern though.

Date Difference in php on days?

strtotime will convert your date string to a unix time stamp. (seconds since the unix epoch.

$ts1 = strtotime($date1);
$ts2 = strtotime($date2);

$seconds_diff = $ts2 - $ts1;

PHP: check if any posted vars are empty - form: all fields required

foreach($_POST as $key=>$value)
{

   if(empty(trim($value))
        echo "$key input required of value ";

}

Getting input values from text box

you have multiple elements with the same id. That is a big no-no. Make sure your inputs have unique ids.

<td id="pass"><label>Password</label></td>
<tr>
   <td colspan="2"><input class="textBox" id="pass" type="text" maxlength="30" required/></td>
</tr>

see, both the td and the input share the id value pass.

how to write value into cell with vba code without auto type conversion?

Indeed, just as commented by Tim Williams, the way to make it work is pre-formatting as text. Thus, to do it all via VBA, just do that:

Cells(1, 1).NumberFormat = "@"
Cells(1, 1).Value = "1234,56"

The meaning of NoInitialContextException error

make sure dependencies for jetty naming and jetty plus are included (not just provided scope). This fixed it for me.

variable or field declared void

Did you put void while calling your function?

For example:

void something(int x){
    logic..
}

int main() {

    **void** something();

    return 0;

}

If so, you should delete the last void.

Get an OutputStream into a String

I like the Apache Commons IO library. Take a look at its version of ByteArrayOutputStream, which has a toString(String enc) method as well as toByteArray(). Using existing and trusted components like the Commons project lets your code be smaller and easier to extend and repurpose.

How to create a multiline UITextfield?

Ok I did it with some trick ;) First build a UITextField and increased it's size like this :

CGRect frameRect = textField.frame;
        frameRect.size.height = 53;
        textField.frame = frameRect;

Then build a UITextView exactly in the same area that u made my UITextField, and deleted its background color. Now it looks like that u have a multiple lines TextField !

How to find the cumulative sum of numbers in a list?

Assignment expressions from PEP 572 (new in Python 3.8) offer yet another way to solve this:

time_interval = [4, 6, 12]

total_time = 0
cum_time = [total_time := total_time + t for t in time_interval]

Passing html values into javascript functions

Try: if(parseInt(order)>0){....

How do I get cURL to not show the progress bar?

I found that with curl 7.18.2 the download progress bar is not hidden with:

curl -s http://google.com > temp.html

but it is with:

curl -ss http://google.com > temp.html

How to make matrices in Python?

Looping helps:

for row in matrix:
    print ' '.join(row)

or use nested str.join() calls:

print '\n'.join([' '.join(row) for row in matrix])

Demo:

>>> matrix = [['A', 'B', 'C', 'D', 'E'], ['A', 'B', 'C', 'D', 'E'], ['A', 'B', 'C', 'D', 'E'], ['A', 'B', 'C', 'D', 'E'], ['A', 'B', 'C', 'D', 'E']]
>>> for row in matrix:
...     print ' '.join(row)
... 
A B C D E
A B C D E
A B C D E
A B C D E
A B C D E
>>> print '\n'.join([' '.join(row) for row in matrix])
A B C D E
A B C D E
A B C D E
A B C D E
A B C D E

If you wanted to show the rows and columns transposed, transpose the matrix by using the zip() function; if you pass each row as a separate argument to the function, zip() recombines these value by value as tuples of columns instead. The *args syntax lets you apply a whole sequence of rows as separate arguments:

>>> for cols in zip(*matrix):  # transposed
...     print ' '.join(cols)
... 
A A A A A
B B B B B
C C C C C
D D D D D
E E E E E

OVER_QUERY_LIMIT in Google Maps API v3: How do I pause/delay in Javascript to slow it down?

Here I have loaded 2200 markers. It takes around 1 min to add 2200 locations. https://jsfiddle.net/suchg/qm1pqunz/11/

//function to get random element from an array
    (function($) {
        $.rand = function(arg) {
            if ($.isArray(arg)) {
                return arg[$.rand(arg.length)];
            } else if (typeof arg === "number") {
                return Math.floor(Math.random() * arg);
            } else {
                return 4;  // chosen by fair dice roll
            }
        };
    })(jQuery);

//start code on document ready
$(document).ready(function () {
    var map;
    var elevator;
    var myOptions = {
        zoom: 0,
        center: new google.maps.LatLng(35.392738, -100.019531), 
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    map = new google.maps.Map($('#map_canvas')[0], myOptions);

    //get place from inputfile.js
    var placesObject = place;
    errorArray = [];

  //will fire 20 ajax request at a time and other will keep in queue
    var queuCounter = 0, setLimit = 20; 

  //keep count of added markers and update at top
  totalAddedMarkers = 0;

  //make an array of geocode keys to avoid the overlimit error
    var geoCodKeys = [
                    'AIzaSyCF82XXUtT0vzMTcEPpTXvKQPr1keMNr_4',
                    'AIzaSyAYPw6oFHktAMhQqp34PptnkDEdmXwC3s0',
                    'AIzaSyAwd0OLvubYtKkEWwMe4Fe0DQpauX0pzlk',
                    'AIzaSyDF3F09RkYcibDuTFaINrWFBOG7ilCsVL0',
                    'AIzaSyC1dyD2kzPmZPmM4-oGYnIH_0x--0hVSY8'                   
                ];

  //funciton to add marker
    var addMarkers = function(address, queKey){
        var key = jQuery.rand(geoCodKeys);
        var url = 'https://maps.googleapis.com/maps/api/geocode/json?key='+key+'&address='+address+'&sensor=false';

        var qyName = '';
        if( queKey ) {
            qyName = queKey;
        } else {
            qyName = 'MyQueue'+queuCounter;
        }

        $.ajaxq (qyName, {
            url: url,
            dataType: 'json'
        }).done(function( data ) {
                    var address = getParameterByName('address', this.url);
                    var index = errorArray.indexOf(address);
                    try{
                        var p = data.results[0].geometry.location;
                        var latlng = new google.maps.LatLng(p.lat, p.lng);
                        new google.maps.Marker({
                            position: latlng,
                            map: map
                        });
                        totalAddedMarkers ++;

            //update adde marker count
                        $("#totalAddedMarker").text(totalAddedMarkers);
                        if (index > -1) {
                            errorArray.splice(index, 1);
                        }
                    }catch(e){
                        if(data.status = 'ZERO_RESULTS')
                            return false;

            //on error call add marker function for same address
            //and keep in Error ajax queue
                        addMarkers( address, 'Errror' );
                        if (index == -1) {
                            errorArray.push( address );
                        }
                    }
        });

    //mentain ajax queue set
        queuCounter++;
        if( queuCounter == setLimit ){
            queuCounter = 0;
        }
    }

  //function get url parameter from url string
    getParameterByName = function ( name,href )
    {
      name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
      var regexS = "[\\?&]"+name+"=([^&#]*)";
      var regex = new RegExp( regexS );
      var results = regex.exec( href );
      if( results == null )
        return "";
      else
        return decodeURIComponent(results[1].replace(/\+/g, " "));
    }

  //call add marker function for each address mention in inputfile.js
    for (var x = 0; x < placesObject.length; x++) {
        var address = placesObject[x]['City'] + ', ' + placesObject[x]['State'];
        addMarkers(address);
    }
});

C - The %x format specifier

From http://en.wikipedia.org/wiki/Printf_format_string

use 0 instead of spaces to pad a field when the width option is specified. For example, printf("%2d", 3) results in " 3", while printf("%02d", 3) results in "03".

How can I create a simple message box in Python?

You can use pyautogui or pymsgbox:

import pyautogui
pyautogui.alert("This is a message box",title="Hello World")

Using pymsgbox is the same as using pyautogui:

import pymsgbox
pymsgbox.alert("This is a message box",title="Hello World")

Cannot authenticate into mongo, "auth fails"

Authentication is managed at a database level. When you try to connect to the system using a database, mongo actually checks for the credentials you provide in the collection <database>.system.users. So, basically when you are trying to connect to "test", it looks for the credentials in test.system.users and returns an error because it cannot find them (as they are stored in admin.system.users). Having the right to read and write from all db doesn't mean you can directly connect to them.

You have to connect to the database holding the credentials first. Try:

mongo admin -u admin -p SECRETPASSWORD

For more info, check this http://docs.mongodb.org/manual/reference/privilege-documents/

How do you get total amount of RAM the computer has?

The Windows API function GlobalMemoryStatusEx can be called with p/invoke:

  [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
  private class MEMORYSTATUSEX
  {
     public uint dwLength;
     public uint dwMemoryLoad;
     public ulong ullTotalPhys;
     public ulong ullAvailPhys;
     public ulong ullTotalPageFile;
     public ulong ullAvailPageFile;
     public ulong ullTotalVirtual;
     public ulong ullAvailVirtual;
     public ulong ullAvailExtendedVirtual;
     public MEMORYSTATUSEX()
     {
        this.dwLength = (uint)Marshal.SizeOf(typeof(NativeMethods.MEMORYSTATUSEX));
     }
  }


  [return: MarshalAs(UnmanagedType.Bool)]
  [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
  static extern bool GlobalMemoryStatusEx([In, Out] MEMORYSTATUSEX lpBuffer);

Then use like:

ulong installedMemory;
MEMORYSTATUSEX memStatus = new MEMORYSTATUSEX();
if( GlobalMemoryStatusEx( memStatus))
{ 
   installedMemory = memStatus.ullTotalPhys;
}

Or you can use WMI (managed but slower) to query TotalPhysicalMemory in the Win32_ComputerSystem class.

How do I install a plugin for vim?

Update (as 2019):

cd ~/.vim
git clone git://github.com/tpope/vim-haml.git pack/bundle/start/haml

Explanation (from :h pack ad :h packages):

  1. All the directories found are added to runtimepath. They must be in ~/.vim/pack/whatever/start [you can only change whatever].
  2. the plugins found in the plugins dir in runtimepath are sourced.

So this load the plugin on start (hence the name start).

You can also get optional plugin (loaded with :packadd) if you put them in ~/.vim/pack/bundle/opt

CSS Selector "(A or B) and C"?

No. Standard CSS does not provide the kind of thing you're looking for.

However, you might want to look into LESS and SASS.

These are two projects which aim to extend default CSS syntax by introducing additional features, including variables, nested rules, and other enhancements.

They allow you to write much more structured CSS code, and either of them will almost certainly solve your particular use case.

Of course, none of the browsers support their extended syntax (especially since the two projects each have different syntax and features), but what they do is provide a "compiler" which converts your LESS or SASS code into standard CSS, which you can then deploy on your site.

How do you connect to a MySQL database using Oracle SQL Developer?

My experience with windows client and linux/mysql server:

When sqldev is used in a windows client and mysql is installed in a linux server meaning, sqldev network access to mysql.

Assuming mysql is already up and running and the databases to be accessed are up and functional:

• Ensure the version of sqldev (32 or 64). If 64 and to avoid dealing with path access copy a valid 64 version of msvcr100.dll into directory ~\sqldeveloper\jdev\bin.

a. Open the file msvcr100.dll in notepad and search for first occurrence of “PE “

 i. “PE  d” it is 64.

ii. “PE  L” it is 32.

b. Note: if sqldev is 64 and msvcr100.dll is 32, the application gets stuck at startup.

• For sqldev to work with mysql there is need of the JDBC jar driver. Download it from mysql site.

a. Driver name = mysql-connector-java-x.x.xx

b. Copy it into someplace related to your sqldeveloper directory.

c. Set it up in menu sqldev Tools/Preferences/Database/Third Party JDBC Driver (add entry)

• In Linux/mysql server change file /etc/mysql/mysql.conf.d/mysqld.cnf look for

bind-address = 127.0.0.1 (this linux localhost)

and change to

bind-address = xxx.xxx.xxx.xxx (this linux server real IP or machine name if DNS is up)

• Enter to linux mysql and grant needed access for example

# mysql –u root -p

GRANT ALL ON . to root@'yourWindowsClientComputerName' IDENTIFIED BY 'mysqlPasswd';

flush privileges;

restart mysql - sudo /etc/init.d/mysql restart

• Start sqldev and create a new connection

a. user = root

b. pass = (your mysql pass)

c. Choose MySql tab

 i.   Hostname = the linux IP hostname

 ii.  Port     = 3306 (default for mysql)

 iii. Choose Database = (from pull down the mysql database you want to use)

 iv.  save and connect

That is all I had to do in my case.

Thank you,

Ale

How to get elements with multiple classes

html

<h2 class="example example2">A heading with class="example"</h2>

javascritp code

var element = document.querySelectorAll(".example.example2");
element.style.backgroundColor = "green";

The querySelectorAll() method returns all elements in the document that matches a specified CSS selector(s), as a static NodeList object.

The NodeList object represents a collection of nodes. The nodes can be accessed by index numbers. The index starts at 0.

also learn more about https://www.w3schools.com/jsref/met_document_queryselectorall.asp

== Thank You ==

iloc giving 'IndexError: single positional indexer is out-of-bounds'

This happens when you index a row/column with a number that is larger than the dimensions of your dataframe. For instance, getting the eleventh column when you have only three.

import pandas as pd

df = pd.DataFrame({'Name': ['Mark', 'Laura', 'Adam', 'Roger', 'Anna'],
                   'City': ['Lisbon', 'Montreal', 'Lisbon', 'Berlin', 'Glasgow'],
                   'Car': ['Tesla', 'Audi', 'Porsche', 'Ford', 'Honda']})

You have 5 rows and three columns:

    Name      City      Car
0   Mark    Lisbon    Tesla
1  Laura  Montreal     Audi
2   Adam    Lisbon  Porsche
3  Roger    Berlin     Ford
4   Anna   Glasgow    Honda

Let's try to index the eleventh column (it doesn't exist):

df.iloc[:, 10] # there is obviously no 11th column

IndexError: single positional indexer is out-of-bounds

If you are a beginner with Python, remember that df.iloc[:, 10] would refer to the eleventh column.

How to set only time part of a DateTime variable in C#

It isn't possible as DateTime is immutable. The same discussion is available here: How to change time in datetime?

How to run a shell script on a Unix console or Mac terminal?

Little addition, to run an interpreter from the same folder, still using #!hashbang in scripts.

As example a php7.2 executable copied from /usr/bin is in a folder along a hello script.

#!./php7.2
<?php

echo "Hello!"; 

To run it:

./hello

Which behave just as equal as:

./php7.2 hello

The proper solutions with good documentation can be the tools linuxdeploy and/or appimage, this is using this method under the hood.

CSS: Set Div height to 100% - Pixels

I'm guessing that you are trying to get sticky footer

git recover deleted file where no commit was made after the delete

Just do git checkout path/to/file-I-want-to-bring-back.txt

Is it possible to set async:false to $.getJSON call

I think you both are right. The later answer works fine but its like setting a global option so you have to do the following:

    $.ajaxSetup({
        async: false
    });

    //ajax call here

    $.ajaxSetup({
        async: true
    });

C++ variable has initializer but incomplete type?

You use a forward declaration when you need a complete type.

You must have a full definition of the class in order to use it.

The usual way to go about this is:

1) create a file Cat_main.h

2) move

#include <string>

class Cat
{
    public:
        Cat(std::string str);
    // Variables
        std::string name;
    // Functions
        void Meow();
};

to Cat_main.h. Note that inside the header I removed using namespace std; and qualified string with std::string.

3) include this file in both Cat_main.cpp and Cat.cpp:

#include "Cat_main.h"

how to convert long date value to mm/dd/yyyy format

Refer Below code which give the date in String form.

import java.text.SimpleDateFormat;
import java.util.Date;



public class Test{

    public static void main(String[] args) {
        long val = 1346524199000l;
        Date date=new Date(val);
        SimpleDateFormat df2 = new SimpleDateFormat("dd/MM/yy");
        String dateText = df2.format(date);
        System.out.println(dateText);
    }
}

Could not load file or assembly 'Newtonsoft.Json, Version=4.5.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed'

I was getting same error and by adding below code error resolved on production.

Answer is too late but might help someone.

    <runtime>
        <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
            <dependentAssembly>
                <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
                <bindingRedirect oldVersion="0.0.0.0-12.0.0.0" newVersion="12.0.0.0" />
            </dependentAssembly>
        </assemblyBinding>
    </runtime>

Get the selected option id with jQuery

You can get it using the :selected selector, like this:

$("#my_select").change(function() {
  var id = $(this).children(":selected").attr("id");
});

Center-align a HTML table

<table align="center"></table>

This works for me.

SDK Manager.exe doesn't work

I fixed this issue by reinstalling it in Program Files, it originally tried to install it in c:/Users/.../AppData/Android/....

Mine was caused by a user permission issue that running as admin didn't seem to fix (perhaps because they call batch files?).

How to fix the error "Windows SDK version 8.1" was not found?

I installed the 8.1 SDK's version:

https://developer.microsoft.com/en-us/windows/downloads/sdk-archive

It used 1GB (a little more) in the installation.


Update October, 9. There's a https error: the sdksetup link is https://go.microsoft.com/fwlink/p/?LinkId=323507

"Save link as" should help.

Get filename from file pointer

You can get the path via fp.name. Example:

>>> f = open('foo/bar.txt')
>>> f.name
'foo/bar.txt'

You might need os.path.basename if you want only the file name:

>>> import os
>>> f = open('foo/bar.txt')
>>> os.path.basename(f.name)
'bar.txt'

File object docs (for Python 2) here.

Does MS SQL Server's "between" include the range boundaries?

I've always used this:

WHERE myDate BETWEEN startDate AND (endDate+1)

What is the best way to manage a user's session in React?

To name a few we can use redux-react-session which is having good API for session management like, initSessionService, refreshFromLocalStorage, checkAuth and many other. It also provide some advanced functionality like Immutable JS.

Alternatively we can leverage react-web-session which provides options like callback and timeout.

Getting a better understanding of callback functions in JavaScript

You can just say

callback();

Alternately you can use the call method if you want to adjust the value of this within the callback.

callback.call( newValueForThis);

Inside the function this would be whatever newValueForThis is.

Combine Points with lines with ggplot2

A small change to Paul's code so that it doesn't return the error mentioned above.

dat = melt(subset(iris, select = c("Sepal.Length","Sepal.Width", "Species")),
           id.vars = "Species")
dat$x <- c(1:150, 1:150)
ggplot(aes(x = x, y = value, color = variable), data = dat) +  
  geom_point() + geom_line()