Programs & Examples On #Reduction

How to get the dimensions of a tensor (in TensorFlow) at graph construction time?

Tensor.get_shape() from this post.

From documentation:

c = tf.constant([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
print(c.get_shape())
==> TensorShape([Dimension(2), Dimension(3)])

how to call scalar function in sql server 2008

Your syntax is for table valued function which return a resultset and can be queried like a table. For scalar function do

 select  dbo.fun_functional_score('01091400003') as [er]

Replacing Numpy elements if condition is met

The quickest (and most flexible) way is to use np.where, which chooses between two arrays according to a mask(array of true and false values):

import numpy as np
a = np.random.randint(0, 5, size=(5, 4))
b = np.where(a<3,0,1)
print('a:',a)
print()
print('b:',b)

which will produce:

a: [[1 4 0 1]
 [1 3 2 4]
 [1 0 2 1]
 [3 1 0 0]
 [1 4 0 1]]

b: [[0 1 0 0]
 [0 1 0 1]
 [0 0 0 0]
 [1 0 0 0]
 [0 1 0 0]]

OpenMP set_num_threads() is not working

Try setting your num_threads inside your omp parallel code, it worked for me. This will give output as 4

#pragma omp parallel
{
   omp_set_num_threads(4);
   int id = omp_get_num_threads();
   #pragma omp for
   for (i = 0:n){foo(A);}
}

printf("Number of threads: %d", id);

How can I generate a list or array of sequential integers in Java?

This is the shortest I could find.

List version

public List<Integer> makeSequence(int begin, int end)
{
    List<Integer> ret = new ArrayList<Integer>(++end - begin);

    for (; begin < end; )
        ret.add(begin++);

    return ret;
}

Array Version

public int[] makeSequence(int begin, int end)
{
    if(end < begin)
        return null;

    int[] ret = new int[++end - begin];
    for (int i=0; begin < end; )
        ret[i++] = begin++;
    return ret;
}

OpenCV C++/Obj-C: Detecting a sheet of paper / Square Detection

Once you have detected the bounding box of the document, you can perform a four-point perspective transform to obtain a top-down birds eye view of the image. This will fix the skew and isolate only the desired object.


Input image:

Detected text object

Top-down view of text document

Code

from imutils.perspective import four_point_transform
import cv2
import numpy

# Load image, grayscale, Gaussian blur, Otsu's threshold
image = cv2.imread("1.png")
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (7,7), 0)
thresh = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]

# Find contours and sort for largest contour
cnts = cv2.findContours(thresh, cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
cnts = sorted(cnts, key=cv2.contourArea, reverse=True)
displayCnt = None

for c in cnts:
    # Perform contour approximation
    peri = cv2.arcLength(c, True)
    approx = cv2.approxPolyDP(c, 0.02 * peri, True)
    if len(approx) == 4:
        displayCnt = approx
        break

# Obtain birds' eye view of image
warped = four_point_transform(image, displayCnt.reshape(4, 2))

cv2.imshow("thresh", thresh)
cv2.imshow("warped", warped)
cv2.imshow("image", image)
cv2.waitKey()

Getting an attribute value in xml element

How about:

import java.io.File;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

public class Demo {

    public static void main(String[] args) throws Exception {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document document = db.parse(new File("input.xml"));
        NodeList nodeList = document.getElementsByTagName("Item");
        for(int x=0,size= nodeList.getLength(); x<size; x++) {
            System.out.println(nodeList.item(x).getAttributes().getNamedItem("name").getNodeValue());
        }
    }
}

Ball to Ball Collision - Detection and Handling

Well, years ago I made the program like you presented here.
There is one hidden problem (or many, depends on point of view):

  • If the speed of the ball is too high, you can miss the collision.

And also, almost in 100% cases your new speeds will be wrong. Well, not speeds, but positions. You have to calculate new speeds precisely in the correct place. Otherwise you just shift balls on some small "error" amount, which is available from the previous discrete step.

The solution is obvious: you have to split the timestep so, that first you shift to correct place, then collide, then shift for the rest of the time you have.

Play audio from a stream using C#

I haven't tried it from a WebRequest, but both the Windows Media Player ActiveX and the MediaElement (from WPF) components are capable of playing and buffering MP3 streams.

I use it to play data coming from a SHOUTcast stream and it worked great. However, I'm not sure if it will work in the scenario you propose.

Aligning a float:left div to center?

Perhaps this what you're looking for - https://www.w3schools.com/css/css3_flexbox.asp

CSS:

#container {
  display:                 flex;
  flex-wrap:               wrap;
  justify-content:         center;
}

.block {
  width:              150px;
  height:             150px;
  margin:             10px;        
}

HTML:

<div id="container">
  <div class="block">1</div>    
  <div class="block">2</div>    
  <div class="block">3</div>          
</div>

How to ignore user's time zone and force Date() use specific time zone

To account for milliseconds and the user's time zone, use the following:

var _userOffset = _date.getTimezoneOffset()*60*1000; // user's offset time
var _centralOffset = 6*60*60*1000; // 6 for central time - use whatever you need
_date = new Date(_date.getTime() - _userOffset + _centralOffset); // redefine variable

How do I add a new class to an element dynamically?

Using CSS only, no. You need to use jQuery to add it.

When to use std::size_t?

By definition, size_t is the result of the sizeof operator. size_t was created to refer to sizes.

The number of times you do something (10, in your example) is not about sizes, so why use size_t? int, or unsigned int, should be ok.

Of course it is also relevant what you do with i inside the loop. If you pass it to a function which takes an unsigned int, for example, pick unsigned int.

In any case, I recommend to avoid implicit type conversions. Make all type conversions explicit.

Getting execute permission to xp_cmdshell

Don't grant control to the user, it's totally unnecessay. Select permission on the database is enough. After you have created the login and the user on master (see above answers):

use YourDatabase
go
create user [YourDomain\YourUser] for login [YourDomain\YourUser] with default_schema=[dbo]
go
alter role [db_datareader] add member [YourDomain\YourUser]
go

How to put space character into a string name in XML?

xml:space="preserve"

Works like a charm.

Edit: Wrong. Actually, it only works when the content is comprised of white spaces only.

Link

fatal error LNK1104: cannot open file 'libboost_system-vc110-mt-gd-1_51.lib'

In case you have trouble building boost or prefer not to do that, an alternative is to download the lib files from SourceForge. The link will take you to a folder of zipped lib and dll files for version 1.51. But, you should be able to edit the link to specify the version of choice. Apparently the installer from BoostPro has some issues.

Conditional formatting using AND() function

Same issues as others reported - using Excel 2016. Found that when applying conditional formulas against tables; AND, multiplying the conditions, and adding the conditions failed. Had to create the TRUE/FALSE logic myself:

=IF($C2="SomeText",0,1)+IF(INT($D2)>1000,0,1)=0

JPA Native Query select and cast object

First of all create a model POJO

import javax.persistence.*;
@Entity
@Table(name = "sys_std_user")
public class StdUser {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "class_id")
    public int classId;
    @Column(name = "user_name")
    public String userName;
    //getter,setter
}

Controller

import com.example.demo.models.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
import java.util.List;

@RestController
public class HomeController {
    @PersistenceUnit
    private EntityManagerFactory emf;

    @GetMapping("/")
    public List<StdUser> actionIndex() {
        EntityManager em = emf.createEntityManager(); // Without parameter
        List<StdUser> arr_cust = (List<StdUser>)em
                .createQuery("SELECT c FROM StdUser c")
                .getResultList();
        return arr_cust;
    }

    @GetMapping("/paramter")
    public List actionJoin() {
        int id = 3;
        String userName = "Suresh Shrestha";
        EntityManager em = emf.createEntityManager(); // With parameter
        List arr_cust = em
                .createQuery("SELECT c FROM StdUser c WHERE c.classId = :Id ANd c.userName = :UserName")
                .setParameter("Id",id)
                .setParameter("UserName",userName)
                .getResultList();
        return arr_cust;
    }
}

SQL DROP TABLE foreign key constraint

No, this will not drop your table if there are indeed foreign keys referencing it.

To get all foreign key relationships referencing your table, you could use this SQL (if you're on SQL Server 2005 and up):

SELECT * 
FROM sys.foreign_keys
WHERE referenced_object_id = object_id('Student')

and if there are any, with this statement here, you could create SQL statements to actually drop those FK relations:

SELECT 
    'ALTER TABLE [' +  OBJECT_SCHEMA_NAME(parent_object_id) +
    '].[' + OBJECT_NAME(parent_object_id) + 
    '] DROP CONSTRAINT [' + name + ']'
FROM sys.foreign_keys
WHERE referenced_object_id = object_id('Student')

How to update column with null value

if you set NULL for all records try this:

UPDATE `table_name` SET `column_you_want_set_null`= NULL

OR just set NULL for special records use WHERE

UPDATE `table_name` SET `column_you_want_set_null`= NULL WHERE `column_name` = 'column_value' 

Which Android IDE is better - Android Studio or Eclipse?

The use of IDE is your personal preference. But personally if I had to choose, Eclipse is a widely known, trusted and certainly offers more features then Android Studio. Android Studio is a little new right now. May be it's upcoming versions keep up to Eclipse level soon.

PyCharm shows unresolved references error for valid code

For me it helped: update your main directory "mark Directory as" -> "source root"

Unable to show a Git tree in terminal

git log --oneline --decorate --all --graph

A visual tree with branch names included.

Use this to add it as an alias

git config --global alias.tree "log --oneline --decorate --all --graph"

You call it with

git tree

Git Tree

What's the difference between "Layers" and "Tiers"?

I like the below description from Microsoft Application Architecture Guide 2

Layers describe the logical groupings of the functionality and components in an application; whereas tiers describe the physical distribution of the functionality and components on separate servers, computers, networks, or remote locations. Although both layers and tiers use the same set of names (presentation, business, services, and data), remember that only tiers imply a physical separation.

Looping through a DataTable

     foreach (DataRow row in dt.Rows) 
     {
        foreach (DataColumn col in dt.Columns)
           Console.WriteLine(row[col]);
     }

How to return values in javascript

You can return an array, an object literal, or an object of a type you created that encapsulates the returned values.

Then you can pass in the array, object literal, or custom object into a method to disseminate the values.

Object example:

function myFunction(value1,value2,value3)
{
     var returnedObject = {};
     returnedObject["value1"] = value1;
     returnedObject["value2"] = value2;
     return returnedObject;
}

var returnValue = myFunction("1",value2,value3);

if(returnValue.value1  && returnValue.value2)
{
//Do some stuff
}

Array example:

function myFunction(value1,value2,value3)
{
     var returnedArray = [];
     returnedArray.push(value1);
     returnedArray.push(value2);
     return returnedArray;
}

var returnValue = myFunction("1",value2,value3);

if(returnValue[0]  && returnValue[1])
{
//Do some stuff
}

Custom Object:

function myFunction(value1,value2,value3)
{
     var valueHolder = new ValueHolder(value1, value2);
     return valueHolder;
}

var returnValue = myFunction("1",value2,value3);

// hypothetical method that you could build to create an easier to read conditional 
// (might not apply to your situation)
if(returnValue.valid())
{
//Do some stuff
}

I would avoid the array method because you would have to access the values via indices rather than named object properties.

SQL Insert into table only if record doesn't exist

This might be a simple solution to achieve this:

INSERT INTO funds (ID, date, price)
SELECT 23, DATE('2013-02-12'), 22.5
  FROM dual
 WHERE NOT EXISTS (SELECT 1 
                     FROM funds 
                    WHERE ID = 23
                      AND date = DATE('2013-02-12'));

p.s. alternatively (if ID a primary key):

 INSERT INTO funds (ID, date, price)
    VALUES (23, DATE('2013-02-12'), 22.5)
        ON DUPLICATE KEY UPDATE ID = 23; -- or whatever you need

see this Fiddle.

Darken CSS background image?

You can use the CSS3 Linear Gradient property along with your background-image like this:

#landing-wrapper {
    display:table;
    width:100%;
    background: linear-gradient( rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5) ), url('landingpagepic.jpg');
    background-position:center top;
    height:350px;
}

Here's a demo:

_x000D_
_x000D_
#landing-wrapper {_x000D_
  display: table;_x000D_
  width: 100%;_x000D_
  background: linear-gradient(rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url('http://placehold.it/350x150');_x000D_
  background-position: center top;_x000D_
  height: 350px;_x000D_
  color: white;_x000D_
}
_x000D_
<div id="landing-wrapper">Lorem ipsum dolor ismet.</div>
_x000D_
_x000D_
_x000D_

Match exact string

Use the start and end delimiters: ^abc$

How do I align views at the bottom of the screen?

You don't even need to nest the second relative layout inside the first one. Simply use the android:layout_alignParentBottom="true" in the Button and EditText.

Reading CSV file and storing values into an array

My favourite CSV parser is one built into .NET library. This is a hidden treasure inside Microsoft.VisualBasic namespace. Below is a sample code:

using Microsoft.VisualBasic.FileIO;

var path = @"C:\Person.csv"; // Habeeb, "Dubai Media City, Dubai"
using (TextFieldParser csvParser = new TextFieldParser(path))
{
 csvParser.CommentTokens = new string[] { "#" };
 csvParser.SetDelimiters(new string[] { "," });
 csvParser.HasFieldsEnclosedInQuotes = true;

 // Skip the row with the column names
 csvParser.ReadLine();

 while (!csvParser.EndOfData)
 {
  // Read current line fields, pointer moves to the next line.
  string[] fields = csvParser.ReadFields();
  string Name = fields[0];
  string Address = fields[1];
 }
}

Remember to add reference to Microsoft.VisualBasic

More details about the parser is given here: http://codeskaters.blogspot.ae/2015/11/c-easiest-csv-parser-built-in-net.html

What are the differences between type() and isinstance()?

The latter is preferred, because it will handle subclasses properly. In fact, your example can be written even more easily because isinstance()'s second parameter may be a tuple:

if isinstance(b, (str, unicode)):
    do_something_else()

or, using the basestring abstract class:

if isinstance(b, basestring):
    do_something_else()

Extracting hours from a DateTime (SQL Server 2005)

select case when [am or _pm] ='PM' and datepart(HOUR,time_received)<>12 
           then dateadd(hour,12,time_received) 
           else time_received 
       END 
from table

works

How do I add a newline to a windows-forms TextBox?

make sure you textbox is set for multiline then you wont need any extra dims vbnewline will work just fine

How to configure logging to syslog in Python?

Change the line to this:

handler = SysLogHandler(address='/dev/log')

This works for me

import logging
import logging.handlers

my_logger = logging.getLogger('MyLogger')
my_logger.setLevel(logging.DEBUG)

handler = logging.handlers.SysLogHandler(address = '/dev/log')

my_logger.addHandler(handler)

my_logger.debug('this is debug')
my_logger.critical('this is critical')

How to build a Debian/Ubuntu package from source?

If you want a quick and dirty way of installing the build dependencies, use:

apt-get build-dep

This installs the dependencies. You need sources lines in your sources.list for this:

deb-src http://ftp.nl.debian.org/debian/ squeeze-updates main contrib non-free

If you are backporting packages from testing to stable, please be advised that the dependencies might have changed. The command apt-get build-deb installs dependencies for the source packages in your current repository.

But of course, dpkg-buildpackage -us -uc will show you any uninstalled dependencies.

If you want to compile more often, use cowbuilder.

apt-get install cowbuilder

Then create a build-area:

sudo DIST=squeeze ARCH=amd64 cowbuilder --create

Then compile a source package:

apt-get source cowsay

# do your magic editing
dpkg-source -b cowsay-3.03+dfsg1              # build the new source packages
cowbuilder --build cowsay_3.03+dfsg1-2.dsc    # build the packages from source

Watch where cowbuilder puts the resulting package.

Good luck!

SQL Server Pivot Table with multiple column aggregates

The least complicated, most straight-forward way of doing this is by simply wrapping your main query with the pivot in a common table expression, then grouping/aggregating.

WITH PivotCTE AS
(
    select * from  mytransactions
    pivot (sum (totalcount) for country in ([Australia], [Austria])) as pvt
)
SELECT
    numericmonth,
    chardate,
    SUM(totalamount) AS totalamount,
    SUM(ISNULL(Australia, 0)) AS Australia,
    SUM(ISNULL(Austria, 0)) Austria
FROM PivotCTE
GROUP BY numericmonth, chardate

The ISNULL is to stop a NULL value from nullifying the sum (because NULL + any value = NULL)

Is there any simple way to convert .xls file to .csv file? (Excel)

Checkout the .SaveAs() method in Excel object.

wbWorkbook.SaveAs("c:\yourdesiredFilename.csv", Microsoft.Office.Interop.Excel.XlFileFormat.xlCSV)

Or following:

public static void SaveAs()
{
    Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.ApplicationClass();
    Microsoft.Office.Interop.Excel.Workbook wbWorkbook = app.Workbooks.Add(Type.Missing);
    Microsoft.Office.Interop.Excel.Sheets wsSheet = wbWorkbook.Worksheets;
    Microsoft.Office.Interop.Excel.Worksheet CurSheet = (Microsoft.Office.Interop.Excel.Worksheet)wsSheet[1];

    Microsoft.Office.Interop.Excel.Range thisCell = (Microsoft.Office.Interop.Excel.Range)CurSheet.Cells[1, 1];

    thisCell.Value2 = "This is a test.";

    wbWorkbook.SaveAs(@"c:\one.xls", Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlShared, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
    wbWorkbook.SaveAs(@"c:\two.csv", Microsoft.Office.Interop.Excel.XlFileFormat.xlCSVWindows, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlShared, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);

    wbWorkbook.Close(false, "", true);
}

How to start Fragment from an Activity

You can either add or replace fragment in your activity. Create a FrameLayout in activity layout xml file.

Then do this in your activity to add fragment:

FragmentManager manager = getFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.add(R.id.container,YOUR_FRAGMENT_NAME,YOUR_FRAGMENT_STRING_TAG);
transaction.addToBackStack(null);
transaction.commit();

And to replace fragment do this:

FragmentManager manager = getFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.container,YOUR_FRAGMENT_NAME,YOUR_FRAGMENT_STRING_TAG);
transaction.addToBackStack(null);
transaction.commit();

See Android documentation on adding a fragment to an activity or following related questions on SO:

Difference between add(), replace(), and addToBackStack()

Basic difference between add() and replace() method of Fragment

Difference between add() & replace() with Fragment's lifecycle

How to run a specific Android app using Terminal?

Use the cmd activity start-activity (or the alternative am start) command, which is a command-line interface to the ActivityManager. Use am to start activities as shown in this help:

$ adb shell am
usage: am [start|instrument]
       am start [-a <ACTION>] [-d <DATA_URI>] [-t <MIME_TYPE>]
                [-c <CATEGORY> [-c <CATEGORY>] ...]
                [-e <EXTRA_KEY> <EXTRA_VALUE> [-e <EXTRA_KEY> <EXTRA_VALUE> ...]
                [-n <COMPONENT>] [-D] [<URI>]
       ...

For example, to start the Contacts application, and supposing you know only the package name but not the Activity, you can use

$ pkg=com.google.android.contacts
$ comp=$(adb shell cmd package resolve-activity --brief -c android.intent.category.LAUNCHER $pkg | tail -1)
$ adb shell cmd activity start-activity $comp

or the alternative

$ adb shell am start -n $comp

See also http://www.kandroid.org/online-pdk/guide/instrumentation_testing.html (may be a copy of obsolete url : http://source.android.com/porting/instrumentation_testing.html ) for other details.

To terminate the application you can use

$ adb shell am kill com.google.android.contacts

or the more drastic

$ adb shell am force-stop com.google.android.contacts

FileSystemWatcher Changed event is raised twice

I know this is an old issue, but had the same problem and none of the above solution really did the trick for the problem I was facing. I have created a dictionary which maps the file name with the LastWriteTime. So if the file is not in the dictionary will go ahead with the process other wise check to see when was the last modified time and if is different from what it is in the dictionary run the code.

    Dictionary<string, DateTime> dateTimeDictionary = new Dictionary<string, DateTime>(); 

        private void OnChanged(object source, FileSystemEventArgs e)
            {
                if (!dateTimeDictionary.ContainsKey(e.FullPath) || (dateTimeDictionary.ContainsKey(e.FullPath) && System.IO.File.GetLastWriteTime(e.FullPath) != dateTimeDictionary[e.FullPath]))
                {
                    dateTimeDictionary[e.FullPath] = System.IO.File.GetLastWriteTime(e.FullPath);

                    //your code here
                }
            }

SQL query for a carriage return in a string and ultimately removing carriage return

This also works

SELECT TRANSLATE(STRING_WITH_NL_CR, CHAR(10) || CHAR(13), '  ') FROM DUAL;

Redirect HTTP to HTTPS on default virtual host without ServerName

Both works fine. But according to the Apache docs you should avoid using mod_rewrite for simple redirections, and use Redirect instead. So according to them, you should preferably do:

<VirtualHost *:80>
    ServerName www.example.com
    Redirect / https://www.example.com/
</VirtualHost>

<VirtualHost *:443>
    ServerName www.example.com
    # ... SSL configuration goes here
</VirtualHost>

The first / after Redirect is the url, the second part is where it should be redirected.

You can also use it to redirect URLs to a subdomain: Redirect /one/ http://one.example.com/

How to store a list in a column of a database table

If you really wanted to store it in a column and have it queryable a lot of databases support XML now. If not querying you can store them as comma separated values and parse them out with a function when you need them separated. I agree with everyone else though if you are looking to use a relational database a big part of normalization is the separating of data like that. I am not saying that all data fits a relational database though. You could always look into other types of databases if a lot of your data doesn't fit the model.

Removing multiple keys from a dictionary safely

Using dict.pop:

d = {'some': 'data'}
entries_to_remove = ('any', 'iterable')
for k in entries_to_remove:
    d.pop(k, None)

Sending email from Command-line via outlook without having to click send

Option 1
You didn't say much about your environment, but assuming you have it available you could use a PowerShell script; one example is here. The essence of this is:

$smtp = New-Object Net.Mail.SmtpClient("ho-ex2010-caht1.exchangeserverpro.net")
$smtp.Send("[email protected]","[email protected]","Test Email","This is a test")

You could then launch the script from the command line as per this example:

powershell.exe -noexit c:\scripts\test.ps1

Note that PowerShell 2.0, which is installed by default on Windows 7 and Windows Server 2008R2, includes a simpler Send-MailMessage command, making things easier.

Option 2
If you're prepared to use third-party software, is something line this SendEmail command-line tool. It depends on your target environment, though; if you're deploying your batch file to multiple machines, that will obviously require inclusion (but not formal installation) each time.

Option 3
You could drive Outlook directly from a VBA script, which in turn you would trigger from a batch file; this would let you send an email using Outlook itself, which looks to be closest to what you're wanting. There are two parts to this; first, figure out the VBA scripting required to send an email. There are lots of examples for this online, including from Microsoft here. Essence of this is:

Sub SendMessage(DisplayMsg As Boolean, Optional AttachmentPath)
    Dim objOutlook As Outlook.Application
    Dim objOutlookMsg As Outlook.MailItem
    Dim objOutlookRecip As Outlook.Recipient
    Dim objOutlookAttach As Outlook.Attachment

    Set objOutlook = CreateObject("Outlook.Application")
    Set objOutlookMsg  = objOutlook.CreateItem(olMailItem)

    With objOutlookMsg
        Set objOutlookRecip = .Recipients.Add("Nancy Davolio")
        objOutlookRecip.Type = olTo
        ' Set the Subject, Body, and Importance of the message.
        .Subject = "This is an Automation test with Microsoft Outlook"
        .Body = "This is the body of the message." &vbCrLf & vbCrLf
        .Importance = olImportanceHigh  'High importance

        If Not IsMissing(AttachmentPath) Then
            Set objOutlookAttach = .Attachments.Add(AttachmentPath)
        End If

        For Each ObjOutlookRecip In .Recipients
            objOutlookRecip.Resolve
        Next

        .Save
        .Send
    End With
    Set objOutlook = Nothing
End Sub

Then, launch Outlook from the command line with the /autorun parameter, as per this answer (alter path/macroname as necessary):

C:\Program Files\Microsoft Office\Office11\Outlook.exe" /autorun macroname

Option 4
You could use the same approach as option 3, but move the Outlook VBA into a PowerShell script (which you would run from a command line). Example here. This is probably the tidiest solution, IMO.

VirtualBox Cannot register the hard disk already exists

1 - Open the files '.vbox' and '.vbox-prev' (if exist) files in any text editor and replace the first character of HardDisk uuid (take note to revert this change on step 6)

Example: nano /home/virtualbox/WindowsServer/WindowsServer.vbox

Change:

<HardDisks>
        <HardDisk uuid="{3ebaa9b6-8318-4b81-b853-8f30dd278bdc}" location="/home/virtualbox/WindowsServer/WindowsServer.vdi" format="VDI" type="Normal"/>

To:

<HardDisks>
        <HardDisk uuid="{2ebaa9b6-8318-4b81-b853-8f30dd278bdc}" location="/home/virtualbox/WindowsServer/WindowsServer.vdi" format="VDI" type="Normal"/>

2 - Reboot machine

4 - Stop Virtual Machine (if started)

5 - On terminal:

su vbox
cd /home/virtualbox/WindowsServer/
VBoxManage modifyhd WindowsServer.vdi --resize SIZE
exit
exit

change SIZE for a number in Megabytes, example 80000 (80GB)

6 - Open again the files '.vbox' and '.vbox-prev' (if exist) files in any text editor and replace the first character of HardDisk uuid whith the original value

Example: nano /home/virtualbox/WindowsServer/WindowsServer.vbox

Change:

<HardDisks>
        <HardDisk uuid="{2ebaa9b6-8318-4b81-b853-8f30dd278bdc}" location="/home/virtualbox/WindowsServer/WindowsServer.vdi" format="VDI" type="Normal"/>

To:

<HardDisks>
        <HardDisk uuid="{3ebaa9b6-8318-4b81-b853-8f30dd278bdc}" location="/home/virtualbox/WindowsServer/WindowsServer.vdi" format="VDI" type="Normal"/>

7 - Reboot machine

How to change the value of attribute in appSettings section with Web.config transformation

You want something like:

<appSettings>
  <add key="developmentModeUserId" xdt:Transform="Remove" xdt:Locator="Match(key)"/>
  <add key="developmentMode" value="false" xdt:Transform="SetAttributes"
          xdt:Locator="Match(key)"/>
</appSettings>

See Also: Web.config Transformation Syntax for Web Application Project Deployment

Error: Java: invalid target release: 11 - IntelliJ IDEA

January 6th, 2021

This is what worked for me.

Go to File -> Project Structure and select the "Dependencies" tab on the right panel of the window. Then change the "Module SDK" using the drop-down like this. Then apply changes.

image 1

How to create a custom-shaped bitmap marker with Android map API v2

I hope it still not too late to share my solution. Before that, you can follow the tutorial as stated in Android Developer documentation. To achieve this, you need to use Cluster Manager with defaultRenderer.

  1. Create an object that implements ClusterItem

    public class SampleJob implements ClusterItem {
    
    private double latitude;
    private double longitude;
    
    //Create constructor, getter and setter here
    
    @Override
    public LatLng getPosition() {
        return new LatLng(latitude, longitude);
    }
    
  2. Create a default renderer class. This is the class that do all the job (inflating custom marker/cluster with your own style). I am using Universal image loader to do the downloading and caching the image.

    public class JobRenderer extends DefaultClusterRenderer< SampleJob > {
    
    private final IconGenerator iconGenerator;
    private final IconGenerator clusterIconGenerator;
    private final ImageView imageView;
    private final ImageView clusterImageView;
    private final int markerWidth;
    private final int markerHeight;
    private final String TAG = "ClusterRenderer";
    private DisplayImageOptions options;
    
    
    public JobRenderer(Context context, GoogleMap map, ClusterManager<SampleJob> clusterManager) {
        super(context, map, clusterManager);
    
        // initialize cluster icon generator
        clusterIconGenerator = new IconGenerator(context.getApplicationContext());
        View clusterView = LayoutInflater.from(context).inflate(R.layout.multi_profile, null);
        clusterIconGenerator.setContentView(clusterView);
        clusterImageView = (ImageView) clusterView.findViewById(R.id.image);
    
        // initialize cluster item icon generator
        iconGenerator = new IconGenerator(context.getApplicationContext());
        imageView = new ImageView(context.getApplicationContext());
        markerWidth = (int) context.getResources().getDimension(R.dimen.custom_profile_image);
        markerHeight = (int) context.getResources().getDimension(R.dimen.custom_profile_image);
        imageView.setLayoutParams(new ViewGroup.LayoutParams(markerWidth, markerHeight));
        int padding = (int) context.getResources().getDimension(R.dimen.custom_profile_padding);
        imageView.setPadding(padding, padding, padding, padding);
        iconGenerator.setContentView(imageView);
    
        options = new DisplayImageOptions.Builder()
                .showImageOnLoading(R.drawable.circle_icon_logo)
                .showImageForEmptyUri(R.drawable.circle_icon_logo)
                .showImageOnFail(R.drawable.circle_icon_logo)
                .cacheInMemory(false)
                .cacheOnDisk(true)
                .considerExifParams(true)
                .bitmapConfig(Bitmap.Config.RGB_565)
                .build();
    }
    
    @Override
    protected void onBeforeClusterItemRendered(SampleJob job, MarkerOptions markerOptions) {
    
    
        ImageLoader.getInstance().displayImage(job.getJobImageURL(), imageView, options);
        Bitmap icon = iconGenerator.makeIcon(job.getName());
        markerOptions.icon(BitmapDescriptorFactory.fromBitmap(icon)).title(job.getName());
    
    
    }
    
    @Override
    protected void onBeforeClusterRendered(Cluster<SampleJob> cluster, MarkerOptions markerOptions) {
    
        Iterator<Job> iterator = cluster.getItems().iterator();
        ImageLoader.getInstance().displayImage(iterator.next().getJobImageURL(), clusterImageView, options);
        Bitmap icon = clusterIconGenerator.makeIcon(iterator.next().getName());
        markerOptions.icon(BitmapDescriptorFactory.fromBitmap(icon));
    }
    
    @Override
    protected boolean shouldRenderAsCluster(Cluster cluster) {
        return cluster.getSize() > 1;
    }
    
  3. Apply cluster manager in your activity/fragment class.

    public class SampleActivity extends AppCompatActivity implements OnMapReadyCallback {
    
    private ClusterManager<SampleJob> mClusterManager;
    private GoogleMap mMap;
    private ArrayList<SampleJob> jobs = new ArrayList<SampleJob>();
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_landing);
    
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }
    
    
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        mMap.getUiSettings().setMapToolbarEnabled(true);
        mClusterManager = new ClusterManager<SampleJob>(this, mMap);
        mClusterManager.setRenderer(new JobRenderer(this, mMap, mClusterManager));
        mMap.setOnCameraChangeListener(mClusterManager);
        mMap.setOnMarkerClickListener(mClusterManager);
    
        //Assume that we already have arraylist of jobs
    
    
        for(final SampleJob job: jobs){
            mClusterManager.addItem(job);
        }
        mClusterManager.cluster();
    }
    
  4. Result

Result

Where Sticky Notes are saved in Windows 10 1607

It depends on the version of Windows 10 you're using. Starting with Windows 10 Anniversary Update version 1607, Sticky Notes is storing its data in the following directory:

%UserProfile%\AppData\Local\Packages\Microsoft.MicrosoftStickyNotes_8wekyb3d8bbwe

If your Windows 10 has an older version, it is storing the date in the following directory:

%UserProfile%\AppData\Roaming\Microsoft\StickyNotes\StickyNotes.snt

Difference between Return and Break statements

break is used to exit (escape) the for-loop, while-loop, switch-statement that you are currently executing.

return will exit the entire method you are currently executing (and possibly return a value to the caller, optional).

So to answer your question (as others have noted in comments and answers) you cannot use either break nor return to escape an if-else-statement per se. They are used to escape other scopes.


Consider the following example. The value of x inside the while-loop will determine if the code below the loop will be executed or not:

void f()
{
   int x = -1;
   while(true)
   {
     if(x == 0)
        break;         // escape while() and jump to execute code after the the loop 
     else if(x == 1)
        return;        // will end the function f() immediately,
                       // no further code inside this method will be executed.

     do stuff and eventually set variable x to either 0 or 1
     ...
   }

   code that will be executed on break (but not with return).
   ....
}

sudo in php exec()

It sounds like you need to set up passwordless sudo. Try:

%admin ALL=(ALL) NOPASSWD: osascript myscript.scpt

Also comment out the following line (in /etc/sudoers via visudo), if it is there:

Defaults    requiretty

Convert System.Drawing.Color to RGB and Hex Value

I found an extension method that works quite well

public static string ToHex(this Color color)
{
    return String.Format("#{0}{1}{2}{3}"
        , color.A.ToString("X").Length == 1 ? String.Format("0{0}", color.A.ToString("X")) : color.A.ToString("X")
        , color.R.ToString("X").Length == 1 ? String.Format("0{0}", color.R.ToString("X")) : color.R.ToString("X")
        , color.G.ToString("X").Length == 1 ? String.Format("0{0}", color.G.ToString("X")) : color.G.ToString("X")
        , color.B.ToString("X").Length == 1 ? String.Format("0{0}", color.B.ToString("X")) : color.B.ToString("X"));
}

Ref: https://social.msdn.microsoft.com/Forums/en-US/4c77ba6c-6659-4a46-920a-7261dd4a15d0/how-to-convert-rgba-value-into-its-equivalent-hex-code?forum=winappswithcsharp

Android Spinner: Get the selected item change event

By default, you will get the first item of the spinner array through

value = spinner.getSelectedItem().toString();

whenever you selected the value in the spinner this will give you the selected value

if you want the position of the selected item then do it like that

pos = spinner.getSelectedItemPosition();

the above two answers are for without applying listener

AES vs Blowfish for file encryption

AES.

(I also am assuming you mean twofish not the much older and weaker blowfish)

Both (AES & twofish) are good algorithms. However even if they were equal or twofish was slightly ahead on technical merit I would STILL chose AES.

Why? Publicity. AES is THE standard for government encryption and thus millions of other entities also use it. A talented cryptanalyst simply gets more "bang for the buck" finding a flaw in AES then it does for the much less know and used twofish.

Obscurity provides no protection in encryption. More bodies looking, studying, probing, attacking an algorithm is always better. You want the most "vetted" algorithm possible and right now that is AES. If an algorithm isn't subject to intense and continual scrutiny you should place a lower confidence of it's strength. Sure twofish hasn't been compromised. Is that because of the strength of the cipher or simply because not enough people have taken a close look ..... YET

Update or Insert (multiple rows and columns) from subquery in PostgreSQL

For the UPDATE

Use:

UPDATE table1 
   SET col1 = othertable.col2,
       col2 = othertable.col3 
  FROM othertable 
 WHERE othertable.col1 = 123;

For the INSERT

Use:

INSERT INTO table1 (col1, col2) 
SELECT col1, col2 
  FROM othertable

You don't need the VALUES syntax if you are using a SELECT to populate the INSERT values.

How to change the background color of a UIButton while it's highlighted?

Here's an approach in Swift, using a UIButton extension to add an IBInspectable, called highlightedBackgroundColor. Similar to subclassing, without requiring a subclass.

private var HighlightedBackgroundColorKey = 0
private var NormalBackgroundColorKey = 0

extension UIButton {

    @IBInspectable var highlightedBackgroundColor: UIColor? {
        get {
            return objc_getAssociatedObject(self, &HighlightedBackgroundColorKey) as? UIColor
        }

        set(newValue) {
            objc_setAssociatedObject(self,
                &HighlightedBackgroundColorKey, newValue, UInt(OBJC_ASSOCIATION_RETAIN))
        }
    }

    private var normalBackgroundColor: UIColor? {
        get {
            return objc_getAssociatedObject(self, &NormalBackgroundColorKey) as? UIColor
        }

        set(newValue) {
            objc_setAssociatedObject(self,
                &NormalBackgroundColorKey, newValue, UInt(OBJC_ASSOCIATION_RETAIN))
        }
    }

    override public var backgroundColor: UIColor? {
        didSet {
            if !highlighted {
                normalBackgroundColor = backgroundColor
            }
        }
    }

    override public var highlighted: Bool {
        didSet {
            if let highlightedBackgroundColor = self.highlightedBackgroundColor {
                if highlighted {
                    backgroundColor = highlightedBackgroundColor
                } else {
                    backgroundColor = normalBackgroundColor
                }
            }
        }
    }
}

I hope this helps.

Import/Index a JSON file into Elasticsearch

The right command if you want to use a file with curl is this:

curl -XPOST 'http://jfblouvmlxecs01:9200/test/_doc/1' -d @lane.json

Elasticsearch is schemaless, therefore you don't necessarily need a mapping. If you send the json as it is and you use the default mapping, every field will be indexed and analyzed using the standard analyzer.

If you want to interact with Elasticsearch through the command line, you may want to have a look at the elasticshell which should be a little bit handier than curl.

2019-07-10: Should be noted that custom mapping types is deprecated and should not be used. I updated the type in the url above to make it easier to see which was the index and which was the type as having both named "test" was confusing.

Using Eloquent ORM in Laravel to perform search of database using LIKE

You're able to do database finds using LIKE with this syntax:

Model::where('column', 'LIKE', '%value%')->get();

Create timestamp variable in bash script

ISO 8601 format (2018-12-23T12:34:56) is more readable than UNIX timestamp. However on some OSs you cannot have : in the filenames. Therefore I recommend using something like this instead:

2018-12-23_12-34-56

You can use the following command to get the timestamp in this format:

TIMESTAMP=`date +%Y-%m-%d_%H-%M-%S`

This is the format I have seen many applications use. Another nice thing about this is that if your file names start with this, you can sort them alphabetically and they would be sorted by date.

Zsh: Conda/Pip installs command not found

You need to fix the spacing and quotes:

export PATH ="/Users/Dz/anaconda/bin:$PATH"

Instead use

export PATH="/Users/Dz/anaconda/bin":$PATH

How to enable NSZombie in Xcode?

Product > Profile will pop up Instruments. Select zombies from the panel and go nuts.

Set textbox to readonly and background color to grey in jquery

If supported by your browser, you may use CSS3 :read-only selector:

input[type="text"]:read-only {
    cursor: normal;
    background-color: #f8f8f8;
    color: #999;
}

setTimeout in for-loop does not print consecutive values

You have to arrange for a distinct copy of "i" to be present for each of the timeout functions.

function doSetTimeout(i) {
  setTimeout(function() { alert(i); }, 100);
}

for (var i = 1; i <= 2; ++i)
  doSetTimeout(i);

If you don't do something like this (and there are other variations on this same idea), then each of the timer handler functions will share the same variable "i". When the loop is finished, what's the value of "i"? It's 3! By using an intermediating function, a copy of the value of the variable is made. Since the timeout handler is created in the context of that copy, it has its own private "i" to use.

edit — there have been a couple of comments over time in which some confusion was evident over the fact that setting up a few timeouts causes the handlers to all fire at the same time. It's important to understand that the process of setting up the timer — the calls to setTimeout() — take almost no time at all. That is, telling the system, "Please call this function after 1000 milliseconds" will return almost immediately, as the process of installing the timeout request in the timer queue is very fast.

Thus, if a succession of timeout requests is made, as is the case in the code in the OP and in my answer, and the time delay value is the same for each one, then once that amount of time has elapsed all the timer handlers will be called one after another in rapid succession.

If what you need is for the handlers to be called at intervals, you can either use setInterval(), which is called exactly like setTimeout() but which will fire more than once after repeated delays of the requested amount, or instead you can establish the timeouts and multiply the time value by your iteration counter. That is, to modify my example code:

function doScaledTimeout(i) {
  setTimeout(function() {
    alert(i);
  }, i * 5000);
}

(With a 100 millisecond timeout, the effect won't be very obvious, so I bumped the number up to 5000.) The value of i is multiplied by the base delay value, so calling that 5 times in a loop will result in delays of 5 seconds, 10 seconds, 15 seconds, 20 seconds, and 25 seconds.

Update

Here in 2018, there is a simpler alternative. With the new ability to declare variables in scopes more narrow than functions, the original code would work if so modified:

for (let i = 1; i <= 2; i++) {
    setTimeout(function() { alert(i) }, 100);
}

The let declaration, unlike var, will itself cause there to be a distinct i for each iteration of the loop.

How to activate the Bootstrap modal-backdrop?

Just append a div with that class to body, then remove it when you're done:

// Show the backdrop
$('<div class="modal-backdrop"></div>').appendTo(document.body);

// Remove it (later)
$(".modal-backdrop").remove();

Live Example:

_x000D_
_x000D_
$("input").click(function() {_x000D_
  var bd = $('<div class="modal-backdrop"></div>');_x000D_
  bd.appendTo(document.body);_x000D_
  setTimeout(function() {_x000D_
    bd.remove();_x000D_
  }, 2000);_x000D_
});
_x000D_
<link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css" rel="stylesheet" type="text/css" />_x000D_
<script src="//code.jquery.com/jquery.min.js"></script>_x000D_
<script src="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/js/bootstrap.min.js"></script>_x000D_
<p>Click the button to get the backdrop for two seconds.</p>_x000D_
<input type="button" value="Click Me">
_x000D_
_x000D_
_x000D_

How to list all the roles existing in Oracle database?

all_roles.sql

SELECT SUBSTR(TRIM(rtp.role),1,12)          AS ROLE
     , SUBSTR(rp.grantee,1,16)              AS GRANTEE
     , SUBSTR(TRIM(rtp.privilege),1,12)     AS PRIVILEGE
     , SUBSTR(TRIM(rtp.owner),1,12)         AS OWNER
     , SUBSTR(TRIM(rtp.table_name),1,28)    AS TABLE_NAME
     , SUBSTR(TRIM(rtp.column_name),1,20)   AS COLUMN_NAME
     , SUBSTR(rtp.common,1,4)               AS COMMON
     , SUBSTR(rtp.grantable,1,4)            AS GRANTABLE
     , SUBSTR(rp.default_role,1,16)         AS DEFAULT_ROLE
     , SUBSTR(rp.admin_option,1,4)          AS ADMIN_OPTION
  FROM role_tab_privs rtp
  LEFT JOIN dba_role_privs rp
    ON (rtp.role = rp.granted_role)
 WHERE ('&1' IS NULL OR UPPER(rtp.role) LIKE UPPER('%&1%'))
   AND ('&2' IS NULL OR UPPER(rp.grantee) LIKE UPPER('%&2%'))
   AND ('&3' IS NULL OR UPPER(rtp.table_name) LIKE UPPER('%&3%'))
   AND ('&4' IS NULL OR UPPER(rtp.owner) LIKE UPPER('%&4%'))
 ORDER BY 1
        , 2
        , 3
        , 4
;

Usage

SQLPLUS> @all_roles '' '' '' '' '' ''
SQLPLUS> @all_roles 'somerol' '' '' '' '' ''
SQLPLUS> @all_roles 'roler' 'username' '' '' '' ''
SQLPLUS> @all_roles '' '' 'part-of-database-package-name' '' '' ''
etc.

move_uploaded_file gives "failed to open stream: Permission denied" error

I ran into this related issue even after having already successfully run composer. I updated composer, and when running composer install or php composer.phar install I got:

...failed to open stream: Permission denied...

It turns out after much research that the previous answers regarding changing permissions for the folder worked. They are just slightly different directories now.

In my install, on OS X, the cache file is in /Users/[USER]/.composer/cache, and I was having trouble because the cache file was owned by root. Changing ownership of '.composer' recursively to my user solved the issue.

This is what I did:

sudo chown -R [USER] cache

Then I ran the composer install again and voila!

Select a date from date picker using Selenium webdriver

I think there will be different ways to select a Date for different Date picker formats. For a Date Picker where you need to select a year and month from a dropdown and then pick/click a Date, I wrote the following code.

private void setupDate(WebDriver driver, String csvRow) throws Exception {
    String date[] = (csvRow).split("-");
    driver.findElement(By.id("flddateanchor")).click();
    new Select(driver.findElement(By
            .cssSelector("select.ui-datepicker-year")))
            .selectByVisibleText(date[0]);
    Thread.sleep(1000);
    new Select(driver.findElement(By
            .cssSelector("select.ui-datepicker-month")))
            .selectByVisibleText(date[1]);
    Thread.sleep(1000);
    driver.findElement(By.linkText(date[2])).click();
    Thread.sleep(1000);
}

I got the cssSelector part by the Selenium Firefox IDE. Also, my Date(csvRow) is in (2015-03-31) format.

Hope it helps.

What does operator "dot" (.) mean?

The dot itself is not an operator, .^ is.

The .^ is a pointwise¹ (i.e. element-wise) power, as .* is the pointwise product.

.^ Array power. A.^B is the matrix with elements A(i,j) to the B(i,j) power. The sizes of A and B must be the same or be compatible.

C.f.

¹) Hence the dot.

Why can't I change my input value in React even with the onChange listener

Unlike in the case of Angular, in React.js you need to update the state manually. You can do something like this:

<input
    className="form-control"
    type="text" value={this.state.name}
    id={'todoName' + this.props.id}
    onChange={e => this.onTodoChange(e.target.value)}
/>

And then in the function:

onTodoChange(value){
        this.setState({
             name: value
        });
    }

Also, you can set the initial state in the constructor of the component:

  constructor (props) {
    super(props);
    this.state = {
        updatable: false,
        name: props.name,
        status: props.status
    };
  }

Implicit type conversion rules in C++ operators

In C++ operators (for POD types) always act on objects of the same type.
Thus if they are not the same one will be promoted to match the other.
The type of the result of the operation is the same as operands (after conversion).

If either is      long          double the other is promoted to      long          double
If either is                    double the other is promoted to                    double
If either is                    float  the other is promoted to                    float
If either is long long unsigned int    the other is promoted to long long unsigned int
If either is long long          int    the other is promoted to long long          int
If either is long      unsigned int    the other is promoted to long      unsigned int
If either is long               int    the other is promoted to long               int
If either is           unsigned int    the other is promoted to           unsigned int
If either is                    int    the other is promoted to                    int
Both operands are promoted to int

Note. The minimum size of operations is int. So short/char are promoted to int before the operation is done.

In all your expressions the int is promoted to a float before the operation is performed. The result of the operation is a float.

int + float =>  float + float = float
int * float =>  float * float = float
float * int =>  float * float = float
int / float =>  float / float = float
float / int =>  float / float = float
int / int                     = int
int ^ float =>  <compiler error>

Pyspark: Exception: Java gateway process exited before sending the driver its port number

This is an old thread but I'm adding my solution for those who use mac.

The issue was with the JAVA_HOME. You have to include this in your .bash_profile.

Check your java -version. If you downloaded the latest Java but it doesn't show up as the latest version, then you know that the path is wrong. Normally, the default path is export JAVA_HOME= /usr/bin/java.

So try changing the path to: /Library/Internet\ Plug-Ins/JavaAppletPlugin.plugin/Contents/Home/bin/java

Alternatively you could also download the latest JDK. https://www.oracle.com/technetwork/java/javase/downloads/index.html and this will automatically replace usr/bin/java to the latest version. You can confirm this by doing java -version again.

Then that should work.

How can the Euclidean distance be calculated with NumPy?

I find a 'dist' function in matplotlib.mlab, but I don't think it's handy enough.

I'm posting it here just for reference.

import numpy as np
import matplotlib as plt

a = np.array([1, 2, 3])
b = np.array([2, 3, 4])

# Distance between a and b
dis = plt.mlab.dist(a, b)

How to get the selected radio button value using js

Try this, I hope this one will work

function loadRadioButton(objectName, selectedValue) {

    var radioButtons = document.getElementsByName(objectName);

    if (radioButtons != null) {
        for (var radioCount = 0; radioCount < radioButtons.length; radioCount++) {
            if (radioButtons[radioCount].value == selectedValue) {
                radioButtons[radioCount].checked = true;
            }
        }
    }
}

What does the servlet <load-on-startup> value signify

  1. If value is same for two servlet than they will be loaded in an order on which they are declared inside web.xml file.
  2. if is 0 or negative integer than Servlet will be loaded when Container feels to load them.
  3. guarantees loading, initialization and call to init() method of servlet by web container.
  4. If there is no element for any servlet than they will be loaded when web container decides to load them.

When increasing the size of VARCHAR column on a large table could there be any problems?

Just wanted to add my 2 cents, since I googled this question b/c I found myself in a similar situation...

BE AWARE that while changing from varchar(xxx) to varchar(yyy) is a meta-data change indeed, but changing to varchar(max) is not. Because varchar(max) values (aka BLOB values - image/text etc) are stored differently on the disk, not within a table row, but "out of row". So the server will go nuts on a big table and become unresponsive for minutes (hours).

--no downtime
ALTER TABLE MyTable ALTER COLUMN [MyColumn] VARCHAR(1200)

--huge downtime
ALTER TABLE MyTable ALTER COLUMN [MyColumn] VARCHAR(max)

PS. same applies to nvarchar or course.

'MOD' is not a recognized built-in function name

for your exact sample, it should be like this.

DECLARE @m INT
SET @m = 321%11
SELECT @m

What is the easiest way to remove the first character from a string?

list = [1,2,3,4] list.drop(1)

# => [2,3,4]

List drops one or more elements from the start of the array, does not mutate the array, and returns the array itself instead of the dropped element.

How do I search a Perl array for a matching string?

It depends on what you want the search to do:

  • if you want to find all matches, use the built-in grep:

    my @matches = grep { /pattern/ } @list_of_strings;
    
  • if you want to find the first match, use first in List::Util:

    use List::Util 'first';  
    my $match = first { /pattern/ } @list_of_strings;
    
  • if you want to find the count of all matches, use true in List::MoreUtils:

    use List::MoreUtils 'true';
    my $count = true { /pattern/ } @list_of_strings;
    
  • if you want to know the index of the first match, use first_index in List::MoreUtils:

    use List::MoreUtils 'first_index'; 
    my $index = first_index { /pattern/ } @list_of_strings;
    
  • if you want to simply know if there was a match, but you don't care which element it was or its value, use any in List::Util:

    use List::Util 1.33 'any';
    my $match_found = any { /pattern/ } @list_of_strings;
    

All these examples do similar things at their core, but their implementations have been heavily optimized to be fast, and will be faster than any pure-perl implementation that you might write yourself with grep, map or a for loop.


Note that the algorithm for doing the looping is a separate issue than performing the individual matches. To match a string case-insensitively, you can simply use the i flag in the pattern: /pattern/i. You should definitely read through perldoc perlre if you have not previously done so.

Visual Studio Code always asking for git credentials

I had a similar problem in Visual Studio Code.

I solved by changing the remote url to https. (in file .git/config)

[remote "origin"]
    url = https://[email protected]/plesk-git/project.git

and also

git config --global credential.helper wincred

pulled again, windows credential popup came out, problems solved.

php - add + 7 days to date format mm dd, YYYY

The "+1 month" issue with strtotime

As noted in several blogs, strtotime() solves the "+1 month" ("next month") issue on days that do not exist in the subsequent month differently than other implementations like for example MySQL.

$dt = date("Y-m-d");
echo date( "Y-m-d", strtotime( "$dt +1 day" ) ); // PHP:  2009-03-04
echo date( "Y-m-d", strtotime( "2009-01-31 +2 month" ) ); // PHP:  2009-03-31

How can I get the UUID of my Android phone in an application?

<uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>

C++ floating point to integer type conversions

Normal way is to:

float f = 3.4;
int n = static_cast<int>(f);

for or while loop to do something n times

The fundamental difference in most programming languages is that unless the unexpected happens a for loop will always repeat n times or until a break statement, (which may be conditional), is met then finish with a while loop it may repeat 0 times, 1, more or even forever, depending on a given condition which must be true at the start of each loop for it to execute and always false on exiting the loop, (for completeness a do ... while loop, (or repeat until), for languages that have it, always executes at least once and does not guarantee the condition on the first execution).

It is worth noting that in Python a for or while statement can have break, continue and else statements where:

  • break - terminates the loop
  • continue - moves on to the next time around the loop without executing following code this time around
  • else - is executed if the loop completed without any break statements being executed.

N.B. In the now unsupported Python 2 range produced a list of integers but you could use xrange to use an iterator. In Python 3 range returns an iterator.

So the answer to your question is 'it all depends on what you are trying to do'!

Test if number is odd or even

//checking even and odd
$num =14;

$even = ($num % 2 == 0);
$odd = ($num % 2 != 0);

if($even){
    echo "Number is even.";
} else {
    echo "Number is odd.";
}

CSS: Position text in the middle of the page

Even though you've accepted an answer, I want to post this method. I use jQuery to center it vertically instead of css (although both of these methods work). Here is a fiddle, and I'll post the code here anyways.

HTML:

<h1>Hello world!</h1>

Javascript (jQuery):

$(document).ready(function(){
  $('h1').css({ 'width':'100%', 'text-align':'center' });
  var h1 = $('h1').height();
  var h = h1/2;
  var w1 = $(window).height();
  var w = w1/2;
  var m = w - h
  $('h1').css("margin-top",m + "px")
});

This takes the height of the viewport, divides it by two, subtracts half the height of the h1, and sets that number to the margin-top of the h1. The beauty of this method is that it works on multiple-line h1s.

EDIT: I modified it so that it centered it every time the window is resized.

res.sendFile absolute path

process.cwd() returns the absolute path of your project.

Then :

res.sendFile( `${process.cwd()}/public/index1.html` );

Download File Using Javascript/jQuery

I have had good results with using a FORM tag since it works everywhere and you don't have to create temporarily files on server. The method works like this.

On the client side (page HTML) you create an invisible form like this

<form method="POST" action="/download.php" target="_blank" id="downloadForm">
    <input type="hidden" name="data" id="csv">
</form>

Then you add this Javascript code to your button:

$('#button').click(function() {
     $('#csv').val('---your data---');
     $('#downloadForm').submit();
}

The on the server-side you have the following PHP code in download.php:

<?php
header('Content-Type: text/csv');
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=out.csv');
header('Content-Transfer-Encoding: binary');
header('Connection: Keep-Alive');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . strlen($data));

echo $_REQUEST['data'];
exit();

You can even create zip files of your data like this:

<?php

$file = tempnam("tmp", "zip");

$zip = new ZipArchive();
$zip->open($file, ZipArchive::OVERWRITE);
$zip->addFromString('test.csv', $_REQUEST['data']);
$zip->close();

header('Content-Type: application/zip');
header('Content-Length: ' . filesize($file));
header('Content-Disposition: attachment; filename="file.zip"');
readfile($file);
unlink($file); 

The best part is it does not leave any residual files on your server since everything is created and destroyed on the fly!

Timing Delays in VBA

I use this little function for VBA.

Public Function Pause(NumberOfSeconds As Variant)
    On Error GoTo Error_GoTo

    Dim PauseTime As Variant
    Dim Start As Variant
    Dim Elapsed As Variant

    PauseTime = NumberOfSeconds
    Start = Timer
    Elapsed = 0
    Do While Timer < Start + PauseTime
        Elapsed = Elapsed + 1
        If Timer = 0 Then
            ' Crossing midnight
            PauseTime = PauseTime - Elapsed
            Start = 0
            Elapsed = 0
        End If
        DoEvents
    Loop

Exit_GoTo:
    On Error GoTo 0
    Exit Function
Error_GoTo:
    Debug.Print Err.Number, Err.Description, Erl
    GoTo Exit_GoTo
End Function

How can I load webpage content into a div on page load?

Take a look into jQuery's .load() function:

<script>
    $(function(){
        $('#siteloader').load('http://www.somesitehere.com');
    });
</script>

However, this only works on the same domain of the JS file.

Git mergetool generates unwanted .orig files

You have to be a little careful with using kdiff3 as while git mergetool can be configured to save a .orig file during merging, the default behaviour for kdiff3 is to also save a .orig backup file independently of git mergetool.

You have to make sure that mergetool backup is off:

git config --global mergetool.keepBackup false

and also that kdiff3's settings are set to not create a backup:

Configure/Options => Directory Merge => Backup Files (*.orig)

Regular expression for extracting tag attributes

splattne,

@VonC solution partly works but there is some issue if the tag had a mixed of unquoted and quoted

This one works with mixed attributes

$pat_attributes = "(\S+)=(\"|'| |)(.*)(\"|'| |>)"

to test it out

<?php
$pat_attributes = "(\S+)=(\"|'| |)(.*)(\"|'| |>)"

$code = '    <IMG title=09.jpg alt=09.jpg src="http://example.com.jpg?v=185579" border=0 mce_src="example.com.jpg?v=185579"
    ';

preg_match_all( "@$pat_attributes@isU", $code, $ms);
var_dump( $ms );

$code = '
<a href=test.html class=xyz>
<a href="test.html" class="xyz">
<a href=\'test.html\' class="xyz">
<img src="http://"/>      ';

preg_match_all( "@$pat_attributes@isU", $code, $ms);

var_dump( $ms );

$ms would then contain keys and values on the 2nd and 3rd element.

$keys = $ms[1];
$values = $ms[2];

How to run Maven from another directory (without cd to project dir)?

You can try this:

pushd ../
maven install [...]
popd

pandas: How do I split text in a column into multiple rows?

Differently from Dan, I consider his answer quite elegant... but unfortunately it is also very very inefficient. So, since the question mentioned "a large csv file", let me suggest to try in a shell Dan's solution:

time python -c "import pandas as pd;
df = pd.DataFrame(['a b c']*100000, columns=['col']);
print df['col'].apply(lambda x : pd.Series(x.split(' '))).head()"

... compared to this alternative:

time python -c "import pandas as pd;
from scipy import array, concatenate;
df = pd.DataFrame(['a b c']*100000, columns=['col']);
print pd.DataFrame(concatenate(df['col'].apply( lambda x : [x.split(' ')]))).head()"

... and this:

time python -c "import pandas as pd;
df = pd.DataFrame(['a b c']*100000, columns=['col']);
print pd.DataFrame(dict(zip(range(3), [df['col'].apply(lambda x : x.split(' ')[i]) for i in range(3)]))).head()"

The second simply refrains from allocating 100 000 Series, and this is enough to make it around 10 times faster. But the third solution, which somewhat ironically wastes a lot of calls to str.split() (it is called once per column per row, so three times more than for the others two solutions), is around 40 times faster than the first, because it even avoids to instance the 100 000 lists. And yes, it is certainly a little ugly...

EDIT: this answer suggests how to use "to_list()" and to avoid the need for a lambda. The result is something like

time python -c "import pandas as pd;
df = pd.DataFrame(['a b c']*100000, columns=['col']);
print pd.DataFrame(df.col.str.split().tolist()).head()"

which is even more efficient than the third solution, and certainly much more elegant.

EDIT: the even simpler

time python -c "import pandas as pd;
df = pd.DataFrame(['a b c']*100000, columns=['col']);
print pd.DataFrame(list(df.col.str.split())).head()"

works too, and is almost as efficient.

EDIT: even simpler! And handles NaNs (but less efficient):

time python -c "import pandas as pd;
df = pd.DataFrame(['a b c']*100000, columns=['col']);
print df.col.str.split(expand=True).head()"

C dynamically growing array

I can use pointers, but I am a bit afraid of using them.

If you need a dynamic array, you can't escape pointers. Why are you afraid though? They won't bite (as long as you're careful, that is). There's no built-in dynamic array in C, you'll just have to write one yourself. In C++, you can use the built-in std::vector class. C# and just about every other high-level language also have some similar class that manages dynamic arrays for you.

If you do plan to write your own, here's something to get you started: most dynamic array implementations work by starting off with an array of some (small) default size, then whenever you run out of space when adding a new element, double the size of the array. As you can see in the example below, it's not very difficult at all: (I've omitted safety checks for brevity)

typedef struct {
  int *array;
  size_t used;
  size_t size;
} Array;

void initArray(Array *a, size_t initialSize) {
  a->array = malloc(initialSize * sizeof(int));
  a->used = 0;
  a->size = initialSize;
}

void insertArray(Array *a, int element) {
  // a->used is the number of used entries, because a->array[a->used++] updates a->used only *after* the array has been accessed.
  // Therefore a->used can go up to a->size 
  if (a->used == a->size) {
    a->size *= 2;
    a->array = realloc(a->array, a->size * sizeof(int));
  }
  a->array[a->used++] = element;
}

void freeArray(Array *a) {
  free(a->array);
  a->array = NULL;
  a->used = a->size = 0;
}

Using it is just as simple:

Array a;
int i;

initArray(&a, 5);  // initially 5 elements
for (i = 0; i < 100; i++)
  insertArray(&a, i);  // automatically resizes as necessary
printf("%d\n", a.array[9]);  // print 10th element
printf("%d\n", a.used);  // print number of elements
freeArray(&a);

HorizontalScrollView within ScrollView Touch Handling

Thanks to Neevek his answer worked for me but it doesn't lock the vertical scrolling when user has started scrolling the horizontal view(ViewPager) in horizontal direction and then without lifting the finger scroll vertically it starts to scroll the underlying container view(ScrollView). I fixed it by making a slight change in Neevak's code:

private float xDistance, yDistance, lastX, lastY;

int lastEvent=-1;

boolean isLastEventIntercepted=false;
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
    switch (ev.getAction()) {
        case MotionEvent.ACTION_DOWN:
            xDistance = yDistance = 0f;
            lastX = ev.getX();
            lastY = ev.getY();


            break;

        case MotionEvent.ACTION_MOVE:
            final float curX = ev.getX();
            final float curY = ev.getY();
            xDistance += Math.abs(curX - lastX);
            yDistance += Math.abs(curY - lastY);
            lastX = curX;
            lastY = curY;

            if(isLastEventIntercepted && lastEvent== MotionEvent.ACTION_MOVE){
                return false;
            }

            if(xDistance > yDistance )
                {

                isLastEventIntercepted=true;
                lastEvent = MotionEvent.ACTION_MOVE;
                return false;
                }


    }

    lastEvent=ev.getAction();

    isLastEventIntercepted=false;
    return super.onInterceptTouchEvent(ev);

}

Reading a single char in Java

You can use Scanner like so:

Scanner s= new Scanner(System.in);
char x = s.next().charAt(0);

By using the charAt function you are able to get the value of the first char without using external casting.

Find all files in a folder

A lot of these answers won't actually work, having tried them myself. Give this a go:

string filepath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
DirectoryInfo d = new DirectoryInfo(filepath);

foreach (var file in d.GetFiles("*.txt"))
{
      Directory.Move(file.FullName, filepath + "\\TextFiles\\" + file.Name);
}

It will move all .txt files on the desktop to the folder TextFiles.

How do you list the primary key of a SQL Server table?

I like the INFORMATION_SCHEMA technique, but another I've used is: exec sp_pkeys 'table'

How do I use the built in password reset/change views with my own templates

The documentation says that there only one context variable, form.

If you're having trouble with login (which is common), the documentation says there are three context variables:

  • form: A Form object representing the login form. See the forms documentation for more on Form objects.
  • next: The URL to redirect to after successful login. This may contain a query string, too.
  • site_name: The name of the current Site, according to the SITE_ID setting.

C++ array initialization

Yes, this form of initialization is supported by all C++ compilers. It is a part of C++ language. In fact, it is an idiom that came to C++ from C language. In C language = { 0 } is an idiomatic universal zero-initializer. This is also almost the case in C++.

Since this initalizer is universal, for bool array you don't really need a different "syntax". 0 works as an initializer for bool type as well, so

bool myBoolArray[ARRAY_SIZE] = { 0 };

is guaranteed to initialize the entire array with false. As well as

char* myPtrArray[ARRAY_SIZE] = { 0 };

in guaranteed to initialize the whole array with null-pointers of type char *.

If you believe it improves readability, you can certainly use

bool myBoolArray[ARRAY_SIZE] = { false };
char* myPtrArray[ARRAY_SIZE] = { nullptr };

but the point is that = { 0 } variant gives you exactly the same result.

However, in C++ = { 0 } might not work for all types, like enum types, for example, which cannot be initialized with integral 0. But C++ supports the shorter form

T myArray[ARRAY_SIZE] = {};

i.e. just an empty pair of {}. This will default-initialize an array of any type (assuming the elements allow default initialization), which means that for basic (scalar) types the entire array will be properly zero-initialized.

Tree view of a directory/folder in Windows?

TreeSize professional has what you want. but it focus on the sizes of folders and files.

Joda DateTime to Timestamp conversion

//This Works just fine
DateTime dt = new DateTime();
Log.d("ts",String.valueOf(dt.now()));               
dt=dt.plusYears(3);
dt=dt.minusDays(7);
Log.d("JODA DateTime",String.valueOf(dt));
Timestamp ts= new Timestamp(dt.getMillis());
Log.d("Coverted to java.sql.Timestamp",String.valueOf(ts));

How to dismiss notification after action has been clicked

You will need to run the following code after your intent is fired to remove the notification.

NotificationManagerCompat.from(this).cancel(null, notificationId);

NB: notificationId is the same id passed to run your notification

Forcing label to flow inline with input that they label

<style>
.nowrap {
    white-space: nowrap;
}
</style>

...

<label for="id1" class="nowrap">label1:
    <input type="text" id="id1"/>
</label>

Wrap your inputs within the label tag

PHP & MySQL: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given

The query either returned no rows or is erroneus, thus FALSE is returned. Change it to

if (!$dbc || mysqli_num_rows($dbc) == 0)

mysqli_num_rows:

Return Values

Returns TRUE on success or FALSE on failure. For SELECT, SHOW, DESCRIBE or EXPLAIN mysqli_query() will return a result object.

jQuery $.cookie is not a function

Check that you included the script in header and not in footer of the page. Particularly in WordPress this one didn't work:

wp_register_script('cookie', get_template_directory_uri() . '/js/jquery.cookie.js', array(), false, true);

The last parameter indicates including the script in footer and needed to be changed to false (default). The way it worked:

wp_register_script('cookie', get_template_directory_uri() . '/js/jquery.cookie.js');

Editing specific line in text file in Python

def replace_line(file_name, line_num, text):
    lines = open(file_name, 'r').readlines()
    lines[line_num] = text
    out = open(file_name, 'w')
    out.writelines(lines)
    out.close()

And then:

replace_line('stats.txt', 0, 'Mage')

Can I have multiple :before pseudo-elements for the same element?

In CSS2.1, an element can only have at most one of any kind of pseudo-element at any time. (This means an element can have both a :before and an :after pseudo-element — it just cannot have more than one of each kind.)

As a result, when you have multiple :before rules matching the same element, they will all cascade and apply to a single :before pseudo-element, as with a normal element. In your example, the end result looks like this:

.circle.now:before {
    content: "Now";
    font-size: 19px;
    color: black;
}

As you can see, only the content declaration that has highest precedence (as mentioned, the one that comes last) will take effect — the rest of the declarations are discarded, as is the case with any other CSS property.

This behavior is described in the Selectors section of CSS2.1:

Pseudo-elements behave just like real elements in CSS with the exceptions described below and elsewhere.

This implies that selectors with pseudo-elements work just like selectors for normal elements. It also means the cascade should work the same way. Strangely, CSS2.1 appears to be the only reference; neither css3-selectors nor css3-cascade mention this at all, and it remains to be seen whether it will be clarified in a future specification.

If an element can match more than one selector with the same pseudo-element, and you want all of them to apply somehow, you will need to create additional CSS rules with combined selectors so that you can specify exactly what the browser should do in those cases. I can't provide a complete example including the content property here, since it's not clear for instance whether the symbol or the text should come first. But the selector you need for this combined rule is either .circle.now:before or .now.circle:before — whichever selector you choose is personal preference as both selectors are equivalent, it's only the value of the content property that you will need to define yourself.

If you still need a concrete example, see my answer to this similar question.

The legacy css3-content specification contains a section on inserting multiple ::before and ::after pseudo-elements using a notation that's compatible with the CSS2.1 cascade, but note that that particular document is obsolete — it hasn't been updated since 2003, and no one has implemented that feature in the past decade. The good news is that the abandoned document is actively undergoing a rewrite in the guise of css-content-3 and css-pseudo-4. The bad news is that the multiple pseudo-elements feature is nowhere to be found in either specification, presumably owing, again, to lack of implementer interest.

Split array into chunks

my trick is to use parseInt(i/chunkSize) and parseInt(i%chunkSize) and then filling the array

_x000D_
_x000D_
// filling items_x000D_
let array = [];_x000D_
for(let i = 0; i< 543; i++)_x000D_
  array.push(i);_x000D_
 _x000D_
 // printing the splitted array_x000D_
 console.log(getSplittedArray(array, 50));_x000D_
 _x000D_
 // get the splitted array_x000D_
 function getSplittedArray(array, chunkSize){_x000D_
  let chunkedArray = [];_x000D_
  for(let i = 0; i<array.length; i++){_x000D_
    try{_x000D_
      chunkedArray[parseInt(i/chunkSize)][parseInt(i%chunkSize)] = array[i];_x000D_
    }catch(e){_x000D_
      chunkedArray[parseInt(i/chunkSize)] = [];_x000D_
      chunkedArray[parseInt(i/chunkSize)][parseInt(i%chunkSize)] = array[i];_x000D_
    }_x000D_
  }_x000D_
  return chunkedArray;_x000D_
 }
_x000D_
_x000D_
_x000D_

How to run docker-compose up -d at system start up?

You should be able to add:

restart: always 

to every service you want to restart in the docker-compose.yml file.

See: https://github.com/compose-spec/compose-spec/blob/master/spec.md#restart

Clearing input in vuejs form

What you need is to set this.text to an empty string in your submitForm function:

submitForm(e){
    this.todos.push(
        {
            text: this.text,
            completed: false
        }
    );
    this.text = "";

    // To prevent the form from submitting
    e.preventDefault();
}

Remember that binding works both ways: The (input) view can update the (string) model, or the model can update the view.

ERROR 1044 (42000): Access denied for 'root' With All Privileges

The reason i could not delete some of the users via 'drop' statement was that there is a bug in Mysql http://bugs.mysql.com/bug.php?id=62255 with hostname containing upper case letters. The solution was running following query:

DELETE FROM mysql.user where host='Some_Host_With_UpperCase_Letters';

I am still trying to figure the other issue where the root user with all permissions are unable to grant privileges to new user for particular database

How do I find the last column with data?

I know this is old, but I've tested this in many ways and it hasn't let me down yet, unless someone can tell me otherwise.

Row number

Row = ws.Cells.Find(What:="*", After:=[A1] , SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row

Column Letter

ColumnLetter = Split(ws.Cells.Find(What:="*", After:=[A1], SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Cells.Address(1, 0), "$")(0)

Column Number

ColumnNumber = ws.Cells.Find(What:="*", After:=[A1], SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column

MySQL stored procedure vs function, which would I use when?

A stored function can be used within a query. You could then apply it to every row, or within a WHERE clause.

A procedure is executed using the CALL query.

Purpose of Activator.CreateInstance with example?

You can also do this -

var handle = Activator.CreateInstance("AssemblyName", 
                "Full name of the class including the namespace and class name");
var obj = handle.Unwrap();

Unable to obtain LocalDateTime from TemporalAccessor when parsing LocalDateTime (Java 8)

Try this one:

DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("MM-dd-yyyy"); 
LocalDate fromLocalDate = LocalDate.parse(fromdstrong textate, dateTimeFormatter);

You can add any format you want. That works for me!

How can I convert a string to an int in Python?

>>> a = "123"
>>> int(a)
123

Here's some freebie code:

def getTwoNumbers():
    numberA = raw_input("Enter your first number: ")
    numberB = raw_input("Enter your second number: ")
    return int(numberA), int(numberB)

Call a function after previous function is complete

If you're using jQuery 1.5 you can use the new Deferreds pattern:

$('a.button').click(function(){
    if(condition == 'true'){
        $.when(function1()).then(function2());
    }
    else {
        doThis(someVariable);
    }
});

Edit: Updated blog link:

Rebecca Murphy had a great write-up on this here: http://rmurphey.com/blog/2010/12/25/deferreds-coming-to-jquery/

Bridged networking not working in Virtualbox under Windows 10

I solved it with similar way to @Khalil's but I attched to 'Bridged Adapter' instead of 'Host-only Adapter'. Here is more detail with screenshots.

How do I display a MySQL error in PHP for a long query that depends on the user input?

One useful line of code for you would be:

$sql = "Your SQL statement here";
$result = mysqli_query($this->db_link, $sql) or trigger_error("Query Failed! SQL: $sql - Error: ".mysqli_error($this->db_link), E_USER_ERROR);

This method is better than die, because you can use it for development AND production. It's the permanent solution.

Difference between Static methods and Instance methods

Static methods, variables belongs to the whole class, not just an object instance. A static method, variable is associated with the class as a whole rather than with specific instances of a class. Each object will share a common copy of the static methods, variables. There is only one copy per class, no matter how many objects are created from it.

How to use componentWillMount() in React Hooks?

useLayoutEffect could accomplish this with an empty set of observers ([]) if the functionality is actually similar to componentWillMount -- it will run before the first content gets to the DOM -- though there are actually two updates but they are synchronous before drawing to the screen.

for example:


function MyComponent({ ...andItsProps }) {
     useLayoutEffect(()=> {
          console.log('I am about to render!');
     },[]);

     return (<div>some content</div>);
}

The benefit over useState with an initializer/setter or useEffect is though it may compute a render pass, there are no actual re-renders to the DOM that a user will notice, and it is run before the first noticable render, which is not the case for useEffect. The downside is of course a slight delay in your first render since a check/update has to happen before painting to screen. It really does depend on your use-case, though.

I think personally, useMemo is fine in some niche cases where you need to do something heavy -- as long as you keep in mind it is the exception vs the norm.

How do I compare two variables containing strings in JavaScript?

I used below function to compare two strings and It is working good.

function CompareUserId (first, second)
{

   var regex = new RegExp('^' + first+ '$', 'i');
   if (regex.test(second)) 
   {
        return true;
   }
   else 
   {
        return false;
   }
   return false;
}

How to use npm with ASP.NET Core

I give you two answers. npm combined with other tools is powerful but requires some work to setup. If you just want to download some libraries, you might want to use Library Manager instead (released in Visual Studio 15.8).

NPM (Advanced)

First add package.json in the root of you project. Add the following content:

{
  "version": "1.0.0",
  "name": "asp.net",
  "private": true,
  "devDependencies": {
    "gulp": "3.9.1",
    "del": "3.0.0"
  },
  "dependencies": {
    "jquery": "3.3.1",
    "jquery-validation": "1.17.0",
    "jquery-validation-unobtrusive": "3.2.10",
    "bootstrap": "3.3.7"
  }
}

This will make NPM download Bootstrap, JQuery and other libraries that is used in a new asp.net core project to a folder named node_modules. Next step is to copy the files to an appropriate place. To do this we will use gulp, which also was downloaded by NPM. Then add a new file in the root of you project named gulpfile.js. Add the following content:

/// <binding AfterBuild='default' Clean='clean' />
/*
This file is the main entry point for defining Gulp tasks and using Gulp plugins.
Click here to learn more. http://go.microsoft.com/fwlink/?LinkId=518007
*/

var gulp = require('gulp');
var del = require('del');

var nodeRoot = './node_modules/';
var targetPath = './wwwroot/lib/';

gulp.task('clean', function () {
    return del([targetPath + '/**/*']);
});

gulp.task('default', function () {
    gulp.src(nodeRoot + "bootstrap/dist/js/*").pipe(gulp.dest(targetPath + "/bootstrap/dist/js"));
    gulp.src(nodeRoot + "bootstrap/dist/css/*").pipe(gulp.dest(targetPath + "/bootstrap/dist/css"));
    gulp.src(nodeRoot + "bootstrap/dist/fonts/*").pipe(gulp.dest(targetPath + "/bootstrap/dist/fonts"));

    gulp.src(nodeRoot + "jquery/dist/jquery.js").pipe(gulp.dest(targetPath + "/jquery/dist"));
    gulp.src(nodeRoot + "jquery/dist/jquery.min.js").pipe(gulp.dest(targetPath + "/jquery/dist"));
    gulp.src(nodeRoot + "jquery/dist/jquery.min.map").pipe(gulp.dest(targetPath + "/jquery/dist"));

    gulp.src(nodeRoot + "jquery-validation/dist/*.js").pipe(gulp.dest(targetPath + "/jquery-validation/dist"));

    gulp.src(nodeRoot + "jquery-validation-unobtrusive/dist/*.js").pipe(gulp.dest(targetPath + "/jquery-validation-unobtrusive"));
});

This file contains a JavaScript code that is executed when the project is build and cleaned. It’s will copy all necessary files to lib2 (not lib – you can easily change this). I have used the same structure as in a new project, but it’s easy to change files to a different location. If you move the files, make sure you also update _Layout.cshtml. Note that all files in the lib2-directory will be removed when the project is cleaned.

If you right click on gulpfile.js, you can select Task Runner Explorer. From here you can run gulp manually to copy or clean files.

Gulp could also be useful for other tasks like minify JavaScript and CSS-files:

https://docs.microsoft.com/en-us/aspnet/core/client-side/using-gulp?view=aspnetcore-2.1

Library Manager (Simple)

Right click on you project and select Manage client side-libraries. The file libman.json is now open. In this file you specify which library and files to use and where they should be stored locally. Really simple! The following file copies the default libraries that is used when creating a new ASP.NET Core 2.1 project:

{
  "version": "1.0",
  "defaultProvider": "cdnjs",
  "libraries": [
    {
      "library": "[email protected]",
      "files": [ "jquery.js", "jquery.min.map", "jquery.min.js" ],
      "destination": "wwwroot/lib/jquery/dist/"
    },
    {
      "library": "[email protected]",
      "files": [ "additional-methods.js", "additional-methods.min.js", "jquery.validate.js", "jquery.validate.min.js" ],
      "destination": "wwwroot/lib/jquery-validation/dist/"
    },
    {
      "library": "[email protected]",
      "files": [ "jquery.validate.unobtrusive.js", "jquery.validate.unobtrusive.min.js" ],
      "destination": "wwwroot/lib/jquery-validation-unobtrusive/"
    },
    {
      "library": "[email protected]",
      "files": [
        "css/bootstrap.css",
        "css/bootstrap.css.map",
        "css/bootstrap.min.css",
        "css/bootstrap.min.css.map",
        "css/bootstrap-theme.css",
        "css/bootstrap-theme.css.map",
        "css/bootstrap-theme.min.css",
        "css/bootstrap-theme.min.css.map",
        "fonts/glyphicons-halflings-regular.eot",
        "fonts/glyphicons-halflings-regular.svg",
        "fonts/glyphicons-halflings-regular.ttf",
        "fonts/glyphicons-halflings-regular.woff",
        "fonts/glyphicons-halflings-regular.woff2",
        "js/bootstrap.js",
        "js/bootstrap.min.js",
        "js/npm.js"
      ],
      "destination": "wwwroot/lib/bootstrap/dist"
    },
    {
      "library": "[email protected]",
      "files": [ "list.js", "list.min.js" ],
      "destination": "wwwroot/lib/listjs"
    }
  ]
}

If you move the files, make sure you also update _Layout.cshtml.

How to add new line in Markdown presentation?

It depends on what kind of markdown parser you're using. For example in showdownjs there is an option {simpleLineBreaks: true} which gives corresponding html for the following md input:

a line
wrapped in two
<p>a line<br>
wrapped in two</p>

Find and Replace text in the entire table using a MySQL query

phpMyAdmin includes a neat find-and-replace tool.

Select the table, then hit Search > Find and replace

This query took about a minute and successfully replaced several thousand instances of oldurl.ext with the newurl.ext within Column post_content

screenshot of the find-and-replace feature in phpMyAdmin

Best thing about this method : You get to check every match before committing.

N.B. I am using phpMyAdmin 4.9.0.1

Send JavaScript variable to PHP variable

As Jordan already said you have to post back the javascript variable to your server before the server can handle the value. To do this you can either program a javascript function that submits a form - or you can use ajax / jquery. jQuery.post

Maybe the most easiest approach for you is something like this

function myJavascriptFunction() { 
  var javascriptVariable = "John";
  window.location.href = "myphpfile.php?name=" + javascriptVariable; 
}

On your myphpfile.php you can use $_GET['name'] after your javascript was executed.

Regards

How to add url parameter to the current url?

It is not elegant but possible to do it as one-liner <a> element

_x000D_
_x000D_
<a href onclick="event.preventDefault(); location+='&like=like'">Like</a>
_x000D_
_x000D_
_x000D_

What does the Excel range.Rows property really do?

Since the .Rows result is marked as consisting of rows, you can "For Each" it to deal with each row individually, like this:

Function Attendance(rng As Range) As Long
Attendance = 0
For Each rRow In rng.Rows
    If WorksheetFunction.Sum(rRow) > 0 Then
        Attendance = Attendance + 1
    End If
Next
End Function

I use this to check attendance in any of a few categories (different columns) for a list of people (different rows).

(And of course you could use .Columns to do a "For Each" over the columns in the range.)

What is the use of BindingResult interface in spring MVC?

It's important to note that the order of parameters is actually important to spring. The BindingResult needs to come right after the Form that is being validated. Likewise, the [optional] Model parameter needs to come after the BindingResult. Example:

Valid:

@RequestMapping(value = "/entry/updateQuantity", method = RequestMethod.POST)
public String updateEntryQuantity(@Valid final UpdateQuantityForm form,
                                  final BindingResult bindingResult,
                                  @RequestParam("pk") final long pk,
                                  final Model model) {
}

Not Valid:

RequestMapping(value = "/entry/updateQuantity", method = RequestMethod.POST)
public String updateEntryQuantity(@Valid final UpdateQuantityForm form,
                                  @RequestParam("pk") final long pk,
                                  final BindingResult bindingResult,
                                  final Model model) {
}

How to Set RadioButtonFor() in ASp.net MVC 2 as Checked by default

I find it best to just put the default value in the constructor method of the model.

Gender = "Male";

How to use class from other files in C# with visual studio?

Yeah, I just made the same 'noob' error and found this thread. I had in fact added the class to the solution and not to the project. So it looked like this:

Wrong and right description

Just adding this in the hope to be of help to someone.

Iterating over a 2 dimensional python list

This is the correct way.

>>> x = [ ['0,0', '0,1'], ['1,0', '1,1'], ['2,0', '2,1'] ]
>>> for i in range(len(x)):
        for j in range(len(x[i])):
                print(x[i][j])


0,0
0,1
1,0
1,1
2,0
2,1
>>> 

How do I do word Stemming or Lemmatization?

Martin Porter's official page contains a Porter Stemmer in PHP as well as other languages.

If you're really serious about good stemming though you're going to need to start with something like the Porter Algorithm, refine it by adding rules to fix incorrect cases common to your dataset, and then finally add a lot of exceptions to the rules. This can be easily implemented with key/value pairs (dbm/hash/dictionaries) where the key is the word to look up and the value is the stemmed word to replace the original. A commercial search engine I worked on once ended up with 800 some exceptions to a modified Porter algorithm.

Create a folder and sub folder in Excel VBA

This is a recursive version that works with letter drives as well as UNC. I used the error catching to implement it but if anyone can do one without, I would be interested to see it. This approach works from the branches to the root so it will be somewhat usable when you don't have permissions in the root and lower parts of the directory tree.

' Reverse create directory path. This will create the directory tree from the top    down to the root.
' Useful when working on network drives where you may not have access to the directories close to the root
Sub RevCreateDir(strCheckPath As String)
    On Error GoTo goUpOneDir:
    If Len(Dir(strCheckPath, vbDirectory)) = 0 And Len(strCheckPath) > 2 Then
        MkDir strCheckPath
    End If
    Exit Sub
' Only go up the tree if error code Path not found (76).
goUpOneDir:
    If Err.Number = 76 Then
        Call RevCreateDir(Left(strCheckPath, InStrRev(strCheckPath, "\") - 1))
        Call RevCreateDir(strCheckPath)
    End If
End Sub

List all files in one directory PHP

You are looking for the command scandir.

$path    = '/tmp';
$files = scandir($path);

Following code will remove . and .. from the returned array from scandir:

$files = array_diff(scandir($path), array('.', '..'));

Bootstrap 3 select input form inline

Can be done with pure Bootstrap code.

_x000D_
_x000D_
<link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/css/bootstrap.css" rel="stylesheet"/>_x000D_
_x000D_
<div class="form-group">_x000D_
  <label for="id" class="col-md-2 control-label">ID</label>_x000D_
  <div class="input-group">_x000D_
    <span class="input-group-btn">_x000D_
      <select class="form-control" name="id" id="id">_x000D_
        <option value="">_x000D_
      </select>_x000D_
    </span>_x000D_
    <span class="input-group-btn">_x000D_
      <select class="form-control" name="nr" id="nr">_x000D_
        <option value="">_x000D_
      </select>_x000D_
    </span>_x000D_
  </div> _x000D_
</div> 
_x000D_
_x000D_
_x000D_

Compare 2 JSON objects

Simply parsing the JSON and comparing the two objects is not enough because it wouldn't be the exact same object references (but might be the same values).

You need to do a deep equals.

From http://threebit.net/mail-archive/rails-spinoffs/msg06156.html - which seems the use jQuery.

Object.extend(Object, {
   deepEquals: function(o1, o2) {
     var k1 = Object.keys(o1).sort();
     var k2 = Object.keys(o2).sort();
     if (k1.length != k2.length) return false;
     return k1.zip(k2, function(keyPair) {
       if(typeof o1[keyPair[0]] == typeof o2[keyPair[1]] == "object"){
         return deepEquals(o1[keyPair[0]], o2[keyPair[1]])
       } else {
         return o1[keyPair[0]] == o2[keyPair[1]];
       }
     }).all();
   }
});

Usage:

var anObj = JSON.parse(jsonString1);
var anotherObj= JSON.parse(jsonString2);

if (Object.deepEquals(anObj, anotherObj))
   ...

Meaning of .Cells(.Rows.Count,"A").End(xlUp).row

It is used to find the how many rows contain data in a worksheet that contains data in the column "A". The full usage is

 lastRowIndex = ws.Cells(ws.Rows.Count, "A").End(xlUp).row

Where ws is a Worksheet object. In the questions example it was implied that the statement was inside a With block

With ws
    lastRowIndex = .Cells(.Rows.Count, "A").End(xlUp).row
End With
  1. ws.Rows.Count returns the total count of rows in the worksheet (1048576 in Excel 2010).
  2. .Cells(.Rows.Count, "A") returns the bottom most cell in column "A" in the worksheet

Then there is the End method. The documentation is ambiguous as to what it does.

Returns a Range object that represents the cell at the end of the region that contains the source range

Particularly it doesn't define what a "region" is. My understanding is a region is a contiguous range of non-empty cells. So the expected usage is to start from a cell in a region and find the last cell in that region in that direction from the original cell. However there are multiple exceptions for when you don't use it like that:

  • If the range is multiple cells, it will use the region of rng.cells(1,1).
  • If the range isn't in a region, or the range is already at the end of the region, then it will travel along the direction until it enters a region and return the first encountered cell in that region.
  • If it encounters the edge of the worksheet it will return the cell on the edge of that worksheet.

So Range.End is not a trivial function.

  1. .row returns the row index of that cell.

angular 2 how to return data from subscribe

You just can't return the value directly because it is an async call. An async call means it is running in the background (actually scheduled for later execution) while your code continues to execute.

You also can't have such code in the class directly. It needs to be moved into a method or the constructor.

What you can do is not to subscribe() directly but use an operator like map()

export class DataComponent{
    someMethod() {
      return this.http.get(path).map(res => {
        return res.json();
      });
    }
}

In addition, you can combine multiple .map with the same Observables as sometimes this improves code clarity and keeps things separate. Example:

validateResponse = (response) => validate(response);

parseJson = (json) => JSON.parse(json);

fetchUnits() {
    return this.http.get(requestUrl).map(this.validateResponse).map(this.parseJson);
}

This way an observable will be return the caller can subscribe to

export class DataComponent{
    someMethod() {
      return this.http.get(path).map(res => {
        return res.json();
      });
    }

    otherMethod() {
      this.someMethod().subscribe(data => this.data = data);
    }
}

The caller can also be in another class. Here it's just for brevity.

data => this.data = data

and

res => return res.json()

are arrow functions. They are similar to normal functions. These functions are passed to subscribe(...) or map(...) to be called from the observable when data arrives from the response. This is why data can't be returned directly, because when someMethod() is completed, the data wasn't received yet.

Why can't I use a list as a dict key in python?

There's a good article on the topic in the Python wiki: Why Lists Can't Be Dictionary Keys. As explained there:

What would go wrong if you tried to use lists as keys, with the hash as, say, their memory location?

It can be done without really breaking any of the requirements, but it leads to unexpected behavior. Lists are generally treated as if their value was derived from their content's values, for instance when checking (in-)equality. Many would - understandably - expect that you can use any list [1, 2] to get the same key, where you'd have to keep around exactly the same list object. But lookup by value breaks as soon as a list used as key is modified, and for lookup by identity requires you to keep around exactly the same list - which isn't requires for any other common list operation (at least none I can think of).

Other objects such as modules and object make a much bigger deal out of their object identity anyway (when was the last time you had two distinct module objects called sys?), and are compared by that anyway. Therefore, it's less surprising - or even expected - that they, when used as dict keys, compare by identity in that case as well.

How do I move to end of line in Vim?

  • $ moves to the last character on the line.
  • g _ goes to the last non-whitespace character.

  • g $ goes to the end of the screen line (when a buffer line is wrapped across multiple screen lines)

Convert seconds to HH-MM-SS with JavaScript?

This does the trick:

function secondstotime(secs)
{
    var t = new Date(1970,0,1);
    t.setSeconds(secs);
    var s = t.toTimeString().substr(0,8);
    if(secs > 86399)
        s = Math.floor((t - Date.parse("1/1/70")) / 3600000) + s.substr(2);
    return s;
}

(Sourced from here)

Error creating bean with name 'entityManagerFactory

Adding dependencies didn't fix the issue at my end.

The issue was happening at my end because of "additional" fields that are part of the "@Entity" class and don't exist in the database.

I removed the additional fields from the @Entity class and it worked.

What are NR and FNR and what does "NR==FNR" imply?

In awk, FNR refers to the record number (typically the line number) in the current file and NR refers to the total record number. The operator == is a comparison operator, which returns true when the two surrounding operands are equal.

This means that the condition NR==FNR is only true for the first file, as FNR resets back to 1 for the first line of each file but NR keeps on increasing.

This pattern is typically used to perform actions on only the first file. The next inside the block means any further commands are skipped, so they are only run on files other than the first.

The condition FNR==NR compares the same two operands as NR==FNR, so it behaves in the same way.

What does file:///android_asset/www/index.html mean?

The URI "file:///android_asset/" points to YourProject/app/src/main/assets/.

Note: android_asset/ uses the singular (asset) and src/main/assets uses the plural (assets).

Suppose you have a file YourProject/app/src/main/assets/web_thing.html that you would like to display in a WebView. You can refer to it like this:

WebView webViewer = (WebView) findViewById(R.id.webViewer);
webView.loadUrl("file:///android_asset/web_thing.html");

The snippet above could be located in your Activity class, possibly in the onCreate method.

Here is a guide to the overall directory structure of an android project, that helped me figure out this answer.

Get data from JSON file with PHP

Try:
$data = file_get_contents ("file.json");
        $json = json_decode($data, true);
        foreach ($json as $key => $value) {
            if (!is_array($value)) {
                echo $key . '=>' . $value . '<br/>';
            } else {
                foreach ($value as $key => $val) {
                    echo $key . '=>' . $val . '<br/>';
                }
            }
        }

IntelliJ - Convert a Java project/module into a Maven project/module

Just follow the steps:

  1. Right click to on any module pox.xml and then chose "Add as Maven Project"

enter image description here

  1. Next to varify it, go to the maven tab, you will see the project with all maven goal which you can use:

enter image description here

Center align with table-cell

Here is a good starting point.

HTML:

<div class="containing-table">
    <div class="centre-align">
        <div class="content"></div>
    </div>
</div>

CSS:

.containing-table {
    display: table;
    width: 100%;
    height: 400px; /* for demo only */
    border: 1px dotted blue;
}
.centre-align {
    padding: 10px;
    border: 1px dashed gray;
    display: table-cell;
    text-align: center;
    vertical-align: middle;
}
.content {
    width: 50px;
    height: 50px;
    background-color: red;
    display: inline-block;
    vertical-align: top; /* Removes the extra white space below the baseline */
}

See demo at: http://jsfiddle.net/audetwebdesign/jSVyY/

.containing-table establishes the width and height context for .centre-align (the table-cell).

You can apply text-align and vertical-align to alter .centre-align as needed.

Note that .content needs to use display: inline-block if it is to be centered horizontally using the text-align property.

Force div element to stay in same place, when page is scrolled

You can do this replacing position:absolute; by position:fixed;.

What is the difference between private and protected members of C++ classes?

Attributes and methods marked as protected are -- unlike private ones -- still visible in subclasses.

Unless you don't want to use or provide the possibility to override the method in possible subclasses, I'd make them private.

CSS: Change image src on img:hover

Fiddle

Agree with AshisKumar's answer,
there is a way to change image url on mouse over by using jQuery functionality as below:

$(function() {
  $("img")
    .mouseover(function() { 
        var src = $(this).attr("src").match(/[^\.]+/) + "over.gif";
        $(this).attr("src", url1); //URL @the time of mouse over on image
    })
    .mouseout(function() {
        var src = $(this).attr("src").replace("over", "");
        $(this).attr("src", url2); //default URL
    });
 });

Space between border and content? / Border distance from content?

Add padding. Padding the element will increase the space between its content and its border. However, note that a box-shadow will begin outside the border, not the content, meaning you can't put space between the shadow and the box. Alternatively you could use :before or :after pseudo selectors on the element to create a slightly bigger box that you place the shadow on, like so: http://jsbin.com/aqemew/edit#source

Carry Flag, Auxiliary Flag and Overflow Flag in Assembly

Carry Flag is a flag set when:

a) two unsigned numbers were added and the result is larger than "capacity" of register where it is saved. Ex: we wanna add two 8 bit numbers and save result in 8 bit register. In your example: 255 + 9 = 264 which is more that 8 bit register can store. So the value "8" will be saved there (264 & 255 = 8) and CF flag will be set.

b) two unsigned numbers were subtracted and we subtracted the bigger one from the smaller one. Ex: 1-2 will give you 255 in result and CF flag will be set.

Auxiliary Flag is used as CF but when working with BCD. So AF will be set when we have overflow or underflow on in BCD calculations. For example: considering 8 bit ALU unit, Auxiliary flag is set when there is carry from 3rd bit to 4th bit i.e. carry from lower nibble to higher nibble. (Wiki link)

Overflow Flag is used as CF but when we work on signed numbers. Ex we wanna add two 8 bit signed numbers: 127 + 2. the result is 129 but it is too much for 8bit signed number, so OF will be set. Similar when the result is too small like -128 - 1 = -129 which is out of scope for 8 bit signed numbers.

You can read more about flags on wikipedia

Exporting functions from a DLL with dllexport

I had exactly the same problem, my solution was to use module definition file (.def) instead of __declspec(dllexport) to define exports(http://msdn.microsoft.com/en-us/library/d91k01sh.aspx). I have no idea why this works, but it does

Java and SQLite

Typo: java -cp .:sqlitejdbc-v056.jar Test

should be: java -cp .:sqlitejdbc-v056.jar; Test

notice the semicolon after ".jar" i hope that helps people, could cause a lot of hassle

Return multiple values from a SQL Server function

Example of using a stored procedure with multiple out parameters

As User Mr. Brownstone suggested you can use a stored procedure; to make it easy for all i created a minimalist example. First create a stored procedure:

Create PROCEDURE MultipleOutParameter
    @Input int,
    @Out1 int OUTPUT, 
    @Out2 int OUTPUT 
AS
BEGIN
    Select @Out1 = @Input + 1
    Select @Out2 = @Input + 2   
    Select 'this returns your normal Select-Statement' as Foo
          , 'amazing is it not?' as Bar

    -- Return can be used to get even more (afaik only int) values 
    Return(@Out1+@Out2+@Input)
END 

Calling the stored procedure

To execute the stored procedure a few local variables are needed to receive the value:

DECLARE @GetReturnResult int, @GetOut1 int, @GetOut2 int 
EXEC @GetReturnResult = MultipleOutParameter  
    @Input = 1,
    @Out1 = @GetOut1 OUTPUT,
    @Out2 = @GetOut2 OUTPUT

To see the values content you can do the following

Select @GetReturnResult as ReturnResult, @GetOut1 as Out_1, @GetOut2 as Out_2 

This will be the result:

Result of Stored Procedure Call with multiple out parameters

How to write UPDATE SQL with Table alias in SQL Server 2008?

You can always take the CTE, (Common Tabular Expression), approach.

;WITH updateCTE AS
(
    SELECT ID, TITLE 
    FROM HOLD_TABLE
    WHERE ID = 101
)

UPDATE updateCTE
SET TITLE = 'TEST';

How do I check in SQLite whether a table exists?

Use:

PRAGMA table_info(your_table_name)

If the resulting table is empty then your_table_name doesn't exist.

Documentation:

PRAGMA schema.table_info(table-name);

This pragma returns one row for each column in the named table. Columns in the result set include the column name, data type, whether or not the column can be NULL, and the default value for the column. The "pk" column in the result set is zero for columns that are not part of the primary key, and is the index of the column in the primary key for columns that are part of the primary key.

The table named in the table_info pragma can also be a view.

Example output:

cid|name|type|notnull|dflt_value|pk
0|id|INTEGER|0||1
1|json|JSON|0||0
2|name|TEXT|0||0

How to write to a CSV line by line?

You could just write to the file as you would write any normal file.

with open('csvfile.csv','wb') as file:
    for l in text:
        file.write(l)
        file.write('\n')

If just in case, it is a list of lists, you could directly use built-in csv module

import csv

with open("csvfile.csv", "wb") as file:
    writer = csv.writer(file)
    writer.writerows(text)

How to check if a process is running via a batch script

Under Windows you can use Windows Management Instrumentation (WMI) to ensure that no apps with the specified command line is launched, for example:

wmic process where (name="nmake.exe") get commandline | findstr /i /c:"/f load.mak" /c:"/f build.mak" > NUL && (echo THE BUILD HAS BEEN STARTED ALREADY! > %ALREADY_STARTED% & exit /b 1)

How to align center the text in html table row?

The CSS to center text in your td elements is

td {
  text-align: center;
  vertical-align: middle;
}

Rubymine: How to make Git ignore .idea files created by Rubymine

Use .ignore plugin: https://plugins.jetbrains.com/plugin/7495--ignore

It manages a lot of paths/patterns for you automatically and also has many useful extra features. It's compatible with:

  • IntelliJ IDEA
  • PhpStorm
  • WebStorm
  • PyCharm
  • RubyMine
  • AppCode
  • CLion
  • GoLand
  • DataGrip
  • Rider
  • MPS
  • Android Studio

Remove a string from the beginning of a string

str_replace ( mixed $search , mixed $replace , mixed $subject [, int &$count ] )

now does what you want.

$str = "bla_string_bla_bla_bla";
str_replace("bla_","",$str,1);

How to extract file name from path?

I needed the path, not the filename.

So to extract the file path in code:

JustPath = Left(sFileP, Len(sFileP) - Len(Split(sFileP, "\")(UBound(Split(sFileP, "\"))))) 

Uncaught ReferenceError: $ is not defined error in jQuery

Include the jQuery file first:

 <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
 <script type="text/javascript" src="./javascript.js"></script>
    <script
        src="http://maps.googleapis.com/maps/api/js?key=AIzaSyCJnj2nWoM86eU8Bq2G4lSNz3udIkZT4YY&sensor=false">
    </script>

Exception thrown in catch and finally clause

class MyExc1 extends Exception {}
class MyExc2 extends Exception {}
class MyExc3 extends MyExc2 {}

public class C1 {
    public static void main(String[] args) throws Exception {
        try {
            System.out.print("TryA L1\n");
            q();
            System.out.print("TryB L1\n");
        }
        catch (Exception i) {
            System.out.print("Catch L1\n");                
        }
        finally {
            System.out.print("Finally L1\n");
            throw new MyExc1();
        }
    }

    static void q() throws Exception {
        try {
            System.out.print("TryA L2\n");
            q2();
            System.out.print("TryB L2\n");
        }
        catch (Exception y) {
            System.out.print("Catch L2\n");
            throw new MyExc2();  
        }
        finally {
            System.out.print("Finally L2\n");
            throw new Exception();
        }
    }

    static void q2() throws Exception {
        throw new MyExc1();
    }
}

Order:

TryA L1
TryA L2
Catch L2
Finally L2
Catch L1
Finally L1        
Exception in thread "main" MyExc1 at C1.main(C1.java:30)

https://www.compilejava.net/

How to compress an image via Javascript in the browser?

I see two things missing from the other answers:

  • canvas.toBlob (when available) is more performant than canvas.toDataURL, and also async.
  • the file -> image -> canvas -> file conversion loses EXIF data; in particular, data about image rotation commonly set by modern phones/tablets.

The following script deals with both points:

// From https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob, needed for Safari:
if (!HTMLCanvasElement.prototype.toBlob) {
    Object.defineProperty(HTMLCanvasElement.prototype, 'toBlob', {
        value: function(callback, type, quality) {

            var binStr = atob(this.toDataURL(type, quality).split(',')[1]),
                len = binStr.length,
                arr = new Uint8Array(len);

            for (var i = 0; i < len; i++) {
                arr[i] = binStr.charCodeAt(i);
            }

            callback(new Blob([arr], {type: type || 'image/png'}));
        }
    });
}

window.URL = window.URL || window.webkitURL;

// Modified from https://stackoverflow.com/a/32490603, cc by-sa 3.0
// -2 = not jpeg, -1 = no data, 1..8 = orientations
function getExifOrientation(file, callback) {
    // Suggestion from http://code.flickr.net/2012/06/01/parsing-exif-client-side-using-javascript-2/:
    if (file.slice) {
        file = file.slice(0, 131072);
    } else if (file.webkitSlice) {
        file = file.webkitSlice(0, 131072);
    }

    var reader = new FileReader();
    reader.onload = function(e) {
        var view = new DataView(e.target.result);
        if (view.getUint16(0, false) != 0xFFD8) {
            callback(-2);
            return;
        }
        var length = view.byteLength, offset = 2;
        while (offset < length) {
            var marker = view.getUint16(offset, false);
            offset += 2;
            if (marker == 0xFFE1) {
                if (view.getUint32(offset += 2, false) != 0x45786966) {
                    callback(-1);
                    return;
                }
                var little = view.getUint16(offset += 6, false) == 0x4949;
                offset += view.getUint32(offset + 4, little);
                var tags = view.getUint16(offset, little);
                offset += 2;
                for (var i = 0; i < tags; i++)
                    if (view.getUint16(offset + (i * 12), little) == 0x0112) {
                        callback(view.getUint16(offset + (i * 12) + 8, little));
                        return;
                    }
            }
            else if ((marker & 0xFF00) != 0xFF00) break;
            else offset += view.getUint16(offset, false);
        }
        callback(-1);
    };
    reader.readAsArrayBuffer(file);
}

// Derived from https://stackoverflow.com/a/40867559, cc by-sa
function imgToCanvasWithOrientation(img, rawWidth, rawHeight, orientation) {
    var canvas = document.createElement('canvas');
    if (orientation > 4) {
        canvas.width = rawHeight;
        canvas.height = rawWidth;
    } else {
        canvas.width = rawWidth;
        canvas.height = rawHeight;
    }

    if (orientation > 1) {
        console.log("EXIF orientation = " + orientation + ", rotating picture");
    }

    var ctx = canvas.getContext('2d');
    switch (orientation) {
        case 2: ctx.transform(-1, 0, 0, 1, rawWidth, 0); break;
        case 3: ctx.transform(-1, 0, 0, -1, rawWidth, rawHeight); break;
        case 4: ctx.transform(1, 0, 0, -1, 0, rawHeight); break;
        case 5: ctx.transform(0, 1, 1, 0, 0, 0); break;
        case 6: ctx.transform(0, 1, -1, 0, rawHeight, 0); break;
        case 7: ctx.transform(0, -1, -1, 0, rawHeight, rawWidth); break;
        case 8: ctx.transform(0, -1, 1, 0, 0, rawWidth); break;
    }
    ctx.drawImage(img, 0, 0, rawWidth, rawHeight);
    return canvas;
}

function reduceFileSize(file, acceptFileSize, maxWidth, maxHeight, quality, callback) {
    if (file.size <= acceptFileSize) {
        callback(file);
        return;
    }
    var img = new Image();
    img.onerror = function() {
        URL.revokeObjectURL(this.src);
        callback(file);
    };
    img.onload = function() {
        URL.revokeObjectURL(this.src);
        getExifOrientation(file, function(orientation) {
            var w = img.width, h = img.height;
            var scale = (orientation > 4 ?
                Math.min(maxHeight / w, maxWidth / h, 1) :
                Math.min(maxWidth / w, maxHeight / h, 1));
            h = Math.round(h * scale);
            w = Math.round(w * scale);

            var canvas = imgToCanvasWithOrientation(img, w, h, orientation);
            canvas.toBlob(function(blob) {
                console.log("Resized image to " + w + "x" + h + ", " + (blob.size >> 10) + "kB");
                callback(blob);
            }, 'image/jpeg', quality);
        });
    };
    img.src = URL.createObjectURL(file);
}

Example usage:

inputfile.onchange = function() {
    // If file size > 500kB, resize such that width <= 1000, quality = 0.9
    reduceFileSize(this.files[0], 500*1024, 1000, Infinity, 0.9, blob => {
        let body = new FormData();
        body.set('file', blob, blob.name || "file.jpg");
        fetch('/upload-image', {method: 'POST', body}).then(...);
    });
};

bitwise XOR of hex numbers in python

Whoa. You're really over-complicating it by a very long distance. Try:

>>> print hex(0x12ef ^ 0xabcd)
0xb922

You seem to be ignoring these handy facts, at least:

  • Python has native support for hexadecimal integer literals, with the 0x prefix.
  • "Hexadecimal" is just a presentation detail; the arithmetic is done in binary, and then the result is printed as hex.
  • There is no connection between the format of the inputs (the hexadecimal literals) and the output, there is no such thing as a "hexadecimal number" in a Python variable.
  • The hex() function can be used to convert any number into a hexadecimal string for display.

If you already have the numbers as strings, you can use the int() function to convert to numbers, by providing the expected base (16 for hexadecimal numbers):

>>> print int("12ef", 16)
4874

So you can do two conversions, perform the XOR, and then convert back to hex:

>>> print hex(int("12ef", 16) ^ int("abcd", 16))
0xb922

The filename, directory name, or volume label syntax is incorrect inside batch

set myPATH="C:\Users\DEB\Downloads\10.1.1.0.4"
cd %myPATH%
  • The single quotes do not indicate a string, they make it starts: 'C:\ instead of C:\ so

  • %name% is the usual syntax for expanding a variable, the !name! syntax needs to be enabled using the command setlocal ENABLEDELAYEDEXPANSION first, or by running the command prompt with CMD /V:ON.

  • Don't use PATH as your name, it is a system name that contains all the locations of executable programs. If you overwrite it, random bits of your script will stop working. If you intend to change it, you need to do set PATH=%PATH%;C:\Users\DEB\Downloads\10.1.1.0.4 to keep the current PATH content, and add something to the end.

extracting days from a numpy.timedelta64 value

Use dt.days to obtain the days attribute as integers.

For eg:

In [14]: s = pd.Series(pd.timedelta_range(start='1 days', end='12 days', freq='3000T'))

In [15]: s
Out[15]: 
0    1 days 00:00:00
1    3 days 02:00:00
2    5 days 04:00:00
3    7 days 06:00:00
4    9 days 08:00:00
5   11 days 10:00:00
dtype: timedelta64[ns]

In [16]: s.dt.days
Out[16]: 
0     1
1     3
2     5
3     7
4     9
5    11
dtype: int64

More generally - You can use the .components property to access a reduced form of timedelta.

In [17]: s.dt.components
Out[17]: 
   days  hours  minutes  seconds  milliseconds  microseconds  nanoseconds
0     1      0        0        0             0             0            0
1     3      2        0        0             0             0            0
2     5      4        0        0             0             0            0
3     7      6        0        0             0             0            0
4     9      8        0        0             0             0            0
5    11     10        0        0             0             0            0

Now, to get the hours attribute:

In [23]: s.dt.components.hours
Out[23]: 
0     0
1     2
2     4
3     6
4     8
5    10
Name: hours, dtype: int64

addID in jQuery?

do you mean a method?

$('div.foo').attr('id', 'foo123');

Just be careful that you don't set multiple elements to the same ID.

How to do logging in React Native?

enter image description hereUse react native debugger for logging and redux store https://github.com/jhen0409/react-native-debugg

Just download it and run as software then enable Debug mode from the simulator.

It supports other debugging feature just like element in chrome developer tools, which helps to see the styling provided to any component.

Last complete support for redux dev tools

ISO C++ forbids comparison between pointer and integer [-fpermissive]| [c++]

char a[2] defines an array of char's. a is a pointer to the memory at the beginning of the array and using == won't actually compare the contents of a with 'ab' because they aren't actually the same types, 'ab' is integer type. Also 'ab' should be "ab" otherwise you'll have problems here too. To compare arrays of char you'd want to use strcmp.

Something that might be illustrative is looking at the typeid of 'ab':

#include <iostream>
#include <typeinfo>
using namespace std;
int main(){
    int some_int =5;
    std::cout << typeid('ab').name() << std::endl;
    std::cout << typeid(some_int).name() << std::endl;
    return 0;
}

on my system this returns:

i
i

showing that 'ab' is actually evaluated as an int.

If you were to do the same thing with a std::string then you would be dealing with a class and std::string has operator == overloaded and will do a comparison check when called this way.

If you wish to compare the input with the string "ab" in an idiomatic c++ way I suggest you do it like so:

#include <iostream>
#include <string>
using namespace std;
int main(){
    string a;
    cout<<"enter ab ";
    cin>>a;
    if(a=="ab"){
         cout<<"correct";
    }
    return 0;
}

This one is due to:

if(a=='ab') , here, a is const char* type (ie : array of char)

'ab' is a constant value,which isn't evaluated as string (because of single quote) but will be evaluated as integer.

Since char is a primitive type inherited from C, no operator == is defined.

the good code should be:

if(strcmp(a,"ab")==0) , then you'll compare a const char* to another const char* using strcmp.

How can I make text appear on next line instead of overflowing?

Just add

white-space: initial;

to the text, a line text will come automatically in the next line.

Using curl to upload POST data with files

As an alternative to curl, you can use HTTPie, it'a CLI, cURL-like tool for humans.

  1. Installation instructions: https://github.com/jakubroztocil/httpie#installation

  2. Then, run:

    http -f POST http://localhost:4040/api/users username=johnsnow photo@images/avatar.jpg
    
    HTTP/1.1 200 OK
    Access-Control-Expose-Headers: X-Frontend
    Cache-control: no-store
    Connection: keep-alive
    Content-Encoding: gzip
    Content-Length: 89
    Content-Type: text/html; charset=windows-1251
    Date: Tue, 26 Jun 2018 11:11:55 GMT
    Pragma: no-cache
    Server: Apache
    Vary: Accept-Encoding
    X-Frontend: front623311
    
    ...
    

Key Shortcut for Eclipse Imports

Yes. you can't remember all the shortcuts. You will forget many of them for sure. In this way, you can recall it and get the work done quickly.

Press Ctrl+3

And type whatever the hell you want :) It's a shortcut for shortcuts

enter image description here

How to get a value from a cell of a dataframe?

Not sure if this is a good practice, but I noticed I can also get just the value by casting the series as float.

e.g.

rate

3 0.042679

Name: Unemployment_rate, dtype: float64

float(rate)

0.0426789

How to click a link whose href has a certain substring in Selenium?

You can do this:

//first get all the <a> elements
List<WebElement> linkList=driver.findElements(By.tagName("a"));

//now traverse over the list and check
for(int i=0 ; i<linkList.size() ; i++)
{
    if(linkList.get(i).getAttribute("href").contains("long"))
    {
        linkList.get(i).click();
        break;
    }
}

in this what we r doing is first we are finding all the <a> tags and storing them in a list.After that we are iterating the list one by one to find <a> tag whose href attribute contains long string. And then we click on that particular <a> tag and comes out of the loop.

Get key from a HashMap using the value

  • If you need only that, simply use put(100, "one"). Note that the key is the first argument, and the value is the 2nd.
  • If you need to be able to get by both the key and the value, use BiMap (from guava)

Catching "Maximum request length exceeded"

You can solve this by increasing the maximum request length in your web.config:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <system.web>
        <httpRuntime maxRequestLength="102400" />
    </system.web>
</configuration>

The example above is for a 100Mb limit.

'node' is not recognized as an internal or external command

Node is missing from the SYSTEM PATH, try this in your command line

SET PATH=C:\Program Files\Nodejs;%PATH%

and then try running node

To set this system wide you need to set in the system settings - cf - http://banagale.com/changing-your-system-path-in-windows-vista.htm

To be very clean, create a new system variable NODEJS

NODEJS="C:\Program Files\Nodejs"

Then edit the PATH in system variables and add %NODEJS%

PATH=%NODEJS%;...

Select data from date range between two dates

Here is a query to find all product sales that were running during the month of August

  • Find Product_sales there were active during the month of August
  • Include anything that started before the end of August
  • Exclude anything that ended before August 1st

Also adds a case statement to validate the query

SELECT start_date, 
       end_date, 
       CASE 
         WHEN start_date <= '2015-08-31' THEN 'true' 
         ELSE 'false' 
       END AS started_before_end_of_month, 
       CASE 
         WHEN NOT end_date <= '2015-08-01' THEN 'true' 
         ELSE 'false' 
       END AS did_not_end_before_begining_of_month 
FROM   product_sales 
WHERE  start_date <= '2015-08-31' 
       AND end_date >= '2015-08-01' 
ORDER  BY start_date; 

How to get the xml node value in string

These posts helped me get past a couple of issues I had creating a CLR Stored Procedure with Restful API call against Infor M3 API.

The XML Result from these API's look like this for my code below:

miResult xmlns="http://lawson.com/m3/miaccess">
    <Program>MMS200MI</Program>
    <Transaction>Get</Transaction>
    <Metadata>...</Metadata>
    <MIRecord>
        <RowIndex>0</RowIndex>
        <NameValue>
            <Name>STAT</Name>
            <Value>20</Value>
        </NameValue>
        <NameValue>
            <Name>ITNO</Name>
            <Value>ITEM123</Value>
        </NameValue>
        <NameValue>
            <Name>ITDS</Name>
            <Value>ITEM DESCRIPTION 123 </Value>
        </NameValue>
...

The CLR C# Code to accomplish listing out the Resultset from the API works as shown below:

using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.IO;
using System.Net;
using System.Text;
using System.Xml;
using Microsoft.SqlServer.Server;

public partial class StoredProcedures
{
    [Microsoft.SqlServer.Server.SqlProcedure]
    public static void CallM3API_Test1()
    {
        SqlPipe pipe_msg = SqlContext.Pipe;
        try
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://M3Server.domain.com:12345/m3api-rest/execute/MMS200MI/Get?ITNO=ITEM123");

            request.Method = "Get";
            request.ContentLength = 0;

            request.Credentials = new NetworkCredential("[email protected]", "MyPassword");
            request.ContentType = "application/xml";
            request.Accept = "application/xml";

            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            {
                    using (Stream receiveStream = response.GetResponseStream())
                    {
                        using (StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8))
                        {
                            string strContent = readStream.ReadToEnd();
                            XmlDocument xdoc = new XmlDocument();
                            xdoc.LoadXml(strContent);
                            try
                            {
                                SqlPipe pipe = SqlContext.Pipe;

                                //Define Output Columns and Max Length of each Column in the Resultset    
                                SqlMetaData[] cols = new SqlMetaData[2];
                                cols[0] = new SqlMetaData("Name", SqlDbType.NVarChar, 50);
                                cols[1] = new SqlMetaData("Value", SqlDbType.NVarChar, 120);
                                SqlDataRecord record = new SqlDataRecord(cols);

                                pipe.SendResultsStart(record);

                                XmlNodeList nodeList = xdoc.GetElementsByTagName("NameValue");
                                //List ALL Output Names + Values
                                foreach (XmlNode nodeRes in nodeList)
                                {
                                    record.SetSqlString(0, nodeRes["Name"].InnerText);
                                    record.SetSqlString(1, nodeRes["Value"].InnerText);

                                    pipe.SendResultsRow(record);
                                }

                                pipe.SendResultsEnd();
                            }
                            catch (Exception ex)
                            {
                                SqlContext.Pipe.Send("Error (readStream): " + ex.Message);
                            }
                        }
                    }
            }
        }
        catch (Exception ex)
        {
            SqlContext.Pipe.Send("Error (CallM3API_Test1): " + ex.Message);

        }
    }
}

Hopefully this provides helpful.

Script @php artisan package:discover handling the post-autoload-dump event returned with error code 1

I came across this when upgrading from 5.8 to 6.x.

I had str_slug() in config/cache.php and config/session.php.

I have changed it to Str::slug() and the error has disappeared.

See https://laravel.com/docs/6.x/upgrade#helpers.

Disable nginx cache for JavaScript files

Remember set sendfile off; or cache headers doesn't work. I use this snipped:

location / {

        index index.php index.html index.htm;
        try_files $uri $uri/ =404; #.s. el /index.html para html5Mode de angular

        #.s. kill cache. use in dev
        sendfile off;
        add_header Last-Modified $date_gmt;
        add_header Cache-Control 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0';
        if_modified_since off;
        expires off;
        etag off;
        proxy_no_cache 1;
        proxy_cache_bypass 1; 
    }

How to view hierarchical package structure in Eclipse package explorer

Here is representation of screen eclipse to make hierarachical.

enter image description here

How do you embed binary data in XML?

I had this problem just last week. I had to serialize a PDF file and send it, inside an XML file, to a server.

If you're using .NET, you can convert a binary file directly to a base64 string and stick it inside an XML element.

string base64 = Convert.ToBase64String(File.ReadAllBytes(fileName));

Or, there is a method built right into the XmlWriter object. In my particular case, I had to include Microsoft's datatype namespace:

StringBuilder sb = new StringBuilder();
System.Xml.XmlWriter xw = XmlWriter.Create(sb);
xw.WriteStartElement("doc");
xw.WriteStartElement("serialized_binary");
xw.WriteAttributeString("types", "dt", "urn:schemas-microsoft-com:datatypes", "bin.base64");
byte[] b = File.ReadAllBytes(fileName);
xw.WriteBase64(b, 0, b.Length);
xw.WriteEndElement();
xw.WriteEndElement();
string abc = sb.ToString();

The string abc looks something that looks like this:

<?xml version="1.0" encoding="utf-16"?>
<doc>
    <serialized_binary types:dt="bin.base64" xmlns:types="urn:schemas-microsoft-com:datatypes">
        JVBERi0xLjMKJaqrrK0KNCAwIG9iago8PCAvVHlwZSAvSW5mbw...(plus lots more)
    </serialized_binary>
</doc>

How to convert String object to Boolean Object?

Use .isBool in your String value. It work for me

your_string.isBool

Copy to Clipboard for all Browsers using javascript

I spent a lot of time looking for a solution to this problem too. Here's what i've found thus far:

If you want your users to be able to click on a button and copy some text, you may have to use Flash.

If you want your users to press Ctrl+C anywhere on the page, but always copy xyz to the clipboard, I wrote an all-JS solution in YUI3 (although it could easily be ported to other frameworks, or raw JS if you're feeling particularly self-loathing).

It involves creating a textbox off the screen which gets highlighted as soon as the user hits Ctrl/CMD. When they hit 'C' shortly after, they copy the hidden text. If they hit 'V', they get redirected to a container (of your choice) before the paste event fires.

This method can work well, because while you listen for the Ctrl/CMD keydown anywhere in the body, the 'A', 'C' or 'V' keydown listeners only attach to the hidden text box (and not the whole body). It also doesn't have to break the users expectations - you only get redirected to the hidden box if you had nothing selected to copy anyway!

Here's what i've got working on my site, but check http://at.cg/js/clipboard.js for updates if there are any:

YUI.add('clipboard', function(Y) {


// Change this to the id of the text area you would like to always paste in to:

pasteBox = Y.one('#pasteDIV');


// Make a hidden textbox somewhere off the page.

Y.one('body').append('<input id="copyBox" type="text" name="result" style="position:fixed; top:-20%;" onkeyup="pasteBox.focus()">');
copyBox = Y.one('#copyBox');


// Key bindings for Ctrl+A, Ctrl+C, Ctrl+V, etc:

// Catch Ctrl/Window/Apple keydown anywhere on the page.
Y.on('key', function(e) {
    copyData();
        //  Uncomment below alert and remove keyCodes after 'down:' to figure out keyCodes for other buttons.
        //  alert(e.keyCode);
        //  }, 'body',  'down:', Y);
}, 'body',  'down:91,224,17', Y);

// Catch V - BUT ONLY WHEN PRESSED IN THE copyBox!!!
Y.on('key', function(e) {
    // Oh no! The user wants to paste, but their about to paste into the hidden #copyBox!!
    // Luckily, pastes happen on keyPress (which is why if you hold down the V you get lots of pastes), and we caught the V on keyDown (before keyPress).
    // Thus, if we're quick, we can redirect the user to the right box and they can unload their paste into the appropriate container. phew.
    pasteBox.select();
}, '#copyBox',  'down:86', Y);

// Catch A - BUT ONLY WHEN PRESSED IN THE copyBox!!!
Y.on('key', function(e) {
    // User wants to select all - but he/she is in the hidden #copyBox! That wont do.. select the pasteBox instead (which is probably where they wanted to be).
    pasteBox.select();
}, '#copyBox',  'down:65', Y);



// What to do when keybindings are fired:

// User has pressed Ctrl/Meta, and is probably about to press A,C or V. If they've got nothing selected, or have selected what you want them to copy, redirect to the hidden copyBox!
function copyData() {
    var txt = '';
    // props to Sabarinathan Arthanari for sharing with the world how to get the selected text on a page, cheers mate!
        if (window.getSelection) { txt = window.getSelection(); }
        else if (document.getSelection) { txt = document.getSelection(); }
        else if (document.selection) { txt = document.selection.createRange().text; }
        else alert('Something went wrong and I have no idea why - please contact me with your browser type (Firefox, Safari, etc) and what you tried to copy and I will fix this immediately!');

    // If the user has nothing selected after pressing Ctrl/Meta, they might want to copy what you want them to copy. 
        if(txt=='') {
                copyBox.select();
        }
    // They also might have manually selected what you wanted them to copy! How unnecessary! Maybe now is the time to tell them how silly they are..?!
        else if (txt == copyBox.get('value')) {
        alert('This site uses advanced copy/paste technology, possibly from the future.\n \nYou do not need to select things manually - just press Ctrl+C! \n \n(Ctrl+V will always paste to the main box too.)');
                copyBox.select();
        } else {
                // They also might have selected something completely different! If so, let them. It's only fair.
        }
}
});

Hope someone else finds this useful :]

Creating object with dynamic keys

In the new ES2015 standard for JavaScript (formerly called ES6), objects can be created with computed keys: Object Initializer spec.

The syntax is:

var obj = {
  [myKey]: value,
}

If applied to the OP's scenario, it would turn into:

stuff = function (thing, callback) {
  var inputs  = $('div.quantity > input').map(function(){
    return {
      [this.attr('name')]: this.attr('value'),
    };
  }) 

  callback(null, inputs);
}

Note: A transpiler is still required for browser compatiblity.

Using Babel or Google's traceur, it is possible to use this syntax today.


In earlier JavaScript specifications (ES5 and below), the key in an object literal is always interpreted literally, as a string.

To use a "dynamic" key, you have to use bracket notation:

var obj = {};
obj[myKey] = value;

In your case:

stuff = function (thing, callback) {
  var inputs  = $('div.quantity > input').map(function(){
    var key   = this.attr('name')
     ,  value = this.attr('value')
     ,  ret   = {};

     ret[key] = value;
     return ret;
  }) 

  callback(null, inputs);
}

Efficient way to rotate a list in python

What is the use case? Often, we don't actually need a fully shifted array --we just need to access a handful of elements in the shifted array.

Getting Python slices is runtime O(k) where k is the slice, so a sliced rotation is runtime N. The deque rotation command is also O(k). Can we do better?

Consider an array that is extremely large (let's say, so large it would be computationally slow to slice it). An alternative solution would be to leave the original array alone and simply calculate the index of the item that would have existed in our desired index after a shift of some kind.

Accessing a shifted element thus becomes O(1).

def get_shifted_element(original_list, shift_to_left, index_in_shifted):
    # back calculate the original index by reversing the left shift
    idx_original = (index_in_shifted + shift_to_left) % len(original_list)
    return original_list[idx_original]

my_list = [1, 2, 3, 4, 5]

print get_shifted_element(my_list, 1, 2) ----> outputs 4

print get_shifted_element(my_list, -2, 3) -----> outputs 2 

Tracking changes in Windows registry

When using a VM, I use these steps to inspect changes to the registry:

  1. Using 7-Zip, open the vdi/vhd/vmdk file and extract the folder C:\Windows\System32\config
  2. Run OfflineRegistryView to convert the registry to plaintext
    • Set the 'Config Folder' to the folder you extracted
    • Set the 'Base Key' to HKLM\SYSTEM or HKLM\SOFTWARE
    • Set the 'Subkey Depth' to 'Unlimited'
    • Press the 'Go' button

Now use your favourite diff program to compare the 'before' and 'after' snapshots.

Html.RenderPartial() syntax with Razor

Html.RenderPartial() is a void method - you can check whether a method is a void method by placing your mouse over the call to RenderPartial in your code and you will see the text (extension) void HtmlHelper.RenderPartial...

Void methods require a semicolon at the end of the calling code.

In the Webforms view engine you would have encased your Html.RenderPartial() call within the bee stings <% %>

like so

<% Html.RenderPartial("Path/to/my/partial/view"); %>

when you are using the Razor view engine the equivalent is

@{Html.RenderPartial("Path/to/my/partial/view");}

What is an instance variable in Java?

An instance variable is a variable that is a member of an instance of a class (i.e., associated with something created with a new), whereas a class variable is a member of the class itself.

Every instance of a class will have its own copy of an instance variable, whereas there is only one of each static (or class) variable, associated with the class itself.

What’s the difference between a class variable and an instance variable?

This test class illustrates the difference:

public class Test {
   
    public static String classVariable = "I am associated with the class";
    public String instanceVariable = "I am associated with the instance";
    
    public void setText(String string){
        this.instanceVariable = string;
    }
    
    public static void setClassText(String string){
        classVariable = string;
    }
    
    public static void main(String[] args) {
        Test test1 = new Test();
        Test test2 = new Test();
        
        // Change test1's instance variable
        test1.setText("Changed");
        System.out.println(test1.instanceVariable); // Prints "Changed"
        // test2 is unaffected
        System.out.println(test2.instanceVariable); // Prints "I am associated with the instance"
        
        // Change class variable (associated with the class itself)
        Test.setClassText("Changed class text");
        System.out.println(Test.classVariable); // Prints "Changed class text"
        
        // Can access static fields through an instance, but there still is only one
        // (not best practice to access static variables through instance)
        System.out.println(test1.classVariable); // Prints "Changed class text"
        System.out.println(test2.classVariable); // Prints "Changed class text"
    }
}

React navigation goBack() and update parent state

I would also use navigation.navigate. If someone has the same problem and also uses nested navigators, this is how it would work:

onPress={() =>
        navigation.navigate('MyStackScreen', {
          // Passing params to NESTED navigator screen:
          screen: 'goToScreenA',
          params: { Data: data.item },
        })
      }

How do I automatically resize an image for a mobile site?

Your css with doesn't have any effect as the outer element doesn't have a width defined (and body is missing as well).

A different approach is to deliver already scaled images. http://www.sencha.com/products/io/ for example delivers the image already scaled down depending on the viewing device.

VBA Macro to compare all cells of two Excel files

Do NOT loop through all cells!! There is a lot of overhead in communications between worksheets and VBA, for both reading and writing. Looping through all cells will be agonizingly slow. I'm talking hours.

Instead, load an entire sheet at once into a Variant array. In Excel 2003, this takes about 2 seconds (and 250 MB of RAM). Then you can loop through it in no time at all.

In Excel 2007 and later, sheets are about 1000 times larger (1048576 rows × 16384 columns = 17 billion cells, compared to 65536 rows × 256 columns = 17 million in Excel 2003). You will run into an "Out of memory" error if you try to load the whole sheet into a Variant; on my machine I can only load 32 million cells at once. So you have to limit yourself to the range you know has actual data in it, or load the sheet bit by bit, e.g. 30 columns at a time.

Option Explicit

Sub test()

    Dim varSheetA As Variant
    Dim varSheetB As Variant
    Dim strRangeToCheck As String
    Dim iRow As Long
    Dim iCol As Long

    strRangeToCheck = "A1:IV65536"
    ' If you know the data will only be in a smaller range, reduce the size of the ranges above.
    Debug.Print Now
    varSheetA = Worksheets("Sheet1").Range(strRangeToCheck)
    varSheetB = Worksheets("Sheet2").Range(strRangeToCheck) ' or whatever your other sheet is.
    Debug.Print Now

    For iRow = LBound(varSheetA, 1) To UBound(varSheetA, 1)
        For iCol = LBound(varSheetA, 2) To UBound(varSheetA, 2)
            If varSheetA(iRow, iCol) = varSheetB(iRow, iCol) Then
                ' Cells are identical.
                ' Do nothing.
            Else
                ' Cells are different.
                ' Code goes here for whatever it is you want to do.
            End If
        Next iCol
    Next iRow

End Sub

To compare to a sheet in a different workbook, open that workbook and get the sheet as follows:

Set wbkA = Workbooks.Open(filename:="C:\MyBook.xls")
Set varSheetA = wbkA.Worksheets("Sheet1") ' or whatever sheet you need

How to search through all Git and Mercurial commits in the repository for a certain string?

In addition to richq answer of using git log -g --grep=<regexp> or git grep -e <regexp> $(git log -g --pretty=format:%h): take a look at the following blog posts by Junio C Hamano, current git maintainer


Summary

Both git grep and git log --grep are line oriented, in that they look for lines that match specified pattern.

You can use git log --grep=<foo> --grep=<bar> (or git log --author=<foo> --grep=<bar> that internally translates to two --grep) to find commits that match either of patterns (implicit OR semantic).

Because of being line-oriented, the useful AND semantic is to use git log --all-match --grep=<foo> --grep=<bar> to find commit that has both line matching first and line matching second somewhere.

With git grep you can combine multiple patterns (all which must use the -e <regexp> form) with --or (which is the default), --and, --not, ( and ). For grep --all-match means that file must have lines that match each of alternatives.

How to schedule a task to run when shutting down windows

Execute gpedit.msc (local Policies)

Computer Configuration -> Windows settings -> Scripts -> Shutdown -> Properties -> Add

PDF files do not open in Internet Explorer with Adobe Reader 10.0 - users get an empty gray screen. How can I fix this for my users?

I realize this is a rather late post but still a possible solution for the OP. I use IE9 on Win 7 and have been having Adobe Reader's grey screen issues for several months when trying to open pdf bank and credit card statements online. I could open everything in Firefox or Opera but not IE. I finally tried PDF-Viewer, set it as the default pdf viewer in its preferences and no more problems. I'm sure there are other free viewers out there, like Foxit, PDF-Xchange, etc., that will give better results than Reader with less headaches. Adobe is like some of the other big companies that develop software on a take it or leave it basis ... so I left it.

What is the difference between a web API and a web service?

The basic difference between Web Services and Web APIs

Web Service:

1) It is a SOAP-based service and returns data as XML.

2) It only supports the HTTP protocol.

3) It is not open source but can be used by any client that understands XML.

5) It requires a SOAP protocol to receive and send data over the network, so it is not a light-weight architecture.

Web API:

1) A Web API is an HTTP based service and returns JSON or XML data by default.

2) It supports the HTTP protocol.

3) It can be hosted within an application or IIS.

4) It is open source and it can be used by any client that understands JSON or XML.

