Programs & Examples On #Vssget

How to set the size of a column in a Bootstrap responsive table

Bootstrap 4.0

Be aware of all migration changes from Bootstrap 3 to 4. On the table you now need to enable flex box by adding the class d-flex, and drop the xs to allow bootstrap to automatically detect the viewport.

<div class="container-fluid">
    <table id="productSizes" class="table">
        <thead>
            <tr class="d-flex">
                <th class="col-1">Size</th>
                <th class="col-3">Bust</th>
                <th class="col-3">Waist</th>
                <th class="col-5">Hips</th>
            </tr>
        </thead>
        <tbody>
            <tr class="d-flex">
                <td class="col-1">6</td>
                <td class="col-3">79 - 81</td>
                <td class="col-3">61 - 63</td>
                <td class="col-5">89 - 91</td>
            </tr>
            <tr class="d-flex">
                <td class="col-1">8</td>
                <td class="col-3">84 - 86</td>
                <td class="col-3">66 - 68</td>
                <td class="col-5">94 - 96</td>
            </tr>
        </tbody>
    </table>

bootply

Bootstrap 3.2

Table column width use the same layout as grids do; using col-[viewport]-[size]. Remember the column sizes should total 12; 1 + 3 + 3 + 5 = 12 in this example.

        <thead>
            <tr>
                <th class="col-xs-1">Size</th>
                <th class="col-xs-3">Bust</th>
                <th class="col-xs-3">Waist</th>
                <th class="col-xs-5">Hips</th>
            </tr>
        </thead>

Remember to set the <th> elements rather than the <td> elements so it sets the whole column. Here is a working BOOTPLY.

Thanks to @Dan for reminding me to always work mobile view (col-xs-*) first.

What is the 'override' keyword in C++ used for?

override is a C++11 keyword which means that a method is an "override" from a method from a base class. Consider this example:

   class Foo
   {
   public:
        virtual void func1();
   }

   class Bar : public Foo
   {
   public:
        void func1() override;
   }

If B::func1() signature doesn't equal A::func1() signature a compilation error will be generated because B::func1() does not override A::func1(), it will define a new method called func1() instead.

Get href attribute on jQuery

var a_href = $('div.cpt').find('h2 a').attr('href');

should be

var a_href = $(this).find('div.cpt').find('h2 a').attr('href');

In the first line, your query searches the entire document. In the second, the query starts from your tr element and only gets the element underneath it. (You can combine the finds if you like, I left them separate to illustrate the point.)

Loading context in Spring using web.xml

You can also load the context while defining the servlet itself (WebApplicationContext)

  <servlet>
    <servlet-name>admin</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>
                /WEB-INF/spring/*.xml
            </param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>admin</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

rather than (ApplicationContext)

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/applicationContext*.xml</param-value>
</context-param>

<listener>
   <listener-class>
        org.springframework.web.context.ContextLoaderListener
   </listener-class>
</listener> 

or can do both together.

Drawback of just using WebApplicationContext is that it will load context only for this particular Spring entry point (DispatcherServlet) where as with above mentioned methods context will be loaded for multiple entry points (Eg. Webservice Servlet, REST servlet etc)

Context loaded by ContextLoaderListener will infact be a parent context to that loaded specifically for DisplacherServlet . So basically you can load all your business service, data access or repository beans in application context and separate out your controller, view resolver beans to WebApplicationContext.

Generate random integers between 0 and 9

I would try one of the following:

1.> numpy.random.randint

import numpy as np
X1 = np.random.randint(low=0, high=10, size=(15,))

print (X1)
>>> array([3, 0, 9, 0, 5, 7, 6, 9, 6, 7, 9, 6, 6, 9, 8])

2.> numpy.random.uniform

import numpy as np
X2 = np.random.uniform(low=0, high=10, size=(15,)).astype(int)

print (X2)
>>> array([8, 3, 6, 9, 1, 0, 3, 6, 3, 3, 1, 2, 4, 0, 4])

3.> numpy.random.choice

import numpy as np
X3 = np.random.choice(a=10, size=15 )

print (X3)
>>> array([1, 4, 0, 2, 5, 2, 7, 5, 0, 0, 8, 4, 4, 0, 9])

4.> random.randrange

from random import randrange
X4 = [randrange(10) for i in range(15)]

print (X4)
>>> [2, 1, 4, 1, 2, 8, 8, 6, 4, 1, 0, 5, 8, 3, 5]

5.> random.randint

from random import randint
X5 = [randint(0, 9) for i in range(0, 15)]

print (X5)
>>> [6, 2, 6, 9, 5, 3, 2, 3, 3, 4, 4, 7, 4, 9, 6]

Speed:

? np.random.uniform and np.random.randint are much faster (~10 times faster) than np.random.choice, random.randrange, random.randint .

%timeit np.random.randint(low=0, high=10, size=(15,))
>> 1.64 µs ± 7.83 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

%timeit np.random.uniform(low=0, high=10, size=(15,)).astype(int)
>> 2.15 µs ± 38.6 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

%timeit np.random.choice(a=10, size=15 )
>> 21 µs ± 629 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

%timeit [randrange(10) for i in range(15)]
>> 12.9 µs ± 60.4 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

%timeit [randint(0, 9) for i in range(0, 15)]
>> 20 µs ± 386 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

Notes:

1.> np.random.randint generates random integers over the half-open interval [low, high).

2.> np.random.uniform generates uniformly distributed numbers over the half-open interval [low, high).

3.> np.random.choice generates a random sample over the half-open interval [low, high) as if the argument a was np.arange(n).

4.> random.randrange(stop) generates a random number from range(start, stop, step).

5.> random.randint(a, b) returns a random integer N such that a <= N <= b.

6.> astype(int) casts the numpy array to int data type.

7.> I have chosen size = (15,). This will give you a numpy array of length = 15.

How do I list all the files in a directory and subdirectories in reverse chronological order?

The command in wfg5475's answer is working properly, just need to add one thing to show only files in a directory & sub directory:

ls -ltraR |egrep -v '\.$|\.\.|\.:|\.\/|total|^d' |sed '/^$/d'

Added one thing: ^d to ignore the all directories from the listing outputs

How to block until an event is fired in c#

If the current method is async then you can use TaskCompletionSource. Create a field that the event handler and the current method can access.

    TaskCompletionSource<bool> tcs = null;

    private async void Button_Click(object sender, RoutedEventArgs e)
    {
        tcs = new TaskCompletionSource<bool>();
        await tcs.Task;
        WelcomeTitle.Text = "Finished work";
    }

    private void Button_Click2(object sender, RoutedEventArgs e)
    {
        tcs?.TrySetResult(true);
    }

This example uses a form that has a textblock named WelcomeTitle and two buttons. When the first button is clicked it starts the click event but stops at the await line. When the second button is clicked the task is completed and the WelcomeTitle text is updated. If you want to timeout as well then change

await tcs.Task;

to

await Task.WhenAny(tcs.Task, Task.Delay(25000));
if (tcs.Task.IsCompleted)
    WelcomeTitle.Text = "Task Completed";
else
    WelcomeTitle.Text = "Task Timed Out";

Undo git update-index --assume-unchanged <file>

I assume (heh) you meant --assume-unchanged, since I don't see any --assume-changed option. The inverse of --assume-unchanged is --no-assume-unchanged.

Where to get "UTF-8" string literal in Java?

Now I use org.apache.commons.lang3.CharEncoding.UTF_8 constant from commons-lang.

jquery-ui-dialog - How to hook into dialog close event

You may try the following code for capturing the closing event for any item : page, dialog etc.

$("#dialog").live('pagehide', function(event, ui) {
      $(this).hide();
});

TypeScript: Property does not exist on type '{}'

Access the field with array notation to avoid strict type checking on single field:

data['propertyName']; //will work even if data has not declared propertyName

Alternative way is (un)cast the variable for single access:

(<any>data).propertyName;//access propertyName like if data has no type

The first is shorter, the second is more explicit about type (un)casting


You can also totally disable type checking on all variable fields:

let untypedVariable:any= <any>{}; //disable type checking while declaring the variable
untypedVariable.propertyName = anyValue; //any field in untypedVariable is assignable and readable without type checking

Note: This would be more dangerous than avoid type checking just for a single field access, since all consecutive accesses on all fields are untyped

Command to run a .bat file

"F:\- Big Packets -\kitterengine\Common\Template.bat" maybe prefaced with call (see call /?). Or Cd /d "F:\- Big Packets -\kitterengine\Common\" & Template.bat.


CMD Cheat Sheet

  • Cmd.exe

  • Getting Help

  • Punctuation

  • Naming Files

  • Starting Programs

  • Keys

CMD.exe

First thing to remember its a way of operating a computer. It's the way we did it before WIMP (Windows, Icons, Mouse, Popup menus) became common. It owes it roots to CPM, VMS, and Unix. It was used to start programs and copy and delete files. Also you could change the time and date.

For help on starting CMD type cmd /?. You must start it with either the /k or /c switch unless you just want to type in it.

Getting Help

For general help. Type Help in the command prompt. For each command listed type help <command> (eg help dir) or <command> /? (eg dir /?).

Some commands have sub commands. For example schtasks /create /?.

The NET command's help is unusual. Typing net use /? is brief help. Type net help use for full help. The same applies at the root - net /? is also brief help, use net help.

References in Help to new behaviour are describing changes from CMD in OS/2 and Windows NT4 to the current CMD which is in Windows 2000 and later.

WMIC is a multipurpose command. Type wmic /?.


Punctuation

&    seperates commands on a line.

&&    executes this command only if previous command's errorlevel is 0.

||    (not used above) executes this command only if previous command's 
errorlevel is NOT 0

>    output to a file

>>    append output to a file

<    input from a file

2> Redirects command error output to the file specified. (0 is StdInput, 1 is StdOutput, and 2 is StdError)

2>&1 Redirects command error output to the same location as command output. 

|    output of one command into the input of another command

^    escapes any of the above, including itself, if needed to be passed 
to a program

"    parameters with spaces must be enclosed in quotes

+ used with copy to concatenate files. E.G. copy file1+file2 newfile

, used with copy to indicate missing parameters. This updates the files 
modified date. E.G. copy /b file1,,

%variablename% a inbuilt or user set environmental variable

!variablename! a user set environmental variable expanded at execution 
time, turned with SelLocal EnableDelayedExpansion command

%<number> (%1) the nth command line parameter passed to a batch file. %0 
is the batchfile's name.

%* (%*) the entire command line.

%CMDCMDLINE% - expands to the original command line that invoked the
Command Processor (from set /?).

%<a letter> or %%<a letter> (%A or %%A) the variable in a for loop. 
Single % sign at command prompt and double % sign in a batch file.

\\ (\\servername\sharename\folder\file.ext) access files and folders via UNC naming.

: (win.ini:streamname) accesses an alternative steam. Also separates drive from rest of path.

. (win.ini) the LAST dot in a file path separates the name from extension

. (dir .\*.txt) the current directory

.. (cd ..) the parent directory


\\?\ (\\?\c:\windows\win.ini) When a file path is prefixed with \\?\ filename checks are turned off. 

Naming Files

< > : " / \ | Reserved characters. May not be used in filenames.



Reserved names. These refer to devices eg, 

copy filename con 

which copies a file to the console window.

CON, PRN, AUX, NUL, COM1, COM2, COM3, COM4, 

COM5, COM6, COM7, COM8, COM9, LPT1, LPT2, 

LPT3, LPT4, LPT5, LPT6, LPT7, LPT8, and LPT9

CONIN$, CONOUT$, CONERR$

--------------------------------

Maximum path length              260 characters
Maximum path length (\\?\)      32,767 characters (approx - some rare characters use 2 characters of storage)
Maximum filename length        255 characters

Starting a Program

See start /? and call /? for help on all three ways.

There are two types of Windows programs - console or non console (these are called GUI even if they don't have one). Console programs attach to the current console or Windows creates a new console. GUI programs have to explicitly create their own windows.

If a full path isn't given then Windows looks in

  1. The directory from which the application loaded.

  2. The current directory for the parent process.

  3. Windows NT/2000/XP: The 32-bit Windows system directory. Use the GetSystemDirectory function to get the path of this directory. The name of this directory is System32.

  4. Windows NT/2000/XP: The 16-bit Windows system directory. There is no function that obtains the path of this directory, but it is searched. The name of this directory is System.

  5. The Windows directory. Use the GetWindowsDirectory function to get the path of this directory.

  6. The directories that are listed in the PATH environment variable.

Specify a program name

This is the standard way to start a program.

c:\windows\notepad.exe

In a batch file the batch will wait for the program to exit. When typed the command prompt does not wait for graphical programs to exit.

If the program is a batch file control is transferred and the rest of the calling batch file is not executed.

Use Start command

Start starts programs in non standard ways.

start "" c:\windows\notepad.exe

Start starts a program and does not wait. Console programs start in a new window. Using the /b switch forces console programs into the same window, which negates the main purpose of Start.

Start uses the Windows graphical shell - same as typing in WinKey + R (Run dialog). Try

start shell:cache

Also program names registered under HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths can also be typed without specifying a full path.

Also note the first set of quotes, if any, MUST be the window title.

Use Call command

Call is used to start batch files and wait for them to exit and continue the current batch file.

Other Filenames

Typing a non program filename is the same as double clicking the file.


Keys

Ctrl + C exits a program without exiting the console window.

For other editing keys type Doskey /?.

  • ? and ? recall commands

  • ESC clears command line

  • F7 displays command history

  • ALT+F7 clears command history

  • F8 searches command history

  • F9 selects a command by number

  • ALT+F10 clears macro definitions

Also not listed

  • Ctrl + ?or? Moves a word at a time

  • Ctrl + Backspace Deletes the previous word

  • Home Beginning of line

  • End End of line

  • Ctrl + End Deletes to end of line

How to fix "unable to open stdio.h in Turbo C" error?

Do this: Open your turboc2 folder you have tc.exe file inside, beside this file you find another file as named as ' tcinst.exe ' open it.

You will see the installation menu:

select as-- > Option > Directory > Include directory

Here you have to change the path of the directory to the path where your INCLUDE folder is located. Same way change the path to library directory also over restart your tc.exe.

Clearing all cookies with JavaScript

I found a problem in IE and Edge. Webkit browsers (Chrome, safari) seem to be more forgiving. When setting cookies, always set the "path" to something, because the default will be the page that set the cookie. So if you try to expire it on a different page without specifying the "path", the path won't match and it won't expire. The document.cookie value doesn't show the path or expiration for a cookie, so you can't derive where the cookie was set by looking at the value.

If you need to expire cookies from different pages, save the path of the setting page in the cookie value so you can pull it out later or always append "; path=/;" to the cookie value. Then it will expire from any page.

error: invalid initialization of non-const reference of type ‘int&’ from an rvalue of type ‘int’

12 is a compile-time constant which can not be changed unlike the data referenced by int&. What you can do is

const int& z = 12;

How do I accomplish an if/else in mustache.js?

Note, you can use {{.}} to render the current context item.

{{#avatar}}{{.}}{{/avatar}}

{{^avatar}}missing{{/avatar}}

Convert a timedelta to days, hours and minutes

I used the following:

delta = timedelta()
totalMinute, second = divmod(delta.seconds, 60)
hour, minute = divmod(totalMinute, 60)
print(f"{hour}h{minute:02}m{second:02}s")

List<Object> and List<?>

List<Object> object = new List<Object>();

You cannot do this because List is an interface and you cannot create object of any interface or in other word you cannot instantiate any interface. Moreover, you can assign any object of class which implements List to its reference variable. For example you can do this:

list<Object> object = new ArrayList<Object>();

Here ArrayList is a class which implements List, you can use any class which implements List.

What's the difference between “mod” and “remainder”?

There is a difference between modulus and remainder. For example:

-21 mod 4 is 3 because -21 + 4 x 6 is 3.

But -21 divided by 4 gives -5 with a remainder of -1.

For positive values, there is no difference.

How do I use Node.js Crypto to create a HMAC-SHA1 hash?

Gwerder's solution wont work because hash = hmac.read(); happens before the stream is done being finalized. Thus AngraX's issues. Also the hmac.write statement is un-necessary in this example.

Instead do this:

var crypto    = require('crypto');
var hmac;
var algorithm = 'sha1';
var key       = 'abcdeg';
var text      = 'I love cupcakes';
var hash;

hmac = crypto.createHmac(algorithm, key);

// readout format:
hmac.setEncoding('hex');
//or also commonly: hmac.setEncoding('base64');

// callback is attached as listener to stream's finish event:
hmac.end(text, function () {
    hash = hmac.read();
    //...do something with the hash...
});

More formally, if you wish, the line

hmac.end(text, function () {

could be written

hmac.end(text, 'utf8', function () {

because in this example text is a utf string

Replacing NULL and empty string within Select statement

Sounds like you want a view instead of altering actual table data.

Coalesce(NullIf(rtrim(Address.Country),''),'United States')

This will force your column to be null if it is actually an empty string (or blank string) and then the coalesce will have a null to work with.

Trim spaces from start and end of string

jQuery.trim(" hello, how are you? ");

:)

How can I print to the same line?

First, I'd like to apologize for bringing this question back up, but I felt that it could use another answer.

Derek Schultz is kind of correct. The '\b' character moves the printing cursor one character backwards, allowing you to overwrite the character that was printed there (it does not delete the entire line or even the character that was there unless you print new information on top). The following is an example of a progress bar using Java though it does not follow your format, it shows how to solve the core problem of overwriting characters (this has only been tested in Ubuntu 12.04 with Oracle's Java 7 on a 32-bit machine, but it should work on all Java systems):

public class BackSpaceCharacterTest
{
    // the exception comes from the use of accessing the main thread
    public static void main(String[] args) throws InterruptedException
    {
        /*
            Notice the user of print as opposed to println:
            the '\b' char cannot go over the new line char.
        */
        System.out.print("Start[          ]");
        System.out.flush(); // the flush method prints it to the screen

        // 11 '\b' chars: 1 for the ']', the rest are for the spaces
        System.out.print("\b\b\b\b\b\b\b\b\b\b\b");
        System.out.flush();
        Thread.sleep(500); // just to make it easy to see the changes

        for(int i = 0; i < 10; i++)
        {
            System.out.print("."); //overwrites a space
            System.out.flush();
            Thread.sleep(100);
        }

        System.out.print("] Done\n"); //overwrites the ']' + adds chars
        System.out.flush();
    }
}

