Programs & Examples On #Extendercontrol

"The Controls collection cannot be modified because the control contains code blocks"

In my case I got this error because I was wrongly setting InnerText to a div with html inside it.

Example:

SuccessMessagesContainer.InnerText = "";

   <div class="SuccessMessages ui-state-success" style="height: 25px; display: none;" id="SuccessMessagesContainer" runat="server">
      <table>
         <tr>
            <td style="width: 80px; vertical-align: middle; height: 18px; text-align: center;">
               <img src="<%=Image_success_icn %>" style="margin: 0 auto; height: 18px;
                  width: 18px;" />
            </td>
            <td id="SuccessMessage" style="vertical-align: middle;" class="SuccessMessage" runat="server" >
            </td>
         </tr>
      </table>
   </div>

Operator overloading in Java

As many others have answered: Java doesn't support user-defined operator overloading.

Maybe this is off-topic, but I want to comment on some things I read in some answers.

About readability.
Compare:

  1. c = a + b
  2. c = a.add(b)

Look again!
Which one is more readable?

A programming language that allows the creation of user-defined types, should allow them to act in the same way as the built-in types (or primitive types).

So Java breaks a fundamental principle of Generic Programming:
We should be able to interchange objects of built-in types with objects of user-defined types.
(You may be wondering: "Did he say 'objects of built-in'?". Yes, see here.)

About String concatenation:

Mathematicians use the symbol + for commutative operations on sets.
So we can be sure that a + b = b + a.
String concatenation (in most programming languages) doesn't respect this common mathematical notation.

a := "hello";
b := "world";
c := (a + b = b + a);

or in Java:

String a = "hello";
String b = "world";
boolean c = (a + b).equals(b + a);

Extra:
Notice how in Java equality and identity are confused. The == (equality) symbol means:
a. Equality for primitive types.
b. Identity-check for user-defined types, therefore, we are forced to use the function equals() for equality.
But... What has this to do with operator overloading?
If the language allows the operator overloading the user could give the proper meaning to the equality operator.

Sublime Text 2 multiple line edit

ctrl + shift + right-click it works better that way

Can an angular directive pass arguments to functions in expressions specified in the directive's attributes?

Yes, there is a better way: You can use the $parse service in your directive to evaluate an expression in the context of the parent scope while binding certain identifiers in the expression to values visible only inside your directive:

$parse(attributes.callback)(scope.$parent, { arg2: yourSecondArgument });

Add this line to the link function of the directive where you can access the directive's attributes.

Your callback attribute may then be set like callback = "callback(item.id, arg2)" because arg2 is bound to yourSecondArgument by the $parse service inside the directive. Directives like ng-click let you access the click event via the $event identifier inside the expression passed to the directive by using exactly this mechanism.

Note that you do not have to make callback a member of your isolated scope with this solution.

Oracle SQL query for Date format

you can use this command by getting your data. this will extract your data...

select * from employees where to_char(es_date,'dd/mon/yyyy')='17/jun/2003';

Chrome / Safari not filling 100% height of flex parent

I have had a similar issue in iOS 8, 9 and 10 and the info above couldn't fix it, however I did discover a solution after a day of working on this. Granted it won't work for everyone but in my case my items were stacked in a column and had 0 height when it should have been content height. Switching the css to be row and wrap fixed the issue. This only works if you have a single item and they are stacked but since it took me a day to find this out I thought I should share my fix!

.wrapper {
    flex-direction: column; // <-- Remove this line
    flex-direction: row; // <-- replace it with
    flex-wrap: wrap; // <-- Add wrapping
}

.item {
    width: 100%;
}

SQL Server database backup restore on lower version

You'd have to use the Import/Export wizards in SSMS to migrate everything

There is no "downgrade" possible using backup/restore or detach/attach. Therefore what you have to do is:

  1. Backup the database from the server running the new SSMS/SQL version.
  2. Import data from the generated .bak file, by expanding the "Tasks" menu(after right-clicking the target database) and selecting the "Import Data" option.

Which programming languages can be used to develop in Android?

Java and C:

  • C used for low level functionalities and device connectivities
  • Java used for Framework and Application Level

You may find more information in Android developers site.

[Vue warn]: Cannot find element

I think sometimes stupid mistakes can give us this error.

<div id="#main"> <--- id with hashtag
    <div id="mainActivity" v-component="{{currentActivity}}" class="activity"></div>
</div>

To

<div id="main"> <--- id without hashtag
    <div id="mainActivity" v-component="{{currentActivity}}" class="activity"></div>
</div>

Hide the browse button on a input type=file

No, what you can do is a (ugly) workaround, but largely used

  1. Create a normal input and a image
  2. Create file input with opacity 0
  3. When the user click on the image, you simulate a click on the file input
  4. When file input change, you pass it's value to the normal input (so user can see the path)

Here you can see a full explanation, along with code:

http://www.quirksmode.org/dom/inputfile.html

Practical uses of different data structures

I am in the same boat as you do. I need to study for tech interviews, but memorizing a list is not really helpful. If you have 3-4 hours to spare, and want to do a deeper dive, I recommend checking out

mycodeschool
I’ve looked on Coursera and other resources such as blogs and textbooks, but I find them either not comprehensive enough or at the other end of the spectrum, too dense with prerequisite computer science terminologies.

The dude in the video have a bunch of lectures on data structures. Don’t mind the silly drawings, or the slight accent at all. You need to understand not just which data structure to select, but some other points to consider when people think about data structures:

  • pros and cons of the common data structures
  • why each data structure exist
  • how it actually work in the memory
  • specific questions/exercises and deciding which structure to use for maximum efficiency
  • lucid Big 0 explanation

I also posted notes on github if you are interested.

Why am I getting this error: No mapping specified for the following EntitySet/AssociationSet - Entity1?

I found I was getting the same error because I had forgot to create referential constraint after creating an association between two entities.

less than 10 add 0 to number

A single regular expression replace should do it:

var stringWithSmallIntegers = "4° 7' 34"W, 168° 1' 23"N";

var paddedString = stringWithSmallIntegers.replace(
    /\d+/g,
    function pad(digits) {
        return digits.length === 1 ? '0' + digits : digits;
    });

alert(paddedString);

shows the expected output.

Get loop count inside a Python FOR loop

Try using itertools.count([n])

Global Variable in app.js accessible in routes?

It is actually very easy to do this using the "set" and "get" methods available on an express object.

Example as follows, say you have a variable called config with your configuration related stuff that you want to be available in other places:

In app.js:

var config = require('./config');

app.configure(function() {
  ...
  app.set('config', config); 
  ...
}

In routes/index.js

exports.index = function(req, res){
  var config = req.app.get('config');
  // config is now available
  ...
}

Laravel 5.4 redirection to custom url after login

That's what i am currrently working, what a coincidence.

You also need to add the following lines into your LoginController

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;

use Illuminate\Foundation\Auth\AuthenticatesUsers;

use Illuminate\Http\Request;

class LoginController extends Controller
{
/*
|--------------------------------------------------------------------------
| Login Controller
|--------------------------------------------------------------------------
|
| This controller handles authenticating users for the application and
| redirecting them to your home screen. The controller uses a trait
| to conveniently provide its functionality to your applications.
|
*/

use AuthenticatesUsers;


protected function authenticated(Request $request, $user)
{
if ( $user->isAdmin() ) {// do your magic here
    return redirect()->route('dashboard');
}

 return redirect('/home');
}
/**
 * Where to redirect users after login.
 *
 * @var string
 */
//protected $redirectTo = '/admin';

/**
 * Create a new controller instance.
 *
 * @return void
 */
public function __construct()
{
    $this->middleware('guest', ['except' => 'logout']);
}
}

Interface/enum listing standard mime-type constants

From https://docs.oracle.com/javaee/7/api/javax/ws/rs/core/MediaType.html :

staticjava.lang.String APPLICATION_ATOM_XML             "application/atom+xml"
staticMediaType        APPLICATION_ATOM_XML_TYPE        "application/atom+xml"
staticjava.lang.String APPLICATION_FORM_URLENCODED      "application/x-www-form-urlencoded"
staticMediaType        APPLICATION_FORM_URLENCODED_TYPE "application/x-www-form-urlencoded"
staticjava.lang.String APPLICATION_JSON                 "application/json"
staticMediaType        APPLICATION_JSON_TYPE            "application/json"
staticjava.lang.String APPLICATION_OCTET_STREAM         "application/octet-stream"
staticMediaType        APPLICATION_OCTET_STREAM_TYPE    "application/octet-stream"
staticjava.lang.String APPLICATION_SVG_XML              "application/svg+xml"
staticMediaType        APPLICATION_SVG_XML_TYPE         "application/svg+xml"
staticjava.lang.String APPLICATION_XHTML_XML            "application/xhtml+xml"
staticMediaType        APPLICATION_XHTML_XML_TYPE       "application/xhtml+xml"
staticjava.lang.String APPLICATION_XML                  "application/xml"
staticMediaType        APPLICATION_XML_TYPE             "application/xml"
staticjava.lang.String MEDIA_TYPE_WILDCARD              The value of a type or subtype wildcard: "*"
staticjava.lang.String MULTIPART_FORM_DATA              "multipart/form-data"
staticMediaType        MULTIPART_FORM_DATA_TYPE         "multipart/form-data"
staticjava.lang.String TEXT_HTML                        "text/html"
staticMediaType        TEXT_HTML_TYPE                   "text/html"
staticjava.lang.String TEXT_PLAIN                       "text/plain"
staticMediaType        TEXT_PLAIN_TYPE                  "text/plain"
staticjava.lang.String TEXT_XML                         "text/xml"
staticMediaType        TEXT_XML_TYPE                    "text/xml"
staticjava.lang.String WILDCARD                         "*/*"
staticMediaType        WILDCARD_TYPE                    "*/*"

How do I change data-type of pandas data frame to string with a defined format?

If you could reload this, you might be able to use dtypes argument.

pd.read_csv(..., dtype={'COL_NAME':'str'})

How can I use the MS JDBC driver with MS SQL Server 2008 Express?

The latest JDBC MSSQL connectivity driver can be found on JDBC 4.0

The class file should be in the classpath. If you are using eclipse you can easily do the same by doing the following -->

Right Click Project Name --> Properties --> Java Build Path --> Libraries --> Add External Jars

Also as already been pointed out by @Cheeso the correct way to access is jdbc:sqlserver://server:port;DatabaseName=dbname

Meanwhile please find a sample class for accessing MSSQL DB (2008 in my case).

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class ConnectMSSQLServer
{
   public void dbConnect(String db_connect_string,
            String db_userid,
            String db_password)
   {
      try {
         Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
         Connection conn = DriverManager.getConnection(db_connect_string,
                  db_userid, db_password);
         System.out.println("connected");
         Statement statement = conn.createStatement();
         String queryString = "select * from SampleTable";
         ResultSet rs = statement.executeQuery(queryString);
         while (rs.next()) {
            System.out.println(rs.getString(1));
         }
         conn.close();
      } catch (Exception e) {
         e.printStackTrace();
      }
   }

   public static void main(String[] args)
   {
      ConnectMSSQLServer connServer = new ConnectMSSQLServer();
      connServer.dbConnect("jdbc:sqlserver://xx.xx.xx.xxxx:1433;databaseName=MyDBName", "DB_USER","DB_PASSWORD");
   }
}

Hope this helps.

How to import multiple .csv files at once?

I like the approach using list.files(), lapply() and list2env() (or fs::dir_ls(), purrr::map() and list2env()). That seems simple and flexible.

Alternatively, you may try the small package {tor} (to-R): By default it imports files from the working directory into a list (list_*() variants) or into the global environment (load_*() variants).

For example, here I read all the .csv files from my working directory into a list using tor::list_csv():

library(tor)

dir()
#>  [1] "_pkgdown.yml"     "cran-comments.md" "csv1.csv"        
#>  [4] "csv2.csv"         "datasets"         "DESCRIPTION"     
#>  [7] "docs"             "inst"             "LICENSE.md"      
#> [10] "man"              "NAMESPACE"        "NEWS.md"         
#> [13] "R"                "README.md"        "README.Rmd"      
#> [16] "tests"            "tmp.R"            "tor.Rproj"

list_csv()
#> $csv1
#>   x
#> 1 1
#> 2 2
#> 
#> $csv2
#>   y
#> 1 a
#> 2 b

And now I load those files into my global environment with tor::load_csv():

# The working directory contains .csv files
dir()
#>  [1] "_pkgdown.yml"     "cran-comments.md" "CRAN-RELEASE"    
#>  [4] "csv1.csv"         "csv2.csv"         "datasets"        
#>  [7] "DESCRIPTION"      "docs"             "inst"            
#> [10] "LICENSE.md"       "man"              "NAMESPACE"       
#> [13] "NEWS.md"          "R"                "README.md"       
#> [16] "README.Rmd"       "tests"            "tmp.R"           
#> [19] "tor.Rproj"

load_csv()

# Each file is now available as a dataframe in the global environment
csv1
#>   x
#> 1 1
#> 2 2
csv2
#>   y
#> 1 a
#> 2 b

Should you need to read specific files, you can match their file-path with regexp, ignore.case and invert.


For even more flexibility use list_any(). It allows you to supply the reader function via the argument .f.

(path_csv <- tor_example("csv"))
#> [1] "C:/Users/LeporeM/Documents/R/R-3.5.2/library/tor/extdata/csv"
dir(path_csv)
#> [1] "file1.csv" "file2.csv"

list_any(path_csv, read.csv)
#> $file1
#>   x
#> 1 1
#> 2 2
#> 
#> $file2
#>   y
#> 1 a
#> 2 b

Pass additional arguments via ... or inside the lambda function.

path_csv %>% 
  list_any(readr::read_csv, skip = 1)
#> Parsed with column specification:
#> cols(
#>   `1` = col_double()
#> )
#> Parsed with column specification:
#> cols(
#>   a = col_character()
#> )
#> $file1
#> # A tibble: 1 x 1
#>     `1`
#>   <dbl>
#> 1     2
#> 
#> $file2
#> # A tibble: 1 x 1
#>   a    
#>   <chr>
#> 1 b

path_csv %>% 
  list_any(~read.csv(., stringsAsFactors = FALSE)) %>% 
  map(as_tibble)
#> $file1
#> # A tibble: 2 x 1
#>       x
#>   <int>
#> 1     1
#> 2     2
#> 
#> $file2
#> # A tibble: 2 x 1
#>   y    
#>   <chr>
#> 1 a    
#> 2 b

refresh leaflet map: map container is already initialized

We facing this issue today and we solved it. what we do ?

leaflet map load div is below.

<div id="map_container">
   <div id="listing_map" class="right_listing"></div>
</div>

When form input change or submit we follow this step below. after leaflet map container removed in my page and create new again.

$( '#map_container' ).html( ' ' ).append( '<div id="listing_map" class="right_listing"></div>' );

After this code my leaflet map is working fine with form filter to reload again.

Thank you.

How do I use namespaces with TypeScript external modules?

Try to organize by folder:

baseTypes.ts

export class Animal {
    move() { /* ... */ }
}

export class Plant {
    photosynthesize() { /* ... */ }
}

dog.ts

import b = require('./baseTypes');

export class Dog extends b.Animal {
    woof() { }
}   

tree.ts

import b = require('./baseTypes');

class Tree extends b.Plant {
}

LivingThings.ts

import dog = require('./dog')
import tree = require('./tree')

export = {
    dog: dog,
    tree: tree
}

main.ts

import LivingThings = require('./LivingThings');
console.log(LivingThings.Tree)
console.log(LivingThings.Dog)

The idea is that your module themselves shouldn't care / know they are participating in a namespace, but this exposes your API to the consumer in a compact, sensible way which is agnostic to which type of module system you are using for the project.

Volatile vs Static in Java

Not sure static variables are cached in thread local memory or NOT. But when I executed two threads(T1,T2) accessing same object(obj) and when update made by T1 thread to static variable it got reflected in T2.

How to make child element higher z-index than parent?

Try using this code, it worked for me:

z-index: unset;

How to save final model using keras?

The model has a save method, which saves all the details necessary to reconstitute the model. An example from the keras documentation:

from keras.models import load_model

model.save('my_model.h5')  # creates a HDF5 file 'my_model.h5'
del model  # deletes the existing model

# returns a compiled model
# identical to the previous one
model = load_model('my_model.h5')

php - How do I fix this illegal offset type error

check $xml->entry[$i] exists and is an object before trying to get a property of it

 if(isset($xml->entry[$i]) && is_object($xml->entry[$i])){
   $source = $xml->entry[$i]->source;          
   $s[$source] += 1;
 }

or $source might not be a legal array offset but an array, object, resource or possibly null

Better way to sort array in descending order

Use LINQ OrderByDescending method. It returns IOrderedIEnumerable<int>, which you can convert back to Array if you need so. Generally, List<>s are more functional then Arrays.

array = array.OrderByDescending(c => c).ToArray();

MySQL Query - Records between Today and Last 30 Days

For the current date activity and complete activity for previous 30 days use this, since the SYSDATE is variable in a day the previous 30th day will not have the whole data for that day.

SELECT  DATE_FORMAT(create_date, '%m/%d/%Y')
FROM mytable
WHERE create_date BETWEEN CURDATE() - INTERVAL 30 DAY AND SYSDATE()

Delete many rows from a table using id in Mysql

Use IN Clause

   DELETE from tablename where id IN (1,2);

OR you can merge the use of BETWEEN and NOT IN to decrease the numbers you have to mention.

DELETE from tablename 
where (id BETWEEN 1 AND 255) 
AND (id NOT IN (254));

Which HTTP methods match up to which CRUD methods?

The Symfony project tries to keep its HTTP methods joined up with CRUD methods, and their list associates them as follows:

  • GET Retrieve the resource from the server
  • POST Create a resource on the server
  • PUT Update the resource on the server
  • DELETE Delete the resource from the server

It's worth noting that, as they say on that page, "In reality, many modern browsers don't support the PUT and DELETE methods."

From what I remember, Symfony "fakes" PUT and DELETE for those browsers that don't support them when generating its forms, in order to try to be as close to using the theoretically-correct HTTP method even when a browser doesn't support it.

Calling remove in foreach loop in Java

The java design of the "enhanced for loop" was to not expose the iterator to code, but the only way to safely remove an item is to access the iterator. So in this case you have to do it old school:

 for(Iterator<String> i = names.iterator(); i.hasNext();) {
       String name = i.next();
       //Do Something
       i.remove();
 }

If in the real code the enhanced for loop is really worth it, then you could add the items to a temporary collection and call removeAll on the list after the loop.

EDIT (re addendum): No, changing the list in any way outside the iterator.remove() method while iterating will cause problems. The only way around this is to use a CopyOnWriteArrayList, but that is really intended for concurrency issues.

The cheapest (in terms of lines of code) way to remove duplicates is to dump the list into a LinkedHashSet (and then back into a List if you need). This preserves insertion order while removing duplicates.

Altering a column: null to not null

this worked for me:

ALTER TABLE [Table] 
Alter COLUMN [Column] VARCHAR(50) not null;

Removing pip's cache?

pip can install a package ignoring the cache, like this

pip --no-cache-dir install scipy

How to get a value inside an ArrayList java

Assuming your Car class has a getter method for price, you can simply use

System.out.println (car.get(i).getPrice());

where i is the index of the element.

You can also use

Car c = car.get(i);
System.out.println (c.getPrice());

You also need to return totalprice from your function if you need to store it

main

public static void processCar(ArrayList<Car> cars){
    int totalAmount=0;
    for (int i=0; i<cars.size(); i++){
        int totalprice= cars.get(i).computeCars ();
        totalAmount=+ totalprice; 
    }
}

And change the return type of your function

public int computeCars (){
    int  totalprice= price+tax;
    System.out.println (name + "\t" +totalprice+"\t"+year );
    return  totalprice; 
 }

How can I make content appear beneath a fixed DIV element?

I liked grdevphl's Javascript answer best, but in my own use case, I found that using height() in the calculation still left a little overlap since it didn't take padding into account. If you run into the same issue, try outerHeight() instead to compensate for padding and border.

$(document).ready(function() {
    var contentPlacement = $('#header').position().top + $('#header').outerHeight();
    $('#content').css('margin-top',contentPlacement);
});

Prefer composition over inheritance?

Prefer composition over inheritance as it is more malleable / easy to modify later, but do not use a compose-always approach. With composition, it's easy to change behavior on the fly with Dependency Injection / Setters. Inheritance is more rigid as most languages do not allow you to derive from more than one type. So the goose is more or less cooked once you derive from TypeA.

My acid test for the above is:

  • Does TypeB want to expose the complete interface (all public methods no less) of TypeA such that TypeB can be used where TypeA is expected? Indicates Inheritance.

    • e.g. A Cessna biplane will expose the complete interface of an airplane, if not more. So that makes it fit to derive from Airplane.
  • Does TypeB want only some/part of the behavior exposed by TypeA? Indicates need for Composition.

    • e.g. A Bird may need only the fly behavior of an Airplane. In this case, it makes sense to extract it out as an interface / class / both and make it a member of both classes.

Update: Just came back to my answer and it seems now that it is incomplete without a specific mention of Barbara Liskov's Liskov Substitution Principle as a test for 'Should I be inheriting from this type?'

How to extract extension from filename string in Javascript?

Use the lastIndexOf method to find the last period in the string, and get the part of the string after that:

var ext = fileName.substr(fileName.lastIndexOf('.') + 1);

How to add action listener that listens to multiple buttons

Using my approach, you can write the button click event handler in the 'classical way', just like how you did it in VB or MFC ;)