5) It has light-weight architecture and good for devices which have limited bandwidth, like mobile devices.

How do I toggle an ng-show in AngularJS based on a boolean?

It's worth noting that if you have a button in Controller A and the element you want to show in Controller B, you may need to use dot notation to access the scope variable across controllers.

For example, this will not work:

<div ng-controller="ControllerA">
  <a ng-click="isReplyFormOpen = !isReplyFormOpen">Reply</a>

  <div ng-controller="ControllerB">
    <div ng-show="isReplyFormOpen" id="replyForm">
    </div>
  </div>

</div>

To solve this, create a global variable (ie. in Controller A or your main Controller):

.controller('ControllerA', function ($scope) {
  $scope.global = {};
}

Then add a 'global' prefix to your click and show variables:

<div ng-controller="ControllerA">
  <a ng-click="global.isReplyFormOpen = !global.isReplyFormOpen">Reply</a>

  <div ng-controller="ControllerB">
    <div ng-show="global.isReplyFormOpen" id="replyForm">
    </div>
  </div>

</div>

For more detail, check out the Nested States & Nested Views in the Angular-UI documentation, watch a video, or read understanding scopes.

How do I get video durations with YouTube API version 3?

I got it!

$dur = file_get_contents("https://www.googleapis.com/youtube/v3/videos?part=contentDetails&id=$vId&key=dldfsd981asGhkxHxFf6JqyNrTqIeJ9sjMKFcX4");

$duration = json_decode($dur, true);
foreach ($duration['items'] as $vidTime) {
    $vTime= $vidTime['contentDetails']['duration'];
}

There it returns the time for YouTube API version 3 (the key is made up by the way ;). I used $vId that I had gotten off of the returned list of the videos from the channel I am showing the videos from...

It works. Google REALLY needs to include the duration in the snippet so you can get it all with one call instead of two... it's on their 'wontfix' list.

Manually put files to Android emulator SD card

Use the adb tool that comes with the SDK.

adb push myDirectory /sdcard/targetDir

If you only specify /sdcard/ (with the trailing slash) as destination, then the CONTENTS of myDirectory will end up in the root of /sdcard.

(Built-in) way in JavaScript to check if a string is a valid number

And you could go the RegExp-way:

var num = "987238";

if(num.match(/^-?\d+$/)){
  //valid integer (positive or negative)
}else if(num.match(/^\d+\.\d+$/)){
  //valid float
}else{
  //not valid number
}

When to use SELECT ... FOR UPDATE?

Short answers:

Q1: Yes.

Q2: Doesn't matter which you use.

Long answer:

A select ... for update will (as it implies) select certain rows but also lock them as if they have already been updated by the current transaction (or as if the identity update had been performed). This allows you to update them again in the current transaction and then commit, without another transaction being able to modify these rows in any way.

Another way of looking at it, it is as if the following two statements are executed atomically:

select * from my_table where my_condition;

update my_table set my_column = my_column where my_condition;

Since the rows affected by my_condition are locked, no other transaction can modify them in any way, and hence, transaction isolation level makes no difference here.

Note also that transaction isolation level is independent of locking: setting a different isolation level doesn't allow you to get around locking and update rows in a different transaction that are locked by your transaction.

What transaction isolation levels do guarantee (at different levels) is the consistency of data while transactions are in progress.