Programs & Examples On #Iso 8859 1

iso-8859-1 is part of the ISO/IEC 8859 series of ASCII-based standard character encodings, first edition published in 1987.

Setting the character encoding in form submit for Internet Explorer

It seems that this can't be done, not at least with current versions of IE (6 and 7).

IE supports form attribute accept-charset, but only if its value is 'utf-8'.

The solution is to modify server A to produce encoding 'ISO-8859-1' for page that contains the form.

How do I write out a text file in C# with a code page other than UTF-8?

Simple!

System.IO.File.WriteAllText(path, text, Encoding.GetEncoding(28591));

Converting UTF-8 to ISO-8859-1 in Java - how to keep it as single byte

byte[] iso88591Data = theString.getBytes("ISO-8859-1");

Will do the trick. From your description it seems as if you're trying to "store an ISO-8859-1 String". String objects in Java are always implicitly encoded in UTF-16. There's no way to change that encoding.

What you can do, 'though is to get the bytes that constitute some other encoding of it (using the .getBytes() method as shown above).

C# Convert string from UTF-8 to ISO-8859-1 (Latin1) H

Use Encoding.Convert to adjust the byte array before attempting to decode it into your destination encoding.

Encoding iso = Encoding.GetEncoding("ISO-8859-1");
Encoding utf8 = Encoding.UTF8;
byte[] utfBytes = utf8.GetBytes(Message);
byte[] isoBytes = Encoding.Convert(utf8, iso, utfBytes);
string msg = iso.GetString(isoBytes);

What is the difference between UTF-8 and ISO-8859-1?

ISO-8859-1 is a legacy standards from back in 1980s. It can only represent 256 characters so only suitable for some languages in western world. Even for many supported languages, some characters are missing. If you create a text file in this encoding and try copy/paste some Chinese characters, you will see weird results. So in other words, don't use it. Unicode has taken over the world and UTF-8 is pretty much the standards these days unless you have some legacy reasons (like HTTP headers which needs to compatible with everything).

HTML encoding issues - "Â" character showing up instead of " "

In my case this (a with caret) occurred in code I generated from visual studio using my own tool for generating code. It was easy to solve:

Select single spaces ( ) in the document. You should be able to see lots of single spaces that are looking different from the other single spaces, they are not selected. Select these other single spaces - they are the ones responsible for the unwanted characters in the browser. Go to Find and Replace with single space ( ). Done.

PS: It's easier to see all similar characters when you place the cursor on one or if you select it in VS2017+; I hope other IDEs may have similar features

How do I convert between ISO-8859-1 and UTF-8 in Java?

The easiest way to convert an ISO-8859-1 string to UTF-8 string.

private static String convertIsoToUTF8(String example) throws UnsupportedEncodingException {
    return new String(example.getBytes("ISO-8859-1"), "utf-8");
}

If we want to convert an UTF-8 string to ISO-8859-1 string.

private static String convertUTF8ToISO(String example) throws UnsupportedEncodingException {
    return new String(example.getBytes("utf-8"), "ISO-8859-1");
}

Moreover, a method that converts an ISO-8859-1 string to UTF-8 string without using the constructor of class String.

public static String convertISO_to_UTF8_personal(String strISO_8859_1) {
    String res = "";
    int i = 0;
    for (i = 0; i < strISO_8859_1.length() - 1; i++) {
        char ch = strISO_8859_1.charAt(i);
        char chNext = strISO_8859_1.charAt(i + 1);
        if (ch <= 127) {
            res += ch;
        } else if (ch == 194 && chNext >= 128 && chNext <= 191) {
            res += chNext;
        } else if(ch == 195 && chNext >= 128 && chNext <= 191){
            int resNum = chNext + 64;
            res += (char) resNum;
        } else if(ch == 194){
            res += (char) 173;
        } else if(ch == 195){
            res += (char) 224;
        }
    }
    char ch = strISO_8859_1.charAt(i);
    if (ch <= 127 ){
        res += ch;
    }
    return res;
}

}

That method is based on enconding utf-8 to iso-8859-1 of this website. Encoding utf-8 to iso-8859-1

Convert utf8-characters to iso-88591 and back in PHP

It is much better to use

$value = mb_convert_encode($value,'HTML-ENTITIES','UTF-8');

Specially when you are using AJAX call for submitting 'ISO-8859-1' characters. It works for Chinese, Japanese, Czech, German and many more languages.

How to hide a column (GridView) but still access its value?

You can use DataKeys for retrieving the value of such fields, because (as you said) when you set a normal BoundField as visible false you cannot get their value.

In the .aspx file set the GridView property

DataKeyNames = "Outlook_ID"

Now, in an event handler you can access the value of this key like so:

grid.DataKeys[rowIndex]["Outlook_ID"]

This will give you the id at the specified rowindex of the grid.

disable textbox using jquery?

I know it is not a good habit to answer an old question but I'm putting this answer for people who would see the question afterwards.

The best way to change the state in JQuery now is through

$("#input").prop('disabled', true); 
$("#input").prop('disabled', false);

Please check this link for full illustration. Disable/enable an input with jQuery?

#1025 - Error on rename of './database/#sql-2e0f_1254ba7' to './database/table' (errno: 150)

To bypass this in PHPMyAdmin or with MySQL, first remove the foreign key constraint before renaming the attribute.

(For PHPMyAdmin users: To remove FK constrains in PHPMyAdmin, select the attribute then click "relation view" next to "print view" in the toolbar below the table structure)

delete vs delete[] operators in C++

The delete operator deallocates memory and calls the destructor for a single object created with new.

The delete [] operator deallocates memory and calls destructors for an array of objects created with new [].

Using delete on a pointer returned by new [] or delete [] on a pointer returned by new results in undefined behavior.

Running script upon login mac

tl;dr: use OSX's native process launcher and manager, launchd.

To do so, make a launchctl daemon. You'll have full control over all aspects of the script. You can run once or keep alive as a daemon. In most cases, this is the way to go.

  1. Create a .plist file according to the instructions in the Apple Dev docs here or more detail below.
  2. Place in ~/Library/LaunchAgents
  3. Log in (or run manually via launchctl load [filename.plist])

For more on launchd, the wikipedia article is quite good and describes the system and its advantages over other older systems.


Here's the specific plist file to run a script at login.

Updated 2017/09/25 for OSX El Capitan and newer (credit to José Messias Jr):

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
   <key>Label</key>
   <string>com.user.loginscript</string>
   <key>ProgramArguments</key>
   <array><string>/path/to/executable/script.sh</string></array>
   <key>RunAtLoad</key>
   <true/>
</dict>
</plist>

Replace the <string> after the Program key with your desired command (note that any script referenced by that command must be executable: chmod a+x /path/to/executable/script.sh to ensure it is for all users).

Save as ~/Library/LaunchAgents/com.user.loginscript.plist

Run launchctl load ~/Library/LaunchAgents/com.user.loginscript.plist and log out/in to test (or to test directly, run launchctl start com.user.loginscript)

Tail /var/log/system.log for error messages.

The key is that this is a User-specific launchd entry, so it will be run on login for the given user. System-specific launch daemons (placed in /Library/LaunchDaemons) are run on boot.

If you want a script to run on login for all users, I believe LoginHook is your only option, and that's probably the reason it exists.

How do I find out what version of WordPress is running?

From Dashboard At a Glance box

or at the bottom right corner of any admin page.

enter image description here

If that Glance box is hidden - click on screen options at top-right corner and check At a Glance option.

Get only specific attributes with from Laravel Collection

this is a follow up on the patricus [answer][1] above but for nested arrays:

$topLevelFields =  ['id','status'];
$userFields = ['first_name','last_name','email','phone_number','op_city_id'];

return $onlineShoppers->map(function ($user) { 
    return collect($user)->only($topLevelFields)
                             ->merge(collect($user['user'])->only($userFields))->all();  
    })->all();

ERROR 1064 (42000) in MySQL

Finally got a solution.

First .sql file converts into the UTF8.

Then use this command

mysql -p -u root --default_character_set utf8 test </var/201535.sql

---root is the username

---test is the database name

or

mysql -p -u root test < /var/201535.sql 

---root is the username

---test is the database name

How do I return to an older version of our code in Subversion?

Just use this line

svn update -r yourOldRevesion

You can know your current revision by using:

svn info

How to escape % in String.Format?

To escape %, you will need to double it up: %%.

Scroll to the top of the page using JavaScript?

You can use javascript's built in function scrollTo:

_x000D_
_x000D_
function scroll() {
  window.scrollTo({
    top: 0,
    behavior: 'smooth'
  });
}
_x000D_
<button onclick="scroll">Scroll</button>
_x000D_
_x000D_
_x000D_

How to check if any fields in a form are empty in php

Specify POST method in form
<form name="registrationform" action="register.php" method="post">


your form code

</form>

how to download file in react js

If you are using React Router, use this:

<Link to="/files/myfile.pdf" target="_blank" download>Download</Link>

Where /files/myfile.pdf is inside your public folder.

Redirecting to previous page after login? PHP

Since the login page is a separate page, I am assuming that you want to redirect to the page that the user reached the login page from.

$_SERVER['REQUEST_URI'] will simply hold the current page. What you want to do is use $_SERVER['HTTP_REFERER']

So save the HTTP_REFERER in a hidden element on your form <input type="hidden" name="referer" value="<?= $_SERVER['HTTP_REFERER'] ?>" /> but keep in mind that in the PHP that processes the form you will need some logic that redirects back to the login page if login fails but also to check that the referer is actually your website, if it isn't, then redirect back to the homepage.

A non well formed numeric value encountered

$_GET['start_date'] is not numeric is my bet, but an date format not supported by strtotime. You will need to re-format the date to a workable format for strtotime or use combination of explode/mktime.

I could add you an example if you'd be kind enough to post the format you currently receive.

What are the differences between virtual memory and physical memory?

Virtual memory is, among other things, an abstraction to give the programmer the illusion of having infinite memory available on their system.

Virtual memory mappings are made to correspond to actual physical addresses. The operating system creates and deals with these mappings - utilizing the page table, among other data structures to maintain the mappings. Virtual memory mappings are always found in the page table or some similar data structure (in case of other implementations of virtual memory, we maybe shouldn't call it the "page table"). The page table is in physical memory as well - often in kernel-reserved spaces that user programs cannot write over.

Virtual memory is typically larger than physical memory - there wouldn't be much reason for virtual memory mappings if virtual memory and physical memory were the same size.

Only the needed part of a program is resident in memory, typically - this is a topic called "paging". Virtual memory and paging are tightly related, but not the same topic. There are other implementations of virtual memory, such as segmentation.

I could be assuming wrong here, but I'd bet the things you are finding hard to wrap your head around have to do with specific implementations of virtual memory, most likely paging. There is no one way to do paging - there are many implementations and the one your textbook describes is likely not the same as the one that appears in real OSes like Linux/Windows - there are probably subtle differences.

I could blab a thousand paragraphs about paging... but I think that is better left to a different question targeting specifically that topic.

Uncaught TypeError: Cannot read property 'msie' of undefined

$.browser was removed from jQuery starting with version 1.9. It is now available as a plugin. It's generally recommended to avoid browser detection, which is why it was removed.

XML Error: Extra content at the end of the document

I've found that this error is also generated if the document is empty. In this case it's also because there is no root element - but the error message "Extra content and the end of the document" is misleading in this situation.

Variable might not have been initialized error

because of your a and b variable is not have been initialized. You must initialized this variables for excample if you declare this variable like this int a=0; int b=0; than your code run without error.

Make file echo displaying "$PATH" string

The make uses the $ for its own variable expansions. E.g. single character variable $A or variable with a long name - ${VAR} and $(VAR).

To put the $ into a command, use the $$, for example:

all:
  @echo "Please execute next commands:"
  @echo 'setenv PATH /usr/local/greenhills/mips5/linux86:$$PATH'

Also note that to make the "" and '' (double and single quoting) do not play any role and they are passed verbatim to the shell. (Remove the @ sign to see what make sends to shell.) To prevent the shell from expanding $PATH, second line uses the ''.

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

You cant simply (directly) convert the datareader to list.

You have to loop through all the elements in datareader and insert into list

below the sample code

using (drOutput)   
{
            System.Collections.Generic.List<CustomerEntity > arrObjects = new System.Collections.Generic.List<CustomerEntity >();        
            int customerId = drOutput.GetOrdinal("customerId ");
            int CustomerName = drOutput.GetOrdinal("CustomerName ");

        while (drOutput.Read())        
        {
            CustomerEntity obj=new CustomerEntity ();
            obj.customerId = (drOutput[customerId ] != Convert.DBNull) ? drOutput[customerId ].ToString() : null;
            obj.CustomerName = (drOutput[CustomerName ] != Convert.DBNull) ? drOutput[CustomerName ].ToString() : null;
            arrObjects .Add(obj);
        }

}

Stop executing further code in Java

You can just use return to end the method's execution

Matplotlib make tick labels font size smaller

To specify both font size and rotation at the same time, try this:

plt.xticks(fontsize=14, rotation=90)

creating triggers for After Insert, After Update and After Delete in SQL

(Update: overlooked a fault in the matter, I have corrected)

(Update2: I wrote from memory the code screwed up, repaired it)

(Update3: check on SQLFiddle)

create table Derived_Values
  (
    BusinessUnit nvarchar(100) not null
    ,Questions nvarchar(100) not null
    ,Answer nvarchar(100)
    )

go

ALTER TABLE Derived_Values ADD CONSTRAINT PK_Derived_Values
PRIMARY KEY CLUSTERED (BusinessUnit, Questions);

create table Derived_Values_Test
  (
    BusinessUnit nvarchar(150)
    ,Questions nvarchar(100)
    ,Answer nvarchar(100)
    )

go

CREATE TRIGGER trgAfterUpdate ON  [Derived_Values]
FOR UPDATE
AS  
begin
    declare @BusinessUnit nvarchar(50)
    set @BusinessUnit = 'Updated Record -- After Update Trigger.'

    insert into 
        [Derived_Values_Test]
        --(BusinessUnit,Questions, Answer) 
    SELECT 
        @BusinessUnit + i.BusinessUnit, i.Questions, i.Answer
    FROM 
        inserted i
        inner join deleted d on i.BusinessUnit = d.BusinessUnit
end

go

CREATE TRIGGER trgAfterDelete ON  [Derived_Values]
FOR UPDATE
AS  
begin
    declare @BusinessUnit nvarchar(50)
    set @BusinessUnit = 'Deleted Record -- After Delete Trigger.'

    insert into 
        [Derived_Values_Test]
        --(BusinessUnit,Questions, Answer) 
    SELECT 
        @BusinessUnit + d.BusinessUnit, d.Questions, d.Answer
    FROM 
        deleted d
end

go

insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU1', 'Q11', 'A11')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU1', 'Q12', 'A12')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU2', 'Q21', 'A21')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU2', 'Q22', 'A22')