Bootstrap tab activation with JQuery

why not select active tab first then active the selected tab content ?
1. Add class 'active' to the < li > element of tab first .
2. then use set 'active' class to selected div.

    $(document).ready( function(){
        SelectTab(1); //or use other method  to set active class to tab
        ShowInitialTabContent();

    });
    function SelectTab(tabindex)
    {
        $('.nav-tabs li ').removeClass('active');
        $('.nav-tabs li').eq(tabindex).addClass('active'); 
        //tabindex start at 0 
    }
    function FindActiveDiv()
    {  
        var DivName = $('.nav-tabs .active a').attr('href');  
        return DivName;
    }
    function RemoveFocusNonActive()
    {
        $('.nav-tabs  a').not('.active').blur();  
        //to >  remove  :hover :focus;
    }
    function ShowInitialTabContent()
    {
        RemoveFocusNonActive();
        var DivName = FindActiveDiv();
        if (DivName)
        {
            $(DivName).addClass('active'); 
        } 
    }

How to time Java program execution speed

I created a higher order function which takes the code you want to measure in/as a lambda:

class Utils {

    public static <T> T timeIt(String msg, Supplier<T> s) {
        long startTime = System.nanoTime();
        T t = s.get();
        long endTime = System.nanoTime();
        System.out.println(msg + ": " + (endTime - startTime) + " ns");
        return t;
    }

    public static void timeIt(String msg, Runnable r) {
       timeIt(msg, () -> {r.run(); return null; });
    }
}

Call it like that:

Utils.timeIt("code 0", () ->
        System.out.println("Hallo")
);

// in case you need the result of the lambda
int i = Utils.timeIt("code 1", () ->
        5 * 5
);

Output:

code 0: 180528 ns
code 1: 12003 ns

Special thanks to Andy Turner who helped me cut down the redundancy. See here.

How to initialize weights in PyTorch?

If you want some extra flexibility, you can also set the weights manually.

Say you have input of all ones:

import torch
import torch.nn as nn

input = torch.ones((8, 8))
print(input)
tensor([[1., 1., 1., 1., 1., 1., 1., 1.],
        [1., 1., 1., 1., 1., 1., 1., 1.],
        [1., 1., 1., 1., 1., 1., 1., 1.],
        [1., 1., 1., 1., 1., 1., 1., 1.],
        [1., 1., 1., 1., 1., 1., 1., 1.],
        [1., 1., 1., 1., 1., 1., 1., 1.],
        [1., 1., 1., 1., 1., 1., 1., 1.],
        [1., 1., 1., 1., 1., 1., 1., 1.]])

And you want to make a dense layer with no bias (so we can visualize):

d = nn.Linear(8, 8, bias=False)

Set all the weights to 0.5 (or anything else):

d.weight.data = torch.full((8, 8), 0.5)
print(d.weight.data)

The weights:

Out[14]: 
tensor([[0.5000, 0.5000, 0.5000, 0.5000, 0.5000, 0.5000, 0.5000, 0.5000],
        [0.5000, 0.5000, 0.5000, 0.5000, 0.5000, 0.5000, 0.5000, 0.5000],
        [0.5000, 0.5000, 0.5000, 0.5000, 0.5000, 0.5000, 0.5000, 0.5000],
        [0.5000, 0.5000, 0.5000, 0.5000, 0.5000, 0.5000, 0.5000, 0.5000],
        [0.5000, 0.5000, 0.5000, 0.5000, 0.5000, 0.5000, 0.5000, 0.5000],
        [0.5000, 0.5000, 0.5000, 0.5000, 0.5000, 0.5000, 0.5000, 0.5000],
        [0.5000, 0.5000, 0.5000, 0.5000, 0.5000, 0.5000, 0.5000, 0.5000],
        [0.5000, 0.5000, 0.5000, 0.5000, 0.5000, 0.5000, 0.5000, 0.5000]])

All your weights are now 0.5. Pass the data through:

d(input)
Out[13]: 
tensor([[4., 4., 4., 4., 4., 4., 4., 4.],
        [4., 4., 4., 4., 4., 4., 4., 4.],
        [4., 4., 4., 4., 4., 4., 4., 4.],
        [4., 4., 4., 4., 4., 4., 4., 4.],
        [4., 4., 4., 4., 4., 4., 4., 4.],
        [4., 4., 4., 4., 4., 4., 4., 4.],
        [4., 4., 4., 4., 4., 4., 4., 4.],
        [4., 4., 4., 4., 4., 4., 4., 4.]], grad_fn=<MmBackward>)

Remember that each neuron receives 8 inputs, all of which have weight 0.5 and value of 1 (and no bias), so it sums up to 4 for each.

Sequelize OR condition object

Use Sequelize.or:

var condition = {
  where: Sequelize.and(
    { name: 'a project' },
    Sequelize.or(
      { id: [1,2,3] },
      { id: { lt: 10 } }
    )
  )
};

Reference (search for Sequelize.or)

Edit: Also, this has been modified and for the latest method see Morio's answer,

How to get the request parameters in Symfony 2?

public function indexAction(Request $request)
{
   $data = $request->get('corresponding_arg');
   // this also works
   $data1 = $request->query->get('corresponding_arg1');
}

Difference between app.use and app.get in express.js

app.get is called when the HTTP method is set to GET, whereas app.use is called regardless of the HTTP method, and therefore defines a layer which is on top of all the other RESTful types which the express packages gives you access to.

How can I expand and collapse a <div> using javascript?

You might want to give a look at this simple Javascript method to be invoked when clicking on a link to make a panel/div expande or collapse.

<script language="javascript"> 
function toggle(elementId) {
    var ele = document.getElementById(elementId);
    if(ele.style.display == "block") {
            ele.style.display = "none";
    }
    else {
        ele.style.display = "block";
    }
} 
</script>

You can pass the div ID and it will toggle between display 'none' or 'block'.

Original source on snip2code - How to collapse a div in html

Xcode Product -> Archive disabled

Select active scheme to Generic iOs Device.

select to Generic iOs Device

Why is <deny users="?" /> included in the following example?

Example 1 is for asp.net applications using forms authenication. This is common practice for internet applications because user is unauthenticated until it is authentcation against some security module.

Example 2 is for asp.net application using windows authenication. Windows Authentication uses Active Directory to authenticate users. The will prevent access to your application. I use this feature on intranet applications.

How can I detect if a selector returns null?

I like to do something like this:

$.fn.exists = function(){
    return this.length > 0 ? this : false;
}

So then you can do something like this:

var firstExistingElement = 
    $('#iDontExist').exists() ||      //<-returns false;
    $('#iExist').exists() ||          //<-gets assigned to the variable 
    $('#iExistAsWell').exists();      //<-never runs

firstExistingElement.doSomething();   //<-executes on #iExist

http://jsfiddle.net/vhbSG/

Force flushing of output to a file while bash script is still running

well like it or not this is how redirection works.

In your case the output (meaning your script has finished) of your script redirected to that file.

What you want to do is add those redirections in your script.

Get cookie by name

I know it is an old question but I came across this problem too. Just for the record, There is a little API in developers mozilla web page.

