Programs & Examples On #Thinking sphinx

Thinking Sphinx is a Ruby library that connects ActiveRecord models to the Sphinx search service.

How do I programmatically click on an element in JavaScript?

The document.createEvent documentation says that "The createEvent method is deprecated. Use event constructors instead."

So you should use this method instead:

var clickEvent = new MouseEvent("click", {
    "view": window,
    "bubbles": true,
    "cancelable": false
});

and fire it on an element like this:

element.dispatchEvent(clickEvent);

as shown here.

JFrame background image

You can do:

setContentPane(new JLabel(new ImageIcon("resources/taverna.jpg")));

At first line of the Jframe class constructor, that works fine for me

Stopping Excel Macro executution when pressing Esc won't work

My laptop did not have Break nor Scr Lock, so I somehow managed to make it work by pressing Ctrl + Function + Right Shift (to activate 'pause').

fatal error: iostream.h no such file or directory

You should be using iostream without the .h.

Early implementations used the .h variants but the standard mandates the more modern style.

How to print instances of a class using print()?

>>> class Test:
...     def __repr__(self):
...         return "Test()"
...     def __str__(self):
...         return "member of Test"
... 
>>> t = Test()
>>> t
Test()
>>> print(t)
member of Test

The __str__ method is what happens when you print it, and the __repr__ method is what happens when you use the repr() function (or when you look at it with the interactive prompt). If this isn't the most Pythonic method, I apologize, because I'm still learning too - but it works.

If no __str__ method is given, Python will print the result of __repr__ instead. If you define __str__ but not __repr__, Python will use what you see above as the __repr__, but still use __str__ for printing.

How to turn on line numbers in IDLE?

If you are trying to track down which line caused an error, if you right-click in the Python shell where the line error is displayed it will come up with a "Go to file/line" which takes you directly to the line in question.

C# - Making a Process.Start wait until the process has start-up

I used the EventWaitHandle class. On the parent process, create a named EventWaitHandle with initial state of the event set to non-signaled. The parent process blocks until the child process calls the Set method, changing the state of the event to signaled, as shown below.

Parent Process:

using System;
using System.Threading;
using System.Diagnostics;

namespace MyParentProcess
{
    class Program
    {
        static void Main(string[] args)
        {
            EventWaitHandle ewh = null;
            try
            {
                ewh = new EventWaitHandle(false, EventResetMode.AutoReset, "CHILD_PROCESS_READY");

                Process process = Process.Start("MyChildProcess.exe", Process.GetCurrentProcess().Id.ToString());
                if (process != null)
                {
                    if (ewh.WaitOne(10000))
                    {
                        // Child process is ready.
                    }
                }
            }
            catch(Exception exception)
            { }
            finally
            {
                if (ewh != null)
                    ewh.Close();
            }
        }
    }
}

Child Process:

using System;
using System.Threading;
using System.Diagnostics;

namespace MyChildProcess
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                // Representing some time consuming work.
                Thread.Sleep(5000);

                EventWaitHandle.OpenExisting("CHILD_PROCESS_READY")
                    .Set();

                Process.GetProcessById(Convert.ToInt32(args[0]))
                    .WaitForExit();
            }
            catch (Exception exception)
            { }
        }
    }
}

pandas: merge (join) two data frames on multiple columns

the problem here is that by using the apostrophes you are setting the value being passed to be a string, when in fact, as @Shijo stated from the documentation, the function is expecting a label or list, but not a string! If the list contains each of the name of the columns beings passed for both the left and right dataframe, then each column-name must individually be within apostrophes. With what has been stated, we can understand why this is inccorect:

new_df = pd.merge(A_df, B_df,  how='left', left_on='[A_c1,c2]', right_on = '[B_c1,c2]')

And this is the correct way of using the function:

new_df = pd.merge(A_df, B_df,  how='left', left_on=['A_c1','c2'], right_on = ['B_c1','c2'])

How to reformat JSON in Notepad++?

You can use http://www.jsonlint.com/ to edit your json online if you don't have Notepad++.

makefile:4: *** missing separator. Stop

Its pretty old question but still I would like say about one more option using vi/vim editor to visualize the tabs. If you have vi/vim installed then open a Makefile (e.g. vim Makefile) and enter :set list. This will show number of tabs inserted as below,

 %-linux: force$
^I@if [ "$(GCC_VERSION)" = "2.96" ] ; then \$
^I^Iecho ===== Generating build tree for legacy $@ architecture =====; \$
^I^I$(CONFIGURE) $(CWD) $@ legacy; \$
^Ielse \$
^I^Iecho ===== Generating build tree for $@ architecture =====; \$
^I^I$(CONFIGURE) $(CWD) $@; \$
^Ifi$
^Icd build-$@;make$

Convert integer to class Date

You can use ymd from lubridate

lubridate::ymd(v)
#[1] "2008-11-01"

Or anytime::anydate

anytime::anydate(v)
#[1] "2008-11-01"

Where does MAMP keep its php.ini?

It depends on which version of PHP your MAMP is using. You can find it out on: /Applications/MAMP/conf/apache/httpd.conf looking for the configured php5_module.

After that, as someone said before, you have to go to the bin folder. There you'll find a conf folder with a php.ini inside.

example: /Applications/MAMP/bin/php/php5.4.10/conf

Leo

How to get the last value of an ArrayList

In case you have a spring project, you can also use the CollectionUtils.lastElement from Spring (javadoc) and you don't need to add an extra dependency like Google Guave if you didn't need to before.

It is null-safe so if you pass null, you will simply receive null in return. Be careful when handling the response though.

Here are somes unit test to demonstrate them:

@Test
void lastElementOfList() {
    var names = List.of("John", "Jane");

    var lastName = CollectionUtils.lastElement(names);

    then(lastName)
        .as("Expected Jane to be the last name in the list")
        .isEqualTo("Jane");
}

@Test
void lastElementOfSet() {
    var names = new TreeSet<>(Set.of("Jane", "John", "James"));

    var lastName = CollectionUtils.lastElement(names);

    then(lastName)
        .as("Expected John to be the last name in the list")
        .isEqualTo("John");
}

Note: org.assertj.core.api.BDDAssertions#then(java.lang.String) is used for assertions.

Simulation of CONNECT BY PRIOR of Oracle in SQL Server

The SQL standard way to implement recursive queries, as implemented e.g. by IBM DB2 and SQL Server, is the WITH clause. See this article for one example of translating a CONNECT BY into a WITH (technically a recursive CTE) -- the example is for DB2 but I believe it will work on SQL Server as well.

Edit: apparently the original querant requires a specific example, here's one from the IBM site whose URL I already gave. Given a table:

CREATE TABLE emp(empid  INTEGER NOT NULL PRIMARY KEY,
                 name   VARCHAR(10),
                 salary DECIMAL(9, 2),
                 mgrid  INTEGER);

where mgrid references an employee's manager's empid, the task is, get the names of everybody who reports directly or indirectly to Joan. In Oracle, that's a simple CONNECT:

SELECT name 
  FROM emp
  START WITH name = 'Joan'
  CONNECT BY PRIOR empid = mgrid