Suppose we have a class for a frame window which contains 2 buttons:

class MainWindow {
    Jbutton searchButton;
    Jbutton filterButton;
}

You can use my 'router' class to route the event back to your MainWindow class:

class MainWindow {
    JButton searchButton;
    Jbutton filterButton;
    ButtonClickRouter buttonRouter = new ButtonClickRouter(this);
    
    void initWindowContent() {
        // create your components here...
        
        // setup button listeners
        searchButton.addActionListener(buttonRouter);
        filterButton.addActionListener(buttonRouter);
    }

    void on_searchButton() {
        // TODO your handler goes here...
    }
    
    void on_filterButton() {
        // TODO your handler goes here...
    }
}

Do you like it? :)

If you like this way and hate the Java's anonymous subclass way, then you are as old as I am. The problem of 'addActionListener(new ActionListener {...})' is that it squeezes all button handlers into one outer method which makes the programme look wired. (in case you have a number of buttons in one window)

Finally, the router class is at below. You can copy it into your programme without the need for any update.

Just one thing to mention: the button fields and the event handler methods must be accessible to this router class! To simply put, if you copy this router class in the same package of your programme, your button fields and methods must be package-accessible. Otherwise, they must be public.

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class ButtonClickRouter implements ActionListener {
    private Object target;

    ButtonClickRouter(Object target) {
        this.target = target;
    }

    @Override
    public void actionPerformed(ActionEvent actionEvent) {
        // get source button
        Object sourceButton = actionEvent.getSource();

        // find the corresponding field of the button in the host class
        Field fieldOfSourceButton = null;
        for (Field field : target.getClass().getDeclaredFields()) {
            try {
                if (field.get(target).equals(sourceButton)) {
                    fieldOfSourceButton = field;
                    break;
                }
            } catch (IllegalAccessException e) {
            }
        }

        if (fieldOfSourceButton == null)
            return;

        // make the expected method name for the source button
        // rule: suppose the button field is 'searchButton', then the method
        // is expected to be 'void on_searchButton()'
        String methodName = "on_" + fieldOfSourceButton.getName();

        // find such a method
        Method expectedHanderMethod = null;
        for (Method method : target.getClass().getDeclaredMethods()) {
            if (method.getName().equals(methodName)) {
                expectedHanderMethod = method;
                break;
            }
        }

        if (expectedHanderMethod == null)
            return;

        // fire
        try {
            expectedHanderMethod.invoke(target);
        } catch (IllegalAccessException | InvocationTargetException e) { }
    }
}

I'm a beginner in Java (not in programming), so maybe there are anything inappropriate in the above code. Review it before using it, please.

Label on the left side instead above an input field

I managed to fix my issue with. Seems to work fine and means I dont have to add widths to all my inputs manually.

.form-inline .form-group input {
 width: auto; 
}

c# foreach (property in object)... Is there a simple way of doing this?

I looked for the answer to a similar question on this page, I wrote the answers to several similar questions that may help people who enter this page.

Class List

List < T > class represents the list of objects which can be accessed by index. It comes under the System.Collection.Generic namespace. List class can be used to create a collection of different types like integers, strings etc. List class also provides the methods to search, sort, and manipulate lists.

Class with property:

class TestClss
{
    public string id { set; get; }
    public string cell1 { set; get; }
    public string cell2 { set; get; }
}
var MyArray = new List<TestClss> {
    new TestClss() { id = "1", cell1 = "cell 1 row 1 Data", cell2 = "cell 2 row 1 Data" },
    new TestClss() { id = "2", cell1 = "cell 1 row 2 Data", cell2 = "cell 2 row 2 Data" },
    new TestClss() { id = "3", cell1 = "cell 1 row 2 Data", cell2 = "cell 2 row 3 Data" }
};
foreach (object Item in MyArray)
{
    Console.WriteLine("Row Start");
    foreach (PropertyInfo property in Item.GetType().GetProperties())
    {
        var Key = property.Name;
        var Value = property.GetValue(Item, null);
        Console.WriteLine("{0}={1}", Key, Value);
    }
}

OR, Class with field:

class TestClss
{
    public string id = "";
    public string cell1 = "";
    public string cell2 = "";
}
var MyArray = new List<TestClss> {
    new TestClss() { id = "1", cell1 = "cell 1 row 1 Data", cell2 = "cell 2 row 1 Data" },
    new TestClss() { id = "2", cell1 = "cell 1 row 2 Data", cell2 = "cell 2 row 2 Data" },
    new TestClss() { id = "3", cell1 = "cell 1 row 2 Data", cell2 = "cell 2 row 3 Data" }
};
foreach (object Item in MyArray)
{
    Console.WriteLine("Row Start");
    foreach (var fieldInfo in Item.GetType().GetFields())
    {
        var Key = fieldInfo.Name;
        var Value = fieldInfo.GetValue(Item);
    }

}

OR, List of objects (without same cells):

var MyArray = new List<object> {
    new { id = "1", cell1 = "cell 1 row 1 Data", cell2 = "cell 2 row 1 Data" },
    new { id = "2", cell1 = "cell 1 row 2 Data", cell2 = "cell 2 row 2 Data" },
    new { id = "3", cell1 = "cell 1 row 2 Data", cell2 = "cell 2 row 3 Data", anotherCell = "" }
};
foreach (object Item in MyArray)
{
    Console.WriteLine("Row Start");
    foreach (var props in Item.GetType().GetProperties())
    {
        var Key = props.Name;
        var Value = props.GetMethod.Invoke(Item, null).ToString();
        Console.WriteLine("{0}={1}", Key, Value);
    }
}

OR, List of objects (It must have the same cells):

var MyArray = new[] {
    new { id = "1", cell1 = "cell 1 row 1 Data", cell2 = "cell 2 row 1 Data" },
    new { id = "2", cell1 = "cell 1 row 2 Data", cell2 = "cell 2 row 2 Data" },
    new { id = "3", cell1 = "cell 1 row 2 Data", cell2 = "cell 2 row 3 Data" }
};
foreach (object Item in MyArray)
{
    Console.WriteLine("Row Start");
    foreach (var props in Item.GetType().GetProperties())
    {
        var Key = props.Name;
        var Value = props.GetMethod.Invoke(Item, null).ToString();
        Console.WriteLine("{0}={1}", Key, Value);
    }
}

OR, List of objects (with key):

var MyArray = new {
    row1 = new { id = "1", cell1 = "cell 1 row 1 Data", cell2 = "cell 2 row 1 Data" },
    row2 = new { id = "2", cell1 = "cell 1 row 2 Data", cell2 = "cell 2 row 2 Data" },
    row3 = new { id = "3", cell1 = "cell 1 row 2 Data", cell2 = "cell 2 row 3 Data" }
};
// using System.ComponentModel;  for TypeDescriptor
foreach (PropertyDescriptor Item in TypeDescriptor.GetProperties(MyArray))
{
    string Rowkey = Item.Name;
    object RowValue = Item.GetValue(MyArray);
    Console.WriteLine("Row key is: {0}", Rowkey);
    foreach (var props in RowValue.GetType().GetProperties())
    {
        var Key = props.Name;
        var Value = props.GetMethod.Invoke(RowValue, null).ToString();
        Console.WriteLine("{0}={1}", Key, Value);
    }
}

OR, List of Dictionary

var MyArray = new List<Dictionary<string, string>>() {
    new Dictionary<string, string>() { { "id", "1" }, { "cell1", "cell 1 row 1 Data" }, { "cell2", "cell 2 row 1 Data" } },
    new Dictionary<string, string>() { { "id", "2" }, { "cell1", "cell 1 row 2 Data" }, { "cell2", "cell 2 row 2 Data" } },
    new Dictionary<string, string>() { { "id", "3" }, { "cell1", "cell 1 row 3 Data" }, { "cell2", "cell 2 row 3 Data" } }
};
foreach (Dictionary<string, string> Item in MyArray)
{
    Console.WriteLine("Row Start");
    foreach (KeyValuePair<string, string> props in Item)
    {
        var Key = props.Key;
        var Value = props.Value;
        Console.WriteLine("{0}={1}", Key, Value);
    }
}

Good luck..

How to add values in a variable in Unix shell scripting?

In ksh ,bash ,sh:

$ count7=0                     
$ count1=5
$ 
$ (( count7 += count1 ))
$ echo $count7
$ 5

DBCC SHRINKFILE on log file not reducing size even after BACKUP LOG TO DISK

I resolved this problem by taking the full and transactional backup. Sometimes, the backup process is not completed and that's one of the reason the .ldf file is not getting shrink. Try this. It worked for me.

Safari 3rd party cookie iframe trick no longer working?

I had this problem on devices running iOS. I made a shop that is embeddable in a normal website using an iframe. Somehow, on every pageload the user got a new sessionid, resulting in users getting stuck halfway the process because some values weren't present in the session.

I tried some of the solutions given on this page, but popups don't work very well on an iPad and I needed the most transparent solution.

I resolved it using a redirect. The website that embeds my site must first redirect the user to my site, so the top frame contains the url to my site, where I set a cookie and redirect the user to the proper page on the website that embeds my site, that is passed through in the url.

Example PHP code

Remote website redirects user to

http://clientname.example.com/init.php?redir=http://www.domain.com/shop/frame

init.php

