Programs & Examples On #Com

Component Object Model (COM) is a component technology from Microsoft, featuring remoting, language independence and interface-based programming. For questions about the COM serial port, you should use the [serial-port] tag instead.

Retrieving the COM class factory for component failed

I had the same error when I deployed my app. I've got solution from this site: Component with CLSID XXX failed due to the following error: 80070005 Access is denied

Here is this solution:

  1. In DCOMCNFG, right click on the My Computer and select properties.

  2. Choose the COM Securities tab.

  3. In Access Permissions, click Edit Defaults and add Network Service to it and give it Allow local access permission. Do the same for < Machine_name >\Users.

  4. In Launch and Activation Permissions, click Edit Defaults and add Network Service to it and give it Local launch and Local Activation permission. Do the same for < Machine_name >\Users.

*I used forms authentication.

How to Enable ActiveX in Chrome?

I downloaded this "IE Tab Multi" from Chrome. It works good! http://iblogbox.com/chrome/ietab/alert.php

How can I generate UUID in C#

Be careful: while the string representations for .NET Guid and (RFC4122) UUID are identical, the storage format is not. .NET trades in little-endian bytes for the first three Guid parts.

If you are transmitting the bytes (for example, as base64), you can't just use Guid.ToByteArray() and encode it. You'll need to Array.Reverse the first three parts (Data1-3).

I do it this way:

var rfc4122bytes = Convert.FromBase64String("aguidthatIgotonthewire==");
Array.Reverse(rfc4122bytes,0,4);
Array.Reverse(rfc4122bytes,4,2);
Array.Reverse(rfc4122bytes,6,2);
var guid = new Guid(rfc4122bytes);

See this answer for the specific .NET implementation details.

Edit: Thanks to Jeff Walker, Code Ranger, for pointing out that the internals are not relevant to the format of the byte array that goes in and out of the byte-array constructor and ToByteArray().

C# - How to add an Excel Worksheet programmatically - Office XP / 2003

Would like to thank you for some excellent replies. @AR., your a star and it works perfectly. I had noticed last night that the Excel.exe was not closing; so I did some research and found out about how to release the COM objects. Here is my final code:

using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.IO;
using Excel;

namespace testExcelconsoleApp
{
    class Program
    {
        private String fileLoc = @"C:\temp\test.xls";

        static void Main(string[] args)
        {
            Program p = new Program();
            p.createExcel();
        }

        private void createExcel()
        {
            Excel.Application excelApp = null;
            Excel.Workbook workbook = null;
            Excel.Sheets sheets = null;
            Excel.Worksheet newSheet = null;

            try
            {
                FileInfo file = new FileInfo(fileLoc);
                if (file.Exists)
                {
                    excelApp = new Excel.Application();
                    workbook = excelApp.Workbooks.Open(fileLoc, 0, false, 5, "", "",
                                                        false, XlPlatform.xlWindows, "",
                                                        true, false, 0, true, false, false);

                    sheets = workbook.Sheets;

                    //check columns exist
                    foreach (Excel.Worksheet sheet in sheets)
                    {
                        Console.WriteLine(sheet.Name);
                        sheet.Select(Type.Missing);

                        System.Runtime.InteropServices.Marshal.ReleaseComObject(sheet);
                    }

                    newSheet = (Worksheet)sheets.Add(sheets[1], Type.Missing, Type.Missing, Type.Missing);
                    newSheet.Name = "My New Sheet";
                    newSheet.Cells[1, 1] = "BOO!";

                    workbook.Save();
                    workbook.Close(null, null, null);
                    excelApp.Quit();
                }
            }
            finally
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(newSheet);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(sheets);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp);

                newSheet = null;
                sheets = null;
                workbook = null;
                excelApp = null;

                GC.Collect();
            }
        }
    }
}

Thank you for all your help.

BSTR to std::string (std::wstring) and vice versa

BSTR to std::wstring:

// given BSTR bs
assert(bs != nullptr);
std::wstring ws(bs, SysStringLen(bs));

 
std::wstring to BSTR:

// given std::wstring ws
assert(!ws.empty());
BSTR bs = SysAllocStringLen(ws.data(), ws.size());

Doc refs:

  1. std::basic_string<typename CharT>::basic_string(const CharT*, size_type)
  2. std::basic_string<>::empty() const
  3. std::basic_string<>::data() const
  4. std::basic_string<>::size() const
  5. SysStringLen()
  6. SysAllocStringLen()

Could you explain STA and MTA?

It's all down to how calls to objects are handled, and how much protection they need. COM objects can ask the runtime to protect them against being called by multiple threads at the same time; those that don't can potentially be called concurrently from different threads, so they have to protect their own data.

In addition, it's also necessary for the runtime to prevent a COM object call from blocking the user interface, if a call is made from a user interface thread.

An apartment is a place for objects to live, and they contain one or more threads. The apartment defines what happens when calls are made. Calls to objects in an apartment will be received and processed on any thread in that apartment, with the exception that a call by a thread already in the right apartment is processed by itself (i.e. a direct call to the object).

Threads can be either in a Single-Threaded Apartment (in which case they are the only thread in that apartment) or in a Multi-Threaded Apartment. They specify which when the thread initializes COM for that thread.

The STA is primarily for compatibility with the user interface, which is tied to a specific thread. An STA receives notifications of calls to process by receiving a window message to a hidden window; when it makes an outbound call, it starts a modal message loop to prevent other window messages being processed. You can specify a message filter to be called, so that your application can respond to other messages.

By contrast all MTA threads share a single MTA for the process. COM may start a new worker thread to handle an incoming call if no threads are available, up to a pool limit. Threads making outbound calls simply block.

For simplicity we'll consider only objects implemented in DLLs, which advertise in the registry what they support, by setting the ThreadingModel value for their class's key. There are four options:

  • Main thread (ThreadingModel value not present). The object is created on the host's main UI thread, and all calls are marshalled to that thread. The class factory will only be called on that thread.
  • Apartment. This indicates that the class can run on any single-threaded-mode thread. If the thread that creates it is an STA thread, the object will run on that thread, otherwise it will be created in the main STA - if no main STA exists, an STA thread will be created for it. (This means MTA threads that create Apartment objects will be marshalling all calls to a different thread.) The class factory can be called concurrently by multiple STA threads so it must protect its internal data against this.
  • Free. This indicates a class designed to run in the MTA. It will always load in the MTA, even if created by an STA thread, which again means the STA thread's calls will be marshalled. This is because a Free object is generally written with the expectation that it can block.
  • Both. These classes are flexible and load in whichever apartment they're created from. They must be written to fit both sets of requirements, however: they must protect their internal state against concurrent calls, in case they're loaded in the MTA, but must not block, in case they're loaded in an STA.

From the .NET Framework, basically just use [STAThread] on any thread that creates UI. Worker threads should use the MTA, unless they're going to use Apartment-marked COM components, in which case use the STA to avoid marshalling overhead and scalability problems if the same component is called from multiple threads (as each thread will have to wait for the component in turn). It's much easier all around if you use a separate COM object per thread, whether the component is in the STA or MTA.

Register 32 bit COM DLL to 64 bit Windows 7

I believe, things have changed now. On My Win 2008 R2 Box, I was able to register a 32 bit dll with a 64 bit regsvr32 as the 64 bit version can detect the target bitness and spawn a new 32 bit regsvr32 from %SYSWOW% folder.

Refer: Registering a 32 bit DLL with 64 bit regsvr32

Error 80040154 (Class not registered exception) when initializing VCProjectEngineObject (Microsoft.VisualStudio.VCProjectEngine.dll)

There are not many good reasons this would fail, especially the regsvr32 step. Run dumpbin /exports on that dll. If you don't see DllRegisterServer then you've got a corrupt install. It should have more side-effects, you wouldn't be able to build C/C++ projects anymore.

One standard failure mode is running this on a 64-bit operating system. This is 32-bit unmanaged code, you would indeed get the 'class not registered' exception. Project + Properties, Build tab, change Platform Target to x86.

HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))

This could also be an issue of building the code using a 64 bit configuration. You can try to select x86 as the build platform which can solve this issue. To do this right-click the solution and select Configuration Manager From there you can change the Platform of the project using the 32-bit .dll to x86

How to repair COMException error 80040154?

Move excel variables which are global declare in your form to local like in my form I have:

Dim xls As New MyExcel.Interop.Application  
Dim xlb As MyExcel.Interop.Workbook

above two lines were declare global in my form so i moved these two lines to local function and now tool is working fine.

How to handle AccessViolationException

Compiled from above answers, worked for me, did following steps to catch it.

Step #1 - Add following snippet to config file

<configuration>
   <runtime>
      <legacyCorruptedStateExceptionsPolicy enabled="true" />
   </runtime>
</configuration>

Step #2

Add -

[HandleProcessCorruptedStateExceptions]

[SecurityCritical]

on the top of function you are tying catch the exception

source: http://www.gisremotesensing.com/2017/03/catch-exception-attempted-to-read-or.html

The #include<iostream> exists, but I get an error: identifier "cout" is undefined. Why?

The problem is the std namespace you are missing. cout is in the std namespace.
Add using namespace std; after the #include

Microsoft.Office.Core Reference Missing

Now there is a nuget package for that.

https://www.nuget.org/packages/NetOffice.Core.Net40/

First I didn't find office in COM, so tried this nuget and it worked!

Is there an embeddable Webkit component for Windows / C# development?

There is OpenWebKitSharp, a fork of WebKit.NET 0.5 and very advanced. Details: http://code.google.com/p/open-webkit-sharp/

Class not registered Error

In 64 bit windows machines the COM components need to register itself in HKEY_CLASSES_ROOT\CLSID (64 bit component) OR HKEY_CLASSES_ROOT\Wow6432Node\CLSID (32 bit component) . If your application is a 32 bit application running on 64-bit machine the COM library would typically look for the GUID under Wow64 node and if your application is a 64 bit application, the COM library would try to load from HKEY_CLASSES_ROOT\CLSID. Make sure you are targeting the correct platform and ensure you have installed the correct version of library(32/64 bit).

System.Runtime.InteropServices.COMException (0x800A03EC)

I was seeing this same error when trying to save an excel file. The code worked fine when I was using MS Office 2003, but after upgrading to MS Office 2007 I started seeing this. It would happen anytime I tried to save an Excel file to a server or remote fie share.

My solution, though rudimentary, worked well. I just had the program save the file locally, like to the user's C:\ drive. Then use the "System.IO.File.Copy(File, Destination, Overwrite)" method to move the file to the server. Then you can delete the file on the C:\ drive.

Works great, and simple. But admittedly not the most elegant approach.

Hope this helps! I was having a ton of trouble finding any solutions on the web till this idea popped into my head.

SQL "IF", "BEGIN", "END", "END IF"?

You could also rewrite the code to remove the nested 'If' statement completely.

INSERT INTO @Classes    
SELECT XXXXXX      
FROM XXXX 
Where @Term = 3   

---- **always** "fall thru" to here, no matter what @Term is equal to - always do
---- the following INSERT for all elementary schools    
INSERT INTO @Classes        
SELECT    XXXXXXXX        
FROM XXXXXX (more code) 

Where does PHP store the error log? (php5, apache, fastcgi, cpanel)

something like this :

sudo locate error.log | xargs -IX grep -iH "errorlog" X

or

sudo locate error_log | xargs -IX grep -iH "errorlog" X

or

sudo find / -iname "error?log" 2>/dev/null | xargs -IX grep -iH "errorlog" X

Left padding a String with Zeros

An old question, but I also have two methods.


For a fixed (predefined) length:

    public static String fill(String text) {
        if (text.length() >= 10)
            return text;
        else
            return "0000000000".substring(text.length()) + text;
    }

For a variable length:

    public static String fill(String text, int size) {
        StringBuilder builder = new StringBuilder(text);
        while (builder.length() < size) {
            builder.append('0');
        }
        return builder.toString();
    }

Changing user agent on urllib2.urlopen

Setting the User-Agent from everyone's favorite Dive Into Python.

The short story: You can use Request.add_header to do this.

You can also pass the headers as a dictionary when creating the Request itself, as the docs note:

headers should be a dictionary, and will be treated as if add_header() was called with each key and value as arguments. This is often used to “spoof” the User-Agent header, which is used by a browser to identify itself – some HTTP servers only allow requests coming from common browsers as opposed to scripts. For example, Mozilla Firefox may identify itself as "Mozilla/5.0 (X11; U; Linux i686) Gecko/20071127 Firefox/2.0.0.11", while urllib2‘s default user agent string is "Python-urllib/2.6" (on Python 2.6).

Prevent wrapping of span or div

Looks like divs will not go outside of their body's width. Even within another div.

I threw this up to test (without a doctype though) and it does not work as thought.

_x000D_
_x000D_
.slideContainer {_x000D_
    overflow-x: scroll;_x000D_
}_x000D_
.slide {_x000D_
    float: left;_x000D_
}
_x000D_
<div class="slideContainer">_x000D_
    <div class="slide" style="background: #f00">Some content Some content Some content Some content Some content Some content</div>_x000D_
    <div class="slide" style="background: #ff0">More content More content More content More content More content More content</div>_x000D_
    <div class="slide" style="background: #f0f">Even More content! Even More content! Even More content!</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

What i am thinking is that the inner div's could be loaded through an iFrame, since that is another page and its content could be very wide.

How do I make a batch file terminate upon encountering an error?

We cannot always depend on ERRORLEVEL, because many times external programs or batch scripts do not return exit codes.

In that case we can use generic checks for failures like this:

IF EXIST %outfile% (DEL /F %outfile%)
CALL some_script.bat -o %outfile%
IF NOT EXIST %outfile%  (ECHO ERROR & EXIT /b)

And if the program outputs something to console, we can check it also.

some_program.exe 2>&1 | FIND "error message here" && (ECHO ERROR & EXIT /b)
some_program.exe 2>&1 | FIND "Done processing." || (ECHO ERROR & EXIT /b)

How to test for $null array in PowerShell

If your solution requires returning 0 instead of true/false, I've found this to be useful:

PS C:\> [array]$foo = $null
PS C:\> ($foo | Measure-Object).Count
0

This operation is different from the count property of the array, because Measure-Object is counting objects. Since there are none, it will return 0.

How to read the last row with SQL Server

If some of your id are in order, i am assuming there will be some order in your db

SELECT * FROM TABLE WHERE ID = (SELECT MAX(ID) FROM TABLE)

Rounded corner for textview in android

There is Two steps

1) Create this file in your drawable folder :- rounded_corner.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
         <corners android:radius="10dp" />  // set radius of corner
         <stroke android:width="2dp" android:color="#ff3478" /> // set color and width of border
         <solid android:color="#FFFFFF" /> // inner bgcolor