UPDATE Derived_Values SET Answer='Updated Answers A11' from Derived_Values WHERE (BusinessUnit = 'BU1') AND (Questions = 'Q11');
UPDATE Derived_Values SET Answer='Updated Answers A12' from Derived_Values WHERE (BusinessUnit = 'BU1') AND (Questions = 'Q12');
UPDATE Derived_Values SET Answer='Updated Answers A21' from Derived_Values WHERE (BusinessUnit = 'BU2') AND (Questions = 'Q21');
UPDATE Derived_Values SET Answer='Updated Answers A22' from Derived_Values WHERE (BusinessUnit = 'BU2') AND (Questions = 'Q22');

delete Derived_Values;

and then:

SELECT * FROM Derived_Values;
go

select * from Derived_Values_Test;


Record Count: 0;

BUSINESSUNIT    QUESTIONS   ANSWER
Updated Record -- After Update Trigger.BU1  Q11 Updated Answers A11
Deleted Record -- After Delete Trigger.BU1  Q11 A11
Updated Record -- After Update Trigger.BU1  Q12 Updated Answers A12
Deleted Record -- After Delete Trigger.BU1  Q12 A12
Updated Record -- After Update Trigger.BU2  Q21 Updated Answers A21
Deleted Record -- After Delete Trigger.BU2  Q21 A21
Updated Record -- After Update Trigger.BU2  Q22 Updated Answers A22
Deleted Record -- After Delete Trigger.BU2  Q22 A22

(Update4: If you want to sync: SQLFiddle)

create table Derived_Values
  (
    BusinessUnit nvarchar(100) not null
    ,Questions nvarchar(100) not null
    ,Answer nvarchar(100)
    )

go

ALTER TABLE Derived_Values ADD CONSTRAINT PK_Derived_Values
PRIMARY KEY CLUSTERED (BusinessUnit, Questions);

create table Derived_Values_Test
  (
    BusinessUnit nvarchar(150) not null
    ,Questions nvarchar(100) not null
    ,Answer nvarchar(100)
    )

go

ALTER TABLE Derived_Values_Test ADD CONSTRAINT PK_Derived_Values_Test
PRIMARY KEY CLUSTERED (BusinessUnit, Questions);

CREATE TRIGGER trgAfterInsert ON  [Derived_Values]
FOR INSERT
AS  
begin
    insert
        [Derived_Values_Test]
        (BusinessUnit,Questions,Answer)
    SELECT 
        i.BusinessUnit, i.Questions, i.Answer
    FROM 
        inserted i
end

go


CREATE TRIGGER trgAfterUpdate ON  [Derived_Values]
FOR UPDATE
AS  
begin
    declare @BusinessUnit nvarchar(50)
    set @BusinessUnit = 'Updated Record -- After Update Trigger.'

    update
        [Derived_Values_Test]
    set
        --BusinessUnit = i.BusinessUnit
        --,Questions = i.Questions
        Answer = i.Answer
    from
        [Derived_Values]
        inner join inserted i 
    on
        [Derived_Values].BusinessUnit = i.BusinessUnit
        and
        [Derived_Values].Questions = i.Questions
end

go

CREATE TRIGGER trgAfterDelete ON  [Derived_Values]
FOR DELETE
AS  
begin
    delete 
        [Derived_Values_Test]
    from
        [Derived_Values_Test]
        inner join deleted d 
    on
        [Derived_Values_Test].BusinessUnit = d.BusinessUnit
        and
        [Derived_Values_Test].Questions = d.Questions
end

go

insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU1', 'Q11', 'A11')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU1', 'Q12', 'A12')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU2', 'Q21', 'A21')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU2', 'Q22', 'A22')

UPDATE Derived_Values SET Answer='Updated Answers A11' from Derived_Values WHERE (BusinessUnit = 'BU1') AND (Questions = 'Q11');
UPDATE Derived_Values SET Answer='Updated Answers A12' from Derived_Values WHERE (BusinessUnit = 'BU1') AND (Questions = 'Q12');
UPDATE Derived_Values SET Answer='Updated Answers A21' from Derived_Values WHERE (BusinessUnit = 'BU2') AND (Questions = 'Q21');
UPDATE Derived_Values SET Answer='Updated Answers A22' from Derived_Values WHERE (BusinessUnit = 'BU2') AND (Questions = 'Q22');

--delete Derived_Values;

And then:

SELECT * FROM Derived_Values;
go

select * from Derived_Values_Test;


BUSINESSUNIT    QUESTIONS   ANSWER
BU1 Q11 Updated Answers A11
BU1 Q12 Updated Answers A12
BU2 Q21 Updated Answers A21
BU2 Q22 Updated Answers A22

BUSINESSUNIT    QUESTIONS   ANSWER
BU1 Q11 Updated Answers A11
BU1 Q12 Updated Answers A12
BU2 Q21 Updated Answers A21
BU2 Q22 Updated Answers A22

How to check if curl is enabled or disabled

var_dump(extension_loaded('curl'));

npm ERR! registry error parsing json - While trying to install Cordova for Ionic Framework in Windows 8

My npm install worked fine, but I had this problem with npm update. To fix it, I had to run npm cache clean and then npm cache clear.

PNG transparency issue in IE8

I had the same thing happen to a PNG with transparency that was set as the background-image of an <A> element with opacity applied.

The fix was to set the background-color of the <A> element.

So, the following:

filter: alpha(opacity=40);
-moz-opacity: 0.4;
-khtml-opacity: 0.4;
opacity: 0.4;
background-image: ...;

Turns into:

/* "Overwritten" by the background-image. However this fixes the IE7 and IE8 PNG-transparency-plus-opacity bug. */
background-color: #FFFFFF; 

filter: alpha(opacity=40);
-moz-opacity: 0.4;
-khtml-opacity: 0.4;
opacity: 0.4;
background-image: ...;

How to handle static content in Spring MVC?

If I understand your issue correctly, I think I have found a solution to your problem:

I had the same issue where raw output was shown with no css styles, javascripts or jquery files found.

I just added mappings to the "default" servlet. The following was added to the web.xml file:

 <servlet-mapping>
  <servlet-name>default</servlet-name>
  <url-pattern>*.css</url-pattern>
 </servlet-mapping>

 <servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>*.js</url-pattern>
 </servlet-mapping>

This should filter out the javascript and css file requests from the DispatcherRequest object.

Again, not sure if this is what you are after, but it worked for me. I think "default" is the name of the default servlet within JBoss. Not too sure what it is for other servers.

Java, How to specify absolute value and square roots

Use the static methods in the Math class for both - there are no operators for this in the language:

double root = Math.sqrt(value);
double absolute = Math.abs(value);