Yoy can get any cookie by name using only JS. The code is also cleaner IMHO (except for the long line, that I'm sure you can easily fix).

function getCookie(sKey) {
    if (!sKey) { return null; }
    return decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1")) || null;
}

As stated in the comments be aware that this method assumes that the key and value were encoded using encodeURIComponent(). Remove decode & encodeURIComponent() if the key and value of the cookie were not encoded.

document.getElementByID is not a function

It's getElementById()

Note the lower-case d in Id.

GIT clone repo across local file system in windows

I was successful in doing this using file://, but with one additional slash to denote an absolute path.

git clone file:///cygdrive/c/path/to/repository/

In my case I'm using Git on Cygwin for Windows, which you can see because of the /cygdrive/c part in my paths. With some tweaking to the path it should work with any git installation.

Adding a remote works the same way

git remote add remotename file:///cygdrive/c/path/to/repository/

Print raw string from variable? (not getting the answers)

In general, to make a raw string out of a string variable, I use this:

string = "C:\\Windows\Users\alexb"

raw_string = r"{}".format(string)

output:

'C:\\\\Windows\\Users\\alexb'

string.split - by multiple character delimiter

string tests = "abc][rfd][5][,][.";
string[] reslts = tests.Split(new char[] { ']', '[' }, StringSplitOptions.RemoveEmptyEntries);

How to read a value from the Windows registry

Since Windows >=Vista/Server 2008, RegGetValue is available, which is a safer function than RegQueryValueEx. No need for RegOpenKeyEx, RegCloseKey or NUL termination checks of string values (REG_SZ, REG_MULTI_SZ, REG_EXPAND_SZ).

#include <iostream>
#include <string>
#include <exception>
#include <windows.h>

/*! \brief                          Returns a value from HKLM as string.
    \exception  std::runtime_error  Replace with your error handling.
*/
std::wstring GetStringValueFromHKLM(const std::wstring& regSubKey, const std::wstring& regValue)
{
    size_t bufferSize = 0xFFF; // If too small, will be resized down below.
    std::wstring valueBuf; // Contiguous buffer since C++11.
    valueBuf.resize(bufferSize);
    auto cbData = static_cast<DWORD>(bufferSize * sizeof(wchar_t));
    auto rc = RegGetValueW(
        HKEY_LOCAL_MACHINE,
        regSubKey.c_str(),
        regValue.c_str(),
        RRF_RT_REG_SZ,
        nullptr,
        static_cast<void*>(valueBuf.data()),
        &cbData
    );
    while (rc == ERROR_MORE_DATA)
    {
        // Get a buffer that is big enough.
        cbData /= sizeof(wchar_t);
        if (cbData > static_cast<DWORD>(bufferSize))
        {
            bufferSize = static_cast<size_t>(cbData);
        }
        else
        {
            bufferSize *= 2;
            cbData = static_cast<DWORD>(bufferSize * sizeof(wchar_t));
        }
        valueBuf.resize(bufferSize);
        rc = RegGetValueW(
            HKEY_LOCAL_MACHINE,
            regSubKey.c_str(),
            regValue.c_str(),
            RRF_RT_REG_SZ,
            nullptr,
            static_cast<void*>(valueBuf.data()),
            &cbData
        );
    }
    if (rc == ERROR_SUCCESS)
    {
        cbData /= sizeof(wchar_t);
        valueBuf.resize(static_cast<size_t>(cbData - 1)); // remove end null character
        return valueBuf;
    }
    else
    {
        throw std::runtime_error("Windows system error code: " + std::to_string(rc));
    }
}

int main()
{
    std::wstring regSubKey;
#ifdef _WIN64 // Manually switching between 32bit/64bit for the example. Use dwFlags instead.
    regSubKey = L"SOFTWARE\\WOW6432Node\\Company Name\\Application Name\\";
#else
    regSubKey = L"SOFTWARE\\Company Name\\Application Name\\";
#endif
    std::wstring regValue(L"MyValue");
    std::wstring valueFromRegistry;
    try
    {
        valueFromRegistry = GetStringValueFromHKLM(regSubKey, regValue);
    }
    catch (std::exception& e)
    {
        std::cerr << e.what();
    }
    std::wcout << valueFromRegistry;
}

Its parameter dwFlags supports flags for type restriction, filling the value buffer with zeros on failure (RRF_ZEROONFAILURE) and 32/64bit registry access (RRF_SUBKEY_WOW6464KEY, RRF_SUBKEY_WOW6432KEY) for 64bit programs.

Angular HttpPromise: difference between `success`/`error` methods and `then`'s arguments

.then() is chainable and will wait for previous .then() to resolve.

.success() and .error() can be chained, but they will all fire at once (so not much point to that)

.success() and .error() are just nice for simple calls (easy makers):

$http.post('/getUser').success(function(user){ 
   ... 
})

so you don't have to type this:

$http.post('getUser').then(function(response){
  var user = response.data;
})

But generally i handler all errors with .catch():

$http.get(...)
    .then(function(response){ 
      // successHandler
      // do some stuff
      return $http.get('/somethingelse') // get more data
    })
    .then(anotherSuccessHandler)
    .catch(errorHandler)

If you need to support <= IE8 then write your .catch() and .finally() like this (reserved methods in IE):

    .then(successHandler)
    ['catch'](errorHandler)

Working Examples:

Here's something I wrote in more codey format to refresh my memory on how it all plays out with handling errors etc:

http://jsfiddle.net/nalberg/v95tekz2/

Reinitialize Slick js after successful ajax call

The best way would be to use the unslick setting or function(depending on your version of slick) as stated in the other answers but that did not work for me. I'm getting some errors from slick that seem to be related to this.

What did work for now, however, is removing the slick-initialized and slick-slider classes from the container before reinitializing slick, like so:

function slickCarousel() {
    $('.skills_section').removeClass("slick-initialized slick-slider");
    $('.skills_section').slick({
        infinite: true,
        slidesToShow: 3,
        slidesToScroll: 1
    });
}

Removing the classes doesn't seem to initiate the destroy event(not tested but makes sense) but does cause the later slick() call to behave properly so as long as you don't have any triggers on destroy, you should be good.

SQL Inner Join On Null Values

Basically you want to join two tables together where their QID columns are both not null, correct? However, you aren't enforcing any other conditions, such as that the two QID values (which seems strange to me, but ok). Something as simple as the following (tested in MySQL) seems to do what you want:

SELECT * FROM `Y` INNER JOIN `X` ON (`Y`.`QID` IS NOT NULL AND `X`.`QID` IS NOT NULL);

This gives you every non-null row in Y joined to every non-null row in X.

Update: Rico says he also wants the rows with NULL values, why not just:

SELECT * FROM `Y` INNER JOIN `X`;

Mockito : doAnswer Vs thenReturn

doAnswer and thenReturn do the same thing if:

  1. You are using Mock, not Spy
  2. The method you're stubbing is returning a value, not a void method.

Let's mock this BookService

public interface BookService {
    String getAuthor();
    void queryBookTitle(BookServiceCallback callback);
}

You can stub getAuthor() using doAnswer and thenReturn.

BookService service = mock(BookService.class);
when(service.getAuthor()).thenReturn("Joshua");
// or..
doAnswer(new Answer() {
    @Override
    public Object answer(InvocationOnMock invocation) throws Throwable {
        return "Joshua";
    }
}).when(service).getAuthor();

Note that when using doAnswer, you can't pass a method on when.

// Will throw UnfinishedStubbingException
doAnswer(invocation -> "Joshua").when(service.getAuthor());

So, when would you use doAnswer instead of thenReturn? I can think of two use cases:

  1. When you want to "stub" void method.

Using doAnswer you can do some additionals actions upon method invocation. For example, trigger a callback on queryBookTitle.

BookServiceCallback callback = new BookServiceCallback() {
    @Override
    public void onSuccess(String bookTitle) {
        assertEquals("Effective Java", bookTitle);
    }
};
doAnswer(new Answer() {
    @Override
    public Object answer(InvocationOnMock invocation) throws Throwable {
        BookServiceCallback callback = (BookServiceCallback) invocation.getArguments()[0];
        callback.onSuccess("Effective Java");
        // return null because queryBookTitle is void
        return null;
    }
}).when(service).queryBookTitle(callback);
service.queryBookTitle(callback);
  1. When you are using Spy instead of Mock

When using when-thenReturn on Spy Mockito will call real method and then stub your answer. This can cause a problem if you don't want to call real method, like in this sample:

List list = new LinkedList();
List spy = spy(list);
// Will throw java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
when(spy.get(0)).thenReturn("java");
assertEquals("java", spy.get(0));

Using doAnswer we can stub it safely.

List list = new LinkedList();
List spy = spy(list);
doAnswer(invocation -> "java").when(spy).get(0);
assertEquals("java", spy.get(0));

Actually, if you don't want to do additional actions upon method invocation, you can just use doReturn.

List list = new LinkedList();
List spy = spy(list);
doReturn("java").when(spy).get(0);
assertEquals("java", spy.get(0));

facebook Uncaught OAuthException: An active access token must be used to query information about the current user

Use:

$facebook->api('/'.$facebook_uid)

instead of

$facebook->api('/me')

it works.

How can I pass arguments to anonymous functions in JavaScript?

What you have done is created a new anonymous function that takes a single parameter which then gets assigned to the local variable myMessage inside the function. Since no arguments are actually passed, and arguments which aren't passed a value become null, your function just does alert(null).

Eclipse can't find / load main class

Note: This worked in the past and I received many up votes. Perhaps this is not a solution anymore - but it once was - as the eclipse version was indicated.


Problem

This can also be caused by a Java Build Path Problem.

In my case, I had a an error:

A cycle was detected in the build path of project {project}. The cycle consists of projects {x, y, z}.

This can occur when you include other projects in the build path of the project you wish to run. In fact, all the projects will fail to run with the error Could not find the main class: Example.class


Solution

Open

Windows -> Preferences -> Java-> Compiler -> Building -> Build Path Problems

Uncheck the Abort build when build path errors occur toggle

This seems like a can of worms if you end up with other build path errors I image. So use with caution.


  • Note: This only works if you have a "cycle error". This error message can be found in the "Markers" tab

I found the solution to this here


Info

  • Java 1.8.0_152
  • Eclipse Photon (June 2018)

Dockerfile copy keep subdirectory structure

To merge a local directory into a directory within an image, do this. It will not delete files already present within the image. It will only add files that are present locally, overwriting the files in the image if a file of the same name already exists.

COPY ./files/. /files/

Obtaining only the filename when using OpenFileDialog property "FileName"

Use OpenFileDialog.SafeFileName

OpenFileDialog.SafeFileName Gets the file name and extension for the file selected in the dialog box. The file name does not include the path.

How do I use tools:overrideLibrary in a build.gradle file?

it doesn't matter that you declare your minSdk in build.gradle. You have to copy overrideLibrary in your AndroidManifest.xml, as documented here.

<manifest 
    ... >
<uses-sdk tools:overrideLibrary="com.example.lib1, com.example.lib2"/>
    ...
</manifest>

The system automatically ignores the sdkVersion declared in AndroidManifest.xml.

I hope this solve your problem.

Read line by line in bash script

FILE=test

while read CMD; do
    echo "$CMD"
done < "$FILE"

A redirection with < "$FILE" has a few advantages over cat "$FILE" | while .... It avoids a useless use of cat, saving an unnecessary child process. It also avoids a common pitfall where the loop runs in a subshell. In bash, commands in a | pipeline run in subshells, which means variable assignments are lost after the loop ends. Redirection with < doesn't have that problem, so you could use $CMD after the loop or modify other variables inside the loop. It also, again, avoids unnecessary child processes.

There are some additional improvements that could be made:

  • Add IFS= so that read won't trim leading and trailing whitespace from each line.
  • Add -r to read to prevent from backslashes from being interpreted as escape sequences.
  • Lower case CMD and FILE. The bash convention is only environmental and internal shell variables are uppercase.
  • Use printf in place of echo which is safer if $cmd is a string like -n, which echo would interpret as a flag.
file=test

while IFS= read -r cmd; do
    printf '%s\n' "$cmd"
done < "$file"

Can anyone explain IEnumerable and IEnumerator to me?

An understanding of the Iterator pattern will be helpful for you. I recommend reading the same.

Iterator Pattern

At a high level the iterator pattern can be used to provide a standard way of iterating through collections of any type. We have 3 participants in the iterator pattern, the actual collection (client), the aggregator and the iterator. The aggregate is an interface/abstract class that has a method that returns an iterator. Iterator is an interface/abstract class that has methods allowing us to iterate through a collection.

In order to implement the pattern we first need to implement an iterator to produce a concrete that can iterate over the concerned collection (client) Then the collection (client) implements the aggregator to return an instance of the above iterator.

Here is the UML diagram Iterator Pattern

So basically in c#, IEnumerable is the abstract aggregate and IEnumerator is the abstract Iterator. IEnumerable has a single method GetEnumerator that is responsible for creating an instance of IEnumerator of the desired type. Collections like Lists implement the IEnumerable.

Example. Lets suppose that we have a method getPermutations(inputString) that returns all the permutations of a string and that the method returns an instance of IEnumerable<string>

In order to count the number of permutations we could do something like the below.

 int count = 0;
        var permutations = perm.getPermutations(inputString);
        foreach (string permutation in permutations)
        {
            count++;
        }

The c# compiler more or less converts the above to

using (var permutationIterator = perm.getPermutations(input).GetEnumerator())
        {
            while (permutationIterator.MoveNext())
            {
                count++;
            }
        }

If you have any questions please don't hesitate to ask.

Android canvas draw rectangle

Assuming that "part within rectangle don't have content color" means that you want different fills within the rectangle; you need to draw a rectangle within your rectangle then with stroke width 0 and the desired fill colour(s).

For example:

DrawView.java

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.View;

public class DrawView extends View {
    Paint paint = new Paint();

    public DrawView(Context context) {
        super(context);            
    }

    @Override
    public void onDraw(Canvas canvas) {
        paint.setColor(Color.BLACK);
        paint.setStrokeWidth(3);
        canvas.drawRect(30, 30, 80, 80, paint);
        paint.setStrokeWidth(0);
        paint.setColor(Color.CYAN);
        canvas.drawRect(33, 60, 77, 77, paint );
        paint.setColor(Color.YELLOW);
        canvas.drawRect(33, 33, 77, 60, paint );

    }

}

The activity to start it:

StartDraw.java

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;

public class StartDraw extends Activity {
    DrawView drawView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        drawView = new DrawView(this);
        drawView.setBackgroundColor(Color.WHITE);
        setContentView(drawView);

    }
}

...will turn out this way:

enter image description here

How to modify WooCommerce cart, checkout pages (main theme portion)

I've found this works well as a conditional within page.php that includes the WooCommerce cart and checkout screens.

!is_page(array('cart', 'checkout'))

Take nth column in a text file

If you are using structured data, this has the added benefit of not invoking an extra shell process to run tr and/or cut or something. ...

(Of course, you will want to guard against bad inputs with conditionals and sane alternatives.)

...
while read line ; 
do 
    lineCols=( $line ) ;
    echo "${lineCols[0]}"
    echo "${lineCols[1]}"
done < $myFQFileToRead ; 
...

String.Format for Hex

Translate composed UInt32 color Value to CSS in .NET

I know the question applies to 3 input values (red green blue). But there may be the situation where you already have a composed 32bit Value. It looks like you want to send the data to some HTML CSS renderer (because of the #HEX format). Actually CSS wants you to print 6 or at least 3 zero filled hex digits here. so #{0:X06} or #{0:X03} would be required. Due to some strange behaviour, this always prints 8 digits instead of 6.

Solve this by:

String.Format("#{0:X02}{1:X02}{2:X02}", (Value & 0x00FF0000) >> 16, (Value & 0x0000FF00) >> 8, (Value & 0x000000FF) >> 0)

What is the purpose of "pip install --user ..."?

Other answers mention site.USER_SITE as where Python packages get placed. If you're looking for binaries, these go in {site.USER_BASE}/bin.

If you want to add this directory to your shell's search path, use:

export PATH="${PATH}:$(python3 -c 'import site; print(site.USER_BASE)')/bin"

Can anyone explain me StandardScaler?

After applying StandardScaler(), each column in X will have mean of 0 and standard deviation of 1.

Formulas are listed by others on this page.

Rationale: some algorithms require data to look like this (see sklearn docs).

Twitter Bootstrap onclick event on buttons-radio

For Bootstrap 3 the default radio/button-group structure is :

<div class="btn-group" data-toggle="buttons">
    <label class="btn btn-primary">
        <input type="radio" name="options" id="option1"> Option 1
    </label>
    <label class="btn btn-primary">
        <input type="radio" name="options" id="option2"> Option 2
    </label>
    <label class="btn btn-primary">
        <input type="radio" name="options" id="option3"> Option 3
    </label>
</div>

And you can select the active one like this:

$('.btn-primary').on('click', function(){
    alert($(this).find('input').attr('id'));
}); 

laravel Unable to prepare route ... for serialization. Uses Closure

the solustion when we use routes like this:

Route::get('/', function () {
    return view('welcome');
});

laravel call them Closure so you cant optimize routes uses as Closures you must route to controller to use php artisan optimize

How store a range from excel into a Range variable?

When you use a Range object, you cannot simply use the following syntax:

Dim myRange as Range
myRange = Range("A1")  

You must use the set keyword to assign Range objects:

Function getData(currentWorksheet As Worksheet, dataStartRow As Integer, dataEndRow As Integer, DataStartCol As Integer, dataEndCol As Integer)

    Dim dataTable As Range
    Set dataTable = currentWorksheet.Range(currentWorksheet.Cells(dataStartRow, DataStartCol), currentWorksheet.Cells(dataEndRow, dataEndCol))

    Set getData = dataTable

End Function

Sub main()
    Dim test As Range

    Set test = getData(ActiveSheet, 1, 3, 2, 5)
    test.select

End Sub

Note that every time a range is declared I use the Set keyword.


You can also allow your getData function to return a Range object instead of a Variant although this is unrelated to the problem you are having.

How do I populate a JComboBox with an ArrayList?

Elegant way to fill combo box with an array list :

List<String> ls = new ArrayList<String>(); 
jComboBox.setModel(new DefaultComboBoxModel<String>(ls.toArray(new String[0])));

Exception Error c0000005 in VC++

Exception code c0000005 is the code for an access violation. That means that your program is accessing (either reading or writing) a memory address to which it does not have rights. Most commonly this is caused by:

  • Accessing a stale pointer. That is accessing memory that has already been deallocated. Note that such stale pointer accesses do not always result in access violations. Only if the memory manager has returned the memory to the system do you get an access violation.
  • Reading off the end of an array. This is when you have an array of length N and you access elements with index >=N.

To solve the problem you'll need to do some debugging. If you are not in a position to get the fault to occur under your debugger on your development machine you should get a crash dump file and load it into your debugger. This will allow you to see where in the code the problem occurred and hopefully lead you to the solution. You'll need to have the debugging symbols associated with the executable in order to see meaningful stack traces.

Angular 2 @ViewChild annotation returns undefined

In my case, I had an input variable setter using the ViewChild, and the ViewChild was inside of an *ngIf directive, so the setter was trying to access it before the *ngIf rendered (it would work fine without the *ngIf, but would not work if it was always set to true with *ngIf="true").

To solve, I used Rxjs to make sure any reference to the ViewChild waited until the view was initiated. First, create a Subject that completes when after view init.

export class MyComponent implements AfterViewInit {
  private _viewInitWaiter$ = new Subject();

  ngAfterViewInit(): void {
    this._viewInitWaiter$.complete();
  }
}

Then, create a function that takes and executes a lambda after the subject completes.

private _executeAfterViewInit(func: () => any): any {
  this._viewInitWaiter$.subscribe(null, null, () => {
    return func();
  })
}

Finally, make sure references to the ViewChild use this function.

@Input()
set myInput(val: any) {
    this._executeAfterViewInit(() => {
        const viewChildProperty = this.viewChild.someProperty;
        ...
    });
}

@ViewChild('viewChildRefName', {read: MyViewChildComponent}) viewChild: MyViewChildComponent;

How can I copy a file on Unix using C?

There is no need to either call non-portable APIs like sendfile, or shell out to external utilities. The same method that worked back in the 70s still works now:

#include <fcntl.h>
#include <unistd.h>
#include <errno.h>

int cp(const char *to, const char *from)
{
    int fd_to, fd_from;
    char buf[4096];
    ssize_t nread;
    int saved_errno;

    fd_from = open(from, O_RDONLY);
    if (fd_from < 0)
        return -1;

    fd_to = open(to, O_WRONLY | O_CREAT | O_EXCL, 0666);
    if (fd_to < 0)
        goto out_error;

    while (nread = read(fd_from, buf, sizeof buf), nread > 0)
    {
        char *out_ptr = buf;
        ssize_t nwritten;

        do {
            nwritten = write(fd_to, out_ptr, nread);

            if (nwritten >= 0)
            {
                nread -= nwritten;
                out_ptr += nwritten;
            }
            else if (errno != EINTR)
            {
                goto out_error;
            }
        } while (nread > 0);
    }

    if (nread == 0)
    {
        if (close(fd_to) < 0)
        {
            fd_to = -1;
            goto out_error;
        }
        close(fd_from);

        /* Success! */
        return 0;
    }

  out_error:
    saved_errno = errno;

    close(fd_from);
    if (fd_to >= 0)
        close(fd_to);

    errno = saved_errno;
    return -1;
}

How to find schema name in Oracle ? when you are connected in sql session using read only user

How about the following 3 statements?

-- change to your schema

ALTER SESSION SET CURRENT_SCHEMA=yourSchemaName;

-- check current schema

SELECT SYS_CONTEXT('USERENV','CURRENT_SCHEMA') FROM DUAL;

-- generate drop table statements

SELECT 'drop table ', table_name, 'cascade constraints;' FROM ALL_TABLES WHERE OWNER = 'yourSchemaName';

COPY the RESULT and PASTE and RUN.

Postgres user does not exist?

For me This was the solution on macOS ReInstall the psql

brew install postgres

Start PostgreSQL server

pg_ctl -D /usr/local/var/postgres start

Initialize DB

initdb /usr/local/var/postgres

If this command throws an error the rm the old database file and re-run the above command

rm -r /usr/local/var/postgres

Create a new database

createdb postgres_test
psql -W postegres_test

You will be logged into this db and can create a user in here to login

Turn off enclosing <p> tags in CKEditor 3.0

Found it!

ckeditor.js line #91 ... search for

B.config.enterMode==3?'div':'p'

change to

B.config.enterMode==3?'div':'' (NO P!)

Dump your cache and BAM!

Twitter Bootstrap 3: How to center a block

center-block can be found in bootstrap 3.0 in utilities.less on line 12 and mixins.less on line 39

How to redirect from one URL to another URL?

window.location.href = "URL2"

inside a JS block on the page or in an included file; that's assuming you really want to do it on the client. Usually, the server sends the redirect via a 300-series response.

Pythonic way to add datetime.date and datetime.time objects

It's in the python docs.

import datetime
datetime.datetime.combine(datetime.date(2011, 1, 1), 
                          datetime.time(10, 23))

returns

datetime.datetime(2011, 1, 1, 10, 23)

How do I move a file from one location to another in Java?

myFile.renameTo(new File("/the/new/place/newName.file"));

File#renameTo does that (it can not only rename, but also move between directories, at least on the same file system).

Renames the file denoted by this abstract pathname.

Many aspects of the behavior of this method are inherently platform-dependent: The rename operation might not be able to move a file from one filesystem to another, it might not be atomic, and it might not succeed if a file with the destination abstract pathname already exists. The return value should always be checked to make sure that the rename operation was successful.

If you need a more comprehensive solution (such as wanting to move the file between disks), look at Apache Commons FileUtils#moveFile

li:before{ content: "¦"; } How to Encode this Special Character as a Bullit in an Email Stationery?

You ca try this:

ul { list-style: none;}

li { position: relative;}

li:before {
    position: absolute;  
    top: 8px;  
    margin: 8px 0 0 -12px;    
    vertical-align: middle;
    display: inline-block;
    width: 4px;
    height: 4px;
    background: #ccc;
    content: "";
}

It worked for me, thanks to this post.

Using if-else in JSP

Instead of if-else condition use if in both conditions. it will work that way but not sure why.

How can git be installed on CENTOS 5.5?

I'm sure this question is about to die now that RHEL 5 is nearing end of life, but the answer seems to have gotten a lot simpler now:

sudo yum install epel-release
sudo yum install git

worked for me on a fresh install of CentOS 5.11.

How to show code but hide output in RMarkdown?

For muting library("name_of_library") codes, meanly just showing the codes, {r loadlib, echo=T, results='hide', message=F, warning=F} is great. And imho a better way than library(package, warn.conflicts=F, quietly=T)

How do I reverse a C++ vector?

You can also use std::list instead of std::vector. list has a built-in function list::reverse for reversing elements.

Android - SMS Broadcast receiver

For android 19+ you can get it in Telephony.Sms.Intents.SMS_RECEIVED_ACTION). There are more in the Intents class that 're worth looking at

