Programs & Examples On #Exchange server 2007

Released to business customers as part of Microsoft's roll-out wave of new products. It includes new clustering options, x64 support for greater scalability, voice mail integration, better search&support for Web services, better filtering options, and a new Outlook Web Access interface. Exchange 2007 also dropped support for Exchange 5.5 migrations, routing groups, admin groups, Outlook Mobile Access, X.400, and some API interfaces, amongst other features.

Powershell command to hide user from exchange address lists

I was getting the exact same error, however I solved it by running $false first and then $true.

Android map v2 zoom to show all the markers

I had similar problem, using following code solved the issue:

CameraUpdateFactory.newLatLngBounds(bounds, 200, 200, 5) generally the location differences in my case are no more than two neighbour cities.

zoom to fit all markers on map google maps v2

Perl - If string contains text?

if ($string =~ m/something/) {
   # Do work
}

Where something is a regular expression.

matplotlib.pyplot will not forget previous plots - how can I flush/refresh?

I discovered that this behaviour only occurs after running a particular script, similar to the one in the question. I have no idea why it occurs.

It works (refreshes the graphs) if I put

plt.clf()
plt.cla()
plt.close()

after every plt.show()

Find out free space on tablespace

The following query will help to find out free space of tablespaces in MB:

select tablespace_name , sum(bytes)/1024/1024 from dba_free_space group by tablespacE_name order by 1;

What is the use of adding a null key or value to a HashMap in Java?

One example of usage for null values is when using a HashMap as a cache for results of an expensive operation (such as a call to an external web service) which may return null.

Putting a null value in the map then allows you to distinguish between the case where the operation has not been performed for a given key (cache.containsKey(someKey) returns false), and where the operation has been performed but returned a null value (cache.containsKey(someKey) returns true, cache.get(someKey) returns null).

Without null values, you would have to either put some special value in the cache to indicate a null response, or simply not cache that response at all and perform the operation every time.

How to fix error "Updating Maven Project". Unsupported IClasspathEntry kind=4?

I tried Marco's steps but no luck. Instead if you just get the latest m2e plugin from the link he provides and one by one right click on each project -> Maven -> Update Dependencies the error still pops up but the issue is resolved. That is to say the warnings disappear in the Markers view. I encountered this issue after importing some projects into SpringSource Tool Suite (STS). When I returned to my Eclipse Juno installation the warnings were displaying. Seeing that I had m2e 1.1 already installed I tried Marco's steps to no avail. Getting the latest version fixed it however.

A reference to the dll could not be added

I have the same problem with importing WinSCard.dll in my project. I deal with that importing directly from dll like this:

[DllImport("winscard.dll")]
public static extern int SCardEstablishContext(int dwScope, int pvReserved1, int pvReserved2, ref int phContext);

[DllImport("winscard.dll")]
public static extern int SCardReleaseContext(int phContext);

You could add this to separate project and then add a reference from your main project.

What are these ^M's that keep showing up in my files in emacs?

^M at the end of line in Emacs is indicating a carriage return (\r) followed by a line feed (\n). You'll often see this if one person edits files on Windows (where end of line is the combination of carriage return and newline characters) and you edit in Unix or Linux (where end of line is only a newline character).

The combination of characters is usually not harmful. If you're using source control, you may be able to configure the text file checkin format so that lines are magically adjusted for you. Alternatively, you may be able to use checkin and checkout triggers that will automatically "fix" the files for you. Or, you might just use a tool like dos2unix to manually adjust things.

Exporting functions from a DLL with dllexport

If you want plain C exports, use a C project not C++. C++ DLLs rely on name-mangling for all the C++isms (namespaces etc...). You can compile your code as C by going into your project settings under C/C++->Advanced, there is an option "Compile As" which corresponds to the compiler switches /TP and /TC.

If you still want to use C++ to write the internals of your lib but export some functions unmangled for use outside C++, see the second section below.

Exporting/Importing DLL Libs in VC++

What you really want to do is define a conditional macro in a header that will be included in all of the source files in your DLL project:

#ifdef LIBRARY_EXPORTS
#    define LIBRARY_API __declspec(dllexport)
#else
#    define LIBRARY_API __declspec(dllimport)
#endif

Then on a function that you want to be exported you use LIBRARY_API:

LIBRARY_API int GetCoolInteger();

In your library build project create a define LIBRARY_EXPORTS this will cause your functions to be exported for your DLL build.

Since LIBRARY_EXPORTS will not be defined in a project consuming the DLL, when that project includes the header file of your library all of the functions will be imported instead.

If your library is to be cross-platform you can define LIBRARY_API as nothing when not on Windows:

#ifdef _WIN32
#    ifdef LIBRARY_EXPORTS
#        define LIBRARY_API __declspec(dllexport)
#    else
#        define LIBRARY_API __declspec(dllimport)
#    endif
#elif
#    define LIBRARY_API
#endif

When using dllexport/dllimport you do not need to use DEF files, if you use DEF files you do not need to use dllexport/dllimport. The two methods accomplish the same task different ways, I believe that dllexport/dllimport is the recommended method out of the two.

Exporting unmangled functions from a C++ DLL for LoadLibrary/PInvoke

If you need this to use LoadLibrary and GetProcAddress, or maybe importing from another language (i.e PInvoke from .NET, or FFI in Python/R etc) you can use extern "C" inline with your dllexport to tell the C++ compiler not to mangle the names. And since we are using GetProcAddress instead of dllimport we don't need to do the ifdef dance from above, just a simple dllexport:

The Code:

#define EXTERN_DLL_EXPORT extern "C" __declspec(dllexport)

EXTERN_DLL_EXPORT int getEngineVersion() {
  return 1;
}

EXTERN_DLL_EXPORT void registerPlugin(Kernel &K) {
  K.getGraphicsServer().addGraphicsDriver(
    auto_ptr<GraphicsServer::GraphicsDriver>(new OpenGLGraphicsDriver())
  );
}

And here's what the exports look like with Dumpbin /exports:

  Dump of file opengl_plugin.dll

  File Type: DLL

  Section contains the following exports for opengl_plugin.dll

    00000000 characteristics
    49866068 time date stamp Sun Feb 01 19:54:32 2009
        0.00 version
           1 ordinal base
           2 number of functions
           2 number of names

    ordinal hint RVA      name

          1    0 0001110E getEngineVersion = @ILT+265(_getEngineVersion)
          2    1 00011028 registerPlugin = @ILT+35(_registerPlugin)

So this code works fine:

m_hDLL = ::LoadLibrary(T"opengl_plugin.dll");

m_pfnGetEngineVersion = reinterpret_cast<fnGetEngineVersion *>(
  ::GetProcAddress(m_hDLL, "getEngineVersion")
);
m_pfnRegisterPlugin = reinterpret_cast<fnRegisterPlugin *>(
  ::GetProcAddress(m_hDLL, "registerPlugin")
);

How to upgrade pip3?

In Ubuntu 18.04, below are the steps that I followed.

python3 -m pip install --upgrade pip

For some reason you will be getting an error, and that be fixed by making bash forget the wrongly referenced locations using the following command.

hash -r pip

How to build a DataTable from a DataGridView?

I don't know anything provided by the Framework (beyond what you want to avoid) that would do what you want but (as I suspect you know) it would be pretty easy to create something simple yourself:

private DataTable GetDataTableFromDGV(DataGridView dgv) {
    var dt = new DataTable();
    foreach (DataGridViewColumn column in dgv.Columns) {
        if (column.Visible) {
            // You could potentially name the column based on the DGV column name (beware of dupes)
            // or assign a type based on the data type of the data bound to this DGV column.
            dt.Columns.Add();
        }
    }

    object[] cellValues = new object[dgv.Columns.Count];
    foreach (DataGridViewRow row in dgv.Rows) {
        for (int i = 0; i < row.Cells.Count; i++) {
            cellValues[i] = row.Cells[i].Value;
        }
        dt.Rows.Add(cellValues);
    }

    return dt;
}

Excel - find cell with same value in another worksheet and enter the value to the left of it

Assuming employee numbers are in the first column and their names are in the second:

=VLOOKUP(A1, Sheet2!A:B, 2,false)

Python: Best way to add to sys.path relative to the current running script

There is a problem with every answer provided that can be summarized as "just add this magical incantation to the beginning of your script. See what you can do with just a line or two of code." They will not work in every possible situation!

For example, one such magical incantation uses __file__. Unfortunately, if you package your script using cx_Freeze or you are using IDLE, this will result in an exception.

Another such magical incantation uses os.getcwd(). This will only work if you are running your script from the command prompt and the directory containing your script is the current working directory (that is you used the cd command to change into the directory prior to running the script). Eh gods! I hope I do not have to explain why this will not work if your Python script is in the PATH somewhere and you ran it by simply typing the name of your script file.

Fortunately, there is a magical incantation that will work in all the cases I have tested. Unfortunately, the magical incantation is more than just a line or two of code.

import inspect
import os
import sys

# Add script directory to sys.path.
# This is complicated due to the fact that __file__ is not always defined.

def GetScriptDirectory():
    if hasattr(GetScriptDirectory, "dir"):
        return GetScriptDirectory.dir
    module_path = ""
    try:
        # The easy way. Just use __file__.
        # Unfortunately, __file__ is not available when cx_Freeze is used or in IDLE.
        module_path = __file__
    except NameError:
        if len(sys.argv) > 0 and len(sys.argv[0]) > 0 and os.path.isabs(sys.argv[0]):
            module_path = sys.argv[0]
        else:
            module_path = os.path.abspath(inspect.getfile(GetScriptDirectory))
            if not os.path.exists(module_path):
                # If cx_Freeze is used the value of the module_path variable at this point is in the following format.
                # {PathToExeFile}\{NameOfPythonSourceFile}. This makes it necessary to strip off the file name to get the correct
                # path.
                module_path = os.path.dirname(module_path)
    GetScriptDirectory.dir = os.path.dirname(module_path)
    return GetScriptDirectory.dir

sys.path.append(os.path.join(GetScriptDirectory(), "lib"))
print(GetScriptDirectory())
print(sys.path)

As you can see, this is no easy task!

How to check if "Radiobutton" is checked?

You can use switch like this:

XML Layout

<RadioGroup
            android:id="@+id/RG"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">

            <RadioButton
                android:id="@+id/R1"
                android:layout_width="wrap_contnet"
                android:layout_height="wrap_content"
                android:text="R1" />

            <RadioButton
                android:id="@+id/R2"
                android:layout_width="wrap_contnet"
                android:layout_height="wrap_content"
                android:text="R2" />
</RadioGroup>

And JAVA Activity

switch (RG.getCheckedRadioButtonId()) {
        case R.id.R1:
            regAuxiliar = ultimoRegistro;
        case R.id.R2:
            regAuxiliar = objRegistro;
        default:
            regAuxiliar = null; // none selected
    }

You will also need to implement an onClick function with button or setOnCheckedChangeListener function to get required functionality.

C Macro definition to determine big endian or little endian machine?

If you have a compiler that supports C99 compound literals:

#define IS_BIG_ENDIAN (!*(unsigned char *)&(uint16_t){1})

or:

#define IS_BIG_ENDIAN (!(union { uint16_t u16; unsigned char c; }){ .u16 = 1 }.c)

In general though, you should try to write code that does not depend on the endianness of the host platform.


Example of host-endianness-independent implementation of ntohl():

uint32_t ntohl(uint32_t n)
{
    unsigned char *np = (unsigned char *)&n;

    return ((uint32_t)np[0] << 24) |
        ((uint32_t)np[1] << 16) |
        ((uint32_t)np[2] << 8) |
        (uint32_t)np[3];
}

How do I delete files programmatically on Android?

Try this one. It is working for me.

handler.postDelayed(new Runnable() {
    @Override
    public void run() {
        // Set up the projection (we only need the ID)
        String[] projection = { MediaStore.Images.Media._ID };

        // Match on the file path
        String selection = MediaStore.Images.Media.DATA + " = ?";
        String[] selectionArgs = new String[] { imageFile.getAbsolutePath() };

        // Query for the ID of the media matching the file path
        Uri queryUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
        ContentResolver contentResolver = getActivity().getContentResolver();
        Cursor c = contentResolver.query(queryUri, projection, selection, selectionArgs, null);

        if (c != null) {
            if (c.moveToFirst()) {
                // We found the ID. Deleting the item via the content provider will also remove the file
                long id = c.getLong(c.getColumnIndexOrThrow(MediaStore.Images.Media._ID));
                Uri deleteUri = ContentUris.withAppendedId(queryUri, id);
                contentResolver.delete(deleteUri, null, null);
            } else {
                // File not found in media store DB
            }
            c.close();
        }
    }
}, 5000);

How to write a foreach in SQL Server?

I came up with a very effective, (I think) readable way to do this.

    1. create a temp table and put the records you want to iterate in there
    2. use WHILE @@ROWCOUNT <> 0 to do the iterating
    3. to get one row at a time do, SELECT TOP 1 <fieldnames>
        b. save the unique ID for that row in a variable
    4. Do Stuff, then delete the row from the temp table based on the ID saved at step 3b.

Here's the code. Sorry, its using my variable names instead of the ones in the question.

            declare @tempPFRunStops TABLE (ProformaRunStopsID int,ProformaRunMasterID int, CompanyLocationID int, StopSequence int );    

        INSERT @tempPFRunStops (ProformaRunStopsID,ProformaRunMasterID, CompanyLocationID, StopSequence) 
        SELECT ProformaRunStopsID, ProformaRunMasterID, CompanyLocationID, StopSequence from ProformaRunStops 
        WHERE ProformaRunMasterID IN ( SELECT ProformaRunMasterID FROM ProformaRunMaster WHERE ProformaId = 15 )

    -- SELECT * FROM @tempPFRunStops

    WHILE @@ROWCOUNT <> 0  -- << I dont know how this works
        BEGIN
            SELECT TOP 1 * FROM @tempPFRunStops
            -- I could have put the unique ID into a variable here
            SELECT 'Ha'  -- Do Stuff
            DELETE @tempPFRunStops WHERE ProformaRunStopsID = (SELECT TOP 1 ProformaRunStopsID FROM @tempPFRunStops)
        END

Embed an External Page Without an Iframe?

Why not use PHP! It's all server side:

<?php print file_get_contents("http://foo.com")?>

If you own both sites, you may need to ok this transaction with full declaration of headers at the server end. Works beautifully.

Update multiple tables in SQL Server using INNER JOIN

You can update with a join if you only affect one table like this:

UPDATE table1 
SET table1.name = table2.name 
FROM table1, table2 
WHERE table1.id = table2.id 
AND table2.foobar ='stuff'

But you are trying to affect multiple tables with an update statement that joins on multiple tables. That is not possible.

However, updating two tables in one statement is actually possible but will need to create a View using a UNION that contains both the tables you want to update. You can then update the View which will then update the underlying tables.

SQL JOINS

But this is a really hacky parlor trick, use the transaction and multiple updates, it's much more intuitive.

Test for non-zero length string in Bash: [ -n "$var" ] or [ "$var" ]

Edit: This is a more complete version that shows more differences between [ (aka test) and [[.

The following table shows that whether a variable is quoted or not, whether you use single or double brackets and whether the variable contains only a space are the things that affect whether using a test with or without -n/-z is suitable for checking a variable.

     | 1a    2a    3a    4a    5a    6a   | 1b    2b    3b    4b    5b    6b
     | [     ["    [-n   [-n"  [-z   [-z" | [[    [["   [[-n  [[-n" [[-z  [[-z"
-----+------------------------------------+------------------------------------
unset| false false true  false true  true | false false false false true  true
null | false false true  false true  true | false false false false true  true
space| false true  true  true  true  false| true  true  true  true  false false
zero | true  true  true  true  false false| true  true  true  true  false false
digit| true  true  true  true  false false| true  true  true  true  false false
char | true  true  true  true  false false| true  true  true  true  false false
hyphn| true  true  true  true  false false| true  true  true  true  false false
two  | -err- true  -err- true  -err- false| true  true  true  true  false false
part | -err- true  -err- true  -err- false| true  true  true  true  false false
Tstr | true  true  -err- true  -err- false| true  true  true  true  false false
Fsym | false true  -err- true  -err- false| true  true  true  true  false false
T=   | true  true  -err- true  -err- false| true  true  true  true  false false
F=   | false true  -err- true  -err- false| true  true  true  true  false false
T!=  | true  true  -err- true  -err- false| true  true  true  true  false false
F!=  | false true  -err- true  -err- false| true  true  true  true  false false
Teq  | true  true  -err- true  -err- false| true  true  true  true  false false
Feq  | false true  -err- true  -err- false| true  true  true  true  false false
Tne  | true  true  -err- true  -err- false| true  true  true  true  false false
Fne  | false true  -err- true  -err- false| true  true  true  true  false false

If you want to know if a variable is non-zero length, do any of the following:

  • quote the variable in single brackets (column 2a)
  • use -n and quote the variable in single brackets (column 4a)
  • use double brackets with or without quoting and with or without -n (columns 1b - 4b)

Notice in column 1a starting at the row labeled "two" that the result indicates that [ is evaluating the contents of the variable as if they were part of the conditional expression (the result matches the assertion implied by the "T" or "F" in the description column). When [[ is used (column 1b), the variable content is seen as a string and not evaluated.

The errors in columns 3a and 5a are caused by the fact that the variable value includes a space and the variable is unquoted. Again, as shown in columns 3b and 5b, [[ evaluates the variable's contents as a string.

Correspondingly, for tests for zero-length strings, columns 6a, 5b and 6b show the correct ways to do that. Also note that any of these tests can be negated if negating shows a clearer intent than using the opposite operation. For example: if ! [[ -n $var ]].

If you're using [, the key to making sure that you don't get unexpected results is quoting the variable. Using [[, it doesn't matter.

The error messages, which are being suppressed, are "unary operator expected" or "binary operator expected".

This is the script that produced the table above.

#!/bin/bash
# by Dennis Williamson
# 2010-10-06, revised 2010-11-10
# for http://stackoverflow.com/q/3869072
# designed to fit an 80 character terminal

dw=5    # description column width
w=6     # table column width

t () { printf '%-*s' "$w" " true"; }
f () { [[ $? == 1 ]] && printf '%-*s' "$w" " false" || printf '%-*s' "$w" " -err-"; }

o=/dev/null

echo '     | 1a    2a    3a    4a    5a    6a   | 1b    2b    3b    4b    5b    6b'
echo '     | [     ["    [-n   [-n"  [-z   [-z" | [[    [["   [[-n  [[-n" [[-z  [[-z"'
echo '-----+------------------------------------+------------------------------------'

while read -r d t
do
    printf '%-*s|' "$dw" "$d"

    case $d in
        unset) unset t  ;;
        space) t=' '    ;;
    esac

    [ $t ]        2>$o  && t || f
    [ "$t" ]            && t || f
    [ -n $t ]     2>$o  && t || f
    [ -n "$t" ]         && t || f
    [ -z $t ]     2>$o  && t || f
    [ -z "$t" ]         && t || f
    echo -n "|"
    [[ $t ]]            && t || f
    [[ "$t" ]]          && t || f
    [[ -n $t ]]         && t || f
    [[ -n "$t" ]]       && t || f
    [[ -z $t ]]         && t || f
    [[ -z "$t" ]]       && t || f
    echo

done <<'EOF'
unset
null
space
zero    0
digit   1
char    c
hyphn   -z
two     a b
part    a -a
Tstr    -n a
Fsym    -h .
T=      1 = 1
F=      1 = 2
T!=     1 != 2
F!=     1 != 1
Teq     1 -eq 1
Feq     1 -eq 2
Tne     1 -ne 2
Fne     1 -ne 1
EOF

while installing vc_redist.x64.exe, getting error "Failed to configure per-machine MSU package."

I faced a similar problem but in my case I was trying to install Visual C++ Redistributable for Visual Studio 2015 Update 1 on Windows Server 2012 R2. However the root cause should be the same.

In short, you need to install the prerequisites of KB2999226.

In more details, the installation log I got stated that the installation for Windows Update KB2999226 failed. According to the Microsoft website here:

Prerequisites To install this update, you must have April 2014 update rollup for Windows RT 8.1, Windows 8.1, and Windows Server 2012 R2 (2919355) installed in Windows 8.1 or Windows Server 2012 R2. Or, install Service Pack 1 for Windows 7 or Windows Server 2008 R2. Or, install Service Pack 2 for Windows Vista and for Windows Server 2008.

After I have installed April 2014 on my Windows Server 2012 R2, I am able to install the Visual C++ Redistributable correctly.

Online Internet Explorer Simulators

Adobe Contribute provides a snapshot service also, but it's not free.

Here's the developer toolbar for IE 6 and 7.

Is there a way to get a collection of all the Models in your Rails app?

In just one line:

 ActiveRecord::Base.subclasses.map(&:name)

DataGridView checkbox column - value and functionality

If you try it on CellContentClick Event

Use:

dataGridView1.EndEdit();  //Stop editing of cell.
MessageBox.Show("0 = " + dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString());

How to get default gateway in Mac OSX

For getting the list of ip addresses associated, you can use netstat command

netstat -rn 

This gives a long list of ip addresses and it is not easy to find the required field. The sample result is as following:

Routing tables
Internet:
Destination        Gateway            Flags        Refs      Use   Netif Expire
default            192.168.195.1      UGSc           17        0     en2
127                127.0.0.1          UCS             0        0     lo0
127.0.0.1          127.0.0.1          UH              1   254107     lo0
169.254            link#7             UCS             0        0     en2
192.168.195        link#7             UCS             3        0     en2
192.168.195.1      0:27:22:67:35:ee   UHLWIi         22      397     en2   1193
192.168.195.5      127.0.0.1          UHS             0        0     lo0

More result is truncated.......

The ip address of gateway is in the first line; one with default at its first column.

To display only the selected lines of result, we can use grep command along with netstat

netstat -rn | grep 'default'

This command filters and displays those lines of result having default. In this case, you can see result like following:

default            192.168.195.1      UGSc           14        0     en2

If you are interested in finding only the ip address of gateway and nothing else you can further filter the result using awk. The awk command matches pattern in the input result and displays the output. This can be useful when you are using your result directly in some program or batch job.

netstat -rn | grep 'default' | awk '{print $2}'

The awk command tells to match and print the second column of the result in the text. The final result thus looks like this:

192.168.195.1

In this case, netstat displays all result, grep only selects the line with 'default' in it, and awk further matches the pattern to display the second column in the text.

You can similarly use route -n get default command to get the required result. The full command is

route -n get default | grep 'gateway' | awk '{print $2}'

These commands work well in linux as well as unix systems and MAC OS.

Sorting std::map using value

If you want to present the values in a map in sorted order, then copy the values from the map to vector and sort the vector.

How can I check that JButton is pressed? If the isEnable() is not work?

Just do System.out.println(e.getActionCommand()); inside actionPerformed(ActionEvent e) function. This will tell you which command is just performed.

or

if(e.getActionCommand().equals("Add")){

   System.out.println("Add button pressed");
}

SQLite string contains other string query

Using LIKE:

SELECT *
  FROM TABLE
 WHERE column LIKE '%cats%'  --case-insensitive

SQL Server table creation date query

For SQL Server 2000:

SELECT   su.name,so.name,so.crdate,* 
FROM     sysobjects so JOIN sysusers su
ON       so.uid = su.uid
WHERE    xtype='U'
ORDER BY so.name

Setting individual axis limits with facet_wrap and scales = "free" in ggplot2

Here's some code with a dummy geom_blank layer,

range_act <- range(range(results$act), range(results$pred))

d <- reshape2::melt(results, id.vars = "pred")

dummy <- data.frame(pred = range_act, value = range_act,
                    variable = "act", stringsAsFactors=FALSE)

ggplot(d, aes(x = pred, y = value)) +
  facet_wrap(~variable, scales = "free") +
  geom_point(size = 2.5) + 
  geom_blank(data=dummy) + 
  theme_bw()

enter image description here

adding a datatable in a dataset

Just give any name to the DataTable Like:

DataTable dt = new DataTable();
dt = SecondDataTable.Copy();    
dt .TableName = "New Name";
DataSet.Tables.Add(dt );

Swift - Split string over multiple lines

Sample

var yourString = "first line \n second line \n third line"

In case, you don't find the + operator suitable

How to download all files (but not HTML) from a website using wget?

To filter for specific file extensions:

wget -A pdf,jpg -m -p -E -k -K -np http://site/path/

Or, if you prefer long option names:

wget --accept pdf,jpg --mirror --page-requisites --adjust-extension --convert-links --backup-converted --no-parent http://site/path/

This will mirror the site, but the files without jpg or pdf extension will be automatically removed.

Adding header to all request with Retrofit 2

Use this Retrofit Client

class RetrofitClient2(context: Context) : OkHttpClient() {

    private var mContext:Context = context
    private var retrofit: Retrofit? = null

    val client: Retrofit?
        get() {
            val logging = HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY)

            val client = OkHttpClient.Builder()
                    .connectTimeout(Constants.TIME_OUT, TimeUnit.SECONDS)
                    .readTimeout(Constants.TIME_OUT, TimeUnit.SECONDS)
                    .writeTimeout(Constants.TIME_OUT, TimeUnit.SECONDS)
            client.addInterceptor(logging)
            client.interceptors().add(AddCookiesInterceptor(mContext))

            val gson = GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").create()
            if (retrofit == null) {

                retrofit = Retrofit.Builder()
                        .baseUrl(Constants.URL)
                        .addConverterFactory(GsonConverterFactory.create(gson))
                        .client(client.build())
                        .build()
            }
            return retrofit
        }
}

I'm passing the JWT along with every request. Please don't mind the variable names, it's a bit confusing.

class AddCookiesInterceptor(context: Context) : Interceptor {
    val mContext: Context = context
    @Throws(IOException::class)
    override fun intercept(chain: Interceptor.Chain): Response {
        val builder = chain.request().newBuilder()
        val preferences = CookieStore().getCookies(mContext)
        if (preferences != null) {
            for (cookie in preferences!!) {
                builder.addHeader("Authorization", cookie)
            }
        }
        return chain.proceed(builder.build())
    }
}

What is correct media query for IPad Pro?

/* Landscape*/

@media only screen and (min-device-width: 1366px) and (max-device-height: 1024px) and (-webkit-min-device-pixel-ratio: 2)  and (orientation: landscape)  {}

/* Portrait*/
@media only screen and (min-device-width: 1024px) and (max-device-height: 1366px) and (-webkit-min-device-pixel-ratio: 2)  and (orientation: portrait)  {}

Portrait medias query for iPad Pro should be fine as it is.

Landscape media query for iPad Pro (min-device-width) should be 1366px and (max device-height) should be 1024px.

Hope this helps.

Installing PIL with pip

(Window) If Pilow not work try download pil at http://www.pythonware.com/products/pil/

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '1922-1' for key 'IDX_STOCK_PRODUCT'

Many time this error is caused when you update a product in your custom module's observer as shown below.

class [NAMESPACE]_[MODULE NAME]_Model_Observer
{
    /**
     * Flag to stop observer executing more than once
     *
     * @var static bool
     */
    static protected $_singletonFlag = false;

    public function saveProductData(Varien_Event_Observer $observer)
    {
        if (!self::$_singletonFlag) {
            self::$_singletonFlag = true;

            $product = $observer->getEvent()->getProduct();
             //do stuff to the $product object
            // $product->save();  // commenting out this line prevents the error
            $product->getResource()->save($product);
    }
} 

Hence whenever you save your product after updating some properties in your module's observer use $product->getResource()->save($product) instead of $product->save()

link_to image tag. how to add class to a tag

I tried this too, and works very well:

      <%= link_to home_index_path do %>
      <div class='logo-container'>
        <div class='logo'>
          <%= image_tag('bar.ico') %>
        </div>
        <div class='brand' style='font-size: large;'>
          .BAR
        </div>
      </div>
      <% end %>

Checkbox Check Event Listener

Short answer: Use the change event. Here's a couple of practical examples. Since I misread the question, I'll include jQuery examples along with plain JavaScript. You're not gaining much, if anything, by using jQuery though.

Single checkbox

Using querySelector.

_x000D_
_x000D_
var checkbox = document.querySelector("input[name=checkbox]");

checkbox.addEventListener('change', function() {
  if (this.checked) {
    console.log("Checkbox is checked..");
  } else {
    console.log("Checkbox is not checked..");
  }
});
_x000D_
<input type="checkbox" name="checkbox" />
_x000D_
_x000D_
_x000D_

Single checkbox with jQuery

_x000D_
_x000D_
$('input[name=checkbox]').change(function() {
  if ($(this).is(':checked')) {
    console.log("Checkbox is checked..")
  } else {
    console.log("Checkbox is not checked..")
  }
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input type="checkbox" name="checkbox" />
_x000D_
_x000D_
_x000D_

Multiple checkboxes

Here's an example of a list of checkboxes. To select multiple elements we use querySelectorAll instead of querySelector. Then use Array.filter and Array.map to extract checked values.

_x000D_
_x000D_
// Select all checkboxes with the name 'settings' using querySelectorAll.
var checkboxes = document.querySelectorAll("input[type=checkbox][name=settings]");
let enabledSettings = []

/*
For IE11 support, replace arrow functions with normal functions and
use a polyfill for Array.forEach:
https://vanillajstoolkit.com/polyfills/arrayforeach/
*/

// Use Array.forEach to add an event listener to each checkbox.
checkboxes.forEach(function(checkbox) {
  checkbox.addEventListener('change', function() {
    enabledSettings = 
      Array.from(checkboxes) // Convert checkboxes to an array to use filter and map.
      .filter(i => i.checked) // Use Array.filter to remove unchecked checkboxes.
      .map(i => i.value) // Use Array.map to extract only the checkbox values from the array of objects.
      
    console.log(enabledSettings)
  })
});
_x000D_
<label>
   <input type="checkbox" name="settings" value="forcefield">
   Enable forcefield
</label>
<label>
  <input type="checkbox" name="settings" value="invisibilitycloak">
  Enable invisibility cloak
</label>
<label>
  <input type="checkbox" name="settings" value="warpspeed">
  Enable warp speed
</label>
_x000D_
_x000D_
_x000D_

Multiple checkboxes with jQuery

_x000D_
_x000D_
let checkboxes = $("input[type=checkbox][name=settings]")
let enabledSettings = [];

// Attach a change event handler to the checkboxes.
checkboxes.change(function() {
  enabledSettings = checkboxes
    .filter(":checked") // Filter out unchecked boxes.
    .map(function() { // Extract values using jQuery map.
      return this.value;
    }) 
    .get() // Get array.
    
  console.log(enabledSettings);
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label>
   <input type="checkbox" name="settings" value="forcefield">
   Enable forcefield
</label>
<label>
  <input type="checkbox" name="settings" value="invisibilitycloak">
  Enable invisibility cloak
</label>
<label>
  <input type="checkbox" name="settings" value="warpspeed">
  Enable warp speed
</label>
_x000D_
_x000D_
_x000D_

What is the simplest method of inter-process communication between 2 C# processes?

Anonymous pipes.

Use Asynchronous operations with BeginRead/BeginWrite and AsyncCallback.

Go to next item in ForEach-Object

You may want to use the Continue statement to continue with the innermost loop.

Excerpt from PowerShell help file:

In a script, the continue statement causes program flow to move immediately to the top of the innermost loop controlled by any of these statements:

  • for
  • foreach
  • while

Tesseract running error

I'm using windows OS, I tried all solutions above and none of them work.

Finally, I install Tesseract-OCR on D drive(Where I run my python script from) instead of C drive and it works.

So, if you are using windows, run your python script in the same drive as your Tesseract-OCR.

Formatting doubles for output in C#

i tried to reproduce your findings, but when I watched 'i' in the debugger it showed up as '6.8999999999999995' not as '6.89999999999999946709' as you wrote in the question. Can you provide steps to reproduce what you saw?

To see what the debugger shows you, you can use a DoubleConverter as in the following line of code:

Console.WriteLine(TypeDescriptor.GetConverter(i).ConvertTo(i, typeof(string)));

Hope this helps!

Edit: I guess I'm more tired than I thought, of course this is the same as formatting to the roundtrip value (as mentioned before).

Access images inside public folder in laravel

If you are inside a blade template

{{ URL::to('/') }}/images/stackoverflow.png

How to prevent Browser cache for php site

You can try this:

    header("Expires: Tue, 03 Jul 2001 06:00:00 GMT");
    header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
    header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
    header("Cache-Control: post-check=0, pre-check=0", false);
    header("Pragma: no-cache");
    header("Connection: close");

Hopefully it will help prevent Cache, if any!

Pointer vs. Reference

Use a reference when you can, use a pointer when you have to. From C++ FAQ: "When should I use references, and when should I use pointers?"

How to send/receive SOAP request and response using C#?

The urls are different.

  • http://localhost/AccountSvc/DataInquiry.asmx

vs.

  • /acctinqsvc/portfolioinquiry.asmx

Resolve this issue first, as if the web server cannot resolve the URL you are attempting to POST to, you won't even begin to process the actions described by your request.

You should only need to create the WebRequest to the ASMX root URL, ie: http://localhost/AccountSvc/DataInquiry.asmx, and specify the desired method/operation in the SOAPAction header.

The SOAPAction header values are different.

  • http://localhost/AccountSvc/DataInquiry.asmx/ + methodName

vs.

  • http://tempuri.org/GetMyName

You should be able to determine the correct SOAPAction by going to the correct ASMX URL and appending ?wsdl

There should be a <soap:operation> tag underneath the <wsdl:operation> tag that matches the operation you are attempting to execute, which appears to be GetMyName.

There is no XML declaration in the request body that includes your SOAP XML.

You specify text/xml in the ContentType of your HttpRequest and no charset. Perhaps these default to us-ascii, but there's no telling if you aren't specifying them!

The SoapUI created XML includes an XML declaration that specifies an encoding of utf-8, which also matches the Content-Type provided to the HTTP request which is: text/xml; charset=utf-8

Hope that helps!

How do I check if a string is a number (float)?

User helper function:

def if_ok(fn, string):
  try:
    return fn(string)
  except Exception as e:
    return None

then

if_ok(int, my_str) or if_ok(float, my_str) or if_ok(complex, my_str)
is_number = lambda s: any([if_ok(fn, s) for fn in (int, float, complex)])

_DEBUG vs NDEBUG

Is NDEBUG standard?

Yes it is a standard macro with the semantic "Not Debug" for C89, C99, C++98, C++2003, C++2011, C++2014 standards. There are no _DEBUG macros in the standards.

C++2003 standard send the reader at "page 326" at "17.4.2.1 Headers" to standard C.

That NDEBUG is similar as This is the same as the Standard C library.

In C89 (C programmers called this standard as standard C) in "4.2 DIAGNOSTICS" section it was said

http://port70.net/~nsz/c/c89/c89-draft.html

If NDEBUG is defined as a macro name at the point in the source file where is included, the assert macro is defined simply as

     #define assert(ignore) ((void)0)

If look at the meaning of _DEBUG macros in Visual Studio https://msdn.microsoft.com/en-us/library/b0084kay.aspx then it will be seen, that this macro is automatically defined by your ?hoice of language runtime library version.

int to unsigned int conversion

Since we know that i is an int, you can just go ahead and unsigneding it!

This would do the trick:

int i = -62;
unsigned int j = unsigned(i);

CSS disable text selection

instead of body type a list of elements you want.

Can a foreign key be NULL and/or duplicate?

From the horse's mouth:

Foreign keys allow key values that are all NULL, even if there are no matching PRIMARY or UNIQUE keys

No Constraints on the Foreign Key

When no other constraints are defined on the foreign key, any number of rows in the child table can reference the same parent key value. This model allows nulls in the foreign key. ...

NOT NULL Constraint on the Foreign Key

When nulls are not allowed in a foreign key, each row in the child table must explicitly reference a value in the parent key because nulls are not allowed in the foreign key.

Any number of rows in the child table can reference the same parent key value, so this model establishes a one-to-many relationship between the parent and foreign keys. However, each row in the child table must have a reference to a parent key value; the absence of a value (a null) in the foreign key is not allowed. The same example in the previous section can be used to illustrate such a relationship. However, in this case, employees must have a reference to a specific department.

UNIQUE Constraint on the Foreign Key

When a UNIQUE constraint is defined on the foreign key, only one row in the child table can reference a given parent key value. This model allows nulls in the foreign key.

This model establishes a one-to-one relationship between the parent and foreign keys that allows undetermined values (nulls) in the foreign key. For example, assume that the employee table had a column named MEMBERNO, referring to an employee membership number in the company insurance plan. Also, a table named INSURANCE has a primary key named MEMBERNO, and other columns of the table keep respective information relating to an employee insurance policy. The MEMBERNO in the employee table must be both a foreign key and a unique key:

  • To enforce referential integrity rules between the EMP_TAB and INSURANCE tables (the FOREIGN KEY constraint)

  • To guarantee that each employee has a unique membership number (the UNIQUE key constraint)

UNIQUE and NOT NULL Constraints on the Foreign Key

When both UNIQUE and NOT NULL constraints are defined on the foreign key, only one row in the child table can reference a given parent key value, and because NULL values are not allowed in the foreign key, each row in the child table must explicitly reference a value in the parent key.

See this:

Oracle 11g link

How to export data with Oracle SQL Developer?

In version 3, they changed "export" to "unload". It still functions more or less the same.

How to list records with date from the last 10 days?

http://www.postgresql.org/docs/current/static/functions-datetime.html shows operators you can use for working with dates and times (and intervals).

So you want

SELECT "date"
FROM "Table"
WHERE "date" > (CURRENT_DATE - INTERVAL '10 days');

The operators/functions above are documented in detail:

is there a css hack for safari only NOT chrome?

This hack 100% work only for safari 5.1-6.0. I've just tested it with success.

@media only screen and (-webkit-min-device-pixel-ratio: 1) {
     ::i-block-chrome, .yourcssrule {
        your css property
    }
}

input[type='text'] CSS selector does not apply to default-type text inputs?

try this

 input[type='text']
 {
   background:red !important;
 }

MySQL Check if username and password matches in Database

1.) Storage of database passwords Use some kind of hash with a salt and then alter the hash, obfuscate it, for example add a distinct value for each byte. That way your passwords a super secured against dictionary attacks and rainbow tables.

2.) To check if the password matches, create your hash for the password the user put in. Then perform a query against the database for the username and just check if the two password hashes are identical. If they are, give the user an authentication token.

The query should then look like this:

select hashedPassword from users where username=?

Then compare the password to the input.

Further questions?

Nginx Different Domains on Same IP

Your "listen" directives are wrong. See this page: http://nginx.org/en/docs/http/server_names.html.

They should be

server {
    listen      80;
    server_name www.domain1.com;
    root /var/www/domain1;
}

server {
    listen       80;
    server_name www.domain2.com;
    root /var/www/domain2;
}

Note, I have only included the relevant lines. Everything else looked okay but I just deleted it for clarity. To test it you might want to try serving a text file from each server first before actually serving php. That's why I left the 'root' directive in there.

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

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

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

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

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

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

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

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

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

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

Build Eclipse Java Project from Command Line

Hi Just addition to VonC comments. I am using ecj compiler to compile my project. it was throwing expcetion that some of the classes are not found. But the project was bulding fine with javac compiler.

So just I added the classes into the classpath(which we have to pass as argument) and now its working fine... :)

Kulbir Singh

Python class inherits object

Python 3

  • class MyClass(object): = New-style class
  • class MyClass: = New-style class (implicitly inherits from object)

Python 2

  • class MyClass(object): = New-style class
  • class MyClass: = OLD-STYLE CLASS

Explanation:

When defining base classes in Python 3.x, you’re allowed to drop the object from the definition. However, this can open the door for a seriously hard to track problem…

Python introduced new-style classes back in Python 2.2, and by now old-style classes are really quite old. Discussion of old-style classes is buried in the 2.x docs, and non-existent in the 3.x docs.

The problem is, the syntax for old-style classes in Python 2.x is the same as the alternative syntax for new-style classes in Python 3.x. Python 2.x is still very widely used (e.g. GAE, Web2Py), and any code (or coder) unwittingly bringing 3.x-style class definitions into 2.x code is going to end up with some seriously outdated base objects. And because old-style classes aren’t on anyone’s radar, they likely won’t know what hit them.

So just spell it out the long way and save some 2.x developer the tears.

Get checkbox value in jQuery

Best way is $('input[name="line"]:checked').val()

And also you can get selected text $('input[name="line"]:checked').text()

Add value attribute and name to your radio button inputs. Make sure all inputs have same name attribute.

<div class="col-8 m-radio-inline">
    <label class="m-radio m-radio-filter">
        <input type="radio" name="line" value="1" checked> Value Text 1
    </label>
    <label class="m-radio m-radio-filter">
        <input type="radio" name="line" value="2"> Value Text 2
    </label>
    <label class="m-radio m-radio-filter">
        <input type="radio" name="line" value="3"> Value Text 3
    </label>
</div>

Active Directory LDAP Query by sAMAccountName and Domain

The best way of searching for users is (sAMAccountType=805306368).

Or for disabled users:

(&(sAMAccountType=805306368)(userAccountControl:1.2.840.113556.1.4.803:=2))

Or for active users:

(&(sAMAccountType=805306368)(!(userAccountControl:1.2.840.113556.1.4.803:=2)))

I find LDAP as not being so light at it was supposed to be.

Also resource for common LDAP queries - trying to find them yourself and you will precious time and definitely make mistakes.

Regarding domains: it not possible in a single query because the domain is part of the user distinguisedName (DN) which, on Microsoft AD, is not searchable by partial matching.

How can I fill a column with random numbers in SQL? I get the same value in every row

require_once('db/connect.php');

//rand(1000000 , 9999999);

$products_query = "SELECT id FROM products";
$products_result = mysqli_query($conn, $products_query);
$products_row = mysqli_fetch_array($products_result);
$ids_array = [];

do
{
    array_push($ids_array, $products_row['id']);
}
while($products_row = mysqli_fetch_array($products_result));

/*
echo '<pre>';
print_r($ids_array);
echo '</pre>';
*/
$row_counter = count($ids_array);

for ($i=0; $i < $row_counter; $i++)
{ 
    $current_row = $ids_array[$i];
    $rand = rand(1000000 , 9999999);
    mysqli_query($conn , "UPDATE products SET code='$rand' WHERE id='$current_row'");
}

In Typescript, what is the ! (exclamation mark / bang) operator when dereferencing a member?

Louis' answer is great, but I thought I would try to sum it up succinctly:

The bang operator tells the compiler to temporarily relax the "not null" constraint that it might otherwise demand. It says to the compiler: "As the developer, I know better than you that this variable cannot be null right now".

NuGet behind a proxy

Just a small addition...

If it works for you to only supply the http_proxy setting and not username and password I'd recommend putting the proxy settings in a project local nuget.config file and commit it to source control. That way all team members get the same settings.

Create an empty .\nuget.config

   <?xml version="1.0" encoding="utf-8"?>
   <configuration>
   </configuration>

Then:

   nuget config -Set http_proxy="http://myproxy.example.com:8080" -ConfigFile .\Nuget.Config

And finally commit your new project local Nuget.config file.

Can I target all <H> tags with a single selector?

SCSS+Compass makes this a snap, since we're talking about pre-processors.

#{headings(1,5)} {
    //definitions
  }

You can learn about all the Compass helper selectors here:

Split string in Lua?

If you program in Lua, you are out of luck here. Lua is THE one programming language that just happens to be notoriously infamous because its authors never implemented "the" split function in the standard library, and instead wrote 16 screenfulls of explanations and lame excuses as to why they didn't and wouldn't, interspersed with numerous half-working examples that are virtually guaranteed to work for almost everyone but break in your corner case. This is just Lua state of the art, and everyone who programs in Lua simply ends up clenching their teeth and iterating over characters. There are lots of solutions in existence that are sometimes better, but exactly zero solutions that are reliably better.

error LNK2005: xxx already defined in MSVCRT.lib(MSVCR100.dll) C:\something\LIBCMT.lib(setlocal.obj)

If you VS solution contains several projects, select all of them in the right pane, and press "properties". Then go to C++ -> Code Generation and chose one Run Time library option for all of them

Compile throws a "User-defined type not defined" error but does not go to the offending line of code

Just letting you all know I had this problem too. Rather than the code, the issue lay with what macro a button was calling. (It had been calling the 'createroutes.createroutes' macro, but I had renamed the 'createroutes' module to 'routes'.) Therefore the problem was fixed by pointing the button to the correct location.

Set NOW() as Default Value for datetime datatype?

mysql 5.6 docs say that CURRENT_TIMESTAMP can be used as default for both TIMESTAMP and DATETIME data types:

http://dev.mysql.com/doc/refman/5.6/en/timestamp-initialization.html

"SyntaxError: Unexpected token < in JSON at position 0"

This ended up being a permissions problem for me. I was trying to access a url I didn't have authorization for with cancan, so the url was switched to users/sign_in. the redirected url responds to html, not json. The first character in a html response is <.

Project Links do not work on Wamp Server

Navigate to your www directory (if you are using wamp server) htdocs (if on XAMPP). Open your admin.php and search on project contents/ or just go directly to line number 339 and change the link, inserting 'local host to the link .

That should work ,,

Creating a select box with a search option

Here's a handy open source library I made earlier that uses jQuery: https://bitbucket.org/warwick/searchablelist/src/master/ And here is a working copy on my VPS: http://developersfound.com/SearchableList/ The library is highly customisable with overridable behavours and can have seperate designs on the same web page Hope this helps

Password encryption at client side

This sort of protection is normally provided by using HTTPS, so that all communication between the web server and the client is encrypted.

The exact instructions on how to achieve this will depend on your web server.

The Apache documentation has a SSL Configuration HOW-TO guide that may be of some help. (thanks to user G. Qyy for the link)

How to make Toolbar transparent?

Only this worked for me (AndroidX support library):

 <com.google.android.material.appbar.AppBarLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@null"
            android:theme="@style/AppTheme.AppBarOverlay"
            android:translationZ="0.1dp"
            app:elevation="0dp">

            <androidx.appcompat.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                android:background="@null"
                app:popupTheme="@style/AppTheme.PopupOverlay" />

        </com.google.android.material.appbar.AppBarLayout>

This code removes background in all necessary views and also removes shadow from AppBarLayout (which was a problem)

Answer was found here: remove shadow below AppBarLayout widget android

Catch an exception thrown by an async void method

The reason the exception is not caught is because the Foo() method has a void return type and so when await is called, it simply returns. As DoFoo() is not awaiting the completion of Foo, the exception handler cannot be used.

This opens up a simpler solution if you can change the method signatures - alter Foo() so that it returns type Task and then DoFoo() can await Foo(), as in this code:

public async Task Foo() {
    var x = await DoSomethingThatThrows();
}

public async void DoFoo() {
    try {
        await Foo();
    } catch (ProtocolException ex) {
        // This will catch exceptions from DoSomethingThatThrows
    }
}

How do I multiply each element in a list by a number?

I found it interesting to use list comprehension or map with just one object name x. Note that whenever x is reassigned, its id(x) changes, i.e. points to a different object.

x = [1, 2, 3]
id(x)
2707834975552
x = [1.5 * x for x in x]
id(x)
2707834976576
x
[1.5, 3.0, 4.5]
list(map(lambda x : 2 * x / 3, x))
[1.0, 2.0, 3.0]
id(x) # not reassigned
2707834976576
x = list(map(lambda x : 2 * x / 3, x))
x
[1.0, 2.0, 3.0]
id(x)
2707834980928

.NET - Get protocol, host, and port

The following (C#) code should do the trick

Uri uri = new Uri("http://www.mywebsite.com:80/pages/page1.aspx");
string requested = uri.Scheme + Uri.SchemeDelimiter + uri.Host + ":" + uri.Port;

How to get the last five characters of a string using Substring() in C#?

// Get first three characters
string sub = input.Substring(0, 3);
Console.WriteLine("Substring: {0}", sub); // Output One. 

string sub = input.Substring(6, 5);
Console.WriteLine("Substring: {0}", sub); //You'll get output: Three

ExecJS and could not find a JavaScript runtime

Attempting to debug in RubyMine using Ubuntu 18.04, Ruby 2.6.*, Rails 5, & RubyMine 2019.1.1, I ran into the same issue.

To resolve the issue, I uncommented the mini_racer line from my Gemfile and then ran bundle:

# See https://github.com/rails/execjs#readme for more supported runtimes
# gem 'mini_racer', platforms: :ruby

Change to:

# See https://github.com/rails/execjs#readme for more supported runtimes
gem 'mini_racer', platforms: :ruby

Find the most popular element in int[] array

public int getPopularElement(int[] a)
{
  int count = 1, tempCount;
  int popular = a[0];
  int temp = 0;
  for (int i = 0; i < (a.length - 1); i++)
  {
    temp = a[i];
    tempCount = 0;
    for (int j = 1; j < a.length; j++)
    {
      if (temp == a[j])
        tempCount++;
    }
    if (tempCount > count)
    {
      popular = temp;
      count = tempCount;
    }
  }
  return popular;
}

Error in model.frame.default: variable lengths differ

Its simple, just make sure the data type in your columns are the same. For e.g. I faced the same error, that and an another error:

Error in contrasts<-(*tmp*, value = contr.funs[1 + isOF[nn]]) : contrasts can be applied only to factors with 2 or more levels

So, I went back to my excel file or csv file, set a filter on the variable throwing me an error and checked if the distinct datatypes are the same. And... Oh! it had numbers and strings, so I converted numbers to string and it worked just fine for me.

Make div 100% Width of Browser Window

.myDiv {
    background-color: red;
    width: 100%;
    min-height: 100vh;
    max-height: 100%;
    position: absolute;
    top: 0;
    left: 0;
    margin: 0 auto;
}

Basically, we're fixing the div's position regardless of it's parent, and then position it using margin: 0 auto; and settings its position at the top left corner.

HTML: Select multiple as dropdown

It's quite unpractical to make multiple select with size 1. think about it. I made a fiddle here: https://jsfiddle.net/wqd0yd5m/2/

<select name="test" multiple>
    <option>123</option>
    <option>456</option>
    <option>789</option>
</select>

Try to explore other options such as using checkboxes to achieve your goal.

Get device token for push notification

Objective C for iOS 13+, courtesy of Wasif Saood's answer

Copy and paste below code into AppDelegate.m to print the device APN token.

- (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
  NSUInteger dataLength = deviceToken.length;
  if (dataLength == 0) {
    return;
  }
  const unsigned char *dataBuffer = (const unsigned char *)deviceToken.bytes;
  NSMutableString *hexString  = [NSMutableString stringWithCapacity:(dataLength * 2)];
  for (int i = 0; i < dataLength; ++i) {
    [hexString appendFormat:@"%02x", dataBuffer[i]];
  }
  NSLog(@"APN token:%@", hexString);
}

Get a JSON object from a HTTP response

This is not the exact answer for your question, but this may help you

public class JsonParser {

    private static DefaultHttpClient httpClient = ConnectionManager.getClient();

    public static List<Club> getNearestClubs(double lat, double lon) {
        // YOUR URL GOES HERE
        String getUrl = Constants.BASE_URL + String.format("getClosestClubs?lat=%f&lon=%f", lat, lon);

        List<Club> ret = new ArrayList<Club>();

        HttpResponse response = null;
        HttpGet getMethod = new HttpGet(getUrl);
        try {
            response = httpClient.execute(getMethod);

            // CONVERT RESPONSE TO STRING
            String result = EntityUtils.toString(response.getEntity());

            // CONVERT RESPONSE STRING TO JSON ARRAY
            JSONArray ja = new JSONArray(result);

            // ITERATE THROUGH AND RETRIEVE CLUB FIELDS
            int n = ja.length();
            for (int i = 0; i < n; i++) {
                // GET INDIVIDUAL JSON OBJECT FROM JSON ARRAY
                JSONObject jo = ja.getJSONObject(i);

                // RETRIEVE EACH JSON OBJECT'S FIELDS
                long id = jo.getLong("id");
                String name = jo.getString("name");
                String address = jo.getString("address");
                String country = jo.getString("country");
                String zip = jo.getString("zip");
                double clat = jo.getDouble("lat");
                double clon = jo.getDouble("lon");
                String url = jo.getString("url");
                String number = jo.getString("number");

                // CONVERT DATA FIELDS TO CLUB OBJECT
                Club c = new Club(id, name, address, country, zip, clat, clon, url, number);
                ret.add(c);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        // RETURN LIST OF CLUBS
        return ret;
    }

}
Again, it’s relatively straight forward, but the methods I’ll make special note of are:

JSONArray ja = new JSONArray(result);
JSONObject jo = ja.getJSONObject(i);
long id = jo.getLong("id");
String name = jo.getString("name");
double clat = jo.getDouble("lat");

Overloading operators in typedef structs (c++)

Instead of typedef struct { ... } pos; you should be doing struct pos { ... };. The issue here is that you are using the pos type name before it is defined. By moving the name to the top of the struct definition, you are able to use that name within the struct definition itself.

Further, the typedef struct { ... } name; pattern is a C-ism, and doesn't have much place in C++.

To answer your question about inline, there is no difference in this case. When a method is defined within the struct/class definition, it is implicitly declared inline. When you explicitly specify inline, the compiler effectively ignores it because the method is already declared inline.

(inline methods will not trigger a linker error if the same method is defined in multiple object files; the linker will simply ignore all but one of them, assuming that they are all the same implementation. This is the only guaranteed change in behavior with inline methods. Nowadays, they do not affect the compiler's decision regarding whether or not to inline functions; they simply facilitate making the function implementation available in all translation units, which gives the compiler the option to inline the function, if it decides it would be beneficial to do so.)

How to plot two columns of a pandas data frame using points?

For this (and most plotting) I would not rely on the Pandas wrappers to matplotlib. Instead, just use matplotlib directly:

import matplotlib.pyplot as plt
plt.scatter(df['col_name_1'], df['col_name_2'])
plt.show() # Depending on whether you use IPython or interactive mode, etc.

and remember that you can access a NumPy array of the column's values with df.col_name_1.values for example.

I ran into trouble using this with Pandas default plotting in the case of a column of Timestamp values with millisecond precision. In trying to convert the objects to datetime64 type, I also discovered a nasty issue: < Pandas gives incorrect result when asking if Timestamp column values have attr astype >.

DB2 SQL error sqlcode=-104 sqlstate=42601

You miss the from clause

SELECT *  from TCCAWZTXD.TCC_COIL_DEMODATA WHERE CURRENT_INSERTTIME  BETWEEN(CURRENT_TIMESTAMP)-5 minutes AND CURRENT_TIMESTAMP

Localhost not working in chrome and firefox

Finally I found the solution ... It's very easy

  1. Go to the LAN settings (In Chrome : Tools -> Options -> Under the hood -> Change Proxy setting -> LAN Setting)

  2. There will be a checkbox for "Bypass proxy server for local address"

  3. Tick the checkbox.

Done!

On Mac/Apple: Chrome uses system preferences for localhost exclusion:

  1. Go to System Preferences -> Network -> advanced -> Proxy settings

  2. Add 'localhost' at the bottom where it says: 'ignore proxy settings for these hosts and domains' (Exceptions are separated by a comma)

How to add a char/int to an char array in C?

I think you've forgotten initialize your string "str": You need initialize the string before using strcat. And also you need that tmp were a string, not a single char. Try change this:

char str[1024]; // Only declares size
char tmp = '.';

for

char str[1024] = "Hello World";  //Now you have "Hello World" in str
char tmp[2] = ".";

Convert js Array() to JSon object for use with JQuery .ajax

You can iterate the key/value pairs of the saveData object to build an array of the pairs, then use join("&") on the resulting array:

var a = [];
for (key in saveData) {
    a.push(key+"="+saveData[key]);
}
var serialized = a.join("&") // a=2&c=1

Unable to ping vmware guest from another vmware guest

enter image description here

I came to the same problem and tried all methods on internet, and finally worked it out by accident. May you could try this(see in the picture)

Execute PHP function with onclick

It can be done and with rather simple php if this is your button

<input type="submit" name="submit>

and this is your php code

if(isset($_POST["submit"])) { php code here }

the code get's called when submit get's posted which happens when the button is clicked.

What are the special dollar sign shell variables?

  • $_ last argument of last command
  • $# number of arguments passed to current script
  • $* / $@ list of arguments passed to script as string / delimited list

off the top of my head. Google for bash special variables.

Select method of Range class failed via VBA

Here is a solution worked for me and also, I found all of the above solutions are correct. My excel model got corrupted and which is why my code (similar to this one) stopped working. Here is what worked for me and is working every time-

  1. Calculate the workbook- Formulas->Calculate Now (under calculation section)
  2. Save the workbook
  3. Close and re-open the file. It was fixed and works every time.

add scroll bar to table body

If you don't want to wrap a table under any div:

table{
  table-layout: fixed;
}
tbody{
      display: block;
    overflow: auto;
}

C# difference between == and Equals()

Just as an addition to the already good answers: This behaviour is NOT limited to Strings or comparing different numbertypes. Even if both elements are of type object of the same underlying type. "==" won't work.

The following screenshot shows the results of comparing two object {int} - values

Example From VS2017

bootstrap.min.js:6 Uncaught Error: Bootstrap dropdown require Popper.js

In my case I am using Visual Studio and Nuget packages its failing because have duplicated libraries one in the same folder as jQuery and another in the folder umd. By removing the popper javascript files from the same level as jQuery and refere to the popper.js inside the umd folder fixed my issue and I can see the tooltips correctly.

How does the "view" method work in PyTorch?

torch.Tensor.view()

Simply put, torch.Tensor.view() which is inspired by numpy.ndarray.reshape() or numpy.reshape(), creates a new view of the tensor, as long as the new shape is compatible with the shape of the original tensor.

Let's understand this in detail using a concrete example.

In [43]: t = torch.arange(18) 

In [44]: t 
Out[44]: 
tensor([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17])

With this tensor t of shape (18,), new views can only be created for the following shapes:

(1, 18) or equivalently (1, -1) or (-1, 18)
(2, 9) or equivalently (2, -1) or (-1, 9)
(3, 6) or equivalently (3, -1) or (-1, 6)
(6, 3) or equivalently (6, -1) or (-1, 3)
(9, 2) or equivalently (9, -1) or (-1, 2)
(18, 1) or equivalently (18, -1) or (-1, 1)

As we can already observe from the above shape tuples, the multiplication of the elements of the shape tuple (e.g. 2*9, 3*6 etc.) must always be equal to the total number of elements in the original tensor (18 in our example).

Another thing to observe is that we used a -1 in one of the places in each of the shape tuples. By using a -1, we are being lazy in doing the computation ourselves and rather delegate the task to PyTorch to do calculation of that value for the shape when it creates the new view. One important thing to note is that we can only use a single -1 in the shape tuple. The remaining values should be explicitly supplied by us. Else PyTorch will complain by throwing a RuntimeError:

RuntimeError: only one dimension can be inferred

So, with all of the above mentioned shapes, PyTorch will always return a new view of the original tensor t. This basically means that it just changes the stride information of the tensor for each of the new views that are requested.

Below are some examples illustrating how the strides of the tensors are changed with each new view.

# stride of our original tensor `t`
In [53]: t.stride() 
Out[53]: (1,)

Now, we will see the strides for the new views:

# shape (1, 18)
In [54]: t1 = t.view(1, -1)
# stride tensor `t1` with shape (1, 18)
In [55]: t1.stride() 
Out[55]: (18, 1)

# shape (2, 9)
In [56]: t2 = t.view(2, -1)
# stride of tensor `t2` with shape (2, 9)
In [57]: t2.stride()       
Out[57]: (9, 1)

# shape (3, 6)
In [59]: t3 = t.view(3, -1) 
# stride of tensor `t3` with shape (3, 6)
In [60]: t3.stride() 
Out[60]: (6, 1)

# shape (6, 3)
In [62]: t4 = t.view(6,-1)
# stride of tensor `t4` with shape (6, 3)
In [63]: t4.stride() 
Out[63]: (3, 1)

# shape (9, 2)
In [65]: t5 = t.view(9, -1) 
# stride of tensor `t5` with shape (9, 2)
In [66]: t5.stride()
Out[66]: (2, 1)

# shape (18, 1)
In [68]: t6 = t.view(18, -1)
# stride of tensor `t6` with shape (18, 1)
In [69]: t6.stride()
Out[69]: (1, 1)

So that's the magic of the view() function. It just changes the strides of the (original) tensor for each of the new views, as long as the shape of the new view is compatible with the original shape.

Another interesting thing one might observe from the strides tuples is that the value of the element in the 0th position is equal to the value of the element in the 1st position of the shape tuple.

In [74]: t3.shape 
Out[74]: torch.Size([3, 6])
                        |
In [75]: t3.stride()    |
Out[75]: (6, 1)         |
          |_____________|

This is because:

In [76]: t3 
Out[76]: 
tensor([[ 0,  1,  2,  3,  4,  5],
        [ 6,  7,  8,  9, 10, 11],
        [12, 13, 14, 15, 16, 17]])

the stride (6, 1) says that to go from one element to the next element along the 0th dimension, we have to jump or take 6 steps. (i.e. to go from 0 to 6, one has to take 6 steps.) But to go from one element to the next element in the 1st dimension, we just need only one step (for e.g. to go from 2 to 3).

Thus, the strides information is at the heart of how the elements are accessed from memory for performing the computation.


torch.reshape()

This function would return a view and is exactly the same as using torch.Tensor.view() as long as the new shape is compatible with the shape of the original tensor. Otherwise, it will return a copy.

However, the notes of torch.reshape() warns that:

contiguous inputs and inputs with compatible strides can be reshaped without copying, but one should not depend on the copying vs. viewing behavior.

Android checkbox style

The correct way to do it for Material design is :

Style :

<style name="MyCheckBox" parent="Theme.AppCompat.Light">  
    <item name="colorControlNormal">@color/foo</item>
    <item name="colorControlActivated">@color/bar</item>
</style>  

Layout :

<CheckBox  
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:checked="true"
    android:text="Check Box"
    android:theme="@style/MyCheckBox"/>

It will preserve Material animations on Lollipop+.

Read a Csv file with powershell and capture corresponding data

So I figured out what is wrong with this statement:

Import-Csv H:\Programs\scripts\SomeText.csv |`

(Original)

Import-Csv H:\Programs\scripts\SomeText.csv -Delimiter "|"

(Proposed, You must use quotations; otherwise, it will not work and ISE will give you an error)

It requires the -Delimiter "|", in order for the variable to be populated with an array of items. Otherwise, Powershell ISE does not display the list of items.

I cannot say that I would recommend the | operator, since it is used to pipe cmdlets into one another.

I still cannot get the if statement to return true and output the values entered via the prompt.

If anyone else can help, it would be great. I still appreciate the post, it has been very helpful!

Scala check if element is present in a list

Even easier!

strings contains myString

In reactJS, how to copy text to clipboard?

For those people who are trying to select from the DIV instead of the text field, here is the code. The code is self-explanatory but comment here if you want more information:

     import React from 'react';
     ....

    //set ref to your div
          setRef = (ref) => {
            // debugger; //eslint-disable-line
            this.dialogRef = ref;
          };

          createMarkeup = content => ({
            __html: content,
          });

    //following function select and copy data to the clipboard from the selected Div. 
   //Please note that it is only tested in chrome but compatibility for other browsers can be easily done

          copyDataToClipboard = () => {
            try {
              const range = document.createRange();
              const selection = window.getSelection();
              range.selectNodeContents(this.dialogRef);
              selection.removeAllRanges();
              selection.addRange(range);
              document.execCommand('copy');
              this.showNotification('Macro copied successfully.', 'info');
              this.props.closeMacroWindow();
            } catch (err) {
              // console.log(err); //eslint-disable-line
              //alert('Macro copy failed.');
            }
          };

              render() {
                    return (
                        <div
                          id="macroDiv"
                          ref={(el) => {
                            this.dialogRef = el;
                          }}
                          // className={classes.paper}
                          dangerouslySetInnerHTML={this.createMarkeup(this.props.content)}
                        />
                    );
            }

Can you install and run apps built on the .NET framework on a Mac?

.NetCore is a fine release from Microsoft and Visual Studio's latest version is also available for mac but there is still some limitation. Like for creating GUI based application on .net core you have to write code manually for everything. Like in older version of VS we just drag and drop the things and magic happens. But in VS latest version for mac every code has to be written manually. However you can make web application and console application easily on VS for mac.

How to use BufferedReader in Java

As far as i understand fr is the object of your FileReadExample class. So it is obvious it will not have any method like fr.readLine() if you dont create one yourself.

secondly, i think a correct constructor of the BufferedReader class will help you do your task.

String str;
BufferedReader buffread = new BufferedReader(new FileReader(new File("file.dat")));
str = buffread.readLine();
.
.
buffread.close();

this should help you.

When you use 'badidea' or 'thisisunsafe' to bypass a Chrome certificate/HSTS error, does it only apply for the current site?

The SSL errors are often thrown by network management software such as Cyberroam.

To answer your question,

you will have to enter badidea into Chrome every time you visit a website.

You might at times have to enter it more than once, as the site may try to pull in various resources before load, hence causing multiple SSL errors

How to restrict user to type 10 digit numbers in input element?

  <input type="text" name='mobile_number' pattern=[0-9]{1}[0-9]{9}>

Batch file to split .csv file

I found this question while looking for a similar solution. I modified the answer that @Dale gave to suit my purposes. I wanted something that was a little more flexible and had some error trapping. Just thought I might put it here for anyone looking for the same thing.

@echo off
setLocal EnableDelayedExpansion
GOTO checkvars

:checkvars
    IF "%1"=="" GOTO syntaxerror
    IF NOT "%1"=="-f"  GOTO syntaxerror
    IF %2=="" GOTO syntaxerror
    IF NOT EXIST %2 GOTO nofile
    IF "%3"=="" GOTO syntaxerror
    IF NOT "%3"=="-n" GOTO syntaxerror
    IF "%4"==""  GOTO syntaxerror
    set param=%4
    echo %param%| findstr /xr "[1-9][0-9]* 0" >nul && (
        goto proceed
    ) || (
        echo %param% is NOT a valid number
        goto syntaxerror
    )

:proceed
    set limit=%4
    set file=%2
    set lineCounter=1+%limit%
    set filenameCounter=0

    set name=
    set extension=

    for %%a in (%file%) do (
        set "name=%%~na"
        set "extension=%%~xa"
    )

    for /f "usebackq tokens=*" %%a in (%file%) do (
        if !lineCounter! gtr !limit! (
            set splitFile=!name!_part!filenameCounter!!extension!
            set /a filenameCounter=!filenameCounter! + 1
            set lineCounter=1
            echo Created !splitFile!.
        )
        cls
        echo Adding Line !splitFile! - !lineCounter!
        echo %%a>> !splitFile!
        set /a lineCounter=!lineCounter! + 1
    )
    echo Done!
    goto end
:syntaxerror
    Echo Syntax: %0 -f Filename -n "Number Of Rows Per File"
    goto end
:nofile
    echo %2 does not exist
    goto end
:end

Regex replace (in Python) - a simpler way?

I believe that the best idea is just to capture in a group whatever you want to replace, and then replace it by using the start and end properties of the captured group.

regards

Adrián

#the pattern will contain the expression we want to replace as the first group
pat = "word1\s(.*)\sword2"   
test = "word1 will never be a word2"
repl = "replace"

import re
m = re.search(pat,test)

if m and m.groups() > 0:
    line = test[:m.start(1)] + repl + test[m.end(1):]
    print line
else:
    print "the pattern didn't capture any text"

This will print: 'word1 will never be a word2'

The group to be replaced could be located in any position of the string.

how to run vibrate continuously in iphone?

Read the Apple Human Interaction Guidelines for iPhone. I believe this is not approved behavior in an app.

"ImportError: No module named" when trying to run Python script

import sys sys.path.append('/Users/{user}/Library/Python/3.7/lib/python/site-packages') import ta

MySQL Data Source not appearing in Visual Studio

I have faced the same problem and i have installed mysql-connector-net-8.0.11. But in visual studio is not showing the db connector for mysql. Then I was installed the mysql-for-visualstudio-1.2.8 and run the visual studio. Its working fine.

Thank you!

SQL TRUNCATE DATABASE ? How to TRUNCATE ALL TABLES

The accepted answer doesn't quite work when you have foreign key relationships. In that case you have to drop the constraints and recreate them. Below is a stored proc for doing that based on the answer here

CREATE PROCEDURE [dbo].[deleteAllDataFromAllTables] AS
SET NOCOUNT ON

    DECLARE @dropAndCreateConstraintsTable TABLE ( DropStmt varchar(max) , CreateStmt varchar(max) )

    insert @dropAndCreateConstraintsTable select
      DropStmt = 'ALTER TABLE [' + ForeignKeys.ForeignTableSchema + 
          '].[' + ForeignKeys.ForeignTableName + 
          '] DROP CONSTRAINT [' + ForeignKeys.ForeignKeyName + ']; '
    ,  CreateStmt = 'ALTER TABLE [' + ForeignKeys.ForeignTableSchema + 
          '].[' + ForeignKeys.ForeignTableName + 
          '] WITH CHECK ADD CONSTRAINT [' +  ForeignKeys.ForeignKeyName + 
          '] FOREIGN KEY([' + ForeignKeys.ForeignTableColumn + 
          ']) REFERENCES [' + schema_name(sys.objects.schema_id) + '].[' +
      sys.objects.[name] + ']([' +
      sys.columns.[name] + ']); '
     from sys.objects
      inner join sys.columns
        on (sys.columns.[object_id] = sys.objects.[object_id])
      inner join (
        select sys.foreign_keys.[name] as ForeignKeyName
         ,schema_name(sys.objects.schema_id) as ForeignTableSchema
         ,sys.objects.[name] as ForeignTableName
         ,sys.columns.[name]  as ForeignTableColumn
         ,sys.foreign_keys.referenced_object_id as referenced_object_id
         ,sys.foreign_key_columns.referenced_column_id as referenced_column_id
         from sys.foreign_keys
          inner join sys.foreign_key_columns
            on (sys.foreign_key_columns.constraint_object_id
              = sys.foreign_keys.[object_id])
          inner join sys.objects
            on (sys.objects.[object_id]
              = sys.foreign_keys.parent_object_id)
            inner join sys.columns
              on (sys.columns.[object_id]
                = sys.objects.[object_id])
               and (sys.columns.column_id
                = sys.foreign_key_columns.parent_column_id)
        ) ForeignKeys
        on (ForeignKeys.referenced_object_id = sys.objects.[object_id])
         and (ForeignKeys.referenced_column_id = sys.columns.column_id)
     where (sys.objects.[type] = 'U')
      and (sys.objects.[name] not in ('sysdiagrams'))


    DECLARE @DropStatement nvarchar(max)
    DECLARE @RecreateStatement nvarchar(max)

    DECLARE C1 CURSOR READ_ONLY
    FOR
    SELECT DropStmt from @dropAndCreateConstraintsTable
    OPEN C1

    FETCH NEXT FROM C1 INTO @DropStatement

    WHILE @@FETCH_STATUS = 0
    BEGIN
        PRINT 'Executing ' + @DropStatement
        execute sp_executesql @DropStatement
        FETCH NEXT FROM C1 INTO @DropStatement
    END
    CLOSE C1
    DEALLOCATE C1

    DECLARE @DeleteTableStatement nvarchar(max)
    DECLARE C2 CURSOR READ_ONLY
    FOR
    SELECT 'Delete From [dbo].[' + TABLE_NAME + ']' from INFORMATION_SCHEMA.TABLES 
        WHERE TABLE_SCHEMA = 'dbo' -- Change your schema appropriately.
    OPEN C2

    FETCH NEXT FROM C2 INTO @DeleteTableStatement

    WHILE @@FETCH_STATUS = 0
    BEGIN
        PRINT 'Executing ' + @DeleteTableStatement
        execute sp_executesql @DeleteTableStatement
        FETCH NEXT FROM C2 INTO  @DeleteTableStatement
    END
    CLOSE C2
    DEALLOCATE C2

    DECLARE C3 CURSOR READ_ONLY
    FOR
    SELECT CreateStmt from @dropAndCreateConstraintsTable
    OPEN C3

    FETCH NEXT FROM C3 INTO @RecreateStatement

    WHILE @@FETCH_STATUS = 0
    BEGIN
        PRINT 'Executing ' + @RecreateStatement
        execute sp_executesql @RecreateStatement
        FETCH NEXT FROM C3 INTO  @RecreateStatement
    END
    CLOSE C3
    DEALLOCATE C3

GO

HTML Entity Decode

To do it in pure javascript without jquery or predefining everything you can cycle the encoded html string through an elements innerHTML and innerText(/textContent) properties for every decode step that is required:

<html>
  <head>
    <title>For every decode step, cycle through innerHTML and innerText </title>
    <script>
function decode(str) {
  var d = document.createElement("div");
  d.innerHTML = str; 
  return typeof d.innerText !== 'undefined' ? d.innerText : d.textContent;
}
    </script>
  </head>
  <body>
    <script>
var encodedString = "&lt;p&gt;name&lt;/p&gt;&lt;p&gt;&lt;span style=\"font-size:xx-small;\"&gt;ajde&lt;/span&gt;&lt;/p&gt;&lt;p&gt;&lt;em&gt;da&lt;/em&gt;&lt;/p&gt;";
    </script>
    <input type=button onclick="document.body.innerHTML=decode(encodedString)"/>
  </body>
</html>

Transparent background on winforms?

I've tried the solutions above (and also) many other solutions from other posts.

In my case, I did it with the following setup:

public partial class WaitingDialog : Form
{
    public WaitingDialog()
    {
        InitializeComponent();

        SetStyle(ControlStyles.SupportsTransparentBackColor, true);
        this.BackColor = Color.Transparent;

        // Other stuff
    }

    protected override void OnPaintBackground(PaintEventArgs e) { /* Ignore */ }
}

As you can see, this is a mix of previously given answers.

How do I prevent site scraping?

I will presume that you have set up robots.txt.

As others have mentioned, scrapers can fake nearly every aspect of their activities, and it is probably very difficult to identify the requests that are coming from the bad guys.

I would consider:

  1. Set up a page, /jail.html.
  2. Disallow access to the page in robots.txt (so the respectful spiders will never visit).
  3. Place a link on one of your pages, hiding it with CSS (display: none).
  4. Record IP addresses of visitors to /jail.html.

This might help you to quickly identify requests from scrapers that are flagrantly disregarding your robots.txt.

You might also want to make your /jail.html a whole entire website that has the same, exact markup as normal pages, but with fake data (/jail/album/63ajdka, /jail/track/3aads8, etc.). This way, the bad scrapers won't be alerted to "unusual input" until you have the chance to block them entirely.

How do you get a timestamp in JavaScript?

You can only use

_x000D_
_x000D_
    var timestamp = new Date().getTime();_x000D_
    console.log(timestamp);
_x000D_
_x000D_
_x000D_

to get the current timestamp. No need to do anything extra.

Formatting numbers (decimal places, thousands separators, etc) with CSS

I don't think you can. You could use number_format() if you're coding in PHP. And other programing languages have a function for formatting numbers too.

Delete specified file from document directory

You can double protect your file removal with NSFileManager.defaultManager().isDeletableFileAtPath(PathName) As of now you MUST use do{}catch{} as the old error methods no longer work. isDeletableFileAtPath() is not a "throws" (i.e. "public func removeItemAtPath(path: String) throws") so it does not need the do...catch

let killFile = NSFileManager.defaultManager()

            if (killFile.isDeletableFileAtPath(PathName)){


                do {
                  try killFile.removeItemAtPath(arrayDictionaryFilePath)
                }
                catch let error as NSError {
                    error.description
                }
            }

How to check the gradle version in Android Studio?

  1. Create new project in Android studio;

  2. Press Ctrl+Shift+Alt+S

  3. Proceed to "Project" section

  4. You can see actual gradle version and android pluging version. Copy that to your project.

Linux: is there a read or recv from socket with timeout?

// works also after bind operation for WINDOWS

DWORD timeout = timeout_in_seconds * 1000;
setsockopt(socket, SOL_SOCKET, SO_RCVTIMEO, (const char*)&timeout, sizeof timeout);

How to sort an associative array by its values in Javascript?

i use $.each of jquery but you can make it with a for loop, an improvement is this:

        //.ArraySort(array)
        /* Sort an array
         */
        ArraySort = function(array, sortFunc){
              var tmp = [];
              var aSorted=[];
              var oSorted={};

              for (var k in array) {
                if (array.hasOwnProperty(k)) 
                    tmp.push({key: k, value:  array[k]});
              }

              tmp.sort(function(o1, o2) {
                    return sortFunc(o1.value, o2.value);
              });                     

              if(Object.prototype.toString.call(array) === '[object Array]'){
                  $.each(tmp, function(index, value){
                      aSorted.push(value.value);
                  });
                  return aSorted;                     
              }

              if(Object.prototype.toString.call(array) === '[object Object]'){
                  $.each(tmp, function(index, value){
                      oSorted[value.key]=value.value;
                  });                     
                  return oSorted;
              }               
     };

So now you can do

    console.log("ArraySort");
    var arr1 = [4,3,6,1,2,8,5,9,9];
    var arr2 = {'a':4, 'b':3, 'c':6, 'd':1, 'e':2, 'f':8, 'g':5, 'h':9};
    var arr3 = {a: 'green', b: 'brown', c: 'blue', d: 'red'};
    var result1 = ArraySort(arr1, function(a,b){return a-b});
    var result2 = ArraySort(arr2, function(a,b){return a-b});
    var result3 = ArraySort(arr3, function(a,b){return a>b});
    console.log(result1);
    console.log(result2);       
    console.log(result3);

How to update a plot in matplotlib?

This worked for me:

from matplotlib import pyplot as plt
from IPython.display import clear_output
import numpy as np
for i in range(50):
    clear_output(wait=True)
    y = np.random.random([10,1])
    plt.plot(y)
    plt.show()

Generating a WSDL from an XSD file

I know this question is old, but it deserves an answer. I personally prefer to create a WSDL by hand and test for compliance using SoapUI. But sometimes (specially for complex WSDLs), you have three ways to generate one out of an XSD:

  1. Generating a WSDL from a schema using Eclipse (probably the most user-friendly)
  2. Generating a WSDL via CXF (my favorite)
  3. Generating a WSDL via conventions using Spring WS (my least favorite)

I prefer the CXF approach since I'm a CLI guy. If it has a CLI, you can automate (that's my motto). And I like the Spring WS approach the least since it uses a lot of framework specific conventions.

There are more people who know CXF (I believe) than Spring WS. So anything that can throw a learning curve for a new engineer (without any clear advantage or ROI) is something I frown upon.

It should also go w/o saying that any generated WSDL should be tested for validity and compliance (and tweaked till it complies), and that your application publishes a static wsdl (as opposed to returning an auto-generated one.)

It's been my experience that you start with a WS-I compliant wsdl and then your application auto-generates (and returns to consumers) a non-compliant one.

In other words, beware of auto magic.

Does Internet Explorer 8 support HTML 5?

Modernizr is also a great option for giving IE HTML5 rendering capabilities.

jquery how to get the page's current screen top position?

var top = $('html').offset().top;

should do it.

edit: this is the negative of $(document).scrollTop()

Best way to change font colour halfway through paragraph?

wrap a <span> around those words and style with the appropriate color

now is the time for <span style='color:orange'>all good men</span> to come to the

Select SQL Server database size

If you want to simply check single database size, you can do it using SSMS Gui

Go to Server Explorer -> Expand it -> Right click on Database -> Choose Properties -> In popup window choose General tab ->See Size

Source: Check database size in Sql server ( Various Ways explained)

Changing text color onclick

A rewrite of the answer by Sarfraz would be something like this, I think:

<script>

    document.getElementById('change').onclick = changeColor;   

    function changeColor() {
        document.body.style.color = "purple";
        return false;
    }   

</script>

You'd either have to put this script at the bottom of your page, right before the closing body tag, or put the handler assignment in a function called onload - or if you're using jQuery there's the very elegant $(document).ready(function() { ... } );

Note that when you assign event handlers this way, it takes the functionality out of your HTML. Also note you set it equal to the function name -- no (). If you did onclick = myFunc(); the function would actually execute when the handler is being set.

And I'm curious -- you knew enough to script changing the background color, but not the text color? strange:)

Kill a postgresql session/connection

I had this issue and the problem was that Navicat was connected to my local Postgres db. Once I disconnected Navicat the problem disappeared.

EDIT:

Also, as an absolute last resort you can back up your data then run this command:

sudo kill -15 `ps -u postgres -o pid`

... which will kill everything that the postgres user is accessing. Avoid doing this on a production machine but you shouldn't have a problem with a development environment. It is vital that you ensure every postgres process has really terminated before attempting to restart PostgreSQL after this.

EDIT 2:

Due to this unix.SE post I've changed from kill -9 to kill -15.

How to keep footer at bottom of screen

use this style

min-height:250px;
height:auto;

Git conflict markers

The line (or lines) between the lines beginning <<<<<<< and ====== here:

<<<<<<< HEAD:file.txt
Hello world
=======

... is what you already had locally - you can tell because HEAD points to your current branch or commit. The line (or lines) between the lines beginning ======= and >>>>>>>:

=======
Goodbye
>>>>>>> 77976da35a11db4580b80ae27e8d65caf5208086:file.txt

... is what was introduced by the other (pulled) commit, in this case 77976da35a11. That is the object name (or "hash", "SHA1sum", etc.) of the commit that was merged into HEAD. All objects in git, whether they're commits (version), blobs (files), trees (directories) or tags have such an object name, which identifies them uniquely based on their content.

Multiple Python versions on the same machine?

I'm using Mac & the best way that worked for me is using pyenv!

The commands below are for Mac but pretty similar to Linux (see the links below)

#Install pyenv
brew update
brew install pyenv

Let's say you have python 3.6 as your primary version on your mac:

python --version 

Output:

Python <your current version>

Now Install python 3.7, first list all

pyenv install -l

Let's take 3.7.3:

pyenv install 3.7.3

Make sure to run this in the Terminal (add it to ~/.bashrc or ~/.zshrc):

export PATH="/Users/username/.pyenv:$PATH"
eval "$(pyenv init -)"

Now let's run it only on the opened terminal/shell:

pyenv shell 3.7.3

Now run

python --version

Output:

Python 3.7.3

And not less important unset it in the opened shell/iTerm:

pyenv shell --unset

You can run it globally or locally as well

Event binding on dynamically created elements?

You can attach event to element when dynamically created using jQuery(html, attributes).

As of jQuery 1.8, any jQuery instance method (a method of jQuery.fn) can be used as a property of the object passed to the second parameter:

_x000D_
_x000D_
function handleDynamicElementEvent(event) {_x000D_
  console.log(event.type, this.value)_x000D_
}_x000D_
// create and attach event to dynamic element_x000D_
jQuery("<select>", {_x000D_
    html: $.map(Array(3), function(_, index) {_x000D_
      return new Option(index, index)_x000D_
    }),_x000D_
    on: {_x000D_
      change: handleDynamicElementEvent_x000D_
    }_x000D_
  })_x000D_
  .appendTo("body");
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">_x000D_
</script>
_x000D_
_x000D_
_x000D_

Creating a PDF from a RDLC Report in the Background

You can instanciate LocalReport

                FicheInscriptionBean fiche = new FicheInscriptionBean();
                fiche.ToFicheInscriptionBean(inscription);List<FicheInscriptionBean> list = new List<FicheInscriptionBean>();
                list.Add(fiche);
                ReportDataSource rds = new ReportDataSource();
                rds = new ReportDataSource("InscriptionDataSet", list);
                // attachement du QrCode.
                string stringToCode = numinscription + "," + inscription.Nom + "," + inscription.Prenom + "," + inscription.Cin;
                Bitmap BitmapCaptcha = PostulerFiche.GenerateQrCode(fiche.NumInscription + ":" + fiche.Cin, Brushes.Black, Brushes.White, 200);
                MemoryStream ms = new MemoryStream();
                BitmapCaptcha.Save(ms, ImageFormat.Gif);
                var base64Data = Convert.ToBase64String(ms.ToArray());
                string QR_IMG = base64Data;
                ReportParameter parameter = new ReportParameter("QR_IMG", QR_IMG, true);

                LocalReport report = new LocalReport();
                report.ReportPath = Page.Server.MapPath("~/rdlc/FicheInscription.rdlc");
                report.DataSources.Clear();
                report.SetParameters(new ReportParameter[] { parameter });
                report.DataSources.Add(rds);
                report.Refresh();

                string FileName = "FichePreinscription_" + numinscription + ".pdf";
                string extension;
                string encoding;
                string mimeType;
                string[] streams;
                Warning[] warnings;
                Byte[] mybytes = report.Render("PDF", null,
                              out extension, out encoding,
                              out mimeType, out streams, out warnings);
                using (FileStream fs = File.Create(Server.MapPath("~/rdlc/Reports/" + FileName)))
                {
                    fs.Write(mybytes, 0, mybytes.Length);
                }
                Response.ClearHeaders();
                Response.ClearContent();
                Response.Buffer = true;
                Response.Clear();
                Response.Charset = "";
                Response.ContentType = "application/pdf";
                Response.AddHeader("Content-Disposition", "attachment;filename=\"" + FileName + "\"");
                Response.WriteFile(Server.MapPath("~/rdlc/Reports/" + FileName));

                Response.Flush();
                File.Delete(Server.MapPath("~/rdlc/Reports/" + FileName));
                Response.Close();
                Response.End();

Getting one value from a tuple

You can write

i = 5 + tup()[0]

Tuples can be indexed just like lists.

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

How to add a boolean datatype column to an existing table in sql?

In SQL SERVER it is BIT, though it allows NULL to be stored

ALTER TABLE person add  [AdminApproved] BIT default 'FALSE';

Also there are other mistakes in your query

  1. When you alter a table to add column no need to mention column keyword in alter statement

  2. For adding default constraint no need to use SET keyword

  3. Default value for a BIT column can be ('TRUE' or '1') / ('FALSE' or 0). TRUE or FALSE needs to mentioned as string not as Identifier

Pass array to ajax request in $.ajax()

Just use the JSON.stringify method and pass it through as the "data" parameter for the $.ajax function, like follows:

$.ajax({
    type: "POST",
    url: "index.php",
    dataType: "json",
    data: JSON.stringify({ paramName: info }),
    success: function(msg){
        $('.answer').html(msg);
    }
});

You just need to make sure you include the JSON2.js file in your page...

How to update attributes without validation

USE update_attribute instead of update_attributes

Updates a single attribute and saves the record without going through the normal validation procedure.

if a.update_attribute('state', a.state)

Note:- 'update_attribute' update only one attribute at a time from the code given in question i think it will work for you.

How to get file size in Java

Use the length() method in the File class. From the javadocs:

Returns the length of the file denoted by this abstract pathname. The return value is unspecified if this pathname denotes a directory.

UPDATED Nowadays we should use the Files.size() method:

Paths path = Paths.get("/path/to/file");
long size = Files.size(path);

For the second part of the question, straight from File's javadocs:

  • getUsableSpace() Returns the number of bytes available to this virtual machine on the partition named by this abstract pathname

  • getTotalSpace() Returns the size of the partition named by this abstract pathname

  • getFreeSpace() Returns the number of unallocated bytes in the partition named by this abstract path name

How to block until an event is fired in c#

If you're happy to use the Microsoft Reactive Extensions, then this can work nicely:

public class Foo
{
    public delegate void MyEventHandler(object source, MessageEventArgs args);
    public event MyEventHandler _event;
    public string ReadLine()
    {
        return Observable
            .FromEventPattern<MyEventHandler, MessageEventArgs>(
                h => this._event += h,
                h => this._event -= h)
            .Select(ep => ep.EventArgs.Message)
            .First();
    }
    public void SendLine(string message)
    {
        _event(this, new MessageEventArgs() { Message = message });
    }
}

public class MessageEventArgs : EventArgs
{
    public string Message;
}

I can use it like this:

var foo = new Foo();

ThreadPoolScheduler.Instance
    .Schedule(
        TimeSpan.FromSeconds(5.0),
        () => foo.SendLine("Bar!"));

var resp = foo.ReadLine();

Console.WriteLine(resp);

I needed to call the SendLine message on a different thread to avoid locking, but this code shows that it works as expected.

Failed to open the HAX device! HAX is not working and emulator runs in emulation mode emulator

I had the same problem recently.

First you need to install HAXM in the Android SDK Manager (from the error message I think you already did that). This will enable the emulator to use the HAXM framework, and for this it needs to open the HAX device. On your system this cannot be found, hence the error message.

To make this device available, you need to install the HAXM driver from Intel. You can find it here: http://software.intel.com/en-us/android/articles/intel-hardware-accelerated-execution-manager (You also need to enable virtualization in your computer BIOS).

Hope this helps.

Maximum value of maxRequestLength?

As per MSDN the default value is 4096 KB (4 MB).

UPDATE

As for the Maximum, since it is an int data type, then theoretically you can go up to 2,147,483,647. Also I wanted to make sure that you are aware that IIS 7 uses maxAllowedContentLength for specifying file upload size. By default it is set to 30000000 around 30MB and being an uint, it should theoretically allow a max of 4,294,967,295

load jquery after the page is fully loaded

If you're trying to avoid loading jquery until your content has been loaded, the best way is to simply put the reference to it in the bottom of your page, like many other answers have said.

General tips on Jquery usage:

  1. Use a CDN. This way, your site can use the cached version a user likely has on their computer. The // at the beginning allows it to be called (and use the same resource) whether it's http or https. Example:

    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

Using a CDN has a couple of big benefits: it makes it more likely that users have it cached from another site, so there will be no download (and no render-blocking). Further, CDNs use the closest, fastest connection available, meaning that if they do need to load it, it will probably be faster than connecting to your server. More info from Google.

  1. Put scripts at the bottom. Move as much of your js to the bottom of the page as possible. I use php to include a file with all my JS resources below the footer.

  2. If you're using a template system, you may need to have javascript spread throughout the html output. If you're using jquery in scripts that get called as the page renders, this will cause errors. To have your scripts wait until jquery is loaded, put them into

    window.onload() = function () { //... your js that isn't called by user interaction ... }

This will prevent errors but still run before user interaction and without timers.

Of course, if jquery is cached, it won't matter too much where you put it, except to page speed tools that will tell you you're blocking rendering.

Access a function variable outside the function without using "global"

You could do something along this lines:

def static_example():
   if not hasattr(static_example, "static_var"):
       static_example.static_var = 0
   static_example.static_var += 1
   return static_example.static_var

print static_example()
print static_example()
print static_example()

Reloading submodules in IPython

In IPython 0.12 (and possibly earlier), you can use this:

%load_ext autoreload
%autoreload 2

This is essentially the same as the answer by pv., except that the extension has been renamed and is now loaded using %load_ext.

How to check if a string "StartsWith" another string?

The best performant solution is to stop using library calls and just recognize that you're working with two arrays. A hand-rolled implementation is both short and also faster than every other solution I've seen here.

function startsWith2(str, prefix) {
    if (str.length < prefix.length)
        return false;
    for (var i = prefix.length - 1; (i >= 0) && (str[i] === prefix[i]); --i)
        continue;
    return i < 0;
}

For performance comparisons (success and failure), see http://jsperf.com/startswith2/4. (Make sure you check for later versions that may have trumped mine.)

How do I test axios in Jest?

I could do that following the steps:

  1. Create a folder __mocks__/ (as pointed by @Januartha comment)
  2. Implement an axios.js mock file
  3. Use my implemented module on test

The mock will happen automatically

Example of the mock module:

module.exports = {
    get: jest.fn((url) => {
        if (url === '/something') {
            return Promise.resolve({
                data: 'data'
            });
        }
    }),
    post: jest.fn((url) => {
        if (url === '/something') {
            return Promise.resolve({
                data: 'data'
            });
        }
        if (url === '/something2') {
            return Promise.resolve({
                data: 'data2'
            });
        }
    }),
    create: jest.fn(function () {
        return this;
    })
};

How do I set up Android Studio to work completely offline?

I'm using Android Studio 0.5.4 (Mavericks).

Preferences ? Gradle ? Global Gradle Settings ? Offline work

Jquery function BEFORE form submission

Just because I made this mistake every time when using the submit function.

This is the full code you need:

Add the id "yourid" to the HTML form tag.

<form id="yourid" action='XXX' name='form' method='POST' accept-charset='UTF-8' enctype='multipart/form-data'>

the jQuery code:

$('#yourid').submit(function() {
  // do something
});

How to convert BigInteger to String in java

String input = "0101";
BigInteger x = new BigInteger ( input , 2 );
String output = x.toString(2);

Function to clear the console in R and RStudio

You can combine the following two commands

cat("\014"); 
cat(rep("\n", 50))

What is the purpose of the single underscore "_" variable in Python?

There are 5 cases for using the underscore in Python.

  1. For storing the value of last expression in interpreter.

  2. For ignoring the specific values. (so-called “I don’t care”)

  3. To give special meanings and functions to name of variables or functions.

  4. To use as ‘internationalization (i18n)’ or ‘localization (l10n)’ functions.

  5. To separate the digits of number literal value.

Here is a nice article with examples by mingrammer.

writing to serial port from linux command line

If you want to use hex codes, you should add -e option to enable interpretation of backslash escapes by echo (but the result is the same as with echoCtrlRCtrlB). And as wallyk said, you probably want to add -n to prevent the output of a newline:

echo -en '\x12\x02' > /dev/ttyS0

Also make sure that /dev/ttyS0 is the port you want.

typedef struct vs struct definitions

struct and typedef are two very different things.

The struct keyword is used to define, or to refer to, a structure type. For example, this:

struct foo {
    int n;
};

creates a new type called struct foo. The name foo is a tag; it's meaningful only when it's immediately preceded by the struct keyword, because tags and other identifiers are in distinct name spaces. (This is similar to, but much more restricted than, the C++ concept of namespaces.)

A typedef, in spite of the name, does not define a new type; it merely creates a new name for an existing type. For example, given:

typedef int my_int;

my_int is a new name for int; my_int and int are exactly the same type. Similarly, given the struct definition above, you can write:

typedef struct foo foo;

The type already has a name, struct foo. The typedef declaration gives the same type a new name, foo.

The syntax allows you to combine a struct and typedef into a single declaration:

typedef struct bar {
    int n;
} bar;

This is a common idiom. Now you can refer to this structure type either as struct bar or just as bar.

Note that the typedef name doesn't become visible until the end of the declaration. If the structure contains a pointer to itself, you have use the struct version to refer to it:

typedef struct node {
    int data;
    struct node *next; /* can't use just "node *next" here */
} node;

Some programmers will use distinct identifiers for the struct tag and for the typedef name. In my opinion, there's no good reason for that; using the same name is perfectly legal and makes it clearer that they're the same type. If you must use different identifiers, at least use a consistent convention:

typedef struct node_s {
    /* ... */
} node;

(Personally, I prefer to omit the typedef and refer to the type as struct bar. The typedef save a little typing, but it hides the fact that it's a structure type. If you want the type to be opaque, this can be a good thing. If client code is going to be referring to the member n by name, then it's not opaque; it's visibly a structure, and in my opinion it makes sense to refer to it as a structure. But plenty of smart programmers disagree with me on this point. Be prepared to read and understand code written either way.)

(C++ has different rules. Given a declaration of struct blah, you can refer to the type as just blah, even without a typedef. Using a typedef might make your C code a little more C++-like -- if you think that's a good thing.)

GROUP BY + CASE statement

For TSQL I like to encapsulate case statements in an outer apply. This prevents me from having to have the case statement written twice, allows reference to the case statement by alias in future joins and avoids the need for positional references.

select oa.day, 
model.name, 
attempt.type, 
oa.result
COUNT(*) MyCount 
FROM attempt attempt, prod_hw_id prod_hw_id, model model
WHERE time >= '2013-11-06 00:00:00'  
AND time < '2013-11-07 00:00:00'
AND attempt.hard_id = prod_hw_id.hard_id
AND prod_hw_id.model_id = model.model_id
OUTER APPLY (
    SELECT CURRENT_DATE-1 AS day,
     CASE WHEN attempt.result = 0 THEN 0 ELSE 1 END result
    ) oa    
group by oa.day, 
model.name, 
attempt.type, 
oa.result
order by model.name, attempt.type, oa.result;

Syntax for a single-line Bash infinite while loop

A very simple infinite loop.. :)

while true ; do continue ; done

Fr your question it would be:

while true; do foo ; sleep 2 ; done

git diff between cloned and original remote repository

Another reply to your questions (assuming you are on master and already did "git fetch origin" to make you repo aware about remote changes):

1) Commits on remote branch since when local branch was created:

git diff HEAD...origin/master

2) I assume by "working copy" you mean your local branch with some local commits that are not yet on remote. To see the differences of what you have on your local branch but that does not exist on remote branch run:

git diff origin/master...HEAD

3) See the answer by dbyrne.

Adding form action in html in laravel

You can use the action() helper to generate an URL to your route:

<form method="post" action="{{ action('WelcomeController@log_in') }}" accept-charset="UTF-8">

Note that the Laravel 5 default installation already comes with views and controllers for the whole authentication process. Just go to /home on a fresh install and you should get redirected to a login page.

Also make sure to read the Authentication section in the docs


The error you're getting now (TokenMismatchException) is because Laravel has CSRF protection out of the box

To make use of it (and make the error go away) add a hidden field to your form:

<input name="_token" type="hidden" value="{{ csrf_token() }}"/>

Alternatively you can also disable CSRF protection by removing 'App\Http\Middleware\VerifyCsrfToken' from the $middleware array in app/Http/Kernel.php

Div Scrollbar - Any way to style it?

Using javascript you can style the scroll bars. Which works fine in IE as well as FF.

Check the below links

From Twinhelix , Example 2 , Example 3 [or] you can find some 30 type of scroll style types by click the below link 30 scrolling techniques

How do I check CPU and Memory Usage in Java?

Here is some simple code to calculate the current memory usage in megabytes:

double currentMemory = ( (double)((double)(Runtime.getRuntime().totalMemory()/1024)/1024))- ((double)((double)(Runtime.getRuntime().freeMemory()/1024)/1024));

How can I get just the first row in a result set AFTER ordering?

This question is similar to How do I limit the number of rows returned by an Oracle query after ordering?.

It talks about how to implement a MySQL limit on an oracle database which judging by your tags and post is what you are using.

The relevant section is:

select *
from  
  ( select * 
  from emp 
  order by sal desc ) 
  where ROWNUM <= 5;

Programmatic equivalent of default(Type)

Can't find anything simple and elegant just yet, but I have one idea: If you know the type of the property you wish to set, you can write your own default(T). There are two cases - T is a value type, and T is a reference type. You can see this by checking T.IsValueType. If T is a reference type, then you can simply set it to null. If T is a value type, then it will have a default parameterless constructor that you can call to get a "blank" value.

Why is the Visual Studio 2015/2017/2019 Test Runner not discovering my xUnit v2 tests

Do make sure that you haven't written your unit tests in a .NET Standard 2.0 Class Library. The visualstudio runner does not support running tests in netstandard2.0 class libraries at the time of this writing.

Check here for the Test Runner Compatibility matrix:

https://xunit.github.io/#runners

How to get the directory of the currently running file?

Use package osext

It's providing function ExecutableFolder() that returns an absolute path to folder where the currently running program executable reside (useful for cron jobs). It's cross platform.

Online documentation

package main

import (
    "github.com/kardianos/osext"
    "fmt"
    "log"
)

func main() {
    folderPath, err := osext.ExecutableFolder()
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(folderPath)
}

Heatmap in matplotlib with pcolor?

Main issue is that you first need to set the location of your x and y ticks. Also, it helps to use the more object-oriented interface to matplotlib. Namely, interact with the axes object directly.

import matplotlib.pyplot as plt
import numpy as np
column_labels = list('ABCD')
row_labels = list('WXYZ')
data = np.random.rand(4,4)
fig, ax = plt.subplots()
heatmap = ax.pcolor(data)

# put the major ticks at the middle of each cell, notice "reverse" use of dimension
ax.set_yticks(np.arange(data.shape[0])+0.5, minor=False)
ax.set_xticks(np.arange(data.shape[1])+0.5, minor=False)


ax.set_xticklabels(row_labels, minor=False)
ax.set_yticklabels(column_labels, minor=False)
plt.show()

Hope that helps.

Is using 'var' to declare variables optional?

Var doesn't let you, the programmer, declare a variable because Javascript doesn't have variables. Javascript has objects. Var declares a name to an undefined object, explicitly. Assignment assigns a name as a handle to an object that has been given a value.

Using var tells the Javacript interpreter two things:

  1. not to use delegation reverse traversal look up value for the name, instead use this one
  2. not to delete the name

Omission of var tells the Javacript interpreter to use the first-found previous instance of an object with the same name.

Var as a keyword arose from a poor decision by the language designer much in the same way that Javascript as a name arose from a poor decision.

ps. Study the code examples above.

Counting the Number of keywords in a dictionary in python

In order to count the number of keywords in a dictionary:

def dict_finder(dict_finders):
    x=input("Enter the thing you want to find: ")
    if x in dict_finders:
        print("Element found")
    else:
        print("Nothing found:")

Found conflicts between different versions of the same dependent assembly that could not be resolved

I found that, sometimes, nuget packages will install (what I'm guessing are) .NET Core required components or other items that conflict with the already-installed framework. My solution there was to open the project (.csproj) file and remove those references. For example, System.IO, System.Threading and such, tend to be added when Microsoft.Bcl is included via some recently installed NuGet package. There's no reason for specific versions of those in my projects, so I remove the references and the project builds. Hope that helps.

You can search your project file for "reference" and remove the conflicts. If they're included in System, get rid of them, and the build should work. This may not answer all cases of this issue - I'm making sure you know what worked for me :)

Example of what I commented out:

_x000D_
_x000D_
<!-- <Reference Include="System.Runtime, Version=2.6.9.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL"> -->_x000D_
  <!-- <HintPath>$(SolutionDir)packages\Microsoft.Bcl.1.1.9\lib\net40\System.Runtime.dll</HintPath> -->_x000D_
  <!-- <Private>True</Private> -->_x000D_
<!-- </Reference> -->
_x000D_
_x000D_
_x000D_

Running a shell script through Cygwin on Windows

If you don't mind always including .sh on the script file name, then you can keep the same script for Cygwin and Unix (Macbook).

To illustrate:
1. Always include .sh to your script file name, e.g., test1.sh
2. test1.sh looks like the following as an example:
#!/bin/bash echo '$0 = ' $0 echo '$1 = ' $1 filepath=$1 3. On Windows with Cygwin, you type "test1.sh" to run
4. On a Unix, you also type "test1.sh" to run


Note: On Windows, you need to use the file explorer to do following once:
1. Open the file explorer
2. Right-click on a file with .sh extension, like test1.sh
3. Open with... -> Select sh.exe
After this, your Windows 10 remembers to execute all .sh files with sh.exe.

Note: Using this method, you do not need to prepend your script file name with bash to run

Check whether a path is valid

You can try this code:

try
{
  Path.GetDirectoryName(myPath);
}
catch
{
  // Path is not valid
}

I'm not sure it covers all the cases...

ActionBarActivity cannot resolve a symbol

Make sure that in the path to the project there is no foldername having whitespace. While creating a project the specified path folders must not contain any space in their naming.

Can I use jQuery with Node.js?

As of jsdom v10, .env() function is deprecated. I did it like below after trying a lot of things to require jquery:

_x000D_
_x000D_
var jsdom = require('jsdom');_x000D_
const { JSDOM } = jsdom;_x000D_
const { window } = new JSDOM();_x000D_
const { document } = (new JSDOM('')).window;_x000D_
global.document = document;_x000D_
_x000D_
var $ = jQuery = require('jquery')(window);
_x000D_
_x000D_
_x000D_

Hope this helps you or anyone who has been facing these types of issues.

Sprintf equivalent in Java

Strings are immutable types. You cannot modify them, only return new string instances.

Because of that, formatting with an instance method makes little sense, as it would have to be called like:

String formatted = "%s: %s".format(key, value);

The original Java authors (and .NET authors) decided that a static method made more sense in this situation, as you are not modifying the target, but instead calling a format method and passing in an input string.

Here is an example of why format() would be dumb as an instance method. In .NET (and probably in Java), Replace() is an instance method.

You can do this:

 "I Like Wine".Replace("Wine","Beer");

However, nothing happens, because strings are immutable. Replace() tries to return a new string, but it is assigned to nothing.

This causes lots of common rookie mistakes like:

inputText.Replace(" ", "%20");

Again, nothing happens, instead you have to do:

inputText = inputText.Replace(" ","%20");

Now, if you understand that strings are immutable, that makes perfect sense. If you don't, then you are just confused. The proper place for Replace() would be where format() is, as a static method of String:

 inputText = String.Replace(inputText, " ", "%20");

Now there is no question as to what's going on.

The real question is, why did the authors of these frameworks decide that one should be an instance method, and the other static? In my opinion, both are more elegantly expressed as static methods.

Regardless of your opinion, the truth is that you are less prone to make a mistake using the static version, and the code is easier to understand (No Hidden Gotchas).

Of course there are some methods that are perfect as instance methods, take String.Length()

int length = "123".Length();

In this situation, it's obvious we are not trying to modify "123", we are just inspecting it, and returning its length. This is a perfect candidate for an instance method.

My simple rules for Instance Methods on Immutable Objects:

  • If you need to return a new instance of the same type, use a static method.
  • Otherwise, use an instance method.

Mosaic Grid gallery with dynamic sized images

I think you can try "Google Grid Gallery", it based on aforementioned Masonry with some additions, like styles and viewer.

Create html documentation for C# code

In 2017, the thing closest to Javadoc would probably DocFx which was developed by Microsoft and comes as a Commmand-Line-Tool as well as a VS2017 plugin.

It's still a little rough around the edges but it looks promising.

Another alternative would be Wyam which has a documentation recipe suitable for net aplications. Look at the cake documentation for an example.

merge two object arrays with Angular 2 and TypeScript?

With angular 6 spread operator and concat not work. You can resolve it easy:

result.push(...data);

How to see PL/SQL Stored Function body in Oracle

SELECT text 
FROM all_source
where name = 'FGETALGOGROUPKEY'
order by line

alternatively:

select dbms_metadata.get_ddl('FUNCTION', 'FGETALGOGROUPKEY')
from dual;

Java 8 stream map to list of keys sorted by values

You say you want to sort by value, but you don't have that in your code. Pass a lambda (or method reference) to sorted to tell it how you want to sort.

And you want to get the keys; use map to transform entries to keys.

List<Type> types = countByType.entrySet().stream()
        .sorted(Comparator.comparing(Map.Entry::getValue))
        .map(Map.Entry::getKey)
        .collect(Collectors.toList());

multiple conditions for filter in spark data frames

In spark/scala, it's pretty easy to filter with varargs.

val d = spark.read...//data contains column named matid
val ids = Seq("BNBEL0608AH", "BNBEL00608H")
val filtered = d.filter($"matid".isin(ids:_*))

Common CSS Media Queries Break Points

This is from css-tricks link

/* Smartphones (portrait and landscape) ----------- */
@media only screen 
and (min-device-width : 320px) 
and (max-device-width : 480px) {
/* Styles */
}

/* Smartphones (landscape) ----------- */
@media only screen 
and (min-width : 321px) {
/* Styles */
}

/* Smartphones (portrait) ----------- */
@media only screen 
and (max-width : 320px) {
/* Styles */
}

/* iPads (portrait and landscape) ----------- */
@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) {
/* Styles */
}

/* iPads (landscape) ----------- */
@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) 
and (orientation : landscape) {
/* Styles */
}

/* iPads (portrait) ----------- */
@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) 
and (orientation : portrait) {
/* Styles */
}

/* Desktops and laptops ----------- */
@media only screen 
and (min-width : 1224px) {
/* Styles */
}

/* Large screens ----------- */
@media only screen 
and (min-width : 1824px) {
/* Styles */
}

/* iPhone 4 ----------- */
@media
only screen and (-webkit-min-device-pixel-ratio : 1.5),
only screen and (min-device-pixel-ratio : 1.5) {
/* Styles */
}

What is difference between png8 and png24

While making image with fully transparent background in PNG-8, the outline of the image looks prominent with little white bits. But in PNG-24 the outline is gone and looks perfect. Transparency in PNG-24 is greater and cleaner than PNG-8.

PNG-8 contains 256 colors, while PNG-24 contains 16 million colors.

File size is almost double in PNG-24 than PNG-8.

Python: how to print range a-z?

#1)
print " ".join(map(chr, range(ord('a'),ord('n')+1)))

#2)
print " ".join(map(chr, range(ord('a'),ord('n')+1,2)))

#3)
urls = ["hello.com/", "hej.com/", "hallo.com/"]
an = map(chr, range(ord('a'),ord('n')+1))
print [ x + y for x,y in zip(urls, an)]

UnicodeEncodeError: 'charmap' codec can't encode - character maps to <undefined>, print function

If you are using Windows command line to print the data, you should use

chcp 65001

This worked for me!

Detect if value is number in MySQL

You can use Regular Expression too... it would be like:

SELECT * FROM myTable WHERE col1 REGEXP '^[0-9]+$';

Reference: http://dev.mysql.com/doc/refman/5.1/en/regexp.html

How can I determine the current CPU utilization from the shell?

Try this command:

cat /proc/stat

This will be something like this:

cpu  55366 271 17283 75381807 22953 13468 94542 0
cpu0 3374 0 2187 9462432 1393 2 665 0
cpu1 2074 12 1314 9459589 841 2 43 0
cpu2 1664 0 1109 9447191 666 1 571 0
cpu3 864 0 716 9429250 387 2 118 0
cpu4 27667 110 5553 9358851 13900 2598 21784 0
cpu5 16625 146 2861 9388654 4556 4026 24979 0
cpu6 1790 0 1836 9436782 480 3307 19623 0
cpu7 1306 0 1702 9399053 726 3529 26756 0
intr 4421041070 559 10 0 4 5 0 0 0 26 0 0 0 111 0 129692 0 0 0 0 0 95 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 369 91027 1580921706 1277926101 570026630 991666971 0 277768 0 0 0 0 0 0 0 0 0 0 0 0 0
ctxt 8097121
btime 1251365089
processes 63692
procs_running 2
procs_blocked 0

More details:

http://www.mail-archive.com/[email protected]/msg01690.html http://www.linuxhowtos.org/System/procstat.htm

Understanding The Modulus Operator %

As others have pointed out modulus is based on remainder system.

I think an easier way to think about modulus is what remains after a dividend (number to be divided) has been fully divided by a divisor. So if we think about 5%7, when you divide 5 by 7, 7 can go into 5 only 0 times and when you subtract 0 (7*0) from 5 (just like we learnt back in elementary school), then the remainder would be 5 ( the mod). See the illustration below.

   0
  ______
7) 5    
__-0____
   5

With the same logic, -5 mod 7 will be -5 ( only 0 7s can go in -5 and -5-0*7 = -5). With the same token -5 mod -7 will also be -5. A few more interesting cases:

5 mod (-3) = 2 i.e. 5 - (-3*-1)

(-5) mod (-3) = -2 i.e. -5 - (-3*1) = -5+3

What is the use of printStackTrace() method in Java?

It helps to trace the exception. For example you are writing some methods in your program and one of your methods causes bug. Then printstack will help you to identify which method causes the bug. Stack will help like this:

First your main method will be called and inserted to stack, then the second method will be called and inserted to the stack in LIFO order and if any error occurs somewhere inside any method then this stack will help to identify that method.

jquery save json data object in cookie

Now there is already no need to use JSON.stringify explicitly. Just execute this line of code

$.cookie.json = true;

After that you can save any object in cookie, which will be automatically converted to JSON and back from JSON when reading cookie.

var user = { name: "name", age: 25 }
$.cookie('user', user);
...

var currentUser = $.cookie('user');
alert('User name is ' + currentUser.name);

But JSON library does not come with jquery.cookie, so you have to download it by yourself and include into html page before jquery.cookie.js

time.sleep -- sleeps thread or process?

The thread will block, but the process is still alive.

In a single threaded application, this means everything is blocked while you sleep. In a multithreaded application, only the thread you explicitly 'sleep' will block and the other threads still run within the process.

How can I trim beginning and ending double quotes from a string?

Groovy

You can subtract a substring from a string using a regular expression in groovy:

String unquotedString = theString - ~/^"/ - ~/"$/

Can I assume (bool)true == (int)1 for any C++ compiler?

Charles Bailey's answer is correct. The exact wording from the C++ standard is (§4.7/4): "If the source type is bool, the value false is converted to zero and the value true is converted to one."

Edit: I see he's added the reference as well -- I'll delete this shortly, if I don't get distracted and forget...

Edit2: Then again, it is probably worth noting that while the Boolean values themselves always convert to zero or one, a number of functions (especially from the C standard library) return values that are "basically Boolean", but represented as ints that are normally only required to be zero to indicate false or non-zero to indicate true. For example, the is* functions in <ctype.h> only require zero or non-zero, not necessarily zero or one.

If you cast that to bool, zero will convert to false, and non-zero to true (as you'd expect).

How to find column names for all tables in all databases in SQL Server

Some minor improvements

->previous answers weren't showing all results

->possible to filter on column name by setting the column name variable

DECLARE @columnname nvarchar(150)
SET @columnname=''

DECLARE @SQL varchar(max)
SET @SQL=''
SELECT @SQL=@SQL+'UNION
select 
'''+d.name+'.''+sh.name+''.''+o.name COLLATE SQL_Latin1_General_CP1_CI_AS as name,c.name COLLATE SQL_Latin1_General_CP1_CI_AS as columnname,c.column_id
from '+d.name+'.sys.columns            c
    inner join '+d.name+'.sys.objects  o on c.object_id=o.object_id
    INNER JOIN '+d.name+'.sys.schemas  sh on o.schema_id=sh.schema_id
    where c.name like ''%'+@columnname+'%'' and sh.name<>''sys'' 
'
FROM sys.databases d
SELECT @SQL=RIGHT(@SQL,LEN(@SQL)-5)+'order by 1,3'
--print @SQL
EXEC (@SQL)