(Likewise there's no operator for raising a value to a particular power - use Math.pow for that.)

If you use these a lot, you might want to use static imports to make your code more readable:

import static java.lang.Math.sqrt;
import static java.lang.Math.abs;

...

double x = sqrt(abs(x) + abs(y));

instead of

double x = Math.sqrt(Math.abs(x) + Math.abs(y));

How to create the pom.xml for a Java project with Eclipse

To create POM.XML file in Eclipse:

  1. Install M2E plugin (http://www.eclipse.org/m2e/)

  2. Right click on project -> Configure -> Convert to Maven Project

How to detect idle time in JavaScript elegantly?

<script type="text/javascript">
var idleTime = 0;
$(document).ready(function () {
    //Increment the idle time counter every minute.
    idleInterval = setInterval(timerIncrement, 60000); // 1 minute

    //Zero the idle timer on mouse movement.
    $('body').mousemove(function (e) {
     //alert("mouse moved" + idleTime);
     idleTime = 0;
    });

    $('body').keypress(function (e) {
      //alert("keypressed"  + idleTime);
        idleTime = 0;
    });



    $('body').click(function() {
      //alert("mouse moved" + idleTime);
       idleTime = 0;
    });

});

function timerIncrement() {
    idleTime = idleTime + 1;
    if (idleTime > 10) { // 10 minutes

        window.location.assign("http://www.google.com");
    }
}
</script> 

I think this jquery code is perfect one , though copied and modified from above answers!! donot forgot to include jquery library in your file!

Fastest method to escape HTML tags as HTML entities?

You could try passing a callback function to perform the replacement:

var tagsToReplace = {
    '&': '&amp;',
    '<': '&lt;',
    '>': '&gt;'
};

function replaceTag(tag) {
    return tagsToReplace[tag] || tag;
}

function safe_tags_replace(str) {
    return str.replace(/[&<>]/g, replaceTag);
}

Here is a performance test: http://jsperf.com/encode-html-entities to compare with calling the replace function repeatedly, and using the DOM method proposed by Dmitrij.

Your way seems to be faster...

Why do you need it, though?

Set the selected index of a Dropdown using jQuery

This will work:

<head>
    <script type="text/javascript">
        function Init () {
            var counter = document.getElementById ("counter");
            for (var i = 1; i < 1000; i++) {
                var option = new Option (i, i);
                counter.options.add (option);
            }
            counter.focus ();
        }
        
        function OnKeyPressCounter (event, counter) {
            var chCode = ('charCode' in event) ? event.charCode : event.keyCode;
        
            if (chCode == 68 /* + */) {
                if (counter.selectedIndex < counter.options.length - 1) {
                    counter.selectedIndex++;
                }
            }
            if (chCode == 45 /* - */) {
                if (counter.selectedIndex > 0) {
                    counter.selectedIndex--;
                }
            }
        }
    </script>
</head>
<body onload="Init ()">
    Use the + and - keys to increase/decrease the counter.
    <select id="counter" onkeypress="OnKeyPressCounter(event, this)" style="width:80px"></select>
</body>

Ignore .pyc files in git repository

You should add a line with:

*.pyc 

to the .gitignore file in the root folder of your git repository tree right after repository initialization.

As ralphtheninja said, if you forgot to to do it beforehand, if you just add the line to the .gitignore file, all previously committed .pyc files will still be tracked, so you'll need to remove them from the repository.

If you are on a Linux system (or "parents&sons" like a MacOSX), you can quickly do it with just this one line command that you need to execute from the root of the repository:

find . -name "*.pyc" -exec git rm -f "{}" \;

This just means:

starting from the directory i'm currently in, find all files whose name ends with extension .pyc, and pass file name to the command git rm -f

After *.pyc files deletion from git as tracked files, commit this change to the repository, and then you can finally add the *.pyc line to the .gitignore file.

(adapted from http://yuji.wordpress.com/2010/10/29/git-remove-all-pyc/)

PHP move_uploaded_file() error?

Edit the code to be as follows:

// Upload file
$moved = move_uploaded_file($_FILES["file"]["tmp_name"], "images/" . "myFile.txt" );

if( $moved ) {
  echo "Successfully uploaded";         
} else {
  echo "Not uploaded because of error #".$_FILES["file"]["error"];
}

It will give you one of the following error code values 1 to 8:

UPLOAD_ERR_INI_SIZE = Value: 1; The uploaded file exceeds the upload_max_filesize directive in php.ini.

UPLOAD_ERR_FORM_SIZE = Value: 2; The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.

UPLOAD_ERR_PARTIAL = Value: 3; The uploaded file was only partially uploaded.

UPLOAD_ERR_NO_FILE = Value: 4; No file was uploaded.

UPLOAD_ERR_NO_TMP_DIR = Value: 6; Missing a temporary folder. Introduced in PHP 5.0.3.

UPLOAD_ERR_CANT_WRITE = Value: 7; Failed to write file to disk. Introduced in PHP 5.1.0.

UPLOAD_ERR_EXTENSION = Value: 8; A PHP extension stopped the file upload. PHP does not provide a way to ascertain which extension caused the file upload to stop; examining the list of loaded extensions with phpinfo() may help.

Oracle insert if not exists statement

insert into OPT       (email,        campaign_id) 
select 'mom@coxnet' as email, 100 as campaign_id from dual MINUS
select                 email,        campaign_id from OPT;

If there is already a record with [email protected]/100 in OPT, the MINUS will subtract this record from the select 'mom@coxnet' as email, 100 as campaign_id from dual record and nothing will be inserted. On the other hand, if there is no such record, the MINUS does not subract anything and the values mom@coxnet/100 will be inserted.

As p.marino has already pointed out, merge is probably the better (and more correct) solution for your problem as it is specifically designed to solve your task.

Convert.ToDateTime: how to set format

You can use Convert.ToDateTime is it is shown at How to convert a Datetime string to a current culture datetime string

DateTimeFormatInfo usDtfi = new CultureInfo("en-US", false).DateTimeFormat;

var result = Convert.ToDateTime("12/01/2011", usDtfi)

How do I merge a specific commit from one branch into another in Git?

If BranchA has not been pushed to a remote then you can reorder the commits using rebase and then simply merge. It's preferable to use merge over rebase when possible because it doesn't create duplicate commits.

git checkout BranchA
git rebase -i HEAD~113
... reorder the commits so the 10 you want are first ...
git checkout BranchB
git merge [the 10th commit]

Executing set of SQL queries using batch file?

Use the SQLCMD utility.

http://technet.microsoft.com/en-us/library/ms162773.aspx

There is a connect statement that allows you to swing from database server A to server B in the same batch.

:Connect server_name[\instance_name] [-l timeout] [-U user_name [-P password]] Connects to an instance of SQL Server. Also closes the current connection.

On the other hand, if you are familiar with PowerShell, you can programmatic do the same.

http://technet.microsoft.com/en-us/library/cc281954(v=sql.105).aspx

What is the reason for having '//' in Python?

To complement these other answers, the // operator also offers significant (3x) performance benefits over /, presuming you want integer division.

$ python -m timeit '20.5 // 2'
100,000,000 loops, best of 3: 14.9 nsec per loop

$ python -m timeit '20.5 / 2'
 10,000,000 loops, best of 3: 48.4 nsec per loop

$ python -m timeit '20 / 2'
 10,000,000 loops, best of 3: 43.0 nsec per loop

$ python -m timeit '20 // 2'
100,000,000 loops, best of 3: 14.4 nsec per loop

How to call servlet through a JSP page

Why would you want to do this? You shouldn't be executing controller code in the view, and most certainly shouldn't be trying to pull code inside of another servlet into the view either.

Do all of your processing and refactoring of the application first, then just pass off the results to a view. Make the view as dumb as possible and you won't even run into these problems.

If this kind of design is hard for you, try Freemarker or even something like Velocity (although I don't recommend it) to FORCE you to do this. You never have to do this sort of thing ever.

To put it more accurately, the problem you are trying to solve is just a symptom of a greater problem - your architecture/design of your servlets.

Controlling execution order of unit tests in Visual Studio

As you should know by now, purists say it's forbiden to run ordered tests. That might be true for unit tests. MSTest and other Unit Test frameworks are used to run pure unit test but also UI tests, full integration tests, you name it. Maybe we shouldn't call them Unit Test frameworks, or maybe we should and use them according to our needs. That's what most people do anyway.

I'm running VS2015 and I MUST run tests in a given order because I'm running UI tests (Selenium).

Priority - Doesn't do anything at all This attribute is not used by the test system. It is provided to the user for custom purposes.

orderedtest - it works but I don't recommend it because:

  1. An orderedtest a text file that lists your tests in the order they should be executed. If you change a method name, you must fix the file.
  2. The test execution order is respected inside a class. You can't order which class executes its tests first.
  3. An orderedtest file is bound to a configuration, either Debug or Release
  4. You can have several orderedtest files but a given method can not be repeated in different orderedtest files. So you can't have one orderedtest file for Debug and another for Release.

Other suggestions in this thread are interesting but you loose the ability to follow the test progress on Test Explorer.

You are left with the solution that purist will advise against, but in fact is the solution that works: sort by declaration order.

The MSTest executor uses an interop that manages to get the declaration order and this trick will work until Microsoft changes the test executor code.

This means the test method that is declared in the first place executes before the one that is declared in second place, etc.

To make your life easier, the declaration order should match the alphabetical order that is is shown in the Test Explorer.

  • A010_FirstTest
  • A020_SecondTest
  • etc
  • A100_TenthTest

I strongly suggest some old and tested rules:

  • use a step of 10 because you will need to insert a test method later on
  • avoid the need to renumber your tests by using a generous step between test numbers
  • use 3 digits to number your tests if you are running more than 10 tests
  • use 4 digits to number your tests if you are running more than 100 tests

VERY IMPORTANT

In order to execute the tests by the declaration order, you must use Run All in the Test Explorer.

Say you have 3 test classes (in my case tests for Chrome, Firefox and Edge). If you select a given class and right click Run Selected Tests it usually starts by executing the method declared in the last place.

Again, as I said before, declared order and listed order should match or else you'll in big trouble in no time.

How can I color Python logging output?

Just another solution, with the colors of ZetaSyanthis:

def config_log(log_level):

    def set_color(level, code):
        level_fmt = "\033[1;" + str(code) + "m%s\033[1;0m" 
        logging.addLevelName( level, level_fmt % logging.getLevelName(level) )

    std_stream = sys.stdout
    isatty = getattr(std_stream, 'isatty', None)
    if isatty and isatty():
        levels = [logging.DEBUG, logging.CRITICAL, logging.WARNING, logging.ERROR]
        for idx, level in enumerate(levels):
            set_color(level, 30 + idx )
        set_color(logging.DEBUG, 0)
    logging.basicConfig(stream=std_stream, level=log_level)

call it once from your __main__ function. I have something like this there:

options, arguments = p.parse_args()
log_level = logging.DEBUG if options.verbose else logging.WARNING
config_log(log_level)

it also verifies that the output is a console, otherwise no colors are used.

Best data type to store money values in MySQL

I prefer to use BIGINT, and store the values in by multiply with 100, so that it will become integer.

For e.g., to represent a currency value of 93.49, the value shall be stored as 9349, while displaying the value we can divide by 100 and display. This will occupy less storage space.

Caution:
Mostly we don't perform currency * currency multiplication, in case if we are doing it then divide the result with 100 and store, so that it returns to proper precision.

How do I enable Java in Microsoft Edge web browser?

About this, java declares that on Windows 10, Edge browser does not support plugins, so it will NOT run java. (see https://www.java.com/it/download/win10.jsp --> only visible with edge in win10) It also reports a notice: java is not officially supported yet in Windows 10. (see https://www.java.com/it/download/faq/win10_faq.xml)

How can I test if a letter in a string is uppercase or lowercase using JavaScript?

Another way is to compare the character with an empty object, i don't really know's why it works, but it works :

for (let i = 1; i <= 26; i++) {
   const letter = (i + 9).toString(36).toUpperCase();
   console.log('letter', letter, 'is upper', letter<{}); // returns true
}
for (let i = 1; i <= 26; i++) {
   const letter = (i + 9).toString(36);
   console.log('letter', letter, 'is upper', letter<{}); // returns false
}

so in a function :

function charIsUpper(character) {
   return character<{};
}

EDIT: it doesn't work with accents and diacritics, so it's possible to remove it

function charIsUpper(character) {
   return character
           .normalize('NFD')
           .replace(/[\u0300-\u036f]/g, '')<{};
}

How to position the form in the center screen?

Using this Function u can define your won position

setBounds(500, 200, 647, 418);

Converting .NET DateTime to JSON

Thought i'd add my solution that i've been using.

If you're using the System.Web.Script.Serialization.JavaScriptSerializer() then the time returned isn't going to be specific to your timezone. To fix this you'll also want to use dte.getTimezoneOffset() to get it back to your correct time.

String.prototype.toDateFromAspNet = function() {
    var dte = eval("new " + this.replace(/\//g, '') + ";");
    dte.setMinutes(dte.getMinutes() - dte.getTimezoneOffset());
    return dte;
}

now you'll just call

"/Date(1245398693390)/".toDateFromAspNet();

Fri Jun 19 2009 00:04:53 GMT-0400 (Eastern Daylight Time) {}

NullPointerException in Java with no StackTrace

As you mentioned in a comment, you're using log4j. I discovered (inadvertently) a place where I had written

LOG.error(exc);

instead of the typical

LOG.error("Some informative message", e);

through laziness or perhaps just not thinking about it. The unfortunate part of this is that it doesn't behave as you expect. The logger API actually takes Object as the first argument, not a string - and then it calls toString() on the argument. So instead of getting the nice pretty stack trace, it just prints out the toString - which in the case of NPE is pretty useless.

Perhaps this is what you're experiencing?

How to convert an object to a byte array in C#

If you want the serialized data to be really compact, you can write serialization methods yourself. That way you will have a minimum of overhead.

Example:

public class MyClass {

   public int Id { get; set; }
   public string Name { get; set; }

   public byte[] Serialize() {
      using (MemoryStream m = new MemoryStream()) {
         using (BinaryWriter writer = new BinaryWriter(m)) {
            writer.Write(Id);
            writer.Write(Name);
         }
         return m.ToArray();
      }
   }

   public static MyClass Desserialize(byte[] data) {
      MyClass result = new MyClass();
      using (MemoryStream m = new MemoryStream(data)) {
         using (BinaryReader reader = new BinaryReader(m)) {
            result.Id = reader.ReadInt32();
            result.Name = reader.ReadString();
         }
      }
      return result;
   }

}

R: rJava package install failing

below is one of my answers on another post - error: unable to load installed packages just now
(this is also relevant to this question)

For Linux(Ubuntu) users: If you have oracle-java (7/8) installed. It'll be at this location /usr/lib/jvm and sudo access is required.

Create the file /etc/ld.so.conf.d/java.conf with the following entries:

/usr/lib/jvm/java-8-oracle/jre/lib/amd64
/usr/lib/jvm/java-8-oracle/jre/lib/amd64/server

(Replace java-8-oracle with java-7-oracle depending on your java version)

Then:

sudo ldconfig

Restart RStudio and then install the rJava package.

AngularJS Multiple ng-app within a page

Use angular.bootstrap(element, [modules], [config]) to manually start up AngularJS application (for more information, see the Bootstrap guide).

See the following example:

_x000D_
_x000D_
// root-app_x000D_
const rootApp = angular.module('root-app', ['app1', 'app2']);_x000D_
_x000D_
// app1_x000D_
const app1 = angular.module('app1', []);_x000D_
app1.controller('main', function($scope) {_x000D_
  $scope.msg = 'App 1';_x000D_
});_x000D_
_x000D_
// app2_x000D_
const app2 = angular.module('app2', []);_x000D_
app2.controller('main', function($scope) {_x000D_
  $scope.msg = 'App 2';_x000D_
});_x000D_
_x000D_
// bootstrap_x000D_
angular.bootstrap(document.querySelector('#app1'), ['app1']);_x000D_
angular.bootstrap(document.querySelector('#app2'), ['app2']);
_x000D_
<!-- [email protected] -->_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.0/angular.min.js"></script>_x000D_
_x000D_
<!-- root-app -->_x000D_
<div ng-app="root-app">_x000D_
_x000D_
  <!-- app1 -->_x000D_
  <div id="app1">_x000D_
    <div ng-controller="main">_x000D_
      {{msg}}_x000D_
    </div>_x000D_
  </div>_x000D_
_x000D_
  <!-- app2 -->_x000D_
  <div id="app2">_x000D_
    <div ng-controller="main">_x000D_
      {{msg}}_x000D_
    </div>_x000D_
  </div>_x000D_
_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to select all columns, except one column in pandas?

You can use df.columns.isin()

df.loc[:, ~df.columns.isin(['b'])]

When you want to drop multiple columns, as simple as:

df.loc[:, ~df.columns.isin(['col1', 'col2'])]

How to insert TIMESTAMP into my MySQL table?

Please try CURRENT_TIME() or now() functions

"INSERT INTO contactinfo (name, email, subject, date, comments)
VALUES ('$name', '$email', '$subject', NOW(), '$comments')"

OR

"INSERT INTO contactinfo (name, email, subject, date, comments)
VALUES ('$name', '$email', '$subject', CURRENT_TIME(), '$comments')"

OR you could try with PHP date function here:

$date = date("Y-m-d H:i:s");

Check if Cookie Exists

You can do something like this to find out the cookies's value:

Request.Cookies[SESSION_COOKIE_NAME].Value

How to set recurring schedule for xlsm file using Windows Task Scheduler

I referred a blog by Kim for doing this and its working fine for me. See the blog

The automated execution of macro can be accomplished with the help of a VB Script file which is being invoked by Windows Task Scheduler at specified times.

Remember to replace 'YourWorkbook' with the name of the workbook you want to open and replace 'YourMacro' with the name of the macro you want to run.

See the VB Script File (just named it RunExcel.VBS):

    ' Create a WshShell to get the current directory
Dim WshShell
Set WshShell = CreateObject("WScript.Shell")

' Create an Excel instance
Dim myExcelWorker
Set myExcelWorker = CreateObject("Excel.Application") 

' Disable Excel UI elements
myExcelWorker.DisplayAlerts = False
myExcelWorker.AskToUpdateLinks = False
myExcelWorker.AlertBeforeOverwriting = False
myExcelWorker.FeatureInstall = msoFeatureInstallNone

' Tell Excel what the current working directory is 
' (otherwise it can't find the files)
Dim strSaveDefaultPath
Dim strPath
strSaveDefaultPath = myExcelWorker.DefaultFilePath
strPath = WshShell.CurrentDirectory
myExcelWorker.DefaultFilePath = strPath

' Open the Workbook specified on the command-line 
Dim oWorkBook
Dim strWorkerWB
strWorkerWB = strPath & "\YourWorkbook.xls"

Set oWorkBook = myExcelWorker.Workbooks.Open(strWorkerWB)

' Build the macro name with the full path to the workbook
Dim strMacroName
strMacroName = "'" & strPath & "\YourWorkbook" & "!Sheet1.YourMacro"
on error resume next 
   ' Run the calculation macro
   myExcelWorker.Run strMacroName
   if err.number <> 0 Then
      ' Error occurred - just close it down.
   End If
   err.clear
on error goto 0 

oWorkBook.Save 

myExcelWorker.DefaultFilePath = strSaveDefaultPath

' Clean up and shut down
Set oWorkBook = Nothing

' Don’t Quit() Excel if there are other Excel instances 
' running, Quit() will shut those down also
if myExcelWorker.Workbooks.Count = 0 Then
   myExcelWorker.Quit
End If

Set myExcelWorker = Nothing
Set WshShell = Nothing

You can test this VB Script from command prompt:

>> cscript.exe RunExcel.VBS

Once you have the VB Script file and workbook tested so that it does what you want, you can then use Microsoft Task Scheduler (Control Panel-> Administrative Tools--> Task Scheduler) to execute ‘cscript.exe RunExcel.vbs’ automatically for you.

Please note the path of the macro should be in correct format and inside single quotes like:

strMacroName = "'" & strPath & "\YourWorkBook.xlsm'" & 
"!ModuleName.MacroName"

Select every Nth element in CSS

You need the correct argument for the nth-child pseudo class.

  • The argument should be in the form of an + b to match every ath child starting from b.

  • Both a and b are optional integers and both can be zero or negative.

    • If a is zero then there is no "every ath child" clause.
    • If a is negative then matching is done backwards starting from b.
    • If b is zero or negative then it is possible to write equivalent expression using positive b e.g. 4n+0 is same as 4n+4. Likewise 4n-1 is same as 4n+3.

Examples:

Select every 4th child (4, 8, 12, ...)

_x000D_
_x000D_
li:nth-child(4n) {_x000D_
  background: yellow;_x000D_
}
_x000D_
<ol>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
</ol>
_x000D_
_x000D_
_x000D_

Select every 4th child starting from 1 (1, 5, 9, ...)

_x000D_
_x000D_
li:nth-child(4n+1) {_x000D_
  background: yellow;_x000D_
}
_x000D_
<ol>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
</ol>
_x000D_
_x000D_
_x000D_

Select every 3rd and 4th child from groups of 4 (3 and 4, 7 and 8, 11 and 12, ...)

_x000D_
_x000D_
/* two selectors are required */_x000D_
li:nth-child(4n+3),_x000D_
li:nth-child(4n+4) {_x000D_
  background: yellow;_x000D_
}
_x000D_
<ol>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
</ol>
_x000D_
_x000D_
_x000D_

Select first 4 items (4, 3, 2, 1)

_x000D_
_x000D_
/* when a is negative then matching is done backwards  */_x000D_
li:nth-child(-n+4) {_x000D_
  background: yellow;_x000D_
}
_x000D_
<ol>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
</ol>
_x000D_
_x000D_
_x000D_

Error: could not find function "%>%"

You need to load a package (like magrittr or dplyr) that defines the function first, then it should work.

install.packages("magrittr") # package installations are only needed the first time you use it
install.packages("dplyr")    # alternative installation of the %>%
library(magrittr) # needs to be run every time you start R and want to use %>%
library(dplyr)    # alternatively, this also loads %>%

The pipe operator %>% was introduced to "decrease development time and to improve readability and maintainability of code."

But everybody has to decide for himself if it really fits his workflow and makes things easier. For more information on magrittr, click here.

Not using the pipe %>%, this code would return the same as your code:

words <- colnames(as.matrix(dtm))
words <- words[nchar(words) < 20]
words

EDIT: (I am extending my answer due to a very useful comment that was made by @Molx)

Despite being from magrittr, the pipe operator is more commonly used with the package dplyr (which requires and loads magrittr), so whenever you see someone using %>% make sure you shouldn't load dplyr instead.

Linq select to new object

The answers here got me close, but in 2016, I was able to write the following LINQ:

List<ObjectType> objectList = similarTypeList.Select(o =>
    new ObjectType
    {
        PropertyOne = o.PropertyOne,
        PropertyTwo = o.PropertyTwo,
        PropertyThree = o.PropertyThree
    }).ToList();

React-router: How to manually invoke Link?

again this is JS :) this still works ....

var linkToClick = document.getElementById('something');
linkToClick.click();

<Link id="something" to={/somewhaere}> the link </Link>

What is a magic number, and why is it bad?

In programming, a "magic number" is a value that should be given a symbolic name, but was instead slipped into the code as a literal, usually in more than one place.

It's bad for the same reason SPOT (Single Point of Truth) is good: If you wanted to change this constant later, you would have to hunt through your code to find every instance. It is also bad because it might not be clear to other programmers what this number represents, hence the "magic".

People sometimes take magic number elimination further, by moving these constants into separate files to act as configuration. This is sometimes helpful, but can also create more complexity than it's worth.

Is it possible to use Visual Studio on macOS?

While Parallels is technically a VM it is capable of running games in high resolution at a high frame rate. If you run Parallels in Coherence mode it completely integrates Windows 7 into OS X and .Net framework is fully supported. So yes you can install Visual Studio on your Mac however the Apps you created would only run of windows computers unless they were web based.

How to wrap text in LaTeX tables?

To change the text AB into A \r B in a table cell, put this into the cell position: \makecell{A \\ B}.

Before doing that, you also need to include package makecell.

Is it better to use path() or url() in urls.py for django 2.0?

path is simply new in Django 2.0, which was only released a couple of weeks ago. Most tutorials won't have been updated for the new syntax.

It was certainly supposed to be a simpler way of doing things; I wouldn't say that URL is more powerful though, you should be able to express patterns in either format.

Converting java date to Sql timestamp

You can cut off the milliseconds using a Calendar:

java.util.Date utilDate = new java.util.Date();
Calendar cal = Calendar.getInstance();
cal.setTime(utilDate);
cal.set(Calendar.MILLISECOND, 0);
System.out.println(new java.sql.Timestamp(utilDate.getTime()));
System.out.println(new java.sql.Timestamp(cal.getTimeInMillis()));

Output:

2014-04-04 10:10:17.78
2014-04-04 10:10:17.0

How to open every file in a folder

you should try using os.walk

yourpath = 'path'

import os
for root, dirs, files in os.walk(yourpath, topdown=False):
    for name in files:
        print(os.path.join(root, name))
        stuff
    for name in dirs:
        print(os.path.join(root, name))
        stuff

Saving image from PHP URL

See file()PHP Manual:

$url    = 'http://mixednews.ru/wp-content/uploads/2011/10/0ed9320413f3ba172471860e77b15587.jpg';
$img    = 'miki.png';
$file   = file($url);
$result = file_put_contents($img, $file)

How to properly export an ES6 class in Node 4?

With ECMAScript 2015 you can export and import multiple classes like this

class Person
{
    constructor()
    {
        this.type = "Person";
    }
}

class Animal{
    constructor()
    {
        this.type = "Animal";
    }
}

module.exports = {
    Person,
    Animal
};

then where you use them:

const { Animal, Person } = require("classes");

const animal = new Animal();
const person = new Person();

In case of name collisions, or you prefer other names you can rename them like this:

const { Animal : OtherAnimal, Person : OtherPerson} = require("./classes");

const animal = new OtherAnimal();
const person = new OtherPerson();

Use ASP.NET MVC validation with jquery ajax?

Here's a rather simple solution:

In the controller we return our errors like this:

if (!ModelState.IsValid)
        {
            return Json(new { success = false, errors = ModelState.Values.SelectMany(x => x.Errors).Select(x => x.ErrorMessage).ToList() }, JsonRequestBehavior.AllowGet);
        }

Here's some of the client script:

function displayValidationErrors(errors)
{
    var $ul = $('div.validation-summary-valid.text-danger > ul');

    $ul.empty();
    $.each(errors, function (idx, errorMessage) {
        $ul.append('<li>' + errorMessage + '</li>');
    });
}

That's how we handle it via ajax:

$.ajax({
    cache: false,
    async: true,
    type: "POST",
    url: form.attr('action'),
    data: form.serialize(),
    success: function (data) {
        var isSuccessful = (data['success']);

        if (isSuccessful) {
            $('#partial-container-steps').html(data['view']);
            initializePage();
        }
        else {
            var errors = data['errors'];

            displayValidationErrors(errors);
        }
    }
});

Also, I render partial views via ajax in the following way:

var view = this.RenderRazorViewToString(partialUrl, viewModel);
        return Json(new { success = true, view }, JsonRequestBehavior.AllowGet);

RenderRazorViewToString method:

public string RenderRazorViewToString(string viewName, object model)
    {
        ViewData.Model = model;
        using (var sw = new StringWriter())
        {
            var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext,
                                                                     viewName);
            var viewContext = new ViewContext(ControllerContext, viewResult.View,
                                         ViewData, TempData, sw);
            viewResult.View.Render(viewContext, sw);
            viewResult.ViewEngine.ReleaseView(ControllerContext, viewResult.View);
            return sw.GetStringBuilder().ToString();
        }
    }

How to open standard Google Map application from my application?

To go to location WITH PIN on it, use:

String uri = "http://maps.google.com/maps?q=loc:" + destinationLatitude + "," + destinationLongitude;
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
intent.setPackage("com.google.android.apps.maps");
startActivity(intent);

for without pin, use this in uri:

 String uri = "geo:" + destinationLatitude + "," + destinationLongitude;

How do I lowercase a string in C?

Are you just dealing with ASCII strings, and have no locale issues? Then yes, that would be a good way to do it.

Remove empty strings from array while keeping record Without Loop?

arr = arr.filter(v => v);

as returned v is implicity converted to truthy

How can I toggle word wrap in Visual Studio?

I use this feature often enough that I add a custom button to the command bar.

  1. Click on the Add or Remove Buttons -> Customize
  2. Click on the Commands tab
  3. Click Add Command...
  4. Select Edit (or Edit|Advanced for newer VS versions) from the list
  5. Find Toggle Word Wrap and drag it onto your bar

How to refresh the data in a jqGrid?

$('#grid').trigger( 'reloadGrid' );

Convert javascript array to string

I needed an array to became a String rappresentation of an array I mean I needed that

var a = ['a','b','c'];
//became a "real" array string-like to pass on query params so was easy to do:
JSON.stringify(a); //-->"['a','b','c']"

maybe someone need it :)

Why do people hate SQL cursors so much?

basicaly 2 blocks of code that do the same thing. maybe it's a bit weird example but it proves the point. SQL Server 2005:

SELECT * INTO #temp FROM master..spt_values
DECLARE @startTime DATETIME

BEGIN TRAN 

SELECT @startTime = GETDATE()
UPDATE #temp
SET number = 0
select DATEDIFF(ms, @startTime, GETDATE())

ROLLBACK 

BEGIN TRAN 
DECLARE @name VARCHAR

DECLARE tempCursor CURSOR
    FOR SELECT name FROM #temp

OPEN tempCursor

FETCH NEXT FROM tempCursor 
INTO @name

SELECT @startTime = GETDATE()
WHILE @@FETCH_STATUS = 0
BEGIN

    UPDATE #temp SET number = 0 WHERE NAME = @name
    FETCH NEXT FROM tempCursor 
    INTO @name

END 
select DATEDIFF(ms, @startTime, GETDATE())
CLOSE tempCursor
DEALLOCATE tempCursor

ROLLBACK 
DROP TABLE #temp

the single update takes 156 ms while the cursor takes 2016 ms.

Cocoa Touch: How To Change UIView's Border Color And Thickness?

@IBInspectable is working for me on iOS 9 , Swift 2.0

extension UIView {

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

@IBInspectable var cornerRadius: CGFloat {
    get {
        return layer.cornerRadius
    }
    set(newValue) {
        layer.cornerRadius = newValue
    }
}

@IBInspectable var borderColor: UIColor? {
    get {
        if let color = layer.borderColor {
            return UIColor(CGColor: color)
        }
        return nil
    }
    set(newValue) {
        layer.borderColor = newValue?.CGColor
    }
}

Cell color changing in Excel using C#

Note: This assumes that you will declare constants for row and column indexes named COLUMN_HEADING_ROW, FIRST_COL, and LAST_COL, and that _xlSheet is the name of the ExcelSheet (using Microsoft.Interop.Excel)

First, define the range:

var columnHeadingsRange = _xlSheet.Range[
    _xlSheet.Cells[COLUMN_HEADING_ROW, FIRST_COL],
    _xlSheet.Cells[COLUMN_HEADING_ROW, LAST_COL]];

Then, set the background color of that range:

columnHeadingsRange.Interior.Color = XlRgbColor.rgbSkyBlue;

Finally, set the font color:

columnHeadingsRange.Font.Color = XlRgbColor.rgbWhite;

And here's the code combined:

var columnHeadingsRange = _xlSheet.Range[
    _xlSheet.Cells[COLUMN_HEADING_ROW, FIRST_COL],
    _xlSheet.Cells[COLUMN_HEADING_ROW, LAST_COL]];

columnHeadingsRange.Interior.Color = XlRgbColor.rgbSkyBlue;

columnHeadingsRange.Font.Color = XlRgbColor.rgbWhite;

Format a Go string without printing?

I've created go project for string formatting from template (it allow to format strings in C# or Python style, just first version for very simple cases), you could find it here https://github.com/Wissance/stringFormatter

it works in following manner:


func TestStrFormat(t *testing.T) {
    strFormatResult, err := Format("Hello i am {0}, my age is {1} and i am waiting for {2}, because i am {0}!",
                              "Michael Ushakov (Evillord666)", "34", "\"Great Success\"")
    assert.Nil(t, err)
    assert.Equal(t, "Hello i am Michael Ushakov (Evillord666), my age is 34 and i am waiting for \"Great Success\", because i am Michael Ushakov (Evillord666)!", strFormatResult)

    strFormatResult, err = Format("We are wondering if these values would be replaced : {5}, {4}, {0}", "one", "two", "three")
    assert.Nil(t, err)
    assert.Equal(t, "We are wondering if these values would be replaced : {5}, {4}, one", strFormatResult)

    strFormatResult, err = Format("No args ... : {0}, {1}, {2}")
    assert.Nil(t, err)
    assert.Equal(t, "No args ... : {0}, {1}, {2}", strFormatResult)
}

func TestStrFormatComplex(t *testing.T) {
    strFormatResult, err := FormatComplex("Hello {user} what are you doing here {app} ?", map[string]string{"user":"vpupkin", "app":"mn_console"})
    assert.Nil(t, err)
    assert.Equal(t, "Hello vpupkin what are you doing here mn_console ?", strFormatResult)
}

Get a DataTable Columns DataType

You could always use typeof in the if statement. It is better than working with string values like the answer of Natarajan.

if (dt.Columns[0].DataType == typeof(DateTime))
{
}

equivalent of vbCrLf in c#

You are looking for System.Environment.NewLine.

On Windows, this is equivalent to \r\n though it could be different under another .NET implementation, such as Mono on Linux, for example.

Rename Excel Sheet with VBA Macro

This should do it:

WS.Name = WS.Name & "_v1"

Android button onClickListener

easy:

launching activity (onclick handler)

 Intent myIntent = new Intent(CurrentActivity.this, NextActivity.class);
 myIntent.putExtra("key", value); //Optional parameters
 CurrentActivity.this.startActivity(myIntent);

on the new activity:

@Override
protected void onCreate(Bundle savedInstanceState) {
Intent intent = getIntent();
String value = intent.getStringExtra("key"); //if it's a string you stored.

and add your new activity in the AndroidManifest.xml:

<activity android:label="@string/app_name" android:name="NextActivity"/>

How to check file MIME type with javascript before upload?

As Drake states this could be done with FileReader. However, what I present here is a functional version. Take in consideration that the big problem with doing this with JavaScript is to reset the input file. Well, this restricts to only JPG (for other formats you will have to change the mime type and the magic number):

<form id="form-id">
  <input type="file" id="input-id" accept="image/jpeg"/>
</form>

<script type="text/javascript">
    $(function(){
        $("#input-id").on('change', function(event) {
            var file = event.target.files[0];
            if(file.size>=2*1024*1024) {
                alert("JPG images of maximum 2MB");
                $("#form-id").get(0).reset(); //the tricky part is to "empty" the input file here I reset the form.
                return;
            }

            if(!file.type.match('image/jp.*')) {
                alert("only JPG images");
                $("#form-id").get(0).reset(); //the tricky part is to "empty" the input file here I reset the form.
                return;
            }

            var fileReader = new FileReader();
            fileReader.onload = function(e) {
                var int32View = new Uint8Array(e.target.result);
                //verify the magic number
                // for JPG is 0xFF 0xD8 0xFF 0xE0 (see https://en.wikipedia.org/wiki/List_of_file_signatures)
                if(int32View.length>4 && int32View[0]==0xFF && int32View[1]==0xD8 && int32View[2]==0xFF && int32View[3]==0xE0) {
                    alert("ok!");
                } else {
                    alert("only valid JPG images");
                    $("#form-id").get(0).reset(); //the tricky part is to "empty" the input file here I reset the form.
                    return;
                }
            };
            fileReader.readAsArrayBuffer(file);
        });
    });
</script>

Take in consideration that this was tested on latest versions of Firefox and Chrome, and on IExplore 10.

For a complete list of mime types see Wikipedia.

For a complete list of magic number see Wikipedia.

Check if boolean is true?

Both are correct.

You probably have some coding standard in your company - just see to follow it through. If you don't have - you should :)

Check if key exists in JSON object using jQuery

No need of JQuery simply you can do

if(yourObject['email']){
 // what if this property exists.
}

as with any value for email will return you true, if there is no such property or that property value is null or undefined will result to false

How to set value of input text using jQuery

Your selector is retrieving the text box's surrounding <div class='textBoxEmployeeNumber'> instead of the input inside it.

// Access the input inside the div with this selector:
$(function () {
  $('.textBoxEmployeeNumber input').val("fgg");
});

Update after seeing output HTML

If the ASP.NET code reliably outputs the HTML <input> with an id attribute id='EmployeeId', you can more simply just use:

$(function () {
  $('#EmployeeId').val("fgg");
});

Failing this, you will need to verify in your browser's error console that you don't have other script errors causing this to fail. The first example above works correctly in this demonstration.

Spring MVC Multipart Request with JSON

We've seen in our projects that a post request with JSON and files is creating a lot of confusion between the frontend and backend developers, leading to unnecessary wastage of time.

Here's a better approach: convert file bytes array to Base64 string and send it in the JSON.

public Class UserDTO {
    private String firstName;
    private String lastName;
    private FileDTO profilePic; 
}

public class FileDTO {
    private String base64;
    // just base64 string is enough. If you want, send additional details
    private String name;
    private String type;
    private String lastModified;
}

@PostMapping("/user")
public String saveUser(@RequestBody UserDTO user) {
    byte[] fileBytes = Base64Utils.decodeFromString(user.getProfilePic().getBase64());
    ....
}

JS code to convert file to base64 string:

var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function () {

  const userDTO = {
    firstName: "John",
    lastName: "Wick",
    profilePic: {
      base64: reader.result,
      name: file.name,
      lastModified: file.lastModified,
      type: file.type
    }
  }
  
  // post userDTO
};
reader.onerror = function (error) {
  console.log('Error: ', error);
};

How can you export the Visual Studio Code extension list?

Dump extensions:

code --list-extensions > extensions.txt

Install extensions with Bash (Linux, OS X and WSL):

cat extensions.txt | xargs code --list-extensions {}

Install extensions on Windows with PowerShell:

cat extensions.txt |% { code --install-extension $_}

Why do Sublime Text 3 Themes not affect the sidebar?

I thought I would put a note here that explains a basic misconception for a lot of people who are using these Text Editors... Sublime Text in particular (or at least that's the one I use, so I don't know how it works for other editors):

There are "Themes" and there are "Color Schemes". They are similar but affect different things. "Themes" actively change the entire UI, and can include a Color Scheme if you set it up that way. This typically includes the sidebar, and can also include options for the file tabs, and some even include icons for the sidebar as well. And then we have "Color Schemes" which only change the coding windows and nothing else... not the Sidebar, nor the File tabs, etc.

The confusion happens because some people call Color Schemes "Themes" which makes folks think that their "Theme" is going to change everything.... when technically, it's just a color scheme.

And an additional note: Themes don't automatically install for all users. When I install a Theme, I have to open my User preferences (under "preferences > Settings - User"), and then you have to add the line which says something like:

"theme": "Theme-Name.sublime-theme" 

(where "Theme-Name" is the name of your theme).

This is different than just activating a color scheme. If you've chosen a color scheme via the dropdown menus in Sublime Text, you will see a line in there like this:

"color_scheme": "Packages/Color-Scheme-Name.tmTheme"

(where "Color-Scheme-Name" is the name of your color scheme).

Getting Cannot read property 'offsetWidth' of undefined with bootstrap carousel script

I have got the same error, but in my case I wrote class names for carousel item as .carousel-item the bootstrap.css is referring .item. SO ERROR solved. carosel-item is renamed to item

<div class="carousel-item active"></div>

RENAMED To the following:

<div class="item active"></div>

How do I run a batch file from my Java Application?

Runtime runtime = Runtime.getRuntime();
try {
    Process p1 = runtime.exec("cmd /c start D:\\temp\\a.bat");
    InputStream is = p1.getInputStream();
    int i = 0;
    while( (i = is.read() ) != -1) {
        System.out.print((char)i);
    }
} catch(IOException ioException) {
    System.out.println(ioException.getMessage() );
}

Is there a command for formatting HTML in the Atom editor?

Not Just HTML, Using atom-beautify - Package for Atom, you can format code for HTML, CSS, JavaScript, PHP, Python, Ruby, Java, C, C++, C#, Objective-C, CoffeeScript, TypeScript, Coldfusion, SQL, and more) in Atom within a matter of seconds.

To Install the atom-beautify package :

  • Open Atom Editor.
  • Press Ctrl+Shift+P (Cmd+Shift+P on mac), this will open the atom Command Palette.
  • Search and click on Install Packages & Themes. A Install Package window comes up.
  • Search for Beautify package, you will see a lot of beautify packages. Install any. I will recommend for atom-beautify.
  • Now Restart atom and TADA! now you are ready for quick formatting.

To Format text Using atom-beautify :

  • Go to the file you want to format.
  • Hit Ctrl+Alt+B (Ctrl+Option+B on mac).
  • Your file is formatted in seconds.

Iterating through a list to render multiple widgets in Flutter?

when you return some thing, the code exits out of the loop with what ever you are returning.so, in your code, in the first iteration, name is "one". so, as soon as it reaches return new Text(name), code exits the loop with return new Text("one"). so, try to print it or use asynchronous returns.

ImportError: No module named site on Windows

I have an application which relies heavily on Python and have kept up-to-date with python 2.7.x as new versions are released. Everthing has been fine until 2.7.11 when I got the same "No module named site" error. I've set PYTHONHOME to c:\Python27 and it's working. But the mystery remains why this is now needed when it wasn't with previous releases. And, if it is needed, why doesn't the installer set this var?

Excel - Button to go to a certain sheet

In Excel 2007, goto Insert/Shape and pick a shape. Colour it and enter whatever text you want. Then right click on the shape and insert a hyperlink

enter image description here

enter image description here

A few tips with shapes..

If you want to easily position the shape with cells, hold down Alt when you move the shape and it will lock to the cell. If you don't want the shape to move or resize with rows/columns, right click the shape, select size and properties and choose the setting which works best.

How to initialize an array in one step using Ruby?

If you have an Array of strings, you can also initialize it like this:

array = %w{1 2 3}

just separate each element with any whitespace

How to make an anchor tag refer to nothing?

I think you can try

<a href="JavaScript:void(0)">link</a>

The only catch I see over here is high level browser security may prompt on executing javascript.

Though this is one of the easier way than

<a href="#" onclick="return false;">Link</a>

this should be used sparingly

Read this article for some pointers https://web.archive.org/web/20090301044015/http://blog.reindel.com/2006/08/11/a-hrefjavascriptvoid0-avoid-the-void

How can I interrupt a running code in R with a keyboard command?

Self Answer (pretty much summary of other's comments and answers):

  • In RStudio, Esc works, on windows, Mac, and ubuntu (and I would guess on other linux distributions as well).

  • If the process is ran in say ubuntu shell (and this is not R specific), for example using:

    Rscript my_file.R
    

    Ctrl + c kills the process

    Ctrl + z suspends the process

  • Within R shell, Ctrl + C kills helps you escape it

How to find available directory objects on Oracle 11g system?

The ALL_DIRECTORIES data dictionary view will have information about all the directories that you have access to. That includes the operating system path

SELECT owner, directory_name, directory_path
  FROM all_directories

How do I perform HTML decoding/encoding using Python/Django?

For html encoding, there's cgi.escape from the standard library:

>> help(cgi.escape)
cgi.escape = escape(s, quote=None)
    Replace special characters "&", "<" and ">" to HTML-safe sequences.
    If the optional flag quote is true, the quotation mark character (")
    is also translated.

For html decoding, I use the following:

import re
from htmlentitydefs import name2codepoint
# for some reason, python 2.5.2 doesn't have this one (apostrophe)
name2codepoint['#39'] = 39

def unescape(s):
    "unescape HTML code refs; c.f. http://wiki.python.org/moin/EscapingHtml"
    return re.sub('&(%s);' % '|'.join(name2codepoint),
              lambda m: unichr(name2codepoint[m.group(1)]), s)

For anything more complicated, I use BeautifulSoup.

How to get the directory of the currently running file?

if you use this way :

dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
if err != nil {
    log.Fatal(err)
}
fmt.Println(dir)

you will get the /tmp path when you are running program using some IDE like GoLang because the executable will save and run from /tmp

i think the best way for getting the currentWorking Directory or '.' is :

import(
  "os" 
  "fmt"
  "log"
)

func main() {
  dir, err := os.Getwd()
    if err != nil {
        log.Fatal(err)
    }
  fmt.Println(dir)
}

the os.Getwd() function will return the current working directory. and its all without using of any external library :D

How do I open port 22 in OS X 10.6.7

I'm using OSX 10.11.6 and this article works for me.

enter image description here

Bootstrap modal z-index

I fell into this this with using the JQLayout plugin, especially when using nested layouts and modals with Bootstrap 4.

An overriding css needs to be added to correct the behaviour,

.pane-center{
    z-index:inherit !important;
}

Uploading Laravel Project onto Web Server

Had this problem too and found out that the easiest way is to point your domain to the public folder and leave everything else the way they are.

PLEASE ENSURE TO USE THE RIGHT VERSION OF PHP. Save yourself some stress :)

Java - Create a new String instance with specified length and filled with specific character. Best solution?

Try this jobber

String stringy =null;
 byte[] buffer =  new byte[100000];
            for (int i = 0; i < buffer.length; i++) {
            buffer[i] =0;

        }
            stringy =StringUtils.toAsciiString(buffer);

Html: Difference between cell spacing and cell padding

This is the simple answer I can give.

enter image description here

CSS selector last row from main table

Your tables should have as immediate children just tbody and thead elements, with the rows within*. So, amend the HTML to be:

<table border="1" width="100%" id="test">
  <tbody>
    <tr>
     <td>
      <table border="1" width="100%">
        <tbody>
          <tr>
            <td>table 2</td>
          </tr>
        </tbody>
      </table>
     </td>
    </tr> 
    <tr><td>table 1</td></tr>
    <tr><td>table 1</td></tr>
    <tr><td>table 1</td></tr>
  </tbody>
</table>

Then amend your selector slightly to this:

#test > tbody > tr:last-child { background:#ff0000; }

See it in action here. That makes use of the child selector, which:

...separates two selectors and matches only those elements matched by the second selector that are direct children of elements matched by the first.

So, you are targeting only direct children of tbody elements that are themselves direct children of your #test table.

Alternative solution

The above is the neatest solution, as you don't need to over-ride any styles. The alternative would be to stick with your current set-up, and over-ride the background style for the inner table, like this:

#test tr:last-child { background:#ff0000; }
#test table tr:last-child { background:transparent; }

* It's not mandatory but most (all?) browsers will add these in, so it's best to make it explicit. As @BoltClock states in the comments:

...it's now set in stone in HTML5, so for a browser to be compliant it basically must behave this way.

Jackson overcoming underscores in favor of camel-case

The above answers regarding @JsonProperty and CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES are 100% accurate, although some people (like me) might be trying to do this inside a Spring MVC application with code-based configuration. Here's sample code (that I have inside Beans.java) to achieve the desired effect:

@Bean
public ObjectMapper jacksonObjectMapper() {
    return new ObjectMapper().setPropertyNamingStrategy(
            PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES);
}

How to make inline functions in C#

C# 7 adds support for local functions

Here is the previous example using a local function

void Method()
{
    string localFunction(string source)
    {
        // add your functionality here
        return source ;
    };

   // call the inline function
   localFunction("prefix");
}

Can functions be passed as parameters?

Here is a simple example:

    package main

    import "fmt"

    func plusTwo() (func(v int) (int)) {
        return func(v int) (int) {
            return v+2
        }
    }

    func plusX(x int) (func(v int) (int)) {
       return func(v int) (int) {
           return v+x
       }
    }

    func main() {
        p := plusTwo()
        fmt.Printf("3+2: %d\n", p(3))

        px := plusX(3)
        fmt.Printf("3+3: %d\n", px(3))
    }

Hide div after a few seconds

we can directly use

$('#selector').delay(5000).fadeOut('slow');

Not connecting to SQL Server over VPN

I was having this issue too with SQL Server 2017.

I'm on the same network as the server via VPN and can ping it. After being frustrated that no authentication method would work - I set up an SSH server on the SQL server - and I was able to connect normally. This confirmed the correct port wasn't being hit for some reason. I even created a new user accounts, domain accounts, firewall checks on both ends, etc...

The solution for me was: 1. Set Connection to strictly use TCP/IP on SSMS 2. Use a custom string to point to the default port (ex: Data Source=192.168.168.166,1433;)

All the other comments above haven't worked so far. It looks like it was mandatory to include the port (even though its default).

Telling Python to save a .txt file to a certain directory on Windows and Mac

Another simple way without using import OS is,

outFileName="F:\\folder\\folder\\filename.txt"
outFile=open(outFileName, "w")
outFile.write("""Hello my name is ABCD""")
outFile.close()

bash: shortest way to get n-th column of output

If you are ok with manually selecting the column, you could be very fast using pick:

svn st | pick | xargs rm

Just go to any cell of the 2nd column, press c and then hit enter

R apply function with multiple parameters

To further generalize @Alexander's example, outer is relevant in cases where a function must compute itself on each pair of vector values:

vars1<-c(1,2,3)
vars2<-c(10,20,30)
mult_one<-function(var1,var2)
{
   var1*var2
}
outer(vars1,vars2,mult_one)

gives:

> outer(vars1, vars2, mult_one)
     [,1] [,2] [,3]
[1,]   10   20   30
[2,]   20   40   60
[3,]   30   60   90

What is the difference between CSS and SCSS?

Sass is a language that provides features to make it easier to deal with complex styling compared to editing raw .css. An example of such a feature is allowing definition of variables that can be re-used in different styles.

The language has two alternative syntaxes:

  • A JSON like syntax that is kept in files ending with .scss
  • A YAML like syntax that is kept in files ending with .sass

Either of these must be compiled to .css files which are recognized by browsers.

See https://sass-lang.com/ for further information.

How to remove leading whitespace from each line in a file

This Perl code edits your original file:

perl -i -ne 's/^\s+//;print' file

The next one makes a backup copy before editing the original file:

perl -i.bak -ne 's/^\s+//;print' file

Notice that Perl borrows heavily from sed (and AWK).

Webpack how to build production code and how to use it

If you have a lot of duplicate code in your webpack.dev.config and your webpack.prod.config, you could use a boolean isProd to activate certain features only in certain situations and only have a single webpack.config.js file.

const isProd = (process.env.NODE_ENV === 'production');

 if (isProd) {
     plugins.push(new AotPlugin({
      "mainPath": "main.ts",
      "hostReplacementPaths": {
        "environments/index.ts": "environments/index.prod.ts"
      },
      "exclude": [],
      "tsConfigPath": "src/tsconfig.app.json"
    }));
    plugins.push(new UglifyJsPlugin({
      "mangle": {
        "screw_ie8": true
      },
      "compress": {
        "screw_ie8": true,
        "warnings": false
      },
      "sourceMap": false
    }));
  }

By the way: The DedupePlugin plugin was removed from Webpack. You should remove it from your configuration.

UPDATE:

In addition to my previous answer:

If you want to hide your code for release, try enclosejs.com. It allows you to:

  • make a release version of your application without sources
  • create a self-extracting archive or installer
  • Make a closed source GUI application
  • Put your assets inside the executable

You can install it with npm install -g enclose

Integer value in TextView

TextView tv = new TextView(this);
tv.setText(String.valueOf(number));

or

tv.setText(""+number);

Export HTML page to PDF on user click using JavaScript

This is because you define your "doc" variable outside of your click event. The first time you click the button the doc variable contains a new jsPDF object. But when you click for a second time, this variable can't be used in the same way anymore. As it is already defined and used the previous time.

change it to:

$(function () {

    var specialElementHandlers = {
        '#editor': function (element,renderer) {
            return true;
        }
    };
 $('#cmd').click(function () {
        var doc = new jsPDF();
        doc.fromHTML(
            $('#target').html(), 15, 15, 
            { 'width': 170, 'elementHandlers': specialElementHandlers }, 
            function(){ doc.save('sample-file.pdf'); }
        );

    });  
});

and it will work.

TypeError: 'in <string>' requires string as left operand, not int

You simply need to make cab a string:

cab = '6176'

As the error message states, you cannot do <int> in <string>:

>>> 1 in '123'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'in <string>' requires string as left operand, not int
>>> 

because integers and strings are two totally different things and Python does not embrace implicit type conversion ("Explicit is better than implicit.").

In fact, Python only allows you to use the in operator with a right operand of type string if the left operand is also of type string:

>>> '1' in '123'  # Works!
True
>>>
>>> [] in '123'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'in <string>' requires string as left operand, not list
>>>
>>> 1.0 in '123'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'in <string>' requires string as left operand, not float
>>>
>>> {} in '123'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'in <string>' requires string as left operand, not dict
>>>

How to delete last character from a string using jQuery?

You can do it with plain JavaScript:

alert('123-4-'.substr(0, 4)); // outputs "123-"

This returns the first four characters of your string (adjust 4 to suit your needs).

How do I get the path of the Python script I am running in?

The accepted solution for this will not work if you are planning to compile your scripts using py2exe. If you're planning to do so, this is the functional equivalent:

os.path.dirname(sys.argv[0])

Py2exe does not provide an __file__ variable. For reference: http://www.py2exe.org/index.cgi/Py2exeEnvironment

How to add label in chart.js for pie chart

Rachel's solution is working fine, although you need to use the third party script from raw.githubusercontent.com

By now there is a feature they show on the landing page when advertisng the "modular" script. You can see a legend there with this structure:

<div class="labeled-chart-container">
    <div class="canvas-holder">
        <canvas id="modular-doughnut" width="250" height="250" style="width: 250px; height: 250px;"></canvas>
    </div>

<ul class="doughnut-legend">
    <li><span style="background-color:#5B90BF"></span>Core</li>
    <li><span style="background-color:#96b5b4"></span>Bar</li>
    <li><span style="background-color:#a3be8c"></span>Doughnut</li>
    <li><span style="background-color:#ab7967"></span>Radar</li>
    <li><span style="background-color:#d08770"></span>Line</li>
    <li><span style="background-color:#b48ead"></span>Polar Area</li>
</ul>
</div>

To achieve this they use the chart configuration option legendTemplate

legendTemplate : "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<segments.length; i++){%><li><span style=\"background-color:<%=segments[i].fillColor%>\"></span><%if(segments[i].label){%><%=segments[i].label%><%}%></li><%}%></ul>"

You can find the doumentation here on chartjs.org This works for all the charts although it is not part of the global chart configuration.

Then they create the legend and add it to the DOM like this:

var legend = myPie.generateLegend();
$("#legend").html(legend);

Sample See also my JSFiddle sample

Making an image act like a button

You could implement a JavaScript block which contains a function with your needs.

<div style="position: absolute; left: 10px; top: 40px;"> 
    <img src="logg.png" width="114" height="38" onclick="DoSomething();" />
</div>

How to get $HOME directory of different user in bash script?

In BASH, you can find a user's $HOME directory by prefixing the user's login ID with a tilde character. For example:

$ echo ~bob

This will echo out user bob's $HOME directory.

However, you say you want to be able to execute a script as a particular user. To do that, you need to setup sudo. This command allows you to execute particular commands as either a particular user. For example, to execute foo as user bob:

$ sudo -i -ubob -sfoo

This will start up a new shell, and the -i will simulate a login with the user's default environment and shell (which means the foo command will execute from the bob's$HOME` directory.)

Sudo is a bit complex to setup, and you need to be a superuser just to be able to see the shudders file (usually /etc/sudoers). However, this file usually has several examples you can use.

In this file, you can specify the commands you specify who can run a command, as which user, and whether or not that user has to enter their password before executing that command. This is normally the default (because it proves that this is the user and not someone who came by while the user was getting a Coke.) However, when you run a shell script, you usually want to disable this feature.

PowerShell Remoting giving "Access is Denied" error

Running the command prompt or Powershell ISE as an administrator fixed this for me.

Input size vs width

Both the size attribute in HTML and the width property in CSS will set the width of an <input>. If you want to set the width to something closer to the width of each character use the **ch** unit as in:

input {
    width: 10ch;
}

How do I set proxy for chrome in python webdriver?

from selenium import webdriver

PROXY = "23.23.23.23:3128" # IP:PORT or HOST:PORT

chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--proxy-server=%s' % PROXY)

chrome = webdriver.Chrome(options=chrome_options)
chrome.get("http://whatismyipaddress.com")

HTML5 Pre-resize images before uploading

Typescript

async resizeImg(file: Blob): Promise<Blob> {
    let img = document.createElement("img");
    img.src = await new Promise<any>(resolve => {
        let reader = new FileReader();
        reader.onload = (e: any) => resolve(e.target.result);
        reader.readAsDataURL(file);
    });
    await new Promise(resolve => img.onload = resolve)
    let canvas = document.createElement("canvas");
    let ctx = canvas.getContext("2d");
    ctx.drawImage(img, 0, 0);
    let MAX_WIDTH = 1000;
    let MAX_HEIGHT = 1000;
    let width = img.naturalWidth;
    let height = img.naturalHeight;
    if (width > height) {
        if (width > MAX_WIDTH) {
            height *= MAX_WIDTH / width;
            width = MAX_WIDTH;
        }
    } else {
        if (height > MAX_HEIGHT) {
            width *= MAX_HEIGHT / height;
            height = MAX_HEIGHT;
        }
    }
    canvas.width = width;
    canvas.height = height;
    ctx = canvas.getContext("2d");
    ctx.drawImage(img, 0, 0, width, height);
    let result = await new Promise<Blob>(resolve => { canvas.toBlob(resolve, 'image/jpeg', 0.95); });
    return result;
}

How do I clear this setInterval inside a function?

The setInterval method returns a handle that you can use to clear the interval. If you want the function to return it, you just return the result of the method call:

function intervalTrigger() {
  return window.setInterval( function() {
    if (timedCount >= markers.length) {
       timedCount = 0;
    }
    google.maps.event.trigger(markers[timedCount], "click");
    timedCount++;
  }, 5000 );
};
var id = intervalTrigger();

Then to clear the interval:

window.clearInterval(id);

Get the latest record from mongodb collection

This is a rehash of the previous answer but it's more likely to work on different mongodb versions.

db.collection.find().limit(1).sort({$natural:-1})

How do I increase modal width in Angular UI Bootstrap?

I found it easier to just take over the template from Bootstrap-ui. I have left the commented HTML still in-place to show what I changed.

Overwrite their default template:

<script type="text/ng-template" id="myDlgTemplateWrapper.html">
    <div tabindex="-1" role="dialog" class="modal fade" ng-class="{in: animate}" 
         ng-style="{'z-index': 1050 + index*10, display: 'block'}" ng-click="close($event)"> 
        <!-- <div class="modal-dialog"
            ng-class="{'modal-sm': size == 'sm', 'modal-lg': size == 'lg'}"
            >
            <div class="modal-content"  modal-transclude></div>
        </div>--> 

        <div modal-transclude>
            <!-- Your content goes here -->
        </div>
    </div>
</script>

Modify your dialog template (note the wrapper DIVs containing "modal-dialog" class and "modal-content" class):

<script type="text/ng-template" id="myModalContent.html">
    <div class="modal-dialog {{extraDlgClass}}"
         style="width: {{width}}; max-width: {{maxWidth}}; min-width: {{minWidth}}; ">
        <div class="modal-content">
            <div class="modal-header bg-primary">
                <h3>I am a more flexible modal!</h3>
            </div>
            <div class="modal-body"
                 style="min-height: {{minHeight}}; height: {{height}}; max-height {{maxHeight}}; ">
                <p>Make me any size you want</p>
            </div>
            <div class="modal-footer">
                <button class="btn btn-primary" ng-click="ok()">OK</button>
                <button class="btn btn-warning" ng-click="cancel()">Cancel</button>
            </div>
        </div>
    </div>
</script>

And then call the modal with whatever CSS class or style parameters you wish to change (assuming you have already defined "app" somewhere else):

<script type="text/javascript">
    app.controller("myTest", ["$scope", "$modal", function ($scope, $modal)
    {
        //  Adjust these with your parameters as needed

        $scope.extraDlgClass = undefined;

        $scope.width = "70%";
        $scope.height = "200px";
        $scope.maxWidth = undefined;
        $scope.maxHeight = undefined;
        $scope.minWidth = undefined;
        $scope.minHeight = undefined;

        $scope.open = function ()
        {
            $scope.modalInstance = $modal.open(
            {
                backdrop: 'static',
                keyboard: false,
                modalFade: true,

                templateUrl: "myModalContent.html",
                windowTemplateUrl: "myDlgTemplateWrapper.html",
                scope: $scope,
                //size: size,   - overwritten by the extraDlgClass below (use 'modal-lg' or 'modal-sm' if desired)

                extraDlgClass: $scope.extraDlgClass,

                width: $scope.width,
                height: $scope.height,
                maxWidth: $scope.maxWidth,
                maxHeight: $scope.maxHeight,
                minWidth: $scope.minWidth,
                minHeight: $scope.minHeight
            });

            $scope.modalInstance.result.then(function ()
            {
                console.log('Modal closed at: ' + new Date());
            },
            function ()
            {
                console.log('Modal dismissed at: ' + new Date());
            });
        };

        $scope.ok = function ($event)
        {
            if ($event)
                $event.preventDefault();
            $scope.modalInstance.close("OK");
        };

        $scope.cancel = function ($event)
        {
            if ($event)
                $event.preventDefault();
            $scope.modalInstance.dismiss('cancel');
        };

        $scope.openFlexModal = function ()
        {
            $scope.open();
        }

    }]);
</script>

Add an "open" button and fire away.

    <button ng-controller="myTest" class="btn btn-default" type="button" ng-click="openFlexModal();">Open Flex Modal!</button>

Now you can add whatever extra class you want, or simply change width/height sizes as necessary.

I further enclosed it within a wrapper directive, which is should be trivial from this point forward.

Cheers.

Convert dd-mm-yyyy string to date

Take a look at Datejs for all those petty date related issues.. You could solve this by parseDate function too

extract month from date in python

>>> a='2010-01-31'
>>> a.split('-')
['2010', '01', '31']
>>> year,month,date=a.split('-')
>>> year
'2010'
>>> month
'01'
>>> date
'31'

convert an enum to another type of enum

Based on Justin's answer above I came up with this:

    /// <summary>
    /// Converts Enum Value to different Enum Value (by Value Name) See https://stackoverflow.com/a/31993512/6500501.
    /// </summary>
    /// <typeparam name="TEnum">The type of the enum to convert to.</typeparam>
    /// <param name="source">The source enum to convert from.</param>
    /// <returns></returns>
    /// <exception cref="InvalidOperationException"></exception>
    public static TEnum ConvertTo<TEnum>(this Enum source)
    {
        try
        {
            return (TEnum) Enum.Parse(typeof(TEnum), source.ToString(), ignoreCase: true);
        }
        catch (ArgumentException aex)
        {
            throw new InvalidOperationException
            (
                $"Could not convert {source.GetType().ToString()} [{source.ToString()}] to {typeof(TEnum).ToString()}", aex
            );
        }
    }

Finding even or odd ID values

In oracle,

select num from table where MOD (num, 2) = 0;

Using jQuery to see if a div has a child with a certain class

If it's a direct child you can do as below if it could be nested deeper remove the >

$("#text-field").keydown(function(event) {
    if($('#popup>p.filled-text').length !== 0) {
        console.log("Found");
     }
});

How to comment/uncomment in HTML code

Depends on the extension. If it's .html, you can use <? to start and ?> to end a comment. That's really the only alternative that I can think of. http://jsfiddle.net/SuEAW/

Java 8 Distinct by property

Late to the party but I sometimes use this one-liner as an equivalent:

((Function<Value, Key>) Value::getKey).andThen(new HashSet<>()::add)::apply

The expression is a Predicate<Value> but since the map is inline, it works as a filter. This is of course less readable but sometimes it can be helpful to avoid the method.

What is the difference between WCF and WPF?

WCF = Windows Communication Foundation is used to build service-oriented applications. WPF = Windows Presentation Foundation is used to write platform-independent applications.

How to add Google Maps Autocomplete search box?

So I've been playing around with this and it seems you need both places and js maps api activated. Then use the following:

HTML:

<input id="searchTextField" type="text" size="50">
<input id="address" name="address" value='' type="hidden" placeholder="">

JS:

<script>
function initMap() {
  var input = document.getElementById('searchTextField');
  var autocomplete = new google.maps.places.Autocomplete(input);
  autocomplete.addListener('place_changed', function() {
    var place = autocomplete.getPlace();
    document.getElementById("address").value = JSON.stringify(place.address_components);
  });
}
</script>

<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places&callback=initMap" async defer></script>

Adding script tag to React/JSX

componentDidMount() {
  const head = document.querySelector("head");
  const script = document.createElement("script");
  script.setAttribute(
    "src",
    "https://assets.calendly.com/assets/external/widget.js"
  );
  head.appendChild(script);
}

C++ Object Instantiation

On the contrary, you should always prefer stack allocations, to the extent that as a rule of thumb, you should never have new/delete in your user code.

As you say, when the variable is declared on the stack, its destructor is automatically called when it goes out of scope, which is your main tool for tracking resource lifetime and avoiding leaks.

So in general, every time you need to allocate a resource, whether it's memory (by calling new), file handles, sockets or anything else, wrap it in a class where the constructor acquires the resource, and the destructor releases it. Then you can create an object of that type on the stack, and you're guaranteed that your resource gets freed when it goes out of scope. That way you don't have to track your new/delete pairs everywhere to ensure you avoid memory leaks.

The most common name for this idiom is RAII

Also look into smart pointer classes which are used to wrap the resulting pointers on the rare cases when you do have to allocate something with new outside a dedicated RAII object. You instead pass the pointer to a smart pointer, which then tracks its lifetime, for example by reference counting, and calls the destructor when the last reference goes out of scope. The standard library has std::unique_ptr for simple scope-based management, and std::shared_ptr which does reference counting to implement shared ownership.

Many tutorials demonstrate object instantiation using a snippet such as ...

So what you've discovered is that most tutorials suck. ;) Most tutorials teach you lousy C++ practices, including calling new/delete to create variables when it's not necessary, and giving you a hard time tracking lifetime of your allocations.

How to get the second column from command output?

#!/usr/bin/python
import sys 

col = int(sys.argv[1]) - 1

for line in sys.stdin:
    columns = line.split()

    try:
        print(columns[col])
    except IndexError:
        # ignore
        pass

Then, supposing you name the script as co, say, do something like this to get the sizes of files (the example assumes you're using Linux, but the script itself is OS-independent) :-

ls -lh | co 5

JWT (Json Web Token) Audience "aud" versus Client_Id - What's the difference?

Though this is old, I think question is valid even today

My suspicion is that aud should refer to the resource server(s), and the client_id should refer to one of the client applications recognized by the authentication server

Yes, aud should refer to token consuming party. And client_id refers to token obtaining party.

In my current case, my resource server is also my web app client.

In the OP's scenario, web app and resource server both belongs to same party. So this means client and audience to be same. But there can be situations where this is not the case.

Think about a SPA which consume an OAuth protected resource. In this scenario SPA is the client. Protected resource is the audience of access token.

This second scenario is interesting. There is a working draft in place named "Resource Indicators for OAuth 2.0" which explain where you can define the intended audience in your authorisation request. So the resulting token will restricted to the specified audience. Also, Azure OIDC use a similar approach where it allows resource registration and allow auth request to contain resource parameter to define access token intended audience. Such mechanisms allow OAuth adpotations to have a separation between client and token consuming (audience) party.

How to change link color (Bootstrap)

If you are using Bootstrap 4, you can simple use a color utility class (e.g. text-success, text-danger, etc... ).

You can also create your own classes (e.g. text-my-own-color)

Both options are shown in the example below, run the code snippet to see a live demo.

_x000D_
_x000D_
.text-my-own-color {
  color: #663300 !important; // Define your own color in your CSS
}
.text-my-own-color:hover, .text-my-own-color:active {
  color: #664D33 !important; // Define your own color's darkening/lightening in your CSS
}
_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" />
<div class="navbar-collapse">
  <ul class="nav pull-right">

    <!-- Bootstrap's color utility class -->
    <li class="active"><a class="text-success" href="#">? ???</a></li>

    <!-- Bootstrap's color utility class -->
    <li><a class="text-danger" href="#">??? ??? ????????</a></li>

    <!-- Bootstrap's color utility class -->
    <li><a class="text-warning" href="#">????</a></li>

    <!-- Custom color utility class -->
    <li><a class="text-my-own-color" href="#">????????</a></li>

  </ul>
</div>
_x000D_
_x000D_
_x000D_

How to increment a datetime by one day?

Incrementing dates can be accomplished using timedelta objects:

import datetime

datetime.datetime.now() + datetime.timedelta(days=1)

Look up timedelta objects in the Python docs: http://docs.python.org/library/datetime.html

Trying to use fetch and pass in mode: no-cors

If you are using Express as back-end you just have to install cors and import and use it in app.use(cors());. If it is not resolved then try switching ports. It will surely resolve after switching ports

How to find item with max value using linq?

With EF or LINQ to SQL:

var item = db.Items.OrderByDescending(i => i.Value).FirstOrDefault();

With LINQ to Objects I suggest to use morelinq extension MaxBy (get morelinq from nuget):

var item = items.MaxBy(i => i.Value);

Convert String XML fragment to Document Node in Java

If you're using dom4j, you can just do:

Document document = DocumentHelper.parseText(text);

(dom4j now found here: https://github.com/dom4j/dom4j)

Getting XML Node text value with Java DOM

I use a very old java. Jdk 1.4.08 and I had the same issue. The Node class for me did not had the getTextContent() method. I had to use Node.getFirstChild().getNodeValue() instead of Node.getNodeValue() to get the value of the node. This fixed for me.

How to get data from observable in angular2

Angular is based on observable instead of promise base as of angularjs 1.x, so when we try to get data using http it returns observable instead of promise, like you did

 return this.http
      .get(this.configEndPoint)
      .map(res => res.json());

then to get data and show on view we have to convert it into desired form using RxJs functions like .map() function and .subscribe()

.map() is used to convert the observable (received from http request)to any form like .json(), .text() as stated in Angular's official website,

.subscribe() is used to subscribe those observable response and ton put into some variable so from which we display it into the view

this.myService.getConfig().subscribe(res => {
   console.log(res);
   this.data = res;
});

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

The solution is to put an N in front of both the type and the SQL string to indicate it is a double-byte character string:

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

Why should I use an IDE?

Simply put, an IDE offers additional time-saving features over a simple editor.

Accessing AppDelegate from framework?

If you're creating a framework the whole idea is to make it portable. Tying a framework to the app delegate defeats the purpose of building a framework. What is it you need the app delegate for?

Select query to get data from SQL Server

According to MSDN

http://msdn.microsoft.com/ru-ru/library/system.data.sqlclient.sqlcommand.executenonquery(v=vs.110).aspx

result is the number of lines affected, and since your query is select no lines are affected (i.e. inserted, deleted or updated) anyhow.

If you want to return a single row of the query, use ExecuteScalar() instead of ExecuteNonQuery():

  int result = (int) (command.ExecuteScalar());

However, if you expect many rows to be returned, ExecuteReader() is the only option:

  using (SqlDataReader reader = command.ExecuteReader()) {
    while (reader.Read()) {
      int result = reader.GetInt32(0);

      ...
    }
  }

How to check if a file exists in Ansible?

I find it can be annoying and error prone to do a lot of these .stat.exists type checks. For example they require extra care to get check mode (--check) working.

Many answers here suggest

  • get and register
  • apply when register expression is true

However, sometimes this is a code smell so always look for better ways to use Ansible, specifically there are many advantages to using the correct module. e.g.

- name: install ntpdate
  package:
    name: ntpdate

or

- file:
    path: /etc/file.txt
    owner: root
    group: root
    mode: 0644

But when it is not possible use one module, also investigate if you can register and check the result of a previous task. e.g.

# jmeter_version: 4.0 
- name: Download Jmeter archive
  get_url:
    url: "http://archive.apache.org/dist/jmeter/binaries/apache-jmeter-{{ jmeter_version }}.tgz"
    dest: "/opt/jmeter/apache-jmeter-{{ jmeter_version }}.tgz"
    checksum: sha512:eee7d68bd1f7e7b269fabaf8f09821697165518b112a979a25c5f128c4de8ca6ad12d3b20cd9380a2b53ca52762b4c4979e564a8c2ff37196692fbd217f1e343
  register: download_result

- name: Extract apache-jmeter
  unarchive:
    src: "/opt/jmeter/apache-jmeter-{{ jmeter_version }}.tgz"
    dest: "/opt/jmeter/"
    remote_src: yes
    creates: "/opt/jmeter/apache-jmeter-{{ jmeter_version }}"
  when: download_result.state == 'file'

Note the when: but also the creates: so --check doesn't error out

I mention this because often these less-than-ideal practices come in pairs i.e. no apt/yum package so we have to 1) download and 2) unzip

Hope this helps

Click a button programmatically

Best implementation depends of what you are attempting to do exactly. Nadeem_MK gives you a valid one. Know you can also:

  1. raise the Button2_Click event using PerformClick() method:

    Private Sub Button1_Click(sender As Object, e As System.EventArgs) Handles Button1.Click
        'do stuff
        Me.Button2.PerformClick()
    End Sub
    
  2. attach the same handler to many buttons:

    Private Sub Button1_Click(sender As Object, e As System.EventArgs) _
        Handles Button1.Click, Button2.Click
        'do stuff
    End Sub
    
  3. call the Button2_Click method using the same arguments than Button1_Click(...) method (IF you need to know which is the sender, for example) :

    Private Sub Button1_Click(sender As Object, e As System.EventArgs) Handles Button1.Click
        'do stuff
         Button2_Click(sender, e)
    End Sub
    

Apache Name Virtual Host with SSL

You MUST add below part to enable NameVirtualHost functionality with given IP.

NameVirtualHost IP_Address:443

Unable to find the requested .Net Framework Data Provider in Visual Studio 2010 Professional

its solved. Use nuget and search for the "ODP.NET, Managed Driver" invariant="Oracle.ManagedDataAccess.Client".

and install the package. it will resolve the issue for me.

Javascript find json value

Making more general the @showdev answer.

var getObjectByValue = function (array, key, value) {
    return array.filter(function (object) {
        return object[key] === value;
    });
};

Example:

getObjectByValue(data, "code", "DZ" );

Node.js: Difference between req.query[] and req.params

Given this route

app.get('/hi/:param1', function(req,res){} );

and given this URL http://www.google.com/hi/there?qs1=you&qs2=tube

You will have:

req.query

{
  qs1: 'you',
  qs2: 'tube'
}

req.params

{
  param1: 'there'
}

Express req.params >>

How can I join on a stored procedure?

Why not just performing the calculation in your SQL?

SELECT 
  t.TenantName
  , t.CarPlateNumber
  , t.CarColor
  , t.Sex
  , t.SSNO
  , t.Phone
  , t.Memo
  , u.UnitNumber
  , p.PropertyName
  , trans.TenantBalance
FROM tblTenant t
     LEFT JOIN tblRentalUnit u ON t.UnitID = u.ID
     LEFT JOIN tblProperty p ON u.PropertyID = p.ID
     INNER JOIN (
       SELECT tenant.ID AS TenantID, SUM(ISNULL(trans.Amount,0)) AS TenantBalance 
       FROM tblTenant tenant
            LEFT JOIN tblTransaction trans ON tenant.ID = trans.TenantID
       GROUP BY tenant.ID
     ) trans ON trans.ID = t.ID
ORDER BY 
  p.PropertyName
  , t.CarPlateNumber

Adding two Java 8 streams, or an extra element to a stream

If you don't mind using 3rd Party Libraries cyclops-react has an extended Stream type that will allow you to do just that via the append / prepend operators.

Individual values, arrays, iterables, Streams or reactive-streams Publishers can be appended and prepended as instance methods.

Stream stream = ReactiveSeq.of(1,2)
                           .filter(x -> x!=0)
                           .append(ReactiveSeq.of(3,4))
                           .filter(x -> x!=1)
                           .append(5)
                           .filter(x -> x!=2);

[Disclosure I am the lead developer of cyclops-react]

Open source PDF library for C/C++ application?

It depends a bit on your needs. Some toolkits are better at drawing, others are better for writing text. Cairo has a pretty good for drawing (it support a wide range of screen and file types, including pdf), but it may not be ideal for good typography.

How to hide form code from view code/inspect element browser?

This code removes the inner html of an element from the dom when the debugger is open (tested in Chrome and IE)

var currentInnerHtml;
var element = new Image();
var elementWithHiddenContent = document.querySelector("#element-to-hide");
var innerHtml = elementWithHiddenContent.innerHTML;

element.__defineGetter__("id", function() {
    currentInnerHtml = "";
});

setInterval(function() {
    currentInnerHtml = innerHtml;
    console.log(element);
    console.clear();
    elementWithHiddenContent.innerHTML = currentInnerHtml;
}, 1000);

Here #element-to-hide is the id of element you want to hide. It is a hack, but I hope it helps you.

JavaScript private methods

Don't be so verbose. It's Javascript. Use a Naming Convention.

After years of working in es6 classes, I recently started work on an es5 project (using requireJS which is already very verbose-looking). I've been over and over all the strategies mentioned here and it all basically boils down to use a naming convention:

  1. Javascript doesn't have scope keywords like private. Other developers entering Javascript will know this upfront. Therefore, a simple naming convention is more than sufficient. A simple naming convention of prefixing with an underscore solves the problem of both private properties and private methods.
  2. Let's take advantage of the Prototype for speed reasons, but lets not get anymore verbose than that. Let's try to keep the es5 "class" looking as closely to what we might expect in other backend languages (and treat every file as a class, even if we don't need to return an instance).
  3. Let's demonstrate with a more realistic module situation (we'll use old es5 and old requireJs).

my-tooltip.js

    define([
        'tooltip'
    ],
    function(
        tooltip
    ){

        function MyTooltip() {
            // Later, if needed, we can remove the underscore on some
            // of these (make public) and allow clients of our class
            // to set them.
            this._selector = "#my-tooltip"
            this._template = 'Hello from inside my tooltip!';
            this._initTooltip();
        }

        MyTooltip.prototype = {
            constructor: MyTooltip,

            _initTooltip: function () {
                new tooltip.tooltip(this._selector, {
                    content: this._template,
                    closeOnClick: true,
                    closeButton: true
                });
            }
        }

        return {
            init: function init() {
               new MyTooltip();  // <-- Our constructor adds our tooltip to the DOM so not much we need to do after instantiation.
            }

            // You could instead return a new instantiation, 
            // if later you do more with this class.
            /* 
            create: function create() {
               return new MyTooltip();
            }
            */
        }
    });

"401 Unauthorized" on a directory

For me the Anonymous User access was fine at the server level, but varied at just one of my "virtual" folders.

Took me quite a bit of foundering about and then some help from a colleague to learn that IIS has "authentication" settings at the virtual folder level too - hopefully this helps someone else with my predicament.

'router-outlet' is not a known element

Try this:

Import RouterModule into your app.module.ts

import { RouterModule } from '@angular/router';

Add RouterModule into your imports []

like this:

 imports: [    RouterModule,  ]

Android dex gives a BufferOverflowException when building

For the ones facing issue with IntelliJ IDEA 13, uninstall Build Tools 19.

How to sort by Date with DataTables jquery plugin?

I got solution after working whole day on it. It is little hacky solution Added span inside td tag

<td><span><%= item.StartICDate %></span></td>. 

Date format which Im using is dd/MM/YYYY. Tested in Datatables1.9.0

Invalid length parameter passed to the LEFT or SUBSTRING function

This is because the CHARINDEX-1 is returning a -ive value if the look-up for " " (space) is 0. The simplest solution would be to avoid '-ve' by adding

ABS(CHARINDEX(' ', PostCode ) -1))

which will return only +ive values for your length even if CHARINDEX(' ', PostCode ) -1) is a -ve value. Correct me if I'm wrong!

How to count the number of true elements in a NumPy bool array

You have multiple options. Two options are the following.

numpy.sum(boolarr)
numpy.count_nonzero(boolarr)

Here's an example:

>>> import numpy as np
>>> boolarr = np.array([[0, 0, 1], [1, 0, 1], [1, 0, 1]], dtype=np.bool)
>>> boolarr
array([[False, False,  True],
       [ True, False,  True],
       [ True, False,  True]], dtype=bool)

>>> np.sum(boolarr)
5

Of course, that is a bool-specific answer. More generally, you can use numpy.count_nonzero.

>>> np.count_nonzero(boolarr)
5

Convert an ArrayList to an object array

TypeA[] array = (TypeA[]) a.toArray();

How do I get the value of text input field using JavaScript?

If you are using jQuery then by using plugin formInteract, you just need to do this:

// Just keep the HTML as it is.

<input name="searchTxt" type="text" maxlength="512" id="searchTxt" class="searchField"/>

At bottom of the page just include this plugin file and write this code:

// Initialize one time at the bottom of the page.
var search= $("#searchTxt).formInteract();

search.getAjax("http://www.myurl.com/search/", function(rsp){
    // Now do whatever you want to with your response
});

Or if using a parameterized URL then use this:

$.get("http://www.myurl.com/search/"+search.get().searchTxt, {}, function(rsp){
    // Now do work with your response;
})

Here is the link to project https://bitbucket.org/ranjeet1985/forminteract

You can use this plugin for many purposes like getting the value of a form, putting values into a form, validation of forms and many more. You can see some example of code in the index.html file of the project.

Of course I am the author of this project and all are welcome to make it better.

Error:Execution failed for task ':app:compileDebugKotlin'. > Compilation error. See log for more details

i was surprised to find that when i had a class that was closed it produced this vague error. changing it to a open class resolved the issue.

before:

 class DefaultSubscriber<T> : Observer<T> {//...
}

after:

open class DefaultSubscriber<T> : Observer<T> {//...
}

How to rsync only a specific list of files?

$ date
  Wed 24 Apr 2019 09:54:53 AM PDT
$ rsync --version
  rsync  version 3.1.3  protocol version 31
  ...

Syntax: rsync <file_/_folder_list> <source> <target>

Folder names (here, WITH a trailing /; e.g. Cancer - Evolution/) are in a folder list file (e.g.: cm_folder_list_test):

# /mnt/Vancouver/projects/ie/claws/data/cm_folder_list_test
# test file: 2019-04-24
Cancer/
Cancer - Evolution/
Cancer - Genomic Variants/
Cancer - Metastasis (EMT Transition ...)/
Cancer Pathways, Networks/
Catabolism - Autophagy; Phagosomes; Mitophagy/
Catabolism - Lysosomes/

If you don't include those trailing /, the rsync'd target folders are created, but are empty.

Those folder names are appended to the rest of their path (/home/victoria/Mail/2_RESEARCH - NEWS), thus providing the complete folder path to rsync; e.g.: /home/victoria/Mail/2_RESEARCH - NEWS/Cancer - Evolution/.

Note that you also need to use --files-from= ..., NOT --include-from= ...

rsync -aqP --delete --files-from=/mnt/Vancouver/projects/ie/claws/data/cm_folder_list_test "/home/victoria/Mail/2_RESEARCH - NEWS" $IN/

(In my BASH script, I defined variable $IN as follows.)

BASEDIR="/mnt/Vancouver/projects/ie/claws"
IN=$BASEDIR/data/test/input

rsync options used:

 -a  :   archive: equals -rlptgoD (no -H,-A,-X)
    -r  :   recursive
    -l  :   copy symlinks as symlinks
    -p  :   preserve permissions
    -t  :   preserve modification times 
    -g  :   preserve group 
    -o  :   preserve owner (super-user only) 
    -D  :   same as --devices --specials 
  -q  :   quiet (https://serverfault.com/questions/547106/run-totally-silent-rsync)

  --delete
    This  tells  rsync to delete extraneous files from the RECEIVING SIDE (ones
    that AREN’T ON THE SENDING SIDE), but only for the directories that are
    being synchronized.  You must have asked rsync to send the whole directory
    (e.g.  "dir" or "dir/") without using a wildcard for the directory’s contents
    (e.g. "dir/*") since the wildcard is expanded by the shell and rsync thus
    gets a request to transfer individual files, not the files’ parent directory.
    Files  that  are  excluded  from  the transfer are also excluded from being
    deleted unless you use the --delete-excluded option or mark the rules as
    only matching on the sending side (see the include/exclude modifiers in the
    FILTER RULES section).  ...

How can I make Visual Studio wrap lines at 80 characters?

Adds vertical column guides to the Visual Studio text editor. This version is for Visual Studio 2012, Visual Studio 2013 or Visual Studio 2015.

See the plugin.

How to convert array into comma separated string in javascript

Use the join method from the Array type.

a.value = [a, b, c, d, e, f];
var stringValueYouWant = a.join();

The join method will return a string that is the concatenation of all the array elements. It will use the first parameter you pass as a separator - if you don't use one, it will use the default separator, which is the comma.

json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190)

This error can also show up if there are parts in your string that json.loads() does not recognize. An in this example string, an error will be raised at character 27 (char 27).

string = """[{"Item1": "One", "Item2": False}, {"Item3": "Three"}]"""

My solution to this would be to use the string.replace() to convert these items to a string:

import json

string = """[{"Item1": "One", "Item2": False}, {"Item3": "Three"}]"""

string = string.replace("False", '"False"')

dict_list = json.loads(string)

What's the best three-way merge tool?

The summary is that I found ECMerge to be a great, though commercial product. http://www.elliecomputing.com/products/merge_overview.asp

enter image description here

I also agree with MrTelly that Ultracompare is very good. One nice feature is that it will compare RTF and Word docs, which is handy when you end up programming in word with the sales guys and they don't manage their docs correctly.

C# : changing listbox row color?

I find solution that instead of using ListBox I used ListView.It allows to change list items BackColor.

private void listView1_Refresh()
{
    for (int i = 0; i < listView1.Items.Count; i++)
    {
        listView1.Items[i].BackColor = Color.Red;
        for (int j = 0; j < existingStudents.Count; j++)
        {
            if (listView1.Items[i].ToString().Contains(existingStudents[j]))
            {
                listView1.Items[i].BackColor = Color.Green;
            }
        }
    }
}

Run javascript script (.js file) in mongodb including another file inside js

Use Load function

load(filename)

You can directly call any .js file from the mongo shell, and mongo will execute the JavaScript.

Example : mongo localhost:27017/mydb myfile.js

This executes the myfile.js script in mongo shell connecting to mydb database with port 27017 in localhost.

For loading external js you can write

load("/data/db/scripts/myloadjs.js")

Suppose we have two js file myFileOne.js and myFileTwo.js

myFileOne.js

print('From file 1');
load('myFileTwo.js');     // Load other js file .

myFileTwo.js

print('From file 2');

MongoShell

>mongo myFileOne.js

Output

From file 1
From file 2

Delete all files of specific type (extension) recursively down a directory using a batch file

You can use this to delete ALL Files Inside a Folder and Subfolders:

DEL "C:\Folder\*.*" /S /Q

Or use this to Delete Certain File Types Only:

DEL "C:\Folder\*.mp4" /S /Q 
DEL "C:\Folder\*.dat" /S /Q 

package android.support.v4.app does not exist ; in Android studio 0.8

tl;dr Remove all unused modules which have a dependency on the support library from your settings.gradle.

Long version:

In our case we had declared the support library as a dependency for all of our modules (one app module and multiple library modules) in a common.gradle file which is imported by every module. However there was one library module which wasn't declared as a dependency for any other module and therefore wasn't build. In every few syncs Android Studio would pick that exact module as the one where to look for the support library (that's why it appeared to happen randomly for us). As this module was never used it never got build which in turn caused the jar file not being in the intermediates folder of the module.

Removing this library module from settings.gradle and syncing again fixed the problem for us.

Confusion: @NotNull vs. @Column(nullable = false) with JPA and Hibernate

The most recent versions of hibernate JPA provider applies the bean validation constraints (JSR 303) like @NotNull to DDL by default (thanks to hibernate.validator.apply_to_ddl property defaults to true). But there is no guarantee that other JPA providers do or even have the ability to do that.

You should use bean validation annotations like @NotNull to ensure, that bean properties are set to a none-null value, when validating java beans in the JVM (this has nothing to do with database constraints, but in most situations should correspond to them).

You should additionally use the JPA annotation like @Column(nullable = false) to give the jpa provider hints to generate the right DDL for creating table columns with the database constraints you want. If you can or want to rely on a JPA provider like Hibernate, which applies the bean validation constraints to DDL by default, then you can omit them.

What is the difference between parseInt() and Number()?

Summary:

parseInt():

  • Takes a string as a first argument, the radix (An integer which is the base of a numeral system e.g. decimal 10 or binary 2) as a second argument
  • The function returns a integer number, if the first character cannot be converted to a number NaN will be returned.
  • If the parseInt() function encounters a non numerical value, it will cut off the rest of input string and only parse the part until the non numerical value.
  • If the radix is undefined or 0, JS will assume the following:
    • If the input string begins with "0x" or "0X", the radix is 16 (hexadecimal), the remainder of the string is parsed into a number.
    • If the input value begins with a 0 the radix can be either 8 (octal) or 10 (decimal). Which radix is chosen is depending on JS engine implementation. ES5 specifies that 10 should be used then. However, this is not supported by all browsers, therefore always specify radix if your numbers can begin with a 0.
    • If the input value begins with any number, the radix will be 10

Number():

  • The Number() constructor can convert any argument input into a number. If the Number() constructor cannot convert the input into a number, NaN will be returned.
  • The Number() constructor can also handle hexadecimal number, they have to start with 0x.

Example:

_x000D_
_x000D_
console.log(parseInt('0xF', 16));  // 15_x000D_
_x000D_
// z is no number, it will only evaluate 0xF, therefore 15 is logged_x000D_
console.log(parseInt('0xFz123', 16));_x000D_
_x000D_
// because the radix is 10, A is considered a letter not a number (like in Hexadecimal)_x000D_
// Therefore, A will be cut off the string and 10 is logged_x000D_
console.log(parseInt('10A', 10));  // 10_x000D_
_x000D_
// first character isnot a number, therefore parseInt will return NaN_x000D_
console.log(parseInt('a1213', 10));_x000D_
_x000D_
_x000D_
console.log('\n');_x000D_
_x000D_
_x000D_
// start with 0X, therefore Number will interpret it as a hexadecimal value_x000D_
console.log(Number('0x11'));_x000D_
_x000D_
// Cannot be converted to a number, NaN will be returned, notice that_x000D_
// the number constructor will not cut off a non number part like parseInt does_x000D_
console.log(Number('123A'));_x000D_
_x000D_
// scientific notation is allowed_x000D_
console.log(Number('152e-1'));  // 15.21
_x000D_
_x000D_
_x000D_

How to change the color of text in javafx TextField?

If you are designing your Javafx application using SceneBuilder then use -fx-text-fill(if not available as option then write it in style input box) as style and give the color you want,it will change the text color of your Textfield.

I came here for the same problem and solved it in this way.

correct quoting for cmd.exe for multiple arguments

Spaces are used for separating Arguments. In your case C:\Program becomes argument. If your file path contains spaces then add Double quotation marks. Then cmd will recognize it as single argument.

How to add a spinner icon to button when it's in the Loading state?

Here is a full-fledged css solution inspired by Bulma. Just add

    .button {
      display: inline-flex;
      align-items: center;
      justify-content: center;
      position: relative;
      min-width: 200px;
      max-width: 100%;
      min-height: 40px;
      text-align: center;
      cursor: pointer;
    }

    @-webkit-keyframes spinAround {
      from {
        -webkit-transform: rotate(0deg);
        transform: rotate(0deg);
      }
      to {
        -webkit-transform: rotate(359deg);
        transform: rotate(359deg);
      }
    }
    @keyframes spinAround {
      from {
        -webkit-transform: rotate(0deg);
        transform: rotate(0deg);
      }
      to {
        -webkit-transform: rotate(359deg);
        transform: rotate(359deg);
      }
    }

    .button.is-loading {
      text-indent: -9999px;
      box-shadow: none;
      font-size: 1rem;
      height: 2.25em;
      line-height: 1.5;
      vertical-align: top;
      padding-bottom: calc(0.375em - 1px);
      padding-left: 0.75em;
      padding-right: 0.75em;
      padding-top: calc(0.375em - 1px);
      white-space: nowrap;
    }

    .button.is-loading::after  {
      -webkit-animation: spinAround 500ms infinite linear;
      animation: spinAround 500ms infinite linear;
      border: 2px solid #dbdbdb;
      border-radius: 290486px;
      border-right-color: transparent;
      border-top-color: transparent;
      content: "";
      display: block;
      height: 1em;
      position: relative;
      width: 1em;
    }

How to bind WPF button to a command in ViewModelBase?

 <Grid >
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>
    <Button Command="{Binding ClickCommand}" Width="100" Height="100" Content="wefwfwef"/>
</Grid>

the code behind for the window:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = new ViewModelBase();
    }
}

The ViewModel:

public class ViewModelBase
{
    private ICommand _clickCommand;
    public ICommand ClickCommand
    {
        get
        {
            return _clickCommand ?? (_clickCommand = new CommandHandler(() => MyAction(), ()=> CanExecute));
        }
    }
     public bool CanExecute
     {
        get
        {
            // check if executing is allowed, i.e., validate, check if a process is running, etc. 
            return true/false;
        }
     }

    public void MyAction()
    {

    }
}

Command Handler:

 public class CommandHandler : ICommand
{
    private Action _action;
    private Func<bool> _canExecute;

    /// <summary>
    /// Creates instance of the command handler
    /// </summary>
    /// <param name="action">Action to be executed by the command</param>
    /// <param name="canExecute">A bolean property to containing current permissions to execute the command</param>
    public CommandHandler(Action action, Func<bool> canExecute)
    {
        _action = action;
        _canExecute = canExecute;
    }

    /// <summary>
    /// Wires CanExecuteChanged event 
    /// </summary>
    public event EventHandler CanExecuteChanged
    {
        add { CommandManager.RequerySuggested += value; }
        remove { CommandManager.RequerySuggested -= value; }
    }

    /// <summary>
    /// Forcess checking if execute is allowed
    /// </summary>
    /// <param name="parameter"></param>
    /// <returns></returns>
    public bool CanExecute(object parameter)
    {
        return _canExecute.Invoke();
    }

    public void Execute(object parameter)
    {
        _action();
    }
}

I hope this will give you the idea.

Why won't bundler install JSON gem?

For me, some of the answers mentioned earlier were helpful from understanding point of view, but those didn't solve my problem.

So this is what I did to solve issue.

  • Modified gemfile.lock to update json (2.0.2) (Earlier, it was 1.8.3)
  • Check the Bundler version installed (Bundler -v command). I had version 1.12.5 installed
  • Install bundler version 1.11.2 (using gem install bundler -v '1.11.2')
  • Then run bundle install

Java HttpRequest JSON & Response Handling

The simplest way is using libraries like google-http-java-client but if you want parse the JSON response by yourself you can do that in a multiple ways, you can use org.json, json-simple, Gson, minimal-json, jackson-mapper-asl (from 1.x)... etc

A set of simple examples:

Using Gson:

import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

public class Gson {

    public static void main(String[] args) {
    }

    public HttpResponse http(String url, String body) {

        try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
            HttpPost request = new HttpPost(url);
            StringEntity params = new StringEntity(body);
            request.addHeader("content-type", "application/json");
            request.setEntity(params);
            HttpResponse result = httpClient.execute(request);
            String json = EntityUtils.toString(result.getEntity(), "UTF-8");

            com.google.gson.Gson gson = new com.google.gson.Gson();
            Response respuesta = gson.fromJson(json, Response.class);

            System.out.println(respuesta.getExample());
            System.out.println(respuesta.getFr());

        } catch (IOException ex) {
        }
        return null;
    }

    public class Response{

        private String example;
        private String fr;

        public String getExample() {
            return example;
        }
        public void setExample(String example) {
            this.example = example;
        }
        public String getFr() {
            return fr;
        }
        public void setFr(String fr) {
            this.fr = fr;
        }
    }
}

Using json-simple:

import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

public class JsonSimple {

    public static void main(String[] args) {

    }

    public HttpResponse http(String url, String body) {

        try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
            HttpPost request = new HttpPost(url);
            StringEntity params = new StringEntity(body);
            request.addHeader("content-type", "application/json");
            request.setEntity(params);
            HttpResponse result = httpClient.execute(request);

            String json = EntityUtils.toString(result.getEntity(), "UTF-8");
            try {
                JSONParser parser = new JSONParser();
                Object resultObject = parser.parse(json);

                if (resultObject instanceof JSONArray) {
                    JSONArray array=(JSONArray)resultObject;
                    for (Object object : array) {
                        JSONObject obj =(JSONObject)object;
                        System.out.println(obj.get("example"));
                        System.out.println(obj.get("fr"));
                    }

                }else if (resultObject instanceof JSONObject) {
                    JSONObject obj =(JSONObject)resultObject;
                    System.out.println(obj.get("example"));
                    System.out.println(obj.get("fr"));
                }

            } catch (Exception e) {
                // TODO: handle exception
            }

        } catch (IOException ex) {
        }
        return null;
    }
}

etc...