What does it mean to bind a multicast (UDP) socket?

Correction for What does it mean to bind a multicast (udp) socket? as long as it partially true at the following quote:

The "bind" operation is basically saying, "use this local UDP port for sending and receiving data. In other words, it allocates that UDP port for exclusive use for your application

There is one exception. Multiple applications can share the same port for listening (usually it has practical value for multicast datagrams), if the SO_REUSEADDR option applied. For example

int sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); // create UDP socket somehow
...
int set_option_on = 1;
// it is important to do "reuse address" before bind, not after
int res = setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char*) &set_option_on, 
    sizeof(set_option_on));
res = bind(sock, src_addr, len);

If several processes did such "reuse binding", then every UDP datagram received on that shared port will be delivered to each of the processes (providing natural joint with multicasts traffic).

Here are further details regarding what happens in a few cases:

  1. attempt of any bind ("exclusive" or "reuse") to free port will be successful

  2. attempt to "exclusive binding" will fail if the port is already "reuse-binded"

  3. attempt to "reuse binding" will fail if some process keeps "exclusive binding"

CSS : center form in page horizontally and vertically

If you want to do a horizontal centering, just put the form inside a DIV tag and apply align="center" attribute to it. So even if the form width is changed, your centering will remain the same.

<div align="center"><form id="form_login"><!--form content here--></form></div>

UPDATE

@G-Cyr is right. align="center" attribute is now obsolete. You can use text-align attribute for this as following.

<div style="text-align:center"><form id="form_login"><!--form content here--></form></div>

This will center all the content inside the parent DIV. An optional way is to use margin: auto CSS attribute with predefined widths and heights. Please follow the following thread for more information.

How to horizontally center a in another ?

Vertical centering is little difficult than that. To do that, you can do the following stuff.

html

<body>
<div id="parent">
    <form id="form_login">
     <!--form content here-->
    </form>
</div>
</body>

Css

#parent {
   display: table;
   width: 100%;
}
#form_login {
   display: table-cell;
   text-align: center;
   vertical-align: middle;
}

Rails: How to run `rails generate scaffold` when the model already exists?

Great answer by Lee Jarvis, this is just the command e.g; we already have an existing model called User:

rails g scaffold_controller User

How to add fixed button to the bottom right of page

This will be helpful for the right bottom rounded button

HTML :

      <a class="fixedButton" href>
         <div class="roundedFixedBtn"><i class="fa fa-phone"></i></div>
      </a>
    

CSS:

       .fixedButton{
            position: fixed;
            bottom: 0px;
            right: 0px; 
            padding: 20px;
        }
        .roundedFixedBtn{
          height: 60px;
          line-height: 80px;  
          width: 60px;  
          font-size: 2em;
          font-weight: bold;
          border-radius: 50%;
          background-color: #4CAF50;
          color: white;
          text-align: center;
          cursor: pointer;
        }
    

Here is jsfiddle link http://jsfiddle.net/vpthcsx8/11/

How to create an infinite loop in Windows batch file?

read help GOTO

and try

:again
do it
goto again

Awaiting multiple Tasks with different results

Given three tasks - FeedCat(), SellHouse() and BuyCar(), there are two interesting cases: either they all complete synchronously (for some reason, perhaps caching or an error), or they don't.

Let's say we have, from the question:

Task<string> DoTheThings() {
    Task<Cat> x = FeedCat();
    Task<House> y = SellHouse();
    Task<Tesla> z = BuyCar();
    // what here?
}

Now, a simple approach would be:

Task.WhenAll(x, y, z);

but ... that isn't convenient for processing the results; we'd typically want to await that:

async Task<string> DoTheThings() {
    Task<Cat> x = FeedCat();
    Task<House> y = SellHouse();
    Task<Tesla> z = BuyCar();

    await Task.WhenAll(x, y, z);
    // presumably we want to do something with the results...
    return DoWhatever(x.Result, y.Result, z.Result);
}

but this does lots of overhead and allocates various arrays (including the params Task[] array) and lists (internally). It works, but it isn't great IMO. In many ways it is simpler to use an async operation and just await each in turn:

async Task<string> DoTheThings() {
    Task<Cat> x = FeedCat();
    Task<House> y = SellHouse();
    Task<Tesla> z = BuyCar();

    // do something with the results...
    return DoWhatever(await x, await y, await z);
}

Contrary to some of the comments above, using await instead of Task.WhenAll makes no difference to how the tasks run (concurrently, sequentially, etc). At the highest level, Task.WhenAll predates good compiler support for async/await, and was useful when those things didn't exist. It is also useful when you have an arbitrary array of tasks, rather than 3 discreet tasks.

But: we still have the problem that async/await generates a lot of compiler noise for the continuation. If it is likely that the tasks might actually complete synchronously, then we can optimize this by building in a synchronous path with an asynchronous fallback:

Task<string> DoTheThings() {
    Task<Cat> x = FeedCat();
    Task<House> y = SellHouse();
    Task<Tesla> z = BuyCar();

    if(x.Status == TaskStatus.RanToCompletion &&
       y.Status == TaskStatus.RanToCompletion &&
       z.Status == TaskStatus.RanToCompletion)
        return Task.FromResult(
          DoWhatever(a.Result, b.Result, c.Result));
       // we can safely access .Result, as they are known
       // to be ran-to-completion

    return Awaited(x, y, z);
}

async Task Awaited(Task<Cat> a, Task<House> b, Task<Tesla> c) {
    return DoWhatever(await x, await y, await z);
}

This "sync path with async fallback" approach is increasingly common especially in high performance code where synchronous completions are relatively frequent. Note it won't help at all if the completion is always genuinely asynchronous.

Additional things that apply here:

  1. with recent C#, a common pattern is for the async fallback method is commonly implemented as a local function:

    Task<string> DoTheThings() {
        async Task<string> Awaited(Task<Cat> a, Task<House> b, Task<Tesla> c) {
            return DoWhatever(await a, await b, await c);
        }
        Task<Cat> x = FeedCat();
        Task<House> y = SellHouse();
        Task<Tesla> z = BuyCar();
    
        if(x.Status == TaskStatus.RanToCompletion &&
           y.Status == TaskStatus.RanToCompletion &&
           z.Status == TaskStatus.RanToCompletion)
            return Task.FromResult(
              DoWhatever(a.Result, b.Result, c.Result));
           // we can safely access .Result, as they are known
           // to be ran-to-completion
    
        return Awaited(x, y, z);
    }
    
  2. prefer ValueTask<T> to Task<T> if there is a good chance of things ever completely synchronously with many different return values:

    ValueTask<string> DoTheThings() {
        async ValueTask<string> Awaited(ValueTask<Cat> a, Task<House> b, Task<Tesla> c) {
            return DoWhatever(await a, await b, await c);
        }
        ValueTask<Cat> x = FeedCat();
        ValueTask<House> y = SellHouse();
        ValueTask<Tesla> z = BuyCar();
    
        if(x.IsCompletedSuccessfully &&
           y.IsCompletedSuccessfully &&
           z.IsCompletedSuccessfully)
            return new ValueTask<string>(
              DoWhatever(a.Result, b.Result, c.Result));
           // we can safely access .Result, as they are known
           // to be ran-to-completion
    
        return Awaited(x, y, z);
    }
    
  3. if possible, prefer IsCompletedSuccessfully to Status == TaskStatus.RanToCompletion; this now exists in .NET Core for Task, and everywhere for ValueTask<T>

asp.net Button OnClick event not firing

In the case of nesting the LinkButton within a Repeater you must using something similar to the following:

<asp:LinkButton ID="LinkButton1" runat="server" CommandName="MyUpdate">LinkButton</asp:LinkButton>

 protected void Repeater1_OnItemCommand(object source, RepeaterCommandEventArgs e)
 {
    if (e.CommandName.Equals("MyUpdate"))
    {
        // some code
    }
 }

Swift Alamofire: How to get the HTTP response status code

Or use pattern matching

if let error = response.result.error as? AFError {
   if case .responseValidationFailed(.unacceptableStatusCode(let code)) = error {
       print(code)
   }
}

Using arrays or std::vectors in C++, what's the performance gap?

Preamble for micro-optimizer people

Remember:

"Programmers waste enormous amounts of time thinking about, or worrying about, the speed of noncritical parts of their programs, and these attempts at efficiency actually have a strong negative impact when debugging and maintenance are considered. We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil. Yet we should not pass up our opportunities in that critical 3%".

(Thanks to metamorphosis for the full quote)

Don't use a C array instead of a vector (or whatever) just because you believe it's faster as it is supposed to be lower-level. You would be wrong.

Use by default vector (or the safe container adapted to your need), and then if your profiler says it is a problem, see if you can optimize it, either by using a better algorithm, or changing container.

This said, we can go back to the original question.

Static/Dynamic Array?

The C++ array classes are better behaved than the low-level C array because they know a lot about themselves, and can answer questions C arrays can't. They are able to clean after themselves. And more importantly, they are usually written using templates and/or inlining, which means that what appears to a lot of code in debug resolves to little or no code produced in release build, meaning no difference with their built-in less safe competition.

All in all, it falls on two categories:

Dynamic arrays