In SQL Server, IBM DB2, or PostgreSQL 8.4 (as well as in the SQL standard, for what that's worth;-), the perfectly equivalent solution is instead a recursive query (more complex syntax, but, actually, even more power and flexibility):

WITH n(empid, name) AS 
   (SELECT empid, name 
    FROM emp
    WHERE name = 'Joan'
        UNION ALL
    SELECT nplus1.empid, nplus1.name 
    FROM emp as nplus1, n
    WHERE n.empid = nplus1.mgrid)
SELECT name FROM n

Oracle's START WITH clause becomes the first nested SELECT, the base case of the recursion, to be UNIONed with the recursive part which is just another SELECT.

SQL Server's specific flavor of WITH is of course documented on MSDN, which also gives guidelines and limitations for using this keyword, as well as several examples.

How to config Tomcat to serve images from an external folder outside webapps?

In Tomcat 7, you can use "aliases" property. From the docs:

This attribute provides a list of external locations from which to load resources for this context. The list of aliases should be of the form "/aliasPath1=docBase1,/aliasPath2=docBase2" where aliasPathN must include a leading '/' and docBaseN must be an absolute path to either a .war file or a directory. A resource will be searched for in the first docBaseN for which aliasPathN is a leading path segment of the resource. If there is no such alias, then the resource will be searched in the usual way. These external locations will not be emptied if the context is un-deployed.

How do I set up CLion to compile and run?

You can also use Microsoft Visual Studio compiler instead of Cygwin or MinGW in Windows environment as the compiler for CLion.

Just go to find Actions in Help and type "Registry" without " and enable CLion.enable.msvc Now configure toolchain with Microsoft Visual Studio Compiler. (You need to download it if not already downloaded)

follow this link for more details: https://www.jetbrains.com/help/clion/quick-tutorial-on-configuring-clion-on-windows.html

Getting min and max Dates from a pandas dataframe

min(df['some_property'])
max(df['some_property'])

The built-in functions work well with Pandas Dataframes.

how to redirect to home page

window.location = '/';

Should usually do the trick, but it depends on your sites directories. This will work for your example

Can't install nuget package because of "Failed to initialize the PowerShell host"

I run this command on powershell (run as admin) and it solve my issue.

reg delete HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\PowerShell /v ExecutionPolicy /f

scp (secure copy) to ec2 instance without password

I've used below command to copy from local linux Centos 7 to AWS EC2.

scp -i user_key.pem file.txt [email protected]:/home/ec2-user

Why do I get "Procedure expects parameter '@statement' of type 'ntext/nchar/nvarchar'." when I try to use sp_executesql?

Sounds like you're calling sp_executesql with a VARCHAR statement, when it needs to be NVARCHAR.

e.g. This will give the error because @SQL needs to be NVARCHAR

DECLARE @SQL VARCHAR(100)
SET @SQL = 'SELECT TOP 1 * FROM sys.tables'
EXECUTE sp_executesql @SQL

So:

DECLARE @SQL NVARCHAR(100)
SET @SQL = 'SELECT TOP 1 * FROM sys.tables'
EXECUTE sp_executesql @SQL

How large should my recv buffer be when calling recv in the socket library

If you have a SOCK_STREAM socket, recv just gets "up to the first 3000 bytes" from the stream. There is no clear guidance on how big to make the buffer: the only time you know how big a stream is, is when it's all done;-).

If you have a SOCK_DGRAM socket, and the datagram is larger than the buffer, recv fills the buffer with the first part of the datagram, returns -1, and sets errno to EMSGSIZE. Unfortunately, if the protocol is UDP, this means the rest of the datagram is lost -- part of why UDP is called an unreliable protocol (I know that there are reliable datagram protocols but they aren't very popular -- I couldn't name one in the TCP/IP family, despite knowing the latter pretty well;-).

To grow a buffer dynamically, allocate it initially with malloc and use realloc as needed. But that won't help you with recv from a UDP source, alas.

jQuery animated number counter from zero to value

This worked for me

HTML CODE

<span class="number-count">841</span>

jQuery Code

$('.number-count').each(function () {
    $(this).prop('Counter',0).animate({
        Counter: $(this).text()
    }, {
        duration: 4000,
        easing: 'swing',
        step: function (now) {
            $(this).text(Math.ceil(now));
        }
    });

Quick Sort Vs Merge Sort

I personally wanted to test the difference between Quick sort and merge sort myself and saw the running times for a sample of 1,000,000 elements.

Quick sort was able to do it in 156 milliseconds whereas Merge sort did the same in 247 milliseconds

The Quick sort data, however, was random and quick sort performs well if the data is random where as its not the case with merge sort i.e. merge sort performs the same, irrespective of whether data is sorted or not. But merge sort requires one full extra space and quick sort does not as its an in-place sort

I have written comprehensive working program for them will illustrative pictures too.

convert an enum to another type of enum

public static TEnum ConvertByName<TEnum>(this Enum source, bool ignoreCase = false) where TEnum : struct
{
    // if limited by lack of generic enum constraint
    if (!typeof(TEnum).IsEnum)
    {
        throw new InvalidOperationException("enumeration type required.");
    }

    TEnum result;
    if (!Enum.TryParse(source.ToString(), ignoreCase, out result))
    {
        throw new Exception("conversion failure.");
    }

    return result;
}

How to replace ${} placeholders in a text file?

I would suggest using something like Sigil: https://github.com/gliderlabs/sigil

It is compiled to a single binary, so it's extremely easy to install on systems.

Then you can do a simple one-liner like the following:

cat my-file.conf.template | sigil -p $(env) > my-file.conf

This is much safer than eval and easier then using regex or sed

CSS full screen div with text in the middle

There is no pure CSS solution to this classical problem.

If you want to achieve this, you have two solutions:

  • Using a table (ugly, non semantic, but the only way to vertically align things that are not a single line of text)
  • Listening to window.resize and absolute positionning

EDIT: when I say that there is no solution, I take as an hypothesis that you don't know in advance the size of the block to center. If you know it, paislee's solution is very good

How can I get table names from an MS Access Database?

You can use schemas in Access.

Sub ListAccessTables2(strDBPath)
   Dim cnnDB As ADODB.Connection
   Dim rstList As ADODB.Recordset

   Set cnnDB = New ADODB.Connection

   ' Open the connection.
   With cnnDB
      .Provider = "Microsoft.Jet.OLEDB.4.0"
      .Open strDBPath
   End With

   ' Open the tables schema rowset.
   Set rstList = cnnDB.OpenSchema(adSchemaTables)

   ' Loop through the results and print the
   ' names and types in the Immediate pane.
   With rstList
      Do While Not .EOF
         If .Fields("TABLE_TYPE") <> "VIEW" Then
            Debug.Print .Fields("TABLE_NAME") & vbTab & _
               .Fields("TABLE_TYPE")
         End If
         .MoveNext
      Loop
   End With
   cnnDB.Close
   Set cnnDB = Nothing
End Sub

From: http://msdn.microsoft.com/en-us/library/aa165325(office.10).aspx

How to add custom Http Header for C# Web Service Client consuming Axis 1.4 Web service

Instead of modding the auto-generated code or wrapping every call in duplicate code, you can inject your custom HTTP headers by adding a custom message inspector, it's easier than it sounds:

public class CustomMessageInspector : IClientMessageInspector
{
    readonly string _authToken;

    public CustomMessageInspector(string authToken)
    {
        _authToken = authToken;
    }

    public object BeforeSendRequest(ref Message request, IClientChannel channel)
    {
        var reqMsgProperty = new HttpRequestMessageProperty();
        reqMsgProperty.Headers.Add("Auth-Token", _authToken);
        request.Properties[HttpRequestMessageProperty.Name] = reqMsgProperty;
        return null;
    }

    public void AfterReceiveReply(ref Message reply, object correlationState)
    { }
}


public class CustomAuthenticationBehaviour : IEndpointBehavior
{
    readonly string _authToken;

    public CustomAuthenticationBehaviour (string authToken)
    {
        _authToken = authToken;
    }
    public void Validate(ServiceEndpoint endpoint)
    { }

    public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
    { }

    public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
    { }

    public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
    {
        clientRuntime.ClientMessageInspectors.Add(new CustomMessageInspector(_authToken));
    }
}

And when instantiating your client class you can simply add it as a behavior:

this.Endpoint.EndpointBehaviors.Add(new CustomAuthenticationBehaviour("Auth Token"));

This will make every outgoing service call to have your custom HTTP header.

Chrome - ERR_CACHE_MISS

This is a known issue in Chrome and resolved in latest versions. Please refer https://bugs.chromium.org/p/chromium/issues/detail?id=942440 for more details.

Custom fonts and XML layouts (Android)

Extend TextView and give it a custom attribute or just use the android:tag attribute to pass in a String of what font you want to use. You will need to pick a convention and stick to it such as I will put all of my fonts in the res/assets/fonts/ folder so your TextView class knows where to find them. Then in your constructor you just set the font manually after the super call.

foreach vs someList.ForEach(){}

For fun, I popped List into reflector and this is the resulting C#:

public void ForEach(Action<T> action)
{
    if (action == null)
    {
        ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match);
    }
    for (int i = 0; i < this._size; i++)
    {
        action(this._items[i]);
    }
}

Similarly, the MoveNext in Enumerator which is what is used by foreach is this:

public bool MoveNext()
{
    if (this.version != this.list._version)
    {
        ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumFailedVersion);
    }
    if (this.index < this.list._size)
    {
        this.current = this.list._items[this.index];
        this.index++;
        return true;
    }
    this.index = this.list._size + 1;
    this.current = default(T);
    return false;
}

The List.ForEach is much more trimmed down than MoveNext - far less processing - will more likely JIT into something efficient..

In addition, foreach() will allocate a new Enumerator no matter what. The GC is your friend, but if you're doing the same foreach repeatedly, this will make more throwaway objects, as opposed to reusing the same delegate - BUT - this is really a fringe case. In typical usage you will see little or no difference.

Response.Redirect to new window

Here's a jQuery version based on the answer by @takrl and @tom above. Note: no hardcoded formid (named aspnetForm above) and also does not use direct form.target references which Firefox may find problematic:

<asp:Button ID="btnSubmit" OnClientClick="openNewWin();"  Text="Submit" OnClick="btn_OnClick" runat="server"/>

Then in your js file referenced on the SAME page:

function openNewWin () {
    $('form').attr('target','_blank');
    setTimeout('resetFormTarget()', 500);
}

function resetFormTarget(){
    $('form').attr('target','');
}

Accessing the logged-in user in a template

{{ app.user.username|default('') }}

Just present login username for example, filter function default('') should be nice when user is NOT login by just avoid annoying error message.

Storing Form Data as a Session Variable

To use session variables, it's necessary to start the session by using the session_start function, this will allow you to store your data in the global variable $_SESSION in a productive way.

so your code will finally look like this :

<strong>Test Form</strong>
<form action="" method"post">
<input type="text" name="picturenum"/>
<input type="submit" name="Submit" value="Submit!" />
</form>

<?php 
 
 // starting the session
 session_start();


 if (isset($_POST['Submit'])) { 
 $_SESSION['picturenum'] = $_POST['picturenum'];
 } 
?> 

<strong><?php echo $_SESSION['picturenum'];?></strong>

to make it easy to use and to avoid forgetting it again, you can create a session_file.php which you will want to be included in all your codes and will start the session for you:

session_start.php

 <?php
   session_start();
 ?> 

and then include it wherever you like :

<strong>Test Form</strong>
<form action="" method"post">
<input type="text" name="picturenum"/>
<input type="submit" name="Submit" value="Submit!" />
</form>

<?php 
 
 // including the session file
 require_once("session_start.php");


 if (isset($_POST['Submit'])) { 
 $_SESSION['picturenum'] = $_POST['picturenum'];
 } 
?> 

that way it is more portable and easy to maintain in the future.

other remarks

  • if you are using Apache version 2 or newer, be careful. instead of
    <?
    to open php's tags, use <?php, otherwise your code will not be interpreted

  • variables names in php are case-sensitive, instead of write $_session, write $_SESSION in capital letters

good work!

Indentation Error in Python

Did you maybe use some <tab> instead of spaces?

Try remove all the spaces before the code and readd them using <space> characters, just to be sure it's not a <tab>.

The character encoding of the plain text document was not declared - mootool script

In your HTML it is a good pratice to provide the encoding like using the following meta like this for example:

<meta http-equiv="content-type" content="text/html; charset=utf-8" />

But your warning that you see may be trigged by one of multiple files. it might not be your HTML document. It might be something in a javascript file or css file. if you page is made of up multiples php files included together it may be only 1 of those files.

I dont think this error has anything to do with mootools. you see this message in your firefox console window. not mootools script.

maybe you simply need to re-save your html pages using a code editor that lets you specify the correct character encoding.

Embedding a media player in a website using HTML

Definitely the HTML5 element is the way to go. There's at least basic support for it in the most recent versions of almost all browsers:

http://caniuse.com/#feat=audio

And it allows to specify what to do when the element is not supported by the browser. For example you could add a link to a file by doing:

<audio controls src="intro.mp3">
   <a href="intro.mp3">Introduction to HTML5 (10:12) - MP3 - 3.2MB</a>
</audio>

You can find this examples and more information about the audio element in the following link:

http://hacks.mozilla.org/2012/04/enhanceyourhtml5appwithaudio/

Finally, the good news are that mozilla's April's dev Derby is about this element so that's probably going to provide loads of great examples of how to make the most out of this element:

http://hacks.mozilla.org/2012/04/april-dev-derby-show-us-what-you-can-do-with-html5-audio/

UIButton Image + Text IOS

I encountered the same problem, and I fix it by creating a new subclass of UIButton and overriding the layoutSubviews: method as below :

-(void)layoutSubviews {
    [super layoutSubviews];

    // Center image
    CGPoint center = self.imageView.center;
    center.x = self.frame.size.width/2;
    center.y = self.imageView.frame.size.height/2;
    self.imageView.center = center;

    //Center text
    CGRect newFrame = [self titleLabel].frame;
    newFrame.origin.x = 0;
    newFrame.origin.y = self.imageView.frame.size.height + 5;
    newFrame.size.width = self.frame.size.width;

    self.titleLabel.frame = newFrame;
    self.titleLabel.textAlignment = UITextAlignmentCenter;

}

I think that the Angel García Olloqui's answer is another good solution, if you place all of them manually with interface builder but I'll keep my solution since I don't have to modify the content insets for each of my button.

How can I get the source directory of a Bash script from within the script itself?

Here is a POSIX compliant one-liner:

SCRIPT_PATH=`dirname "$0"`; SCRIPT_PATH=`eval "cd \"$SCRIPT_PATH\" && pwd"`

# test
echo $SCRIPT_PATH

How do I configure HikariCP in my Spring Boot app in my application.properties files?

My SetUp:
Spring Boot v1.5.10
Hikari v.3.2.x (for evaluation)

To really understand the configuration of Hikari Data Source, I recommend to disable Spring Boot's Auto-Configuration for Data Source.

Add following to application.properties:-

spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration

This will disable Spring Boot's capability to configure the DataSource on its own.

Now is the chance for you to define your own Custom Configuration to create HikariDataSource bean and populate it with the desired properties.

NOTE :::
public class HikariDataSource extends HikariConfig

You need to

  1. populate HikariConfig Object using desired Hikari Properties
  2. initialize HikariDataSource object with HikariConfig object passed as an argument to constructor.

I believe in defining my own Custom Configuration class ( @Configuration ) to create the data source on my own and populate it with the data source properties defined in a separate file (than traditional: application.properties)

In this manner I can define my own sessionFactory Bean using Hibernate recommended: "LocalSessionFactoryBean" class and populate it with your Hikari Data Source > and other Hiberante-JPA based properties.

Summary of Spring Boot based Hikari DataSource Properties:-

spring.datasource.hikari.allow-pool-suspension=true
spring.datasource.hikari.auto-commit=false
spring.datasource.hikari.catalog=
spring.datasource.hikari.connection-init-sql=
spring.datasource.hikari.connection-test-query=
spring.datasource.hikari.connection-timeout=100
spring.datasource.hikari.data-source-class-name=
spring.datasource.hikari.data-source-j-n-d-i=
spring.datasource.hikari.driver-class-name=
spring.datasource.hikari.idle-timeout=50
spring.datasource.hikari.initialization-fail-fast=true
spring.datasource.hikari.isolate-internal-queries=true
spring.datasource.hikari.jdbc-url=
spring.datasource.hikari.leak-detection-threshold=
spring.datasource.hikari.login-timeout=60
spring.datasource.hikari.max-lifetime=
spring.datasource.hikari.maximum-pool-size=500
spring.datasource.hikari.minimum-idle=30
spring.datasource.hikari.password=
spring.datasource.hikari.pool-name=
spring.datasource.hikari.read-only=true
spring.datasource.hikari.register-mbeans=true
spring.datasource.hikari.transaction-isolation=
spring.datasource.hikari.username=
spring.datasource.hikari.validation-timeout=

Logical operators for boolean indexing in Pandas

Logical operators for boolean indexing in Pandas

It's important to realize that you cannot use any of the Python logical operators (and, or or not) on pandas.Series or pandas.DataFrames (similarly you cannot use them on numpy.arrays with more than one element). The reason why you cannot use those is because they implicitly call bool on their operands which throws an Exception because these data structures decided that the boolean of an array is ambiguous:

>>> import numpy as np
>>> import pandas as pd
>>> arr = np.array([1,2,3])
>>> s = pd.Series([1,2,3])
>>> df = pd.DataFrame([1,2,3])
>>> bool(arr)
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
>>> bool(s)
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
>>> bool(df)
ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

I did cover this more extensively in my answer to the "Truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()" Q+A.

NumPys logical functions

However NumPy provides element-wise operating equivalents to these operators as functions that can be used on numpy.array, pandas.Series, pandas.DataFrame, or any other (conforming) numpy.array subclass:

So, essentially, one should use (assuming df1 and df2 are pandas DataFrames):

np.logical_and(df1, df2)
np.logical_or(df1, df2)
np.logical_not(df1)
np.logical_xor(df1, df2)

Bitwise functions and bitwise operators for booleans

However in case you have boolean NumPy array, pandas Series, or pandas DataFrames you could also use the element-wise bitwise functions (for booleans they are - or at least should be - indistinguishable from the logical functions):

Typically the operators are used. However when combined with comparison operators one has to remember to wrap the comparison in parenthesis because the bitwise operators have a higher precedence than the comparison operators:

(df1 < 10) | (df2 > 10)  # instead of the wrong df1 < 10 | df2 > 10

This may be irritating because the Python logical operators have a lower precendence than the comparison operators so you normally write a < 10 and b > 10 (where a and b are for example simple integers) and don't need the parenthesis.

Differences between logical and bitwise operations (on non-booleans)

It is really important to stress that bit and logical operations are only equivalent for boolean NumPy arrays (and boolean Series & DataFrames). If these don't contain booleans then the operations will give different results. I'll include examples using NumPy arrays but the results will be similar for the pandas data structures:

>>> import numpy as np
>>> a1 = np.array([0, 0, 1, 1])
>>> a2 = np.array([0, 1, 0, 1])

>>> np.logical_and(a1, a2)
array([False, False, False,  True])
>>> np.bitwise_and(a1, a2)
array([0, 0, 0, 1], dtype=int32)

And since NumPy (and similarly pandas) does different things for boolean (Boolean or “mask” index arrays) and integer (Index arrays) indices the results of indexing will be also be different:

>>> a3 = np.array([1, 2, 3, 4])

>>> a3[np.logical_and(a1, a2)]
array([4])
>>> a3[np.bitwise_and(a1, a2)]
array([1, 1, 1, 2])

Summary table

Logical operator | NumPy logical function | NumPy bitwise function | Bitwise operator
-------------------------------------------------------------------------------------
       and       |  np.logical_and        | np.bitwise_and         |        &
-------------------------------------------------------------------------------------
       or        |  np.logical_or         | np.bitwise_or          |        |
-------------------------------------------------------------------------------------
                 |  np.logical_xor        | np.bitwise_xor         |        ^
-------------------------------------------------------------------------------------
       not       |  np.logical_not        | np.invert              |        ~

Where the logical operator does not work for NumPy arrays, pandas Series, and pandas DataFrames. The others work on these data structures (and plain Python objects) and work element-wise. However be careful with the bitwise invert on plain Python bools because the bool will be interpreted as integers in this context (for example ~False returns -1 and ~True returns -2).

What is "runtime"?

I found that the following folder structure makes a very insightful context for understanding what runtime is:

Runtimes of Mozilla XulRunner

You can see that there is the 'source', there is the 'SDK' or 'Software Development Kit' and then there is the Runtime, eg. the stuff that gets run - at runtime. It's contents are like:

runtimes' folder contents

The win32 zip contains .exe -s and .dll -s.

So eg. the C runtime would be the files like this -- C runtime libraries, .so-s or .dll -s -- you run at runtime, made special by their (or their contents' or purposes') inclusion in the definition of the C language (on 'paper'), then implemented by your C implementation of choice. And then you get the runtime of that implementation, to use it and to build upon it.

That is, with a little polarisation, the runnable files that the users of your new C-based program will need. As a developer of a C-based program, so do you, but you need the C compiler and the C library headers, too; the users don't need those.

How can I access each element of a pair in a pair list?

A 2-tuple is a pair. You can access the first and second elements like this:

x = ('a', 1) # make a pair
x[0] # access 'a'
x[1] # access 1

What is the "hasClass" function with plain JavaScript?

What do you think about this approach?

<body class="thatClass anotherClass"> </body>

var bodyClasses = document.querySelector('body').className;
var myClass = new RegExp("thatClass");
var trueOrFalse = myClass.test( bodyClasses );

https://jsfiddle.net/5sv30bhe/

How do I obtain crash-data from my Android application?

You might try the ACRA (Application Crash Report for Android) library:

ACRA is a library enabling Android Application to automatically post their crash reports to a GoogleDoc form. It is targetted to android applications developers to help them get data from their applications when they crash or behave erroneously.

It's easy to install in your app, highly configurable and don't require you to host a server script anywhere... reports are sent to a Google Doc spreadsheet !

How to set TLS version on apache HttpClient

The solution is:

SSLContext sslContext = SSLContexts.custom()
    .useTLS()
    .build();

SSLConnectionSocketFactory f = new SSLConnectionSocketFactory(
    sslContext,
    new String[]{"TLSv1", "TLSv1.1"},   
    null,
    BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);

httpClient = HttpClients.custom()
    .setSSLSocketFactory(f)
    .build();

This requires org.apache.httpcomponents.httpclient 4.3.x though.

read complete file without using loop in java

Since Java 11 you can do it even simpler:

import java.nio.file.Files;

Files.readString(Path path);
Files.readString?(Path path, Charset cs)

Source: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/nio/file/Files.html#readString(java.nio.file.Path)

GSON throwing "Expected BEGIN_OBJECT but was BEGIN_ARRAY"?

The problem is that you are asking for an object of type ChannelSearchEnum but what you actually have is an object of type List<ChannelSearchEnum>.

You can achieve this with:

Type collectionType = new TypeToken<List<ChannelSearchEnum>>(){}.getType();
List<ChannelSearchEnum> lcs = (List<ChannelSearchEnum>) new Gson()
               .fromJson( jstring , collectionType);

IF... OR IF... in a windows batch file

A simple "FOR" can be used in a single line to use an "or" condition:

FOR %%a in (item1 item2 ...) DO IF {condition_involving_%%a} {execute_command}  

Applied to your case:

FOR %%a in (1 2) DO IF %var%==%%a ECHO TRUE

Suppress executing twice

A comment pointed out that {execute_command} may be encountered twice. To avoid this, you can use a goto after the first encounter.

FOR %%a in (1 2) DO IF %var%==%%a (
    ECHO TRUE
    goto :continue
)
:continue 

If you think there's a possibility that {execute_command} might be executed twice and you don't want that, you can just add && goto :eof:

FOR %%a in (1 2) DO IF %var%==%%a ECHO TRUE && goto :eof

Much simpler, and still on a single line.

SQL how to check that two tables has exactly the same data?

dietbuddha has a nice answer. In cases where you don't have a MINUS or EXCEPT, one option is to do a union all between the tables, group by with all the columns and make sure there is two of everything:

SELECT col1, col2, col3
FROM
(SELECT * FROM tableA
UNION ALL  
SELECT * FROM tableB) data
GROUP BY col1, col2, col3
HAVING count(*)!=2

Can an html element have multiple ids?

No. From the XHTML 1.0 Spec

In XML, fragment identifiers are of type ID, and there can only be a single attribute of type ID per element. Therefore, in XHTML 1.0 the id attribute is defined to be of type ID. In order to ensure that XHTML 1.0 documents are well-structured XML documents, XHTML 1.0 documents MUST use the id attribute when defining fragment identifiers on the elements listed above. See the HTML Compatibility Guidelines for information on ensuring such anchors are backward compatible when serving XHTML documents as media type text/html.

How to set corner radius of imageView?

Marked with @IBInspectable in swift (or IBInspectable in Objective-C), they are easily editable in Interface Builder’s attributes inspector panel.
You can directly set borderWidth,cornerRadius,borderColor in attributes inspector

extension UIView {

  @IBInspectable var cornerRadius: CGFloat {

   get{
        return layer.cornerRadius
    }
    set {
        layer.cornerRadius = newValue
        layer.masksToBounds = newValue > 0
    }
  }

  @IBInspectable var borderWidth: CGFloat {
    get {
        return layer.borderWidth
    }
    set {
        layer.borderWidth = newValue
    }
  }

  @IBInspectable var borderColor: UIColor? {
    get {
        return UIColor(cgColor: layer.borderColor!)
    }
    set {
        layer.borderColor = borderColor?.cgColor
    }
  }
}

enter image description here

Rails: Get Client IP address

I would just use the request.remote_ip that's simple and it works. Any reason you need another method?

See: Get real IP address in local Rails development environment for some other things you can do with client server ip's.

How do I retrieve a textbox value using JQuery?

You need to use the val() function to get the textbox value. text does not exist as a property only as a function and even then its not the correct function to use in this situation.

var from = $("input#fromAddress").val()

val() is the standard function for getting the value of an input.

How to use JavaScript with Selenium WebDriver Java

JavaScript With Selenium WebDriver

Selenium is one of the most popular automated testing suites. Selenium is designed in a way to support and encourage automation testing of functional aspects of web based applications and a wide range of browsers and platforms.

    public static WebDriver driver;
    public static void main(String[] args) {
        driver = new FirefoxDriver(); // This opens a window    
        String url = "----";


        /*driver.findElement(By.id("username")).sendKeys("yashwanth.m");
        driver.findElement(By.name("j_password")).sendKeys("yashwanth@123");*/

        JavascriptExecutor jse = (JavascriptExecutor) driver;       
        if (jse instanceof WebDriver) {
            //Launching the browser application
            jse.executeScript("window.location = \'"+url+"\'");
jse.executeScript("document.getElementById('username').value = \"yash\";");
// Tag having name then
driver.findElement(By.xpath(".//input[@name='j_password']")).sendKeys("admin");


//Opend Site and click on some links. then you can apply go(-1)--> back  forword(-1)--> front.
//Refresheing the web-site. driver.navigate().refresh();            
jse.executeScript("window.history.go(0)");
            jse.executeScript("window.history.go(-2)");
            jse.executeScript("window.history.forward(-2)");

            String title = (String)jse.executeScript("return document.title");
            System.out.println(" Title Of site : "+title);

            String domain = (String)jse.executeScript("return document.domain");
            System.out.println("Web Site Domain-Name : "+domain);

            // To get all NodeList[1052] document.querySelectorAll('*');  or document.all
            jse.executeAsyncScript("document.getElementsByTagName('*')");

            String error=(String) jse.executeScript("return window.jsErrors");
            System.out.println("Windowerrors  :   "+error);



            System.out.println("To Find the input tag position from top"); 
            ArrayList<?> al =  (ArrayList<?>) jse.executeScript(
                    "var source = [];"+
                    "var inputs = document.getElementsByTagName('input');"+
                    "for(var i = 0; i < inputs.length; i++) { " +
                       "   source[i] = inputs[i].offsetParent.offsetTop" +      //"    inputs[i].type = 'radio';"
                    "}"+
                    "return source"                 
                    );//inputs[i].offsetParent.offsetTop     inputs[i].type

            System.out.println("next");
            System.out.println("array : "+al);

            // (CTRL + a) to access keyboard keys. org.openqa.selenium.Keys 
            Keys k = null;
            String selectAll = Keys.chord(Keys.CONTROL, "a");
            WebElement body = driver.findElement(By.tagName("body"));
            body.sendKeys(selectAll);

            // Search for text in Site. Gets all ViewSource content and checks their.
            if (driver.getPageSource().contains("login")) {
                System.out.println("Text present in Web Site");
            }

        Long clent_height = (Long) jse.executeScript("return document.body.clientHeight");
        System.out.println("Client Body Height : "+clent_height);

        // using selenium we con only execute script but not JS-functions.

    }
    driver.quit(); // to close browser
}

To Execute User-Functions, Writing JS in to a file and reading as String and executing it to easily use.

Scanner sc = new Scanner(new FileInputStream(new File("JsFile.txt")));
        String js_TxtFile = ""; 
            while (sc.hasNext()) {          
                String[] s = sc.next().split("\r\n");   
                for (int i = 0; i < s.length; i++) {
                    js_TxtFile += s[i];
                    js_TxtFile += " ";
                }           
            }
        String title =  (String) jse.executeScript(js_TxtFile);
        System.out.println("Title  : "+title);

document.title & document.getElementById() is a property/method available in Browsers.

JsFile.txt

var title = getTitle();
return title;

function getTitle() {
    return document.title;
}

PHP session lost after redirect

Another possible reason:

That is my server storage space. My server disk space become full. So, I have removed few files and folders in my server and tried.

It was worked!!!

I am saving my session in AWS Dynamo DB, but it still expects some space in my server to process the session. Not sure why!!!

High-precision clock in Python

If Python 3 is an option, you have two choices:

  • time.perf_counter which always use the most accurate clock on your platform. It does include time spent outside of the process.
  • time.process_time which returns the CPU time. It does NOT include time spent outside of the process.

The difference between the two can be shown with:

from time import (
    process_time,
    perf_counter,
    sleep,
)

print(process_time())
sleep(1)
print(process_time())

print(perf_counter())
sleep(1)
print(perf_counter())

Which outputs:

0.03125
0.03125
2.560001310720671e-07
1.0005455362793145

Pass react component as props

As noted in the accepted answer - you can use the special { props.children } property. However - you can just pass a component as a prop as the title requests. I think this is cleaner sometimes as you might want to pass several components and have them render in different places. Here's the react docs with an example of how to do it:

https://reactjs.org/docs/composition-vs-inheritance.html

Make sure you are actually passing a component and not an object (this tripped me up initially).

The code is simply this:

const Parent = () => { 
  return (
    <Child  componentToPassDown={<SomeComp />}  />
  )
}

const Child = ({ componentToPassDown }) => { 
  return (
    <>
     {componentToPassDown}  
    </>
  )
}

Table variable error: Must declare the scalar variable "@temp"

You've declared @TEMP but in your insert statement used @temp. Case sensitive variable names.

Change @temp to @TEMP

How to map to multiple elements with Java 8 streams?

It's an interesting question, because it shows that there are a lot of different approaches to achieve the same result. Below I show three different implementations.


Default methods in Collection Framework: Java 8 added some methods to the collections classes, that are not directly related to the Stream API. Using these methods, you can significantly simplify the implementation of the non-stream implementation:

Collection<DataSet> convert(List<MultiDataPoint> multiDataPoints) {
    Map<String, DataSet> result = new HashMap<>();
    multiDataPoints.forEach(pt ->
        pt.keyToData.forEach((key, value) ->
            result.computeIfAbsent(
                key, k -> new DataSet(k, new ArrayList<>()))
            .dataPoints.add(new DataPoint(pt.timestamp, value))));
    return result.values();
}

Stream API with flatten and intermediate data structure: The following implementation is almost identical to the solution provided by Stuart Marks. In contrast to his solution, the following implementation uses an anonymous inner class as intermediate data structure.

Collection<DataSet> convert(List<MultiDataPoint> multiDataPoints) {
    return multiDataPoints.stream()
        .flatMap(mdp -> mdp.keyToData.entrySet().stream().map(e ->
            new Object() {
                String key = e.getKey();
                DataPoint dataPoint = new DataPoint(mdp.timestamp, e.getValue());
            }))
        .collect(
            collectingAndThen(
                groupingBy(t -> t.key, mapping(t -> t.dataPoint, toList())),
                m -> m.entrySet().stream().map(e -> new DataSet(e.getKey(), e.getValue())).collect(toList())));
}

Stream API with map merging: Instead of flattening the original data structures, you can also create a Map for each MultiDataPoint, and then merge all maps into a single map with a reduce operation. The code is a bit simpler than the above solution:

Collection<DataSet> convert(List<MultiDataPoint> multiDataPoints) {
    return multiDataPoints.stream()
        .map(mdp -> mdp.keyToData.entrySet().stream()
            .collect(toMap(e -> e.getKey(), e -> asList(new DataPoint(mdp.timestamp, e.getValue())))))
        .reduce(new HashMap<>(), mapMerger())
        .entrySet().stream()
        .map(e -> new DataSet(e.getKey(), e.getValue()))
        .collect(toList());
}

You can find an implementation of the map merger within the Collectors class. Unfortunately, it is a bit tricky to access it from the outside. Following is an alternative implementation of the map merger:

<K, V> BinaryOperator<Map<K, List<V>>> mapMerger() {
    return (lhs, rhs) -> {
        Map<K, List<V>> result = new HashMap<>();
        lhs.forEach((key, value) -> result.computeIfAbsent(key, k -> new ArrayList<>()).addAll(value));
        rhs.forEach((key, value) -> result.computeIfAbsent(key, k -> new ArrayList<>()).addAll(value));
        return result;
    };
}

jQuery, checkboxes and .is(":checked")

In addition to Nick Craver's answer, for this to work properly on IE 8 you need to add a additional click handler to the checkbox:

// needed for IE 8 compatibility
if ($.browser.msie)
    $("#myCheckbox").click(function() { $(this).trigger('change'); });

$("#myCheckbox").change( function() {
    alert($(this).is(":checked"));
});

//Trigger by:
$("#myCheckbox").trigger('click').trigger('change');

Otherwise the callback will only be triggered when the checkbox loses focus, as IE 8 keeps focus on checkboxes and radios when they are clicked.

Haven't tested on IE 9 though.

How do I return clean JSON from a WCF Service?

This is accomplished in web.config for your webservice. Set the bindingBehavior to <webHttp> and you will see the clean JSON. The extra "[d]" is set by the default behavior which you need to overwrite.

See in addition this blogpost: http://blog.clauskonrad.net/2010/11/how-to-expose-json-endpoint-from-wcf.html

How can I get npm start at a different directory?

npm start --prefix path/to/your/app

& inside package.json add the following script

"scripts": {
   "preinstall":"cd $(pwd)"
}

Is there a NumPy function to return the first index of something in an array?

For one-dimensional sorted arrays, it would be much more simpler and efficient O(log(n)) to use numpy.searchsorted which returns a NumPy integer (position). For example,

arr = np.array([1, 1, 1, 2, 3, 3, 4])
i = np.searchsorted(arr, 3)

Just make sure the array is already sorted

Also check if returned index i actually contains the searched element, since searchsorted's main objective is to find indices where elements should be inserted to maintain order.

if arr[i] == 3:
    print("present")
else:
    print("not present")

HTTP post XML data in C#

AlliterativeAlice's example helped me tremendously. In my case, though, the server I was talking to didn't like having single quotes around utf-8 in the content type. It failed with a generic "Server Error" and it took hours to figure out what it didn't like:

request.ContentType = "text/xml; encoding=utf-8";

SQL Server: Database stuck in "Restoring" state

RESTORE DATABASE {DatabaseName}
   FROM DISK = '{databasename}.bak'
   WITH REPLACE, RECOVERY

jquery: get value of custom attribute

You can also do this by passing function with onclick event

<a onclick="getColor(this);" color="red">

<script type="text/javascript">

function getColor(el)
{
     color = $(el).attr('color');
     alert(color);
}

</script> 

How to dismiss AlertDialog in android

Actually there is no any cancel() or dismiss() method from AlertDialog.Builder Class.

So Instead of AlertDialog.Builder optionDialog use AlertDialog instance.

Like,

AlertDialog optionDialog = new AlertDialog.Builder(this).create();

Now, Just call optionDialog.dismiss();

background.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
        SetBackground();
        // here I want to dismiss it after SetBackground() method 
        optionDialog.dismiss();
    }
});