</shape>

2) Set this file into your TextView as background property.

android:background="@drawable/rounded_corner"

You can use this drawable in Button or Edittext also

Spring JPA and persistence.xml

Just to confirm though you probably did...

Did you include the

<!--  tell spring to use annotation based congfigurations -->
<context:annotation-config />
<!--  tell spring where to find the beans -->
<context:component-scan base-package="zz.yy.abcd" />

bits in your application context.xml?

Also I'm not so sure you'd be able to use a jta transaction type with this kind of setup? Wouldn't that require a data source managed connection pool? So try RESOURCE_LOCAL instead.

Converting an OpenCV Image to Black and White

Step-by-step answer similar to the one you refer to, using the new cv2 Python bindings:

1. Read a grayscale image

import cv2
im_gray = cv2.imread('grayscale_image.png', cv2.IMREAD_GRAYSCALE)

2. Convert grayscale image to binary

(thresh, im_bw) = cv2.threshold(im_gray, 128, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)

which determines the threshold automatically from the image using Otsu's method, or if you already know the threshold you can use:

thresh = 127
im_bw = cv2.threshold(im_gray, thresh, 255, cv2.THRESH_BINARY)[1]

3. Save to disk

cv2.imwrite('bw_image.png', im_bw)

How to add pandas data to an existing csv file?

with open(filename, 'a') as f:
    df.to_csv(f, header=f.tell()==0)
  • Create file unless exists, otherwise append
  • Add header if file is being created, otherwise skip it

Evaluate if list is empty JSTL

empty is an operator:

The empty operator is a prefix operation that can be used to determine whether a value is null or empty.

<c:if test="${empty myObject.featuresList}">

How to add text to a WPF Label in code?

You can use the Content property on pretty much all visual WPF controls to access the stuff inside them. There's a heirarchy of classes that the controls belong to, and any descendants of ContentControl will work in this way.

Difference between SelectedItem, SelectedValue and SelectedValuePath

SelectedItem is an object. SelectedValue and SelectedValuePath are strings.

for example using the ListBox:

if you say give me listbox1.SelectedValue it will return the text of the currently selected item.

string value = listbox1.SelectedValue;

if you say give me listbox1.SelectedItem it will give you the entire object.

ListItem item = listbox1.SelectedItem;
string value = item.value;

How to connect to SQL Server database from JavaScript in the browser?

You shouldn´t use client javascript to access databases for several reasons (bad practice, security issues, etc) but if you really want to do this, here is an example:

var connection = new ActiveXObject("ADODB.Connection") ;

var connectionstring="Data Source=<server>;Initial Catalog=<catalog>;User ID=<user>;Password=<password>;Provider=SQLOLEDB";

connection.Open(connectionstring);
var rs = new ActiveXObject("ADODB.Recordset");

rs.Open("SELECT * FROM table", connection);
rs.MoveFirst
while(!rs.eof)
{
   document.write(rs.fields(1));
   rs.movenext;
}

rs.close;
connection.close; 

A better way to connect to a sql server would be to use some server side language like PHP, Java, .NET, among others. Client javascript should be used only for the interfaces.

And there are rumors of an ancient legend about the existence of server javascript, but this is another story. ;)

How to capture multiple repeated groups?

Sorry, not Swift, just a proof of concept in the closest language at hand.

// JavaScript POC. Output:
// Matches:  ["GOODBYE","CRUEL","WORLD","IM","LEAVING","U","TODAY"]

let str = `GOODBYE,CRUEL,WORLD,IM,LEAVING,U,TODAY`
let matches = [];

function recurse(str, matches) {
    let regex = /^((,?([A-Z]+))+)$/gm
    let m
    while ((m = regex.exec(str)) !== null) {
        matches.unshift(m[3])
        return str.replace(m[2], '')
    }
    return "bzzt!"
}

while ((str = recurse(str, matches)) != "bzzt!") ;
console.log("Matches: ", JSON.stringify(matches))

Note: If you were really going to use this, you would use the position of the match as given by the regex match function, not a string replace.

What are the uses of the exec command in shell scripts?

Just to augment the accepted answer with a brief newbie-friendly short answer, you probably don't need exec.

If you're still here, the following discussion should hopefully reveal why. When you run, say,

sh -c 'command'

you run a sh instance, then start command as a child of that sh instance. When command finishes, the sh instance also finishes.

sh -c 'exec command'

runs a sh instance, then replaces that sh instance with the command binary, and runs that instead.

Of course, both of these are useless in this limited context; you simply want

command

There are some fringe situations where you want the shell to read its configuration file or somehow otherwise set up the environment as a preparation for running command. This is pretty much the sole situation where exec command is useful.

#!/bin/sh
ENVIRONMENT=$(some complex task)
exec command

This does some stuff to prepare the environment so that it contains what is needed. Once that's done, the sh instance is no longer necessary, and so it's a (minor) optimization to simply replace the sh instance with the command process, rather than have sh run it as a child process and wait for it, then exit as soon as it finishes.

Similarly, if you want to free up as much resources as possible for a heavyish command at the end of a shell script, you might want to exec that command as an optimization.

If something forces you to run sh but you really wanted to run something else, exec something else is of course a workaround to replace the undesired sh instance (like for example if you really wanted to run your own spiffy gosh instead of sh but yours isn't listed in /etc/shells so you can't specify it as your login shell).

The second use of exec to manipulate file descriptors is a separate topic. The accepted answer covers that nicely; to keep this self-contained, I'll just defer to the manual for anything where exec is followed by a redirect instead of a command name.

Renaming a branch in GitHub

On the Git branch, run:

git branch -m old_name  new_name

This will modify the branch name on your local repository:

git push origin :old_name new_name

This will push the modified name to the remote and delete the old branch:

git push origin -u new_name

It sets the local branch to track the remote branch.

This solves the issue.

SVG fill color transparency / alpha?

To make a fill completely transparent, fill="transparent" seems to work in modern browsers. But it didn't work in Microsoft Word (for Mac), I had to use fill-opacity="0".

Goal Seek Macro with Goal as a Formula

I think your issue is that Range("H18") doesn't contain a formula. Also, you could make your code more efficient by eliminating x. Instead, change your code to

Range("H18").GoalSeek Goal:=Range("H32").Value, ChangingCell:=Range("G18")

sqlalchemy: how to join several tables by one query?

A good style would be to setup some relations and a primary key for permissions (actually, usually it is good style to setup integer primary keys for everything, but whatever):

class User(Base):
    __tablename__ = 'users'
    email = Column(String, primary_key=True)
    name = Column(String)

class Document(Base):
    __tablename__ = "documents"
    name = Column(String, primary_key=True)
    author_email = Column(String, ForeignKey("users.email"))
    author = relation(User, backref='documents')

class DocumentsPermissions(Base):
    __tablename__ = "documents_permissions"
    id = Column(Integer, primary_key=True)
    readAllowed = Column(Boolean)
    writeAllowed = Column(Boolean)
    document_name = Column(String, ForeignKey("documents.name"))
    document = relation(Document, backref = 'permissions')

Then do a simple query with joins:

query = session.query(User, Document, DocumentsPermissions).join(Document).join(DocumentsPermissions)

git push >> fatal: no configured push destination

I have faced this error, Previous I had push in root directory, and now I have push another directory, so I could be remove this error and run below commands.

git add .
git commit -m "some comments"
git push --set-upstream origin master

'workbooks.worksheets.activate' works, but '.select' does not

You can't select a sheet in a non-active workbook.

You must first activate the workbook, then you can select the sheet.

workbooks("A").activate
workbooks("A").worksheets("B").select 

When you use Activate it automatically activates the workbook.

Note you can select >1 sheet in a workbook:

activeworkbook.sheets(array("sheet1","sheet3")).select

but only one sheet can be Active, and if you activate a sheet which is not part of a multi-sheet selection then those other sheets will become un-selected.

Reorder / reset auto increment primary key

This works - https://stackoverflow.com/a/5437720/10219008.....but if you run into an issue 'Error Code: 1265. Data truncated for column 'id' at row 1'...Then run the following. Adding ignore on the update query.

SET @count = 0;
set sql_mode = 'STRICT_ALL_TABLES';
UPDATE IGNORE web_keyword SET id = @count := (@count+1);

Object of custom type as dictionary key

An alternative in Python 2.6 or above is to use collections.namedtuple() -- it saves you writing any special methods:

from collections import namedtuple
MyThingBase = namedtuple("MyThingBase", ["name", "location"])
class MyThing(MyThingBase):
    def __new__(cls, name, location, length):
        obj = MyThingBase.__new__(cls, name, location)
        obj.length = length
        return obj

a = MyThing("a", "here", 10)
b = MyThing("a", "here", 20)
c = MyThing("c", "there", 10)
a == b
# True
hash(a) == hash(b)
# True
a == c
# False

Escape Character in SQL Server

You could use the **\** character before the value you want to escape e.g insert into msglog(recipient) values('Mr. O\'riely') select * from msglog where recipient = 'Mr. O\'riely'

python JSON only get keys in first level

As Karthik mentioned, dct.keys() will work but it will return all the keys in dict_keys type not in list type. So if you want all the keys in a list, then list(dct.keys()) will work.

How to create PDFs in an Android app?

PDFJet offers an open-source version of their library that should be able to handle any basic PDF generation task. It's a purely Java-based solution and it is stated to be compatible with Android. There is a commercial version with some additional features that does not appear to be too expensive.

This could be due to the service endpoint binding not using the HTTP protocol

This could be due to many reasons; below are few of those:

  1. If you are using complex data contract objects(that means custom object with more child custom objects), make sure you have all the custom objects decorated with DataContract and DataMember attributes
  2. If your data contract objects use inheritance, make sure all base classes has the DataContract and DataMember attributes. Also, you need to have the base classes specify the derived classes with the [KnownType(typeof(BaseClassType))] attribute ( check out more info here on this).

  3. Make sure all your data contract object properties have both get and set properties.

How to add minutes to current time in swift

I think the simplest will be

let minutes = Date(timeIntervalSinceNow:(minutes * 60.0))

using CASE in the WHERE clause

This is working Oracle example but it should work in MySQL too.

You are missing smth - see IN after END Replace 'IN' with '=' sign for a single value.

SELECT empno, ename, job
  FROM scott.emp
 WHERE (CASE WHEN job = 'MANAGER' THEN '1'  
         WHEN job = 'CLERK'   THEN '2' 
         ELSE '0'  END) IN (1, 2)

Android - How To Override the "Back" button so it doesn't Finish() my Activity?

@Override
public void onBackPressed() {
// Put your code here.
}

//I had to go back to the dashboard. Hence,

@Override
public void onBackPressed() {
    Intent intent = new Intent(this,Dashboard.class);
    startActivity(intent);
}
Just write this above or below the onCreate Method(within the class)

Return back to MainActivity from another activity

why don't you call finish();

when you want to return to MainActivity

   btnReturn1.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        finish();
    }
});

Command-line Tool to find Java Heap Size and Memory Used (Linux)?

This command shows the configured heap sizes in bytes.

java -XX:+PrintFlagsFinal -version | grep HeapSize

It works on Amazon AMI on EC2 as well.

How to disable HTML links

In Razor (.cshtml) you can do:

@{
    var isDisabled = true;
}

<a href="@(isDisabled ? "#" : @Url.Action("Index", "Home"))" @(isDisabled ? "disabled=disabled" : "") class="btn btn-default btn-lg btn-block">Home</a>

How to append text to a text file in C++?

You could use an fstream and open it with the std::ios::app flag. Have a look at the code below and it should clear your head.

...
fstream f("filename.ext", f.out | f.app);
f << "any";
f << "text";
f << "written";
f << "wll";
f << "be append";
...

You can find more information about the open modes here and about fstreams here.

Magento Product Attribute Get Value

This one works-

echo $_product->getData('ATTRIBUTE_NAME_HERE');

Cron and virtualenv

I've added the following script as manage.sh inside my Django project, it sources the virtualenv and then runs the manage.py script with whatever arguments you pass to it. It makes it very easy in general to run commands inside the virtualenv (cron, systemd units, basically anywhere):

#! /bin/bash

# this is a convenience script that first sources the venv (assumed to be in
# ../venv) and then executes manage.py with whatever arguments you supply the
# script with. this is useful if you need to execute the manage.py from
# somewhere where the venv isn't sourced (e.g. system scripts)

# get the script's location
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"

# source venv <- UPDATE THE PATH HERE WITH YOUR VENV's PATH
source $DIR/../venv/bin/activate

# run manage.py script
$DIR/manage.py "$@"

Then in your cron entry you can just run:

0 3 * * * /home/user/project/manage.sh command arg

Just remember that you need to make the manage.sh script executable

SQL Server query - Selecting COUNT(*) with DISTINCT

You have to create a derived table for the distinct columns and then query the count from that table:

SELECT COUNT(*) 
FROM (SELECT DISTINCT column1,column2
      FROM  tablename  
      WHERE condition ) as dt

Here dt is a derived table.

How do I correctly use "Not Equal" in MS Access?

I have struggled to get a query to return fields from Table 1 that do not exist in Table 2 and tried most of the answers above until I found a very simple way to obtain the results that I wanted.

I set the join properties between table 1 and table 2 to the third setting (3) (All fields from Table 1 and only those records from Table 2 where the joined fields are equal) and placed a Is Null in the criteria field of the query in Table 2 in the field that I was testing for. It works perfectly.

Thanks to all above though.

How to pick an image from gallery (SD Card) for my app?

#initialize in main activity 
    path = Environment.getExternalStorageDirectory()
            + "/images/make_machine_example.jpg"; #
     ImageView image=(ImageView)findViewById(R.id.image);
 //--------------------------------------------------||

 public void FromCamera(View) {

    Log.i("camera", "startCameraActivity()");
    File file = new File(path);
    Uri outputFileUri = Uri.fromFile(file);
    Intent intent = new Intent(
            android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
    intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
    startActivityForResult(intent, 1);

}

public void FromCard() {
    Intent i = new Intent(Intent.ACTION_PICK,
            android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    startActivityForResult(i, 2);
}

 protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == 2 && resultCode == RESULT_OK
            && null != data) {

        Uri selectedImage = data.getData();
        String[] filePathColumn = { MediaStore.Images.Media.DATA };

        Cursor cursor = getContentResolver().query(selectedImage,
                filePathColumn, null, null, null);
        cursor.moveToFirst();

        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        String picturePath = cursor.getString(columnIndex);
        cursor.close();

        bitmap = BitmapFactory.decodeFile(picturePath);
        image.setImageBitmap(bitmap);

        if (bitmap != null) {
            ImageView rotate = (ImageView) findViewById(R.id.rotate);

        }

    } else {

        Log.i("SonaSys", "resultCode: " + resultCode);
        switch (resultCode) {
        case 0:
            Log.i("SonaSys", "User cancelled");
            break;
        case -1:
            onPhotoTaken();
            break;

        }

    }

}