<?php
// set a cookie for a year
setcookie('initialized','1',time() + 3600 * 24 * 365, '/', '.domain.com', false, false);
header('location: ' . $_GET['redir']);
die;

The user ends up on http://www.domain.com/shop/frame where my site is embedded, storing sessions as it should and eating cookies.

Hope this helps someone.

Array Size (Length) in C#

it goes like this: 1D:

 type[] name=new type[size]  //or =new type[]{.....elements...}

2D:

 type[][]name=new type[size][] //second brackets are emtpy

then as you use this array :

 name[i]=new type[size_of_sec.Dim]

or You can declare something like a matrix

type[ , ] name=new type [size1,size2]

conversion of a varchar data type to a datetime data type resulted in an out-of-range value

i faced this issue where i was using SQL it is different from MYSQL the solution was puting in this format: =date('m-d-y h:m:s'); rather than =date('y-m-d h:m:s');

How to get PHP $_GET array?

You can specify an array in your HTML this way:

<input type="hidden" name="id[]" value="1"/>
<input type="hidden" name="id[]" value="2"/>
<input type="hidden" name="id[]" value="3"/>

This will result in this $_GET array in PHP:

array(
  'id' => array(
    0 => 1,
    1 => 2,
    2 => 3
  )
)

Of course, you can use any sort of HTML input, here. The important thing is that all inputs whose values you want in the 'id' array have the name id[].

How do you find out the caller function in JavaScript?

To recap (and make it clearer) ...

this code:

function Hello() {
    alert("caller is " + arguments.callee.caller.toString());
}

is equivalent to this:

function Hello() {
    alert("caller is " + Hello.caller.toString());
}

Clearly the first bit is more portable, since you can change the name of the function, say from "Hello" to "Ciao", and still get the whole thing to work.