Getting msbuild.exe without installing Visual Studio

It used to be installed with the .NET framework. MsBuild v12.0 (2013) is now bundled as a stand-alone utility and has it's own installer.

http://www.microsoft.com/en-us/download/confirmation.aspx?id=40760

To reference the location of MsBuild.exe from within an MsBuild script, use the default $(MsBuildToolsPath) property.

How to add shortcut keys for java code in eclipse

Type "Sysout" and then Ctrl+Space. It expands to

System.out.println();

how to send a post request with a web browser

You can create an html page with a form, having method="post" and action="yourdesiredurl" and open it with your browser.

As an alternative, there are some browser plugins for developers that allow you to do that, like Web Developer Toolbar for Firefox

How to save as a new file and keep working on the original one in Vim?

Use the :w command with a filename:

:w other_filename

How to get HttpRequestMessage data

From this answer:

[HttpPost]
public void Confirmation(HttpRequestMessage request)
{
    var content = request.Content;
    string jsonContent = content.ReadAsStringAsync().Result;
}

Note: As seen in the comments, this code could cause a deadlock and should not be used. See this blog post for more detail.

Shift column in pandas dataframe up by one?

df.gdp = df.gdp.shift(-1) ## shift up
df.gdp.drop(df.gdp.shape[0] - 1,inplace = True) ## removing the last row

Printing chars and their ASCII-code in C

#include<stdio.h>
 void main()
{
char a;
scanf("%c",&a);
printf("%d",a);
}

Fine control over the font size in Seaborn plots for academic papers

You are right. This is a badly documented issue. But you can change the font size parameter (by opposition to font scale) directly after building the plot. Check the following example:

import seaborn as sns
tips = sns.load_dataset("tips")

b = sns.boxplot(x=tips["total_bill"])
b.axes.set_title("Title",fontsize=50)
b.set_xlabel("X Label",fontsize=30)
b.set_ylabel("Y Label",fontsize=20)
b.tick_params(labelsize=5)
sns.plt.show()

, which results in this:

Different font sizes for different labels

To make it consistent in between plots I think you just need to make sure the DPI is the same. By the way it' also a possibility to customize a bit the rc dictionaries since "font.size" parameter exists but I'm not too sure how to do that.

NOTE: And also I don't really understand why they changed the name of the font size variables for axis labels and ticks. Seems a bit un-intuitive.

Convert a RGB Color Value to a Hexadecimal String

This is an adapted version of the answer given by Vivien Barousse with the update from Vulcan applied. In this example I use sliders to dynamically retreive the RGB values from three sliders and display that color in a rectangle. Then in method toHex() I use the values to create a color and display the respective Hex color code.

This example does not include the proper constraints for the GridBagLayout. Though the code will work, the display will look strange.

public class HexColor
{