protected void onPhotoTaken() {
    // Log message
    Log.i("SonaSys", "onPhotoTaken");
    taken = true;
    imgCapFlag = true;
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inSampleSize = 4;
    bitmap = BitmapFactory.decodeFile(path, options);
    image.setImageBitmap(bitmap);


}

Stack Memory vs Heap Memory

In C++ the stack memory is where local variables get stored/constructed. The stack is also used to hold parameters passed to functions.

The stack is very much like the std::stack class: you push parameters onto it and then call a function. The function then knows that the parameters it expects can be found on the end of the stack. Likewise, the function can push locals onto the stack and pop them off it before returning from the function. (caveat - compiler optimizations and calling conventions all mean things aren't this simple)

The stack is really best understood from a low level and I'd recommend Art of Assembly - Passing Parameters on the Stack. Rarely, if ever, would you consider any sort of manual stack manipulation from C++.

Generally speaking, the stack is preferred as it is usually in the CPU cache, so operations involving objects stored on it tend to be faster. However the stack is a limited resource, and shouldn't be used for anything large. Running out of stack memory is called a Stack buffer overflow. It's a serious thing to encounter, but you really shouldn't come across one unless you have a crazy recursive function or something similar.

Heap memory is much as rskar says. In general, C++ objects allocated with new, or blocks of memory allocated with the likes of malloc end up on the heap. Heap memory almost always must be manually freed, though you should really use a smart pointer class or similar to avoid needing to remember to do so. Running out of heap memory can (will?) result in a std::bad_alloc.

Adding attribute in jQuery

This could be more helpfull....

$("element").prop("id", "modifiedId");
//for boolean
$("element").prop("disabled", true);
//also you can remove attribute
$('#someid').removeProp('disabled');

How can I determine the URL that a local Git repository was originally cloned from?

I prefer this one as it is easier to remember:

git config -l

It will list all useful information such as:

user.name=Your Name
[email protected]
core.autocrlf=input
core.repositoryformatversion=0
core.filemode=true
core.bare=false
core.logallrefupdates=true
remote.origin.url=https://github.com/mapstruct/mapstruct-examples
remote.origin.fetch=+refs/heads/*:refs/remotes/origin/*
branch.master.remote=origin
branch.master.merge=refs/heads/master

Python; urllib error: AttributeError: 'bytes' object has no attribute 'read'

Use json.loads not json.load.

(load loads from a file-like object, loads from a string. So you could just as well omit the .read() call instead.)

How to set headers in http get request?

Pay attention that in http.Request header "Host" can not be set via Set method

req.Header.Set("Host", "domain.tld")

but can be set directly:

req.Host = "domain.tld":

req, err := http.NewRequest("GET", "http://10.0.0.1/", nil)
if err != nil {
    ...
}

req.Host = "domain.tld"
client := &http.Client{}
resp, err := client.Do(req)

invalid use of non-static data member

You try to access private member of one class from another. The fact that bar-class is declared within foo-class means that bar in visible only inside foo class, but that is still other class.

And what is p->param?

Actually, it isn't clear what do you want to do

"Integer number too large" error message for 600851475143

You need to use a long literal:

obj.function(600851475143l);  // note the "l" at the end

But I would expect that function to run out of memory (or time) ...

No default constructor found; nested exception is java.lang.NoSuchMethodException with Spring MVC?

You must have to define no-args or default constructor if you are creating your own constructor.

You can read why default or no argument constructor is required.

why-default-or-no-argument-constructor-java-class.html

How to get primary key column in Oracle?

Select constraint_name,constraint_type from user_constraints where table_name** **= ‘TABLE_NAME’ ;

(This will list the primary key and then)

Select column_name,position from user_cons_cloumns where constraint_name=’PK_XYZ’; 

(This will give you the column, here PK_XYZ is the primay key name)

How can I add a hint or tooltip to a label in C# Winforms?

Just to share my idea...

I created a custom class to inherit the Label class. I added a private variable assigned as a Tooltip class and a public property, TooltipText. Then, gave it a MouseEnter delegate method. This is an easy way to work with multiple Label controls and not have to worry about assigning your Tooltip control for each Label control.

    public partial class ucLabel : Label
    {
        private ToolTip _tt = new ToolTip();

        public string TooltipText { get; set; }

        public ucLabel() : base() {
            _tt.AutoPopDelay = 1500;
            _tt.InitialDelay = 400;
//            _tt.IsBalloon = true;
            _tt.UseAnimation = true;
            _tt.UseFading = true;
            _tt.Active = true;
            this.MouseEnter += new EventHandler(this.ucLabel_MouseEnter);
        }

        private void ucLabel_MouseEnter(object sender, EventArgs ea)
        {
            if (!string.IsNullOrEmpty(this.TooltipText))
            {
                _tt.SetToolTip(this, this.TooltipText);
                _tt.Show(this.TooltipText, this.Parent);
            }
        }
    }

In the form or user control's InitializeComponent method (the Designer code), reassign your Label control to the custom class:

this.lblMyLabel = new ucLabel();

Also, change the private variable reference in the Designer code:

private ucLabel lblMyLabel;

How to select following sibling/xml tag using xpath

How would I accomplish the nextsibling and is there an easier way of doing this?

You may use:

tr/td[@class='name']/following-sibling::td

but I'd rather use directly:

tr[td[@class='name'] ='Brand']/td[@class='desc']

This assumes that:

  1. The context node, against which the XPath expression is evaluated is the parent of all tr elements -- not shown in your question.

  2. Each tr element has only one td with class attribute valued 'name' and only one td with class attribute valued 'desc'.

What regular expression will match valid international phone numbers?

Try this, I do not know if there is any phone number longer than 12:

^(00|\+){1}\d{12}$

Refused to display 'url' in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'

I think You are trying to use the normal URL of video Like this :

Copying Direct URL from YouTube

That doesn't let you display the content on other domains.To Tackle this up , You should use the Copy Embed Code feature provided by the YouTube itself .Like this :

Copy Embed Code ( YouTube )

That would free you up from any issues .

For the above Scenario :

  • Go to Youtube Video

  • Copy Embed Code

  • Paste that into your Code ( Make sure you Escape all the " ( Inverted Commas) by \" .

Enable the display of line numbers in Visual Studio

For MS Visual Studio 2015 type "Text" in Quick Launch (Ctrl+Q) of top right corner. 1) quicklaunch

2) In the list select Text Editor->All Languages->General select_allLanguages

3) Now check on "Line Numbers" and click OK to get the line numbers.

Finally we get the line number in text editor.

How to undo last commit

Warning: Don't do this if you've already pushed

You want to do:

git reset HEAD~

If you don't want the changes and blow everything away:

git reset --hard HEAD~

Formatting Phone Numbers in PHP

This function will format international (10+ digit), non-international (10 digit) or old school (7 digit) phone numbers. Any numbers other than 10+, 10 or 7 digits will remain unformatted.

function formatPhoneNumber($phoneNumber) {
    $phoneNumber = preg_replace('/[^0-9]/','',$phoneNumber);

    if(strlen($phoneNumber) > 10) {
        $countryCode = substr($phoneNumber, 0, strlen($phoneNumber)-10);
        $areaCode = substr($phoneNumber, -10, 3);
        $nextThree = substr($phoneNumber, -7, 3);
        $lastFour = substr($phoneNumber, -4, 4);

        $phoneNumber = '+'.$countryCode.' ('.$areaCode.') '.$nextThree.'-'.$lastFour;
    }
    else if(strlen($phoneNumber) == 10) {
        $areaCode = substr($phoneNumber, 0, 3);
        $nextThree = substr($phoneNumber, 3, 3);
        $lastFour = substr($phoneNumber, 6, 4);

        $phoneNumber = '('.$areaCode.') '.$nextThree.'-'.$lastFour;
    }
    else if(strlen($phoneNumber) == 7) {
        $nextThree = substr($phoneNumber, 0, 3);
        $lastFour = substr($phoneNumber, 3, 4);

        $phoneNumber = $nextThree.'-'.$lastFour;
    }

    return $phoneNumber;
}

Passing variable number of arguments around

You can use inline assembly for the function call. (in this code I assume the arguments are characters).

void format_string(char *fmt, ...);
void debug_print(int dbg_level, int numOfArgs, char *fmt, ...)
    {
        va_list argumentsToPass;
        va_start(argumentsToPass, fmt);
        char *list = new char[numOfArgs];
        for(int n = 0; n < numOfArgs; n++)
            list[n] = va_arg(argumentsToPass, char);
        va_end(argumentsToPass);
        for(int n = numOfArgs - 1; n >= 0; n--)
        {
            char next;
            next = list[n];
            __asm push next;
        }
        __asm push fmt;
        __asm call format_string;
        fprintf(stdout, fmt);
    }

Xampp-mysql - "Table doesn't exist in engine" #1932

I have faced same issue and sorted using below step.

  1. Go to MySQL config file (my file at C:\xampp\mysql\bin\my.ini)
  2. Check for the line innodb_data_file_path = ibdata1:10M:autoextend
  3. Next check the ibdata1 file exist under C:/xampp/mysql/data/
  4. If file does not exist copy the ibdata1 file from location C:\xampp\mysql\backup\ibdata1

hope it helps to someone.

How to capture a backspace on the onkeydown event

Nowadays, code to do this should look something like:

document.getElementById('foo').addEventListener('keydown', function (event) {
    if (event.keyCode == 8) {
        console.log('BACKSPACE was pressed');

        // Call event.preventDefault() to stop the character before the cursor
        // from being deleted. Remove this line if you don't want to do that.
        event.preventDefault();
    }
    if (event.keyCode == 46) {
        console.log('DELETE was pressed');

        // Call event.preventDefault() to stop the character after the cursor
        // from being deleted. Remove this line if you don't want to do that.
        event.preventDefault();
    }
});

although in the future, once they are broadly supported in browsers, you may want to use the .key or .code attributes of the KeyboardEvent instead of the deprecated .keyCode.

Details worth knowing:

  • Calling event.preventDefault() in the handler of a keydown event will prevent the default effects of the keypress. When pressing a character, this stops it from being typed into the active text field. When pressing backspace or delete in a text field, it prevents a character from being deleted. When pressing backspace without an active text field, in a browser like Chrome where backspace takes you back to the previous page, it prevents that behaviour (as long as you catch the event by adding your event listener to document instead of a text field).

  • Documentation on how the value of the keyCode attribute is determined can be found in section B.2.1 How to determine keyCode for keydown and keyup events in the W3's UI Events Specification. In particular, the codes for Backspace and Delete are listed in B.2.3 Fixed virtual key codes.

  • There is an effort underway to deprecate the .keyCode attribute in favour of .key and .code. The W3 describe the .keyCode property as "legacy", and MDN as "deprecated".

    One benefit of the change to .key and .code is having more powerful and programmer-friendly handling of non-ASCII keys - see the specification that lists all the possible key values, which are human-readable strings like "Backspace" and "Delete" and include values for everything from modifier keys specific to Japanese keyboards to obscure media keys. Another, which is highly relevant to this question, is distinguishing between the meaning of a modified keypress and the physical key that was pressed.

    On small Mac keyboards, there is no Delete key, only a Backspace key. However, pressing Fn+Backspace is equivalent to pressing Delete on a normal keyboard - that is, it deletes the character after the text cursor instead of the one before it. Depending upon your use case, in code you might want to handle a press of Backspace with Fn held down as either Backspace or Delete. That's why the new key model lets you choose.

    The .key attribute gives you the meaning of the keypress, so Fn+Backspace will yield the string "Delete". The .code attribute gives you the physical key, so Fn+Backspace will still yield the string "Backspace".

    Unfortunately, as of writing this answer, they're only supported in 18% of browsers, so if you need broad compatibility you're stuck with the "legacy" .keyCode attribute for the time being. But if you're a reader from the future, or if you're targeting a specific platform and know it supports the new interface, then you could write code that looked something like this:

    document.getElementById('foo').addEventListener('keydown', function (event) {
        if (event.code == 'Delete') {
            console.log('The physical key pressed was the DELETE key');
        }
        if (event.code == 'Backspace') {
            console.log('The physical key pressed was the BACKSPACE key');
        } 
        if (event.key == 'Delete') {
            console.log('The keypress meant the same as pressing DELETE');
            // This can happen for one of two reasons:
            // 1. The user pressed the DELETE key
            // 2. The user pressed FN+BACKSPACE on a small Mac keyboard where
            //    FN+BACKSPACE deletes the character in front of the text cursor,
            //    instead of the one behind it.
        }
        if (event.key == 'Backspace') {
            console.log('The keypress meant the same as pressing BACKSPACE');
        }
    });
    

Folder is locked and I can't unlock it

I research a lot on this issue but no solution fix my problem until I try this:

My repo folder is shared with a Windows xp virtual machine, so I execute the clean up from the VM and then execute SVN UPDATE from the host.

It worked for me.

Greetings from Costa Rica.

Android button onClickListener

Use OnClicklistener or you can use android:onClick="myMethod" in your button's xml code from which you going to open a new layout. So when that button is clicked your myMethod function will be called automatically. Your myMethod function in class look like this.

public void myMethod(View v) {
Intent intent=new Intent(context,SecondActivty.class);
startActivity(intent);
}

And in that SecondActivity.class set new layout in contentview.

Set default option in mat-select

Try this

<mat-form-field>
    <mat-select [(ngModel)]="modeselect" [placeholder]="modeselect">
        <mat-option value="domain">Domain</mat-option>
        <mat-option value="exact">Exact</mat-option>
    </mat-select>
</mat-form-field>

Component:

export class SelectValueBindingExample {
    public modeselect = 'Domain';
}

Live demo

Also, don't forget to import FormsModule in your app.module

Executable directory where application is running from?

I needed to know this and came here, before I remembered the Environment class.

In case anyone else had this issue, just use this: Environment.CurrentDirectory.

Example:

Dim dataDirectory As String = String.Format("{0}\Data\", Environment.CurrentDirectory)

When run from Visual Studio in debug mode yeilds:

C:\Development\solution folder\application folder\bin\debug

This is the exact behaviour I needed, and its simple and straightforward enough.

How to add a local repo and treat it as a remote repo

You have your arguments to the remote add command reversed:

git remote add <NAME> <PATH>

So:

git remote add bak /home/sas/dev/apps/smx/repo/bak/ontologybackend/.git

See git remote --help for more information.

SyntaxError: missing ) after argument list

For me, once there was a mistake in spelling of function

For e.g. instead of

$(document).ready(function(){

});

I wrote

$(document).ready(funciton(){

});

So keep that also in check

How to use execvp()

In cpp, you need to pay special attention to string types when using execvp:

#include <iostream>
#include <string>
#include <cstring>
#include <stdio.h>
#include <unistd.h>
using namespace std;

const size_t MAX_ARGC = 15; // 1 command + # of arguments
char* argv[MAX_ARGC + 1]; // Needs +1 because of the null terminator at the end
// c_str() converts string to const char*, strdup converts const char* to char*
argv[0] = strdup(command.c_str());

// start filling up the arguments after the first command
size_t arg_i = 1;
while (cin && arg_i < MAX_ARGC) {
    string arg;
    cin >> arg;
    if (arg.empty()) {
        argv[arg_i] = nullptr;
        break;
    } else {
        argv[arg_i] = strdup(arg.c_str());
    }
    ++arg_i;
}

// Run the command with arguments
if (execvp(command.c_str(), argv) == -1) {
    // Print error if command not found
    cerr << "command '" << command << "' not found\n";
}

Reference: execlp?execvp?????

Sort a list alphabetically

You can sort a list in-place just by calling List<T>.Sort:

list.Sort();

That will use the natural ordering of elements, which is fine in your case.

EDIT: Note that in your code, you'd need

_details.Sort();

as the Sort method is only defined in List<T>, not IList<T>. If you need to sort it from the outside where you don't have access to it as a List<T> (you shouldn't cast it as the List<T> part is an implementation detail) you'll need to do a bit more work.

I don't know of any IList<T>-based in-place sorts in .NET, which is slightly odd now I come to think of it. IList<T> provides everything you'd need, so it could be written as an extension method. There are lots of quicksort implementations around if you want to use one of those.

If you don't care about a bit of inefficiency, you could always use:

public void Sort<T>(IList<T> list)
{
    List<T> tmp = new List<T>(list);
    tmp.Sort();
    for (int i = 0; i < tmp.Count; i++)
    {
        list[i] = tmp[i];
    }
}

In other words, copy, sort in place, then copy the sorted list back.


You can use LINQ to create a new list which contains the original values but sorted:

var sortedList = list.OrderBy(x => x).ToList();

It depends which behaviour you want. Note that your shuffle method isn't really ideal:

  • Creating a new Random within the method runs into some of the problems shown here
  • You can declare val inside the loop - you're not using that default value
  • It's more idiomatic to use the Count property when you know you're working with an IList<T>
  • To my mind, a for loop is simpler to understand than traversing the list backwards with a while loop

There are other implementations of shuffling with Fisher-Yates on Stack Overflow - search and you'll find one pretty quickly.

Sql Server 'Saving changes is not permitted' error ? Prevent saving changes that require table re-creation

If you can not see the "Prevent saving changes that required table re-creation" in list like that The image

You need to enable change tracking.

  • Right click on your database and click Properties
  • Click change tracking and make it enable
  • Go Tools -> Options -> Designer again and uncheck it.

What is a Sticky Broadcast?

If an Activity calls onPause with a normal broadcast, receiving the Broadcast can be missed. A sticky broadcast can be checked after it was initiated in onResume.

Update 6/23/2020

Sticky broadcasts are deprecated.

See sendStickyBroadcast documentation.

This method was deprecated in API level 21.

Sticky broadcasts should not be used. They provide no security (anyone can access them), no protection (anyone can modify them), and many other problems. The recommended pattern is to use a non-sticky broadcast to report that something has changed, with another mechanism for apps to retrieve the current value whenever desired.

Implement

Intent intent = new Intent("some.custom.action");
intent.putExtra("some_boolean", true);
sendStickyBroadcast(intent);

Resources

Can not deserialize instance of java.util.ArrayList out of VALUE_STRING

from Jackson 2.7.x+ there is a way to annotate the member variable itself:

 @JsonFormat(with = JsonFormat.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY)
 private List<String> newsletters;

More info here: Jackson @JsonFormat

HTML Tags in Javascript Alert() method

alert() is a method of the window object that cannot interpret HTML tags

What is the difference between smoke testing and sanity testing?

Smoke and sanity testing

In general, smoke and sanity testing seems very similar to many tester who have just started, because in both we talk about build, we talk about functionality and we talk about the rejection of builds, if build's health is not good for the feasible testing.

After going through several projects, from start ups to product base company, I figured out the basic difference between smoke and sanity testing.

I am writing difference between smoke testing and sanity testing here to help you in answering at least one question that normally all testers get asked in interview.

Smoke testing

  • Smoke testing is done to test the health of builds.

  • It is also known as the shallow and wide testing, in that we normally include those test cases which can cover all the functionality of the product.

  • We can say that it's the first step of testing and, after this, we normally do other kind of functional and system testing, including regression testing.

  • It's normally done by a developer with the help of certain scripts or certain tools, but in some cases it can be performed by a tester too.

  • It's valid for initial stage of a build confirmation. For example, suppose we have started the development of a certain product, and we are producing a build for the first time, then smoke testing becomes a necessity for the product.

Sanity testing

  • It is sub-regression

  • Sanity is done for those builds which have gone through many regression tests and a minor change in code has happened. In this case, we normally do the intensive testing of functionalities where this change has occurred or may have influenced.

    • Due to this, it is also known as "narrow" and "deep" testing
  • It's performed by a tester

  • It's done for mature builds, like those that are just going to hit production, and have gone through multiple regression processes.

  • It can be removed from the testing process, if regression is already being performed.

  • If any build doesn't pass the sanity tests, then it is thrown to developer back for the correction of the build.

What is the meaning of the prefix N in T-SQL statements and when should I use it?

Let me tell you an annoying thing that happened with the N' prefix - I wasn't able to fix it for two days.

My database collation is SQL_Latin1_General_CP1_CI_AS.

It has a table with a column called MyCol1. It is an Nvarchar

This query fails to match Exact Value That Exists.

SELECT TOP 1 * FROM myTable1 WHERE  MyCol1 = 'ESKI'  

// 0 result

using prefix N'' fixes it

SELECT TOP 1 * FROM myTable1 WHERE  MyCol1 = N'ESKI'  

// 1 result - found!!!!

Why? Because latin1_general doesn't have big dotted I that's why it fails I suppose.

Angular 4: How to include Bootstrap?

|*| Installing Bootstrap 4 for Angular 2, 4, 5, 6 + :

|+> Install Bootstrap with npm

npm install bootstrap --save

npm install popper.js --save

|+> Add styles and scripts to angular.json

"architect": [{
    ...
    "styles": [
        "node_modules/bootstrap/dist/css/bootstrap.min.css",
        "src/styles.scss"
    ],
    "scripts": [
        "node_modules/jquery/dist/jquery.js",
        "node_modules/popper.js/dist/umd/popper.min.js",
        "node_modules/bootstrap/dist/js/bootstrap.min.js"
    ]
    ...
}]

Request string without GET arguments

$uri_parts = explode('?', $_SERVER['REQUEST_URI'], 2);
$request_uri = $uri_parts[0];
echo $request_uri;

JSON and escaping characters

This is not a bug in either implementation. There is no requirement to escape U+00B0. To quote the RFC:

2.5. Strings

The representation of strings is similar to conventions used in the C family of programming languages. A string begins and ends with quotation marks. All Unicode characters may be placed within the quotation marks except for the characters that must be escaped: quotation mark, reverse solidus, and the control characters (U+0000 through U+001F).

Any character may be escaped.

Escaping everything inflates the size of the data (all code points can be represented in four or fewer bytes in all Unicode transformation formats; whereas encoding them all makes them six or twelve bytes).

It is more likely that you have a text transcoding bug somewhere in your code and escaping everything in the ASCII subset masks the problem. It is a requirement of the JSON spec that all data use a Unicode encoding.

Copy or rsync command

The command as written will create new directories and files with the current date and time stamp, and yourself as the owner. If you are the only user on your system and you are doing this daily it may not matter much. But if preserving those attributes matters to you, you can modify your command with

cp -pur /home/abc/* /mnt/windowsabc/

The -p will preserve ownership, timestamps, and mode of the file. This can be pretty important depending on what you're backing up.

The alternative command with rsync would be

rsync -avh /home/abc/* /mnt/windowsabc

With rsync, -a indicates "archive" which preserves all those attributes mentioned above. -v indicates "verbose" which just lists what it's doing with each file as it runs. -z is left out here for local copies, but is for compression, which will help if you are backing up over a network. Finally, the -h tells rsync to report sizes in human-readable formats like MB,GB,etc.

Out of curiosity, I ran one copy to prime the system and avoid biasing against the first run, then I timed the following on a test run of 1GB of files from an internal SSD drive to a USB-connected HDD. These simply copied to empty target directories.

cp -pur    : 19.5 seconds
rsync -ah  : 19.6 seconds
rsync -azh : 61.5 seconds

Both commands seem to be about the same, although zipping and unzipping obviously tax the system where bandwidth is not a bottleneck.

Normalize columns of pandas data frame

If your data is positively skewed, the best way to normalize is to use the log transformation:

df = np.log10(df)

React - How to force a function component to render?

The accepted answer is good. Just to make it easier to understand.

Example component:

export default function MyComponent(props) {

    const [updateView, setUpdateView] = useState(0);

    return (
        <>
            <span style={{ display: "none" }}>{updateView}</span>
        </>
    );
}

To force re-rendering call the code below:

setUpdateView((updateView) => ++updateView);

How to create a link to a directory

you should use :

ln -s /home/jake/doc/test/2000/something xxx

How to return multiple objects from a Java method?

public class MultipleReturnValues {

    public MultipleReturnValues() {
    }

    public static void functionWithSeveralReturnValues(final String[] returnValues) {
        returnValues[0] = "return value 1";
        returnValues[1] = "return value 2";
    }

    public static void main(String[] args) {
        String[] returnValues = new String[2];
        functionWithSeveralReturnValues(returnValues);
        System.out.println("returnValues[0] = " + returnValues[0]);
        System.out.println("returnValues[1] = " + returnValues[1]);
    }

}

How to manually include external aar package using new Gradle Android Build System

I tried all solution here but none is working, then I realise I made a mistake, I put the .aar in wrong folder, as you can see below, I thought I should put in root folder, so I created a libs folder there (1 in picture), but inside the app folder, there is already a libs, you should put in second libs, hope this help those who has same issue as mine:

enter image description here

How to create a simple proxy in C#?

Agree to dr evil if you use HTTPListener you will have many problems, you have to parse requests and will be engaged to headers and ...

  1. Use tcp listener to listen to browser requests
  2. parse only the first line of the request and get the host domain and port to connect
  3. send the exact raw request to the found host on the first line of browser request
  4. receive the data from the target site(I have problem in this section)
  5. send the exact data received from the host to the browser

you see you dont need to even know what is in the browser request and parse it, only get the target site address from the first line first line usually likes this GET http://google.com HTTP1.1 or CONNECT facebook.com:443 (this is for ssl requests)

How can I change the default width of a Twitter Bootstrap modal box?

Add the following on your css file

.popover{
         width:auto !important; 
         max-width:445px !important; 
         min-width:200px !important;
       }

The data-toggle attributes in Twitter Bootstrap

Here you can also find more examples for values that data-toggle can have assigned. Just visit the page and then CTRL+F to search for data-toggle.

iPhone system font

Swift

Specific font

Setting a specific font in Swift is done like this:

let myFont = UIFont(name: "Helvetica", size: 17)

If you don't know the name, you can get a list of the available font names like this:

print(UIFont.familyNames())

Or an even more detailed list like this:

for familyName in UIFont.familyNames() {
    print(UIFont.fontNamesForFamilyName(familyName))
}

But the system font changes from version to version of iOS. So it would be better to get the system font dynamically.

System font

let myFont = UIFont.systemFontOfSize(17)

But we have the size hard-coded in. What if the user's eyes are bad and they want to make the font larger? Of course, you could make a setting in your app for the user to change the font size, but this would be annoying if the user had to do this separately for every single app on their phone. It would be easier to just make one change in the general settings...

Dynamic font

let myFont = UIFont.preferredFont(forTextStyle: .body)

Ah, now we have the system font at the user's chosen size for the Text Style we are working with. This is the recommended way of setting the font. See Supporting Dynamic Type for more info on this.

Related

How can I view the contents of an ElasticSearch index?

You can even add the size of the terms (indexed terms). Have a look at Elastic Search: how to see the indexed data

TypeError: 'DataFrame' object is not callable

It seems you need DataFrame.var:

Normalized by N-1 by default. This can be changed using the ddof argument

var1 = credit_card.var()

Sample:

#random dataframe
np.random.seed(100)
credit_card = pd.DataFrame(np.random.randint(10, size=(5,5)), columns=list('ABCDE'))
print (credit_card)
   A  B  C  D  E
0  8  8  3  7  7
1  0  4  2  5  2
2  2  2  1  0  8
3  4  0  9  6  2
4  4  1  5  3  4

var1 = credit_card.var()
print (var1)
A     8.8
B    10.0
C    10.0
D     7.7
E     7.8
dtype: float64

var2 = credit_card.var(axis=1)
print (var2)
0     4.3
1     3.8
2     9.8
3    12.2
4     2.3
dtype: float64

If need numpy solutions with numpy.var:

print (np.var(credit_card.values, axis=0))
[ 7.04  8.    8.    6.16  6.24]

print (np.var(credit_card.values, axis=1))
[ 3.44  3.04  7.84  9.76  1.84]

Differences are because by default ddof=1 in pandas, but you can change it to 0:

var1 = credit_card.var(ddof=0)
print (var1)
A    7.04
B    8.00
C    8.00
D    6.16
E    6.24
dtype: float64

var2 = credit_card.var(ddof=0, axis=1)
print (var2)
0    3.44
1    3.04
2    7.84
3    9.76
4    1.84
dtype: float64

Modify SVG fill color when being served as Background-Image

Now you can achieve this on the client side like this:

var green = '3CB54A';
var red = 'ED1F24';
var svg = '<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"  width="320px" height="100px" viewBox="0 0 320 100" enable-background="new 0 0 320 100" xml:space="preserve"> <polygon class="mystar" fill="#'+green+'" points="134.973,14.204 143.295,31.066 161.903,33.77 148.438,46.896 151.617,65.43 134.973,56.679 118.329,65.43 121.507,46.896 108.042,33.77 126.65,31.066 "/><circle class="mycircle" fill="#'+red+'" cx="202.028" cy="58.342" r="12.26"/></svg>';      
var encoded = window.btoa(svg);
document.body.style.background = "url(data:image/svg+xml;base64,"+encoded+")";

Fiddle here!

OnclientClick and OnClick is not working at the same time?

There are two issues here:

Disabling the button on the client side prevents the postback

To overcome this, disable the button after the JavaScript onclick event. An easy way to do this is to use setTimeout as suggested by this answer.

Also, the OnClientClick code runs even if ASP.NET validation fails, so it's probably a good idea to add a check for Page_IsValid. This ensures that the button will not be disabled if validation fails.

OnClientClick="(function(button) { setTimeout(function () { if (Page_IsValid) button.disabled = true; }, 0); })(this);"

It's neater to put all of this JavaScript code in its own function as the question shows:

OnClientClick="disable(this);"

function disable(button) {
    setTimeout(function () {
        if (Page_IsValid)
            button.disabled = true;
    }, 0);
}

Disabling the button on the client side doesn't disable it on the server side

To overcome this, disable the button on the server side. For example, in the OnClick event handler:

OnClick="Button1_Click"

protected void Button1_Click(object sender, EventArgs e)
{
    ((Button)sender).Enabled = false;
}

Lastly, keep in mind that preventing duplicate button presses doesn't prevent two different users from submitting the same data at the same time. Make sure to account for that on the server side.

Want to show/hide div based on dropdown box selection

you have error in your code unexpected token.use:

  $('#purpose').on('change', function () {
   if (this.value == '1') {
    $("#business").show();
    } else {
    $("#business").hide();
   }

   });

Demo

Update: You can narrow down the code using .toggle()

 $('#purpose').on('change', function () {
   $("#business").toggle(this.value == '1');
 });

jQuery Set Select Index

# Set element with index
$("#select option:eq(2)").attr("selected", "selected");

# Set element by text
$("#select").val("option Text").attr("selected", "selected");

when you want to select with top ways for set selection , you can use
$('#select option').removeAttr('selected'); for remove previous selects .

# Set element by value
$("#select").val("2");

# Get selected text
$("#select").children("option:selected").text();  # use attr() for get attributes
$("#select option:selected").text(); # use attr() for get attributes 

# Get selected value
$("#select option:selected").val();
$("#select").children("option:selected").val();
$("#select option:selected").prevAll().size();
$("option:selected",this).val();

# Get selected index
$("#select option:selected").index();
$("#select option").index($("#select option:selected"));

# Select First Option
$("#select option:first");

# Select Last Item
$("#select option:last").remove();


# Replace item with new one
$("#select option:eq(1)").replaceWith("<option value='2'>new option</option>");

# Remove an item
$("#select option:eq(0)").remove();

Detect Safari using jQuery

I use to detect Apple browser engine, this simple JavaScript condition:

 navigator.vendor.startsWith('Apple')

React ignores 'for' attribute of the label element

The for attribute is called htmlFor for consistency with the DOM property API. If you're using the development build of React, you should have seen a warning in your console about this.

Does calling clone() on an array also clone its contents?

1D array of primitives does copy elements when it is cloned. This tempts us to clone 2D array(Array of Arrays).

Remember that 2D array clone doesn't work due to shallow copy implementation of clone().

public static void main(String[] args) {
    int row1[] = {0,1,2,3};
    int row2[] =  row1.clone();
    row2[0] = 10;
    System.out.println(row1[0] == row2[0]); // prints false

    int table1[][]={{0,1,2,3},{11,12,13,14}};
    int table2[][] = table1.clone();
    table2[0][0] = 100;
    System.out.println(table1[0][0] == table2[0][0]); //prints true
}

How to include view/partial specific styling in AngularJS

I know this question is old now, but after doing a ton of research on various solutions to this problem, I think I may have come up with a better solution.

UPDATE 1: Since posting this answer, I have added all of this code to a simple service that I have posted to GitHub. The repo is located here. Feel free to check it out for more info.

UPDATE 2: This answer is great if all you need is a lightweight solution for pulling in stylesheets for your routes. If you want a more complete solution for managing on-demand stylesheets throughout your application, you may want to checkout Door3's AngularCSS project. It provides much more fine-grained functionality.

In case anyone in the future is interested, here's what I came up with:

1. Create a custom directive for the <head> element:

app.directive('head', ['$rootScope','$compile',
    function($rootScope, $compile){
        return {
            restrict: 'E',
            link: function(scope, elem){
                var html = '<link rel="stylesheet" ng-repeat="(routeCtrl, cssUrl) in routeStyles" ng-href="{{cssUrl}}" />';
                elem.append($compile(html)(scope));
                scope.routeStyles = {};
                $rootScope.$on('$routeChangeStart', function (e, next, current) {
                    if(current && current.$$route && current.$$route.css){
                        if(!angular.isArray(current.$$route.css)){
                            current.$$route.css = [current.$$route.css];
                        }
                        angular.forEach(current.$$route.css, function(sheet){
                            delete scope.routeStyles[sheet];
                        });
                    }
                    if(next && next.$$route && next.$$route.css){
                        if(!angular.isArray(next.$$route.css)){
                            next.$$route.css = [next.$$route.css];
                        }
                        angular.forEach(next.$$route.css, function(sheet){
                            scope.routeStyles[sheet] = sheet;
                        });
                    }
                });
            }
        };
    }
]);

This directive does the following things:

  1. It compiles (using $compile) an html string that creates a set of <link /> tags for every item in the scope.routeStyles object using ng-repeat and ng-href.
  2. It appends that compiled set of <link /> elements to the <head> tag.
  3. It then uses the $rootScope to listen for '$routeChangeStart' events. For every '$routeChangeStart' event, it grabs the "current" $$route object (the route that the user is about to leave) and removes its partial-specific css file(s) from the <head> tag. It also grabs the "next" $$route object (the route that the user is about to go to) and adds any of its partial-specific css file(s) to the <head> tag.
  4. And the ng-repeat part of the compiled <link /> tag handles all of the adding and removing of the page-specific stylesheets based on what gets added to or removed from the scope.routeStyles object.

Note: this requires that your ng-app attribute is on the <html> element, not on <body> or anything inside of <html>.

2. Specify which stylesheets belong to which routes using the $routeProvider:

app.config(['$routeProvider', function($routeProvider){
    $routeProvider
        .when('/some/route/1', {
            templateUrl: 'partials/partial1.html', 
            controller: 'Partial1Ctrl',
            css: 'css/partial1.css'
        })
        .when('/some/route/2', {
            templateUrl: 'partials/partial2.html',
            controller: 'Partial2Ctrl'
        })
        .when('/some/route/3', {
            templateUrl: 'partials/partial3.html',
            controller: 'Partial3Ctrl',
            css: ['css/partial3_1.css','css/partial3_2.css']
        })
}]);

This config adds a custom css property to the object that is used to setup each page's route. That object gets passed to each '$routeChangeStart' event as .$$route. So when listening to the '$routeChangeStart' event, we can grab the css property that we specified and append/remove those <link /> tags as needed. Note that specifying a css property on the route is completely optional, as it was omitted from the '/some/route/2' example. If the route doesn't have a css property, the <head> directive will simply do nothing for that route. Note also that you can even have multiple page-specific stylesheets per route, as in the '/some/route/3' example above, where the css property is an array of relative paths to the stylesheets needed for that route.

3. You're done Those two things setup everything that was needed and it does it, in my opinion, with the cleanest code possible.

Hope that helps someone else who might be struggling with this issue as much as I was.

How to click a browser button with JavaScript automatically?

This would work

setInterval(function(){$("#myButtonId").click();}, 1000);

Embed an External Page Without an Iframe?

You could load the external page with jquery:

<script>$("#testLoad").load("http://www.somesite.com/somepage.html");</script>
<div id="testLoad"></div>
//would this help

Simple WPF RadioButton Binding?

I know it's way way overdue, but I have an alternative solution, which is lighter and simpler. Derive a class from System.Windows.Controls.RadioButton and declare two dependency properties RadioValue and RadioBinding. Then in the class code, override OnChecked and set the RadioBinding property value to that of the RadioValue property value. In the other direction, trap changes to the RadioBinding property using a callback, and if the new value is equal to the value of the RadioValue property, set its IsChecked property to true.

Here's the code:

public class MyRadioButton : RadioButton
{
    public object RadioValue
    {
        get { return (object)GetValue(RadioValueProperty); }
        set { SetValue(RadioValueProperty, value); }
    }

    // Using a DependencyProperty as the backing store for RadioValue.
       This enables animation, styling, binding, etc...
    public static readonly DependencyProperty RadioValueProperty =
        DependencyProperty.Register(
            "RadioValue", 
            typeof(object), 
            typeof(MyRadioButton), 
            new UIPropertyMetadata(null));

    public object RadioBinding
    {
        get { return (object)GetValue(RadioBindingProperty); }
        set { SetValue(RadioBindingProperty, value); }
    }

    // Using a DependencyProperty as the backing store for RadioBinding.
       This enables animation, styling, binding, etc...
    public static readonly DependencyProperty RadioBindingProperty =
        DependencyProperty.Register(
            "RadioBinding", 
            typeof(object), 
            typeof(MyRadioButton), 
            new FrameworkPropertyMetadata(
                null, 
                FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, 
                OnRadioBindingChanged));

    private static void OnRadioBindingChanged(
        DependencyObject d,
        DependencyPropertyChangedEventArgs e)
    {
        MyRadioButton rb = (MyRadioButton)d;
        if (rb.RadioValue.Equals(e.NewValue))
            rb.SetCurrentValue(RadioButton.IsCheckedProperty, true);
    }

    protected override void OnChecked(RoutedEventArgs e)
    {
        base.OnChecked(e);
        SetCurrentValue(RadioBindingProperty, RadioValue);
    }
}

XAML usage:

<my:MyRadioButton GroupName="grp1" Content="Value 1"
    RadioValue="val1" RadioBinding="{Binding SelectedValue}"/>
<my:MyRadioButton GroupName="grp1" Content="Value 2"
    RadioValue="val2" RadioBinding="{Binding SelectedValue}"/>
<my:MyRadioButton GroupName="grp1" Content="Value 3"
    RadioValue="val3" RadioBinding="{Binding SelectedValue}"/>
<my:MyRadioButton GroupName="grp1" Content="Value 4"
    RadioValue="val4" RadioBinding="{Binding SelectedValue}"/>

Hope someone finds this useful after all this time :)

Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource

I have added dataType: 'jsonp' and it works!

$.ajax({
   type: 'POST',
   crossDomain: true,
   dataType: 'jsonp',
   url: '',
   success: function(jsondata){

   }
})

JSONP is a method for sending JSON data without worrying about cross-domain issues. Read More

How to find Max Date in List<Object>?

self-explanatory style

import static java.util.Comparator.naturalOrder;
...

    list.stream()
        .map(User::getDate)
        .max(naturalOrder())
        .orElse(null)          // replace with .orElseThrow() is the list cannot be empty

Why can't a text column have a default value in MySQL?

For Ubuntu 16.04:

How to disable strict mode in MySQL 5.7:

Edit file /etc/mysql/mysql.conf.d/mysqld.cnf

If below line exists in mysql.cnf

sql-mode="STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"

Then Replace it with

sql_mode='MYSQL40'

Otherwise

Just add below line in mysqld.cnf

sql_mode='MYSQL40'

This resolved problem.

Generator expressions vs. list comprehensions

The important point is that the list comprehension creates a new list. The generator creates a an iterable object that will "filter" the source material on-the-fly as you consume the bits.

Imagine you have a 2TB log file called "hugefile.txt", and you want the content and length for all the lines that start with the word "ENTRY".

So you try starting out by writing a list comprehension:

logfile = open("hugefile.txt","r")
entry_lines = [(line,len(line)) for line in logfile if line.startswith("ENTRY")]

This slurps up the whole file, processes each line, and stores the matching lines in your array. This array could therefore contain up to 2TB of content. That's a lot of RAM, and probably not practical for your purposes.

So instead we can use a generator to apply a "filter" to our content. No data is actually read until we start iterating over the result.

logfile = open("hugefile.txt","r")
entry_lines = ((line,len(line)) for line in logfile if line.startswith("ENTRY"))

Not even a single line has been read from our file yet. In fact, say we want to filter our result even further:

long_entries = ((line,length) for (line,length) in entry_lines if length > 80)

Still nothing has been read, but we've specified now two generators that will act on our data as we wish.

Lets write out our filtered lines to another file:

outfile = open("filtered.txt","a")
for entry,length in long_entries:
    outfile.write(entry)

Now we read the input file. As our for loop continues to request additional lines, the long_entries generator demands lines from the entry_lines generator, returning only those whose length is greater than 80 characters. And in turn, the entry_lines generator requests lines (filtered as indicated) from the logfile iterator, which in turn reads the file.

So instead of "pushing" data to your output function in the form of a fully-populated list, you're giving the output function a way to "pull" data only when its needed. This is in our case much more efficient, but not quite as flexible. Generators are one way, one pass; the data from the log file we've read gets immediately discarded, so we can't go back to a previous line. On the other hand, we don't have to worry about keeping data around once we're done with it.

What's the use of session.flush() in Hibernate

You might use flush to force validation constraints to be realised and detected in a known place rather than when the transaction is committed. It may be that commit gets called implicitly by some framework logic, through declarative logic, the container, or by a template. In this case, any exception thrown may be difficult to catch and handle (it could be too high in the code).

For example, if you save() a new EmailAddress object, which has a unique constraint on the address, you won't get an error until you commit.

Calling flush() forces the row to be inserted, throwing an Exception if there is a duplicate.

However, you will have to roll back the session after the exception.

Hash function that produces short hashes?

You need to hash the contents to come up with a digest. There are many hashes available but 10-characters is pretty small for the result set. Way back, people used CRC-32, which produces a 33-bit hash (basically 4 characters plus one bit). There is also CRC-64 which produces a 65-bit hash. MD5, which produces a 128-bit hash (16 bytes/characters) is considered broken for cryptographic purposes because two messages can be found which have the same hash. It should go without saying that any time you create a 16-byte digest out of an arbitrary length message you're going to end up with duplicates. The shorter the digest, the greater the risk of collisions.

However, your concern that the hash not be similar for two consecutive messages (whether integers or not) should be true with all hashes. Even a single bit change in the original message should produce a vastly different resulting digest.

So, using something like CRC-64 (and base-64'ing the result) should get you in the neighborhood you're looking for.

How do I pull files from remote without overwriting local files?

You can stash your local changes first, then pull, then pop the stash.

git stash
git pull origin master
git stash pop

Anything that overrides changes from remote will have conflicts which you will have to manually resolve.

Java: Clear the console

A way to get this can be print multiple end of lines ("\n") and simulate the clear screen. At the end clear, at most in the unix shell, not removes the previous content, only moves it up and if you make scroll down can see the previous content.

Here is a sample code:

for (int i = 0; i < 50; ++i) System.out.println();

Android SDK installation doesn't find JDK

Warning: As a commenter mentioned, don't try this on a Windows 7! I tested it with Windows XP 64 bit.

As the posted solution does NOT work for all (including me, myself, and I), I want to leave a note for those seeking for another way (without registry hacking, etc.) to solve this on a Windows 64 bit system. Just add PATH (capital letters!!) to your environment Variables and set the value to your JDK-Path.

I added JDK to the existing "Path" which did not work, like it didn't with JAVA_HOME or the "Back"-Solution. Adding it to "PATH" finally did the trick.

I hope this might be helpful for somebody.

Push to GitHub without a password using ssh-key

Using the command line:

Enter ls -al ~/.ssh to see if existing SSH keys are present.

In the terminal is shows: No directory exist

Then generate a new SSH key

Step 1.

ssh-keygen -t rsa -b 4096 -C "[email protected]"

step 2.

Enter a file in which to save the key (/Users/you/.ssh/id_rsa): <here is file name and enter the key>

step 3.

Enter passphrase (empty for no passphrase): [Type a password]

Enter same passphrase again: [Type password again]

Call a PHP function after onClick HTML event

<div id="sample"></div>   
 <form>
        <fieldset>
            <legend>Add New Contact</legend>
            <input type="text" name="fullname" placeholder="First name and last name" required /> <br />
            <input type="email" name="email" placeholder="[email protected]" required /> <br />
            <input type="text" name="phone" placeholder="Personal phone number: mobile, home phone etc." required /> <br />
            <input type="submit" name="submit" id= "submitButton" class="button" value="Add Contact" onClick="" />
            <input type="button" name="cancel" class="button" value="Reset" />
        </fieldset>
    </form>

<script>

    $(document).ready(function(){
         $("#submitButton").click(function(){
            $("#sample").load(filenameofyourfunction?the the variable you need);
         });
    });

</script>

How to close a JavaFX application on window close?

getContentPane.remove(jfxPanel);

try it (:

C# How can I check if a URL exists/is valid?

This solution seems easy to follow:

public static bool isValidURL(string url) {
    WebRequest webRequest = WebRequest.Create(url);
    WebResponse webResponse;
    try
    {
        webResponse = webRequest.GetResponse();
    }
    catch //If exception thrown then couldn't get response from address
    {
        return false ;
    }
    return true ;
}

html5 audio player - jquery toggle click play/pause?

Simply Use

$('audio').trigger('pause');

How can I get date and time formats based on Culture Info?

Culture can be changed for a specific cell in grid view.

<%# DateTime.ParseExact(Eval("contractdate", "{0}"), "MM/dd/yyyy", System.Globalization.CultureInfo.InvariantCulture).ToString("dd/MM/yyyy", System.Globalization.CultureInfo.CurrentCulture) %>

For more detail check the link.

Date Format Issue in Gridview binding with #eval()

Using CSS in Laravel views?

That is not possible bro, Laravel assumes everything is in public folder.

So my suggestion is:

  1. Go to the public folder.
  2. Create a folder, preferably named css.
  3. Create the folder for the respective views to make things organized.
  4. Put the respective css inside of those folders, that would be easier for you.

Or

If you really insist to put css inside of views folder, you could try creating Symlink (you're mac so it's ok, but for windows, this will only work for Vista, Server 2008 or greater) from your css folder directory to the public folder and you can use {{HTML::style('your_view_folder/myStyle.css')}} inside of your view files, here's a code for your convenience, in the code you posted, put these before the return View::make():

$css_file = 'myStyle.css';
$folder_name = 'your_view_folder';
$view_path = app_path() . '/views/' . $folder_name . '/' . $css_file;
$public_css_path = public_path() . '/' . $folder_name;
if(file_exists($public_css_path)) exec('rm -rf ' . $public_css_path);
exec('mkdir ' . $public_css_path);
exec('ln -s ' . $view_path .' ' . $public_css_path . '/' . $css_file);

If you really want to try doing your idea, try this:

<link rel="stylesheet" href="<?php echo app_path() . 'views/your_view_folder/myStyle.css'?>" type="text/css">

But it won't work even if the file directory is correct because Laravel won't do that for security purposes, Laravel loves you that much.

Catching nullpointerexception in Java

NullPointerException is a run-time exception which is not recommended to catch it, but instead avoid it:

if(someVariable != null) someVariable.doSomething();
else
{
    // do something else
}

How do I enable the column selection mode in Eclipse?

To activate the cursor and select the columns you want to select use:

Windows: Alt+Shift+A

Mac: command + option + A

Linux-based OS: Alt+Shift+A

To deactivate, press the keys again.

This information was taken from DJ's Java Blog.

(XML) The markup in the document following the root element must be well-formed. Start location: 6:2

In XML there can be only one root element - you have two - heading and song.

If you restructure to something like:

<?xml version="1.0" encoding="UTF-8"?>
<song> 
 <heading>
 The Twelve Days of Christmas
 </heading>
 ....
</song>

The error about well-formed XML on the root level should disappear (though there may be other issues).

SELECT using 'CASE' in SQL

Try this.

SELECT 
  CASE 
     WHEN FRUIT = 'A' THEN 'APPLE'
     WHEN FRUIT = 'B' THEN 'BANANA'
     ELSE 'UNKNOWN FRUIT'
  END AS FRUIT
FROM FRUIT_TABLE;

Replace Both Double and Single Quotes in Javascript String

mystring = mystring.replace(/["']/g, "");

How to validate date with format "mm/dd/yyyy" in JavaScript?

It's unusual to see a post so old on such a basic topic, with so many answers, none of them right. (I'm not saying none of them work.)

  • A leap-year determination routine is not needed for this. The language can do that work for us.
  • Moment is not needed for this.
  • Date.parse() shouldn't be used for local date strings. MDN says "It is not recommended to use Date.parse as until ES5, parsing of strings was entirely implementation dependent." The standard requires a (potentially simplified) ISO 8601 string; support for any other format is implementation-dependent.
  • Nor should new Date(string) be used, because that uses Date.parse().
  • IMO the leap day should be validated.
  • The validation function must account for the possibility that the input string doesn't match the expected format. For example, '1a/2a/3aaa', '1234567890', or 'ab/cd/efgh'.

Here's an efficient, concise solution with no implicit conversions. It takes advantage of the Date constructor's willingness to interpret 2018-14-29 as 2019-03-01. It does use a couple modern language features, but those are easily removed if needed. I've also included some tests.

function isValidDate(s) {
    // Assumes s is "mm/dd/yyyy"
    if ( ! /^\d\d\/\d\d\/\d\d\d\d$/.test(s) ) {
        return false;
    }
    const parts = s.split('/').map((p) => parseInt(p, 10));
    parts[0] -= 1;
    const d = new Date(parts[2], parts[0], parts[1]);
    return d.getMonth() === parts[0] && d.getDate() === parts[1] && d.getFullYear() === parts[2];
}

function testValidDate(s) {
    console.log(s, isValidDate(s));
}
testValidDate('01/01/2020'); // true
testValidDate('02/29/2020'); // true
testValidDate('02/29/2000'); // true
testValidDate('02/29/1900'); // false
testValidDate('02/29/2019'); // false
testValidDate('01/32/1970'); // false
testValidDate('13/01/1970'); // false
testValidDate('14/29/2018'); // false
testValidDate('1a/2b/3ccc'); // false
testValidDate('1234567890'); // false
testValidDate('aa/bb/cccc'); // false
testValidDate(null);         // false
testValidDate('');           // false

TypeError: tuple indices must be integers, not str

The Problem is how you access row

Specifically row["waocs"] and row["pool_number"] of ocs[row["pool_number"]]=int(row["waocs"])

If you look up the official-documentation of fetchall() you find.

The method fetches all (or all remaining) rows of a query result set and returns a list of tuples.

Therefore you have to access the values of rows with row[__integer__] like row[0]

Create a Bitmap/Drawable from file path

Well, using the static Drawable.createFromPath(String pathName) seems a bit more straightforward to me than decoding it yourself... :-)

If your mImg is a simple ImageView, you don't even need it, use mImg.setImageUri(Uri uri) directly.

Most efficient way to see if an ArrayList contains an object in Java

Even if the equals method were comparing those two fields, then logically, it would be just the same code as you doing it manually. OK, it might be "messy", but it's still the correct answer

Solr vs. ElasticSearch

I only use Elastic-search. Since I found solr is very hard to start. Elastic-search's features:

  1. Easy to start, very few setting. Even a newbie can setup a cluster step by step.
  2. Simple Restful API which using NoSQL query. And many language libraries for easy accessing.
  3. Good document, you can read the book: . There is a web version on official website.

Add up a column of numbers at the Unix shell

Instead of using cut to get the file size from output of ls -l, you can use directly:

$ cat files.txt | xargs ls -l | awk '{total += $5} END {print "Total:", total, "bytes"}'

Awk interprets "$5" as the fifth column. This is the column from ls -l that gives you the file size.

Hide a EditText & make it visible by clicking a menu

Try phoneNumber.setVisibility(View.GONE);

Remove style attribute from HTML tags

Something like this should work (untested code warning):

<?php

$html = '<p style="asd">qwe</p><br /><p class="qwe">qweqweqwe</p>';

$domd = new DOMDocument();
libxml_use_internal_errors(true);
$domd->loadHTML($html);
libxml_use_internal_errors(false);

$domx = new DOMXPath($domd);
$items = $domx->query("//p[@style]");

foreach($items as $item) {
  $item->removeAttribute("style");
}

echo $domd->saveHTML();

How do you set CMAKE_C_COMPILER and CMAKE_CXX_COMPILER for building Assimp for iOS?

Option 1:

You can set CMake variables at command line like this:

cmake -D CMAKE_C_COMPILER="/path/to/your/c/compiler/executable" -D CMAKE_CXX_COMPILER "/path/to/your/cpp/compiler/executable" /path/to/directory/containing/CMakeLists.txt

See this to learn how to create a CMake cache entry.


Option 2:

In your shell script build_ios.sh you can set environment variables CC and CXX to point to your C and C++ compiler executable respectively, example:

export CC=/path/to/your/c/compiler/executable
export CXX=/path/to/your/cpp/compiler/executable
cmake /path/to/directory/containing/CMakeLists.txt

Option 3:

Edit the CMakeLists.txt file of "Assimp": Add these lines at the top (must be added before you use project() or enable_language() command)

set(CMAKE_C_COMPILER "/path/to/your/c/compiler/executable")
set(CMAKE_CXX_COMPILER "/path/to/your/cpp/compiler/executable")

See this to learn how to use set command in CMake. Also this is a useful resource for understanding use of some of the common CMake variables.


Here is the relevant entry from the official FAQ: https://gitlab.kitware.com/cmake/community/wikis/FAQ#how-do-i-use-a-different-compiler

Understanding ASP.NET Eval() and Bind()

For read-only controls they are the same. For 2 way databinding, using a datasource in which you want to update, insert, etc with declarative databinding, you'll need to use Bind.

Imagine for example a GridView with a ItemTemplate and EditItemTemplate. If you use Bind or Eval in the ItemTemplate, there will be no difference. If you use Eval in the EditItemTemplate, the value will not be able to be passed to the Update method of the DataSource that the grid is bound to.


UPDATE: I've come up with this example:

<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Data binding demo</title>
</head>
<body>
    <form id="form1" runat="server">
        <asp:GridView 
            ID="grdTest" 
            runat="server" 
            AutoGenerateEditButton="true" 
            AutoGenerateColumns="false" 
            DataSourceID="mySource">
            <Columns>
                <asp:TemplateField>
                    <ItemTemplate>
                        <%# Eval("Name") %>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:TextBox 
                            ID="edtName" 
                            runat="server" 
                            Text='<%# Bind("Name") %>' 
                        />
                    </EditItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
    </form>

    <asp:ObjectDataSource 
        ID="mySource" 
        runat="server"
        SelectMethod="Select" 
        UpdateMethod="Update" 
        TypeName="MyCompany.CustomDataSource" />
</body>
</html>

And here's the definition of a custom class that serves as object data source:

public class CustomDataSource
{
    public class Model
    {
        public string Name { get; set; }
    }

    public IEnumerable<Model> Select()
    {
        return new[] 
        {
            new Model { Name = "some value" }
        };
    }

    public void Update(string Name)
    {
        // This method will be called if you used Bind for the TextBox
        // and you will be able to get the new name and update the
        // data source accordingly
    }

    public void Update()
    {
        // This method will be called if you used Eval for the TextBox
        // and you will not be able to get the new name that the user
        // entered
    }
}

Python: Select subset from list based on index set

Matlab and Scilab languages offer a simpler and more elegant syntax than Python for the question you're asking, so I think the best you can do is to mimic Matlab/Scilab by using the Numpy package in Python. By doing this the solution to your problem is very concise and elegant:

from numpy import *
property_a = array([545., 656., 5.4, 33.])
property_b = array([ 1.2,  1.3, 2.3, 0.3])
good_objects = [True, False, False, True]
good_indices = [0, 3]
property_asel = property_a[good_objects]
property_bsel = property_b[good_indices]

Numpy tries to mimic Matlab/Scilab but it comes at a cost: you need to declare every list with the keyword "array", something which will overload your script (this problem doesn't exist with Matlab/Scilab). Note that this solution is restricted to arrays of number, which is the case in your example.

Get current URL/URI without some of $_GET variables

Yii2

Url::current([], true);

or

Url::current();

How to put wildcard entry into /etc/hosts?

use dnsmasq

pretending you're using a debian-based dist(ubuntu,mint..), check if it's installed with

(sudo) systemctl status dnsmasq

If it is just disabled start it with

(sudo) systemctl start dnsmasq

If you have to install it, write

(sudo) apt-get install dnsmasq

To define domains to resolve edit /etc/dnsmasq.conf like this

address=/example.com/127.0.0.1

to resolve *.example.com

! You need to reload dnsmasq to take effect for the changes !

systemctl reload dnsmasq

How do I extract value from Json

Use a JSON parser. There are plenty of JSON parsers written in Java.

http://www.json.org/

Look under the Java section and find one you like.

PDO closing connection

<?php if(!class_exists('PDO2')) {
    class PDO2 {
        private static $_instance;
        public static function getInstance() {
            if (!isset(self::$_instance)) {
                try {
                    self::$_instance = new PDO(
                        'mysql:host=***;dbname=***',
                        '***',
                        '***',
                        array(
                            PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8mb4 COLLATE utf8mb4_general_ci",
                            PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION
                        )
                    );
                } catch (PDOException $e) {
                    throw new PDOException($e->getMessage(), (int) $e->getCode());
                }
            }
            return self::$_instance;
        }
        public static function closeInstance() {
            return self::$_instance = null;
        }
    }
}
$req = PDO2::getInstance()->prepare('SELECT * FROM table');
$req->execute();
$count = $req->rowCount();
$results = $req->fetchAll(PDO::FETCH_ASSOC);
$req->closeCursor();
// Do other requests maybe
// And close connection
PDO2::closeInstance();
// print output

Full example, with custom class PDO2.

How can I solve a connection pool problem between ASP.NET and SQL Server?

In most cases connection pooling problems are related to connection leaks. Your application probably doesn't close its database connections correctly and consistently. When you leave connections open, they remain blocked until the .NET garbage collector closes them for you by calling their Finalize() method.

You want to make sure that you are really closing the connection. For example the following code will cause a connection leak, if the code between .Open and Close throws an exception:

var connection = new SqlConnection(connectionString);

connection.Open();
// some code
connection.Close();                

The correct way would be this:

var connection = new SqlConnection(ConnectionString);

try
{
     connection.Open();
     someCall (connection);
}
finally
{
     connection.Close();                
}

or

using (SqlConnection connection = new SqlConnection(connectionString))
{
     connection.Open();
     someCall(connection);
}

When your function returns a connection from a class method make sure you cache it locally and call its Close method. You'll leak a connection using this code for example:

var command = new OleDbCommand(someUpdateQuery, getConnection());

result = command.ExecuteNonQuery();
connection().Close(); 

The connection returned from the first call to getConnection() is not being closed. Instead of closing your connection, this line creates a new one and tries to close it.

If you use SqlDataReader or a OleDbDataReader, close them. Even though closing the connection itself seems to do the trick, put in the extra effort to close your data reader objects explicitly when you use them.


This article "Why Does a Connection Pool Overflow?" from MSDN/SQL Magazine explains a lot of details and suggests some debugging strategies:

  • Run sp_who or sp_who2. These system stored procedures return information from the sysprocesses system table that shows the status of and information about all working processes. Generally, you'll see one server process ID (SPID) per connection. If you named your connection by using the Application Name argument in the connection string, your working connections will be easy to find.
  • Use SQL Server Profiler with the SQLProfiler TSQL_Replay template to trace open connections. If you're familiar with Profiler, this method is easier than polling by using sp_who.
  • Use the Performance Monitor to monitor the pools and connections. I discuss this method in a moment.
  • Monitor performance counters in code. You can monitor the health of your connection pool and the number of established connections by using routines to extract the counters or by using the new .NET PerformanceCounter controls.

How to move/rename a file using an Ansible task on a remote system

From version 2.0, in copy module you can use remote_src parameter.

If True it will go to the remote/target machine for the src.

- name: Copy files from foo to bar
  copy: remote_src=True src=/path/to/foo dest=/path/to/bar

If you want to move file you need to delete old file with file module

- name: Remove old files foo
  file: path=/path/to/foo state=absent

From version 2.8 copy module remote_src supports recursive copying.

Anaconda site-packages

I installed miniconda and found all the installed packages in /miniconda3/pkgs

How do I assign a null value to a variable in PowerShell?

If the goal simply is to list all computer objects with an empty description attribute try this

import-module activedirectory  
$domain = "domain.example.com" 
Get-ADComputer -Filter '*' -Properties Description | where { $_.Description -eq $null }

How to run crontab job every week on Sunday

The crontab website gives the real time results display: https://crontab.guru/#5_8_*_*_0

enter image description here

mailto link with HTML body

Thunderbird supports html-body: mailto:[email protected]?subject=Me&html-body=<b>ME</b>

Cannot declare instance members in a static class in C#

It is not legal to declare an instance member in a static class. Static class's cannot be instantiated hence it makes no sense to have an instance members (they'd never be accessible).

Find elements inside forms and iframe using Java and Selenium WebDriver

When using an iframe, you will first have to switch to the iframe, before selecting the elements of that iframe

You can do it using:

driver.switchTo().frame(driver.findElement(By.id("frameId")));
//do your stuff
driver.switchTo().defaultContent();

In case if your frameId is dynamic, and you only have one iframe, you can use something like:

driver.switchTo().frame(driver.findElement(By.tagName("iframe")));

What is the meaning of the word logits in TensorFlow?

(FOMOsapiens).

If you check math Logit function, it converts real space from [0,1] interval to infinity [-inf, inf].

Sigmoid and softmax will do exactly the opposite thing. They will convert the [-inf, inf] real space to [0, 1] real space.

This is why, in machine learning we may use logit before sigmoid and softmax function (since they match).

And this is why "we may call" anything in machine learning that goes in front of sigmoid or softmax function the logit.

Here is J. Hinton video using this term.

Jenkins not executing jobs (pending - waiting for next executor)

In my case it was caused by number of executors (I had 1) and running Jenkins Job (Project) from Pipeline (my pipeline script started other Job in Jenkins). It caused deadlock - my pipeline held executor and was waiting for its job, but the job was waiting for free executor.

The solution may be increasing of # of executors in Jenkins -> Manage Jenkins -> Manage Nodes -> Configure (icon on required node).

generate a random number between 1 and 10 in c

Here is a ready to run source code for random number generator using c taken from this site: http://www.random-number.com/random-number-c/ . The implementation here is more general (a function that gets 3 parameters: min,max and number of random numbers to generate)

#include <time.h>
#include <stdlib.h>
#include <stdio.h>

// the random function
void RandomNumberGenerator(const int nMin, const int nMax, const int  nNumOfNumsToGenerate)
{
  int nRandonNumber = 0;
  for (int i = 0; i < nNumOfNumsToGenerate; i++)
  {
    nRandonNumber = rand()%(nMax-nMin) + nMin;
    printf("%d ", nRandonNumber);
  }
  printf("\n");
}

void main()
{
  srand(time(NULL));
  RandomNumberGenerator(1,70,5);
}

Reading a List from properties file and load with spring annotation @Value

Beware of spaces in the values. I could be wrong, but I think spaces in the comma-separated list are not truncated using @Value and Spel. The list

foobar=a, b, c

would be read in as a list of strings

"a", " b", " c"

In most cases you would probably not want the spaces!

The expression

@Value("#{'${foobar}'.trim().replaceAll(\"\\s*(?=,)|(?<=,)\\s*\", \"\").split(',')}")
private List<String> foobarList;

would give you a list of strings:

"a", "b", "c".

The regular expression removes all spaces just before and just after a comma. Spaces inside of the values are not removed. So

foobar = AA, B B, CCC

should result in values

"AA", "B B", "CCC".

Only allow Numbers in input Tag without Javascript

Try this with the + after [0-9]:

input type="text" pattern="[0-9]+" title="number only"

Convert/cast an stdClass object to another class

Changed function for deep casting (using recursion)

/**
 * Translates type
 * @param $destination Object destination
 * @param stdClass $source Source
 */
private static function Cast(&$destination, stdClass $source)
{
    $sourceReflection = new \ReflectionObject($source);
    $sourceProperties = $sourceReflection->getProperties();
    foreach ($sourceProperties as $sourceProperty) {
        $name = $sourceProperty->getName();
        if (gettype($destination->{$name}) == "object") {
            self::Cast($destination->{$name}, $source->$name);
        } else {
            $destination->{$name} = $source->$name;
        }
    }
}

Add rows to CSV File in powershell

To simply append to a file in powershell,you can use add-content.

So, to only add a new line to the file, try the following, where $YourNewDate and $YourDescription contain the desired values.

$NewLine = "{0},{1}" -f $YourNewDate,$YourDescription
$NewLine | add-content -path $file

Or,

"{0},{1}" -f $YourNewDate,$YourDescription | add-content -path $file

This will just tag the new line to the end of the .csv, and will not work for creating new .csv files where you will need to add the header.

Split files using tar, gz, zip, or bzip2

If you are splitting from Linux, you can still reassemble in Windows.

copy /b file1 + file2 + file3 + file4 filetogether

How can I use UIColorFromRGB in Swift?

myLabel.backgroundColor = UIColor(red: 50.0/255, green: 150.0/255, blue: 65.0/255, alpha: 1.0)

Sublime Text 2: How to delete blank/empty lines

Their is a more easily way to do that without regex. you have just to select the whole text. then go to: Edit--> Permute Lines --> Unique.

That's all. and all blank lines will be deleted.

New line in Sql Query

use CHAR(10) for New Line in SQL
char(9) for Tab
and Char(13) for Carriage Return

Order of execution of tests in TestNG

In TestNG, you use dependsOnMethods and/or dependsOnGroups:

@Test(groups = "a")
public void f1() {}

@Test(groups = "a")
public void f2() {}

@Test(dependsOnGroups = "a")
public void g() {}

In this case, g() will only run after f1() and f2() have completed and succeeded.

You will find a lot of examples in the documentation: http://testng.org/doc/documentation-main.html#test-groups

How to write a function that takes a positive integer N and returns a list of the first N natural numbers

Do I even need a for loop to create a list?

No, you can (and in general circumstances should) use the built-in function range():

>>> range(1,5)
[1, 2, 3, 4]

i.e.

def naturalNumbers(n):
    return range(1, n + 1)

Python 3's range() is slightly different in that it returns a range object and not a list, so if you're using 3.x wrap it all in list(): list(range(1, n + 1)).

sh: react-scripts: command not found after running npm start

You shoundt use neither SPACES neither some Special Caracters in you path, like for example using "&". I my case I was using this path: "D:\P&D\mern" and because of this "&" I lost 50 minutes trying to solve the problem! :/

Living and Learning!

String formatting: % vs. .format vs. string literal

For python version >= 3.6 (see PEP 498)

s1='albha'
s2='beta'

f'{s1}{s2:>10}'

#output
'albha      beta'

make iframe height dynamic based on content inside- JQUERY/Javascript

$(document).height() // - $('body').offset().top

and / or

$(window).height()

See Stack Overflow question How to get the height of a body element.

Try this to find the height of the body in jQuery:

if $("body").height()

It doesn't have a value if Firebug. Perhaps that's the problem.

Row count on the Filtered data

I would think that now you have the range for each of the row, you can easily manipulate that range with the offset(row, column) action? What is the point of counting the records filtered (unless you need that count in a variable)? So instead of (or as well as in the same block) write your code action to move each row to an empty hidden sheet and once all done, you can do any work you like from the transferred range data?

What is Node.js' Connect, Express and "middleware"?

node.js

Node.js is a javascript motor for the server side.
In addition to all the js capabilities, it includes networking capabilities (like HTTP), and access to the file system.
This is different from client-side js where the networking tasks are monopolized by the browser, and access to the file system is forbidden for security reasons.

node.js as a web server: express

Something that runs in the server, understands HTTP and can access files sounds like a web server. But it isn't one.
To make node.js behave like a web server one has to program it: handle the incoming HTTP requests and provide the appropriate responses.
This is what Express does: it's the implementation of a web server in js.
Thus, implementing a web site is like configuring Express routes, and programming the site's specific features.

Middleware and Connect

Serving pages involves a number of tasks. Many of those tasks are well known and very common, so node's Connect module (one of the many modules available to run under node) implements those tasks.
See the current impressing offering:

  • logger request logger with custom format support
  • csrf Cross-site request forgery protection
  • compress Gzip compression middleware
  • basicAuth basic http authentication
  • bodyParser extensible request body parser
  • json application/json parser
  • urlencoded application/x-www-form-urlencoded parser
  • multipart multipart/form-data parser
  • timeout request timeouts
  • cookieParser cookie parser
  • session session management support with bundled MemoryStore
  • cookieSession cookie-based session support
  • methodOverride faux HTTP method support
  • responseTime calculates response-time and exposes via X-Response-Time
  • staticCache memory cache layer for the static() middleware
  • static streaming static file server supporting Range and more
  • directory directory listing middleware
  • vhost virtual host sub-domain mapping middleware
  • favicon efficient favicon server (with default icon)
  • limit limit the bytesize of request bodies
  • query automatic querystring parser, populating req.query
  • errorHandler flexible error handler

Connect is the framework and through it you can pick the (sub)modules you need.
The Contrib Middleware page enumerates a long list of additional middlewares.
Express itself comes with the most common Connect middlewares.

What to do?

Install node.js.
Node comes with npm, the node package manager.
The command npm install -g express will download and install express globally (check the express guide).
Running express foo in a command line (not in node) will create a ready-to-run application named foo. Change to its (newly created) directory and run it with node with the command node <appname>, then open http://localhost:3000 and see. Now you are in.

How to get a cross-origin resource sharing (CORS) post request working

REQUEST:

 $.ajax({
            url: "http://localhost:8079/students/add/",
            type: "POST",
            crossDomain: true,
            data: JSON.stringify(somejson),
            dataType: "json",
            success: function (response) {
                var resp = JSON.parse(response)
                alert(resp.status);
            },
            error: function (xhr, status) {
                alert("error");
            }
        });

RESPONSE:

response = HttpResponse(json.dumps('{"status" : "success"}'))
response.__setitem__("Content-type", "application/json")
response.__setitem__("Access-Control-Allow-Origin", "*")

return response

How to generate random number with the specific length in python

From the official documentation, does it not seem that the sample() method is appropriate for this purpose?

import random

def random_digits(n):
    num = range(0, 10)
    lst = random.sample(num, n)
    print str(lst).strip('[]')

Output:

>>>random_digits(5)
2, 5, 1, 0, 4

How to restart kubernetes nodes?

I had this problem too but it looks like it depends on the Kubernetes offering and how everything was installed. In Azure, if you are using acs-engine install, you can find the shell script that is actually being run to provision it at:

/opt/azure/containers/provision.sh

To get a more fine-grained understanding, just read through it and run the commands that it specifies. For me, I had to run as root:

systemctl enable kubectl
systemctl restart kubectl

I don't know if the enable is necessary and I can't say if these will work with your particular installation, but it definitely worked for me.

How can I find the number of days between two Date objects in Ruby?

Try this:

num_days = later_date - earlier_date

/** and /* in Java Comments

Comments in the following listing of Java Code are the greyed out characters:

/** 
 * The HelloWorldApp class implements an application that
 * simply displays "Hello World!" to the standard output.
 */
class HelloWorldApp {
    public static void main(String[] args) {
        System.out.println("Hello World!"); //Display the string.
    }
}

The Java language supports three kinds of comments:

/* text */

The compiler ignores everything from /* to */.

/** documentation */

This indicates a documentation comment (doc comment, for short). The compiler ignores this kind of comment, just like it ignores comments that use /* and */. The JDK javadoc tool uses doc comments when preparing automatically generated documentation.

// text

The compiler ignores everything from // to the end of the line.

Now regarding when you should be using them:

Use // text when you want to comment a single line of code.

Use /* text */ when you want to comment multiple lines of code.

Use /** documentation */ when you would want to add some info about the program that can be used for automatic generation of program documentation.

How can I be notified when an element is added to the page?

A pure javascript solution (without jQuery):

const SEARCH_DELAY = 100; // in ms

// it may run indefinitely. TODO: make it cancellable, using Promise's `reject`
function waitForElementToBeAdded(cssSelector) {
  return new Promise((resolve) => {
    const interval = setInterval(() => {
      if (element = document.querySelector(cssSelector)) {
        clearInterval(interval);
        resolve(element);
      }
    }, SEARCH_DELAY);
  });
}

console.log(await waitForElementToBeAdded('#main'));

How to select a column name with a space in MySQL

If double quotes does not work , try including the string within square brackets.

For eg:

SELECT "Business Name","Other Name" FROM your_Table

can be changed as

SELECT [Business Name],[Other Name] FROM your_Table

Converting datetime.date to UTC timestamp in Python

I defined my own two functions

  • utc_time2datetime(utc_time, tz=None)
  • datetime2utc_time(datetime)

here:

import time
import datetime
from pytz import timezone
import calendar
import pytz


def utc_time2datetime(utc_time, tz=None):
    # convert utc time to utc datetime
    utc_datetime = datetime.datetime.fromtimestamp(utc_time)

    # add time zone to utc datetime
    if tz is None:
        tz_datetime = utc_datetime.astimezone(timezone('utc'))
    else:
        tz_datetime = utc_datetime.astimezone(tz)

    return tz_datetime


def datetime2utc_time(datetime):
    # add utc time zone if no time zone is set
    if datetime.tzinfo is None:
        datetime = datetime.replace(tzinfo=timezone('utc'))

    # convert to utc time zone from whatever time zone the datetime is set to
    utc_datetime = datetime.astimezone(timezone('utc')).replace(tzinfo=None)

    # create a time tuple from datetime
    utc_timetuple = utc_datetime.timetuple()

    # create a time element from the tuple an add microseconds
    utc_time = calendar.timegm(utc_timetuple) + datetime.microsecond / 1E6

    return utc_time

How to fix Error: "Could not find schema information for the attribute/element" by creating schema

In my case I had an ambiguous reference in my code. I restarted Visual Studio and was able to see the error message. When I resolved this the other error disappeared.

TypeScript typed array usage

The translation is correct, the typing of the expression isn't. TypeScript is incorrectly typing the expression new Thing[100] as an array. It should be an error to index Thing, a constructor function, using the index operator. In C# this would allocate an array of 100 elements. In JavaScript this calls the value at index 100 of Thing as if was a constructor. Since that values is undefined it raises the error you mentioned. In JavaScript and TypeScript you want new Array(100) instead.

You should report this as a bug on CodePlex.

Django - Did you forget to register or load this tag?

did you try this

{% load games_tags %} 

at the top instead of pygmentize?

Deleting folders in python recursively

Just for the next guy searching for a micropython solution, this works purely based on os (listdir, remove, rmdir). It is neither complete (especially in errorhandling) nor fancy, it will however work in most circumstances.

def deltree(target):
    print("deltree", target)
    for d in os.listdir(target):
        try:
            deltree(target + '/' + d)
        except OSError:
            os.remove(target + '/' + d)

    os.rmdir(target)

The SELECT permission was denied on the object 'Users', database 'XXX', schema 'dbo'

I resolve my problem doing this. [IMPORTANT NOTE: It allows escalated (expanded) privileges to the particular account, possibly more than are needed for individual scenario].

  1. Go to 'Object Explorer' of SQL Management Studio.
  2. Expand Security, then Login.
  3. Select the user you are working with, then right click and select Properties Windows.
  4. In Select a Page, Go to Server Roles
  5. Click on sysadmin and save.

XML Schema minOccurs / maxOccurs default values

The default values for minOccurs and maxOccurs are 1. Thus:

<xsd:element minOccurs="1" name="asdf"/>

cardinality is [1-1] Note: if you specify only minOccurs attribute, it can't be greater than 1, because the default value for maxOccurs is 1.

<xsd:element minOccurs="5" maxOccurs="2" name="asdf"/>

invalid

<xsd:element maxOccurs="2" name="asdf"/>

cardinality is [1-2] Note: if you specify only maxOccurs attribute, it can't be smaller than 1, because the default value for minOccurs is 1.

<xsd:element minOccurs="0" maxOccurs="0"/>

is a valid combination which makes the element prohibited.

For more info see http://www.w3.org/TR/xmlschema-0/#OccurrenceConstraints

Fill Combobox from database

            SqlConnection conn = new SqlConnection(@"Data Source=TOM-PC\sqlexpress;Initial Catalog=Northwind;User ID=sa;Password=xyz") ;
            conn.Open();
            SqlCommand sc = new SqlCommand("select customerid,contactname from customers", conn);
            SqlDataReader reader;

            reader = sc.ExecuteReader();
            DataTable dt = new DataTable();
            dt.Columns.Add("customerid", typeof(string));
            dt.Columns.Add("contactname", typeof(string));
            dt.Load(reader);

            comboBox1.ValueMember = "customerid";
            comboBox1.DisplayMember = "contactname";
            comboBox1.DataSource = dt;

            conn.Close();

pull out p-values and r-squared from a linear regression

r-squared: You can return the r-squared value directly from the summary object summary(fit)$r.squared. See names(summary(fit)) for a list of all the items you can extract directly.

Model p-value: If you want to obtain the p-value of the overall regression model, this blog post outlines a function to return the p-value:

lmp <- function (modelobject) {
    if (class(modelobject) != "lm") stop("Not an object of class 'lm' ")
    f <- summary(modelobject)$fstatistic
    p <- pf(f[1],f[2],f[3],lower.tail=F)
    attributes(p) <- NULL
    return(p)
}

> lmp(fit)
[1] 1.622665e-05

In the case of a simple regression with one predictor, the model p-value and the p-value for the coefficient will be the same.

Coefficient p-values: If you have more than one predictor, then the above will return the model p-value, and the p-value for coefficients can be extracted using:

summary(fit)$coefficients[,4]  

Alternatively, you can grab the p-value of coefficients from the anova(fit) object in a similar fashion to the summary object above.

Pass parameter to EventHandler

Timer.Elapsed expects method of specific signature (with arguments object and EventArgs). If you want to use your PlayMusicEvent method with additional argument evaluated during event registration, you can use lambda expression as an adapter:

myTimer.Elapsed += new ElapsedEventHandler((sender, e) => PlayMusicEvent(sender, e, musicNote));

Edit: you can also use shorter version:

myTimer.Elapsed += (sender, e) => PlayMusicEvent(sender, e, musicNote);

Running a Python script from PHP

This is so trivial, but just wanted to help anyone who already followed along Alejandro's suggestion but encountered this error:

sh: blabla.py: command not found

If anyone encountered that error, then a little change needs to be made to the php file by Alejandro:

$command = escapeshellcmd('python blabla.py');

How to echo or print an array in PHP?

I checked the answer however, (for each) in PHP is deprecated and no longer work with the latest php versions.

Usually we would convert an array into a string to log it somewhere, perhaps debugging or test etc.

I would convert the array into a string by doing:

$Output = implode(",", $SourceArray);

Whereas:

$output is the result (where the string would be generated

",": is the separator (between each array field

$SourceArray: is your source array.

I hope this helps

UIButton action in table view cell

class TableViewCell: UITableViewCell {
   @IBOutlet weak var oneButton: UIButton!
   @IBOutlet weak var twoButton: UIButton!
}


class TableViewController: UITableViewController {

  override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! TableViewCell

    cell.oneButton.addTarget(self, action: #selector(TableViewController.oneTapped(_:)), for: .touchUpInside)
    cell.twoButton.addTarget(self, action: #selector(TableViewController.twoTapped(_:)), for: .touchUpInside)

    return cell
}

func oneTapped(_ sender: Any?) {

    print("Tapped")
}

func twoTapped(_ sender: Any?) {

    print("Tapped")
   }
}

How to filter Pandas dataframe using 'in' and 'not in' like in SQL

I've been usually doing generic filtering over rows like this:

criterion = lambda row: row['countries'] not in countries
not_in = df[df.apply(criterion, axis=1)]

How find out which process is using a file in Linux?

$ lsof | tree MyFold

As shown in the image attached:

enter image description here

Pandas df.to_csv("file.csv" encode="utf-8") still gives trash characters for minus sign

Your "bad" output is UTF-8 displayed as CP1252.

On Windows, many editors assume the default ANSI encoding (CP1252 on US Windows) instead of UTF-8 if there is no byte order mark (BOM) character at the start of the file. While a BOM is meaningless to the UTF-8 encoding, its UTF-8-encoded presence serves as a signature for some programs. For example, Microsoft Office's Excel requires it even on non-Windows OSes. Try:

df.to_csv('file.csv',encoding='utf-8-sig')

That encoder will add the BOM.

Java : Cannot format given Object as a Date

java.time

I should like to contribute the modern answer. The SimpleDateFormat class is notoriously troublesome, and while it was reasonable to fight one’s way through with it when this question was asked six and a half years ago, today we have much better in java.time, the modern Java date and time API. SimpleDateFormat and its friend Date are now considered long outdated, so don’t use them anymore.

    DateTimeFormatter monthFormatter = DateTimeFormatter.ofPattern("MM/uuuu");
    String dateformat = "2012-11-17T00:00:00.000-05:00";
    OffsetDateTime dateTime = OffsetDateTime.parse(dateformat);
    String monthYear = dateTime.format(monthFormatter);
    System.out.println(monthYear);

Output:

11/2012

I am exploiting the fact that your string is in ISO 8601 format, the international standard, and that the classes of java.time parse this format as their default, that is, without any explicit formatter. It’s stil true what the other answers say, you need to parse the original string first, then format the resulting date-time object into a new string. Usually this requires two formatters, only in this case we’re lucky and can do with just one formatter.

What went wrong in your code

  • As others have said, SimpleDateFormat.format cannot accept a String argument, also when the parameter type is declared to be Object.
  • Because of the exception you didn’t get around to discovering: there is also a bug in your format pattern string, mm/yyyy. Lowercase mm os for minute of the hour. You need uppercase MM for month.
  • Finally the Java naming conventions say to use a lowercase first letter in variable names, so use lowercase m in monthYear (also because java.time includes a MonthYear class with uppercase M, so to avoid confusion).

Links

Using multiple parameters in URL in express

app.get('/fruit/:fruitName/:fruitColor', function(req, res) {
    var data = {
        "fruit": {
            "apple": req.params.fruitName,
            "color": req.params.fruitColor
        }
    }; 

    send.json(data);
});

If that doesn't work, try using console.log(req.params) to see what it is giving you.

How to get the current time in Python

The previous answers are all good suggestions, but I find it easiest to use ctime():

In [2]: from time import ctime
In [3]: ctime()
Out[3]: 'Thu Oct 31 11:40:53 2013'

This gives a nicely formatted string representation of the current local time.

Oracle's default date format is YYYY-MM-DD, WHY?

Are you sure you're not confusing Oracle database with Oracle SQL Developer?

The database itself has no date format, the date comes out of the database in raw form. It's up to the client software to render it, and SQL Developer does use YYYY-MM-DD as its default format, which is next to useless, I agree.

edit: As was commented below, SQL Developer can be reconfigured to display DATE values properly, it just has bad defaults.

AttributeError: 'str' object has no attribute

The problem is in your playerMovement method. You are creating the string name of your room variables (ID1, ID2, ID3):

letsago = "ID" + str(self.dirDesc.values())

However, what you create is just a str. It is not the variable. Plus, I do not think it is doing what you think its doing:

>>>str({'a':1}.values())
'dict_values([1])'

If you REALLY needed to find the variable this way, you could use the eval function:

>>>foo = 'Hello World!'
>>>eval('foo')
'Hello World!'

or the globals function:

class Foo(object):
    def __init__(self):
        super(Foo, self).__init__()
    def test(self, name):
        print(globals()[name])

foo = Foo()
bar = 'Hello World!'
foo.text('bar')

However, instead I would strongly recommend you rethink you class(es). Your userInterface class is essentially a Room. It shouldn't handle player movement. This should be within another class, maybe GameManager or something like that.

MySQL error #1054 - Unknown column in 'Field List'

I had this error aswell.

I am working in mysql workbench. When giving the values they have to be inside "". That solved it for me.

Javascript Thousand Separator / string format

All you need to do is just really this:

123000.9123.toLocaleString()
//result will be "123,000.912"

CMake link to external library

arrowdodger's answer is correct and preferred on many occasions. I would simply like to add an alternative to his answer:

You could add an "imported" library target, instead of a link-directory. Something like:

# Your-external "mylib", add GLOBAL if the imported library is located in directories above the current.
add_library( mylib SHARED IMPORTED )
# You can define two import-locations: one for debug and one for release.
set_target_properties( mylib PROPERTIES IMPORTED_LOCATION ${CMAKE_BINARY_DIR}/res/mylib.so )

And then link as if this library was built by your project:

TARGET_LINK_LIBRARIES(GLBall mylib)

Such an approach would give you a little more flexibility: Take a look at the add_library( ) command and the many target-properties related to imported libraries.

I do not know if this will solve your problem with "updated versions of libs".

RestTemplate: How to send URL and query parameters together

String url = "http://test.com/Services/rest/{id}/Identifier";
Map<String, String> params = new HashMap<String, String>();
params.put("id", "1234");
URI uri = UriComponentsBuilder.fromUriString(url)
        .buildAndExpand(params)
        .toUri();
uri = UriComponentsBuilder
        .fromUri(uri)
        .queryParam("name", "myName")
        .build()
        .toUri();
restTemplate.exchange(uri , HttpMethod.PUT, requestEntity, class_p);

The safe way is to expand the path variables first, and then add the query parameters:

For me this resulted in duplicated encoding, e.g. a space was decoded to %2520 (space -> %20 -> %25).

I solved it by:

String url = "http://test.com/Services/rest/{id}/Identifier";
Map<String, String> params = new HashMap<String, String>();
params.put("id", "1234");
UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.fromUriString(url);
uriComponentsBuilder.uriVariables(params);
Uri uri = uriComponentsBuilder.queryParam("name", "myName");
        .build()
        .toUri();
restTemplate.exchange(uri , HttpMethod.PUT, requestEntity, class_p);

Essentially I am using uriComponentsBuilder.uriVariables(params); to add path parameters. The documentation says:

... In contrast to UriComponents.expand(Map) or buildAndExpand(Map), this method is useful when you need to supply URI variables without building the UriComponents instance just yet, or perhaps pre-expand some shared default values such as host and port. ...

Source: https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/util/UriComponentsBuilder.html#uriVariables-java.util.Map-