In the latter, in case you decide to refactor the name of the invoked function (Hello), you would have to change all its occurrences :(

Node JS Error: ENOENT

"/tmp/test.jpg" is not the correct path – this path starts with / which is the root directory.

In unix, the shortcut to the current directory is .

Try this "./tmp/test.jpg"

Take a list of numbers and return the average

You can use python's built-in function sum

  • sum will return the sum of all the values
  • len to get list's length

code:

>>> list = [1,2,3,4]
>>> sum(list)
>>> 10
>>> len(list)
>>> 4
>>> avg = float(sum(list))/len(list)
>>> 2.5
>>>"""In pyton3 don't want to specify float"""
>>> 10 / 4
>>> 2.5 

Use float because when using python 2.x, because:

  • int/int returns int value (i.e. 2)
  • float/int returns float value (i.e. 2.5)

While in Python 3.x:

  • int/int return float
  • int//int return int

python and sys.argv

I would do it this way:

import sys

def main(argv):
    if len(argv) < 2:
        sys.stderr.write("Usage: %s <database>" % (argv[0],))
        return 1

    if not os.path.exists(argv[1]):
        sys.stderr.write("ERROR: Database %r was not found!" % (argv[1],))
        return 1

if __name__ == "__main__":
    sys.exit(main(sys.argv))

This allows main() to be imported into other modules if desired, and simplifies debugging because you can choose what argv should be.

Refresh certain row of UITableView based on Int in Swift

Swift 4

let indexPathRow:Int = 0    
let indexPosition = IndexPath(row: indexPathRow, section: 0)
tableView.reloadRows(at: [indexPosition], with: .none)

Angular 5 Service to read local .json file

For Angular 7, I followed these steps to directly import json data:

In tsconfig.app.json:

add "resolveJsonModule": true in "compilerOptions"

In a service or component:

import * as exampleData from '../example.json';

And then

private example = exampleData;

Objective-C : BOOL vs bool

At the time of writing this is the most recent version of objc.h:

/// Type to represent a boolean value.
#if (TARGET_OS_IPHONE && __LP64__)  ||  TARGET_OS_WATCH
#define OBJC_BOOL_IS_BOOL 1
typedef bool BOOL;
#else
#define OBJC_BOOL_IS_CHAR 1
typedef signed char BOOL; 
// BOOL is explicitly signed so @encode(BOOL) == "c" rather than "C" 
// even if -funsigned-char is used.
#endif

It means that on 64-bit iOS devices and on WatchOS BOOL is exactly the same thing as bool while on all other devices (OS X, 32-bit iOS) it is signed char and cannot even be overridden by compiler flag -funsigned-char

It also means that this example code will run differently on different platforms (tested it myself):

int myValue = 256;
BOOL myBool = myValue;
if (myBool) {
    printf("i'm 64-bit iOS");
} else {
    printf("i'm 32-bit iOS");
}

BTW never assign things like array.count to BOOL variable because about 0.4% of possible values will be negative.

View google chrome's cached pictures

Modified version from @dovidev as his version loads the image externally instead of reading the local cache.

  1. Navigate to chrome://cache/
  2. In the chrome top menu go to "View > Developer > Javascript Console"
  3. In the console that opens paste the below and press enter

_x000D_
_x000D_
var cached_anchors = $$('a');_x000D_
document.body.innerHTML = '';_x000D_
for (var i in cached_anchors) {_x000D_
    var ca = cached_anchors[i];_x000D_
    if(ca.href.search('.png') > -1 || ca.href.search('.gif') > -1 || ca.href.search('.jpg') > -1) {_x000D_
        var xhr = new XMLHttpRequest();_x000D_
        xhr.open("GET", ca.href);_x000D_
        xhr.responseType = "document";_x000D_
        xhr.onload = response;_x000D_
        xhr.send();_x000D_
    }_x000D_
}_x000D_
_x000D_
function response(e) {_x000D_
  var hexdata = this.response.getElementsByTagName("pre")[2].innerHTML.split(/\r?\n/).slice(0,-1).map(e => e.split(/[\s:]+\s/)[1]).map(e => e.replace(/\s/g,'')).join('');_x000D_
  var byteArray = new Uint8Array(hexdata.length/2);_x000D_
  for (var x = 0; x < byteArray.length; x++){_x000D_
      byteArray[x] = parseInt(hexdata.substr(x*2,2), 16);_x000D_
  }_x000D_
  var blob = new Blob([byteArray], {type: "application/octet-stream"});_x000D_
  var image = new Image();_x000D_
  image.src = URL.createObjectURL(blob);_x000D_
  document.body.appendChild(image);_x000D_
}
_x000D_
_x000D_
_x000D_

Xcode 'CodeSign error: code signing is required'

Summarised form an answer to Xcode fails with "Code Signing" Error

project.pbxproj files can be merged in such a way that two CODE_SIGN_IDENTITY lines can be inserted. Deleting one of these normally fixes the issue.

I have created simple script to help diagnose this issue it can be found here: https://gist.github.com/4339226

A full answer can be found here.

What's the proper way to compare a String to an enum value?

This seems to be clean.

public enum Plane{

/**
 * BOEING_747 plane.
 */
BOEING_747("BOEING_747"),

/**
 * AIRBUS_A380 Plane.
 */
AIRBUS_A380("AIRBUS_A380"),

;

private final String plane;       

private Plane(final String plane) {
    this.plane= plane;
}

Plane(){ 
    plane=null; 
}


/**
 * toString method.
 * 
 * @return Value of this Enum as String.
 */
@Override
public String toString(){
   return plane;
}

/**
 * This method add support to compare Strings with the equalsIgnoreCase String method.
 * 
 * Replicated functionality of the equalsIgnorecase of the java.lang.String.class
 * 
 * @param value String to test.
 * @return True if equal otherwise false.
 */
public boolean equalsIgnoreCase(final String value){
    return plane.equalsIgnoreCase(value);
}

And then in main code:

String airplane="BOEING_747";

if(Plane.BOEING_747.equalsIgnoreCase(airplane)){
     //code
}

How to make a great R reproducible example

I wonder if an http://old.r-fiddle.org/ link could be a very neat way of sharing a problem. It receives a unique ID like and one could even think about embedding it in SO.

Convert 24 Hour time to 12 Hour plus AM/PM indication Oracle SQL

For the 24-hour time, you need to use HH24 instead of HH.

For the 12-hour time, the AM/PM indicator is written as A.M. (if you want periods in the result) or AM (if you don't). For example:

SELECT invoice_date,
       TO_CHAR(invoice_date, 'DD-MM-YYYY HH24:MI:SS') "Date 24Hr",
       TO_CHAR(invoice_date, 'DD-MM-YYYY HH:MI:SS AM') "Date 12Hr"
  FROM invoices
;

For more information on the format models you can use with TO_CHAR on a date, see http://docs.oracle.com/cd/E16655_01/server.121/e17750/ch4datetime.htm#NLSPG004.

How do I use an image as a submit button?

Why not:

<button type="submit">
<img src="mybutton.jpg" />
</button>

TypeError: unhashable type: 'dict'

A possible solution might be to use the JSON dumps() method, so you can convert the dictionary to a string ---

import json

a={"a":10, "b":20}
b={"b":20, "a":10}
c = [json.dumps(a), json.dumps(b)]


set(c)
json.dumps(a) in c

Output -

set(['{"a": 10, "b": 20}'])
True

Val and Var in Kotlin

var is a mutable variable and can be assigned multiple times and val is immutable variable and can be intialized only single time.

Convert a CERT/PEM certificate to a PFX certificate

If you have a self-signed certificate generated by makecert.exe on a Windows machine, you will get two files: cert.pvk and cert.cer. These can be converted to a pfx using pvk2pfx

pvk2pfx is found in the same location as makecert (e.g. C:\Program Files (x86)\Windows Kits\10\bin\x86 or similar)

pvk2pfx -pvk cert.pvk -spc cert.cer -pfx cert.pfx

X-Frame-Options Allow-From multiple domains

How about an approach that not only allows multiple domains, but allows dynamic domains.

The use case here is with a Sharepoint app part which loads our site inside of Sharepoint via an iframe. The problem is that sharepoint has dynamic subdomains such as https://yoursite.sharepoint.com. So for IE, we need to specify ALLOW-FROM https://.sharepoint.com

Tricky business, but we can get it done knowing two facts:

  1. When an iframe loads, it only validates the X-Frame-Options on the first request. Once the iframe is loaded, you can navigate within the iframe and the header isn't checked on subsequent requests.

  2. Also, when an iframe is loaded, the HTTP referer is the parent iframe url.

You can leverage these two facts server side. In ruby, I'm using the following code:

  uri = URI.parse(request.referer)
  if uri.host.match(/\.sharepoint\.com$/)
    url = "https://#{uri.host}"
    response.headers['X-Frame-Options'] = "ALLOW-FROM #{url}"
  end

Here we can dynamically allow domains based upon the parent domain. In this case, we ensure that the host ends in sharepoint.com keeping our site safe from clickjacking.

I'd love to hear feedback on this approach.

Line Break in XML formatting?

If you are refering to res strings, use CDATA with \n.

<string name="about">
    <![CDATA[
 Author: Sergio Abreu\n
 http://sites.sitesbr.net
  ]]>        
</string>

How can I get file extensions with JavaScript?

Wallacer's answer is nice, but one more checking is needed.

If file has no extension, it will use filename as extension which is not good.

Try this one:

return ( filename.indexOf('.') > 0 ) ? filename.split('.').pop().toLowerCase() : 'undefined';

IE9 jQuery AJAX with CORS returns "Access is denied"

Building on the solution by MoonScript, you could try this instead:

https://github.com/intuit/xhr-xdr-adapter/blob/master/src/xhr-xdr-adapter.js

The benefit is that since it's a lower level solution, it will enable CORS (to the extent possible) on IE 8/9 with other frameworks, not just with jQuery. I've had success using it with AngularJS, as well as jQuery 1.x and 2.x.

Remove last 3 characters of string or number in javascript

Remove last 3 characters of a string

var str = '1437203995000';
str = str.substring(0, str.length-3);
// '1437203995'

Remove last 3 digits of a number

var a = 1437203995000;
a = (a-(a%1000))/1000;
// a = 1437203995

CSS scale down image to fit in containing div, without specifing original size

This is an old question I know, but this is in the top five for several related Google searches. Here's the CSS-only solution without changing the images to background images:

width: auto;
height: auto;
max-width: MaxSize;
max-height: MaxSize;

"MaxSize" is a placeholder for whatever max-width and max-height you want to use, in pixels or percentage. auto will increase (or decrease) the width and height to occupy the space you specify with MaxSize. It will override any defaults for images you or the viewer's browser might have for images. I've found it's especially important on Android's Firefox. Pixels or percentages work for max size. With both the height and width set to auto, the aspect ratio of the original image will be retained.

If you want to fill the space entirely and don't mind the image being larger than its original size, change the two max-widths to min-width: 100% - this will make them completely occupy their space and maintain aspect ratio. You can see an example of this with a Twitter profile's background image.

How do I deal with installing peer dependencies in Angular CLI?

I found that running the npm install command in the same directory where your Angular project is, eliminates these warnings. I do not know the reason why.

Specifically, I was trying to use ng2-completer

$ npm install ng2-completer --save
npm WARN saveError ENOENT: no such file or directory, open 'C:\Work\foo\package.json'
npm notice created a lockfile as package-lock.json. You should commit this file.
npm WARN enoent ENOENT: no such file or directory, open 'C:\Work\foo\package.json'
npm WARN [email protected] requires a peer of @angular/common@>= 6.0.0 but none is installed. You must install peer dependencies yourself.
npm WARN [email protected] requires a peer of @angular/core@>= 6.0.0 but noneis installed. You must install peer dependencies yourself.
npm WARN [email protected] requires a peer of @angular/forms@>= 6.0.0 but none is installed. You must install peer dependencies yourself.
npm WARN foo No description
npm WARN foo No repository field.
npm WARN foo No README data
npm WARN foo No license field.

I was unable to compile. When I tried again, this time in my Angular project directory which was in foo/foo_app, it worked fine.

cd foo/foo_app
$ npm install ng2-completer --save

What is the difference among col-lg-*, col-md-* and col-sm-* in Bootstrap?

I think the confusing aspect of this is the fact that BootStrap 3 is a mobile first responsive system and fails to explain how this affects the col-xx-n hierarchy in that part of the Bootstrap documentation. This makes you wonder what happens on smaller devices if you choose a value for larger devices and makes you wonder if there is a need to specify multiple values. (You don't)

I would attempt to clarify this by stating that... Lower grain types (xs, sm) attempt retain layout appearance on smaller screens and larger types (md,lg) will display correctly only on larger screens but will wrap columns on smaller devices. The values quoted in previous examples refer to the threshold as which bootstrap degrades the appearance to fit the available screen estate.

What this means in practice is that if you make the columns col-xs-n then they will retain correct appearance even on very small screens, until the window drops to a size that is so restrictive that the page cannot be displayed correctly. This should mean that devices that have a width of 768px or less should show your table as you designed it rather than in degraded (single or wrapped column form). Obviously this still depends on the content of the columns and that's the whole point. If the page attempts to display multiple columns of large data, side by side on a small screen then the columns will naturally wrap in a horrible way if you did not account for it. Therefore, depending on the data within the columns you can decide the point at which the layout is sacificed to display the content adequately.

e.g. If your page contains three col-sm-n columns bootstrap would wrap the columns into rows when the page width drops below 992px. This means that the data is still visible but will require vertical scrolling to view it. If you do not want your layout to degrade, choose xs (as long as your data can be adequately displayed on a lower resolution device in three columns)

If the horizontal position of the data is important then you should try to choose lower granularity values to retain the visual nature. If the position is less important but the page must be visible on all devices then a higher value should be used.

If you choose col-lg-n then the columns will display correctly until the screen width drops below the xs threshold of 1200px.

Unable to create migrations after upgrading to ASP.NET Core 2.0

No need for IDesignTimeDbContextFactory.

Run

add-migration initial -verbose

that will reveal the details under

An error occurred while accessing the IWebHost on class 'Program'. Continuing without the application service provider.

warning, which is the root cause of the problem.

In my case, problem was, having ApplicationRole : IdentityRole<int> and invoking services.AddIdentity<ApplicationUser, IdentityRole>() which was causing below error

System.ArgumentException: GenericArguments[1], 'Microsoft.AspNetCore.Identity.IdentityRole', 
on 'Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserStore`9[TUser,TRole,TContext,
TKey,TUserClaim,TUserRole,TUserLogin,TUserToken,TRoleClaim]' violates the constraint of type 'TRole'.
---> System.TypeLoadException: GenericArguments[1], 'Microsoft.AspNetCore.Identity.IdentityRole', 
on 'Microsoft.AspNetCore.Identity.UserStoreBase`8[TUser,TRole,TKey,TUserClaim,
TUserRole,TUserLogin,TUserToken,TRoleClaim]' violates the constraint of type parameter 'TRole'.

Html.DropdownListFor selected value not being set

I had a similar issue, I was using the ViewBag and Element name as same. (Typing mistake)

Getting "cannot find Symbol" in Java project in Intellij

This works for me, say class A depends on class B(and class c, d etc) but the error throws on class A which does not have any errors. So I try to compile class A alone first ->it shows error on the package of class B. So tried to compile whole package of class B. Now it throws which is the exact error class(on my case class B had error). Usually Intellj shows the exact error class with line number when compile/build. On some occasions it throws error in wrong place/class. Have a try.

ISO time (ISO 8601) in Python

import datetime, time    
def convert_enddate_to_seconds(self, ts):
    """Takes ISO 8601 format(string) and converts into epoch time."""
     dt = datetime.datetime.strptime(ts[:-7],'%Y-%m-%dT%H:%M:%S.%f')+\
                datetime.timedelta(hours=int(ts[-5:-3]),
                minutes=int(ts[-2:]))*int(ts[-6:-5]+'1')
    seconds = time.mktime(dt.timetuple()) + dt.microsecond/1000000.0
    return seconds 

>>> import datetime, time
>>> ts = '2012-09-30T15:31:50.262-08:00'
>>> dt = datetime.datetime.strptime(ts[:-7],'%Y-%m-%dT%H:%M:%S.%f')+ datetime.timedelta(hours=int(ts[-5:-3]), minutes=int(ts[-2:]))*int(ts[-6:-5]+'1')
>>> seconds = time.mktime(dt.timetuple()) + dt.microsecond/1000000.0
>>> seconds
1348990310.26

How to pass json POST data to Web API method as an object?

Working with POST in webapi can be tricky! Would like to add to the already correct answer..

Will focus specifically on POST as dealing with GET is trivial. I don't think many would be searching around for resolving an issue with GET with webapis. Anyways..

If your question is - In MVC Web Api, how to- - Use custom action method names other than the generic HTTP verbs? - Perform multiple posts? - Post multiple simple types? - Post complex types via jQuery?

Then the following solutions may help:

First, to use Custom Action Methods in Web API, add a web api route as:

public static void Register(HttpConfiguration config)
{
    config.Routes.MapHttpRoute(
        name: "ActionApi",
        routeTemplate: "api/{controller}/{action}");
}

And then you may create action methods like:

[HttpPost]
public string TestMethod([FromBody]string value)
{
    return "Hello from http post web api controller: " + value;
}

Now, fire the following jQuery from your browser console

$.ajax({
    type: 'POST',
    url: 'http://localhost:33649/api/TestApi/TestMethod',
    data: {'':'hello'},
    contentType: 'application/x-www-form-urlencoded',
    dataType: 'json',
    success: function(data){ console.log(data) }
});

Second, to perform multiple posts, It is simple, create multiple action methods and decorate with the [HttpPost] attrib. Use the [ActionName("MyAction")] to assign custom names, etc. Will come to jQuery in the fourth point below

Third, First of all, posting multiple SIMPLE types in a single action is not possible. Moreover, there is a special format to post even a single simple type (apart from passing the parameter in the query string or REST style). This was the point that had me banging my head with Rest Clients (like Fiddler and Chrome's Advanced REST client extension) and hunting around the web for almost 5 hours when eventually, the following URL proved to be of help. Will quote the relevant content for the link might turn dead!

Content-Type: application/x-www-form-urlencoded
in the request header and add a = before the JSON statement:
={"Name":"Turbo Tina","Email":"[email protected]"}

PS: Noticed the peculiar syntax?

http://forums.asp.net/t/1883467.aspx?The+received+value+is+null+when+I+try+to+Post+to+my+Web+Api

Anyways, let us get over that story. Moving on:

Fourth, posting complex types via jQuery, ofcourse, $.ajax() is going to promptly come in the role:

Let us say the action method accepts a Person object which has an id and a name. So, from javascript:

var person = { PersonId:1, Name:"James" }
$.ajax({
    type: 'POST',
    url: 'http://mydomain/api/TestApi/TestMethod',
    data: JSON.stringify(person),
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    success: function(data){ console.log(data) }
});

And the action will look like:

[HttpPost]
public string TestMethod(Person person)
{
    return "Hello from http post web api controller: " + person.Name;
}

All of the above, worked for me!! Cheers!

How to generate Javadoc HTML files in Eclipse?

You can also do it from command line much easily.

  1. Open command line from the folder/package.
  2. From command line run:

    javadoc YourClassName.java

  3. To batch generate docs for multiple Class:

    javadoc *.java

How to diff a commit with its parent?

Paul's solution above did what I was hoping it would.

$ git diff HEAD^1

Also, it's useful to add aliases like hobs mentioned, if you put the following in the [alias] section of your ~/.gitconfig file then you can use short-hand to view diff between head and previous.

[alias]
    diff-last = diff HEAD^1

Then running $ git diff-last will get you your result. Note that this will also include any changes you've not yet committed as well as the diff between commits. If you want to ignore changes you've not yet committed, then you can use diff to compare the HEAD with it's parent directly:

$ git diff HEAD^1 HEAD

Automatic login script for a website on windows machine?

From the term "automatic login" I suppose security (password protection) is not of key importance here.

The guidelines for solution could be to use a JavaScript bookmark (idea borrowed form a nice game published on M&M's DK site).

The idea is to create a javascript file and store it locally. It should do the login data entering depending on current site address. Just an example using jQuery:

// dont forget to include jQuery code
// preferably with .noConflict() in order not to break the site scripts
if (window.location.indexOf("mail.google.com") > -1) {
    // Lets login to Gmail
    jQuery("#Email").val("[email protected]");
    jQuery("#Passwd").val("superSecretPassowrd");
    jQuery("#gaia_loginform").submit();
}

Now save this as say login.js

Then create a bookmark (in any browser) with this (as an) url:

javascript:document.write("<script type='text/javascript' src='file:///path/to/login.js'></script>");

Now when you go to Gmail and click this bookmark you will get automatically logged in by your script.

Multiply the code blocks in your script, to add more sites in the similar manner. You could even combine it with window.open(...) functionality to open more sites, but that may get the script inclusion more complicated.

Note: This only illustrates an idea and needs lots of further work, it's not a complete solution.

Gerrit error when Change-Id in commit messages are missing

This can also happen if you have this restriction:

Please enter the commit message for your changes. Lines starting with '#' will be ignored, and an empty message aborts the commit.

and you do like me: write a commit message starting with "#" .....

I had the same error, but I already had the commit-msg and did the rebase and everything. Very silly mistake though :D

Reading a binary input stream into a single byte array in Java

You can read it by chunks (byte buffer[] = new byte[2048]) and write the chunks to a ByteArrayOutputStream. From the ByteArrayOutputStream you can retrieve the contents as a byte[], without needing to determine its size beforehand.

Is there a way to make AngularJS load partials in the beginning and not at when needed?

If you wrap each template in a script tag, eg:

<script id="about.html" type="text/ng-template">
<div>
    <h3>About</h3>
    This is the About page
    Its cool!
</div>
</script>

Concatenate all templates into 1 big file. If using Visual Studio 2013, download Web essentials - it adds a right click menu to create an HTML Bundle.

Add the code that this guy wrote to change the angular $templatecache service - its only a small piece of code and it works: Vojta Jina's Gist

Its the $http.get that should be changed to use your bundle file:

allTplPromise = $http.get('templates/templateBundle.min.html').then(

Your routes templateUrl should look like this:

        $routeProvider.when(
            "/about", {
                controller: "",
                templateUrl: "about.html"
            }
        );

Make content horizontally scroll inside a div

if you remove the float: left from the a and add white-space: nowrap to the outer div

#myWorkContent{
    width:530px;
    height:210px;
    border: 13px solid #bed5cd;
    overflow-x: scroll;
    overflow-y: hidden;
    white-space: nowrap;
}
#myWorkContent a {
    display: inline;
}

this should work for any size or amount of images..

or even:

#myWorkContent a {
    display: inline-block;
    vertical-align: middle;
}

which would also vertically align images of different heights if required

test code

Combine multiple Collections into a single logical Collection?

You could create a new List and addAll() of your other Lists to it. Then return an unmodifiable list with Collections.unmodifiableList().

How to loop through array in jQuery?

You can use a for() loop:

var things = currnt_image_list.split(','); 
for(var i = 0; i < things.length; i++) {
    //Do things with things[i]
}

catching stdout in realtime from subprocess

Change the stdout from the rsync process to be unbuffered.

p = subprocess.Popen(cmd,
                     shell=True,
                     bufsize=0,  # 0=unbuffered, 1=line-buffered, else buffer-size
                     stdin=subprocess.PIPE,
                     stderr=subprocess.PIPE,
                     stdout=subprocess.PIPE)

Pandas convert string to int

You need add parameter errors='coerce' to function to_numeric:

ID = pd.to_numeric(ID, errors='coerce')

If ID is column:

df.ID = pd.to_numeric(df.ID, errors='coerce')

but non numeric are converted to NaN, so all values are float.

For int need convert NaN to some value e.g. 0 and then cast to int:

df.ID = pd.to_numeric(df.ID, errors='coerce').fillna(0).astype(np.int64)

Sample:

df = pd.DataFrame({'ID':['4806105017087','4806105017087','CN414149']})
print (df)
              ID
0  4806105017087
1  4806105017087
2       CN414149

print (pd.to_numeric(df.ID, errors='coerce'))
0    4.806105e+12
1    4.806105e+12
2             NaN
Name: ID, dtype: float64

df.ID = pd.to_numeric(df.ID, errors='coerce').fillna(0).astype(np.int64)
print (df)
              ID
0  4806105017087
1  4806105017087
2              0

EDIT: If use pandas 0.25+ then is possible use integer_na:

df.ID = pd.to_numeric(df.ID, errors='coerce').astype('Int64')
print (df)
              ID
0  4806105017087
1  4806105017087
2            NaN

Using jquery to delete all elements with a given id

The cleanest way to do it is by using html5 selectors api, specifically querySelectorAll().

var contentToRemove = document.querySelectorAll("#myid");
$(contentToRemove).remove(); 

The querySelectorAll() function returns an array of dom elements matching a specific id. Once you have assigned the returned array to a var, then you can pass it as an argument to jquery remove().

Angularjs prevent form submission when input validation fails

Although not a direct solution for the OPs question, if your form is within an ng-app context, but you want Angular to ignore it altogether, you can do this explicitly using the ngNonBindable directive:

<form ng-non-bindable>
  ...
</form>

How to keep :active css style after clicking an element

The :target-pseudo selector is made for these type of situations: http://reference.sitepoint.com/css/pseudoclass-target

It is supported by all modern browsers. To get some IE versions to understand it you can use something like Selectivizr

Here is a tab example with :target-pseudo selector.

ECMAScript 6 arrow function that returns an object

You may wonder, why the syntax is valid (but not working as expected):

var func = p => { foo: "bar" }

It's because of JavaScript's label syntax:

So if you transpile the above code to ES5, it should look like:

var func = function (p) {
  foo:
  "bar"; //obviously no return here!
}

JQuery Number Formatting

I wrote a JavaScript analogue of a PHP function number_format on a base of Abe Miessler addCommas function. Could be usefull.

number_format = function (number, decimals, dec_point, thousands_sep) {
        number = number.toFixed(decimals);

        var nstr = number.toString();
        nstr += '';
        x = nstr.split('.');
        x1 = x[0];
        x2 = x.length > 1 ? dec_point + x[1] : '';
        var rgx = /(\d+)(\d{3})/;

        while (rgx.test(x1))
            x1 = x1.replace(rgx, '$1' + thousands_sep + '$2');

        return x1 + x2;
    }

For example:

var some_number = number_format(42661.55556, 2, ',', ' '); //gives 42 661,56

Insert image after each list item

The easier way to do it is just:

ul li:after {
    content: url('../images/small_triangle.png');
}

Inputting a default image in case the src attribute of an html <img> is not valid?

The above solution is incomplete, it missed the attribute src.

this.src and this.attribute('src') are NOT the same, the first one contains the full reference to the image, for example http://my.host/error.jpg, but the attribute just keeps the original value, error.jpg

Correct solution

<img src="foo.jpg" onerror="if (this.src != 'error.jpg' && this.attribute('src') != 'error.jpg') this.src = 'error.jpg';" />

Select columns in PySpark dataframe

First two columns and 5 rows

 df.select(df.columns[:2]).take(5)

How to use OAuth2RestTemplate?

My simple solution. IMHO it's the cleanest.

First create a application.yml

spring.main.allow-bean-definition-overriding: true

security:
  oauth2:
    client:
      clientId: XXX
      clientSecret: XXX
      accessTokenUri: XXX
      tokenName: access_token
      grant-type: client_credentials

Create the main class: Main

@SpringBootApplication
@EnableOAuth2Client
public class Main extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .antMatchers("/").permitAll();
    }

    public static void main(String[] args) {
        SpringApplication.run(Main.class, args);
    }

    @Bean
    public OAuth2RestTemplate oauth2RestTemplate(ClientCredentialsResourceDetails details) {
        return new OAuth2RestTemplate(details);
    }

}

Then Create the controller class: Controller

@RestController
class OfferController {

    @Autowired
    private OAuth2RestOperations restOperations;

    @RequestMapping(value = "/<your url>"
            , method = RequestMethod.GET
            , produces = "application/json")
    public String foo() {
        ResponseEntity<String> responseEntity = restOperations.getForEntity(<the url you want to call on the server>, String.class);
        return responseEntity.getBody();
    }
}

Maven dependencies

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.5.RELEASE</version>
</parent>
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.security.oauth.boot</groupId>
        <artifactId>spring-security-oauth2-autoconfigure</artifactId>
        <version>2.1.5.RELEASE</version>
    </dependency>
</dependencies>

Calling Javascript function from server side

This works for me. Hope it will work for you too.

ScriptManager.RegisterStartupScript(this, this.GetType(), "isActive", "Test();", true);