  public static void main (String[] args)
  {
   JSlider sRed = new JSlider(0,255,1);
   JSlider sGreen = new JSlider(0,255,1);
   JSlider sBlue = new JSlider(0,255,1);
   JLabel hexCode = new JLabel();
   JPanel myPanel = new JPanel();
   GridBagLayout layout = new GridBagLayout();
   JFrame frame = new JFrame();

   //set frame to organize components using GridBagLayout 
   frame.setLayout(layout);

   //create gray filled rectangle 
   myPanel.paintComponent();
   myPanel.setBackground(Color.GRAY);

   //In practice this code is replicated and applied to sGreen and sBlue. 
   //For the sake of brevity I only show sRed in this post.
   sRed.addChangeListener(
         new ChangeListener()
         {
             @Override
             public void stateChanged(ChangeEvent e){
                 myPanel.setBackground(changeColor());
                 myPanel.repaint();
                 hexCode.setText(toHex());
         }
         }
     );
   //add each component to JFrame
   frame.add(myPanel);
   frame.add(sRed);
   frame.add(sGreen);
   frame.add(sBlue);
   frame.add(hexCode);
} //end of main

  //creates JPanel filled rectangle
  protected void paintComponent(Graphics g)
  {
      super.paintComponent(g);
      g.drawRect(360, 300, 10, 10);
      g.fillRect(360, 300, 10, 10);
  }

  //changes the display color in JPanel
  private Color changeColor()
  {
    int r = sRed.getValue();
    int b = sBlue.getValue();
    int g = sGreen.getValue();
    Color c;
    return  c = new Color(r,g,b);
  }

  //Displays hex representation of displayed color
  private String toHex()
  {
      Integer r = sRed.getValue();
      Integer g = sGreen.getValue();
      Integer b = sBlue.getValue();
      Color hC;
      hC = new Color(r,g,b);
      String hex = Integer.toHexString(hC.getRGB() & 0xffffff);
      while(hex.length() < 6){
          hex = "0" + hex;
      }
      hex = "Hex Code: #" + hex;
      return hex;
  }
}

A huge thank you to both Vivien and Vulcan. This solution works perfectly and was super simple to implement.

Replace a value if null or undefined in JavaScript

Logical nullish assignment, 2020+ solution

A new operator has been added, ??=. This is equivalent to value = value ?? defaultValue.

||= and &&= are similar, links below.

This checks if left side is undefined or null, short-circuiting if already defined. If not, the left side is assigned the right-side value.

Basic Examples

let a          // undefined
let b = null
let c = false

a ??= true  // true
b ??= true  // true
c ??= true  // false

// Equivalent to
a = a ?? true

Object/Array Examples

let x = ["foo"]
let y = { foo: "fizz" }

x[0] ??= "bar"  // "foo"
x[1] ??= "bar"  // "bar"

y.foo ??= "buzz"  // "fizz"
y.bar ??= "buzz"  // "buzz"

x  // Array [ "foo", "bar" ]
y  // Object { foo: "fizz", bar: "buzz" }

Functional Example

function config(options) {
    options.duration ??= 100
    options.speed ??= 25
    return options
}

config({ duration: 555 })   // { duration: 555, speed: 25 }
config({})                  // { duration: 100, speed: 25 }
config({ duration: null })  // { duration: 100, speed: 25 }

??= Browser Support Nov 2020 - 77%

??= Mozilla Documentation

||= Mozilla Documentation

&&= Mozilla Documentation

How to get the selected row values of DevExpress XtraGrid?

All you have to do is use the GetFocusedRowCellValue method of the gridView control and put it into the RowClick event.

For example:

private void gridView1_RowClick(object sender, DevExpress.XtraGrid.Views.Grid.RowClickEventArgs e)
{
    if (this.gvCodigoNombres.GetFocusedRowCellValue("EMP_dni") == null)
        return;
    MessageBox.Show(""+this.gvCodigoNombres.GetFocusedRowCellValue("EMP_dni").ToString());            
}

How do multiple clients connect simultaneously to one port, say 80, on a server?

First off, a "port" is just a number. All a "connection to a port" really represents is a packet which has that number specified in its "destination port" header field.

Now, there are two answers to your question, one for stateful protocols and one for stateless protocols.

For a stateless protocol (ie UDP), there is no problem because "connections" don't exist - multiple people can send packets to the same port, and their packets will arrive in whatever sequence. Nobody is ever in the "connected" state.

For a stateful protocol (like TCP), a connection is identified by a 4-tuple consisting of source and destination ports and source and destination IP addresses. So, if two different machines connect to the same port on a third machine, there are two distinct connections because the source IPs differ. If the same machine (or two behind NAT or otherwise sharing the same IP address) connects twice to a single remote end, the connections are differentiated by source port (which is generally a random high-numbered port).

Simply, if I connect to the same web server twice from my client, the two connections will have different source ports from my perspective and destination ports from the web server's. So there is no ambiguity, even though both connections have the same source and destination IP addresses.

Ports are a way to multiplex IP addresses so that different applications can listen on the same IP address/protocol pair. Unless an application defines its own higher-level protocol, there is no way to multiplex a port. If two connections using the same protocol simultaneously have identical source and destination IPs and identical source and destination ports, they must be the same connection.

decimal vs double! - Which one should I use and when?

My question is when should a use a double and when should I use a decimal type?

decimal for when you work with values in the range of 10^(+/-28) and where you have expectations about the behaviour based on base 10 representations - basically money.

double for when you need relative accuracy (i.e. losing precision in the trailing digits on large values is not a problem) across wildly different magnitudes - double covers more than 10^(+/-300). Scientific calculations are the best example here.

which type is suitable for money computations?

decimal, decimal, decimal

Accept no substitutes.

The most important factor is that double, being implemented as a binary fraction, cannot accurately represent many decimal fractions (like 0.1) at all and its overall number of digits is smaller since it is 64-bit wide vs. 128-bit for decimal. Finally, financial applications often have to follow specific rounding modes (sometimes mandated by law). decimal supports these; double does not.

How can I convert a .py to .exe for Python?

There is an open source project called auto-py-to-exe on GitHub. Actually it also just uses PyInstaller internally but since it is has a simple GUI that controls PyInstaller it may be a comfortable alternative. It can also output a standalone file in contrast to other solutions. They also provide a video showing how to set it up.

GUI:

Auto Py to Exe

Output:

Output

`getchar()` gives the same output as the input string

Strings, by C definition, are terminated by '\0'. You have no "C strings" in your program.

Your program reads characters (buffered till ENTER) from the standard input (the keyboard) and writes them back to the standard output (the screen). It does this no matter how many characters you type or for how long you do this.

To stop the program you have to indicate that the standard input has no more data (huh?? how can a keyboard have no more data?).

You simply press Ctrl+D (Unix) or Ctrl+Z (Windows) to pretend the file has reached its end.
Ctrl+D (or Ctrl+Z) are not really characters in the C sense of the word.

If you run your program with input redirection, the EOF is the actual end of file, not a make belief one
./a.out < source.c

Transpose a range in VBA

Something like this should do it for you.

Sub CombineColumns1()
    Dim xRng As Range
    Dim i As Long, j As Integer
    Dim xNextRow As Long
    Dim xTxt As String
    On Error Resume Next
    With ActiveSheet
        xTxt = .RangeSelection.Address
        Set xRng = Application.InputBox("please select the data range", "Kutools for Excel", xTxt, , , , , 8)
        If xRng Is Nothing Then Exit Sub
        j = xRng.Columns(1).Column
        For i = 4 To xRng.Columns.Count Step 3
            'Need to recalculate the last row, as some of the final columns may not have data in all rows
            xNextRow = .Cells(.Rows.Count, j).End(xlUp).Row + 1

            .Range(xRng.Cells(1, i), xRng.Cells(xRng.Rows.Count, i + 2)).Copy .Cells(xNextRow, j)
            .Range(xRng.Cells(1, i), xRng.Cells(xRng.Rows.Count, i + 2)).Clear
        Next
    End With
End Sub

You could do this too.

Sub TransposeFormulas()
    Dim vFormulas As Variant
    Dim oSel As Range
    If TypeName(Selection) <> "Range" Then
        MsgBox "Please select a range of cells first.", _
                vbOKOnly + vbInformation, "Transpose formulas"
        Exit Sub
    End If
    Set oSel = Selection
    vFormulas = oSel.Formula
    vFormulas = Application.WorksheetFunction.Transpose(vFormulas)
    oSel.Offset(oSel.Rows.Count + 2).Resize(oSel.Columns.Count, oSel.Rows.Count).Formula = vFormulas
End Sub

See this for more info.

http://bettersolutions.com/vba/arrays/transposing.htm

Conversion between UTF-8 ArrayBuffer and String

There's a polyfill for Encoding over on Github: text-encoding. It's easy for Node or the browser, and the Readme advises the following:

var uint8array = TextEncoder(encoding).encode(string);
var string = TextDecoder(encoding).decode(uint8array);

If I recall, 'utf-8' is the encoding you need, and of course you'll need to wrap your buffer:

var uint8array = new Uint8Array(utf8buffer);

Hope it works as well for you as it has for me.

How to format time since xxx e.g. “4 minutes ago” similar to Stack Exchange sites

I was looking for an answer to this and almost implemented one of these solutions, but a colleague reminded me to check the react-intl library since we were already using it.

So adding to the solutions...in the case you are using the react-intl library, they have a <FormattedRelative> component for this.

https://github.com/yahoo/react-intl/wiki/Components#formattedrelative

How to find the highest value of a column in a data frame in R?

Similar to colMeans, colSums, etc, you could write a column maximum function, colMax, and a column sort function, colSort.

colMax <- function(data) sapply(data, max, na.rm = TRUE)
colSort <- function(data, ...) sapply(data, sort, ...)

I use ... in the second function in hopes of sparking your intrigue.

Get your data:

dat <- read.table(h=T, text = "Ozone Solar.R Wind Temp Month Day
1     41     190  7.4   67     5   1
2     36     118  8.0   72     5   2
3     12     149 12.6   74     5   3
4     18     313 11.5   62     5   4
5     NA      NA 14.3   56     5   5
6     28      NA 14.9   66     5   6
7     23     299  8.6   65     5   7
8     19      99 13.8   59     5   8
9      8      19 20.1   61     5   9")

Use colMax function on sample data:

colMax(dat)
#  Ozone Solar.R    Wind    Temp   Month     Day 
#   41.0   313.0    20.1    74.0     5.0     9.0

To do the sorting on a single column,

sort(dat$Solar.R, decreasing = TRUE)
# [1] 313 299 190 149 118  99  19

and over all columns use our colSort function,

colSort(dat, decreasing = TRUE) ## compare with '...' above

$(form).ajaxSubmit is not a function

Try:

$(document).ready(function() {
    $('#contact-form').validate({submitHandler: function(form) {
         var data = $('#contact-form').serialize();   
         $.post(
              'url_request',
               {data: data},
               function(response){
                  console.log(response);
               }
          );
         }
    });
});

Import an existing git project into GitLab?

To keep ALL TAGS AND BRANCHES

Just simply run this command in an existing Git repository

cd existing_repo
git remote rename origin previous-hosts
git remote add gitlab [email protected]:hutber/kindred.com.git
git push -u gitlab --all
git push -u gitlab --tags

Unable to update the EntitySet - because it has a DefiningQuery and no <UpdateFunction> element exist

Adding the primary key worked for me too !

Once that is done, here's how to update the data model without deleting it -

Right click on the edmx Entity designer page and 'Update Model from Database'.

correct way to define class variables in Python

I think this sample explains the difference between the styles:

james@bodacious-wired:~$cat test.py 
#!/usr/bin/env python

class MyClass:
    element1 = "Hello"

    def __init__(self):
        self.element2 = "World"

obj = MyClass()

print dir(MyClass)
print "--"
print dir(obj)
print "--"
print obj.element1 
print obj.element2
print MyClass.element1 + " " + MyClass.element2
james@bodacious-wired:~$./test.py 
['__doc__', '__init__', '__module__', 'element1']
--
['__doc__', '__init__', '__module__', 'element1', 'element2']
--
Hello World
Hello
Traceback (most recent call last):
  File "./test.py", line 17, in <module>
    print MyClass.element2
AttributeError: class MyClass has no attribute 'element2'

element1 is bound to the class, element2 is bound to an instance of the class.

Flushing buffers in C

Flushing the output buffers:

printf("Buffered, will be flushed");
fflush(stdout); // Prints to screen or whatever your standard out is

or

fprintf(fd, "Buffered, will be flushed");
fflush(fd);  //Prints to a file

Can be a very helpful technique. Why would you want to flush an output buffer? Usually when I do it, it's because the code is crashing and I'm trying to debug something. The standard buffer will not print everytime you call printf() it waits until it's full then dumps a bunch at once. So if you're trying to check if you're making it to a function call before a crash, it's helpful to printf something like "got here!", and sometimes the buffer hasn't been flushed before the crash happens and you can't tell how far you've really gotten.

Another time that it's helpful, is in multi-process or multi-thread code. Again, the buffer doesn't always flush on a call to a printf(), so if you want to know the true order of execution of multiple processes you should fflush the buffer after every print.

I make a habit to do it, it saves me a lot of headache in debugging. The only downside I can think of to doing so is that printf() is an expensive operation (which is why it doesn't by default flush the buffer).


As far as flushing the input buffer (stdin), you should not do that. Flushing stdin is undefined behavior according to the C11 standard §7.21.5.2 part 2:

If stream points to an output stream ... the fflush function causes any unwritten data for that stream ... to be written to the file; otherwise, the behavior is undefined.

On some systems, Linux being one as you can see in the man page for fflush(), there's a defined behavior but it's system dependent so your code will not be portable.

Now if you're worried about garbage "stuck" in the input buffer you can use fpurge() on that. See here for more on fflush() and fpurge()

LabelEncoder: TypeError: '>' not supported between instances of 'float' and 'str'

Or use a cast with split to uniform type of str

unique, counts = numpy.unique(str(a).split(), return_counts=True)

How do I raise the same Exception with a custom message in Python?

This only works with Python 3. You can modify the exception's original arguments and add your own arguments.

An exception remembers the args it was created with. I presume this is so that you can modify the exception.

In the function reraise we prepend the exception's original arguments with any new arguments that we want (like a message). Finally we re-raise the exception while preserving the trace-back history.

def reraise(e, *args):
  '''re-raise an exception with extra arguments
  :param e: The exception to reraise
  :param args: Extra args to add to the exception
  '''

  # e.args is a tuple of arguments that the exception with instantiated with.
  #
  e.args = args + e.args

  # Recreate the expection and preserve the traceback info so thta we can see 
  # where this exception originated.
  #
  raise e.with_traceback(e.__traceback__)   


def bad():
  raise ValueError('bad')

def very():
  try:
    bad()
  except Exception as e:
    reraise(e, 'very')

def very_very():
  try:
    very()
  except Exception as e:
    reraise(e, 'very')

very_very()

output

Traceback (most recent call last):
  File "main.py", line 35, in <module>
    very_very()
  File "main.py", line 30, in very_very
    reraise(e, 'very')
  File "main.py", line 15, in reraise
    raise e.with_traceback(e.__traceback__)
  File "main.py", line 28, in very_very
    very()
  File "main.py", line 24, in very
    reraise(e, 'very')
  File "main.py", line 15, in reraise
    raise e.with_traceback(e.__traceback__)
  File "main.py", line 22, in very
    bad()
  File "main.py", line 18, in bad
    raise ValueError('bad')
ValueError: ('very', 'very', 'bad')

gpg failed to sign the data fatal: failed to write commit object [Git 2.10.0]

Ran into this in prezto another zsh variant. There the issue was my git repo was new and did not have the node_modules added to .gitignore. As soon as I added the node_modules to .gitignore the issue was no more to be seen. So my assumption is git-info was taking time due to these large node_modules.

Where does Java's String constant pool live, the heap or the stack?

To the great answers that already included here I want to add something that missing in my perspective - an illustration.

As you already JVM divides the allocated memory to a Java program into two parts. one is stack and another one is heap. Stack is used for execution purpose and heap is used for storage purpose. In that heap memory, JVM allocates some memory specially meant for string literals. This part of the heap memory is called string constants pool.

So for example, if you init the following objects:

String s1 = "abc"; 
String s2 = "123";
String obj1 = new String("abc");
String obj2 = new String("def");
String obj3 = new String("456);

String literals s1 and s2 will go to string constant pool, objects obj1, obj2, obj3 to the heap. All of them, will be referenced from the Stack.

Also, please note that "abc" will appear in heap and in string constant pool. Why is String s1 = "abc" and String obj1 = new String("abc") will be created this way? It's because String obj1 = new String("abc") explicitly creates a new and referentially distinct instance of a String object and String s1 = "abc" may reuse an instance from the string constant pool if one is available. For a more elaborate explanation: https://stackoverflow.com/a/3298542/2811258

enter image description here

How to get current time with jQuery

_x000D_
_x000D_
console.log(_x000D_
  new Date().toLocaleString().slice(9, -3)_x000D_
  , new Date().toString().slice(16, -15)_x000D_
);
_x000D_
_x000D_
_x000D_

Instagram API to fetch pictures with specific hashtags

Take a look here in order to get started: http://instagram.com/developer/

and then in order to retrieve pictures by tag, look here: http://instagram.com/developer/endpoints/tags/

Getting tags from Instagram doesn't require OAuth, so you can make the calls via these URLs:

GET IMAGES https://api.instagram.com/v1/tags/{tag-name}/media/recent?access_token={TOKEN}

SEARCH https://api.instagram.com/v1/tags/search?q={tag-query}&access_token={TOKEN}

TAG INFO https://api.instagram.com/v1/tags/{tag-name}?access_token={TOKEN}

Distinct pair of values SQL

If you just want a count of the distinct pairs.

The simplest way to do that is as follows SELECT COUNT(DISTINCT a,b) FROM pairs

The previous solutions would list all the pairs and then you'd have to do a second query to count them.

How to crop(cut) text files based on starting and ending line-numbers in cygwin?

And if you simply want to cut part of a file - say from line 26 to 142 - and input it to a newfile : cat file-to-cut.txt | sed -n '26,142p' >> new-file.txt

Set a default parameter value for a JavaScript function

Just to showcase my skills too (lol), above function can written even without having named arguments as below:

ES5 and above

function foo() {
    a = typeof arguments[0] !== 'undefined' ? a : 42;
    b = typeof arguments[1] !== 'undefined' ? b : 'default_b';
    ...
}

ES6 and above

function foo(...rest) {
    a = typeof rest[0] !== 'undefined' ? a : 42;
    b = typeof rest[1] !== 'undefined' ? b : 'default_b';
    ...
}

How do I center an SVG in a div?

None of these answers worked for me. This is how I did it.

position: relative;
left: 50%;
-webkit-transform: translateX(-50%);
-ms-transform: translateX(-50%);
transform: translateX(-50%);

Is there something like Codecademy for Java

As of right now, I do not know of any. It appears the code academy folks have set their sites on Ruby on Rails. They do not rule Java out of the picture however.

React native text going off my screen, refusing to wrap. What to do?

<View style={{flexDirection:'row'}}> 
   <Text style={{ flex: number }}> You miss fdddddd dddddddd 
     You miss fdd
   </Text>
</View>

{ flex: aNumber } is all you need!

Just set 'flex' to a number that suit for you. And then the text will wrap.

What are enums and why are they useful?

enum means enumeration i.e. mention (a number of things) one by one.

An enum is a data type that contains fixed set of constants.

OR

An enum is just like a class, with a fixed set of instances known at compile time.

For example:

public class EnumExample {
    interface SeasonInt {
        String seasonDuration();
    }

    private enum Season implements SeasonInt {
        // except the enum constants remaining code looks same as class
        // enum constants are implicitly public static final we have used all caps to specify them like Constants in Java
        WINTER(88, "DEC - FEB"), SPRING(92, "MAR - JUN"), SUMMER(91, "JUN - AUG"), FALL(90, "SEP - NOV");

        private int days;
        private String months;

        Season(int days, String months) { // note: constructor is by default private 
            this.days = days;
            this.months = months;
        }

        @Override
        public String seasonDuration() {
            return this+" -> "+this.days + "days,   " + this.months+" months";
        }

    }
    public static void main(String[] args) {
        System.out.println(Season.SPRING.seasonDuration());
        for (Season season : Season.values()){
            System.out.println(season.seasonDuration());
        }

    }
}

Advantages of enum:

  • enum improves type safety at compile-time checking to avoid errors at run-time.
  • enum can be easily used in switch
  • enum can be traversed
  • enum can have fields, constructors and methods
  • enum may implement many interfaces but cannot extend any class because it internally extends Enum class

for more

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

I would suggest writing an extension method for this:

public static IEnumerable<T> Select<T>(this IDataReader reader,
                                       Func<IDataReader, T> projection)
{
    while (reader.Read())
    {
        yield return projection(reader);
    }
}

You can then use LINQ's ToList() method to convert that into a List<T> if you want, like this:

using (IDataReader reader = ...)
{
    List<Customer> customers = reader.Select(r => new Customer {
        CustomerId = r["id"] is DBNull ? null : r["id"].ToString(),
        CustomerName = r["name"] is DBNull ? null : r["name"].ToString() 
    }).ToList();
}

I would actually suggest putting a FromDataReader method in Customer (or somewhere else):

public static Customer FromDataReader(IDataReader reader) { ... }

That would leave:

using (IDataReader reader = ...)
{
    List<Customer> customers = reader.Select<Customer>(Customer.FromDataReader)
                                     .ToList();
}

(I don't think type inference would work in this case, but I could be wrong...)

RESTful web service - how to authenticate requests from other services?

You can create Session on server and share sessionId in between client and server with each REST call.

  1. First authenticate REST request: /authenticate. Returns response (as per your client format) with sessionId: ABCDXXXXXXXXXXXXXX;

  2. Store this sessionId in Map with actual session. Map.put(sessionid, session) or use SessionListener to create and destroy keys for you;

    public void sessionCreated(HttpSessionEvent arg0) {
      // add session to a static Map 
    }
    
    public void sessionDestroyed(HttpSessionEvent arg0) {
      // Remove session from static map
    }
    
  3. Get sessionid with every REST call, like URL?jsessionid=ABCDXXXXXXXXXXXXXX (or other way);

  4. Retrive HttpSession from map using sessionId;
  5. Validate request for that session if session is active;
  6. Send back response or error message.

C# ASP.NET Send Email via TLS

On SmtpClient there is an EnableSsl property that you would set.

i.e.

SmtpClient client = new SmtpClient(exchangeServer);
client.EnableSsl = true;
client.Send(msg);

Accessing constructor of an anonymous class

Yes , It is right that you can not define construct in an Anonymous class but it doesn't mean that anonymous class don't have constructor. Confuse... Actually you can not define construct in an Anonymous class but compiler generates an constructor for it with the same signature as its parent constructor called. If the parent has more than one constructor, the anonymous will have one and only one constructor

How to assign an exec result to a sql variable?

This will work if you wish to simply return an integer:

DECLARE @ResultForPos INT 
EXEC @ResultForPos = storedprocedureName 'InputParameter'
SELECT @ResultForPos

Bootstrap footer at the bottom of the page

Use this stylesheet:

_x000D_
_x000D_
/* Sticky footer styles_x000D_
-------------------------------------------------- */_x000D_
html {_x000D_
  position: relative;_x000D_
  min-height: 100%;_x000D_
}_x000D_
body {_x000D_
  /* Margin bottom by footer height */_x000D_
  margin-bottom: 60px;_x000D_
}_x000D_
.footer {_x000D_
  position: absolute;_x000D_
  bottom: 0;_x000D_
  width: 100%;_x000D_
  /* Set the fixed height of the footer here */_x000D_
  height: 60px;_x000D_
  line-height: 60px; /* Vertically center the text there */_x000D_
  background-color: #f5f5f5;_x000D_
}_x000D_
_x000D_
_x000D_
/* Custom page CSS_x000D_
-------------------------------------------------- */_x000D_
/* Not required for template or sticky footer method. */_x000D_
_x000D_
body > .container {_x000D_
  padding: 60px 15px 0;_x000D_
}_x000D_
_x000D_
.footer > .container {_x000D_
  padding-right: 15px;_x000D_
  padding-left: 15px;_x000D_
}_x000D_
_x000D_
code {_x000D_
  font-size: 80%;_x000D_
}
_x000D_
_x000D_
_x000D_

How can I add a custom HTTP header to ajax request with js or jQuery?

Assuming that you mean "When using ajax" and "An HTTP Request header", then use the headers property in the object you pass to ajax()

headers(added 1.5)

Default: {}

A map of additional header key/value pairs to send along with the request. This setting is set before the beforeSend function is called; therefore, any values in the headers setting can be overwritten from within the beforeSend function.

http://api.jquery.com/jQuery.ajax/

Set android shape color programmatically

Note: Answer has been updated to cover the scenario where background is an instance of ColorDrawable. Thanks Tyler Pfaff, for pointing this out.

The drawable is an oval and is the background of an ImageView

Get the Drawable from imageView using getBackground():

Drawable background = imageView.getBackground();

Check against usual suspects:

if (background instanceof ShapeDrawable) {
    // cast to 'ShapeDrawable'
    ShapeDrawable shapeDrawable = (ShapeDrawable) background;
    shapeDrawable.getPaint().setColor(ContextCompat.getColor(mContext,R.color.colorToSet));
} else if (background instanceof GradientDrawable) {
    // cast to 'GradientDrawable'
    GradientDrawable gradientDrawable = (GradientDrawable) background;
    gradientDrawable.setColor(ContextCompat.getColor(mContext,R.color.colorToSet));
} else if (background instanceof ColorDrawable) {
    // alpha value may need to be set again after this call
    ColorDrawable colorDrawable = (ColorDrawable) background;
    colorDrawable.setColor(ContextCompat.getColor(mContext,R.color.colorToSet));
}

Compact version:

Drawable background = imageView.getBackground();
if (background instanceof ShapeDrawable) {
    ((ShapeDrawable)background).getPaint().setColor(ContextCompat.getColor(mContext,R.color.colorToSet));
} else if (background instanceof GradientDrawable) {
    ((GradientDrawable)background).setColor(ContextCompat.getColor(mContext,R.color.colorToSet));
} else if (background instanceof ColorDrawable) {
    ((ColorDrawable)background).setColor(ContextCompat.getColor(mContext,R.color.colorToSet));
}

Note that null-checking is not required.

However, you should use mutate() on the drawables before modifying them if they are used elsewhere. (By default, drawables loaded from XML share the same state.)

How do I know which version of Javascript I'm using?

All of todays browsers use at least version 1.5:
http://en.wikipedia.org/wiki/ECMAScript#Dialect

Concerning your tutorial site, the information there seems to be extremely outdated, I beg you to head over to MDC and read their Guide:
https://developer.mozilla.org/en/JavaScript/Guide

You may still want to watch out for features which require version 1.6 or above, as this might give Internet Explorer some troubles.

undefined reference to boost::system::system_category() when compiling

...and in case you wanted to link your main statically, in your Jamfile add the following to requirements:

<link>static
<library>/boost/system//boost_system

and perhaps also:

<linkflags>-static-libgcc
<linkflags>-static-libstdc++

HTML&CSS + Twitter Bootstrap: full page layout or height 100% - Npx

I've found a post here on Stackoverflow and implemented your design:

http://jsfiddle.net/bKsad/25/

Here's the original post: https://stackoverflow.com/a/5768262/1368423

Is that what you're looking for?

HTML:

<div class="container-fluid wrapper">

  <div class="row-fluid columns content"> 

    <div class="span2 article-tree">
      navigation column
    </div>

    <div class="span10 content-area">
      content column 
    </div>
  </div>

  <div class="footer">
     footer content
  </div>
</div>

CSS:

html, body {
    height: 100%;
}
.container-fluid {
    margin: 0 auto;
    height: 100%;
    padding: 20px 0;

    -moz-box-sizing: border-box;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
}

.columns {
    background-color: #C9E6FF;
    height: 100%;   
}

.content-area, .article-tree{
    background: #bada55;
    overflow:auto;
    height: 100%;
}

.footer {
    background: red;
    height: 20px;
}

C#: How do you edit items and subitems in a listview?

If you're looking for "in-place" editing of a ListView's contents (specifically the subitems of a ListView in details view mode), you'll need to implement this yourself, or use a third-party control.

By default, the best you can achieve with a "standard" ListView is to set it's LabelEdit property to true to allow the user to edit the text of the first column of the ListView (assuming you want to allow a free-format text edit).

Some examples (including full source-code) of customized ListView's that allow "in-place" editing of sub-items are:

C# Editable ListView
In-place editing of ListView subitems

How to $http Synchronous call with AngularJS

Since sync XHR is being deprecated, it's best not to rely on that. If you need to do a sync POST request, you can use the following helpers inside of a service to simulate a form post.

It works by creating a form with hidden inputs which is posted to the specified URL.

//Helper to create a hidden input
function createInput(name, value) {
  return angular
    .element('<input/>')
    .attr('type', 'hidden')
    .attr('name', name)
    .val(value);
}

//Post data
function post(url, data, params) {

    //Ensure data and params are an object
    data = data || {};
    params = params || {};

    //Serialize params
    const serialized = $httpParamSerializer(params);
    const query = serialized ? `?${serialized}` : '';

    //Create form
    const $form = angular
        .element('<form/>')
        .attr('action', `${url}${query}`)
        .attr('enctype', 'application/x-www-form-urlencoded')
        .attr('method', 'post');

    //Create hidden input data
    for (const key in data) {
        if (data.hasOwnProperty(key)) {
            const value = data[key];
            if (Array.isArray(value)) {
                for (const val of value) {
                    const $input = createInput(`${key}[]`, val);
                    $form.append($input);
                }
            }
            else {
                const $input = createInput(key, value);
                $form.append($input);
            }
        }
    }

    //Append form to body and submit
    angular.element(document).find('body').append($form);
    $form[0].submit();
    $form.remove();
}

Modify as required for your needs.

How to return a specific element of an array?

Make sure return type of you method is same what you want to return. Eg: `

  public int get(int[] r)
  {
     return r[0];
  }

`

Note : return type is int, not int[], so it is able to return int.

In general, prototype can be

public Type get(Type[] array, int index)
{
    return array[index];
}

Capture keyboardinterrupt in Python without try-except

Yes, you can install an interrupt handler using the module signal, and wait forever using a threading.Event:

import signal
import sys
import time
import threading

def signal_handler(signal, frame):
    print('You pressed Ctrl+C!')
    sys.exit(0)

signal.signal(signal.SIGINT, signal_handler)
print('Press Ctrl+C')
forever = threading.Event()
forever.wait()

Is Xamarin free in Visual Studio 2015?

No, it only contains a free 30 day trial. But I think there would be a package if you buy Visual Studio + Xamarin.

How do I make XAML DataGridColumns fill the entire DataGrid?

My 2 Cent ->

Very late to party

DataGrid -> Column -> Width="*" only work if DataGrid parent container has fix width.

example : i put the DataGrid in Grid -> Column whose width="Auto" then Width="*" in DataGrid does not work but if you set Grid -> Column Width="450" mean fixed then it work fine

How do I base64 encode a string efficiently using Excel VBA?

As Mark C points out, you can use the MSXML Base64 encoding functionality as described here.

I prefer late binding because it's easier to deploy, so here's the same function that will work without any VBA references:

Function EncodeBase64(text As String) As String
  Dim arrData() As Byte
  arrData = StrConv(text, vbFromUnicode)

  Dim objXML As Variant
  Dim objNode As Variant

  Set objXML = CreateObject("MSXML2.DOMDocument")
  Set objNode = objXML.createElement("b64")

  objNode.dataType = "bin.base64"
  objNode.nodeTypedValue = arrData
  EncodeBase64 = objNode.text

  Set objNode = Nothing
  Set objXML = Nothing
End Function

Setting Custom ActionBar Title from Fragment

Use the following:

getActivity().setTitle("YOUR_TITLE");

Byte Array to Image object

From Database.
Blob blob = resultSet.getBlob("pictureBlob");               
byte [] data = blob.getBytes( 1, ( int ) blob.length() );
BufferedImage img = null;
try {
img = ImageIO.read(new ByteArrayInputStream(data));
} catch (IOException e) {
    e.printStackTrace();
}
drawPicture(img);  //  void drawPicture(Image img);

Gradle failed to resolve library in Android Studio

I had the same problem, the first thing that came to mind was repositories. So I checked the build.gradle file for the whole project and added the following code, then synchronized the gradle with project and problem was solved!

allprojects {
    repositories {
        jcenter()
    }
}

Updates were rejected because the tip of your current branch is behind hint: its remote counterpart. Integrate the remote changes (e.g

You need to merge the remote branch into your current branch by running git pull.

If your local branch is already up-to-date, you may also need to run git pull --rebase.

A quick google search also turned up this same question asked by another SO user: Cannot push to GitHub - keeps saying need merge. More details there.

What's the difference between echo, print, and print_r in PHP?

The difference between echo, print, print_r and var_dump is very simple.

echo

echo is actually not a function but a language construct which is used to print output. It is marginally faster than the print.

echo "Hello World";    // this will print Hello World
echo "Hello ","World"; // Multiple arguments - this will print Hello World

$var_1=55;
echo "$var_1";               // this will print 55
echo "var_1=".$var_1;        // this will print var_1=55
echo 45+$var_1;              // this will print 100

$var_2="PHP";
echo "$var_2";                   // this will print PHP

$var_3=array(99,98,97)           // Arrays are not possible with echo (loop or index  value required)
$var_4=array("P"=>"3","J"=>"4"); // Arrays are not possible with echo (loop or index  value required)

You can also use echo statement with or without parenthese

echo ("Hello World");   // this will print Hello World

print

Just like echo construct print is also a language construct and not a real function. The differences between echo and print is that print only accepts a single argument and print always returns 1. Whereas echo has no return value. So print statement can be used in expressions.

print "Hello World";    // this will print Hello World
print "Hello ","World"; // Multiple arguments - NOT POSSIBLE with print
$var_1=55;
print "$var_1";               // this will print 55
print "var_1=".$var_1;        // this will print var_1=55
print 45+$var_1;              // this will print 100

$var_2="PHP";
print "$var_2";                   // this will print PHP

$var_3=array(99,98,97)           // Arrays are not possible with print (loop or index  value required)
$var_4=array("P"=>"3","J"=>"4"); // Arrays are not possible with print (loop or index  value required)

Just like echo, print can be used with or without parentheses.

print ("Hello World");   // this will print Hello World

print_r

The print_r() function is used to print human-readable information about a variable. If the argument is an array, print_r() function prints its keys and elements (same for objects).

print_r ("Hello World");    // this will print Hello World

$var_1=55;
print_r ("$var_1");               // this will print 55
print_r ("var_1=".$var_1);        // this will print var_1=55
print_r (45+$var_1);              // this will print 100

$var_2="PHP";
print_r ("$var_2");                // this will print PHP

$var_3=array(99,98,97)             // this will print Array ( [0] => 1 [1] => 2 [2] => 3 ) 
$var_4=array("P"=>"3","J"=>"4");   // this will print  Array ( [P] => 3 [J] => 4 ) 

var_dump

var_dump function usually used for debugging and prints the information ( type and value) about a variable/array/object.

var_dump($var_1);     // this will print  int(5444) 
var_dump($var_2);     // this will print  string(5) "Hello" 
var_dump($var_3);     // this will print  array(3) { [0]=> int(1) [1]=> int(2) [2]=> int(3) } 
var_dump($var_4);     // this will print  array(2) { ["P"]=> string(1) "3" ["J"]=> string(1) "4" }

Get JavaScript object from array of objects by value of property

Using find with bind to pass specific key values to a callback function.

   function byValue(o) { 
       return o.a === this.a && o.b === this.b; 
   };   

   var result = jsObjects.find(byValue.bind({ a: 5, b: 6 }));

Creating pdf files at runtime in c#

iTextSharp is no longer licensed under the MIT/LGPL license. Versions greater than 4.1.6 are licensed under the Affero GPL, meaning you can't even use it in a SaaS (Software as a Service) scenario without licensing your code under the GPL, or a GPL-compatible license.

Other opensource PDF implementations in native .NET include

There's also a couple of Java PDF libraries (like PDFBox) you can convert to .NET using IKVM.

A potentially dangerous Request.Path value was detected from the client (*)

Try to set web project's server propery as Local IIS if it is IIS Express. Be sure if project url is right and create virual directory.

Array initialization in Perl

What do you mean by "initialize an array to zero"? Arrays don't contain "zero" -- they can contain "zero elements", which is the same as "an empty list". Or, you could have an array with one element, where that element is a zero: my @array = (0);

my @array = (); should work just fine -- it allocates a new array called @array, and then assigns it the empty list, (). Note that this is identical to simply saying my @array;, since the initial value of a new array is the empty list anyway.

Are you sure you are getting an error from this line, and not somewhere else in your code? Ensure you have use strict; use warnings; in your module or script, and check the line number of the error you get. (Posting some contextual code here might help, too.)

Angular JS: Full example of GET/POST/DELETE/PUT client for a REST/CRUD backend?

You can implement this way

$resource('http://localhost\\:3000/realmen/:entryId', {entryId: '@entryId'}, {
        UPDATE: {method: 'PUT', url: 'http://localhost\\:3000/realmen/:entryId' },
        ACTION: {method: 'PUT', url: 'http://localhost\\:3000/realmen/:entryId/action' }
    })

RealMen.query() //GET  /realmen/
RealMen.save({entryId: 1},{post data}) // POST /realmen/1
RealMen.delete({entryId: 1}) //DELETE /realmen/1

//any optional method
RealMen.UPDATE({entryId:1}, {post data}) // PUT /realmen/1

//query string
RealMen.query({name:'john'}) //GET /realmen?name=john

Documentation: https://docs.angularjs.org/api/ngResource/service/$resource

Hope it helps

byte[] to file in Java

This is a program where we are reading and printing array of bytes offset and length using String Builder and Writing the array of bytes offset length to the new file.

`Enter code here

import java.io.File;   
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;        

//*This is a program where we are reading and printing array of bytes offset and length using StringBuilder and Writing the array of bytes offset length to the new file*//     

public class ReadandWriteAByte {
    public void readandWriteBytesToFile(){
        File file = new File("count.char"); //(abcdefghijk)
        File bfile = new File("bytefile.txt");//(New File)
        byte[] b;
        FileInputStream fis = null;              
        FileOutputStream fos = null;          

        try{               
            fis = new FileInputStream (file);           
            fos = new FileOutputStream (bfile);             
            b = new byte [1024];              
            int i;              
            StringBuilder sb = new StringBuilder();

            while ((i = fis.read(b))!=-1){                  
                sb.append(new String(b,5,5));               
                fos.write(b, 2, 5);               
            }               

            System.out.println(sb.toString());               
        }catch (IOException e) {                    
            e.printStackTrace();                
        }finally {               
            try {              
                if(fis != null);           
                    fis.close();    //This helps to close the stream          
            }catch (IOException e){           
                e.printStackTrace();              
            }            
        }               
    }               

    public static void main (String args[]){              
        ReadandWriteAByte rb = new ReadandWriteAByte();              
        rb.readandWriteBytesToFile();              
    }                 
}                

O/P in console : fghij

O/P in new file :cdefg

How to change checkbox's border style in CSS?

Styling checkboxes (and many other input elements for that mater) is not really possible with pure css if you want to drastically change the visual appearance.

Your best bet is to implement something like jqTransform does which actually replaces you inputs with images and applies javascript behaviour to it to mimic a checkbox (or other element for that matter)

Query for array elements inside JSON type

jsonb in Postgres 9.4+

You can use the same query as below, just with jsonb_array_elements().

But rather use the jsonb "contains" operator @> in combination with a matching GIN index on the expression data->'objects':

CREATE INDEX reports_data_gin_idx ON reports
USING gin ((data->'objects') jsonb_path_ops);

SELECT * FROM reports WHERE data->'objects' @> '[{"src":"foo.png"}]';

Since the key objects holds a JSON array, we need to match the structure in the search term and wrap the array element into square brackets, too. Drop the array brackets when searching a plain record.

More explanation and options:

json in Postgres 9.3+

Unnest the JSON array with the function json_array_elements() in a lateral join in the FROM clause and test for its elements:

SELECT data::text, obj
FROM   reports r, json_array_elements(r.data#>'{objects}') obj
WHERE  obj->>'src' = 'foo.png';

db<>fiddle here
Old sqlfiddle

The CTE (WITH query) just substitutes for a table reports.
Or, equivalent for just a single level of nesting:

SELECT *
FROM   reports r, json_array_elements(r.data->'objects') obj
WHERE  obj->>'src' = 'foo.png';

->>, -> and #> operators are explained in the manual.

Both queries use an implicit JOIN LATERAL.

Closely related:

Is there an easy way to return a string repeated X number of times?

I like the answer given. Along the same lines though is what I've used in the past:

"".PadLeft(3*Indent,'-')

This will fulfill creating an indent but technically the question was to repeat a string. If the string indent is something like >-< then this as well as the accepted answer would not work. In this case, c0rd's solution using StringBuilder looks good, though the overhead of StringBuilder may in fact not make it the most performant. One option is to build an array of strings, fill it with indent strings, then concat that. To whit:

int Indent = 2;
        
string[] sarray = new string[6];  //assuming max of 6 levels of indent, 0 based

for (int iter = 0; iter < 6; iter++)
{
    //using c0rd's stringbuilder concept, insert ABC as the indent characters to demonstrate any string can be used
    sarray[iter] = new StringBuilder().Insert(0, "ABC", iter).ToString();
}

Console.WriteLine(sarray[Indent] +"blah");  //now pretend to output some indented line

We all love a clever solution but sometimes simple is best.

How to move Jenkins from one PC to another

In case your JENKINS_HOME directory is too large to copy, and all you need is to set up same jobs, Jenkins Plugins and Jenkins configurations (and don't need old Job artifacts and reports), then you can use the ThinBackup Plugin:

  1. Install ThinBackup on both the source and the target Jenkins servers

  2. Configure the backup directory on both (in Manage Jenkins ? ThinBackup ? Settings)

  3. On the source Jenkins, go to ThinBackup ? Backup Now

  4. Copy from Jenkins source backup directory to the Jenkins target backup directory

  5. On the target Jenkins, go to ThinBackup ? Restore, and then restart the Jenkins service.

  6. If some plugins or jobs are missing, copy the backup content directly to the target JENKINS_HOME.

  7. If you had user authentication on the source Jenkins, and now locked out on the target Jenkins, then edit Jenkins config.xml, set <useSecurity> to false, and restart Jenkins.

Laravel 5.5 ajax call 419 (unknown status)

in my case i forgot to add csrf_token input to the submitted form. so i did this HTML:

<form class="form-material" id="myform">
...
<input type="file" name="l_img" id="l_img">
<input type="hidden" id="_token" value="{{ csrf_token() }}">
..
</form>

JS:

//setting containers
        var _token = $('input#_token').val();
        var l_img = $('input#l_img').val();
        var formData = new FormData();
        formData.append("_token", _token);
        formData.append("l_img", $('#l_img')[0].files[0]);

        if(!l_img) {
            //do error if no image uploaded
            return false;
        }
        else
        {
            $.ajax({
                type: "POST",
                url: "/my_url",
                contentType: false,
                processData: false,
                dataType: "json",
                data : formData,
                beforeSend: function()
                {
                    //do before send
                },
                success: function(data)
                {
                    //do success
                },
                error: function(jqXhr, textStatus, errorThrown) //jqXHR, textStatus, errorThrown
                {
                    if( jqXhr.status === "422" ) {
                        //do error
                    } else {
                        //do error
                    }
                }
            });
        }
        return false; //not to post the form physically

Get PostGIS version

Since some of the functions depend on other libraries like GEOS and proj4 you might want to get their versions too. Then use:

SELECT PostGIS_full_version();

Which characters need to be escaped in HTML?

Basically, there are three main characters which should be always escaped in your HTML and XML files, so they don't interact with the rest of the markups, so as you probably expect, two of them gonna be the syntax wrappers, which are <>, they are listed as below:

 1)  &lt; (<)
    
 2)  &gt; (>)
    
 3)  &amp; (&)

Also we may use double-quote (") as " and the single quote (') as &apos

Avoid putting dynamic content in <script> and <style>.These rules are not for applied for them. For example, if you have to include JSON in a , replace < with \x3c, the U+2028 character with \u2028, and U+2029 with \u2029 after JSON serialisation.)

HTML Escape Characters: Complete List: http://www.theukwebdesigncompany.com/articles/entity-escape-characters.php

So you need to escape <, or & when followed by anything that could begin a character reference. Also The rule on ampersands is the only such rule for quoted attributes, as the matching quotation mark is the only thing that will terminate one. But if you don’t want to terminate the attribute value there, escape the quotation mark.

Changing to UTF-8 means re-saving your file:

Using the character encoding UTF-8 for your page means that you can avoid the need for most escapes and just work with characters. Note, however, that to change the encoding of your document, it is not enough to just change the encoding declaration at the top of the page or on the server. You need to re-save your document in that encoding. For help understanding how to do that with your application read Setting encoding in web authoring applications.

Invisible or ambiguous characters:

A particularly useful role for escapes is to represent characters that are invisible or ambiguous in presentation.

One example would be Unicode character U+200F RIGHT-TO-LEFT MARK. This character can be used to clarify directionality in bidirectional text (eg. when using the Arabic or Hebrew scripts). It has no graphic form, however, so it is difficult to see where these characters are in the text, and if they are lost or forgotten they could create unexpected results during later editing. Using ? (or its numeric character reference equivalent ?) instead makes it very easy to spot these characters.

An example of an ambiguous character is U+00A0 NO-BREAK SPACE. This type of space prevents line breaking, but it looks just like any other space when used as a character. Using   makes it quite clear where such spaces appear in the text.

Can't install laravel installer via composer

For PHP 7.2 in Ubuntu 18.04 LTS

sudo apt-get install php7.2-zip

Works like a charm

Hide/encrypt password in bash file to stop accidentally seeing it

  • indent it off the edge of your screen (assuming you don't use line wrapping and you have a consistant editor width)

or

  • store it in a separate file and read it in.

How to convert a const char * to std::string

std::string the_string(c_string);
if(the_string.size() > max_length)
    the_string.resize(max_length);

Is it possible to use global variables in Rust?

I am new to Rust, but this solution seems to work:

#[macro_use]
extern crate lazy_static;

use std::sync::{Arc, Mutex};

lazy_static! {
    static ref GLOBAL: Arc<Mutex<GlobalType> =
        Arc::new(Mutex::new(GlobalType::new()));
}

Another solution is to declare a crossbeam channel tx/rx pair as an immutable global variable. The channel should be bounded and can only hold 1 element. When you initialize the global variable, push the global instance into the channel. When using the global variable, pop the channel to acquire it and push it back when done using it.

Both solutions should provide a safe approach to using global variables.

Angularjs if-then-else construction in expression

This can be done in one line.

{{corretor.isAdministrador && 'YES' || 'NÂO'}}

Usage in a td tag:

<td class="text-center">{{corretor.isAdministrador && 'Sim' || 'Não'}}</td>

Random number c++ in some range

int random(int min, int max) //range : [min, max]
{
   static bool first = true;
   if (first) 
   {  
      srand( time(NULL) ); //seeding for the first time only!
      first = false;
   }
   return min + rand() % (( max + 1 ) - min);
}

How do I make entire div a link?

You need to assign display: block; property to the wrapping anchor. Otherwise it won't wrap correctly.

<a style="display:block" href="http://justinbieber.com">
  <div class="xyz">My div contents</div>
</a>

import android packages cannot be resolved

right click on project->properties->android->select target name as "Android 4.4.2" --click ok

since DocumentsContract is added in API level 19

How to convert unix timestamp to calendar date moment.js

Might be a little late but for new issues like this I use this code:

moment(timestamp, 'X').format('lll');

You can change the format to match your needs and also add timezone like this:

moment(timestamp, 'X').tz(timezone).format('lll');

Java Runtime.getRuntime(): getting output from executing a command line program

If you write on Kotlin, you can use:

val firstProcess = ProcessBuilder("echo","hello world").start()
val firstError = firstProcess.errorStream.readBytes().decodeToString()
val firstResult = firstProcess.inputStream.readBytes().decodeToString()

How to create a DOM node as an object?

And here is the one liner:

$("<li><div class='bar'>bla</div></li>").find("li").attr("id","1234").end().appendTo("body")

But I'm wondering why you would like to add the "id" attribute at a later stage rather than injecting it directly in the template.

How do I pass JavaScript variables to PHP?

when your page first loads the PHP code first run and set the complete layout of your webpage. after the page layout, it set the JavaScript load up. now JavaScript directly interacts with DOM and can manipulate the layout but PHP can't it needs to refresh the page. There is only way is to refresh your page to and pass the parameters in the page URL so that you can get the data via PHP. So we use AJAX to interact Javascript with PHP without page reload. AJAX can also be used as an API. one more thing if you have already declared the variable in PHP. before the page load then you can use it with your Javascript example.

<script>
var username = "<?php echo $myname;?>";
alert(username);
</script>

the above code is correct and it will work. but the code below is totally wrong and it will never work.

<script>
    var username = "syed ali";
    var <?php $myname;?> = username;
    alert(myname);
    </script>
  • Pass value from JavaScript to PHP via AJAX

    it is the most secure way to do it. because HTML content can be edited via developer tools and the user can manipulate the data. so it is better to use AJAX if you want security over that variable.if you are a newbie to AJAX please learn AJAX it is very simple.

The best and most secure way to pass JavaScript variable into PHP is via AJAX

simple AJAX example

var mydata = 55;
var myname = "syed ali";
var userdata = {'id':mydata,'name':myname};
    $.ajax({
            type: "POST",
            url: "YOUR PHP URL HERE",
            data:userdata, 
            success: function(data){
                console.log(data);
            }
            });
  • PASS value from javascript to php via hidden fields.

otherwise, you can create hidden HTML input inside your form. like

<input type="hidden" id="mydata">

then via jQuery or javaScript pass the value to the hidden field. like

<script>
var myvalue = 55;
$("#mydata").val(myvalue);
</script>

Now when you submit the form you can get the value in PHP.

How does Java resolve a relative path in new File()?

I went off of peter.petrov's answer but let me explain where you make the file edits to change it to a relative path.

Simply edit "AXLAPIService.java" and change

url = new URL("file:C:users..../schema/current/AXLAPI.wsdl");

to

url = new URL("file:./schema/current/AXLAPI.wsdl");

or where ever you want to store it.

You can still work on packaging the wsdl file into the meta-inf folder in the jar but this was the simplest way to get it working for me.

Pyspark replace strings in Spark dataframe column

For Spark 1.5 or later, you can use the functions package:

from pyspark.sql.functions import *
newDf = df.withColumn('address', regexp_replace('address', 'lane', 'ln'))

Quick explanation:

  • The function withColumn is called to add (or replace, if the name exists) a column to the data frame.
  • The function regexp_replace will generate a new column by replacing all substrings that match the pattern.

When should we use intern method of String on String literals

I want to add my 2 cents on using == with interned strings.

The first thing String.equals does is this==object.

So although there is some miniscule performance gain ( you are not calling a method), from the maintainer point of view using == is a nightmare, because some interned strings have a tendency to become non-interned.

So I suggest not to rely on special case of == for interned strings, but always use equals as Gosling intended.

EDIT: interned becoming non-interned:

V1.0
public class MyClass
{
  private String reference_val;

  ...

  private boolean hasReferenceVal ( final String[] strings )
  {
    for ( String s : strings )
    {
      if ( s == reference_val )
      {
        return true;
      }
    }

    return false;
  }

  private void makeCall ( )
  {
     final String[] interned_strings =  { ... init with interned values ... };

     if ( hasReference( interned_strings ) )
     {
        ...
     }
  }
}

In version 2.0 maintainer decided to make hasReferenceVal public, without going into much detail that it expects an array of interned strings.

V2.0
public class MyClass
{
  private String reference_val;

  ...

  public boolean hasReferenceVal ( final String[] strings )
  {
    for ( String s : strings )
    {
      if ( s == reference_val )
      {
        return true;
      }
    }

    return false;
  }

  private void makeCall ( )
  {
     final String[] interned_strings =  { ... init with interned values ... };

     if ( hasReference( interned_strings ) )
     {
        ...
     }
  }
}

Now you have a bug, that may be very hard to find, because in majority of cases array contains literal values, and sometimes a non-literal string is used. If equals were used instead of == then hasReferenceVal would have still continue to work. Once again, performance gain is miniscule, but maintenance cost is high.

DLL and LIB files - what and why?

One other difference lies in the performance.

As the DLL is loaded at runtime by the .exe(s), the .exe(s) and the DLL work with shared memory concept and hence the performance is low relatively to static linking.

On the other hand, a .lib is code that is linked statically at compile time into every process that requests. Hence the .exe(s) will have single memory, thus increasing the performance of the process.

parse html string with jquery

MarvinS.-

Try:

$.ajax({  
        url: uri+'?js',  
        success: function(data) {  
                var imgAttr = $("img", data).attr('src'); 
                var htmlCode = $(data).html();
                $('#imgSrc').html(imgAttr);
                $('#fullHtmlOutput').html(htmlCode);
        }  
    });

This should load the whole html block from data into #fullHtmlOutput and the src of the image into #imgSrc.

How do I get values from a SQL database into textboxes using C#?

using (SqlConnection connection =  new SqlConnection("Data Source=localhost;Initial Catalog=LoginScreen;Integrated Security=True"))
{
    SqlCommand command =
    new SqlCommand("select * from Pending_Tasks WHERE CustomerId=...", connection);
    connection.Open();

    SqlDataReader read= command.ExecuteReader();

    while (read.Read())
    {
        CustID.Text = (read["Customer_ID"].ToString());
        CustName.Text = (read["Customer_Name"].ToString());
        Add1.Text = (read["Address_1"].ToString());
        Add2.Text = (read["Address_2"].ToString());
        PostBox.Text = (read["Postcode"].ToString());
        PassBox.Text = (read["Password"].ToString());
        DatBox.Text = (read["Data_Important"].ToString());
        LanNumb.Text = (read["Landline"].ToString());
        MobNumber.Text = (read["Mobile"].ToString());
        FaultRep.Text = (read["Fault_Report"].ToString());
    }
    read.Close();
}

Make sure you have data in the query : select * from Pending_Tasks and you are using "using System.Data.SqlClient;"

Using python's mock patch.object to change the return value of a method called within another method

To add to Silfheed's answer, which was useful, I needed to patch multiple methods of the object in question. I found it more elegant to do it this way:

Given the following function to test, located in module.a_function.to_test.py:

from some_other.module import SomeOtherClass

def add_results():
    my_object = SomeOtherClass('some_contextual_parameters')
    result_a = my_object.method_a()
    result_b = my_object.method_b()
    
    return result_a + result_b

To test this function (or class method, it doesn't matter), one can patch multiple methods of the class SomeOtherClass by using patch.object() in combination with sys.modules:

@patch.object(sys.modules['module.a_function.to_test'], 'SomeOtherClass')
def test__should_add_results(self, mocked_other_class):
  mocked_other_class().method_a.return_value = 4
  mocked_other_class().method_b.return_value = 7

  self.assertEqual(add_results(), 11)

This works no matter the number of methods of SomeOtherClass you need to patch, with independent results.

Also, using the same patching method, an actual instance of SomeOtherClass can be returned if need be:

@patch.object(sys.modules['module.a_function.to_test'], 'SomeOtherClass')
def test__should_add_results(self, mocked_other_class):
  other_class_instance = SomeOtherClass('some_controlled_parameters')
  mocked_other_class.return_value = other_class_instance 
  ...

In WPF, what are the differences between the x:Name and Name attributes?

I always use the x:Name variant. I have no idea if this affects any performance, I just find it easier for the following reason. If you have your own usercontrols that reside in another assembly just the "Name" property won't always suffice. This makes it easier to just stick too the x:Name property.

How to set Sqlite3 to be case insensitive when string comparing?

Another option that may or may not make sense in your case, is to actually have a separate column with pre-lowerscored values of your existing column. This can be populated using the SQLite function LOWER(), and you can then perform matching on this column instead.

Obviously, it adds redundancy and a potential for inconsistency, but if your data is static it might be a suitable option.

Rmi connection refused with localhost

it seems that you should set your command as an String[],for example:

String[] command = new String[]{"rmiregistry","2020"};
Runtime.getRuntime().exec(command);

it just like the style of main(String[] args).

Http Post With Body

You can try something like this using HttpClient and HttpPost:

List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("mystring", "value_of_my_string"));
// etc...

// Post data to the server
HttpPost httppost = new HttpPost("http://...");
httppost.setEntity(new UrlEncodedFormEntity(params));

HttpClient httpclient = new DefaultHttpClient();
HttpResponse httpResponse = httpclient.execute(httppost);

How to filter in NaN (pandas)?

This doesn't work because NaN isn't equal to anything, including NaN. Use pd.isnull(df.var2) instead.

How to set Java environment path in Ubuntu

To Set JAVA_HOME / PATH for a single user, Login to your account and open .bash_profile file

$ vi ~/.bash_profile

Set JAVA_HOME as follows using syntax export JAVA_HOME=<path-to-java>. If your path is set to /usr/java/jdk1.5.0_07/bin/java, set it as follows:

export JAVA_HOME=/usr/java/jdk1.5.0_07/bin/java

Set PATH as follows:

export PATH=$PATH:/usr/java/jdk1.5.0_07/bin

Feel free to replace /usr/java/jdk1.5.0_07 as per your setup. Save and close the file. Just logout and login back to see new changes. Alternatively, type the following command to activate the new path settings immediately:

$ source ~/.bash_profile

OR

$ . ~/.bash_profile

Verify new settings:

$ echo $JAVA_HOME
$ echo $PATH

Tip: Use the following command to find out exact path to which java executable under UNIX / Linux:

$ which java

Please note that the file ~/.bashrc is similar, with the exception that ~/.bash_profile runs only for Bash login shells and .bashrc runs for every new Bash shell.

To Set JAVA_HOME / PATH for all user, You need to setup global config in /etc/profile OR /etc/bash.bashrc file for all users:

# vi /etc/profile

Next setup PATH / JAVA_PATH variables as follows:

export PATH=$PATH:/usr/java/jdk1.5.0_07/bin
export PATH=$PATH:/usr/java/jdk1.5.0_07/bin

Save and close the file. Once again you need to type the following command to activate the path settings immediately:

# source /etc/profile

OR

# . /etc/profile

Callback functions in C++

The accepted answer is very useful and quite comprehensive. However, the OP states

I would like to see a simple example to write a callback function.

So here you go, from C++11 you have std::function so there is no need for function pointers and similar stuff:

#include <functional>
#include <string>
#include <iostream>

void print_hashes(std::function<int (const std::string&)> hash_calculator) {
    std::string strings_to_hash[] = {"you", "saved", "my", "day"};
    for(auto s : strings_to_hash)
        std::cout << s << ":" << hash_calculator(s) << std::endl;    
}

int main() {
    print_hashes( [](const std::string& str) {   /** lambda expression */
        int result = 0;
        for (int i = 0; i < str.length(); i++)
            result += pow(31, i) * str.at(i);
        return result;
    });
    return 0;
}

This example is by the way somehow real, because you wish to call function print_hashes with different implementations of hash functions, for this purpose I provided a simple one. It receives a string, returns an int (a hash value of the provided string), and all that you need to remember from the syntax part is std::function<int (const std::string&)> which describes such function as an input argument of the function that will invoke it.

How to Remove Array Element and Then Re-Index Array?

Unset($array[0]); 

Sort($array); 

I don't know why this is being downvoted, but if anyone has bothered to try it, you will notice that it works. Using sort on an array reassigns the keys of the the array. The only drawback is it sorts the values. Since the keys will obviously be reassigned, even with array_values, it does not matter is the values are being sorted or not.

Using Pip to install packages to Anaconda Environment

For others who run into this situation, I found this to be the most straightforward solution:

  1. Run conda create -n venv_name and source activate venv_name, where venv_name is the name of your virtual environment.

  2. Run conda install pip. This will install pip to your venv directory.

  3. Find your anaconda directory, and find the actual venv folder. It should be somewhere like /anaconda/envs/venv_name/.

  4. Install new packages by doing /anaconda/envs/venv_name/bin/pip install package_name.

This should now successfully install packages using that virtual environment's pip!

How to see the values of a table variable at debug time in T-SQL?

Why not just select the Table and view the variable that way?

SELECT * FROM @d

How can I delete a newline if it is the last character in a file?

head -n -1 abc > newfile
tail -n 1 abc | tr -d '\n' >> newfile

Edit 2:

Here is an awk version (corrected) that doesn't accumulate a potentially huge array:

awk '{if (line) print line; line=$0} END {printf $0}' abc

How can I convert the "arguments" object to an array in JavaScript?

This is a very old question, but I think I have a solution that is slightly easier to type than previous solutions and doesn't rely on external libraries:

function sortArguments() {
  return Array.apply(null, arguments).sort();
}

IIS AppPoolIdentity and file system write access permissions

  1. Right click on folder.

  2. Click Properties

  3. Click Security Tab. You will see something like this:

enter image description here

  1. Click "Edit..." button in above screen. You will see something like this:

enter image description here

  1. Click "Add..." button in above screen. You will see something like this:

enter image description here

  1. Click "Locations..." button in above screen. You will see something like this. Now, go to the very of top of this tree structure and select your computer name, then click OK.

enter image description here

  1. Now type "iis apppool\your_apppool_name" and click "Check Names" button. If the apppool exists, you will see your apppool name in the textbox with underline in it. Click OK button.

enter image description here

  1. Check/uncheck whatever access you need to grant to the account

  2. Click Apply button and then OK.

Foreign Key naming scheme

The standard convention in SQL Server is:

FK_ForeignKeyTable_PrimaryKeyTable

So, for example, the key between notes and tasks would be:

FK_note_task

And the key between tasks and users would be:

FK_task_user

This gives you an 'at a glance' view of which tables are involved in the key, so it makes it easy to see which tables a particular one (the first one named) depends on (the second one named). In this scenario the complete set of keys would be:

FK_task_user
FK_note_task
FK_note_user

So you can see that tasks depend on users, and notes depend on both tasks and users.

Finding current executable's path without /proc/self/exe

Depending on the version of QNX Neutrino, there are different ways to find the full path and name of the executable file that was used to start the running process. I denote the process identifier as <PID>. Try the following:

  1. If the file /proc/self/exefile exists, then its contents are the requested information.
  2. If the file /proc/<PID>/exefile exists, then its contents are the requested information.
  3. If the file /proc/self/as exists, then:
    1. open() the file.
    2. Allocate a buffer of, at least, sizeof(procfs_debuginfo) + _POSIX_PATH_MAX.
    3. Give that buffer as input to devctl(fd, DCMD_PROC_MAPDEBUG_BASE,....
    4. Cast the buffer to a procfs_debuginfo*.
    5. The requested information is at the path field of the procfs_debuginfo structure. Warning: For some reason, sometimes, QNX omits the first slash / of the file path. Prepend that / when needed.
    6. Clean up (close the file, free the buffer, etc.).
  4. Try the procedure in 3. with the file /proc/<PID>/as.
  5. Try dladdr(dlsym(RTLD_DEFAULT, "main"), &dlinfo) where dlinfo is a Dl_info structure whose dli_fname might contain the requested information.

I hope this helps.

How to place two forms on the same page?

You can use this easiest method.

_x000D_
_x000D_
<form action="validator.php" method="post" id="form1">_x000D_
    <input type="text" name="user">_x000D_
    <input type="password" name="password">_x000D_
    <input type="submit" value="submit" form="form1">_x000D_
</form>_x000D_
_x000D_
<br />_x000D_
_x000D_
<form action="validator.php" method="post" id="form2">_x000D_
    <input type="text" name="user">_x000D_
    <input type="password" name="password">_x000D_
    <input type="submit" value="submit" form="form2">_x000D_
</form>
_x000D_
_x000D_
_x000D_

Disable SSL fallback and use only TLS for outbound connections in .NET? (Poodle mitigation)

@Eddie Loeffen's answer seems to be the most popular answer to this question, but it has some bad long term effects. If you review the documentation page for System.Net.ServicePointManager.SecurityProtocol here the remarks section implies that the negotiation phase should just address this (and forcing the protocol is bad practice because in the future, TLS 1.2 will be compromised as well). However, we wouldn't be looking for this answer if it did.

Researching, it appears that the ALPN negotiation protocol is required to get to TLS1.2 in the negotiation phase. We took that as our starting point and tried newer versions of the .Net framework to see where support starts. We found that .Net 4.5.2 does not support negotiation to TLS 1.2, but .Net 4.6 does.

So, even though forcing TLS1.2 will get the job done now, I recommend that you upgrade to .Net 4.6 instead. Since this is a PCI DSS issue for June 2016, the window is short, but the new framework is a better answer.

UPDATE: Working from the comments, I built this:

ServicePointManager.SecurityProtocol = 0;    
foreach (SecurityProtocolType protocol in SecurityProtocolType.GetValues(typeof(SecurityProtocolType)))
    {
        switch (protocol)
        {
            case SecurityProtocolType.Ssl3:
            case SecurityProtocolType.Tls:
            case SecurityProtocolType.Tls11:
                break;
            default:
                ServicePointManager.SecurityProtocol |= protocol;
            break;
        }
    }

In order to validate the concept, I or'd together SSL3 and TLS1.2 and ran the code targeting a server that supports only TLS 1.0 and TLS 1.2 (1.1 is disabled). With the or'd protocols, it seems to connect fine. If I change to SSL3 and TLS 1.1, that failed to connect. My validation uses HttpWebRequest from System.Net and just calls GetResponse(). For instance, I tried this and failed:

        HttpWebRequest request = WebRequest.Create("https://www.contoso.com/my/web/resource") as HttpWebRequest;
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls11;
        request.GetResponse();

while this worked:

        HttpWebRequest request = WebRequest.Create("https://www.contoso.com/my/web/resource") as HttpWebRequest;
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls12;
        request.GetResponse();

This has an advantage over forcing TLS 1.2 in that, if the .Net framework is upgraded so that there are more entries in the Enum, they will be supported by the code as is. It has a disadvantage over just using .Net 4.6 in that 4.6 uses ALPN and should support new protocols if no restriction is specified.

Edit 4/29/2019 - Microsoft published this article last October. It has a pretty good synopsis of their recommendation of how this should be done in the various versions of .net framework.

Generating Random Passwords

Insert a Timer: timer1, 2 buttons: button1, button2, 1 textBox: textBox1, and a comboBox: comboBox1. Make sure you declare:

int count = 0;

Source Code:

 private void button1_Click(object sender, EventArgs e)
    {
    // This clears the textBox, resets the count, and starts the timer
        count = 0;
        textBox1.Clear();
        timer1.Start();
    }

    private void timer1_Tick(object sender, EventArgs e)
    {
    // This generates the password, and types it in the textBox
        count += 1;
            string possible = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
            string psw = "";
            Random rnd = new Random { };
            psw += possible[rnd.Next(possible.Length)];
            textBox1.Text += psw;
            if (count == (comboBox1.SelectedIndex + 1))
            {
                timer1.Stop();
            }
    }
    private void Form1_Load(object sender, EventArgs e)
    {
        // This adds password lengths to the comboBox to choose from.
        comboBox1.Items.Add("1");
        comboBox1.Items.Add("2");
        comboBox1.Items.Add("3");
        comboBox1.Items.Add("4");
        comboBox1.Items.Add("5");
        comboBox1.Items.Add("6");
        comboBox1.Items.Add("7");
        comboBox1.Items.Add("8");
        comboBox1.Items.Add("9");
        comboBox1.Items.Add("10");
        comboBox1.Items.Add("11");
        comboBox1.Items.Add("12");
    }
    private void button2_click(object sender, EventArgs e)
    {
        // This encrypts the password
        tochar = textBox1.Text;
        textBox1.Clear();
        char[] carray = tochar.ToCharArray();
        for (int i = 0; i < carray.Length; i++)
        {
            int num = Convert.ToInt32(carray[i]) + 10;
            string cvrt = Convert.ToChar(num).ToString();
            textBox1.Text += cvrt;
        }
    }

Easiest way to loop through a filtered list with VBA?

I would recommend using Offset assuming that the Headers are in Row 1. See this example

Option Explicit

Sub Sample()
    Dim rRange As Range, filRange As Range, Rng as Range
    'Remove any filters
    ActiveSheet.AutoFilterMode = False

    '~~> Set your range
    Set rRange = Sheets("Sheet1").Range("A1:E10")

    With rRange
        '~~> Set your criteria and filter
        .AutoFilter Field:=1, Criteria1:="=1"

        '~~> Filter, offset(to exclude headers)
        Set filRange = .Offset(1, 0).SpecialCells(xlCellTypeVisible).EntireRow

        Debug.Print filRange.Address

        For Each Rng In filRange
            '~~> Your Code
        Next
    End With

    'Remove any filters
    ActiveSheet.AutoFilterMode = False
End Sub

How to parse Excel (XLS) file in Javascript/HTML5

This code can help you
Most of the time jszip.js is not working so include xlsx.full.min.js in your js code.

Html Code

 <input type="file" id="file" ng-model="csvFile"  
    onchange="angular.element(this).scope().ExcelExport(event)"/>

Javascript

<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.8.0/xlsx.js">
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.8.0/jszip.js">
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.10.8/xlsx.full.min.js">
</script>

$scope.ExcelExport= function (event) {


    var input = event.target;
    var reader = new FileReader();
    reader.onload = function(){
        var fileData = reader.result;
        var wb = XLSX.read(fileData, {type : 'binary'});

        wb.SheetNames.forEach(function(sheetName){
        var rowObj =XLSX.utils.sheet_to_row_object_array(wb.Sheets[sheetName]);
        var jsonObj = JSON.stringify(rowObj);
        console.log(jsonObj)
        })
    };
    reader.readAsBinaryString(input.files[0]);
    };

Python one-line "for" expression

for item in array: array2.append (item)

Or, in this case:

array2 += array

What is the difference between Select and Project Operations

select just changes cardinality of the result table but project does change both degree of relation and cardinality.

How do I convert certain columns of a data frame to become factors?

Here's an example:

#Create a data frame
> d<- data.frame(a=1:3, b=2:4)
> d
  a b
1 1 2
2 2 3
3 3 4

#currently, there are no levels in the `a` column, since it's numeric as you point out.
> levels(d$a)
NULL

#Convert that column to a factor
> d$a <- factor(d$a)
> d
  a b
1 1 2
2 2 3
3 3 4

#Now it has levels.
> levels(d$a)
[1] "1" "2" "3"

You can also handle this when reading in your data. See the colClasses and stringsAsFactors parameters in e.g. readCSV().

Note that, computationally, factoring such columns won't help you much, and may actually slow down your program (albeit negligibly). Using a factor will require that all values are mapped to IDs behind the scenes, so any print of your data.frame requires a lookup on those levels -- an extra step which takes time.

Factors are great when storing strings which you don't want to store repeatedly, but would rather reference by their ID. Consider storing a more friendly name in such columns to fully benefit from factors.

dlib installation on Windows 10

None of the answers worked for me. This is what worked Assuming you have anaconda python 3.7 installed

1) Dowload and install cmake(make sure to check the option to add cmake to system path during installation to avoid manually doing later) Download from this link cmake download

2) conda install -c conda-forge dlib

What's the difference between "git reset" and "git checkout"?

  • git reset is specifically about updating the index, moving the HEAD.
  • git checkout is about updating the working tree (to the index or the specified tree). It will update the HEAD only if you checkout a branch (if not, you end up with a detached HEAD).
    (actually, with Git 2.23 Q3 2019, this will be git restore, not necessarily git checkout)

By comparison, since svn has no index, only a working tree, svn checkout will copy a given revision on a separate directory.
The closer equivalent for git checkout would:

  • svn update (if you are in the same branch, meaning the same SVN URL)
  • svn switch (if you checkout for instance the same branch, but from another SVN repo URL)

All those three working tree modifications (svn checkout, update, switch) have only one command in git: git checkout.
But since git has also the notion of index (that "staging area" between the repo and the working tree), you also have git reset.


Thinkeye mentions in the comments the article "Reset Demystified ".

For instance, if we have two branches, 'master' and 'develop' pointing at different commits, and we're currently on 'develop' (so HEAD points to it) and we run git reset master, 'develop' itself will now point to the same commit that 'master' does.

On the other hand, if we instead run git checkout master, 'develop' will not move, HEAD itself will. HEAD will now point to 'master'.

So, in both cases we're moving HEAD to point to commit A, but how we do so is very different. reset will move the branch HEAD points to, checkout moves HEAD itself to point to another branch.

http://git-scm.com/images/reset/reset-checkout.png

On those points, though:

LarsH adds in the comments:

The first paragraph of this answer, though, is misleading: "git checkout ... will update the HEAD only if you checkout a branch (if not, you end up with a detached HEAD)".
Not true: git checkout will update the HEAD even if you checkout a commit that's not a branch (and yes, you end up with a detached HEAD, but it still got updated).

git checkout a839e8f updates HEAD to point to commit a839e8f.

De Novo concurs in the comments:

@LarsH is correct.
The second bullet has a misconception about what HEAD is in will update the HEAD only if you checkout a branch.
HEAD goes wherever you are, like a shadow.
Checking out some non-branch ref (e.g., a tag), or a commit directly, will move HEAD. Detached head doesn't mean you've detached from the HEAD, it means the head is detached from a branch ref, which you can see from, e.g., git log --pretty=format:"%d" -1.

  • Attached head states will start with (HEAD ->,
  • detached will still show (HEAD, but will not have an arrow to a branch ref.

Best way to represent a Grid or Table in AngularJS with Bootstrap 3?

TrNgGrid is working great so far. Here are the reasons I prefer it to ng-grid and moved to this component

  • It makes table elements so it can be bootswatched and use all the power of bootstrap .css (ng-grid uses jQuery UI themes).

  • Simple, well documented grid options.

  • Server size paging works

Why compile Python code?

Yep, performance is the main reason and, as far as I know, the only reason.

If some of your files aren't getting compiled, maybe Python isn't able to write to the .pyc file, perhaps because of the directory permissions or something. Or perhaps the uncompiled files just aren't ever getting loaded... (scripts/modules only get compiled when they first get loaded)

How can I multiply and divide using only bit shifting and adding?

Take two numbers, lets say 9 and 10, write them as binary - 1001 and 1010.

Start with a result, R, of 0.

Take one of the numbers, 1010 in this case, we'll call it A, and shift it right by one bit, if you shift out a one, add the first number, we'll call it B, to R.

Now shift B left by one bit and repeat until all bits have been shifted out of A.

It's easier to see what's going on if you see it written out, this is the example:

      0
   0000      0
  10010      1
 000000      0
1001000      1
 ------
1011010

How to initialize an array in angular2 and typescript

In order to make more concise you can declare constructor parameters as public which automatically create properties with same names and these properties are available via this:

export class Environment {

  constructor(public id:number, public name:string) {}

  getProperties() {
    return `${this.id} : ${this.name}`;
  }
}

let serverEnv = new Environment(80, 'port');
console.log(serverEnv);

 ---result---
// Environment { id: 80, name: 'port' }

How to convert NUM to INT in R?

You can use convert from hablar to change a column of the data frame quickly.

library(tidyverse)
library(hablar)

x <- tibble(var = c(1.34, 4.45, 6.98))

x %>% 
  convert(int(var))

gives you:

# A tibble: 3 x 1
    var
  <int>
1     1
2     4
3     6

jQuery checkbox check/uncheck

 $('mainCheckBox').click(function(){
    if($(this).prop('checked')){
        $('Id or Class of checkbox').prop('checked', true);
    }else{
        $('Id or Class of checkbox').prop('checked', false);
    }
});

How to Update Multiple Array Elements in mongodb

Please be aware that some answers in this thread suggesting use $[] is WRONG.

db.collection.update(
   {"events.profile":10},
   {$set:{"events.$[].handled":0}},
   {multi:true}
)

The above code will update "handled" to 0 for all elements in "events" array, regardless of its "profile" value. The query {"events.profile":10} is only to filter the whole document, not the documents in the array. In this situation it is a must to use $[elem] with arrayFilters to specify the condition of array items so Neil Lunn's answer is correct.

How many bits or bytes are there in a character?

It depends what is the character and what encoding it is in:

  • An ASCII character in 8-bit ASCII encoding is 8 bits (1 byte), though it can fit in 7 bits.

  • An ISO-8895-1 character in ISO-8859-1 encoding is 8 bits (1 byte).

  • A Unicode character in UTF-8 encoding is between 8 bits (1 byte) and 32 bits (4 bytes).

  • A Unicode character in UTF-16 encoding is between 16 (2 bytes) and 32 bits (4 bytes), though most of the common characters take 16 bits. This is the encoding used by Windows internally.

  • A Unicode character in UTF-32 encoding is always 32 bits (4 bytes).

  • An ASCII character in UTF-8 is 8 bits (1 byte), and in UTF-16 - 16 bits.

  • The additional (non-ASCII) characters in ISO-8895-1 (0xA0-0xFF) would take 16 bits in UTF-8 and UTF-16.

That would mean that there are between 0.03125 and 0.125 characters in a bit.