Using a pointer to a malloc-ed/new-ed array will be at best as fast as the std::vector version, and a lot less safe (see litb's post).

So use a std::vector.

Static arrays

Using a static array will be at best:

  • as fast as the std::array version
  • and a lot less safe.

So use a std::array.

Uninitialized memory

Sometimes, using a vector instead of a raw buffer incurs a visible cost because the vector will initialize the buffer at construction, while the code it replaces didn't, as remarked bernie by in his answer.

If this is the case, then you can handle it by using a unique_ptr instead of a vector or, if the case is not exceptional in your codeline, actually write a class buffer_owner that will own that memory, and give you easy and safe access to it, including bonuses like resizing it (using realloc?), or whatever you need.

define a List like List<int,string>?

For that, you could use a Dictionary where the int is the key.

new Dictionary<int, string>();

If you really want to use a list, it could be a List<Tuple<int,string>>() but, Tuple class is readonly, so you have to recreate the instance to modifie it.

Prepend line to beginning of a file

To put code to NPE's answer, I think the most efficient way to do this is:

def insert(originalfile,string):
    with open(originalfile,'r') as f:
        with open('newfile.txt','w') as f2: 
            f2.write(string)
            f2.write(f.read())
    os.rename('newfile.txt',originalfile)

Module 'tensorflow' has no attribute 'contrib'

I used tensorflow 1.8 to train my model and there is no problem for now. Tensorflow 2.0 alpha is not suitable with object detection API

Can I use return value of INSERT...RETURNING in another INSERT?

In line with the answer given by Denis de Bernardy..

If you want id to be returned afterwards as well and want to insert more things into Table2:

with rows as (
INSERT INTO Table1 (name) VALUES ('a_title') RETURNING id
)
INSERT INTO Table2 (val, val2, val3)
SELECT id, 'val2value', 'val3value'
FROM rows
RETURNING val

Hide console window from Process.Start C#

This doesn't show the window:

Process cmd = new Process();
cmd.StartInfo.FileName = "cmd.exe";
cmd.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
cmd.StartInfo.CreateNoWindow = true;

...
cmd.Start();

Create MSI or setup project with Visual Studio 2012

Microsoft has listened to the cry for supporting installers (MSI) in Visual Studio and released the Visual Studio Installer Projects Extension. You can now create installers in Visual Studio 2013; download the extension here from the visualstudiogallery.

SQL Server 2008 - IF NOT EXISTS INSERT ELSE UPDATE

At first glance your original attempt seems pretty close. I'm assuming that clockDate is a DateTime fields so try this:

IF (NOT EXISTS(SELECT * FROM Clock WHERE cast(clockDate as date) = '08/10/2012') 
    AND userName = 'test') 
BEGIN 
    INSERT INTO Clock(clockDate, userName, breakOut) 
    VALUES(GetDate(), 'test', GetDate()) 
END 
ELSE 
BEGIN 
    UPDATE Clock 
    SET breakOut = GetDate()
    WHERE Cast(clockDate AS Date) = '08/10/2012' AND userName = 'test'
END 

Note that getdate gives you the current date. If you are trying to compare to a date (without the time) you need to cast or the time element will cause the compare to fail.


If clockDate is NOT datetime field (just date), then the SQL engine will do it for you - no need to cast on a set/insert statement.

IF (NOT EXISTS(SELECT * FROM Clock WHERE clockDate = '08/10/2012') 
    AND userName = 'test') 
BEGIN 
    INSERT INTO Clock(clockDate, userName, breakOut) 
    VALUES(GetDate(), 'test', GetDate()) 
END 
ELSE 
BEGIN 
    UPDATE Clock 
    SET breakOut = GetDate()
    WHERE clockDate = '08/10/2012' AND userName = 'test'
END 

As others have pointed out, the merge statement is another way to tackle this same logic. However, in some cases, especially with large data sets, the merge statement can be prohibitively slow, causing a lot of tran log activity. So knowing how to logic it out as shown above is still a valid technique.

Count unique values in a column in Excel

Here’s another quickie way to get the unique value count, as well as to get the unique values. Copy the column you care about into another worksheet, then select the entire column. Click on Data -> Remove Duplicates -> OK. This removes all duplicated values.

Plotting histograms from grouped data in a pandas DataFrame

I write this answer because I was looking for a way to plot together the histograms of different groups. What follows is not very smart, but it works fine for me. I use Numpy to compute the histogram and Bokeh for plotting. I think it is self-explanatory, but feel free to ask for clarifications and I'll be happy to add details (and write it better).

figures = {
    'Transit': figure(title='Transit', x_axis_label='speed [km/h]', y_axis_label='frequency'),
    'Driving': figure(title='Driving', x_axis_label='speed [km/h]', y_axis_label='frequency')
}

cols = {'Vienna': 'red', 'Turin': 'blue', 'Rome': 'Orange'}
for gr in df_trips.groupby(['locality', 'means']):
    locality = gr[0][0]
    means = gr[0][1]
    fig = figures[means]
    h, b = np.histogram(pd.DataFrame(gr[1]).speed.values)
    fig.vbar(x=b[1:], top=h, width=(b[1]-b[0]), legend_label=locality, fill_color=cols[locality], alpha=0.5)

show(gridplot([
    [figures['Transit']],
    [figures['Driving']],
]))

Laravel Pagination links not including other GET parameters

Pass the page number for pagination as well. Some thing like this

_x000D_
_x000D_
$currentPg = Input::get('page') ? Input::get('page') : '1';_x000D_
    $boards = Cache::remember('boards'.$currentPg, 60, function(){ return WhatEverModel::paginate(15); });
_x000D_
_x000D_
_x000D_

Why do we need virtual functions in C++?

You need at least 1 level of inheritance and an upcast to demonstrate it. Here is a very simple example:

class Animal
{        
    public: 
      // turn the following virtual modifier on/off to see what happens
      //virtual   
      std::string Says() { return "?"; }  
};

class Dog: public Animal
{
    public: std::string Says() { return "Woof"; }
};

void test()
{
    Dog* d = new Dog();
    Animal* a = d;       // refer to Dog instance with Animal pointer

    std::cout << d->Says();   // always Woof
    std::cout << a->Says();   // Woof or ?, depends on virtual
}

Why is SQL server throwing this error: Cannot insert the value NULL into column 'id'?

In my case,

I was trying to update my model by making a foreign key required, but the database had "null" data in it already in some columns from previously entered data. So every time i run update-database...i got the error.

I SOLVED it by manually deleting from the database all rows that had null in the column i was making required.

Index was outside the bounds of the Array. (Microsoft.SqlServer.smo)

The Reason behind the error message is that SQL couldn't show new features in your old SQL server version.

Please upgrade your client SQL version to same as your server Sql version

How to check permissions of a specific directory?

Here is the short answer:

$ ls -ld directory

Here's what it does:

-d, --directory
    list directory entries instead of contents, and do not dereference symbolic links

You might be interested in manpages. That's where all people in here get their nice answers from.

refer to online man pages

How do I get the resource id of an image if I know its name?

Example for a public system resource:

// this will get id for android.R.drawable.ic_dialog_alert
int id = Resources.getSystem().getIdentifier("ic_dialog_alert", "drawable", "android");

alert

Another way is to refer the documentation for android.R.drawable class.

How do I print a double value with full precision using cout?

IEEE 754 floating point values are stored using base 2 representation. Any base 2 number can be represented as a decimal (base 10) to full precision. None of the proposed answers, however, do. They all truncate the decimal value.

This seems to be due to a misinterpretation of what std::numeric_limits<T>::max_digits10 represents:

The value of std::numeric_limits<T>::max_digits10 is the number of base-10 digits that are necessary to uniquely represent all distinct values of the type T.

In other words: It's the (worst-case) number of digits required to output if you want to roundtrip from binary to decimal to binary, without losing any information. If you output at least max_digits10 decimals and reconstruct a floating point value, you are guaranteed to get the exact same binary representation you started with.

What's important: max_digits10 in general neither yields the shortest decimal, nor is it sufficient to represent the full precision. I'm not aware of a constant in the C++ Standard Library that encodes the maximum number of decimal digits required to contain the full precision of a floating point value. I believe it's something like 767 for doubles1. One way to output a floating point value with full precision would be to use a sufficiently large value for the precision, like so2, and have the library strip any trailing zeros:

#include <iostream>

int main() {
    double d = 0.1;
    std::cout.precision(767);
    std::cout << "d = " << d << std::endl;
}

This produces the following output, that contains the full precision:

d = 0.1000000000000000055511151231257827021181583404541015625

Note that this has significantly more decimals than max_digits10 would suggest.


While that answers the question that was asked, a far more common goal would be to get the shortest decimal representation of any given floating point value, that retains all information. Again, I'm not aware of any way to instruct the Standard I/O library to output that value. Starting with C++17 the possibility to do that conversion has finally arrived in C++ in the form of std::to_chars. By default, it produces the shortest decimal representation of any given floating point value that retains the entire information.

Its interface is a bit clunky, and you'd probably want to wrap this up into a function template that returns something you can output to std::cout (like a std::string), e.g.

#include <charconv>
#include <array>
#include <string>
#include <system_error>

#include <iostream>
#include <cmath>

template<typename T>
std::string to_string(T value)
{
    // 24 characters is the longest decimal representation of any double value
    std::array<char, 24> buffer {};
    auto const res { std::to_chars(buffer.data(), buffer.data() + buffer.size(), value) };
    if (res.ec == std::errc {})
    {
        // Success
        return std::string(buffer.data(), res.ptr);
    }

    // Error
    return { "FAILED!" };
}

int main()
{
    auto value { 0.1f };
    std::cout << to_string(value) << std::endl;
    value = std::nextafter(value, INFINITY);
    std::cout << to_string(value) << std::endl;
    value = std::nextafter(value, INFINITY);
    std::cout << to_string(value) << std::endl;
}

This would print out (using Microsoft's C++ Standard Library):

0.1
0.10000001
0.10000002

1 From Stephan T. Lavavej's CppCon 2019 talk titled Floating-Point <charconv>: Making Your Code 10x Faster With C++17's Final Boss. (The entire talk is worth watching.)

2 This would also require using a combination of scientific and fixed, whichever is shorter. I'm not aware of a way to set this mode using the C++ Standard I/O library.

Cloning specific branch

Please try like this : git clone --single-branch --branch <branchname> <url>

replace <branchname> with your branch and <url> with your url.

url will be like http://[email protected]:portno/yourrepo.git.

Position DIV relative to another DIV?

You want to use position: absolute while inside the other div.

DEMO

How to convert DataTable to class Object?

Is it very expensive to do this by json convert? But at least you have a 2 line solution and its generic. It does not matter eather if your datatable contains more or less fields than the object class:

Dim sSql = $"SELECT '{jobID}' AS ConfigNo, 'MainSettings' AS ParamName, VarNm AS ParamFieldName, 1 AS ParamSetId, Val1 AS ParamValue FROM StrSVar WHERE NmSp = '{sAppName} Params {jobID}'"
            Dim dtParameters As DataTable = DBLib.GetDatabaseData(sSql)

            Dim paramListObject As New List(Of ParameterListModel)()

            If (Not dtParameters Is Nothing And dtParameters.Rows.Count > 0) Then
                Dim json = Newtonsoft.Json.JsonConvert.SerializeObject(dtParameters).ToString()

                paramListObject = Newtonsoft.Json.JsonConvert.DeserializeObject(Of List(Of ParameterListModel))(json)
            End If

Setting public class variables

Use Constructors.

<?php
class TestClass
{
    public $testVar = "default value";
    public function __construct($varValue)
    {
       $this->testVar = $varValue;               
    }
}    
$object = new TestClass('another value');
print $object->testVar;
?>

PDO Prepared Inserts multiple rows in single query

This worked for me

$sql = 'INSERT INTO table(pk_pk1,pk_pk2,date,pk_3) VALUES '; 
$qPart = array_fill(0, count($array), "(?, ?,UTC_TIMESTAMP(),?)");
$sql .= implode(",", $qPart);
$stmt =    DB::prepare('base', $sql);
$i = 1;
foreach ($array as $value) { 
  $stmt->bindValue($i++, $value);
  $stmt->bindValue($i++, $pk_pk1);
  $stmt->bindValue($i++, $pk_pk2); 
  $stmt->bindValue($i++, $pk_pk3); 
} 
$stmt->execute();

How to show the Project Explorer window in Eclipse

If you are on either Eclipse or Spring tool suite then follow the below steps.

(1) Go to 'Window' on the top of the editor. Click on it
(2) Select show view. You should see an option 'Project Explorer'. Click on it.
You should be able to do it.

enter image description here

What are the most widely used C++ vector/matrix math/linear algebra libraries, and their cost and benefit tradeoffs?

I'll add vote for Eigen: I ported a lot of code (3D geometry, linear algebra and differential equations) from different libraries to this one - improving both performance and code readability in almost all cases.

One advantage that wasn't mentioned: it's very easy to use SSE with Eigen, which significantly improves performance of 2D-3D operations (where everything can be padded to 128 bits).

How to calculate the inverse of the normal cumulative distribution function in python?

NORMSINV (mentioned in a comment) is the inverse of the CDF of the standard normal distribution. Using scipy, you can compute this with the ppf method of the scipy.stats.norm object. The acronym ppf stands for percent point function, which is another name for the quantile function.

In [20]: from scipy.stats import norm

In [21]: norm.ppf(0.95)
Out[21]: 1.6448536269514722

Check that it is the inverse of the CDF:

In [34]: norm.cdf(norm.ppf(0.95))
Out[34]: 0.94999999999999996

By default, norm.ppf uses mean=0 and stddev=1, which is the "standard" normal distribution. You can use a different mean and standard deviation by specifying the loc and scale arguments, respectively.

In [35]: norm.ppf(0.95, loc=10, scale=2)
Out[35]: 13.289707253902945

If you look at the source code for scipy.stats.norm, you'll find that the ppf method ultimately calls scipy.special.ndtri. So to compute the inverse of the CDF of the standard normal distribution, you could use that function directly:

In [43]: from scipy.special import ndtri

In [44]: ndtri(0.95)
Out[44]: 1.6448536269514722

Powershell: count members of a AD group

Try:

$group = Get-ADGroup -Identity your-group-name -Properties *

$group.members | count

This worked for me for a group with over 17000 members.

How to convert variable (object) name into String

You can use deparse and substitute to get the name of a function argument:

myfunc <- function(v1) {
  deparse(substitute(v1))
}

myfunc(foo)
[1] "foo"

How to encrypt and decrypt String with my passphrase in Java (Pc not mobile platform)?

My requirement was to keep the password in a config file in encrypted form and decrypt when the program runs. For this I used the jasypt library (jasypt-1.9.3.jar). This is a very good library and we can accomplish the task with just 4 lines of code.

First, after adding jar to my project I imported the below library.

import org.jasypt.util.text.AES256TextEncryptor;

Then I created the below method. I then called this method by passing the text which I need to encrypt in password parameter. Using aesEncryptor.encrypt method, I encrypted the password which is stored to the myEncryptedPassword variable.

public void EncryptPassword(String password)
{   
    AES256TextEncryptor aesEncryptor = new AES256TextEncryptor();
    aesEncryptor.setPassword("mypassword");
    String myEncryptedPassword = aesEncryptor.encrypt(password);
    System.out.println(myEncryptedPassword );       
}

You might have noticed the method setPassword method and the value mypassword is used in the above code. This is to make sure that no one can decrypt the password even if they use the encrypted password using the same library.

Now I can see the value in the myEncryptedPassword variable something like h9oJ4P5P8ToRy38wvK11PUQCBrT1oH/zbMWuMrbOlI0rfZrj+qSg6f/u0jctOs/ZUf9t3shiwnEt05/nq8bnag==. This is the encrypted password. Keep this value in the config file.

I then created the below method to decrypt the password to be used in my program. The value of passwordFromConfigFile is the encrypted text which I got from the EncryptPassword method. Note that you have to use the same password in the aesEncryptor.setPassword method that you used to encrypt the password.

public String DecryptPassword(String passwordFromConfigFile)
{           
    AES256TextEncryptor aesEncryptor = new AES256TextEncryptor();
    aesEncryptor.setPassword("mypassword");
    String decryptedPassword = aesEncryptor.decrypt(passwordFromConfigFile);
    return decryptedPassword;   
}

The variable decryptedPassword will now have the decrypted password value.

How do I get my page title to have an icon?

They're called favicons, and are quite easy to make/use. Have a read of http://www.favicon.com/ for help.

Disable/enable an input with jQuery?

You can use the jQuery prop() method to disable or enable form element or control dynamically using jQuery. The prop() method require jQuery 1.6 and above.

Example:

<script type="text/javascript">
        $(document).ready(function(){
            $('form input[type="submit"]').prop("disabled", true);
            $(".agree").click(function(){
                if($(this).prop("checked") == true){
                    $('form input[type="submit"]').prop("disabled", false);
                }
                else if($(this).prop("checked") == false){
                    $('form input[type="submit"]').prop("disabled", true);
                }
            });
        });
    </script>

What is correct content-type for excel files?

For BIFF .xls files

application/vnd.ms-excel

For Excel2007 and above .xlsx files

application/vnd.openxmlformats-officedocument.spreadsheetml.sheet

How to determine the content size of a UIWebView?

None of the suggestions here helped me with my situation, but I read something that did give me an answer. I have a ViewController with a fixed set of UI controls followed by a UIWebView. I wanted the entire page to scroll as though the UI controls were connected to the HTML content, so I disable scrolling on the UIWebView and must then set the content size of a parent scroll view correctly.

The important tip turned out to be that UIWebView does not report its size correctly until rendered to the screen. So when I load the content I set the content size to the available screen height. Then, in viewDidAppear I update the scrollview's content size to the correct value. This worked for me because I am calling loadHTMLString on local content. If you are using loadRequest you may need to update the contentSize in webViewDidFinishLoad also, depending on how quickly the html is retrieved.

There is no flickering, because only the invisible part of the scroll view is changed.

How to disable scrolling in UITableView table when the content fits on the screen

I think you want to set

tableView.alwaysBounceVertical = NO;

Accessing last x characters of a string in Bash

Last three characters of string:

${string: -3}

or

${string:(-3)}

(mind the space between : and -3 in the first form).

Please refer to the Shell Parameter Expansion in the reference manual:

${parameter:offset}
${parameter:offset:length}

Expands to up to length characters of parameter starting at the character
specified by offset. If length is omitted, expands to the substring of parameter
starting at the character specified by offset. length and offset are arithmetic
expressions (see Shell Arithmetic). This is referred to as Substring Expansion.

If offset evaluates to a number less than zero, the value is used as an offset
from the end of the value of parameter. If length evaluates to a number less than
zero, and parameter is not ‘@’ and not an indexed or associative array, it is
interpreted as an offset from the end of the value of parameter rather than a
number of characters, and the expansion is the characters between the two
offsets. If parameter is ‘@’, the result is length positional parameters
beginning at offset. If parameter is an indexed array name subscripted by ‘@’ or
‘*’, the result is the length members of the array beginning with
${parameter[offset]}. A negative offset is taken relative to one greater than the
maximum index of the specified array. Substring expansion applied to an
associative array produces undefined results.

Note that a negative offset must be separated from the colon by at least one
space to avoid being confused with the ‘:-’ expansion. Substring indexing is
zero-based unless the positional parameters are used, in which case the indexing
starts at 1 by default. If offset is 0, and the positional parameters are used,
$@ is prefixed to the list.

Since this answer gets a few regular views, let me add a possibility to address John Rix's comment; as he mentions, if your string has length less than 3, ${string: -3} expands to the empty string. If, in this case, you want the expansion of string, you may use:

${string:${#string}<3?0:-3}

This uses the ?: ternary if operator, that may be used in Shell Arithmetic; since as documented, the offset is an arithmetic expression, this is valid.


Update for a POSIX-compliant solution

The previous part gives the best option when using Bash. If you want to target POSIX shells, here's an option (that doesn't use pipes or external tools like cut):

# New variable with 3 last characters removed
prefix=${string%???}
# The new string is obtained by removing the prefix a from string
newstring=${string#"$prefix"}

One of the main things to observe here is the use of quoting for prefix inside the parameter expansion. This is mentioned in the POSIX ref (at the end of the section):

The following four varieties of parameter expansion provide for substring processing. In each case, pattern matching notation (see Pattern Matching Notation), rather than regular expression notation, shall be used to evaluate the patterns. If parameter is '#', '*', or '@', the result of the expansion is unspecified. If parameter is unset and set -u is in effect, the expansion shall fail. Enclosing the full parameter expansion string in double-quotes shall not cause the following four varieties of pattern characters to be quoted, whereas quoting characters within the braces shall have this effect. In each variety, if word is omitted, the empty pattern shall be used.

This is important if your string contains special characters. E.g. (in dash),

$ string="hello*ext"
$ prefix=${string%???}
$ # Without quotes (WRONG)
$ echo "${string#$prefix}"
*ext
$ # With quotes (CORRECT)
$ echo "${string#"$prefix"}"
ext

Of course, this is usable only when then number of characters is known in advance, as you have to hardcode the number of ? in the parameter expansion; but when it's the case, it's a good portable solution.

Values of disabled inputs will not be submitted

You can use three things to mimic disabled:

  1. HTML: readonly attribute (so that the value present in input can be used on form submission. Also the user can't change the input value)

  2. CSS: 'pointer-events':'none' (blocking the user from clicking the input)

  3. HTML: tabindex="-1" (blocking the user to navigate to the input from the keyboard)

Android Button Onclick

If you write like this in Button tag in xml file : android:onClick="setLogin" then

Do like this:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<Button
    android:id="@+id/button1"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/btn"
    android:onClick="onClickBtn" />

</LinearLayout>

and in Code part:

public class StartUpActivity extends Activity 
{
    public void onCreate(Bundle savedInstanceState) 
    {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.main);    
    }

    public void onClickBtn(View v)
    {
        Toast.makeText(this, "Clicked on Button", Toast.LENGTH_LONG).show();
    } 
}

and no need all this:

 Button button = (Button) findViewById(R.id.button1);
 button.setOnClickListener(new OnClickListener() {

    public void onClick(View v) {
        // TODO Auto-generated method stub

    }
 });

Check it once;

Adding input elements dynamically to form

Try this JQuery code to dynamically include form, field, and delete/remove behavior:

_x000D_
_x000D_
$(document).ready(function() {_x000D_
    var max_fields = 10;_x000D_
    var wrapper = $(".container1");_x000D_
    var add_button = $(".add_form_field");_x000D_
_x000D_
    var x = 1;_x000D_
    $(add_button).click(function(e) {_x000D_
        e.preventDefault();_x000D_
        if (x < max_fields) {_x000D_
            x++;_x000D_
            $(wrapper).append('<div><input type="text" name="mytext[]"/><a href="#" class="delete">Delete</a></div>'); //add input box_x000D_
        } else {_x000D_
            alert('You Reached the limits')_x000D_
        }_x000D_
    });_x000D_
_x000D_
    $(wrapper).on("click", ".delete", function(e) {_x000D_
        e.preventDefault();_x000D_
        $(this).parent('div').remove();_x000D_
        x--;_x000D_
    })_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div class="container1">_x000D_
    <button class="add_form_field">Add New Field &nbsp; _x000D_
      <span style="font-size:16px; font-weight:bold;">+ </span>_x000D_
    </button>_x000D_
    <div><input type="text" name="mytext[]"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Refer Demo Here

How to choose the id generation strategy when using JPA and Hibernate

The API Doc are very clear on this.

All generators implement the interface org.hibernate.id.IdentifierGenerator. This is a very simple interface. Some applications can choose to provide their own specialized implementations, however, Hibernate provides a range of built-in implementations. The shortcut names for the built-in generators are as follows:

increment

generates identifiers of type long, short or int that are unique only when no other process is inserting data into the same table. Do not use in a cluster.

identity

supports identity columns in DB2, MySQL, MS SQL Server, Sybase and HypersonicSQL. The returned identifier is of type long, short or int.

sequence

uses a sequence in DB2, PostgreSQL, Oracle, SAP DB, McKoi or a generator in Interbase. The returned identifier is of type long, short or int

hilo

uses a hi/lo algorithm to efficiently generate identifiers of type long, short or int, given a table and column (by default hibernate_unique_key and next_hi respectively) as a source of hi values. The hi/lo algorithm generates identifiers that are unique only for a particular database.

seqhilo

uses a hi/lo algorithm to efficiently generate identifiers of type long, short or int, given a named database sequence.

uuid

uses a 128-bit UUID algorithm to generate identifiers of type string that are unique within a network (the IP address is used). The UUID is encoded as a string of 32 hexadecimal digits in length.

guid

uses a database-generated GUID string on MS SQL Server and MySQL.

native

selects identity, sequence or hilo depending upon the capabilities of the underlying database.

assigned

lets the application assign an identifier to the object before save() is called. This is the default strategy if no element is specified.

select

retrieves a primary key, assigned by a database trigger, by selecting the row by some unique key and retrieving the primary key value.

foreign

uses the identifier of another associated object. It is usually used in conjunction with a primary key association.

sequence-identity

a specialized sequence generation strategy that utilizes a database sequence for the actual value generation, but combines this with JDBC3 getGeneratedKeys to return the generated identifier value as part of the insert statement execution. This strategy is only supported on Oracle 10g drivers targeted for JDK 1.4. Comments on these insert statements are disabled due to a bug in the Oracle drivers.

If you are building a simple application with not much concurrent users, you can go for increment, identity, hilo etc.. These are simple to configure and did not need much coding inside the db.

You should choose sequence or guid depending on your database. These are safe and better because the id generation will happen inside the database.

Update: Recently we had an an issue with idendity where primitive type (int) this was fixed by using warapper type (Integer) instead.

Get name of property as a string

Okay, here's what I ended up creating (based upon the answer I selected and the question he referenced):

// <summary>
// Get the name of a static or instance property from a property access lambda.
// </summary>
// <typeparam name="T">Type of the property</typeparam>
// <param name="propertyLambda">lambda expression of the form: '() => Class.Property' or '() => object.Property'</param>
// <returns>The name of the property</returns>

public string GetPropertyName<T>(Expression<Func<T>> propertyLambda)
{
    var me = propertyLambda.Body as MemberExpression;

    if (me == null)
    {
        throw new ArgumentException("You must pass a lambda of the form: '() => Class.Property' or '() => object.Property'");
    }

    return me.Member.Name;
 }

Usage:

// Static Property
string name = GetPropertyName(() => SomeClass.SomeProperty);

// Instance Property
string name = GetPropertyName(() => someObject.SomeProperty);

Given URL is not allowed by the Application configuration Facebook application error

I solved this issue by specifying correct site URL in my App Settings. It works fine now. You have to specify your website Url such as http://www.xyz.com/

Reading values from DataTable

DataTable dr_art_line_2 = ds.Tables["QuantityInIssueUnit"];

for (int i = 0; i < dr_art_line_2.Rows.Count; i++)
{
    QuantityInIssueUnit_value = Convert.ToInt32(dr_art_line_2.Rows[i]["columnname"]);
    //Similarly for QuantityInIssueUnit_uom.
}

How to JSON serialize sets?

If you only need to encode sets, not general Python objects, and want to keep it easily human-readable, a simplified version of Raymond Hettinger's answer can be used:

import json
import collections

class JSONSetEncoder(json.JSONEncoder):
    """Use with json.dumps to allow Python sets to be encoded to JSON

    Example
    -------

    import json

    data = dict(aset=set([1,2,3]))

    encoded = json.dumps(data, cls=JSONSetEncoder)
    decoded = json.loads(encoded, object_hook=json_as_python_set)
    assert data == decoded     # Should assert successfully

    Any object that is matched by isinstance(obj, collections.Set) will
    be encoded, but the decoded value will always be a normal Python set.

    """

    def default(self, obj):
        if isinstance(obj, collections.Set):
            return dict(_set_object=list(obj))
        else:
            return json.JSONEncoder.default(self, obj)

def json_as_python_set(dct):
    """Decode json {'_set_object': [1,2,3]} to set([1,2,3])

    Example
    -------
    decoded = json.loads(encoded, object_hook=json_as_python_set)

    Also see :class:`JSONSetEncoder`

    """
    if '_set_object' in dct:
        return set(dct['_set_object'])
    return dct

Pagination using MySQL LIMIT, OFFSET

First off, don't have a separate server script for each page, that is just madness. Most applications implement pagination via use of a pagination parameter in the URL. Something like:

http://yoursite.com/itempage.php?page=2

You can access the requested page number via $_GET['page'].

This makes your SQL formulation really easy:

// determine page number from $_GET
$page = 1;
if(!empty($_GET['page'])) {
    $page = filter_input(INPUT_GET, 'page', FILTER_VALIDATE_INT);
    if(false === $page) {
        $page = 1;
    }
}

// set the number of items to display per page
$items_per_page = 4;

// build query
$offset = ($page - 1) * $items_per_page;
$sql = "SELECT * FROM menuitem LIMIT " . $offset . "," . $items_per_page;

So for example if input here was page=2, with 4 rows per page, your query would be"

SELECT * FROM menuitem LIMIT 4,4

So that is the basic problem of pagination. Now, you have the added requirement that you want to understand the total number of pages (so that you can determine if "NEXT PAGE" should be shown or if you wanted to allow direct access to page X via a link).

In order to do this, you must understand the number of rows in the table.

You can simply do this with a DB call before trying to return your actual limited record set (I say BEFORE since you obviously want to validate that the requested page exists).

This is actually quite simple:

$sql = "SELECT your_primary_key_field FROM menuitem";
$result = mysqli_query($con, $sql);
if(false === $result) {
   throw new Exception('Query failed with: ' . mysqli_error());
} else {
   $row_count = mysqli_num_rows($result);
   // free the result set as you don't need it anymore
   mysqli_free_result($result);
}

$page_count = 0;
if (0 === $row_count) {  
    // maybe show some error since there is nothing in your table
} else {
   // determine page_count
   $page_count = (int)ceil($row_count / $items_per_page);
   // double check that request page is in range
   if($page > $page_count) {
        // error to user, maybe set page to 1
        $page = 1;
   }
}

// make your LIMIT query here as shown above


// later when outputting page, you can simply work with $page and $page_count to output links
// for example
for ($i = 1; $i <= $page_count; $i++) {
   if ($i === $page) { // this is current page
       echo 'Page ' . $i . '<br>';
   } else { // show link to other page   
       echo '<a href="/menuitem.php?page=' . $i . '">Page ' . $i . '</a><br>';
   }
}

What are libtool's .la file for?

I found very good explanation about .la files here http://openbooks.sourceforge.net/books/wga/dealing-with-libraries.html

Summary (The way I understood): Because libtool deals with static and dynamic libraries internally (through --diable-shared or --disable-static) it creates a wrapper on the library files it builds. They are treated as binary library files with in libtool supported environment.

Async await in linq select

I have the same problem as @KTCheek in that I need it to execute sequentially. However I figured I would try using IAsyncEnumerable (introduced in .NET Core 3) and await foreach (introduced in C# 8). Here's what I have come up with:

public static class IEnumerableExtensions {
    public static async IAsyncEnumerable<TResult> SelectAsync<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, Task<TResult>> selector) {
        foreach (var item in source) {
            yield return await selector(item);
        }
    }
}

public static class IAsyncEnumerableExtensions {
    public static async Task<List<TSource>> ToListAsync<TSource>(this IAsyncEnumerable<TSource> source) {
        var list = new List<TSource>();

        await foreach (var item in source) {
            list.Add(item);
        }

        return list;
    }
}

This can be consumed by saying:

var inputs = await events.SelectAsync(ev => ProcessEventAsync(ev)).ToListAsync();

Update: Alternatively you can add a reference to "System.Linq.Async" and then you can say:

var inputs = await events
    .ToAsyncEnumerable()
    .SelectAwait(async ev => await ProcessEventAsync(ev))
    .ToListAsync();

appcompat-v7:21.0.0': No resource found that matches the given name: attr 'android:actionModeShareDrawable'

Make sure you clean your project in android studio (or eclipse),

It should solve your issues

How can I change all input values to uppercase using Jquery?

use css :

input.upper { text-transform: uppercase; }

probably best to use the style, and convert serverside. There's also a jQuery plugin to force uppercase: http://plugins.jquery.com/plugin-tags/uppercase

Linux bash script to extract IP address

awk '/inet addr:/{gsub(/^.{5}/,"",$2); print $2}' file
192.168.1.103

ArrayList filter

Probably the best way is to use Guava

List<String> list = new ArrayList<String>();
list.add("How are you");
list.add("How you doing");
list.add("Joe");
list.add("Mike");
    
Collection<String> filtered = Collections2.filter(list,
    Predicates.containsPattern("How"));
print(filtered);

prints

How are you
How you doing

In case you want to get the filtered collection as a list, you can use this (also from Guava):

List<String> filteredList = Lists.newArrayList(Collections2.filter(
    list, Predicates.containsPattern("How")));

Move UIView up when the keyboard appears in iOS

Declare a delegate, assign your text field to the delegate and then include these methods.

Assuming you have a login form with email and password text fields, this code will fit perfectly:

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

    [self.emailTextField resignFirstResponder];
    [self.passwordTextField resignFirstResponder];

}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {

    if (self.emailTextField == textField) {
        [self.passwordTextField becomeFirstResponder];
    } else {
        [self.emailTextField resignFirstResponder];
        [self.passwordTextField resignFirstResponder];
    }
    return NO;
}
- (void)viewWillAppear:(BOOL)animated {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}

- (void)viewWillDisappear:(BOOL)animated {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}

#pragma mark - keyboard movements
- (void)keyboardWillShow:(NSNotification *)notification
{
    CGSize keyboardSize = [[[notification userInfo] objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;

    [UIView animateWithDuration:0.3 animations:^{
        CGRect f = self.view.frame;
        f.origin.y = -0.5f * keyboardSize.height;
        self.view.frame = f;
    }];
}

-(void)keyboardWillHide:(NSNotification *)notification
{
    [UIView animateWithDuration:0.3 animations:^{
        CGRect f = self.view.frame;
        f.origin.y = 0.0f;
        self.view.frame = f;
    }];
}

Default values and initialization in Java

There are a few things to keep in mind while declaring primitive type values.

They are:

  1. Values declared inside a method will not be assigned a default value.
  2. Values declared as instance variables or a static variable will have default values assigned which is 0.

So in your code:

public class Main {
    int instanceVariable;
    static int staticVariable;
    public static void main(String[] args) {
        Main mainInstance = new Main()
        int localVariable;
        int localVariableTwo = 2;
        System.out.println(mainInstance.instanceVariable);
        System.out.println(staticVariable);
       // System.out.println(localVariable); // Will throw a compilation error
        System.out.println(localVariableTwo);
    }
}

Error in eval(expr, envir, enclos) : object not found

Don't know why @Janos deleted his answer, but it's correct: your data frame Train doesn't have a column named pre. When you pass a formula and a data frame to a model-fitting function, the names in the formula have to refer to columns in the data frame. Your Train has columns called residual.sugar, total.sulfur, alcohol and quality. You need to change either your formula or your data frame so they're consistent with each other.

And just to clarify: Pre is an object containing a formula. That formula contains a reference to the variable pre. It's the latter that has to be consistent with the data frame.

Eclipse CDT: no rule to make target all

If the above solutions did not work for you so -

Could be that you did not install C++ compiler packages properly, flow this: (Instructions for Win7, 32bit/64bit)

  1. Make sure you install properly one or more of the supporting C++ compiler packages:

    (I installed MinGW (HowTo Install Videos can be found on YouTube))

    In case you choose to install MinGW packages:

    • Download MinGW installer from the Install Page above
    • Run MinGW installer and make sure to choose the following packages:

      - mingw-developer-toolkit
      - mingw32-base
      - mingw32-gcc-g++
      - msys-base

    • Add MinGW and MSYS bin paths to your PATH environment variable , if you didn't change the default installation folders you should add:

    C:\MinGW\msys\1.0\bin;C:\MinGW\bin;
    • Logoff and log back in for making sure Environment vars kicked in
  2. Create a new C++ project in eclipse:

    • New -> C++ Projects
    • Choose Project type: Executables -> Hello World C++ project
      (Now on the right, under Toolchains you shall see MinGW GCC)
    • Select MinGW GCC from the Toolchains list
    • Hit Finish
  3. In you Hello World Project you shall see + src folder, and + Includes (If so you are probably good to go).

  4. Build project
  5. Run it!

S3 - Access-Control-Allow-Origin Header

Like others have stated, you first need to have the CORS configuration in your S3 bucket:

<CORSConfiguration>
<CORSRule>
    <AllowedOrigin>*</AllowedOrigin>
    <AllowedMethod>GET</AllowedMethod>
    <AllowedMethod>HEAD</AllowedMethod> <!-- Add this -->
    <MaxAgeSeconds>3000</MaxAgeSeconds>
    <AllowedHeader>Authorization</AllowedHeader>
</CORSRule>
</CORSConfiguration>

But in my case after doing that, it was still not working. I was using Chrome (probably the same problem with other browsers).

The problem was that Chrome was caching the image with the headers (not containing the CORS data), so no matter what I tried to change in AWS, I would not see my CORS headers.

After clearing Chrome cache and reloading the page, the image had the expected CORS Headers

ReactJs: What should the PropTypes be for this.props.children?

If you want to include render prop components:

  children: PropTypes.oneOfType([
    PropTypes.arrayOf(PropTypes.node),
    PropTypes.node,
    PropTypes.func
  ])

Read file line by line in PowerShell

I was able to read a 4GB log file in about 50 seconds with the following. You may be able to make it faster by loading it as a C# assembly dynamically using PowerShell.

[System.IO.StreamReader]$sr = [System.IO.File]::Open($file, [System.IO.FileMode]::Open)
while (-not $sr.EndOfStream){
    $line = $sr.ReadLine()
}
$sr.Close() 

Disabling Chrome cache for website development

When this question was asked, Chrome didn't support the Disable Cache feature. But now, you can find the "Disable Cache" feature in Network Tab in Chrome Dev Tools.

Network Tab with Cache Disabled

Screenshot - Disable Cache Feature in Chrome Dev Tools

You can see that all the resources (I have filtered JS resources) have been fetched from network and not loaded from disk/memory cache.

Disable Cache not selected

enter image description here

You can see that when I refreshed the page but didn't select the "Disable Cache" feature, almost all the resources were loaded from Cache.

This works fine for local web development but there are certain limitations that I'd like to highlight. You can stop reading here if the solution discussed so far meets your use case.

Limitations

  1. You have to keep the DevTools Open and Disable Cache Selected
  2. When you disable the cache, it is disabled for all the resources in that tab. It makes things slow and is inefficient if you want to disable cache for only 1-2 resources

Using Requestly Chrome Extension to disable Cache for particular resources (JS/CSS/Images, etc)

Recently, I stumbled upon https://medium.com/weekly-webtips/how-to-disable-caching-of-particular-js-css-file-84a93d005172 which helped me understand how you can disable cache for specific resources.

The trick here is to add a query parameter to your resource with random value every time the request is made. Using Requestly Query Param Rule, you can add a param like this

URL Contains mywebsite.com/myresource.js
Add param cb rq_rand(4)

rq_rand(4) is replaced by 4 digits random number when a request is made.

Requestly Query Parameter Rule to add random parameter

enter image description here

After adding the rule, JS/CSS files are not cached

Requestly Rule applied and added a random parameter to disable cache

Here you can see that "Disable Cache" is not selected and still the resources are not loaded from Cache because of a random parameter (cb - Read it as Cache buster) in the URL.

  1. The good thing is you don't need to keep your dev tools open for having this behavior
  2. You can keep this permanently ON and your browsing experience won't be affected too.

How to get the Rule

Here is the link using which you can browse & download the rule if you have Requestly installed - https://app.requestly.io/rules/#sharedList/1600501411585-disable-cache-stackoverflow

Disclaimer: I built Requestly but I think this could be helpful to a lot of web developers and hence sharing here.

Removing Conda environment

After making sure your environment is not active, type:

$ conda env remove --name ENVIRONMENT

How to hide code from cells in ipython notebook visualized with nbviewer?

For better display with printed document or a report, we need to remove the button as well, and the ability to show or hide certain code blocks. Here's what I use (simply copy-paste this to your first cell):

# This is a cell to hide code snippets from displaying
# This must be at first cell!

from IPython.display import HTML

hide_me = ''
HTML('''<script>
code_show=true; 
function code_toggle() {
  if (code_show) {
    $('div.input').each(function(id) {
      el = $(this).find('.cm-variable:first');
      if (id == 0 || el.text() == 'hide_me') {
        $(this).hide();
      }
    });
    $('div.output_prompt').css('opacity', 0);
  } else {
    $('div.input').each(function(id) {
      $(this).show();
    });
    $('div.output_prompt').css('opacity', 1);
  }
  code_show = !code_show
} 
$( document ).ready(code_toggle);
</script>
<form action="javascript:code_toggle()"><input style="opacity:0" type="submit" value="Click here to toggle on/off the raw code."></form>''')

Then in your next cells:

hide_me
print "this code will be hidden"

and

print "this code will be shown"

Handling very large numbers in Python

You could do this for the fun of it, but other than that it's not a good idea. It would not speed up anything I can think of.

  • Getting the cards in a hand will be an integer factoring operation which is much more expensive than just accessing an array.

  • Adding cards would be multiplication, and removing cards division, both of large multi-word numbers, which are more expensive operations than adding or removing elements from lists.

  • The actual numeric value of a hand will tell you nothing. You will need to factor the primes and follow the Poker rules to compare two hands. h1 < h2 for such hands means nothing.

Should switch statements always contain a default clause?

I disagree with the most voted answer of Vanwaril above.

Any code adds complexity. Also tests and documentation must be done for it. So it is always good if you can program using less code. My opinion is that I use a default clause for non-exhaustive switch statements while I use no default clause for exhaustive switch statements. To be sure that I did that right I use a static code analysis tool. So let's go into the details:

  1. Nonexhaustive switch statements: Those should always have a default value. As the name suggests those are statements which do not cover all possible values. This also might not be possible, e.g. a switch statement on an integer value or on a String. Here I would like to use the example of Vanwaril (It should be mentioned that I think he used this example to make a wrong suggestion. I use it here to state the opposite --> Use a default statement):

    switch(keystroke)
    {
      case 'w':
        // move up
      case 'a':
        // move left
      case 's':
        // move down
      case 'd':
        // move right
      default:          
        // cover all other values of the non-exhaustive switch statement
    }
    

    The player could press any other key. Then we could not do anything (this can be shown in the code just by adding a comment to the default case) or it should for example print something on the screen. This case is relevant as it may happen.

  2. Exhaustive switch statements: Those switch statements cover all possible values, e.g. a switch statement on an enumeration of grade system types. When developing code the first time it is easy to cover all values. However, as we are humans there is a small chance to forget some. Additionally if you add an enum value later such that all switch statements have to be adapted to make them exhaustive again opens the path to error hell. The simple solution is a static code analysis tool. The tool should check all switch statements and check if they are exhaustive or if they have a default value. Here an example for an exhaustive switch statement. First we need an enum:

    public enum GradeSystemType {System1To6, SystemAToD, System0To100}
    

    Then we need a variable of this enum like GradeSystemType type = .... An exhaustive switch statement would then look like this:

    switch(type)
    {
      case GradeSystemType.System1To6:
        // do something
      case GradeSystemType.SystemAToD:
        // do something
      case GradeSystemType.System0To100:
        // do something
    }
    

    So if we extend the GradeSystemType by for example System1To3 the static code analysis tool should detect that there is no default clause and the switch statement is not exhaustive so we are save.

Just one additional thing. If we always use a default clause it might happen that the static code analysis tool is not capable of detecting exhaustive or non-exhaustive switch statements as it always detects the default clause. This is super bad as we will not be informed if we extend the enum by another value and forget to add it to one switch statement.

Difference between abstraction and encapsulation?

The process of Abstraction and Encapsulation both generate interfaces.

An interface generated via encapsulation hides implementation details.

An interface generated via abstraction becomes applicable to more data types, compared to before abstraction.

Insert the same fixed value into multiple rows

You're looking for UPDATE not insert.

UPDATE mytable
SET    table_column = 'test';

UPDATE will change the values of existing rows (and can include a WHERE to make it only affect specific rows), whereas INSERT is adding a new row (which makes it look like it changed only the last row, but in effect is adding a new row with that value).

How do I delete all the duplicate records in a MySQL table without temp tables

Instead of drop table TableA, you could delete all registers (delete from TableA;) and then populate original table with registers coming from TableA_Verify (insert into TAbleA select * from TAbleA_Verify). In this way you won't lost all references to original table (indexes,... )

CREATE TABLE TableA_Verify AS SELECT DISTINCT * FROM TableA;

DELETE FROM TableA;

INSERT INTO TableA SELECT * FROM TAbleA_Verify;

DROP TABLE TableA_Verify;

How can I stop "property does not exist on type JQuery" syntax errors when using Typescript?

You can cast it to

(<any>$('.selector') ).function();

Ex: date picker initialize using jquery

(<any>$('.datepicker') ).datepicker();

Missing Maven dependencies in Eclipse project

I had a similar problem. I solved it by running the Maven->Update Project Configuration action

How to send POST request?

Your data dictionary conteines names of form input fields, you just keep on right their values to find results. form view Header configures browser to retrieve type of data you declare. With requests library it's easy to send POST:

import requests

url = "https://bugs.python.org"
data = {'@number': 12524, '@type': 'issue', '@action': 'show'}
headers = {"Content-type": "application/x-www-form-urlencoded", "Accept":"text/plain"}
response = requests.post(url, data=data, headers=headers)

print(response.text)

More about Request object: https://requests.readthedocs.io/en/master/api/

What is RSS and VSZ in Linux memory management

RSS is the Resident Set Size and is used to show how much memory is allocated to that process and is in RAM. It does not include memory that is swapped out. It does include memory from shared libraries as long as the pages from those libraries are actually in memory. It does include all stack and heap memory.

VSZ is the Virtual Memory Size. It includes all memory that the process can access, including memory that is swapped out, memory that is allocated, but not used, and memory that is from shared libraries.

So if process A has a 500K binary and is linked to 2500K of shared libraries, has 200K of stack/heap allocations of which 100K is actually in memory (rest is swapped or unused), and it has only actually loaded 1000K of the shared libraries and 400K of its own binary then:

RSS: 400K + 1000K + 100K = 1500K
VSZ: 500K + 2500K + 200K = 3200K

Since part of the memory is shared, many processes may use it, so if you add up all of the RSS values you can easily end up with more space than your system has.

The memory that is allocated also may not be in RSS until it is actually used by the program. So if your program allocated a bunch of memory up front, then uses it over time, you could see RSS going up and VSZ staying the same.

There is also PSS (proportional set size). This is a newer measure which tracks the shared memory as a proportion used by the current process. So if there were two processes using the same shared library from before:

PSS: 400K + (1000K/2) + 100K = 400K + 500K + 100K = 1000K

Threads all share the same address space, so the RSS, VSZ and PSS for each thread is identical to all of the other threads in the process. Use ps or top to view this information in linux/unix.

There is way more to it than this, to learn more check the following references:

Also see:

Setting a checkbox as checked with Vue.js

Let's say you want to pass a prop to a child component and that prop is a boolean that will determine if the checkbox is checked or not, then you have to pass the boolean value to the v-bind:checked="booleanValue" or the shorter way :checked="booleanValue", for example:

<input
    id="checkbox"
    type="checkbox"
    :value="checkboxVal"
    :checked="booleanValue"
    v-on:input="checkboxVal = $event.target.value"
/>

That should work and the checkbox will display the checkbox with it's current boolean state (if true checked, if not unchecked).

GUI-based or Web-based JSON editor that works like property explorer

Generally when I want to create a JSON or YAML string, I start out by building the Perl data structure, and then running a simple conversion on it. You could put a UI in front of the Perl data structure generation, e.g. a web form.

Converting a structure to JSON is very straightforward:

use strict;
use warnings;
use JSON::Any;

my $data = { arbitrary structure in here };
my $json_handler = JSON::Any->new(utf8=>1);
my $json_string = $json_handler->objToJson($data);

Program "make" not found in PATH

If you are using MinGw, rename the mingw32-make.exe to make.exe in the folder " C:\MinGW\bin " or wherever minGw is installed in your system.

Searching in a ArrayList with custom objects for certain strings

boolean found;

for(CustomObject obj : ArrayOfCustObj) {

   if(obj.getName.equals("Android")) {

      found = true;
   }
}

Best way to verify string is empty or null

springframework library Check whether the given String is empty.

f(StringUtils.isEmpty(str)) {
    //.... String is blank or null
}

PHP: How to generate a random, unique, alphanumeric string for use in a secret link?

You can use UUID(Universally Unique Identifier), it can be used for any purpose, from user authentication string to payment transaction id.

A UUID is a 16-octet (128-bit) number. In its canonical form, a UUID is represented by 32 hexadecimal digits, displayed in five groups separated by hyphens, in the form 8-4-4-4-12 for a total of 36 characters (32 alphanumeric characters and four hyphens).

function generate_uuid() {
    return sprintf( '%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
        mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ),
        mt_rand( 0, 0xffff ),
        mt_rand( 0, 0x0C2f ) | 0x4000,
        mt_rand( 0, 0x3fff ) | 0x8000,
        mt_rand( 0, 0x2Aff ), mt_rand( 0, 0xffD3 ), mt_rand( 0, 0xff4B )
    );

}

//calling funtion

$transationID = generate_uuid();

some example outputs will be like:

E302D66D-87E3-4450-8CB6-17531895BF14
22D288BC-7289-442B-BEEA-286777D559F2
51B4DE29-3B71-4FD2-9E6C-071703E1FF31
3777C8C6-9FF5-4C78-AAA2-08A47F555E81
54B91C72-2CF4-4501-A6E9-02A60DCBAE4C
60F75C7C-1AE3-417B-82C8-14D456542CD7
8DE0168D-01D3-4502-9E59-10D665CEBCB2

hope it helps someone in future :)

How can I get the console logs from the iOS Simulator?

I can open the log directly via the iOS simulator: Debug -> Open System Log... Not sure when this was introduced, so it might not be available for earlier versions.

how to set "camera position" for 3d plots using python/matplotlib?

Try the following code to find the optimal camera position

Move the viewing angle of the plot using the keyboard keys as mentioned in the if clause

Use print to get the camera positions

def move_view(event):
    ax.autoscale(enable=False, axis='both') 
    koef = 8
    zkoef = (ax.get_zbound()[0] - ax.get_zbound()[1]) / koef
    xkoef = (ax.get_xbound()[0] - ax.get_xbound()[1]) / koef
    ykoef = (ax.get_ybound()[0] - ax.get_ybound()[1]) / koef
    ## Map an motion to keyboard shortcuts
    if event.key == "ctrl+down":
        ax.set_ybound(ax.get_ybound()[0] + xkoef, ax.get_ybound()[1] + xkoef)
    if event.key == "ctrl+up":
        ax.set_ybound(ax.get_ybound()[0] - xkoef, ax.get_ybound()[1] - xkoef)
    if event.key == "ctrl+right":
        ax.set_xbound(ax.get_xbound()[0] + ykoef, ax.get_xbound()[1] + ykoef)
    if event.key == "ctrl+left":
        ax.set_xbound(ax.get_xbound()[0] - ykoef, ax.get_xbound()[1] - ykoef)
    if event.key == "down":
        ax.set_zbound(ax.get_zbound()[0] - zkoef, ax.get_zbound()[1] - zkoef)
    if event.key == "up":
        ax.set_zbound(ax.get_zbound()[0] + zkoef, ax.get_zbound()[1] + zkoef)
    # zoom option
    if event.key == "alt+up":
        ax.set_xbound(ax.get_xbound()[0]*0.90, ax.get_xbound()[1]*0.90)
        ax.set_ybound(ax.get_ybound()[0]*0.90, ax.get_ybound()[1]*0.90)
        ax.set_zbound(ax.get_zbound()[0]*0.90, ax.get_zbound()[1]*0.90)
    if event.key == "alt+down":
        ax.set_xbound(ax.get_xbound()[0]*1.10, ax.get_xbound()[1]*1.10)
        ax.set_ybound(ax.get_ybound()[0]*1.10, ax.get_ybound()[1]*1.10)
        ax.set_zbound(ax.get_zbound()[0]*1.10, ax.get_zbound()[1]*1.10)
    
    # Rotational movement
    elev=ax.elev
    azim=ax.azim
    if event.key == "shift+up":
        elev+=10
    if event.key == "shift+down":
        elev-=10
    if event.key == "shift+right":
        azim+=10
    if event.key == "shift+left":
        azim-=10

    ax.view_init(elev= elev, azim = azim)

    # print which ever variable you want 

    ax.figure.canvas.draw()

fig.canvas.mpl_connect("key_press_event", move_view)

plt.show()

Bootstrap 3 .col-xs-offset-* doesn't work?

This was really frustrating so I wrote a gist you can grab that enables col-offset-xs-*. I also noticed that Bootstrap SASS repo Bower installed this week did not include col-offset-sm-0 so that is shimmed too but will be redundant in many cases.

Bootstrap 3 xs offset shim

How to do perspective fixing?

The simple solution is to just remap coordinates from the original to the final image, copying pixels from one coordinate space to the other, rounding off as necessary -- which may result in some pixels being copied several times adjacent to each other, and other pixels being skipped, depending on whether you're stretching or shrinking (or both) in either dimension. Make sure your copying iterates through the destination space, so all pixels are covered there even if they're painted more than once, rather than thru the source which may skip pixels in the output.

The better solution involves calculating the corresponding source coordinate without rounding, and then using its fractional position between pixels to compute an appropriate average of the (typically) four pixels surrounding that location. This is essentially a filtering operation, so you lose some resolution -- but the result looks a LOT better to the human eye; it does a much better job of retaining small details and avoids creating straight-line artifacts which humans find objectionable.

Note that the same basic approach can be used to remap flat images onto any other shape, including 3D surface mapping.

PHP array delete by value (not key)

$fields = array_flip($fields);
unset($fields['myvalue']);
$fields = array_flip($fields);

How do I split an int into its digits?

Start with the highest power of ten that fits into an int on your platform (for 32 bit int: 1.000.000.000) and perform an integer division by it. The result is the leftmost digit. Subtract this result multipled with the divisor from the original number, then continue the same game with the next lower power of ten and iterate until you reach 1.

Create a directory if it doesn't exist

Here is the simple way to create a folder.......

#include <windows.h>
#include <stdio.h>

void CreateFolder(const char * path)
{   
    if(!CreateDirectory(path ,NULL))
    {
        return;
    }
}


CreateFolder("C:\\folder_name\\")

This above code works well for me.

How to filter rows containing a string pattern from a Pandas dataframe

>>> mask = df['ids'].str.contains('ball')    
>>> mask
0     True
1     True
2    False
3     True
Name: ids, dtype: bool

>>> df[mask]
     ids  vals
0  aball     1
1  bball     2
3  fball     4

php delete a single file in directory

http://php.net/manual/en/function.unlink.php

Unlink can safely remove a single file; just make sure the file you are removing it actually a file and not a directory ('.' or '..')

if (is_file($filepath))
  {
    unlink($filepath);
  }

tSQL - Conversion from varchar to numeric works for all but integer

Converting a varchar value into an int fails when the value includes a decimal point to prevent loss of data.

If you convert to a decimal or float value first, then convert to int, the conversion works.

Either example below will return 7082:

SELECT CONVERT(int, CONVERT(decimal(12,7), '7082.7758172'));
SELECT CAST(CAST('7082.7758172' as float) as int);

Be aware that converting to a float value may result, in rare circumstances, in a loss of precision. I would tend towards using a decimal value, however you'll need to specify precision and scale values that make sense for the varchar data you're converting.

Options for initializing a string array

You have several options:

string[] items = { "Item1", "Item2", "Item3", "Item4" };

string[] items = new string[]
{
  "Item1", "Item2", "Item3", "Item4"
};

string[] items = new string[10];
items[0] = "Item1";
items[1] = "Item2"; // ...

How can I use a reportviewer control in an asp.net mvc 3 razor view?

It is possible to get an SSRS report to appear on an MVC page without using iFrames or an aspx page.

The bulk of the work is explained here:

http://geekswithblogs.net/stun/archive/2010/02/26/executing-reporting-services-web-service-from-asp-net-mvc-using-wcf-add-service-reference.aspx

The link explains how to create a web service and MVC action method that will allow you to call the reporting service and render result of the web service as an Excel file. With a small change to the code in the example you can render it as HTML.

All you need to do then is use a button to call a javascript function that makes an AJAX call to your MVC action which returns the HTML of the report. When the AJAX call returns with the HTML just replace a div with this HTML.

We use AngularJS so my example below is in that format, but it could be any javascript function

$scope.getReport = function()
{
    $http({
        method: "POST",
        url: "Report/ExportReport",
        data: 
                [
                    { Name: 'DateFrom', Value: $scope.dateFrom },
                    { Name: 'DateTo', Value: $scope.dateTo },
                    { Name: 'LocationsCSV', Value: $scope.locationCSV }
                ]

    })
    .success(function (serverData)
    {
        $("#ReportDiv").html(serverData);
    });

};

And the Action Method - mainly taken from the above link...

    [System.Web.Mvc.HttpPost]
    public FileContentResult ExportReport([FromBody]List<ReportParameterModel> parameters)
    {
         byte[] output;
         string extension, mimeType, encoding;
         string reportName = "/Reports/DummyReport";
         ReportService.Warning[] warnings;
         string[] ids;

     ReportExporter.Export(
            "ReportExecutionServiceSoap" 
            new NetworkCredential("username", "password", "domain"),
            reportName,
            parameters.ToArray(),
            ExportFormat.HTML4,
            out output,
            out extension,
            out mimeType,
            out encoding,
            out warnings,
            out ids
        );

        //-------------------------------------------------------------
        // Set HTTP Response Header to show download dialog popup
        //-------------------------------------------------------------
        Response.AddHeader("content-disposition", string.Format("attachment;filename=GeneratedExcelFile{0:yyyyMMdd}.{1}", DateTime.Today, extension));
        return new FileContentResult(output, mimeType);
    }

So the result is that you get to pass parameters to an SSRS reporting server which returns a report which you render as HTML. Everything appears on the one page. This is the best solution I could find

Android Log.v(), Log.d(), Log.i(), Log.w(), Log.e() - When to use each one?

You can use LOG such as :

Log.e(String, String) (error)
Log.w(String, String) (warning)
Log.i(String, String) (information)
Log.d(String, String) (debug)
Log.v(String, String) (verbose)

example code:

private static final String TAG = "MyActivity";
...
Log.i(TAG, "MyClass.getView() — get item number " + position);

How can I specify my .keystore file with Spring Boot and Tomcat?

For external keystores, prefix with "file:"

server.ssl.key-store=file:config/keystore 

Refresh a page using JavaScript or HTML

Use:

window.location.reload();

Convert time in HH:MM:SS format to seconds only?

In pseudocode:

split it by colon
seconds = 3600 * HH + 60 * MM + SS

How to clear APC cache entries?

You can use the PHP function apc_clear_cache.

Calling apc_clear_cache() will clear the system cache and calling apc_clear_cache('user') will clear the user cache.

What does .class mean in Java?

If an instance of an object is available, then the simplest way to get its Class is to invoke Object.getClass()

The .class Syntax

If the type is available but there is no instance then it is possible to obtain a Class by appending .class to the name of the type. This is also the easiest way to obtain the Class for a primitive type.

boolean b;
Class c = b.getClass();   // compile-time error

Class c = boolean.class;  // correct

See: docs.oracle.com about class

How to launch Safari and open URL from iOS app

The non deprecated Objective-C version would be:

[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://apple.com"] options:@{} completionHandler:nil];

Date format in the json output using spring boot

If you want to change the format for all dates you can add a builder customizer. Here is an example of a bean that converts dates to ISO 8601:

@Bean
public Jackson2ObjectMapperBuilderCustomizer jsonCustomizer() {
    return new Jackson2ObjectMapperBuilderCustomizer() {
        @Override
        public void customize(Jackson2ObjectMapperBuilder builder) {
            builder.dateFormat(new ISO8601DateFormat());        
        }           
    };
}

How to install beautiful soup 4 with python 2.7 on windows

Install pip

Download get-pip. Remember to save it as "get-pip.py"

Now go to the download folder. Right click on get-pip.py then open with python.exe.

You can add system variable by

(by doing this you can use pip and easy_install without specifying path)

1 Clicking on Properties of My Computer

2 Then chose Advanced System Settings

3 Click on Advanced Tab

4 Click on Environment Variables

5 From System Variables >>> select variable path.

6 Click edit then add the following lines at the end of it

 ;c:\Python27;c:\Python27\Scripts

(please dont copy this, just go to your python directory and copy the paths similar to this)

NB:- you have to do this once only.

Install beautifulsoup4

Open cmd and type

pip install beautifulsoup4

Invalid default value for 'dateAdded'

Also do note when specifying DATETIME as DATETIME(3) or like on MySQL 5.7.x, you also have to add the same value for CURRENT_TIMESTAMP(3). If not it will keep throwing 'Invalid default value'.

Webpack "OTS parsing error" loading fonts

The best and easiest method is to base64 encode the font file. And use it in font-face. For encoding, go to the folder having the font-file and use the command in terminal:

base64 Roboto.ttf > basecodedtext.txt

You will get an output file named basecodedtext.txt. Open that file. Remove any white spaces in that.

Copy that code and add the following line to the CSS file:

@font-face {
  font-family: "font-name";
  src: url(data:application/x-font-woff;charset=utf-8;base64,<<paste your code here>>) format('woff');
}  

Then you can use the font-family: "font-name" in your CSS.

SQL: sum 3 columns when one column has a null value?

If the column has a 0 value, you are fine, my guess is that you have a problem with a Null value, in that case you would need to use IsNull(Column, 0) to ensure it is always 0 at minimum.

how to delete default values in text field using selenium?

driver.findElement(locator).clear() - This command will work in all cases

Setting Inheritance and Propagation flags with set-acl and powershell

Here's a table to help find the required flags for different permission combinations.

    +-----------------------------------------------------------------------------------------------------------------------------------------------------------+
    ¦             ¦ folder only ¦ folder, sub-folders and files ¦ folder and sub-folders ¦ folder and files ¦ sub-folders and files ¦ sub-folders ¦    files    ¦
    ¦-------------+-------------+-------------------------------+------------------------+------------------+-----------------------+-------------+-------------¦
    ¦ Propagation ¦ none        ¦ none                          ¦ none                   ¦ none             ¦ InheritOnly           ¦ InheritOnly ¦ InheritOnly ¦
    ¦ Inheritance ¦ none        ¦ Container|Object              ¦ Container              ¦ Object           ¦ Container|Object      ¦ Container   ¦ Object      ¦
    +-----------------------------------------------------------------------------------------------------------------------------------------------------------+

So, as David said, you'll want

InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit
PropagationFlags.None

How to pass parameter to function using in addEventListener?

In the first line of your JS code:

select.addEventListener('change', getSelection(this), false);

you're invoking getSelection by placing (this) behind the function reference. That is most likely not what you want, because you're now passing the return value of that call to addEventListener, instead of a reference to the actual function itself.


In a function invoked by addEventListener the value for this will automatically be set to the object the listener is attached to, productLineSelect in this case.

If that is what you want, you can just pass the function reference and this will in this example be select in invocations from addEventListener:

select.addEventListener('change', getSelection, false);

If that is not what you want, you'd best bind your value for this to the function you're passing to addEventListener:

var thisArg = { custom: 'object' };
select.addEventListener('change', getSelection.bind(thisArg), false);

The .bind part is also a call, but this call just returns the same function we're calling bind on, with the value for this inside that function scope fixed to thisArg, effectively overriding the dynamic nature of this-binding.


To get to your actual question: "How to pass parameters to function in addEventListener?"

You would have to use an additional function definition:

var globalVar = 'global';

productLineSelect.addEventListener('change', function(event) {
    var localVar = 'local';
    getSelection(event, this, globalVar, localVar);
}, false);

Now we pass the event object, a reference to the value of this inside the callback of addEventListener, a variable defined and initialised inside that callback, and a variable from outside the entire addEventListener call to your own getSelection function.


We also might again have an object of our choice to be this inside the outer callback:

var thisArg = { custom: 'object' };
var globalVar = 'global';

productLineSelect.addEventListener('change', function(event) {
    var localVar = 'local';
    getSelection(event, this, globalVar, localVar);
}.bind(thisArg), false);

How to reload/refresh an element(image) in jQuery

Have you tried resetting the image containers html. Of course if it's the browser that is caching then this wouldn't help.

function imageUploadComplete () {
    $("#image_container").html("<img src='" + newImageUrl + "'>");
}

Excel VBA Loop on columns

Another method to try out. Also select could be replaced when you set the initial column into a Range object. Performance wise it helps.

Dim rng as Range

Set rng = WorkSheets(1).Range("A1") '-- you may change the sheet name according to yours.

'-- here is your loop
i = 1
Do
   '-- do something: e.g. show the address of the column that you are currently in
   Msgbox rng.offset(0,i).Address 
   i = i + 1
Loop Until i > 10

** Two methods to get the column name using column number**

  • Split()

code

colName = Split(Range.Offset(0,i).Address, "$")(1)
  • String manipulation:

code

Function myColName(colNum as Long) as String
    myColName = Left(Range(0, colNum).Address(False, False), _ 
    1 - (colNum > 10)) 
End Function 

afxwin.h file is missing in VC++ Express Edition

Found this post that may help: http://social.msdn.microsoft.com/forums/en-US/Vsexpressvc/thread/7c274008-80eb-42a0-a79b-95f5afbf6528/

Or shortly, afxwin.h is MFC and MFC is not included in the free version of VC++ (Express Edition).

How to set a default Value of a UIPickerView

In normal case, you can do something like this in viewDidLoad method;

[_picker selectRow:1 inComponent:0 animated:YES];

In my case, I'd like to fetch data from api server and display them onto UIPickerView then I want the picker to select the first item by default.

The UIPickerView will look like it selected the first item after it was created, but when you try to get the selected index by using selectedRowInComponent, you will get NSNull. That's because it detected nothing changed by the user (select 0 from 0 ).

Following is my solution (in viewWillAppear, after I fetched the data)

[_picker selectRow:1 inComponent:0 animated:NO];
[_picker selectRow:0 inComponent:0 animated:NO];

Its a bit dirty, but dont worry, the UI rendering in iOS is very fast ;)

Create a user with all privileges in Oracle

My issue was, i am unable to create a view with my "scott" user in oracle 11g edition. So here is my solution for this

Error in my case

SQL>create view v1 as select * from books where id=10;

insufficient privileges.

Solution

1)open your cmd and change your directory to where you install your oracle database. in my case i was downloaded in E drive so my location is E:\app\B_Amar\product\11.2.0\dbhome_1\BIN> after reaching in the position you have to type sqlplus sys as sysdba

E:\app\B_Amar\product\11.2.0\dbhome_1\BIN>sqlplus sys as sysdba

2) Enter password: here you have to type that password that you give at the time of installation of oracle software.

3) Here in this step if you want create a new user then you can create otherwise give all the privileges to existing user.

for creating new user

SQL> create user abc identified by xyz;

here abc is user and xyz is password.

giving all the privileges to abc user

SQL> grant all privileges to abc;

 grant succeeded. 

if you are seen this message then all the privileges are giving to the abc user.

4) Now exit from cmd, go to your SQL PLUS and connect to the user i.e enter your username & password.Now you can happily create view.

In My case

in cmd E:\app\B_Amar\product\11.2.0\dbhome_1\BIN>sqlplus sys as sysdba

SQL> grant all privileges to SCOTT;

grant succeeded.

Now I can create views.

How to fix PHP Warning: PHP Startup: Unable to load dynamic library 'ext\\php_curl.dll'?

If you are using laragon open the php.ini

In the interface of laragon menu-> php-> php.ini

when you open the file look for ; extension_dir = "./"

create another one without **; ** with the path of your php version to the folder ** ext ** for example

extension_dir = "C: \ laragon \ bin \ php \ php-7.3.11-Win32-VC15-x64 \ ext"

change it save it

How to trigger a file download when clicking an HTML button or JavaScript

For me ading button instead of anchor text works really well.

<a href="file.doc"><button>Download!</button></a>

It might not be ok by most rules, but it looks pretty good.

Dialogs / AlertDialogs: How to "block execution" while dialog is up (.NET-style)

Try this in a Thread (not the UI-Thread):

final CountDownLatch latch = new CountDownLatch(1);
handler.post(new Runnable() {
  @Override
  public void run() {
    OnClickListener okListener = new OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
      dialog.dismiss();
      latch.countDown();
    }
  };

  AlertDialog dialog = new AlertDialog.Builder(context).setTitle(title)
    .setMessage(msg).setPositiveButton("OK", okListener).create();
  dialog.show();
}
});
try {
  latch.await();
} catch (InterruptedException e) {
  e.printStackTrace();
}

Is it possible to define more than one function per file in MATLAB, and access them from outside that file?

As of R2017b, this is not officially possible. The relevant documentation states that:

Program files can contain multiple functions. If the file contains only function definitions, the first function is the main function, and is the function that MATLAB associates with the file name. Functions that follow the main function or script code are called local functions. Local functions are only available within the file.

However, workarounds suggested in other answers can achieve something similar.