I have edited the html page which you have provided. The updated page is as below

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head id="Head1" runat="server">
        <title>My Page</title>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script>
        <script type="text/javascript">
            function Test() {
                alert("Hello Test!!!!");
                $('#ButtonRow').css("display", "block");
            }
        </script>
    </head>
    <body>
        <form id="form1" runat="server">
        <table>
            <tr>
                <td>
                    <asp:RadioButtonList ID="SearchCategory" runat="server" RepeatDirection="Horizontal"
                        BorderStyle="Solid">
                        <asp:ListItem>Merchant</asp:ListItem>
                        <asp:ListItem>Store</asp:ListItem>
                        <asp:ListItem>Terminal</asp:ListItem>
                    </asp:RadioButtonList>
                </td>
            </tr>
            <tr id="ButtonRow" style="display: none">
                <td>
                    <asp:Button ID="MyButton" runat="server" Text="Click Here" OnClick="MyButton_Click" />
                </td>
            </tr>
        </table>
        </form>
    </body>
    </html>

    <script type="text/javascript">

        $("#<%=SearchCategory.ClientID%> input").change(function () {
            alert("hi");
            $("#ButtonRow").show();
        });
    </script>

Does Git Add have a verbose switch

You can use git add -i to get an interactive version of git add, although that's not exactly what you're after. The simplest thing to do is, after having git added, use git status to see what is staged or not.

Using git add . isn't really recommended unless it's your first commit. It's usually better to explicitly list the files you want staged, so that you don't start tracking unwanted files accidentally (temp files and such).

How to query DATETIME field using only date in Microsoft SQL Server?

select * from test 
where date between '03/19/2014' and '03/19/2014 23:59:59'

This is a realy bad answer. For two reasons.

1. What happens with times like 23.59.59.700 etc. There are times larger than 23:59:59 and the next day.

2. The behaviour depends on the datatype. The query behaves differently for datetime/date/datetime2 types.

Testing with 23:59:59.999 makes it even worse because depending on the datetype you get different roundings.

select convert (varchar(40),convert(date      , '2014-03-19 23:59:59.999'))
select convert (varchar(40),convert(datetime  , '2014-03-19 23:59:59.999'))
select convert (varchar(40),convert(datetime2 , '2014-03-19 23:59:59.999'))

-- For date the value is 'chopped'. -- For datetime the value is rounded up to the next date. (Nearest value). -- For datetime2 the value is precise.

How to use JUnit to test asynchronous processes

How about calling SomeObject.wait and notifyAll as described here OR using Robotiums Solo.waitForCondition(...) method OR use a class i wrote to do this (see comments and test class for how to use)

Read .mat files in Python

First save the .mat file as:

save('test.mat', '-v7')

After that, in Python, use the usual loadmat function:

import scipy.io as sio
test = sio.loadmat('test.mat')

How to disable a particular checkstyle rule for a particular line of code?

Check out the use of the supressionCommentFilter at http://checkstyle.sourceforge.net/config_filters.html#SuppressionCommentFilter. You'll need to add the module to your checkstyle.xml

<module name="SuppressionCommentFilter"/>

and it's configurable. Thus you can add comments to your code to turn off checkstyle (at various levels) and then back on again through the use of comments in your code. E.g.

//CHECKSTYLE:OFF
public void someMethod(String arg1, String arg2, String arg3, String arg4) {
//CHECKSTYLE:ON

Or even better, use this more tweaked version:

<module name="SuppressionCommentFilter">
    <property name="offCommentFormat" value="CHECKSTYLE.OFF\: ([\w\|]+)"/>
    <property name="onCommentFormat" value="CHECKSTYLE.ON\: ([\w\|]+)"/>
    <property name="checkFormat" value="$1"/>
</module>

which allows you to turn off specific checks for specific lines of code:

//CHECKSTYLE.OFF: IllegalCatch - Much more readable than catching 7 exceptions
catch (Exception e)
//CHECKSTYLE.ON: IllegalCatch

*Note: you'll also have to add the FileContentsHolder:

<module name="FileContentsHolder"/>

See also

<module name="SuppressionFilter">
    <property name="file" value="docs/suppressions.xml"/>
</module>

under the SuppressionFilter section on that same page, which allows you to turn off individual checks for pattern matched resources.

So, if you have in your checkstyle.xml:

<module name="ParameterNumber">
   <property name="id" value="maxParameterNumber"/>
   <property name="max" value="3"/>
   <property name="tokens" value="METHOD_DEF"/>
</module>

You can turn it off in your suppression xml file with:

<suppress id="maxParameterNumber" files="YourCode.java"/>

Another method, now available in Checkstyle 5.7 is to suppress violations via the @SuppressWarnings java annotation. To do this, you will need to add two new modules (SuppressWarningsFilter and SuppressWarningsHolder) in your configuration file:

<module name="Checker">
   ...
   <module name="SuppressWarningsFilter" />
   <module name="TreeWalker">
       ...
       <module name="SuppressWarningsHolder" />
   </module>
</module> 

Then, within your code you can do the following:

@SuppressWarnings("checkstyle:methodlength")
public void someLongMethod() throws Exception {

or, for multiple suppressions:

@SuppressWarnings({"checkstyle:executablestatementcount", "checkstyle:methodlength"})
public void someLongMethod() throws Exception {

NB: The "checkstyle:" prefix is optional (but recommended). According to the docs the parameter name have to be in all lowercase, but practice indicates any case works.

Appending to list in Python dictionary

dates_dict[key] = dates_dict.get(key, []).append(date) sets dates_dict[key] to None as list.append returns None.

In [5]: l = [1,2,3]

In [6]: var = l.append(3)

In [7]: print var
None

You should use collections.defaultdict

import collections
dates_dict = collections.defaultdict(list)

How can I connect to a Tor hidden service using cURL in PHP?

TL;DR: Set CURLOPT_PROXYTYPE to use CURLPROXY_SOCKS5_HOSTNAME if you have a modern PHP, the value 7 otherwise, and/or correct the CURLOPT_PROXY value.

As you correctly deduced, you cannot resolve .onion domains via the normal DNS system, because this is a reserved top-level domain specifically for use by Tor and such domains by design have no IP addresses to map to.

Using CURLPROXY_SOCKS5 will direct the cURL command to send its traffic to the proxy, but will not do the same for domain name resolution. The DNS requests, which are emitted before cURL attempts to establish the actual connection with the Onion site, will still be sent to the system's normal DNS resolver. These DNS requests will surely fail, because the system's normal DNS resolver will not know what to do with a .onion address unless it, too, is specifically forwarding such queries to Tor.

Instead of CURLPROXY_SOCKS5, you must use CURLPROXY_SOCKS5_HOSTNAME. Alternatively, you can also use CURLPROXY_SOCKS4A, but SOCKS5 is much preferred. Either of these proxy types informs cURL to perform both its DNS lookups and its actual data transfer via the proxy. This is required to successfully resolve any .onion domain.

There are also two additional errors in the code in the original question that have yet to be corrected by previous commenters. These are:

  • Missing semicolon at end of line 1.
  • The proxy address value is set to an HTTP URL, but its type is SOCKS; these are incompatible. For SOCKS proxies, the value must be an IP or domain name and port number combination without a scheme/protocol/prefix.

Here is the correct code in full, with comments to indicate the changes.

<?php
$url = 'http://jhiwjjlqpyawmpjx.onion/'; // Note the addition of a semicolon.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_PROXY, "127.0.0.1:9050"); // Note the address here is just `IP:port`, not an HTTP URL.
curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5_HOSTNAME); // Note use of `CURLPROXY_SOCKS5_HOSTNAME`.
$output = curl_exec($ch);
$curl_error = curl_error($ch);
curl_close($ch);

print_r($output);
print_r($curl_error);

You can also omit setting CURLOPT_PROXYTYPE entirely by changing the CURLOPT_PROXY value to include the socks5h:// prefix:

// Note no trailing slash, as this is a SOCKS address, not an HTTP URL.
curl_setopt(CURLOPT_PROXY, 'socks5h://127.0.0.1:9050');

How to get data from database in javascript based on the value passed to the function

Try the following:

<script> 
 //Functions to open database and to create, insert data into tables

 getSelectedRow = function(val)
    {
        db.transaction(function(transaction) {
              transaction.executeSql('SELECT * FROM Employ where number = ?;',[parseInt(val)], selectedRowValues, errorHandler);

        });
    };
    selectedRowValues = function(transaction,results)
    {
         for(var i = 0; i < results.rows.length; i++)
         {
             var row = results.rows.item(i);
             alert(row['number']);
             alert(row['name']);                 
         }
    };
</script>

You don't have access to javascript variable names in SQL, you must pass the values to the Database.

JQuery show/hide when hover

This code also works.

_x000D_
_x000D_
$(".circle").hover(function() {$(this).hide(200).show(200);});
_x000D_
.circle{_x000D_
    width:100px;_x000D_
    height:100px;_x000D_
    border-radius:50px;_x000D_
    font-size:20px;_x000D_
    color:black;_x000D_
    line-height:100px;_x000D_
    text-align:center;_x000D_
    background:yellow_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>_x000D_
<div class="circle">hover me</div>
_x000D_
_x000D_
_x000D_

Unable to connect with remote debugger

Inculding all impressive answers the expert developers specially Ribamar Santos provided, if you didn't get it working, you must check something more tricky!

Something like Airplane mode of your (emulated) phone! Or your network status of Emulator (Data status and Voice status on Cellular tab of Emulator configuration) that might be manipulated to don't express network! for some emulation needs!

I've overcome to this problem by this trick! It was a bit breathtaking debug to find this hole!

Couldn't connect to server 127.0.0.1:27017

After removing mongod.lock which was inside the data directory in my windows OS,it was still showing the same error message. I had to run mongod with --dbpath to make the mongo command run without errors.

Get full URL and query string in Servlet for both HTTP and HTTPS requests

Simply Use:

String Uri = request.getRequestURL()+"?"+request.getQueryString();

Check for column name in a SqlDataReader object

Neither did I get GetSchemaTable to work, until I found this way.

Basically I do this:

Dim myView As DataView = dr.GetSchemaTable().DefaultView
myView.RowFilter = "ColumnName = 'ColumnToBeChecked'"

If myView.Count > 0 AndAlso dr.GetOrdinal("ColumnToBeChecked") <> -1 Then
  obj.ColumnToBeChecked = ColumnFromDb(dr, "ColumnToBeChecked")
End If

Passing arguments to C# generic new() of templated type

I believe you have to constraint T with a where statement to only allow objects with a new constructor.

RIght now it accepts anything including objects without it.

SQL RANK() over PARTITION on joined tables

As the rank doesn't depend at all from the contacts

RANKED_RSLTS

 QRY_ID  |  RES_ID  |  SCORE |  RANK
-------------------------------------
   A     |    1     |    15  |   3
   A     |    2     |    32  |   1
   A     |    3     |    29  |   2
   C     |    7     |    61  |   1
   C     |    9     |    30  |   2

Thus :

SELECT
    C.*
    ,R.SCORE
    ,MYRANK
FROM CONTACTS C LEFT JOIN
(SELECT  *,
 MYRANK = RANK() OVER (PARTITION BY QRY_ID ORDER BY SCORE DESC)
  FROM RSLTS)  R
ON C.RES_ID = R.RES_ID
AND C.QRY_ID = R.QRY_ID

Appending items to a list of lists in python

import csv
cols = [' V1', ' I1'] # define your columns here, check the spaces!
data = [[] for col in cols] # this creates a list of **different** lists, not a list of pointers to the same list like you did in [[]]*len(positions) 
with open('data.csv', 'r') as f:
    for rec in csv.DictReader(f):
        for l, col in zip(data, cols):
            l.append(float(rec[col]))
print data

# [[3.0, 3.0], [0.01, 0.01]]

MySQL - SELECT WHERE field IN (subquery) - Extremely slow why?

sometimes when data grow bigger mysql WHERE IN's could be pretty slow because of query optimization. Try using STRAIGHT_JOIN to tell mysql to execute query as is, e.g.

SELECT STRAIGHT_JOIN table.field FROM table WHERE table.id IN (...)

but beware: in most cases mysql optimizer works pretty well, so I would recommend to use it only when you have this kind of problem

Difference between Visual Basic 6.0 and VBA

Here's a more technical and thorough answer to an old question: Visual Basic for Applications (VBA) and Visual Basic (pre-.NET) are not just similar languages, they are the same language. Specifically:

  • They have the same specification: The implementation-independent description of what the language contains and what it means. You can read it here: [MS-VBAL]: VBA Language Specification
  • They have the same platform: They both compile to Microsoft P-Code, which is in turn executed by the exact same virtual machine, which is implemented in the dll msvbvm[x.0].dll.

In an old VB reference book I came across last year, the author (Paul Lomax) even asserted that 'VBA' has always been the name of the language itself, whether used in stand-alone applications or in embedded contexts (such as MS Office):

"Before we go any further, let's just clarify on fundamental point. Visual Basic for Applications (VBA) is the language used to program in Visual Basic (VB). VB itself is a development environment; the language element of that environment is VBA."

The minor differences

Hosted vs. stand-alone: In practical, terms, when most people say "VBA" they specifically mean "VBA when used in MS Office", and they say "VB6" to mean "VBA used in the last version of the standalone VBA compiler (i.e. Visual Studio 6)". The IDE and compiler bundled with MS Office is almost identical to Visual Studio 6, with the limitation that it does not allow compilation to stand-alone dll or exe files. This in turns means that classes defined in embedded VBA projects are not accessible from non-embedded COM consumers, because they cannot be registered.

Continued development: Microsoft stopped producing a stand-alone VBA compiler with Visual Studio 6, as they switched to the .NET runtime as the platform of choice. However, the MS Office team continues to maintain VBA, and even released a new version (VBA7) with a new VM (now just called VBA7.dll) starting with MS Office 2010. The only major difference is that VBA7 has both a 32- and 64-bit version and has a few enhancements to handle the differences between the two, specifically with regards to external API invocations.

Python unicode equal comparison failed

You may use the == operator to compare unicode objects for equality.

>>> s1 = u'Hello'
>>> s2 = unicode("Hello")
>>> type(s1), type(s2)
(<type 'unicode'>, <type 'unicode'>)
>>> s1==s2
True
>>> 
>>> s3='Hello'.decode('utf-8')
>>> type(s3)
<type 'unicode'>
>>> s1==s3
True
>>> 

But, your error message indicates that you aren't comparing unicode objects. You are probably comparing a unicode object to a str object, like so:

>>> u'Hello' == 'Hello'
True
>>> u'Hello' == '\x81\x01'
__main__:1: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal
False

See how I have attempted to compare a unicode object against a string which does not represent a valid UTF8 encoding.

Your program, I suppose, is comparing unicode objects with str objects, and the contents of a str object is not a valid UTF8 encoding. This seems likely the result of you (the programmer) not knowing which variable holds unicide, which variable holds UTF8 and which variable holds the bytes read in from a file.

I recommend http://nedbatchelder.com/text/unipain.html, especially the advice to create a "Unicode Sandwich."

Can I convert a C# string value to an escaped string literal

EDIT: A more structured approach, including all escape sequences for strings and chars.
Doesn't replace unicode characters with their literal equivalent. Doesn't cook eggs, either.

public class ReplaceString
{
    static readonly IDictionary<string, string> m_replaceDict 
        = new Dictionary<string, string>();

    const string ms_regexEscapes = @"[\a\b\f\n\r\t\v\\""]";

    public static string StringLiteral(string i_string)
    {
        return Regex.Replace(i_string, ms_regexEscapes, match);
    }

    public static string CharLiteral(char c)
    {
        return c == '\'' ? @"'\''" : string.Format("'{0}'", c);
    }

    private static string match(Match m)
    {
        string match = m.ToString();
        if (m_replaceDict.ContainsKey(match))
        {
            return m_replaceDict[match];
        }

        throw new NotSupportedException();
    }

    static ReplaceString()
    {
        m_replaceDict.Add("\a", @"\a");
        m_replaceDict.Add("\b", @"\b");
        m_replaceDict.Add("\f", @"\f");
        m_replaceDict.Add("\n", @"\n");
        m_replaceDict.Add("\r", @"\r");
        m_replaceDict.Add("\t", @"\t");
        m_replaceDict.Add("\v", @"\v");

        m_replaceDict.Add("\\", @"\\");
        m_replaceDict.Add("\0", @"\0");

        //The SO parser gets fooled by the verbatim version 
        //of the string to replace - @"\"""
        //so use the 'regular' version
        m_replaceDict.Add("\"", "\\\""); 
    }

    static void Main(string[] args){

        string s = "here's a \"\n\tstring\" to test";
        Console.WriteLine(ReplaceString.StringLiteral(s));
        Console.WriteLine(ReplaceString.CharLiteral('c'));
        Console.WriteLine(ReplaceString.CharLiteral('\''));

    }
}

How to copy multiple files in one layer using a Dockerfile?

simple

COPY README.md  package.json gulpfile.js __BUILD_NUMBER ./

from the doc

If multiple resources are specified, either directly or due to the use of a wildcard, then must be a directory, and it must end with a slash /.

How can I add a background thread to flask?

First, you should use any WebSocket or polling mechanics to notify the frontend part about changes that happened. I use Flask-SocketIO wrapper, and very happy with async messaging for my tiny apps.

Nest, you can do all logic which you need in a separate thread(s), and notify the frontend via SocketIO object (Flask holds continuous open connection with every frontend client).

As an example, I just implemented page reload on backend file modifications:

<!doctype html>
<script>
    sio = io()

    sio.on('reload',(info)=>{
        console.log(['sio','reload',info])
        document.location.reload()
    })
</script>
class App(Web, Module):

    def __init__(self, V):
        ## flask module instance
        self.flask = flask
        ## wrapped application instance
        self.app = flask.Flask(self.value)
        self.app.config['SECRET_KEY'] = config.SECRET_KEY
        ## `flask-socketio`
        self.sio = SocketIO(self.app)
        self.watchfiles()

    ## inotify reload files after change via `sio(reload)``
    def watchfiles(self):
        from watchdog.observers import Observer
        from watchdog.events import FileSystemEventHandler
        class Handler(FileSystemEventHandler):
            def __init__(self,sio):
                super().__init__()
                self.sio = sio
            def on_modified(self, event):
                print([self.on_modified,self,event])
                self.sio.emit('reload',[event.src_path,event.event_type,event.is_directory])
        self.observer = Observer()
        self.observer.schedule(Handler(self.sio),path='static',recursive=True)
        self.observer.schedule(Handler(self.sio),path='templates',recursive=True)
        self.observer.start()


curl: (35) SSL connect error

curl 7.19.7 (x86_64-redhat-linux-gnu) libcurl/7.19.7 NSS/3.19.1 Basic ECC zlib/1.2.3 libidn/1.18 libssh2/1.4.2

You are using a very old version of curl. My guess is that you run into the bug described 6 years ago. Fix is to update your curl.

Bind class toggle to window scroll event

Thanks to Flek for answering my question in his comment:

http://jsfiddle.net/eTTZj/30/

<div ng-app="myApp" scroll id="page" ng-class="{min:boolChangeClass}">

    <header></header>
    <section></section>

</div>

app = angular.module('myApp', []);
app.directive("scroll", function ($window) {
    return function(scope, element, attrs) {
        angular.element($window).bind("scroll", function() {
             if (this.pageYOffset >= 100) {
                 scope.boolChangeClass = true;
             } else {
                 scope.boolChangeClass = false;
             }
            scope.$apply();
        });
    };
});

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

Just use an absolute path when opening the filehandle for writing.

import os.path

save_path = 'C:/example/'

name_of_file = raw_input("What is the name of the file: ")

completeName = os.path.join(save_path, name_of_file+".txt")         

file1 = open(completeName, "w")

toFile = raw_input("Write what you want into the field")

file1.write(toFile)

file1.close()

You could optionally combine this with os.path.abspath() as described in Bryan's answer to automatically get the path of a user's Documents folder. Cheers!

how to force maven to update local repo

If you are struggling with authenticating to a site, and Maven is caching the results, simply removing the meta-data about the site from the meta-data stash will force Maven to revisit the site.

gvim <local-git-repository>/commons-codec/resolver-status.properties

jQuery detect if textarea is empty

Here is my working code

function emptyTextAreaCheck(textarea, submitButtonClass) {
        if(!submitButtonClass)
            submitButtonClass = ".transSubmit";

            if($(textarea).val() == '') {
                $(submitButtonClass).addClass('disabled_button');
                $(submitButtonClass).removeClass('transSubmit');
            }

        $(textarea).live('focus keydown keyup', function(){
            if($(this).val().length == 0) {
                $(submitButtonClass).addClass('disabled_button');
                $(submitButtonClass).removeClass('transSubmit');
            } else {
                $('.disabled_button').addClass('transSubmit').css({
                    'cursor':'pointer'
                }).removeClass('disabled_button');
            }
        });
    }

Getting Index of an item in an arraylist;

Rather than a brute force loop through the list (eg 1 to 10000), rather use an iterative search approach : The List needs to be sorted by the element to be tested.

Start search at the middle element size()/2 eg 5000 if search item greater than element at 5000, then test the element at the midpoint between the upper(10000) and midpoint(5000) - 7500

keep doing this until you reach the match (or use a brute force loop through once you get down to a smaller range (eg 20 items)

You can search a list of 10000 in around 13 to 14 tests, rather than potentially 9999 tests.

Search for a string in all tables, rows and columns of a DB

/*
This procedure is for finding any string or date in all tables
if search string is date, its format should be yyyy-MM-dd
eg. 2011-07-05
*/

-- ================================================
-- Exec SearchInTables 'f6f56934-a5d4-4967-80a1-1a2223b9c7b1'

-- ================================================
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:      <Joshy,,Name>
-- Create date: <Create Date,,>
-- Description: <Description,,>
-- =============================================
ALTER PROCEDURE SearchInTables
@myValue nvarchar(1000)
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    -- Insert statements for procedure here
        DECLARE @searchsql nvarchar(max)
        DECLARE @table_name nvarchar(1000)
        DECLARE @Schema_name nvarchar(1000)
        DECLARE @ParmDefinition nvarchar(500)
        DECLARE @XMLIn nvarchar(max)
        SET @ParmDefinition = N'@XMLOut varchar(max) OUTPUT'

        SELECT A.name,b.name 
        FROM sys.tables A 
            INNER JOIN sys.schemas B ON A.schema_id=B.schema_id
        WHERE A.name like 'tbl_Tax_Sections' 

        DECLARE tables_cur CURSOR FOR 
                            SELECT A.name,b.name FOM sys.tables A 
                            INNER JOIN sys.schemas B ON A.schema_id=B.schema_id
                            WHERE A.type = 'U'  
        OPEN tables_cur  
        FETCH NEXT FROM tables_cur INTO @table_name , @Schema_name 
            WHILE (@@FETCH_STATUS = 0) 
            BEGIN
                SET @searchsql ='SELECT @XMLOut=(SELECT PATINDEX(''%'+ @myValue+ '%'''
                SET @searchsql =@searchsql  + ', (SELECT * FROM '+@Schema_name+'.'+@table_name+' FOR XML AUTO) ))'
                --print @searchsql 
                EXEC sp_executesql @searchsql, @ParmDefinition, @XMLOut=@XMLIn OUTPUT
                --print @XMLIn 

                IF @XMLIn <> 0 PRINT @Schema_name+'.'+@table_name

                FETCH NEXT FROM tables_cur INTO @table_name , @Schema_name 

            END
        CLOSE tables_cur 
        DEALLOCATE tables_cur 
    RETURN
END
GO

Implicit function declarations in C

Implicit declarations are not valid in C.

C99 removed this feature (present in C89).

gcc chooses to only issue a warning by default with -std=c99 but a compiler has the right to refuse to translate such a program.

SQL Query to fetch data from the last 30 days?

The easiest way would be to specify

SELECT productid FROM product where purchase_date > sysdate-30;

Remember this sysdate above has the time component, so it will be purchase orders newer than 03-06-2011 8:54 AM based on the time now.

If you want to remove the time conponent when comparing..

SELECT productid FROM product where purchase_date > trunc(sysdate-30);

And (based on your comments), if you want to specify a particular date, make sure you use to_date and not rely on the default session parameters.

SELECT productid FROM product where purchase_date > to_date('03/06/2011','mm/dd/yyyy')

And regardng the between (sysdate-30) - (sysdate) comment, for orders you should be ok with usin just the sysdate condition unless you can have orders with order_dates in the future.

Changing the URL in react-router v4 without using Redirect or Link

I'm using this to redirect with React Router v4:

this.props.history.push('/foo');

Hope it work for you ;)

WPF: Grid with column/row margin/padding?

You could write your own GridWithMargin class, inherited from Grid, and override the ArrangeOverride method to apply the margins

How to fix corrupted git repository?

Remove the index and do reset

rm -f .git/index
git reset

filename.whl is not supported wheel on this platform

I had the same problem

I downloaded latest pip from https://pypi.org/project/pip/#files

and then.... pip install << downloaded file location >>

then pygame and kivy installation worked... Thanks...!!

Is there an auto increment in sqlite?

SQLite AUTOINCREMENT is a keyword used for auto incrementing a value of a field in the table. We can auto increment a field value by using AUTOINCREMENT keyword when creating a table with specific column name to auto incrementing it.

The keyword AUTOINCREMENT can be used with INTEGER field only. Syntax:

The basic usage of AUTOINCREMENT keyword is as follows:

CREATE TABLE table_name(
   column1 INTEGER AUTOINCREMENT,
   column2 datatype,
   column3 datatype,
   .....
   columnN datatype,
);

For Example See Below: Consider COMPANY table to be created as follows:

sqlite> CREATE TABLE TB_COMPANY_INFO(
   ID INTEGER PRIMARY KEY   AUTOINCREMENT,
   NAME           TEXT      NOT NULL,
   AGE            INT       NOT NULL,
   ADDRESS        CHAR(50),
   SALARY         REAL
);

Now, insert following records into table TB_COMPANY_INFO:

INSERT INTO TB_COMPANY_INFO (NAME,AGE,ADDRESS,SALARY)
VALUES ( 'MANOJ KUMAR', 40, 'Meerut,UP,INDIA', 200000.00 );

Now Select the record

SELECT *FROM TB_COMPANY_INFO
ID      NAME            AGE     ADDRESS             SALARY
1       Manoj Kumar     40      Meerut,UP,INDIA     200000.00

What's the difference between align-content and align-items?

align-content

align-content controls the cross-axis (i.e. vertical direction if the flex-direction is row, and horizontal if the flex-direction is column) positioning of multiple lines relative to each other.

(Think lines of a paragraph being vertically spread out, stacked toward the top, stacked toward the bottom. This is under a flex-direction row paradigm).

align-items

align-items controls the cross-axis of an individual line of flex elements.

(Think how an individual line of a paragraph is aligned, if it contains some normal text and some taller text like math equations. In that case, will it be the bottom, top, or center of each type of text in a line that will be aligned?)

Why an abstract class implementing an interface can miss the declaration/implementation of one of the interface's methods?

Abstract classes are not required to implement the methods. So even though it implements an interface, the abstract methods of the interface can remain abstract. If you try to implement an interface in a concrete class (i.e. not abstract) and you do not implement the abstract methods the compiler will tell you: Either implement the abstract methods or declare the class as abstract.

How do I change UIView Size?

This can be achieved in various methods in Swift 3.0 Worked on Latest version MAY- 2019

Directly assign the Height & Width values for a view:

userView.frame.size.height = 0

userView.frame.size.width = 10

Assign the CGRect for the Frame

userView.frame =  CGRect(x:0, y: 0, width:0, height:0)

Method Details:

CGRect(x: point of X, y: point of Y, width: Width of View, height: Height of View)

Using an Extension method for CGRECT

Add following extension code in any swift file,

extension CGRect {

    init(_ x:CGFloat, _ y:CGFloat, _ w:CGFloat, _ h:CGFloat) {

        self.init(x:x, y:y, width:w, height:h)
    }
}

Use the following code anywhere in your application for the view to set the size parameters

userView.frame =  CGRect(1, 1, 20, 45)

How to format a duration in java? (e.g format H:MM:SS)

This is a working option.

public static String showDuration(LocalTime otherTime){          
    DateTimeFormatter df = DateTimeFormatter.ISO_LOCAL_TIME;
    LocalTime now = LocalTime.now();
    System.out.println("now: " + now);
    System.out.println("otherTime: " + otherTime);
    System.out.println("otherTime: " + otherTime.format(df));

    Duration span = Duration.between(otherTime, now);
    LocalTime fTime = LocalTime.ofNanoOfDay(span.toNanos());
    String output = fTime.format(df);

    System.out.println(output);
    return output;
}

Call the method with

System.out.println(showDuration(LocalTime.of(9, 30, 0, 0)));

Produces something like:

otherTime: 09:30
otherTime: 09:30:00
11:31:27.463
11:31:27.463

Get the filePath from Filename using Java

Look at the methods in the java.io.File class:

File file = new File("yourfileName");
String path = file.getAbsolutePath();

Remove all whitespace from C# string with regex

Below is the code that would replace the white space from the file name into given URL and also we can remove the same by using string.empty instead of "~"

  if (!string.IsNullOrEmpty(url))
          {
           string origFileName = Path.GetFileName(url);
           string modiFileName = origFileName.Trim().Replace(" ", "~");
           url = url.Replace(origFileName , modiFileName );
          }
          return url;

Predicate in Java

I'm assuming you're talking about com.google.common.base.Predicate<T> from Guava.

From the API:

Determines a true or false value for a given input. For example, a RegexPredicate might implement Predicate<String>, and return true for any string that matches its given regular expression.

This is essentially an OOP abstraction for a boolean test.

For example, you may have a helper method like this:

static boolean isEven(int num) {
   return (num % 2) == 0; // simple
}

Now, given a List<Integer>, you can process only the even numbers like this:

    List<Integer> numbers = Arrays.asList(1,2,3,4,5,6,7,8,9,10);
    for (int number : numbers) {
        if (isEven(number)) {
            process(number);
        }
    }

With Predicate, the if test is abstracted out as a type. This allows it to interoperate with the rest of the API, such as Iterables, which have many utility methods that takes Predicate.

Thus, you can now write something like this:

    Predicate<Integer> isEven = new Predicate<Integer>() {
        @Override public boolean apply(Integer number) {
            return (number % 2) == 0;
        }               
    };
    Iterable<Integer> evenNumbers = Iterables.filter(numbers, isEven);

    for (int number : evenNumbers) {
        process(number);
    }

Note that now the for-each loop is much simpler without the if test. We've reached a higher level of abtraction by defining Iterable<Integer> evenNumbers, by filter-ing using a Predicate.

API links


On higher-order function

Predicate allows Iterables.filter to serve as what is called a higher-order function. On its own, this offers many advantages. Take the List<Integer> numbers example above. Suppose we want to test if all numbers are positive. We can write something like this:

static boolean isAllPositive(Iterable<Integer> numbers) {
    for (Integer number : numbers) {
        if (number < 0) {
            return false;
        }
    }
    return true;
}

//...
if (isAllPositive(numbers)) {
    System.out.println("Yep!");
}

With a Predicate, and interoperating with the rest of the libraries, we can instead write this:

Predicate<Integer> isPositive = new Predicate<Integer>() {
    @Override public boolean apply(Integer number) {
        return number > 0;
    }       
};

//...
if (Iterables.all(numbers, isPositive)) {
    System.out.println("Yep!");
}

Hopefully you can now see the value in higher abstractions for routines like "filter all elements by the given predicate", "check if all elements satisfy the given predicate", etc make for better code.

Unfortunately Java doesn't have first-class methods: you can't pass methods around to Iterables.filter and Iterables.all. You can, of course, pass around objects in Java. Thus, the Predicate type is defined, and you pass objects implementing this interface instead.

See also

How do I count the number of occurrences of a char in a String?

Not sure about the efficiency of this, but it's the shortest code I could write without bringing in 3rd party libs:

public static int numberOf(String target, String content)
{
    return (content.split(target).length - 1);
}

Programmatically get the version number of a DLL

Assembly assembly = Assembly.LoadFrom("MyAssembly.dll");
Version ver = assembly.GetName().Version;

Important: It should be noted that this is not the best answer to the original question. Don't forget to read more on this page.

PostgreSQL: Why psql can't connect to server?

Just want to make a small addition: if your instance is complaining on a socket, you can also check unix_socket_directories at /data/postgresql.conf file which could have been set to /tmp, for example, if you have used a 3rd party distribution. You can change it to /var/run/postgresql and restart the service. That may also require creating a postgresql dir at /var/run and subsys/postgresql-9.6 at /var/lock if those doesn't already exist (worked for me with postgresql 9.6).

How to reset a timer in C#?

You could write an extension method called Reset(), which

  • calls Stop()-Start() for Timers.Timer and Forms.Timer
  • calls Change for Threading.Timer

DISABLE the Horizontal Scroll

Try adding this to your CSS

html, body {
    max-width: 100%;
    overflow-x: hidden;
}

Hibernate: How to set NULL query-parameter value with HQL?

You can use

Restrictions.eqOrIsNull("status", status)

insted of

status == null ? Restrictions.isNull("status") : Restrictions.eq("status", status)

What should be the package name of android app?

Android follows the same naming conventions like Java,

Naming Conventions

Package names are written in all lower case to avoid conflict with the names of classes or interfaces.

Companies use their reversed Internet domain name to begin their package names—for example, com.example.mypackage for a package named mypackage created by a programmer at example.com.

Name collisions that occur within a single company need to be handled by convention within that company, perhaps by including the region or the project name after the company name (for example, com.example.region.mypackage).

Packages in the Java language itself begin with java. or javax.

In some cases, the internet domain name may not be a valid package name. This can occur if the domain name contains a hyphen or other special character, if the package name begins with a digit or other character that is illegal to use as the beginning of a Java name, or if the package name contains a reserved Java keyword, such as "int". In this event, the suggested convention is to add an underscore. For example:

Legalizing Package Names:

       Domain Name                            Package Name Prefix

hyphenated-name.example.org             org.example.hyphenated_name
example.int                             int_.example
123name.example.com                     com.example._123name

How to access Winform textbox control from another class?

I used this method for updating a label but you could easily change it to a textbox:

Class:

public Class1
{
    public Form_Class formToOutput;

    public Class1(Form_Class f){
        formToOutput = f;
    }

    // Then call this method and pass whatever string
    private void Write(string s)
    {
        formToOutput.MethodToBeCalledByClass(s);
    }
}

Form methods that will do the updating:

public Form_Class{

    // Methods that will do the updating
    public void MethodToBeCalledByClass(string messageToSend)
    {
       if (InvokeRequired) { 
           Invoke(new OutputDelegate(UpdateText),messageToSend); 
       }
    }

    public delegate void OutputDelegate(string messageToSend);
    public void UpdateText(string messageToSend)
    {
       label1.Text = messageToSend;
    }
}

Finally

Just pass the form through the constructor:

Class1 c = new Class1(this);

Difference between Arrays.asList(array) and new ArrayList<Integer>(Arrays.asList(array))

1.List<Integer> list1 = new ArrayList<Integer>(Arrays.asList(ia));  //copy
2.List<Integer> list2 = Arrays.asList(ia);

In line 2, Arrays.asList(ia) returns a List reference of inner class object defined within Arrays, which is also called ArrayList but is private and only extends AbstractList. This means what returned from Arrays.asList(ia) is a class object different from what you get from new ArrayList<Integer>.

You cannot use some operations to line 2 because the inner private class within Arrays does not provide those methods.

Take a look at this link and see what you can do with the private inner class: http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/Arrays.java#Arrays.ArrayList

Line 1 creates a new ArrayList object copying elements from what you get from line 2. So you can do whatever you want since java.util.ArrayList provides all those methods.

.NET Events - What are object sender & EventArgs e?

Manually cast the sender to the type of your custom control, and then use it to delete or disable etc. Eg, something like this:

private void myCustomControl_Click(object sender, EventArgs e)
{
  ((MyCustomControl)sender).DoWhatever();
}

The 'sender' is just the object that was actioned (eg clicked).

The event args is subclassed for more complex controls, eg a treeview, so that you can know more details about the event, eg exactly where they clicked.

How are ssl certificates verified?

The client has a pre-seeded store of SSL certificate authorities' public keys. There must be a chain of trust from the certificate for the server up through intermediate authorities up to one of the so-called "root" certificates in order for the server to be trusted.

You can examine and/or alter the list of trusted authorities. Often you do this to add a certificate for a local authority that you know you trust - like the company you work for or the school you attend or what not.

The pre-seeded list can vary depending on which client you use. The big SSL certificate vendors insure that their root certs are in all the major browsers ($$$).

Monkey-in-the-middle attacks are "impossible" unless the attacker has the private key of a trusted root certificate. Since the corresponding certificates are widely deployed, the exposure of such a private key would have serious implications for the security of eCommerce generally. Because of that, those private keys are very, very closely guarded.

FB OpenGraph og:image not pulling images (possibly https?)

Got here from Google but this wasn't much help for me. It turned out that there is a minimum aspect ratio of 3:1 required for the logo. Mine was almost 4:1. I used Gimp to crop it to exactly 3:1 and voila - my logo is now shown on FB.

Unique constraint violation during insert: why? (Oracle)

It looks like you are not providing a value for the primary key field DB_ID. If that is a primary key, you must provide a unique value for that column. The only way not to provide it would be to create a database trigger that, on insert, would provide a value, most likely derived from a sequence.

If this is a restoration from another database and there is a sequence on this new instance, it might be trying to reuse a value. If the old data had unique keys from 1 - 1000 and your current sequence is at 500, it would be generating values that already exist. If a sequence does exist for this table and it is trying to use it, you would need to reconcile the values in your table with the current value of the sequence.

You can use SEQUENCE_NAME.CURRVAL to see the current value of the sequence (if it exists of course)

javax.faces.application.ViewExpiredException: View could not be restored

I was getting this error : javax.faces.application.ViewExpiredException.When I using different requests, I found those having same JsessionId, even after restarting the server. So this is due to the browser cache. Just close the browser and try, it will work.

How to get IntPtr from byte[] in C#

This should work but must be used within an unsafe context:

byte[] buffer = new byte[255];
fixed (byte* p = buffer)
{
    IntPtr ptr = (IntPtr)p;
    // do you stuff here
}

beware, you have to use the pointer in the fixed block! The gc can move the object once you are not anymore in the fixed block.

How do you represent a JSON array of strings?

Your JSON object in this case is a list. JSON is almost always an object with attributes; a set of one or more key:value pairs, so you most likely see a dictionary:

{ "MyStringArray" : ["somestring1", "somestring2"] }

then you can ask for the value of "MyStringArray" and you would get back a list of two strings, "somestring1" and "somestring2".

Zoom to fit all markers in Mapbox or Leaflet

You also can locate all features inside a FeatureGroup or all the featureGroups, see how it works!

_x000D_
_x000D_
//Group1_x000D_
m1=L.marker([7.11, -70.11]);_x000D_
m2=L.marker([7.33, -70.33]);_x000D_
m3=L.marker([7.55, -70.55]);_x000D_
fg1=L.featureGroup([m1,m2,m3]);_x000D_
_x000D_
//Group2_x000D_
m4=L.marker([3.11, -75.11]);_x000D_
m5=L.marker([3.33, -75.33]);_x000D_
m6=L.marker([3.55, -75.55]);_x000D_
fg2=L.featureGroup([m4,m5,m6]);_x000D_
_x000D_
//BaseMap_x000D_
baseLayer = L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png');_x000D_
var map = L.map('map', {_x000D_
  center: [3, -70],_x000D_
  zoom: 4,_x000D_
  layers: [baseLayer, fg1, fg2]_x000D_
});_x000D_
_x000D_
//locate group 1_x000D_
function LocateOne() {_x000D_
    LocateAllFeatures(map, fg1);_x000D_
}_x000D_
_x000D_
function LocateAll() {_x000D_
    LocateAllFeatures(map, [fg1,fg2]);_x000D_
}_x000D_
_x000D_
//Locate the features_x000D_
function LocateAllFeatures(iobMap, iobFeatureGroup) {_x000D_
  if(Array.isArray(iobFeatureGroup)){   _x000D_
   var obBounds = L.latLngBounds();_x000D_
   for (var i = 0; i < iobFeatureGroup.length; i++) {_x000D_
    obBounds.extend(iobFeatureGroup[i].getBounds());_x000D_
   }_x000D_
   iobMap.fitBounds(obBounds);   _x000D_
  } else {_x000D_
   iobMap.fitBounds(iobFeatureGroup.getBounds());_x000D_
  }_x000D_
}
_x000D_
.mymap{_x000D_
  height: 300px;_x000D_
  width: 100%;_x000D_
}
_x000D_
<script src="https://unpkg.com/[email protected]/dist/leaflet.js"></script>_x000D_
<link href="https://unpkg.com/[email protected]/dist/leaflet.css" rel="stylesheet"/>_x000D_
_x000D_
<div id="map" class="mymap"></div>_x000D_
<button onclick="LocateOne()">locate group 1</button>_x000D_
<button onclick="LocateAll()">locate All</button>
_x000D_
_x000D_
_x000D_

Simple excel find and replace for formulas

If the formulas are identical you can use Find and Replace with Match entire cell contents checked and Look in: Formulas. Select the range, go into Find and Replace, make your entries and `Replace All.

enter image description here

Or do you mean that there are several formulas with this same form, but different cell references? If so, then one way to go is a regular expression match and replace. Regular expressions are not built into Excel (or VBA), but can be accessed via Microsoft's VBScript Regular Expressions library.

The following function provides the necessary match and replace capability. It can be used in a subroutine that would identify cells with formulas in the specified range and use the formulas as inputs to the function. For formulas strings that match the pattern you are looking for, the function will produce the replacement formula, which could then be written back to the worksheet.

Function RegexFormulaReplace(formula As String)
    Dim regex As New RegExp
    regex.Pattern = "=\(\(([A-Z]+\d+)-([A-Z]+\d+)\)/([A-Z]+\d+)\)"
'   Test if a match is found
    If regex.Test(formula) = True Then
        RegexFormulaReplace = regex.Replace(formula, "=(EXP((LN($1/$2)/14.32))-1")
    Else
        RegexFormulaReplace = CVErr(xlErrValue)
    End If
    Set regex = Nothing
End Function

In order for the function to work, you would need to add a reference to the Microsoft VBScript Regular Expressions 5.5 library. From the Developer tab of the main ribbon, select VBA and then References from the main toolbar. Scroll down to find the reference to the library and check the box next to it.

How to use python numpy.savetxt to write strings and float number to an ASCII file?

You have to specify the format (fmt) of you data in savetxt, in this case as a string (%s):

num.savetxt('test.txt', DAT, delimiter=" ", fmt="%s") 

The default format is a float, that is the reason it was expecting a float instead of a string and explains the error message.

Foreach value from POST from form

First, please do not use extract(), it can be a security problem because it is easy to manipulate POST parameters

In addition, you don't have to use variable variable names (that sounds odd), instead:

foreach($_POST as $key => $value) {
  echo "POST parameter '$key' has '$value'";
}

To ensure that you have only parameters beginning with 'item_name' you can check it like so:

$param_name = 'item_name';
if(substr($key, 0, strlen($param_name)) == $param_name) {
  // do something
}

Possible heap pollution via varargs parameter

Heap pollution is a technical term. It refers to references which have a type that is not a supertype of the object they point to.

List<A> listOfAs = new ArrayList<>();
List<B> listOfBs = (List<B>)(Object)listOfAs; // points to a list of As

This can lead to "unexplainable" ClassCastExceptions.

// if the heap never gets polluted, this should never throw a CCE
B b = listOfBs.get(0); 

@SafeVarargs does not prevent this at all. However, there are methods which provably will not pollute the heap, the compiler just can't prove it. Previously, callers of such APIs would get annoying warnings that were completely pointless but had to be suppressed at every call site. Now the API author can suppress it once at the declaration site.

However, if the method actually is not safe, users will no longer be warned.

Detecting an "invalid date" Date instance in JavaScript

I use the following code to validate values for year, month and date.

function createDate(year, month, _date) {
  var d = new Date(year, month, _date);
  if (d.getFullYear() != year 
    || d.getMonth() != month
    || d.getDate() != _date) {
    throw "invalid date";
  }
  return d;
}

For details, refer to Check date in javascript

Simple function to sort an array of objects

This isn't a JSON question, per se. Its a javascript array question.

Try this:

people.sort(function(a,b){ 
    var x = a.name < b.name? -1:1; 
    return x; 
});

process.env.NODE_ENV is undefined

in package.json we have to config like below (works in Linux and Mac OS)

the important thing is "export NODE_ENV=production" after your build commands below is an example:

  "scripts": {
     "start": "export NODE_ENV=production && npm run build && npm run start-server",
     "dev": "export NODE_ENV=dev && npm run build && npm run start-server",
  } 
  • for dev environment, we have to hit "npm run dev" command

  • for a production environment, we have to hit "npm run start" command

Rails: Adding an index after adding column

If you need to create a user_id then it would be a reasonable assumption that you are referencing a user table. In which case the migration shall be:

rails generate migration AddUserRefToProducts user:references

This command will generate the following migration:

class AddUserRefToProducts < ActiveRecord::Migration
  def change
    add_reference :user, :product, index: true
  end
end

After running rake db:migrate both a user_id column and an index will be added to the products table.

In case you just need to add an index to an existing column, e.g. name of a user table, the following technique may be helpful:

rails generate migration AddIndexToUsers name:string:index will generate the following migration:

class AddIndexToUsers < ActiveRecord::Migration
  def change
    add_column :users, :name, :string
    add_index :users, :name
  end
end

Delete add_column line and run the migration.

In the case described you could have issued rails generate migration AddIndexIdToTable index_id:integer:index command and then delete add_column line from the generated migration. But I'd rather recommended to undo the initial migration and add reference instead:

rails generate migration RemoveUserIdFromProducts user_id:integer
rails generate migration AddUserRefToProducts user:references

Spring MVC - How to return simple String as JSON in Rest Controller

Simply unregister the default StringHttpMessageConverter instance:

@Configuration
public class WebMvcConfiguration extends WebMvcConfigurationSupport {
  /**
   * Unregister the default {@link StringHttpMessageConverter} as we want Strings
   * to be handled by the JSON converter.
   *
   * @param converters List of already configured converters
   * @see WebMvcConfigurationSupport#addDefaultHttpMessageConverters(List)
   */
  @Override
  protected void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
    converters.stream()
      .filter(c -> c instanceof StringHttpMessageConverter)
      .findFirst().ifPresent(converters::remove);
  }
}

Tested with both controller action handler methods and controller exception handlers:

@RequestMapping("/foo")
public String produceFoo() {
  return "foo";
}

@ExceptionHandler(FooApiException.class)
public String fooException(HttpServletRequest request, Throwable e) {
  return e.getMessage();
}

Final notes:

  • extendMessageConverters is available since Spring 4.1.3, if are running on a previous version you can implement the same technique using configureMessageConverters, it just takes a little bit more work.
  • This was one approach of many other possible approaches, if your application only ever returns JSON and no other content types, you are better off skipping the default converters and adding a single jackson converter. Another approach is to add the default converters but in different order so that the jackson converter is prior to the string one. This should allow controller action methods to dictate how they want String to be converted depending on the media type of the response.

How To Inject AuthenticationManager using Java Configuration in a Custom Filter

Override method authenticationManagerBean in WebSecurityConfigurerAdapter to expose the AuthenticationManager built using configure(AuthenticationManagerBuilder) as a Spring bean:

For example:

   @Bean(name = BeanIds.AUTHENTICATION_MANAGER)
   @Override
   public AuthenticationManager authenticationManagerBean() throws Exception {
       return super.authenticationManagerBean();
   }

Failed to load ApplicationContext for JUnit test of Spring controller

As mentioned in duscusion: WEB-INF is not really a part of class path. If you use a common template such as maven, use src/main/resources or src/test/resources to place the app-context.xml into. Then you can use 'classpath:'.

Place your config file into src/main/resources/app-context.xml and use code

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:app-context.xml")
public class PersonControllerTest {
...
}

or you can make yout test context with different configuration of beans.

Place your config file into src/test/resources/test-app-context.xml and use code

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:test-app-context.xml")
public class PersonControllerTest {
...
}

Codeigniter's `where` and `or_where`

You can use : Query grouping allows you to create groups of WHERE clauses by enclosing them in parentheses. This will allow you to create queries with complex WHERE clauses. Nested groups are supported. Example:

$this->db->select('*')->from('my_table')
        ->group_start()
                ->where('a', 'a')
                ->or_group_start()
                        ->where('b', 'b')
                        ->where('c', 'c')
                ->group_end()
        ->group_end()
        ->where('d', 'd')
->get();

https://www.codeigniter.com/userguide3/database/query_builder.html#query-grouping

When to use RDLC over RDL reports?

If you have a reporting services infrastructure available to you, use it. You will find RDL development to be a bit more pleasant. You can preview the report, easily setup parameters, etc.

Cannot read property 'addEventListener' of null

I faced a similar situation. This is probably because the script is executed before the page loads. By placing the script at the bottom of the page, I circumvented the problem.

Git: Could not resolve host github.com error while cloning remote repository in git

Would like to note, when I did Brian's solution:

git config --global --unset http.proxy

make sure to quit and restart terminal. Mine didn't resolve until I did that.

Thanks so much, issue was killing me!

Serialize and Deserialize Json and Json Array in Unity

Assume you got a JSON like this

[
    {
        "type": "qrcode",
        "symbol": [
            {
                "seq": 0,
                "data": "HelloWorld9887725216",
                "error": null
            }
        ]
    }
]

To parse the above JSON in unity, you can create JSON model like this.

[System.Serializable]
public class QrCodeResult
{
    public QRCodeData[] result;
}

[System.Serializable]
public class Symbol
{
    public int seq;
    public string data;
    public string error;
}

[System.Serializable]
public class QRCodeData
{
    public string type;
    public Symbol[] symbol;
}

And then simply parse in the following manner...

var myObject = JsonUtility.FromJson<QrCodeResult>("{\"result\":" + jsonString.ToString() + "}");

Now you can modify the JSON/CODE according to your need. https://docs.unity3d.com/Manual/JSONSerialization.html

How can I divide two integers to get a double?

I have went through most of the answers and im pretty sure that it's unachievable. Whatever you try to divide two int into double or float is not gonna happen. But you have tons of methods to make the calculation happen, just cast them into float or double before the calculation will be fine.

A Simple AJAX with JSP example

loadXMLDoc JS function should return false, otherwise it will result in postback.

Javascript split regex question

Say your string is:

let str = `word1
word2;word3,word4,word5;word7
word8,word9;word10`;

You want to split the string by the following delimiters:

  • Colon
  • Semicolon
  • New line

You could split the string like this:

let rawElements = str.split(new RegExp('[,;\n]', 'g'));

Finally, you may need to trim the elements in the array:

let elements = rawElements.map(element => element.trim());

Sorting a Dictionary in place with respect to keys

By design, dictionaries are not sortable. If you need this capability in a dictionary, look at SortedDictionary instead.

reading and parsing a TSV file, then manipulating it for saving as CSV (*efficiently*)

You should use the csv module to read the tab-separated value file. Do not read it into memory in one go. Each row you read has all the information you need to write rows to the output CSV file, after all. Keep the output file open throughout.

import csv

with open('sample.txt', newline='') as tsvin, open('new.csv', 'w', newline='') as csvout:
    tsvin = csv.reader(tsvin, delimiter='\t')
    csvout = csv.writer(csvout)

    for row in tsvin:
        count = int(row[4])
        if count > 0:
            csvout.writerows([row[2:4] for _ in range(count)])

or, using the itertools module to do the repeating with itertools.repeat():

from itertools import repeat
import csv

with open('sample.txt', newline='') as tsvin, open('new.csv', 'w', newline='') as csvout:
    tsvin = csv.reader(tsvin, delimiter='\t')
    csvout = csv.writer(csvout)

    for row in tsvin:
        count = int(row[4])
        if count > 0:
            csvout.writerows(repeat(row[2:4], count))

CSS submit button weird rendering on iPad/iPhone

The above answer for webkit appearance worked, but the button still looked kind pale/dull compared to the browser on other devices/desktop. I also had to set opacity to full (ranges from 0 to 1)

-webkit-appearance:none;
opacity: 1

After setting the opacity, the button looked the same on all the different devices/emulator/desktop.

How to pass credentials to httpwebrequest for accessing SharePoint Library

You could also use:

request.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials; 

Laravel 5: Retrieve JSON array from $request

Just a mention with jQuery v3.2.1 and Laravel 5.6.

Case 1: The JS object posted directly, like:

$.post("url", {name:'John'}, function( data ) {
});

Corresponding Laravel PHP code should be:

parse_str($request->getContent(),$data); //JSON will be parsed to object $data

Case 2: The JSON string posted, like:

$.post("url", JSON.stringify({name:'John'}), function( data ) {
});

Corresponding Laravel PHP code should be:

$data = json_decode($request->getContent(), true);

How to set app icon for Electron / Atom Shell App

electron-packager


Setting the icon property when creating the BrowserWindow only has an effect on Windows and Linux platforms. you have to package the .icns for max

To set the icon on OS X using electron-packager, set the icon using the --icon switch.

It will need to be in .icns format for OS X. There is an online icon converter which can create this file from your .png.

electron-builder


As a most recent solution, I found an alternative of using --icon switch. Here is what you can do.

  1. Create a directory named build in your project directory and put the .icns the icon in the directory as named icon.icns.
  2. run builder by executing command electron-builder --dir.

You will find your application icon will be automatically picked up from that directory location and used for an application while packaging.

Note: The given answer is for recent version of electron-builder and tested with electron-builder v21.2.0

Setting CSS pseudo-class rules from JavaScript

A function to cope with the cross-browser stuff:

addCssRule = function(/* string */ selector, /* string */ rule) {
  if (document.styleSheets) {
    if (!document.styleSheets.length) {
      var head = document.getElementsByTagName('head')[0];
      head.appendChild(bc.createEl('style'));
    }

    var i = document.styleSheets.length-1;
    var ss = document.styleSheets[i];

    var l=0;
    if (ss.cssRules) {
      l = ss.cssRules.length;
    } else if (ss.rules) {
      // IE
      l = ss.rules.length;
    }

    if (ss.insertRule) {
      ss.insertRule(selector + ' {' + rule + '}', l);
    } else if (ss.addRule) {
      // IE
      ss.addRule(selector, rule, l);
    }
  }
};

How to connect to a MySQL Data Source in Visual Studio

After a lot of searching and trying many solutions, I got it finally:

  1. uninstall connector

  2. uninstall MySQL for Visual Studio from control panel

    click here

  3. reinstall them according to the table below

    click here

  4. copy the assembly files from C:\Program Files (x86)\MySQL\MySQL Connector Net 6.9.8\Assemblies\v4.5 to C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE

  5. log off and reopen your solution

  6. enjoy

ArrayList - How to modify a member of an object?

You can just do a get on the collection then just modify the attributes of the customer you just did a 'get' on. There is no need to modify the collection nor is there a need to create a new customer:

int currentCustomer = 3;

// get the customer at 3
Customer c = list.get(currentCustomer);
// change his email
c.setEmail("[email protected]");

Get month and year from date cells Excel

Please try something like:

=IF(LEN(C1)>10,VALUE(LEFT(C1,FIND(" ",C1,8))),IF(ISTEXT(C1),DATE(RIGHT(C1,4),MID(C1,4,2),LEFT(C1,2)),C1))  

You seem to have three main possible scenarios:

  1. Space-separated date with time as text (eg as A1 below)
  2. Hyphen-separated date as text (eg as A2 below)
  3. Formatted date index (as A4 and A5 below)

ColumnA below is formatted General and ColumnB as Date (my default setting). ColumnC also as date but with custom formatting to suit the appearances mentioned in your question.
A clue as to whether or not text format is the left or right alignment of the cells’ contents.

I am suggesting separate treatment for each of the above three main cases, so use =IF to differentiate them.

Case #1

This is longer than any of the others, so can be distinguished as having a length greater than say 10 characters, with =LEN.
In this case we want all but the last six characters but for added flexibility (for instance, in case the time element included seconds) I have chosen to count from the left rather than from the right. The problem then is that the month names may vary in length, so I have chosen to look for the space that immediately follows the year to indicate the limit for the relevant number of characters.

This with =FIND which looks for a space (" ") in C1, starting with the eighth character within C1 counting from the left, on the assumption that for this case days will be expressed as two characters and months as three or more.

Since =LEFT is a string function it returns a string, but this can be converted to a value with=VALUE.

So

=VALUE(LEFT(C1,FIND(" ",C1,8))) 

returns 40671 in this example – in Excel’s 1900 date system the date serial number for May 5, 2011.

Case #2

If the length of C1 is not greater than 10 characters, we still need to distinguish between a text entry or a value entry which I have chosen to do with =ISTEXT and, where the if condition is TRUE (as for C2) apply =DATE which takes three parameters, here provided by:

=RIGHT(C2,4)  

Takes the last four characters of C2, hence 2011 in this example.

=MID(C2,4,2) 

Starting at the fourth character, takes the next two characters of C2, hence 05 in this example (representing May).

=LEFT(C2,2))  

Takes the first two characters of C2, hence 08 in this example (representing the 8th day of the month). Date is not a text function so does not need to be wrapped in =VALUE.

Taken together

=DATE(RIGHT(C2,4),MID(C2,4,2),LEFT(C2,2)) 

also returns 40671 in this example, but from different input from Case #1.

Case #3

Is simple because already a date serial number, so just

=C2  

is sufficient.


Put the above together to cover all three cases in a single formula:

=IF(LEN(C1)>10,VALUE(LEFT(C1,FIND(" ",C1,8))),IF(ISTEXT(C1),DATE(RIGHT(C1,4),MID(C1,4,2),LEFT(C1,2)),C1))  

as applied in ColumnF (formatted to suit OP) or in General format (to show values are integers) in ColumnH:

SO23928568 example

Setting Inheritance and Propagation flags with set-acl and powershell

Just because you're in PowerShell don't forgot about good ol' exes. Sometimes they can provide the easiest solution e.g.:

icacls.exe $folder /grant 'domain\user:(OI)(CI)(M)'

AngularJS accessing DOM elements inside directive template

This answer comes a little bit late, but I just was in a similar need.

Observing the comments written by @ganaraj in the question, One use case I was in the need of is, passing a classname via a directive attribute to be added to a ng-repeat li tag in the template.

For example, use the directive like this:

<my-directive class2add="special-class" />

And get the following html:

<div>
    <ul>
       <li class="special-class">Item 1</li>
       <li class="special-class">Item 2</li>
    </ul>
</div>

The solution found here applied with templateUrl, would be:

app.directive("myDirective", function() {
    return {
        template: function(element, attrs){
            return '<div><ul><li ng-repeat="item in items" class="'+attrs.class2add+'"></ul></div>';
        },
        link: function(scope, element, attrs) {
            var list = element.find("ul");
        }
    }
});

Just tried it successfully with AngularJS 1.4.9.

Hope it helps.

How to center and crop an image to always appear in square shape with CSS?

clip property with position may help you

a{
position:absolute;
clip:rect(0px,200px,200px,0px);
}

a img{
position:relative;
left:-50%;
top:-50%;
 }

WORKING FIDDLE

string.IsNullOrEmpty(string) vs. string.IsNullOrWhiteSpace(string)

Here is the actual implementation of both methods ( decompiled using dotPeek)

[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
    public static bool IsNullOrEmpty(string value)
    {
      if (value != null)
        return value.Length == 0;
      else
        return true;
    }

    /// <summary>
    /// Indicates whether a specified string is null, empty, or consists only of white-space characters.
    /// </summary>
    /// 
    /// <returns>
    /// true if the <paramref name="value"/> parameter is null or <see cref="F:System.String.Empty"/>, or if <paramref name="value"/> consists exclusively of white-space characters.
    /// </returns>
    /// <param name="value">The string to test.</param>
    public static bool IsNullOrWhiteSpace(string value)
    {
      if (value == null)
        return true;
      for (int index = 0; index < value.Length; ++index)
      {
        if (!char.IsWhiteSpace(value[index]))
          return false;
      }
      return true;
    }

Remove a symlink to a directory

Assuming it actually is a symlink,

$ rm -d symlink

It should figure it out, but since it can't we enable the latent code that was intended for another case that no longer exists but happens to do the right thing here.

How to remove ASP.Net MVC Default HTTP Headers?

You can change any header or anything in Application_EndRequest() try this

protected void Application_EndRequest()
{
    // removing excessive headers. They don't need to see this.
    Response.Headers.Remove("header_name");
}

Is it possible to have placeholders in strings.xml for runtime values?

When you want to use a parameter from the actual strings.xml file without using any Java code:

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE resources [
  <!ENTITY appname "WhereDat">
  <!ENTITY author "Oded">
]>

<resources>
    <string name="app_name">&appname;</string>
    <string name="description">The &appname; app was created by &author;</string>
</resources>

This does not work across resource files, i.e. variables must be copied into each XML file that needs them.

How to keep the console window open in Visual C++?

cin.get(), or system("PAUSE"). I haven't heard you can use return(0);

How to make the division of 2 ints produce a float instead of another int?

Try this:

class CalcV 
{
      float v;
      float calcV(int s, int t)
      {
          float value1=s;
          float value2=t;
          v = value1 / value2;
          return v;
      } //end calcV
}