Programs & Examples On #Graphical language

0

Javascript to set hidden form value on drop down change

If you have HTML like this, for example:

<select id='myselect'>
    <option value='1'>A</option>
    <option value='2'>B</option>
    <option value='3'>C</option>
    <option value='4'>D</option>
</select>
<input type='hidden' id='myhidden' value=''>

All you have to do is bind a function to the change event of the select, and do what you need there:

<script type='text/javascript'>
$(function() {
    $('#myselect').change(function() {
        // if changed to, for example, the last option, then
        // $(this).find('option:selected').text() == D
        // $(this).val() == 4
        // get whatever value you want into a variable
        var x = $(this).val();
        // and update the hidden input's value
        $('#myhidden').val(x);
    });
});
</script>

All things considered, if you're going to be doing a lot of jQuery programming, always have the documentation open. It is very easy to find what you need there if you give it a chance.

VB.NET - Remove a characters from a String

Function RemoveCharacter(ByVal stringToCleanUp, ByVal characterToRemove)
  ' replace the target with nothing
  ' Replace() returns a new String and does not modify the current one
  Return stringToCleanUp.Replace(characterToRemove, "")
End Function

Here's more information about VB's Replace function

Is there a C# String.Format() equivalent in JavaScript?

I am using:

String.prototype.format = function() {
    var s = this,
        i = arguments.length;

    while (i--) {
        s = s.replace(new RegExp('\\{' + i + '\\}', 'gm'), arguments[i]);
    }
    return s;
};

usage: "Hello {0}".format("World");

I found it at Equivalent of String.format in JQuery

UPDATED:

In ES6/ES2015 you can use string templating for instance

'use strict';

let firstName = 'John',
    lastName = 'Smith';

console.log(`Full Name is ${firstName} ${lastName}`); 
// or
console.log(`Full Name is ${firstName + ' ' + lastName}');

javascript: using a condition in switch case

switch (true) {
  case condition0:
    ...
    break;
  case condition1:
    ...
    break;
}

will work in JavaScript as long as your conditions return proper boolean values, but it doesn't have many advantages over else if statements.

Using setImageDrawable dynamically to set image in an ImageView

Try this,

int id = getResources().getIdentifier("yourpackagename:drawable/" + StringGenerated, null, null);

This will return the id of the drawable you want to access... then you can set the image in the imageview by doing the following

imageview.setImageResource(id);

ExecuteReader requires an open and available Connection. The connection's current state is Connecting

Sorry for only commenting in the first place, but i'm posting almost every day a similar comment since many people think that it would be smart to encapsulate ADO.NET functionality into a DB-Class(me too 10 years ago). Mostly they decide to use static/shared objects since it seems to be faster than to create a new object for any action.

That is neither a good idea in terms of peformance nor in terms of fail-safety.

Don't poach on the Connection-Pool's territory

There's a good reason why ADO.NET internally manages the underlying Connections to the DBMS in the ADO-NET Connection-Pool:

In practice, most applications use only one or a few different configurations for connections. This means that during application execution, many identical connections will be repeatedly opened and closed. To minimize the cost of opening connections, ADO.NET uses an optimization technique called connection pooling.

Connection pooling reduces the number of times that new connections must be opened. The pooler maintains ownership of the physical connection. It manages connections by keeping alive a set of active connections for each given connection configuration. Whenever a user calls Open on a connection, the pooler looks for an available connection in the pool. If a pooled connection is available, it returns it to the caller instead of opening a new connection. When the application calls Close on the connection, the pooler returns it to the pooled set of active connections instead of closing it. Once the connection is returned to the pool, it is ready to be reused on the next Open call.

So obviously there's no reason to avoid creating,opening or closing connections since actually they aren't created,opened and closed at all. This is "only" a flag for the connection pool to know when a connection can be reused or not. But it's a very important flag, because if a connection is "in use"(the connection pool assumes), a new physical connection must be openend to the DBMS what is very expensive.

So you're gaining no performance improvement but the opposite. If the maximum pool size specified (100 is the default) is reached, you would even get exceptions(too many open connections ...). So this will not only impact the performance tremendously but also be a source for nasty errors and (without using Transactions) a data-dumping-area.

If you're even using static connections you're creating a lock for every thread trying to access this object. ASP.NET is a multithreading environment by nature. So theres a great chance for these locks which causes performance issues at best. Actually sooner or later you'll get many different exceptions(like your ExecuteReader requires an open and available Connection).

Conclusion:

  • Don't reuse connections or any ADO.NET objects at all.
  • Don't make them static/shared(in VB.NET)
  • Always create, open(in case of Connections), use, close and dispose them where you need them(f.e. in a method)
  • use the using-statement to dispose and close(in case of Connections) implicitely

That's true not only for Connections(although most noticable). Every object implementing IDisposable should be disposed(simplest by using-statement), all the more in the System.Data.SqlClient namespace.

All the above speaks against a custom DB-Class which encapsulates and reuse all objects. That's the reason why i commented to trash it. That's only a problem source.


Edit: Here's a possible implementation of your retrievePromotion-method:

public Promotion retrievePromotion(int promotionID)
{
    Promotion promo = null;
    var connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["MainConnStr"].ConnectionString;
    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        var queryString = "SELECT PromotionID, PromotionTitle, PromotionURL FROM Promotion WHERE PromotionID=@PromotionID";
        using (var da = new SqlDataAdapter(queryString, connection))
        {
            // you could also use a SqlDataReader instead
            // note that a DataTable does not need to be disposed since it does not implement IDisposable
            var tblPromotion = new DataTable();
            // avoid SQL-Injection
            da.SelectCommand.Parameters.Add("@PromotionID", SqlDbType.Int);
            da.SelectCommand.Parameters["@PromotionID"].Value = promotionID;
            try
            {
                connection.Open(); // not necessarily needed in this case because DataAdapter.Fill does it otherwise 
                da.Fill(tblPromotion);
                if (tblPromotion.Rows.Count != 0)
                {
                    var promoRow = tblPromotion.Rows[0];
                    promo = new Promotion()
                    {
                        promotionID    = promotionID,
                        promotionTitle = promoRow.Field<String>("PromotionTitle"),
                        promotionUrl   = promoRow.Field<String>("PromotionURL")
                    };
                }
            }
            catch (Exception ex)
            {
                // log this exception or throw it up the StackTrace
                // we do not need a finally-block to close the connection since it will be closed implicitely in an using-statement
                throw;
            }
        }
    }
    return promo;
}

CSS centred header image

If you set the margin to be margin:0 auto the image will be centered.

This will give top + bottom a margin of 0, and left and right a margin of 'auto'. Since the div has a width (200px), the image will be 200px wide and the browser will auto set the left and right margin to half of what is left on the page, which will result in the image being centered.

How to create materialized views in SQL Server?

For MS T-SQL Server, I suggest looking into creating an index with the "include" statement. Uniqueness is not required, neither is the physical sorting of data associated with a clustered index. The "Index ... Include ()" creates a separate physical data storage automatically maintained by the system. It is conceptually very similar to an Oracle Materialized View.

https://msdn.microsoft.com/en-us/library/ms190806.aspx

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

How do I add a custom script to my package.json file that runs a javascript file?

Suppose I have this line of scripts in my "package.json"

"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "export_advertisements": "node export.js advertisements",
    "export_homedata": "node export.js homedata",
    "export_customdata": "node export.js customdata",
    "export_rooms": "node export.js rooms"
  },

Now to run the script "export_advertisements", I will simply go to the terminal and type

npm run export_advertisements

You are most welcome

Text not wrapping in p tag

That is because you have continuous text, means single long word without space. To break it add word-break: break-all;

.submenu div p {
    color:#fff;
    margin: 0;
    padding:0;
    width:100%;
    position: relative; word-break: break-all; background:red
}

DEMO

instantiate a class from a variable in PHP?

I would recommend the call_user_func() or call_user_func_arrayphp methods. You can check them out here (call_user_func_array , call_user_func).

example

class Foo {
static public function test() {
    print "Hello world!\n";
}
}

 call_user_func('Foo::test');//FOO is the class, test is the method both separated by ::
 //or
 call_user_func(array('Foo', 'test'));//alternatively you can pass the class and method as an array

If you have arguments you are passing to the method , then use the call_user_func_array() function.

example.

class foo {
function bar($arg, $arg2) {
    echo __METHOD__, " got $arg and $arg2\n";
}
}

// Call the $foo->bar() method with 2 arguments
call_user_func_array(array("foo", "bar"), array("three", "four"));
//or
//FOO is the class, bar is the method both separated by ::
call_user_func_array("foo::bar"), array("three", "four"));

Java Byte Array to String to Byte Array

What Arrays.toString() does is create a string representation of each individual byte in your byteArray.

Please check the API documentation Arrays API

To convert your response string back to the original byte array, you have to use split(",") or something and convert it into a collection and then convert each individual item in there to a byte to recreate your byte array.

should use size_t or ssize_t

ssize_t is used for functions whose return value could either be a valid size, or a negative value to indicate an error. It is guaranteed to be able to store values at least in the range [-1, SSIZE_MAX] (SSIZE_MAX is system-dependent).

So you should use size_t whenever you mean to return a size in bytes, and ssize_t whenever you would return either a size in bytes or a (negative) error value.

See: http://pubs.opengroup.org/onlinepubs/007908775/xsh/systypes.h.html

UnicodeEncodeError: 'ascii' codec can't encode character u'\xef' in position 0: ordinal not in range(128)

An easy solution to overcome this problem is to set your default encoding to utf8. Follow is an example

import sys

reload(sys)
sys.setdefaultencoding('utf8')

How do I read the source code of shell commands?

CoreUtils referred to in other posts does NOT show the real implementation of most of the functionality which I think you seek. In most cases it provides front-ends for the actual functions that retrieve the data, which can be found here:

It is build upon Gnulib with the actual source code in the lib-subdirectory

Getting a "This application is modifying the autolayout engine from a background thread" error?

I had this problem since updating to the iOS 9 SDK when I was calling a block that did UI updates within an NSURLConnection async request completion handler. Putting the block call in a dispatch_async using dispatch_main_queue solved the issue.

It worked fine in iOS 8.

How does Google calculate my location on a desktop?

  • So Google keep records of Wifi router location by using any cellphone GPS that connected to that router when you use Google maps or location on cellphone. then google knows every device that connected to that Wifi router uses the same location.
  • when GPS off or no cellphone connected to router Google uses IP geolocation

Difference between / and /* in servlet mapping url pattern

Perhaps you need to know how urls are mapped too, since I suffered 404 for hours. There are two kinds of handlers handling requests. BeanNameUrlHandlerMapping and SimpleUrlHandlerMapping. When we defined a servlet-mapping, we are using SimpleUrlHandlerMapping. One thing we need to know is these two handlers share a common property called alwaysUseFullPath which defaults to false.

false here means Spring will not use the full path to mapp a url to a controller. What does it mean? It means when you define a servlet-mapping:

<servlet-mapping>
    <servlet-name>viewServlet</servlet-name>
    <url-pattern>/perfix/*</url-pattern>
</servlet-mapping>

the handler will actually use the * part to find the controller. For example, the following controller will face a 404 error when you request it using /perfix/api/feature/doSomething

@Controller()
@RequestMapping("/perfix/api/feature")
public class MyController {
    @RequestMapping(value = "/doSomething", method = RequestMethod.GET) 
    @ResponseBody
    public String doSomething(HttpServletRequest request) {
        ....
    }
}

It is a perfect match, right? But why 404. As mentioned before, default value of alwaysUseFullPath is false, which means in your request, only /api/feature/doSomething is used to find a corresponding Controller, but there is no Controller cares about that path. You need to either change your url to /perfix/perfix/api/feature/doSomething or remove perfix from MyController base @RequestingMapping.

How to initialize an array in one step using Ruby?

To create such an array you could do:

array = ['1', '2', '3']

C - gettimeofday for computing time?

To subtract timevals:

gettimeofday(&t0, 0);
/* ... */
gettimeofday(&t1, 0);
long elapsed = (t1.tv_sec-t0.tv_sec)*1000000 + t1.tv_usec-t0.tv_usec;

This is assuming you'll be working with intervals shorter than ~2000 seconds, at which point the arithmetic may overflow depending on the types used. If you need to work with longer intervals just change the last line to:

long long elapsed = (t1.tv_sec-t0.tv_sec)*1000000LL + t1.tv_usec-t0.tv_usec;

jackson deserialization json to java-objects

Your product class needs a parameterless constructor. You can make it private, but Jackson needs the constructor.

As a side note: You should use Pascal casing for your class names. That is Product, and not product.

Understanding __getitem__ method

The [] syntax for getting item by key or index is just syntax sugar.

When you evaluate a[i] Python calls a.__getitem__(i) (or type(a).__getitem__(a, i), but this distinction is about inheritance models and is not important here). Even if the class of a may not explicitly define this method, it is usually inherited from an ancestor class.

All the (Python 2.7) special method names and their semantics are listed here: https://docs.python.org/2.7/reference/datamodel.html#special-method-names

JAVA_HOME and PATH are set but java -version still shows the old one

Updating the ~/.profile or ~/.bash_profile does not work sometimes. I just deleted JDK 6 and sourced .bash_profile.

Try running this:

sudo rm -rd jdk1.6.0_* #it may not let you delete without sudo

Then, modify/add your JAVA_HOME and PATH variables.

source ~/.bash_profile #assuming you've updated $JAVA_HOME and $PATH

How to make a div with no content have a width?

Use min-height: 1px; Everything has at least min-height of 1px so no extra space is taken up with nbsp or padding, or being forced to know the height first.

Learning Regular Expressions

The most important part is the concepts. Once you understand how the building blocks work, differences in syntax amount to little more than mild dialects. A layer on top of your regular expression engine's syntax is the syntax of the programming language you're using. Languages such as Perl remove most of this complication, but you'll have to keep in mind other considerations if you're using regular expressions in a C program.

If you think of regular expressions as building blocks that you can mix and match as you please, it helps you learn how to write and debug your own patterns but also how to understand patterns written by others.

Start simple

Conceptually, the simplest regular expressions are literal characters. The pattern N matches the character 'N'.

Regular expressions next to each other match sequences. For example, the pattern Nick matches the sequence 'N' followed by 'i' followed by 'c' followed by 'k'.

If you've ever used grep on Unix—even if only to search for ordinary looking strings—you've already been using regular expressions! (The re in grep refers to regular expressions.)

Order from the menu

Adding just a little complexity, you can match either 'Nick' or 'nick' with the pattern [Nn]ick. The part in square brackets is a character class, which means it matches exactly one of the enclosed characters. You can also use ranges in character classes, so [a-c] matches either 'a' or 'b' or 'c'.

The pattern . is special: rather than matching a literal dot only, it matches any character. It's the same conceptually as the really big character class [-.?+%$A-Za-z0-9...].

Think of character classes as menus: pick just one.

Helpful shortcuts

Using . can save you lots of typing, and there are other shortcuts for common patterns. Say you want to match a digit: one way to write that is [0-9]. Digits are a frequent match target, so you could instead use the shortcut \d. Others are \s (whitespace) and \w (word characters: alphanumerics or underscore).

The uppercased variants are their complements, so \S matches any non-whitespace character, for example.

Once is not enough

From there, you can repeat parts of your pattern with quantifiers. For example, the pattern ab?c matches 'abc' or 'ac' because the ? quantifier makes the subpattern it modifies optional. Other quantifiers are

  • * (zero or more times)
  • + (one or more times)
  • {n} (exactly n times)
  • {n,} (at least n times)
  • {n,m} (at least n times but no more than m times)

Putting some of these blocks together, the pattern [Nn]*ick matches all of

  • ick
  • Nick
  • nick
  • Nnick
  • nNick
  • nnick
  • (and so on)

The first match demonstrates an important lesson: * always succeeds! Any pattern can match zero times.

A few other useful examples:

  • [0-9]+ (and its equivalent \d+) matches any non-negative integer
  • \d{4}-\d{2}-\d{2} matches dates formatted like 2019-01-01

Grouping

A quantifier modifies the pattern to its immediate left. You might expect 0abc+0 to match '0abc0', '0abcabc0', and so forth, but the pattern immediately to the left of the plus quantifier is c. This means 0abc+0 matches '0abc0', '0abcc0', '0abccc0', and so on.

To match one or more sequences of 'abc' with zeros on the ends, use 0(abc)+0. The parentheses denote a subpattern that can be quantified as a unit. It's also common for regular expression engines to save or "capture" the portion of the input text that matches a parenthesized group. Extracting bits this way is much more flexible and less error-prone than counting indices and substr.

Alternation

Earlier, we saw one way to match either 'Nick' or 'nick'. Another is with alternation as in Nick|nick. Remember that alternation includes everything to its left and everything to its right. Use grouping parentheses to limit the scope of |, e.g., (Nick|nick).

For another example, you could equivalently write [a-c] as a|b|c, but this is likely to be suboptimal because many implementations assume alternatives will have lengths greater than 1.

Escaping

Although some characters match themselves, others have special meanings. The pattern \d+ doesn't match backslash followed by lowercase D followed by a plus sign: to get that, we'd use \\d\+. A backslash removes the special meaning from the following character.

Greediness

Regular expression quantifiers are greedy. This means they match as much text as they possibly can while allowing the entire pattern to match successfully.

For example, say the input is

"Hello," she said, "How are you?"

You might expect ".+" to match only 'Hello,' and will then be surprised when you see that it matched from 'Hello' all the way through 'you?'.

To switch from greedy to what you might think of as cautious, add an extra ? to the quantifier. Now you understand how \((.+?)\), the example from your question works. It matches the sequence of a literal left-parenthesis, followed by one or more characters, and terminated by a right-parenthesis.

If your input is '(123) (456)', then the first capture will be '123'. Non-greedy quantifiers want to allow the rest of the pattern to start matching as soon as possible.

(As to your confusion, I don't know of any regular-expression dialect where ((.+?)) would do the same thing. I suspect something got lost in transmission somewhere along the way.)

Anchors

Use the special pattern ^ to match only at the beginning of your input and $ to match only at the end. Making "bookends" with your patterns where you say, "I know what's at the front and back, but give me everything between" is a useful technique.

Say you want to match comments of the form

-- This is a comment --

you'd write ^--\s+(.+)\s+--$.

Build your own

Regular expressions are recursive, so now that you understand these basic rules, you can combine them however you like.

Tools for writing and debugging regexes:

Books

Free resources

Footnote

†: The statement above that . matches any character is a simplification for pedagogical purposes that is not strictly true. Dot matches any character except newline, "\n", but in practice you rarely expect a pattern such as .+ to cross a newline boundary. Perl regexes have a /s switch and Java Pattern.DOTALL, for example, to make . match any character at all. For languages that don't have such a feature, you can use something like [\s\S] to match "any whitespace or any non-whitespace", in other words anything.

How to kill a child process by the parent process?

In the parent process, fork()'s return value is the process ID of the child process. Stuff that value away somewhere for when you need to terminate the child process. fork() returns zero(0) in the child process.

When you need to terminate the child process, use the kill(2) function with the process ID returned by fork(), and the signal you wish to deliver (e.g. SIGTERM).

Remember to call wait() on the child process to prevent any lingering zombies.

Move layouts up when soft keyboard is shown?

  1. If user want this task using manifest then add this line in manifest
  2. In manifest add this line: - android:windowSoftInputMode="adjustPan" e.g.

In Java File or Kotlin File (Programmatically):- If the user wants this using Activity then add the below line in onCreate Method

activity?.window()?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE)

How to change a field name in JSON using Jackson

Jackson

If you are using Jackson, then you can use the @JsonProperty annotation to customize the name of a given JSON property.

Therefore, you just have to annotate the entity fields with the @JsonProperty annotation and provide a custom JSON property name, like this:

@Entity
public class City {

   @Id
   @JsonProperty("value")
   private Long id;

   @JsonProperty("label")
   private String name;

   //Getters and setters omitted for brevity
}

JavaEE or JakartaEE JSON-B

JSON-B is the standard binding layer for converting Java objects to and from JSON. If you are using JSON-B, then you can override the JSON property name via the @JsonbProperty annotation:

@Entity
public class City {

   @Id
   @JsonbProperty("value")
   private Long id;

   @JsonbProperty("label")
   private String name;

   //Getters and setters omitted for brevity
}

How to trigger click on page load?

You can do the following :-

$(document).ready(function(){
    $("#id").trigger("click");
});

How do I do top 1 in Oracle?

With Oracle 12c (June 2013), you are able to use it like the following.

SELECT * FROM   MYTABLE
--ORDER BY COLUMNNAME -OPTIONAL          
OFFSET 0 ROWS FETCH NEXT 1 ROWS ONLY

JPA CascadeType.ALL does not delete orphans

According to Java Persistence with Hibernate, cascade orphan delete is not available as a JPA annotation.

It is also not supported in JPA XML.

What is the parameter "next" used for in Express?

Next is used to pass control to the next middleware function. If not the request will be left hanging or open.

Removing Duplicate Values from ArrayList

 public void removeDuplicates() {
    ArrayList<Object> al = new ArrayList<Object>();
    al.add("java");
    al.add('a');
    al.add('b');
    al.add('a');
    al.add("java");
    al.add(10.3);
    al.add('c');
    al.add(14);
    al.add("java");
    al.add(12);

    System.out.println("Before Remove Duplicate elements:" + al);
    for (int i = 0; i < al.size(); i++) {
        for (int j = i + 1; j < al.size(); j++) {
            if (al.get(i).equals(al.get(j))) {
                al.remove(j);
                j--;
            }
        }
    }
    System.out.println("After Removing duplicate elements:" + al);
}

Before Remove Duplicate elements:

[java, a, b, a, java, 10.3, c, 14, java, 12]

After Removing duplicate elements:

[java, a, b, 10.3, c, 14, 12]

Git: How to update/checkout a single file from remote origin master?

git archive --format=zip --remote=ssh://<user>@<host>/repos/<repo name> <tag or HEAD> <filename> > <output file name>.zip

How to connect to local instance of SQL Server 2008 Express

One of the first things that you should check is that the SQL Server (MSSQLSERVER) is started. You can go to the Services Console (services.msc) and look for SQL Server (MSSQLSERVER) to see that it is started. If not, then start the service.

You could also do this through an elevated command prompt by typing net start mssqlserver.

CSS to stop text wrapping under image

Wrap a div around the image and the span and add the following to CSS like so:

HTML

        <li id="CN2787">
          <div><img class="fav_star" src="images/fav.png"></div>
          <div><span>Text, text and more text</span></div>
        </li>

CSS

            #CN2787 > div { 
                display: inline-block;
                vertical-align: top;
            }

            #CN2787 > div:first-of-type {
                width: 35%;
            }

            #CN2787 > div:last-of-type {
                width: 65%;
            }

LESS

        #CN2787 {
            > div { 
                display: inline-block;
                vertical-align: top;
            }

            > div:first-of-type {
                width: 35%;
            }
            > div:last-of-type {
                width: 65%;
            }
        }

Update int column in table with unique incrementing values

Assuming that you have a primary key for this table (you should have), as well as using a CTE or a WITH, it is also possible to use an update with a self-join to the same table:

UPDATE a
SET a.interfaceId = b.sequence
FROM prices a
INNER JOIN
(
   SELECT ROW_NUMBER() OVER ( ORDER BY b.priceId ) + ( SELECT MAX( interfaceId ) + 1 FROM prices ) AS sequence, b.priceId
   FROM prices b
   WHERE b.interfaceId IS NULL
) b ON b.priceId = a.priceId

I have assumed that the primary key is price-id.

The derived table, alias b, is used to generated the sequence via the ROW_NUMBER() function together with the primary key column(s). For each row where the column interface-id is NULL, this will generate a row with a unique sequence value together with the primary key value.

It is possible to order the sequence in some other order rather than the primary key.

The sequence is offset by the current MAX interface-id + 1 via a sub-query. The MAX() function ignores NULL values.

The WHERE clause limits the update to those rows that are NULL.

The derived table is then joined to the same table, alias a, joining on the primary key column(s) with the column to be updated set to the generated sequence.

How to set selected index JComboBox by value

Why not take a collection, likely a Map such as a HashMap, and use it as the nucleus of your own combo box model class that implements the ComboBoxModel interface? Then you could access your combo box's items easily via their key Strings rather than ints.

For instance...

import java.util.HashMap;
import java.util.Map;

import javax.swing.ComboBoxModel;
import javax.swing.event.ListDataListener;

public class MyComboModel<K, V>   implements ComboBoxModel {
   private Map<K, V> nucleus = new HashMap<K, V>();

   // ... any constructors that you want would go here

   public void put(K key, V value) {
      nucleus.put(key, value);
   }

   public V get(K key) {
      return nucleus.get(key);
   }

   @Override
   public void addListDataListener(ListDataListener arg0) {
      // TODO Auto-generated method stub

   }

   // ... plus all the other methods required by the interface
}

SELECT CASE WHEN THEN (SELECT)

You should avoid using nested selects and I would go as far to say you should never use them in the actual select part of your statement. You will be running that select for each row that is returned. This is a really expensive operation. Rather use joins. It is much more readable and the performance is much better.

In your case the query below should help. Note the cases statement is still there, but now it is a simple compare operation.

select
    p.product_id,
    p.type_id,
    p.product_name,
    p.type,
    case p.type_id when 10 then (CONCAT_WS(' ' , first_name, middle_name, last_name )) else (null) end artistC
from
    Product p

    inner join Product_Type pt on
        pt.type_id = p.type_id

    left join Product_ArtistAuthor paa on
        paa.artist_id = p.artist_id
where
    p.product_id = $pid

I used a left join since I don't know the business logic.

How to enable mod_rewrite for Apache 2.2

The first time I struggled with mod_rewrite rules ignoring my traffic, I learned (frustratingly) that I had placed them in the wrong <VirtualHost>, which meant that my traffic would ignore all of them no matter how well-written they were. Make sure this isn't happening to you:

# Change the log location to suit your system. RewriteLog /var/log/apache-rw.log RewriteLogLevel 2

These parameters will activate if you perform a graceful restart of Apache, so you can recycle them in and closely monitor the mod_rewrite behavior. Once your problem is fixed, turn the RewriteLogLevel back down and celebrate.

In 100% of my experience, I've found that the RewriteLog has helped me discover the problem with my rewrite rules. I can't recommend this enough. Good luck in your troubleshooting!

Also, this bookmark is your best friend: http://httpd.apache.org/docs/2.2/mod/mod_rewrite.html#rewritelog

Parse XML using JavaScript

The following will parse an XML string into an XML document in all major browsers, including Internet Explorer 6. Once you have that, you can use the usual DOM traversal methods/properties such as childNodes and getElementsByTagName() to get the nodes you want.

var parseXml;
if (typeof window.DOMParser != "undefined") {
    parseXml = function(xmlStr) {
        return ( new window.DOMParser() ).parseFromString(xmlStr, "text/xml");
    };
} else if (typeof window.ActiveXObject != "undefined" &&
       new window.ActiveXObject("Microsoft.XMLDOM")) {
    parseXml = function(xmlStr) {
        var xmlDoc = new window.ActiveXObject("Microsoft.XMLDOM");
        xmlDoc.async = "false";
        xmlDoc.loadXML(xmlStr);
        return xmlDoc;
    };
} else {
    throw new Error("No XML parser found");
}

Example usage:

var xml = parseXml("<foo>Stuff</foo>");
alert(xml.documentElement.nodeName);

Which I got from https://stackoverflow.com/a/8412989/1232175.

Stop executing further code in Java

return to come out of the method execution, break to come out of a loop execution and continue to skip the rest of the current loop. In your case, just return, but if you are in a for loop, for example, do break to stop the loop or continue to skip to next step in the loop

Read String line by line

You can try the following regular expression:

\r?\n

Code:

String input = "\nab\n\n    \n\ncd\nef\n\n\n\n\n";
String[] lines = input.split("\\r?\\n", -1);
int n = 1;
for(String line : lines) {
    System.out.printf("\tLine %02d \"%s\"%n", n++, line);
}

Output:

Line 01 ""
Line 02 "ab"
Line 03 ""
Line 04 "    "
Line 05 ""
Line 06 "cd"
Line 07 "ef"
Line 08 ""
Line 09 ""
Line 10 ""
Line 11 ""
Line 12 ""

Identifying country by IP address

IP addresses are quite commonly used for geo-targeting i.e. customizing the content of a website by the visitor's location / country but they are not permanently associated with a country and often get re-assigned.

To accomplish what you want, you need to keep an up to date lookup to map an IP address to a country either with a database or a geolocation API. Here's an example :

> https://ipapi.co/8.8.8.8/country
US

> https://ipapi.co/8.8.8.8/country_name
United States

Or you can use the full API to get complete location for IP address e.g.

https://ipapi.co/8.8.8.8/json

{
    "ip": "8.8.8.8",
    "city": "Mountain View",
    "region": "California",
    "region_code": "CA",
    "country": "US",
    "country_name": "United States",
    "continent_code": "NA",
    "postal": "94035",
    "latitude": 37.386,
    "longitude": -122.0838,
    "timezone": "America/Los_Angeles",
    "utc_offset": "-0800",
    "country_calling_code": "+1",
    "currency": "USD",
    "languages": "en-US,es-US,haw,fr",
    "asn": "AS15169",
    "org": "Google Inc."
}

JavaScript Extending Class

For Autodidacts:

function BaseClass(toBePrivate){
    var morePrivates;
    this.isNotPrivate = 'I know';
    // add your stuff
}
var o = BaseClass.prototype;
// add your prototype stuff
o.stuff_is_never_private = 'whatever_except_getter_and_setter';


// MiddleClass extends BaseClass
function MiddleClass(toBePrivate){
    BaseClass.call(this);
    // add your stuff
    var morePrivates;
    this.isNotPrivate = 'I know';
}
var o = MiddleClass.prototype = Object.create(BaseClass.prototype);
MiddleClass.prototype.constructor = MiddleClass;
// add your prototype stuff
o.stuff_is_never_private = 'whatever_except_getter_and_setter';



// TopClass extends MiddleClass
function TopClass(toBePrivate){
    MiddleClass.call(this);
    // add your stuff
    var morePrivates;
    this.isNotPrivate = 'I know';
}
var o = TopClass.prototype = Object.create(MiddleClass.prototype);
TopClass.prototype.constructor = TopClass;
// add your prototype stuff
o.stuff_is_never_private = 'whatever_except_getter_and_setter';


// to be continued...

Create "instance" with getter and setter:

function doNotExtendMe(toBePrivate){
    var morePrivates;
    return {
        // add getters, setters and any stuff you want
    }
}

appending array to FormData and send via AJAX

If you have nested objects and arrays, best way to populate FormData object is using recursion.

function createFormData(formData, data, key) {
    if ( ( typeof data === 'object' && data !== null ) || Array.isArray(data) ) {
        for ( let i in data ) {
            if ( ( typeof data[i] === 'object' && data[i] !== null ) || Array.isArray(data[i]) ) {
                createFormData(formData, data[i], key + '[' + i + ']');
            } else {
                formData.append(key + '[' + i + ']', data[i]);
            }
        }
    } else {
        formData.append(key, data);
    }
}

Error while trying to retrieve text for error ORA-01019

Well,

Just worked it out. While having both installations we have two ORACLE_HOME directories and both have SQAORA32.dll files. While looking up for ORACLE_HOMe my app was getting confused..I just removed the Client oracle home entry as oracle client is by default present in oracle DB Now its working...Thanks!!

The server committed a protocol violation. Section=ResponseStatusLine ERROR

Setting expect 100 continue to false and reducing the socket idle time to two seconds resolved the problem for me

ServicePointManager.Expect100Continue = false; 
ServicePointManager. MaxServicePointIdleTime = 2000; 

SharePoint 2013 get current user using JavaScript

U can use javascript to achive that like this:

function loadConstants() {

    this.clientContext = new SP.ClientContext.get_current();
    this.clientContext = new SP.ClientContext.get_current();
    this.oWeb = clientContext.get_web();
    currentUser = this.oWeb.get_currentUser();  
    this.clientContext.load(currentUser);
      completefunc:this.clientContext.executeQueryAsync(Function.createDelegate(this,this.onQuerySucceeded), Function.createDelegate(this,this.onQueryFailed));


}

//U must set a timeout to recivie the exactly user u want:

function onQuerySucceeded(sender, args) {

    window.setTimeout("ttt();",1000);
}
function onQueryFailed(sender, args) {

    console.log(args.get_message());
}

//By using a proper timeout, u can get current user :

function ttt(){ 

    var clientContext = new SP.ClientContext.get_current();
    var groupCollection = clientContext.get_web().get_siteGroups();
    visitorsGroup = groupCollection.getByName('OLAP Portal Members');

    t=this.currentUser .get_loginName().toLowerCase();

    console.log ('this.currentUser .get_loginName() : '+ t);      

}

How to copy a dictionary and only edit the copy

You can use directly:

dict2 = eval(repr(dict1))

where object dict2 is an independent copy of dict1, so you can modify dict2 without affecting dict1.

This works for any kind of object.

How can I use pointers in Java?

There are pointers in Java, but you cannot manipulate them the way that you can in C++ or C. When you pass an object, you are passing a pointer to that object, but not in the same sense as in C++. That object cannot be dereferenced. If you set its values using its native accessors, it will change because Java knows its memory location through the pointer. But the pointer is immutable. When you attempt to set the pointer to a new location, you instead end up with a new local object with the same name as the other. The original object is unchanged. Here is a brief program to demonstrate the difference.

import java.util.*;
import java.lang.*;
import java.io.*;

class Ideone {

    public static void main(String[] args) throws java.lang.Exception {
        System.out.println("Expected # = 0 1 2 2 1");
        Cat c = new Cat();
        c.setClaws(0);
        System.out.println("Initial value is " + c.getClaws());
        // prints 0 obviously
        clawsAreOne(c);
        System.out.println("Accessor changes value to " + c.getClaws());
        // prints 1 because the value 'referenced' by the 'pointer' is changed using an accessor.
        makeNewCat(c);
        System.out.println("Final value is " + c.getClaws());
        // prints 1 because the pointer is not changed to 'kitten'; that would be a reference pass.
    }

    public static void clawsAreOne(Cat kitty) {
        kitty.setClaws(1);
    }

    public static void makeNewCat(Cat kitty) {
        Cat kitten = new Cat();
        kitten.setClaws(2);
        kitty = kitten;
        System.out.println("Value in makeNewCat scope of kitten " + kitten.getClaws());
        //Prints 2. the value pointed to by 'kitten' is 2
        System.out.println("Value in makeNewcat scope of kitty " + kitty.getClaws());
        //Prints 2. The local copy is being used within the scope of this method.
    }
}

class Cat {

    private int claws;

    public void setClaws(int i) {
        claws = i;
    }

    public int getClaws() {
        return claws;
    }
}

This can be run at Ideone.com.

How to urlencode a querystring in Python?

For Python 3 urllib3 works properly, you can use as follow as per its official docs :

import urllib3

http = urllib3.PoolManager()
response = http.request(
     'GET',
     'https://api.prylabs.net/eth/v1alpha1/beacon/attestations',
     fields={  # here fields are the query params
          'epoch': 1234,
          'pageSize': pageSize 
      } 
 )
response = attestations.data.decode('UTF-8')

How to get the separate digits of an int number?

Just to build on the subject, here's how to confirm that the number is a palindromic integer in Java:

public static boolean isPalindrome(int input) {
List<Integer> intArr = new ArrayList();
int procInt = input;

int i = 0;
while(procInt > 0) {
    intArr.add(procInt%10);
    procInt = procInt/10;
    i++;
}

int y = 0;
int tmp = 0;
int count = 0;
for(int j:intArr) {
    if(j == 0 && count == 0) {
    break;
    }

    tmp = j + (tmp*10);
    count++;
}

if(input != tmp)
    return false;

return true;
}

I'm sure I can simplify this algo further. Yet, this is where I am. And it has worked under all of my test cases.

I hope this helps someone.

How to get first record in each group using Linq

var result = input.GroupBy(x=>x.F1,(key,g)=>g.OrderBy(e=>e.F2).First());

Warning: X may be used uninitialized in this function

You get the warning because you did not assign a value to one, which is a pointer. This is undefined behavior.

You should declare it like this:

Vector* one = malloc(sizeof(Vector));

or like this:

Vector one;

in which case you need to replace -> operator with . like this:

one.a = 12;
one.b = 13;
one.c = -11;

Finally, in C99 and later you can use designated initializers:

Vector one = {
   .a = 12
,  .b = 13
,  .c = -11
};

jQuery - What are differences between $(document).ready and $(window).load?

From the jQuery API Document

While JavaScript provides the load event for executing code when a page is rendered, this event does not get triggered until all assets such as images have been completely received. In most cases, the script can be run as soon as the DOM hierarchy has been fully constructed. The handler passed to .ready() is guaranteed to be executed after the DOM is ready, so this is usually the best place to attach all other event handlers and run other jQuery code. When using scripts that rely on the value of CSS style properties, it's important to reference external stylesheets or embed style elements before referencing the scripts.

In cases where code relies on loaded assets (for example, if the dimensions of an image are required), the code should be placed in a handler for the load event instead.


Answer to the second question -

No, they are identical as long as you are not using jQuery in no conflict mode.

Redis strings vs Redis hashes to represent JSON: efficiency?

It depends on how you access the data:

Go for Option 1:

  • If you use most of the fields on most of your accesses.
  • If there is variance on possible keys

Go for Option 2:

  • If you use just single fields on most of your accesses.
  • If you always know which fields are available

P.S.: As a rule of the thumb, go for the option which requires fewer queries on most of your use cases.

Change File Extension Using C#

You should do a move of the file to rename it. In your example code you are only changing the string, not the file:

myfile= "c:/my documents/my images/cars/a.jpg";
string extension = Path.GetExtension(myffile); 
myfile.replace(extension,".Jpeg");

you are only changing myfile (which is a string). To move the actual file, you should do

FileInfo f = new FileInfo(myfile);
f.MoveTo(Path.ChangeExtension(myfile, ".Jpeg"));

See FileInfo.MoveTo

select count(*) from select

You're missing a FROM and you need to give the subquery an alias.

SELECT COUNT(*) FROM 
(
  SELECT DISTINCT a.my_id, a.last_name, a.first_name, b.temp_val
   FROM dbo.Table_A AS a 
   INNER JOIN dbo.Table_B AS b 
   ON a.a_id = b.a_id
) AS subquery;

How to remove a branch locally?

Force Delete a Local Branch:

$ git branch -D <branch-name>

[NOTE]:

-D is a shortcut for --delete --force.


Two-dimensional array in Swift

Define mutable array

// 2 dimensional array of arrays of Ints 
var arr = [[Int]]() 

OR:

// 2 dimensional array of arrays of Ints 
var arr: [[Int]] = [] 

OR if you need an array of predefined size (as mentioned by @0x7fffffff in comments):

// 2 dimensional array of arrays of Ints set to 0. Arrays size is 10x5
var arr = Array(count: 3, repeatedValue: Array(count: 2, repeatedValue: 0))

// ...and for Swift 3+:
var arr = Array(repeating: Array(repeating: 0, count: 2), count: 3)

Change element at position

arr[0][1] = 18

OR

let myVar = 18
arr[0][1] = myVar

Change sub array

arr[1] = [123, 456, 789] 

OR

arr[0] += 234

OR

arr[0] += [345, 678]

If you had 3x2 array of 0(zeros) before these changes, now you have:

[
  [0, 0, 234, 345, 678], // 5 elements!
  [123, 456, 789],
  [0, 0]
]

So be aware that sub arrays are mutable and you can redefine initial array that represented matrix.

Examine size/bounds before access

let a = 0
let b = 1

if arr.count > a && arr[a].count > b {
    println(arr[a][b])
}

Remarks: Same markup rules for 3 and N dimensional arrays.

How to convert an address into a Google Maps Link (NOT MAP)

If you have latitude and longitude, you can use any part or all of bellow URL

https://www.google.com/maps/@LATITUDE,LONGITUDE,ZOOMNUMBERz?hl=LANGUAGE

For example: https://www.google.com/maps/@31.839472,54.361167,18z?hl=en

How to suppress Pandas Future warning ?

@bdiamante's answer may only partially help you. If you still get a message after you've suppressed warnings, it's because the pandas library itself is printing the message. There's not much you can do about it unless you edit the Pandas source code yourself. Maybe there's an option internally to suppress them, or a way to override things, but I couldn't find one.


For those who need to know why...

Suppose that you want to ensure a clean working environment. At the top of your script, you put pd.reset_option('all'). With Pandas 0.23.4, you get the following:

>>> import pandas as pd
>>> pd.reset_option('all')
html.border has been deprecated, use display.html.border instead
(currently both are identical)

C:\projects\stackoverflow\venv\lib\site-packages\pandas\core\config.py:619: FutureWarning: html.bord
er has been deprecated, use display.html.border instead
(currently both are identical)

  warnings.warn(d.msg, FutureWarning)

: boolean
    use_inf_as_null had been deprecated and will be removed in a future
    version. Use `use_inf_as_na` instead.

C:\projects\stackoverflow\venv\lib\site-packages\pandas\core\config.py:619: FutureWarning:
: boolean
    use_inf_as_null had been deprecated and will be removed in a future
    version. Use `use_inf_as_na` instead.

  warnings.warn(d.msg, FutureWarning)

>>>

Following the @bdiamante's advice, you use the warnings library. Now, true to it's word, the warnings have been removed. However, several pesky messages remain:

>>> import warnings
>>> warnings.simplefilter(action='ignore', category=FutureWarning)
>>> import pandas as pd
>>> pd.reset_option('all')
html.border has been deprecated, use display.html.border instead
(currently both are identical)


: boolean
    use_inf_as_null had been deprecated and will be removed in a future
    version. Use `use_inf_as_na` instead.

>>>

In fact, disabling all warnings produces the same output:

>>> import warnings
>>> warnings.simplefilter(action='ignore', category=Warning)
>>> import pandas as pd
>>> pd.reset_option('all')
html.border has been deprecated, use display.html.border instead
(currently both are identical)


: boolean
    use_inf_as_null had been deprecated and will be removed in a future
    version. Use `use_inf_as_na` instead.

>>>

In the standard library sense, these aren't true warnings. Pandas implements its own warnings system. Running grep -rn on the warning messages shows that the pandas warning system is implemented in core/config_init.py:

$ grep -rn "html.border has been deprecated"
core/config_init.py:207:html.border has been deprecated, use display.html.border instead

Further chasing shows that I don't have time for this. And you probably don't either. Hopefully this saves you from falling down the rabbit hole or perhaps inspires someone to figure out how to truly suppress these messages!

AngularJS: How to clear query parameters in the URL?

Just use

$location.url();

Instead of

$location.path();

python paramiko ssh

There is something wrong with the accepted answer, it sometimes (randomly) brings a clipped response from server. I do not know why, I did not investigate the faulty cause of the accepted answer because this code worked perfectly for me:

import paramiko

ip='server ip'
port=22
username='username'
password='password'

cmd='some useful command' 

ssh=paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(ip,port,username,password)

stdin,stdout,stderr=ssh.exec_command(cmd)
outlines=stdout.readlines()
resp=''.join(outlines)
print(resp)

stdin,stdout,stderr=ssh.exec_command('some really useful command')
outlines=stdout.readlines()
resp=''.join(outlines)
print(resp)

How do I set default values for functions parameters in Matlab?

I've found that the parseArgs function can be very helpful.

Check if a string is not NULL or EMPTY

if (!$variablename) { Write-Host "variable is null" }

I hope this simple answer will is resolve the question. Source

Passing multiple values to a single PowerShell script parameter

The easiest way is probably to use two parameters: One for hosts (can be an array), and one for vlan.

param([String[]] $Hosts, [String] $VLAN)

Instead of

foreach ($i in $args)

you can use

foreach ($hostName in $Hosts)

If there is only one host, the foreach loop will iterate only once. To pass multiple hosts to the script, pass it as an array:

myScript.ps1 -Hosts host1,host2,host3 -VLAN 2

...or something similar.

How to install OpenSSL in windows 10?

Check openssl tool which is a collection of Openssl from the LibreSSL project and Cygwin libraries (2.5 MB). NB! We're the packager.

One liner to create a self signed certificate:

openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout selfsigned.key -out selfsigned.crt

background: fixed no repeat not working on mobile

I've been having the same problem, but now it works. All I had to do was add background-size: cover !important; and it works on my Android device!

The entire code looks like this:

body.page-id-8 #art-main {
  background: #000000 url("link to image") !important;
  background-repeat: no-repeat !important;
  background-position: 50% 50% !important;
  background-attachment: fixed !important;
  background-color: transparent !important;
  background-size: cover !important;
}

Thanks a lot @taylan derinbay and @Vincent!

PHP write file from input to txt

The problems you have are because of the extra <form> you have, that your data goes in GET method, and you are accessing the data in PHP using POST.

<body>
<!--<form>-->
    <form action="myprocessingscript.php" method="POST">

presentViewController and displaying navigation bar

I use this code. It's working fine in iOS 8.

MyProfileEditViewController *myprofileEdit=[self.storyboard instantiateViewControllerWithIdentifier:@"myprofileeditSid"];
UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:myprofileEdit];
[self presentViewController:navigationController animated:YES completion:^{}];

Unable to connect to any of the specified mysql hosts. C# MySQL

Try this:

MySqlConnectionStringBuilder conn_string = new MySqlConnectionStringBuilder();
conn_string.Server = "127.0.0.1";
conn_string.Port = 3306;
conn_string.UserID = "root";
conn_string.Password = "myPassword";
conn_string.Database = "myDB";



MySqlConnection MyCon = new MySqlConnection(conn_string.ToString());

try
{
    MyCon.Open();
    MessageBox.Show("Open");
    MyCon.Close();
    MessageBox.Show("Close");
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message);
}

How do I create an .exe for a Java program?

You could try exe4j. This is effectively what we use through its cousin install4j.

How do I print colored output with Python 3?

It is very simple with colorama, just do this:

import colorama
from colorama import Fore, Style
print(Fore.BLUE + "Hello World")

And here is the running result in Python3 REPL:

And call this to reset the color settings:

print(Style.RESET_ALL)

To avoid printing an empty line write this:

print(f"{Fore.BLUE}Hello World{Style.RESET_ALL}")

Automatically resize jQuery UI dialog to the width of the content loaded by ajax

I imagine setting float:left for the dialog will work. Presumably the dialog is absolutely positioned by the plugin, in which case its position will be determined by this, but the side-effect of float - making elements only as wide as they need to be to hold content - will still take effect.

This should work if you just put a rule like

.myDialog {float:left}

in your stylesheet, though you may need to set it using jQuery

Fade In on Scroll Down, Fade Out on Scroll Up - based on element position in window

I tweaked your code a bit and made it more robust. In terms of progressive enhancement it's probaly better to have all the fade-in-out logic in JavaScript. In the example of myfunksyde any user without JavaScript sees nothing because of the opacity: 0;.

    $(window).on("load",function() {
    function fade() {
        var animation_height = $(window).innerHeight() * 0.25;
        var ratio = Math.round( (1 / animation_height) * 10000 ) / 10000;

        $('.fade').each(function() {

            var objectTop = $(this).offset().top;
            var windowBottom = $(window).scrollTop() + $(window).innerHeight();

            if ( objectTop < windowBottom ) {
                if ( objectTop < windowBottom - animation_height ) {
                    $(this).html( 'fully visible' );
                    $(this).css( {
                        transition: 'opacity 0.1s linear',
                        opacity: 1
                    } );

                } else {
                    $(this).html( 'fading in/out' );
                    $(this).css( {
                        transition: 'opacity 0.25s linear',
                        opacity: (windowBottom - objectTop) * ratio
                    } );
                }
            } else {
                $(this).html( 'not visible' );
                $(this).css( 'opacity', 0 );
            }
        });
    }
    $('.fade').css( 'opacity', 0 );
    fade();
    $(window).scroll(function() {fade();});
});

See it here: http://jsfiddle.net/78xjLnu1/16/

Cheers, Martin

How to use git merge --squash?

You can use tool I've created to make this process easier: git-squash. For example to squash all commits on feature branch that has been branched from master branch, write:

git squash master
git push --force

Why is it that "No HTTP resource was found that matches the request URI" here?

If it is a GET service, then you need to use it with a GET method, not a POST method. Your problem is a type mismatch. A different example of type mismatch (to put severity into perspective) is trying to assign a string to an integer variable.

Access: Move to next record until EOF

Keeping the code simple is always my advice:

If IsNull(Me.Id) = True Then
  DoCmd.GoToRecord , , acNext
Else
  DoCmd.GoToRecord , , acLast
End If

How can I show an image using the ImageView component in javafx and fxml?

You don't need an initializer, unless you're dynamically loading a different image each time. I think doing as much as possible in fxml is more organized. Here is an fxml file that will do what you need.

<?xml version="1.0" encoding="UTF-8"?>

<?import java.lang.*?>
<?import javafx.scene.image.*?>
<?import javafx.scene.layout.*?>

<AnchorPane
    xmlns:fx="http://javafx.co/fxml/1"
    xmlns="http://javafx.com/javafx/2.2"
    fx:controller="application.SampleController"
    prefHeight="316.0"
    prefWidth="321.0"
    >
    <children>
        <ImageView
                fx:id="imageView"
                fitHeight="150.0"
                fitWidth="200.0"
                layoutX="61.0"
                layoutY="83.0"
                pickOnBounds="true"
                preserveRatio="true"
            >
            <image>
                <Image
                    url="src/Box13.jpg"
                    backgroundLoading="true"
                    />
            </image>
        </ImageView>
    </children>
</AnchorPane>

Specifying the backgroundLoading property in the Image tag is optional, it defaults to false. It's best to set backgroundLoading true when it takes a moment or longer to load the image, that way a placeholder will be used until the image loads, and the program wont freeze while loading.

What is causing this error - "Fatal error: Unable to find local grunt"

I think you don't have a grunt.js file in your project directory. Use grunt:init, which gives you options such as jQuery, node,commonjs. Select what you want, then proceed. This really works. For more information you can visit this.

Do this:

 1. npm install -g grunt
 2. grunt:init  ( you will get following options ):
      jquery: A jQuery plugin
      node: A Node module
      commonjs: A CommonJS module
      gruntplugin: A Grunt plugin
      gruntfile: A Gruntfile (grunt.js)
 3 .grunt init:jquery (if you want to create a jQuery related project.).

It should work.

Solution for v1.4:

1. npm install -g grunt-cli
2. npm init
   fill all details and it will create a package.json file.
3. npm install grunt (for grunt dependencies.)

Edit : Updated solution for new versions:

 npm install grunt --save-dev

How do I get first name and last name as whole name in a MYSQL query?

rtrim(lastname)+','+rtrim(firstname) as [Person Name]
from Table

the result will show lastname,firstname as one column header !

Get local href value from anchor (a) tag

The href property sets or returns the value of the href attribute of a link.

  var hello = domains[i].getElementsByTagName('a')[0].getAttribute('href');
    var url="https://www.google.com/";
    console.log( url+hello);

What is the difference between _tmain() and main() in C++?

the _T convention is used to indicate the program should use the character set defined for the application (Unicode, ASCII, MBCS, etc.). You can surround your strings with _T( ) to have them stored in the correct format.

 cout << _T( "There are " ) << argc << _T( " arguments:" ) << endl;

What is the meaning of curly braces?

In languages like C curly braces ({}) are used to create program blocks used in flow control. In Python, curly braces are used to define a data structure called a dictionary (a key/value mapping), while white space indentation is used to define program blocks.

Bind event to right mouse click

document.oncontextmenu = function() {return false;}; //disable the browser context menu
$('selector-name')[0].oncontextmenu = function(){} //set jquery element context menu 

Google Maps API throws "Uncaught ReferenceError: google is not defined" only when using AJAX

I know this answer is not directly related to this questions' issue but in some cases the "Uncaught ReferenceError: google is not defined" issue will occur if your js file is being called prior to the google maps api you're using...so DON'T DO this:

<script type ="text/javascript" src ="SomeJScriptfile.js"></script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>

Display Two <div>s Side-by-Side

Try to Use Flex as that is the new standard of html5.

http://jsfiddle.net/maxspan/1b431hxm/

<div id="row1">
    <div id="column1">I am column one</div>
    <div id="column2">I am column two</div>
</div>

#row1{
    display:flex;
    flex-direction:row;
justify-content: space-around;
}

#column1{
    display:flex;
    flex-direction:column;

}


#column2{
    display:flex;
    flex-direction:column;
}

How to get the size of a range in Excel

The overall dimensions of a range are in its Width and Height properties.

Dim r As Range
Set r = ActiveSheet.Range("A4:H12")

Debug.Print r.Width
Debug.Print r.Height

How do I get the total Json record count using JQuery?

What you're looking for is

j.d.length

The d is the key. At least it is in my case, I'm using a .NET webservice.

 $.ajax({
            type: "POST",
            url: "CantTellU.asmx",
            data: "{'userID' : " + parseInt($.query.get('ID')) + " }",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(msg, status) {
                ApplyTemplate(msg);
                alert(msg.d.length);
            }
        });

How to add include path in Qt Creator?

For anyone completely new to Qt Creator like me, you can modify your project's .pro file from within Qt Creator:

enter image description here

Just double-click on "your project name".pro in the Projects window and add the include path at the bottom of the .pro file like I've done.

Winforms TableLayoutPanel adding rows programmatically

Create a table layout panel with two columns in your form and name it tlpFields.

Then, simply add new control to table layout panel (in this case I added 5 labels in column-1 and 5 textboxes in column-2).

tlpFields.RowStyles.Clear();  //first you must clear rowStyles

for (int ii = 0; ii < 5; ii++)
{
    Label l1= new Label();
    TextBox t1 = new TextBox();

    l1.Text = "field : ";

    tlpFields.Controls.Add(l1, 0, ii);  // add label in column0
    tlpFields.Controls.Add(t1, 1, ii);  // add textbox in column1

    tlpFields.RowStyles.Add(new RowStyle(SizeType.Absolute,30)); // 30 is the rows space
}

Finally, run the code.

Java Calendar, getting current month value, clarification needed

Calendar.getInstance().get(Calendar.MONTH);

is zero based, 10 is November. From the javadoc;

public static final int MONTH Field number for get and set indicating the month. This is a calendar-specific value. The first month of the year in the Gregorian and Julian calendars is JANUARY which is 0; the last depends on the number of months in a year.

Calendar.getInstance().get(Calendar.JANUARY);

is not a sensible thing to do, the value for JANUARY is 0, which is the same as ERA, you are effectively calling;

Calendar.getInstance().get(Calendar.ERA);

What happens to a declared, uninitialized variable in C? Does it have a value?

That depends. If that definition is global (outside any function) then num will be initialized to zero. If it's local (inside a function) then its value is indeterminate. In theory, even attempting to read the value has undefined behavior -- C allows for the possibility of bits that don't contribute to the value, but have to be set in specific ways for you to even get defined results from reading the variable.

In NetBeans how do I change the Default JDK?

If I remember correctly, you'll need to set the netbeans_jdkhome property in your netbeans config file. Should be in your etc/netbeans.conf file.

How can I get enum possible values in a MySQL database?

Here is the same function given by Patrick Savalle adapted for the framework Laravel

function get_enum_values($table, $field)
{

   $test=DB::select(DB::raw("show columns from {$table} where field = '{$field}'"));

   preg_match('/^enum\((.*)\)$/', $test[0]->Type, $matches);
   foreach( explode(',', $matches[1]) as $value )
   {
       $enum[] = trim( $value, "'" );   
   }

   return $enum;

}

Random element from string array

Just store the index generated in a variable, and then access the array using this varaible:

int idx = new Random().nextInt(fruits.length);
String random = (fruits[idx]);

P.S. I usually don't like generating new Random object per randoization - I prefer using a single Random in the program - and re-use it. It allows me to easily reproduce a problematic sequence if I later find any bug in the program.

According to this approach, I will have some variable Random r somewhere, and I will just use:

int idx = r.nextInt(fruits.length)

However, your approach is OK as well, but you might have hard time reproducing a specific sequence if you need to later on.

Increasing Google Chrome's max-connections-per-server limit to more than 6

IE is even worse with 2 connection per domain limit. But I wouldn't rely on fixing client browsers. Even if you have control over them, browsers like chrome will auto update and a future release might behave differently than you expect. I'd focus on solving the problem within your system design.

Your choices are to:

  1. Load the images in sequence so that only 1 or 2 XHR calls are active at a time (use the success event from the previous image to check if there are more images to download and start the next request).

  2. Use sub-domains like serverA.myphotoserver.com and serverB.myphotoserver.com. Each sub domain will have its own pool for connection limits. This means you could have 2 requests going to 5 different sub-domains if you wanted to. The downfall is that the photos will be cached according to these sub-domains. BTW, these don't need to be "mirror" domains, you can just make additional DNS pointers to the exact same website/server. This means you don't have the headache of administrating many servers, just one server with many DNS records.

How to make a <div> appear in front of regular text/tables

You can use the stacking index of the div to make it appear on top of anything else. Make it a larger value that other elements and it well be on top of others.

use z-index property. See Specifying the stack level: the 'z-index' property and

Elaborate description of Stacking Contexts

Something like

#divOnTop { z-index: 1000; }

<div id="divOnTop">I am on top</div>

What you have to look out for will be IE6. In IE 6 some elements like <select> will be placed on top of an element with z-index value higher than the <select>. You can have a workaround for this by placing an <iframe> behind the div.

See this Internet Explorer z-index bug?

Android ADB device offline, can't issue commands

Most likely this is due to an out dated adb process. This may happen due to crappy developers who package adb, the dlls and install them in the root directory of Windows. Such as C:\Windows\adb.exe

Open task manager kill adb.exe, located the adb.exe most likely in root:\Windows and remove it. Then use an up to date SDK

How to get HTTP response code for a URL in Java?

This is what worked for me:

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

public class UrlHelpers {

    public static int getHTTPResponseStatusCode(String u) throws IOException {

        URL url = new URL(u);
        HttpURLConnection http = (HttpURLConnection)url.openConnection();
        return http.getResponseCode();
    }
}

Hope this helps someone :)

How to replace all dots in a string using JavaScript

var mystring = 'okay.this.is.a.string';
var myNewString = escapeHtml(mystring);

function escapeHtml(text) {
if('' !== text) {
    return text.replace(/&amp;/g, "&")
               .replace(/&lt;/g, "<")
               .replace(/&gt;/g, ">")
               .replace(/\./g,' ')
               .replace(/&quot;/g, '"')
               .replace(/&#39/g, "'");
} 

Array Length in Java

if you mean by "logical size", the index of array, then simply int arrayLength = arr.length-1; since the the array index starts with "0", so the logical or "array index" will always be less than the actual size by "one".

Unable to load DLL (Module could not be found HRESULT: 0x8007007E)

I faced the same problem when import C++ Dll in .Net Framework +4, I unchecked Project->Properties->Build->Prefer 32-bit and it solved for me.

How to edit the legend entry of a chart in Excel?

The data series names are defined by the column headers. Add the names to the column headers that you would like to use as titles for each of your data series, select all of the data (including the headers), then re-generate your graph. The names in the headers should then appear as the names in the legend for each series.

Column headers become data series titles in graph legend

How to break long string to multiple lines

You cannot use the VB line-continuation character inside of a string.

SqlQueryString = "Insert into Employee values(" & txtEmployeeNo.Value & _
"','" & txtContractStartDate.Value &  _
"','" & txtSeatNo.Value & _
"','" & txtFloor.Value & "','" & txtLeaves.Value & "')"

Convert dictionary values into array

If you would like to use linq, so you can try following:

Dictionary<string, object> dict = new Dictionary<string, object>();
var arr = dict.Select(z => z.Value).ToArray();

I don't know which one is faster or better. Both work for me.

How to plot a subset of a data frame in R?

This chunk should do the work:

plot(var2 ~ var1, data=subset(dataframe, var3 < 150))

My best regards.

How this works:

  1. Fisrt, we make selection using the subset function. Other possibilities can be used, like, subset(dataframe, var4 =="some" & var5 > 10). The "&" operator can be used to select all "some" and over 10. Also the operator "|" could be used to select "some" or "over 10".
  2. The next step is to plot the results of the subset, using tilde (~) operator, that just imply a formula, in this case var.response ~ var.independet. Of course this is not a formula, but works great for this case.

Finding the id of a parent div using Jquery

To get the id of the parent div:

$(buttonSelector).parents('div:eq(0)').attr('id');

Also, you can refactor your code quite a bit:

$('button').click( function() {
 var correct = Number($(this).attr('rel'));
 validate(Number($(this).siblings('input').val()), correct);
 $(this).parents('div:eq(0)').html(feedback);
});

Now there is no need for a button-class

explanation
eq(0), means that you will select one element from the jQuery object, in this case element 0, thus the first element. http://docs.jquery.com/Selectors/eq#index
$(selector).siblings(siblingsSelector) will select all siblings (elements with the same parent) that match the siblingsSelector http://docs.jquery.com/Traversing/siblings#expr
$(selector).parents(parentsSelector) will select all parents of the elements matched by selector that match the parent selector. http://docs.jquery.com/Traversing/parents#expr
Thus: $(selector).parents('div:eq(0)'); will match the first parent div of the elements matched by selector.

You should have a look at the jQuery docs, particularly selectors and traversing:

CRC32 C or C++ implementation

The most simple and straightforward C/C++ implementation that I found is in a link at the bottom of this page:

Web Page: http://www.barrgroup.com/Embedded-Systems/How-To/CRC-Calculation-C-Code

Code Download Link: https://barrgroup.com/code/crc.zip

It is a simple standalone implementation with one .h and one .c file. There is support for CRC32, CRC16 and CRC_CCITT thru the use of a define. Also, the code lets the user change parameter settings like the CRC polynomial, initial/final XOR value, and reflection options if you so desire.

The license is not explicitly defined ala LGPL or similar. However the site does say that they are placing the code in the public domain for any use. The actual code files also say this.

Hope it helps!

Embed a PowerPoint presentation into HTML

Try PowerPoint ActiveX 2.4. This is an ActiveX component that embeds PowerPoint into an OCX.

Since you are using just Internet Explorer 6 and Internet Explorer 7 you can embed this component into the HTML.

VBA Excel sort range by specific column

Try this code:

Dim lastrow As Long
lastrow = Cells(Rows.Count, 2).End(xlUp).Row
Range("A3:D" & lastrow).Sort key1:=Range("B3:B" & lastrow), _
   order1:=xlAscending, Header:=xlNo

how do I query sql for a latest record date for each user

From my experience the fastest way is to take each row for which there is no newer row in the table.

Another advantage is that the syntax used is very simple, and that the meaning of the query is rather easy to grasp (take all rows such that no newer row exists for the username being considered).

NOT EXISTS

SELECT username, value
FROM t
WHERE NOT EXISTS (
  SELECT *
  FROM t AS witness
  WHERE witness.username = t.username AND witness.date > t.date
);

ROW_NUMBER

SELECT username, value
FROM (
  SELECT username, value, row_number() OVER (PARTITION BY username ORDER BY date DESC) AS rn
  FROM t
) t2
WHERE rn = 1

INNER JOIN

SELECT t.username, t.value
FROM t
INNER JOIN (
  SELECT username, MAX(date) AS date
  FROM t
  GROUP BY username
) tm ON t.username = tm.username AND t.date = tm.date;

LEFT OUTER JOIN

SELECT username, value
FROM t
LEFT OUTER JOIN t AS w ON t.username = w.username AND t.date < w.date
WHERE w.username IS NULL

How to vertically align text in input type="text"?

An alternative is to use line-height: http://jsfiddle.net/DjT37/

.bigbox{
    height:40px;
    line-height:40px;
    padding:0 5px;
}

This tends to be more consistent when you want a specific height as you don't need to calculate padding based on font-size and desired height, etc.

Import regular CSS file in SCSS file?

This was implemented and merged starting from version 3.2 (pull #754 merged on 2 Jan 2015 for libsass, issues originaly were defined here: sass#193 #556, libsass#318).

To cut the long story short, the syntax in next:

  1. to import (include) the raw CSS-file

    the syntax is without .css extension at the end (results in actual read of partial s[ac]ss|css and include of it inline to SCSS/SASS):

    @import "path/to/file";

  2. to import the CSS-file in a traditional way

    syntax goes in traditional way, with .css extension at the end (results to @import url("path/to/file.css"); in your compiled CSS):

    @import "path/to/file.css";

And it is damn good: this syntax is elegant and laconic, plus backward compatible! It works excellently with libsass and node-sass.

__

To avoid further speculations in comments, writing this explicitly: Ruby based Sass still has this feature unimplemented after 7 years of discussions. By the time of writing this answer, it's promised that in 4.0 there will be a simple way to accomplish this, probably with the help of @use. It seems there will be an implementation very soon, the new "planned" "Proposal Accepted" tag was assigned for the issue #556 and the new @use feature.

answer might be updated, as soon as something changes.

Display fullscreen mode on Tkinter

root = Tk()
root.geomentry('1599x1499')

How to uncompress a tar.gz in another directory

gzip -dc archive.tar.gz | tar -xf - -C /destination

or, with GNU tar

tar xzf archive.tar.gz -C /destination

Element-wise addition of 2 lists?

This is simple with numpy.add()

import numpy

list1 = numpy.array([1, 2, 3])
list2 = numpy.array([4, 5, 6])
result = numpy.add(list1, list2) # result receive element-wise addition of list1 and list2
print(result)
array([5, 7, 9])

See doc here

If you want to receiver a python list:

result.tolist()

Java: unparseable date exception

What you're basically doing here is relying on Date#toString() which already has a fixed pattern. To convert a Java Date object into another human readable String pattern, you need SimpleDateFormat#format().

private String modifyDateLayout(String inputDate) throws ParseException{
    Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z").parse(inputDate);
    return new SimpleDateFormat("dd.MM.yyyy HH:mm:ss").format(date);
}

By the way, the "unparseable date" exception can here only be thrown by SimpleDateFormat#parse(). This means that the inputDate isn't in the expected pattern "yyyy-MM-dd HH:mm:ss z". You'll probably need to modify the pattern to match the inputDate's actual pattern.

Update: Okay, I did a test:

public static void main(String[] args) throws Exception {
    String inputDate = "2010-01-04 01:32:27 UTC";
    String newDate = new Test().modifyDateLayout(inputDate);
    System.out.println(newDate);
}

This correctly prints:

03.01.2010 21:32:27

(I'm on GMT-4)

Update 2: as per your edit, you really got a ParseException on that. The most suspicious part would then be the timezone of UTC. Is this actually known at your Java environment? What Java version and what OS version are you using? Check TimeZone.getAvailableIDs(). There must be a UTC in between.

VBA, if a string contains a certain letter

Try using the InStr function which returns the index in the string at which the character was found. If InStr returns 0, the string was not found.

If InStr(myString, "A") > 0 Then

InStr MSDN Website

For the error on the line assigning to newStr, convert oldStr.IndexOf to that InStr function also.

Left(oldStr, InStr(oldStr, "A"))

How do you disable browser Autocomplete on web form field / input tag?

As others have said, the answer is autocomplete="off"

However, I think it's worth stating why it's a good idea to use this in certain cases as some answers to this and duplicate questions have suggested it's better not to turn it off.

Stopping browsers storing credit card numbers shouldn't be left to users. Too many users won't even realize it's a problem.

It's particularly important to turn it off on fields for credit card security codes. As this page states:

"Never store the security code ... its value depends on the presumption that the only way to supply it is to read it from the physical credit card, proving that the person supplying it actually holds the card."

The problem is, if it's a public computer (cyber cafe, library etc) it's then easy for other users to steal your card details, and even on your own machine a malicious website could steal autocomplete data.

Change header background color of modal of twitter bootstrap

Add this class to your css file to override the bootstrap class.modal-header

.modal-header {
   background:#0480be;
}

It's important try to never edit Bootstrap CSS, in order to be able to update from the repo and not loose the changes made or break something in futures releases.

Specify system property to Maven project

Is there a way ( I mean how do I ) set a system property in a maven project? I want to access a property from my test [...]

You can set system properties in the Maven Surefire Plugin configuration (this makes sense since tests are forked by default). From Using System Properties:

<project>
  [...]
  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>2.5</version>
        <configuration>
          <systemPropertyVariables>
            <propertyName>propertyValue</propertyName>
            <buildDirectory>${project.build.directory}</buildDirectory>
            [...]
          </systemPropertyVariables>
        </configuration>
      </plugin>
    </plugins>
  </build>
  [...]
</project>

and my webapp ( running locally )

Not sure what you mean here but I'll assume the webapp container is started by Maven. You can pass system properties on the command line using:

mvn -DargLine="-DpropertyName=propertyValue"

Update: Ok, got it now. For Jetty, you should also be able to set system properties in the Maven Jetty Plugin configuration. From Setting System Properties:

<project>
  ...
  <plugins>
    ...
      <plugin>
        <groupId>org.mortbay.jetty</groupId>
        <artifactId>maven-jetty-plugin</artifactId>
        <configuration>
         ...
         <systemProperties>
            <systemProperty>
              <name>propertyName</name>
              <value>propertyValue</value>
            </systemProperty>
            ...
         </systemProperties>
        </configuration>
      </plugin>
  </plugins>
</project>

inherit from two classes in C#

Multitiple inheritance is not possible in C#, however it can be simulated using interfaces, see Simulated Multiple Inheritance Pattern for C#.

The basic idea is to define an interface for the members on class B that you wish to access (call it IB), and then have C inherit from A and implement IB by internally storing an instance of B, for example:

class C : A, IB
{
    private B _b = new B();

    // IB members
    public void SomeMethod()
    {
        _b.SomeMethod();
    }
}

There are also a couple of other alternaitve patterns explained on that page.

How can I enable Assembly binding logging?

If you sometimes run different versions of your application, make sure you delete 'Bla' from the application bin directory if the version running doesn't need it.

How to inherit constructors?

Too bad we're kind of forced to tell the compiler the obvious:

Subclass(): base() {}
Subclass(int x): base(x) {}
Subclass(int x,y): base(x,y) {}

I only need to do 3 constructors in 12 subclasses, so it's no big deal, but I'm not too fond of repeating that on every subclass, after being used to not having to write it for so long. I'm sure there's a valid reason for it, but I don't think I've ever encountered a problem that requires this kind of restriction.

How to convert JSON object to an Typescript array?

You have a JSON object that contains an Array. You need to access the array results. Change your code to:

this.data = res.json().results

Writing data into CSV file in C#

You might just have to add a line feed "\n\r".

What is the MySQL VARCHAR max size?

Before Mysql version 5.0.3 Varchar datatype can store 255 character, but from 5.0.3 it can be store 65,535 characters.

BUT it has a limitation of maximum row size of 65,535 bytes. It means including all columns it must not be more than 65,535 bytes.

In your case it may possible that when you are trying to set more than 10000 it is exceeding more than 65,535 and mysql will gives the error.

For more information: https://dev.mysql.com/doc/refman/5.0/en/column-count-limit.html

blog with example: http://goo.gl/Hli6G3

Error resolving template "index", template might not exist or might not be accessible by any of the configured Template Resolvers

this can be resolved by copying the below code in application.properties

spring.thymeleaf.enabled=false

How to check if all elements of a list matches a condition?

this way is a bit more flexible than using all():

my_list = [[1, 2, 0], [1, 2, 0], [1, 2, 0]]
all_zeros = False if False in [x[2] == 0 for x in my_list] else True
any_zeros = True if True in [x[2] == 0 for x in my_list] else False

or more succinctly:

all_zeros = not False in [x[2] == 0 for x in my_list]
any_zeros = 0 in [x[2] for x in my_list]

Xcode 5.1 - No architectures to compile for (ONLY_ACTIVE_ARCH=YES, active arch=x86_64, VALID_ARCHS=i386)

Just in case, for anyone still encountering the issue despite following the above, check that the simulator you are running is also the supported one. I had mine specified to arm7 and arm7s but was trying to run the app on a 64 bit simulator.

How can I create Min stl priority_queue?

In C++11 you could also create an alias for convenience:

template<class T> using min_heap = priority_queue<T, std::vector<T>, std::greater<T>>;

And use it like this:

min_heap<int> my_heap;

ERROR : [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified

If you're working with an x64 server, keep in mind that there are different ODBC settings for x86 and x64 applications. The "Data Sources (ODBC)" tool in the Administrative Tools list takes you to the x64 version. To view/edit the x86 ODBC settings, you'll need to run that version of the tool manually:

%windir%\SysWOW64\odbcad32.exe (%windir% is usually C:\Windows)

When your app runs as x64, it will use the x64 data sources, and when it runs as x86, it will use those data sources instead.

How can I invert color using CSS?

I think the only way to handle this is to use JavaScript

Try this Invert text color of a specific element

If you do this with css3 it's only compatible with the newest browser versions.

Threads vs Processes in Linux

How tightly coupled are your tasks?

If they can live independently of each other, then use processes. If they rely on each other, then use threads. That way you can kill and restart a bad process without interfering with the operation of the other tasks.

Google Maps Api v3 - find nearest markers

Use computeDistanceBetween() Google map API method to calculate near marker between your location and markers list on google map.

Steps:-

  1. Create marker on google map.
    function addMarker(location) { var marker = new google.maps.Marker({ title: 'User added marker', icon: { path: google.maps.SymbolPath.BACKWARD_CLOSED_ARROW, scale: 5 }, position: location, map: map }); }

  2. On Mouse click create event for getting lat, long of your location and pass that to find_closest_marker().

    function find_closest_marker(event) {
          var distances = [];
          var closest = -1;
          for (i = 0; i < markers.length; i++) {
            var d = google.maps.geometry.spherical.computeDistanceBetween(markers[i].position, event.latLng);
            distances[i] = d;
            if (closest == -1 || d < distances[closest]) {
              closest = i;
            }
          }
          alert('Closest marker is: ' + markers[closest].getTitle());
        }
    

visit this link follow the steps. You will able to get nearer marker to your location.

Delete duplicate records from a SQL table without a primary key

I'm not an SQL expert so bear with me. I'm sure you'll get a better answer soon enough. Here's how you can find the duplicate records.

select t1.empid, t1.empssn, count(*)
from employee as t1 
inner join employee as t2 on (t1.empid=t2.empid and t1.empssn = t2.empssn)
group by t1.empid, t1.empssn
having count(*) > 1

Deleting them will be more tricky because there is nothing in the data that you could use in a delete statement to differentiate the duplicates. I suspect the answer will involve row_number() or adding an identity column.

Creating a class object in c++

Example example;

Here example is an object on the stack.

Example* example=new Example();

This could be broken into:

Example* example;
....
example=new Example();

Here the first statement creates a variable example which is a "pointer to Example". When the constructor is called, memory is allocated for it on the heap (dynamic allocation). It is the programmer's responsibility to free this memory when it is no longer needed. (C++ does not have garbage collection like java).

How to add/subtract time (hours, minutes, etc.) from a Pandas DataFrame.Index whos objects are of type datetime.time?

Liam's link looks great, but also check out pandas.Timedelta - looks like it plays nicely with NumPy's and Python's time deltas.

https://pandas.pydata.org/pandas-docs/stable/timedeltas.html

pd.date_range('2014-01-01', periods=10) + pd.Timedelta(days=1)

Append a dictionary to a dictionary

You can do

orig.update(extra)

or, if you don't want orig to be modified, make a copy first:

dest = dict(orig)  # or orig.copy()
dest.update(extra)

Note that if extra and orig have overlapping keys, the final value will be taken from extra. For example,

>>> d1 = {1: 1, 2: 2}
>>> d2 = {2: 'ha!', 3: 3}
>>> d1.update(d2)
>>> d1
{1: 1, 2: 'ha!', 3: 3}

"Missing return statement" within if / for / while

That's because the function needs to return a value. Imagine what happens if you execute myMethod() and it doesn't go into if(condition) what would your function returns? The compiler needs to know what to return in every possible execution of your function

Checking Java documentation:

Definition: If a method declaration has a return type then there must be a return statement at the end of the method. If the return statement is not there the missing return statement error is thrown.

This error is also thrown if the method does not have a return type and has not been declared using void (i.e., it was mistakenly omitted).

You can do to solve your problem:

public String myMethod()
{
    String result = null;
    if(condition)
    {
       result = x;
    }
    return result;
}

How to limit the number of selected checkboxes?

If you want to uncheck the checkbox that you have selected first under the condition of 3 checkboxes allowed. With vanilla javascript; you need to assign onclick = "checking(this)" in your html input checkbox

var queue = [];
function checking(id){
   queue.push(id)
   if (queue.length===3){
    queue[0].checked = false
    queue.shift()
   }
}

Drop all tables command

To delete also views add 'view' keyword:

delete from sqlite_master where type in ('view', 'table', 'index', 'trigger');

Python: No acceptable C compiler found in $PATH when installing python

The gcc compiler is not in your $PATH. It means either you dont have gcc installed or it's not in your $PATH variable.

To install gcc use this: (run as root)

  • Redhat base:

    yum groupinstall "Development Tools"
    
  • Debian base:

    apt-get install build-essential
    

Pure CSS scroll animation

Use anchor links and the scroll-behavior property (MDN reference) for the scrolling container:

scroll-behavior: smooth;

Browser support: Firefox 36+, Chrome 61+ (therefore also Edge 79+) and Opera 48+.

Intenet Explorer, non-Chromium Edge and (so far) Safari do not support scroll-behavior and simply "jump" to the link target.

Example usage:

<head>
  <style type="text/css">
    html {
      scroll-behavior: smooth;
    }
  </style>
</head>
<body id="body">
  <a href="#foo">Go to foo!</a>

  <!-- Some content -->

  <div id="foo">That's foo.</div>
  <a href="#body">Back to top</a>
</body>

Here's a Fiddle.

And here's also a Fiddle with both horizontal and vertical scrolling.

WebSocket connection failed: Error during WebSocket handshake: Unexpected response code: 400

After using following load balancer setting my problem solved for wss but for ws problem still exists for specific one ISP.

calssic-load-balancer

how to convert a string to date in mysql?

http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html
use the above page to refer more Functions in MySQL

SELECT  STR_TO_DATE(StringColumn, '%d-%b-%y')
FROM    table

say for example use the below query to get output

SELECT STR_TO_DATE('23-feb-14', '%d-%b-%y') FROM table

For String format use the below link

http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-format

Remove whitespaces inside a string in javascript

You can use

"Hello World ".replace(/\s+/g, '');

trim() only removes trailing spaces on the string (first and last on the chain). In this case this regExp is faster because you can remove one or more spaces at the same time.

If you change the replacement empty string to '$', the difference becomes much clearer:

var string= '  Q  W E   R TY ';
console.log(string.replace(/\s/g, '$'));  // $$Q$$W$E$$$R$TY$
console.log(string.replace(/\s+/g, '#')); // #Q#W#E#R#TY#

Performance comparison - /\s+/g is faster. See here: http://jsperf.com/s-vs-s

C# Switch-case string starting with

Try this and tell my if it works hope it help you:

string value = Convert.ToString(Console.ReadLine());

Switch(value)
{
    Case "abc":

    break;

    default:

    break;
}       

PHP cURL custom headers

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'X-Apple-Tz: 0',
    'X-Apple-Store-Front: 143444,12'
));

http://www.php.net/manual/en/function.curl-setopt.php

Android: How to create a Dialog without a title?

olivierg's answer worked for me and is the best solution if creating a custom Dialog class is the route you want to go. However, it bothered me that I couldn't use the AlertDialog class. I wanted to be able to use the default system AlertDialog style. Creating a custom dialog class would not have this style.

So I found a solution (hack) that will work without having to create a custom class, you can use the existing builders.

The AlertDialog puts a View above your content view as a placeholder for the title. If you find the view and set the height to 0, the space goes away.

I have tested this on 2.3 and 3.0 so far, it is possible it doesn't work on every version yet.

Here are two helper methods for doing it:

/**
 * Show a Dialog with the extra title/top padding collapsed.
 * 
 * @param customView The custom view that you added to the dialog
 * @param dialog The dialog to display without top spacing
     * @param show Whether or not to call dialog.show() at the end.
 */
public static void showDialogWithNoTopSpace(final View customView, final Dialog dialog, boolean show) {
    // Now we setup a listener to detect as soon as the dialog has shown.
    customView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {

        @Override
        public void onGlobalLayout() {
            // Check if your view has been laid out yet
            if (customView.getHeight() > 0) {
                // If it has been, we will search the view hierarchy for the view that is responsible for the extra space. 
                LinearLayout dialogLayout = findDialogLinearLayout(customView);
                if (dialogLayout == null) {
                    // Could find it. Unexpected.

                } else {
                    // Found it, now remove the height of the title area
                    View child = dialogLayout.getChildAt(0);
                    if (child != customView) {
                        // remove height
                        LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) child.getLayoutParams();
                        lp.height = 0;
                        child.setLayoutParams(lp);

                    } else {
                        // Could find it. Unexpected.
                    }
                }

                // Done with the listener
                customView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
            }
         }

    });

    // Show the dialog
    if (show)
             dialog.show();
}

/**
 * Searches parents for a LinearLayout
 * 
 * @param view to search the search from
 * @return the first parent view that is a LinearLayout or null if none was found
 */
public static LinearLayout findDialogLinearLayout(View view) {
    ViewParent parent = (ViewParent) view.getParent();
    if (parent != null) {
        if (parent instanceof LinearLayout) {
            // Found it
            return (LinearLayout) parent;

        } else if (parent instanceof View) {
            // Keep looking
            return findDialogLinearLayout((View) parent);

        }
    }

    // Couldn't find it
    return null;
}

Here is an example of how it is used:

    Dialog dialog = new AlertDialog.Builder(this)
        .setView(yourCustomView)
        .create();

    showDialogWithNoTopSpace(yourCustomView, dialog, true);

If you are using this with a DialogFragment, override the DialogFragment's onCreateDialog method. Then create and return your dialog like the first example above. The only change is that you should pass false as the 3rd parameter (show) so that it doesn't call show() on the dialog. The DialogFragment will handle that later.

Example:

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    Dialog dialog = new AlertDialog.Builder(getContext())
        .setView(yourCustomView)
        .create();

    showDialogWithNoTopSpace(yourCustomView, dialog, false);
    return dialog;
}

As I test this further I'll be sure to update with any additional tweaks needed.

Examples of Algorithms which has O(1), O(n log n) and O(log n) complexities

A simple example of O(1) might be return 23; -- whatever the input, this will return in a fixed, finite time.

A typical example of O(N log N) would be sorting an input array with a good algorithm (e.g. mergesort).

A typical example if O(log N) would be looking up a value in a sorted input array by bisection.

open_basedir restriction in effect. File(/) is not within the allowed path(s):

The path you're refering to is incorect, and not withing the directoryRoot of your workspace. Try building an absolute path the the file you want to access, where you are now probably using a relative path...

Python + Regex: AttributeError: 'NoneType' object has no attribute 'groups'

You are getting AttributeError because you're calling groups on None, which hasn't any methods.

regex.search returning None means the regex couldn't find anything matching the pattern from supplied string.

when using regex, it is nice to check whether a match has been made:

Result = re.search(SearchStr, htmlString)

if Result:
    print Result.groups()

git status shows modifications, git checkout -- <file> doesn't remove them

Having consistent line endings is a good thing. For example it will not trigger unnecessary merges, albeit trivial. I have seen Visual Studio create files with mixed line endings.

Also some programs like bash (on linux) do require that .sh files are LF terminated.

To make sure this happens you can use gitattributes. It works on repository level no matter what the value of autcrlf is.

For example you can have .gitattributes like this: * text=auto

You can also be more specific per file type/extension if it did matter in your case.

Then autocrlf can convert line endings for Windows programs locally.

On a mixed C#/C++/Java/Ruby/R, Windows/Linux project this is working well. No issues so far.

Why doesn't java.util.Set have get(int index)?

The only reason I can think of for using a numerical index in a set would be for iteration. For that, use

for(A a : set) { 
   visit(a); 
}

How do I free my port 80 on localhost Windows?

You can use net stop http it will display which process is using. Moslty world wide web services are using

Creating a new empty branch for a new project

You can create a branch as an orphan:

git checkout --orphan <branchname>

This will create a new branch with no parents. Then, you can clear the working directory with:

git rm --cached -r .

and add the documentation files, commit them and push them up to github.

A pull or fetch will always update the local information about all the remote branches. If you only want to pull/fetch the information for a single remote branch, you need to specify it.

Table with table-layout: fixed; and how to make one column wider

You could just give the first cell (therefore column) a width and have the rest default to auto

_x000D_
_x000D_
table {_x000D_
  table-layout: fixed;_x000D_
  border-collapse: collapse;_x000D_
  width: 100%;_x000D_
}_x000D_
td {_x000D_
  border: 1px solid #000;_x000D_
  width: 150px;_x000D_
}_x000D_
td+td {_x000D_
  width: auto;_x000D_
}
_x000D_
<table>_x000D_
  <tr>_x000D_
    <td>150px</td>_x000D_
    <td>equal</td>_x000D_
    <td>equal</td>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_


or alternatively the "proper way" to get column widths might be to use the col element itself

_x000D_
_x000D_
table {_x000D_
  table-layout: fixed;_x000D_
  border-collapse: collapse;_x000D_
  width: 100%;_x000D_
}_x000D_
td {_x000D_
  border: 1px solid #000;_x000D_
}_x000D_
.wide {_x000D_
  width: 150px;_x000D_
}
_x000D_
<table>_x000D_
  <col span="1" class="wide">_x000D_
    <tr>_x000D_
      <td>150px</td>_x000D_
      <td>equal</td>_x000D_
      <td>equal</td>_x000D_
    </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

How to reset or change the passphrase for a GitHub SSH key?

You can change the passphrase for your private key by doing:

ssh-keygen -f ~/.ssh/id_rsa -p

PHP cURL HTTP CODE return 0

Try this after curl_exec to see what's the problem:

print curl_error($ch);

If it's print something like 'malformed' then check your URL format.

Boolean Field in Oracle

I found this link useful.

Here is the paragraph highlighting some of the pros/cons of each approach.

The most commonly seen design is to imitate the many Boolean-like flags that Oracle's data dictionary views use, selecting 'Y' for true and 'N' for false. However, to interact correctly with host environments, such as JDBC, OCCI, and other programming environments, it's better to select 0 for false and 1 for true so it can work correctly with the getBoolean and setBoolean functions.

Basically they advocate method number 2, for efficiency's sake, using

  • values of 0/1 (because of interoperability with JDBC's getBoolean() etc.) with a check constraint
  • a type of CHAR (because it uses less space than NUMBER).

Their example:

create table tbool (bool char check (bool in (0,1));
insert into tbool values(0);
insert into tbool values(1);`

flow 2 columns of text automatically with CSS

Using jQuery

Create a second column and move over the elements you need into it.

<script type="text/javascript">
  $(document).ready(function() {
    var size = $("#data > p").size();
 $(".Column1 > p").each(function(index){
  if (index >= size/2){
   $(this).appendTo("#Column2");
  }
 });
  });
</script>

<div id="data" class="Column1" style="float:left;width:300px;">
<!--   data Start -->
<p>This is paragraph 1. Lorem ipsum ... </p>
<p>This is paragraph 2. Lorem ipsum ... </p>
<p>This is paragraph 3. Lorem ipsum ... </p>
<p>This is paragraph 4. Lorem ipsum ... </p>
<p>This is paragraph 5. Lorem ipsum ... </p>
<p>This is paragraph 6. Lorem ipsum ... </p>
<!--   data Emd-->
</div>
<div id="Column2" style="float:left;width:300px;"></div>

Update:

Or Since the requirement now is to have them equally sized. I would suggest using the prebuilt jQuery plugins: Columnizer jQuery Plugin

http://jsfiddle.net/dPUmZ/1/

how to make a new line in a jupyter markdown cell

The double space generally works well. However, sometimes the lacking newline in the PDF still occurs to me when using four pound sign sub titles #### in Jupyter Notebook, as the next paragraph is put into the subtitle as a single paragraph. No amount of double spaces and returns fixed this, until I created a notebook copy 'v. PDF' and started using a single backslash '\' which also indents the next paragraph nicely:

#### 1.1 My Subtitle  \

1.1 My Subtitle
    Next paragraph text.

An alternative to this, is to upgrade the level of your four # titles to three # titles, etc. up the title chain, which will remove the next paragraph indent and format the indent of the title itself (#### My Subtitle ---> ### My Subtitle).

### My Subtitle


1.1 My Subtitle

Next paragraph text.

Android SDK manager won't open

In the latest version of the Android SDK, running "SDK Manager.exe" and/or "AVD Manager.exe" will not open anymore. Even the "Launch Standalone SDK Manager" link in Android Studio, which can be previously found in Android SDK Settings, is now gone.

It is now recommended to perform manual SDK and AVD management inside Android Studio. But for those who do not have an Android Studio or for those who do not like to open Android Studio just to perform SDK management, you can still manage the SDK using the command line tools, "tools/bin/sdkmanager.bat" and "tools/bin/avdmanager.bat".

This information is available when running "tools/android.bat". I think this is true for those who currently have Android SDK tooks v25.3.1 and above.

Consider marking event handler as 'passive' to make the page more responsive

For those receiving this warning for the first time, it is due to a bleeding edge feature called Passive Event Listeners that has been implemented in browsers fairly recently (summer 2016). From https://github.com/WICG/EventListenerOptions/blob/gh-pages/explainer.md:

Passive event listeners are a new feature in the DOM spec that enable developers to opt-in to better scroll performance by eliminating the need for scrolling to block on touch and wheel event listeners. Developers can annotate touch and wheel listeners with {passive: true} to indicate that they will never invoke preventDefault. This feature shipped in Chrome 51, Firefox 49 and landed in WebKit. For full official explanation read more here.

See also: What are passive event listeners?

You may have to wait for your .js library to implement support.

If you are handling events indirectly via a JavaScript library, you may be at the mercy of that particular library's support for the feature. As of December 2019, it does not look like any of the major libraries have implemented support. Some examples:

What are the differences between Abstract Factory and Factory design patterns?

Real Life Example. (Easy to remember)

Factory

Imagine you are constructing a house and you approach a carpenter for a door. You give the measurement for the door and your requirements, and he will construct a door for you. In this case, the carpenter is a factory of doors. Your specifications are inputs for the factory, and the door is the output or product from the factory.

Abstract Factory

Now, consider the same example of the door. You can go to a carpenter, or you can go to a plastic door shop or a PVC shop. All of them are door factories. Based on the situation, you decide what kind of factory you need to approach. This is like an Abstract Factory.

I have explained here both Factory method pattern and abstract factory pattern beginning with not using them explaining issues and then solving issues by using the above patterns https://github.com/vikramnagineni/Design-Patterns/tree/master

How many files can I put in a directory?

The biggest issue I've run into is on a 32-bit system. Once you pass a certain number, tools like 'ls' stop working.

Trying to do anything with that directory once you pass that barrier becomes a huge problem.

Is there a way to rollback my last push to Git?

Since you are the only user:

git reset --hard HEAD@{1}
git push -f
git reset --hard HEAD@{1}

( basically, go back one commit, force push to the repo, then go back again - remove the last step if you don't care about the commit )

Without doing any changes to your local repo, you can also do something like:

git push -f origin <sha_of_previous_commit>:master

Generally, in published repos, it is safer to do git revert and then git push

How do I change the background color of the ActionBar of an ActionBarActivity using XML?

Use this, it would work.

ActionBar actionbar = getActionBar();
actionbar.setBackgroundDrawable(new ColorDrawable("color"));

How to use SVG markers in Google Maps API v3

I know this post is a bit old, but I have seen so much bad information on this at SO that I could scream. So I just gotta throw my two cents in with a whole different approach that I know works, as I use it reliably on many maps. Besides that, I believe the OP wanted the ability to rotate the arrow marker around the map point as well, which is different than rotating the icon around it's own x,y axis which will change where the arrow marker points to on the map.

First, remember we are playing with Google maps and SVG, so we must accomodate the way in which Google deploys it's implementation of SVG for markers (or actually symbols). Google sets its anchor for the SVG marker image at 0,0 which IS NOT the upper left corner of the SVG viewBox. In order to get around this, you must draw your SVG image a bit differently to give Google what it wants... yes the answer is in the way you actually create the SVG path in your SVG editor (Illustrator, Inkscape, etc...).

The first step, is to get rid of the viewBox. This can be done by setting the viewBox in your XML to 0... that's right, just one zero instead of the usual four arguments for the viewBox. This turns the view box off (and yes, this is semantically correct). You will probably notice the size of your image jump immeadiately when you do this, and that is because the svg no longer has a base (the viewBox) to scale the image. So we create that reference directly, by setting the width and height to the actual number of pixels you wish your image to be in the XML editor of your SVG editor.

By setting the width and height of the svg image in the XML editor you create a baseline for scaling of the image, and this size becomes a value of 1 for the marker scale properties by default. You can see the advantage this has for dynamic scaling of the marker.

Now that you have your image sized, move the image until the part of the image you wish to have as the anchor is over the 0,0 coordinates of the svg editor. Once you have done this copy the value of the d attribute of the svg path. You will notice about half of the numbers are negative, which is the result of aligning your anchor point for the 0,0 of the image instead of the viewBox.

Using this technique will then let you rotate the marker correctly, around the lat and lng point on the map. This is the only reliable way to bind the point on the svg marker you want to the lat and long of the marker location.

I tried to make a JSFiddle for this, but there is some bug in there implementation, one of the reasons I am not so fond of reinterpreted code. So instead, I have included a fully self-contained example below that you can try out, adapt, and use as a reference. This is the same code I tried at JSFiddle that failed, yet it sails through Firebug without a whimper.

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="utf-8" />
    <meta name="viewport"  content="width=device-width, initial-scale=1" />
    <meta name="author"    content="Drew G. Stimson, Sr. ( Epiphany )" />
    <title>Create Draggable and Rotatable SVG Marker</title>
    <script src="http://maps.googleapis.com/maps/api/js?sensor=false"> </script>
    <style type="text/css">
      #document_body {
        margin:0;
        border: 0;
        padding: 10px;
        font-family: Arial,sans-serif;
        font-size: 14px;
        font-weight: bold;
        color: #f0f9f9;
        text-align: center;
        text-shadow: 1px 1px 1px #000;
        background:#1f1f1f;
      }
      #map_canvas, #rotation_control {
        margin: 1px;
        border:1px solid #000;
        background:#444;
        -webkit-border-radius: 4px;
           -moz-border-radius: 4px;
                border-radius: 4px;
      }
      #map_canvas { 
        width: 100%;
        height: 360px;
      }
      #rotation_control { 
        width: auto;
        padding:5px;
      }
      #rotation_value { 
        margin: 1px;
        border:1px solid #999;
        width: 60px;
        padding:2px;
        font-weight: bold;
        color: #00cc00;
        text-align: center;
        background:#111;
        border-radius: 4px;
      }
</style>

<script type="text/javascript">
  var map, arrow_marker, arrow_options;
  var map_center = {lat:41.0, lng:-103.0};
  var arrow_icon = {
    path: 'M -1.1500216e-4,0 C 0.281648,0 0.547084,-0.13447 0.718801,-0.36481 l 17.093151,-22.89064 c 0.125766,-0.16746 0.188044,-0.36854 0.188044,-0.56899 0,-0.19797 -0.06107,-0.39532 -0.182601,-0.56215 -0.245484,-0.33555 -0.678404,-0.46068 -1.057513,-0.30629 l -11.318243,4.60303 0,-26.97635 C 5.441639,-47.58228 5.035926,-48 4.534681,-48 l -9.06959,0 c -0.501246,0 -0.906959,0.41772 -0.906959,0.9338 l 0,26.97635 -11.317637,-4.60303 c -0.379109,-0.15439 -0.812031,-0.0286 -1.057515,0.30629 -0.245483,0.33492 -0.244275,0.79809 0.0055,1.13114 L -0.718973,-0.36481 C -0.547255,-0.13509 -0.281818,0 -5.7002158e-5,0 Z',
    strokeColor: 'black',
    strokeOpacity: 1,
    strokeWeight: 1,
    fillColor: '#fefe99',
    fillOpacity: 1,
    rotation: 0,
    scale: 1.0
  };

function init(){
  map = new google.maps.Map(document.getElementById('map_canvas'), {
    center: map_center,
    zoom: 4,
    mapTypeId: google.maps.MapTypeId.HYBRID
  });
  arrow_options = {
    position: map_center,
    icon: arrow_icon,
    clickable: false,
    draggable: true,
    crossOnDrag: true,
    visible: true,
    animation: 0,
    title: 'I am a Draggable-Rotatable Marker!' 
  };
  arrow_marker = new google.maps.Marker(arrow_options);
  arrow_marker.setMap(map);
}
function setRotation(){
  var heading = parseInt(document.getElementById('rotation_value').value);
  if (isNaN(heading)) heading = 0;
  if (heading < 0) heading = 359;
  if (heading > 359) heading = 0;
  arrow_icon.rotation = heading;
  arrow_marker.setOptions({icon:arrow_icon});
  document.getElementById('rotation_value').value = heading;
}
</script>
</head>
<body id="document_body" onload="init();">
  <div id="rotation_control">
    <small>Enter heading to rotate marker&nbsp;&nbsp;&nbsp;&nbsp;</small>
    Heading&deg;<input id="rotation_value" type="number" size="3" value="0" onchange="setRotation();" />
    <small>&nbsp;&nbsp;&nbsp;&nbsp;Drag marker to place marker</small>
    </div>
    <div id="map_canvas"></div>
</body>
</html>

This is exactly what Google does for it's own few symbols available in the SYMBOL class of the Maps API, so if that doesn't convince you... Anyway, I hope this will help you to correctly make and set up a SVG marker for your Google maps endevours.

Calling a function every 60 seconds

Call a Javascript function every 2 second continuously for 10 second.

_x000D_
_x000D_
var intervalPromise;_x000D_
$scope.startTimer = function(fn, delay, timeoutTime) {_x000D_
    intervalPromise = $interval(function() {_x000D_
        fn();_x000D_
        var currentTime = new Date().getTime() - $scope.startTime;_x000D_
        if (currentTime > timeoutTime){_x000D_
            $interval.cancel(intervalPromise);_x000D_
          }                  _x000D_
    }, delay);_x000D_
};_x000D_
_x000D_
$scope.startTimer(hello, 2000, 10000);_x000D_
_x000D_
hello(){_x000D_
  console.log("hello");_x000D_
}
_x000D_
_x000D_
_x000D_

Convert SVG to PNG in Python

Actually, I did not want to be dependent of anything else but Python (Cairo, Ink.., etc.) My requirements were to be as simple as possible, at most, a simple pip install "savior" would suffice, that's why any of those above didn't suit for me.

I came through this (going further than Stackoverflow on the research). https://www.tutorialexample.com/best-practice-to-python-convert-svg-to-png-with-svglib-python-tutorial/

Looks good, so far. So I share it in case anyone in the same situation.

How to install requests module in Python 3.4, instead of 2.7

i just reinstalled the pip and it works, but I still wanna know why it happened...

i used the apt-get remove --purge python-pip after I just apt-get install pyhton-pip and it works, but don't ask me why...

What's the console.log() of java?

public class Console {

    public static void Log(Object obj){
        System.out.println(obj);
    }
}

to call and use as JavaScript just do this:

Console.Log (Object)

I think that's what you mean

Angular 2: 404 error occur when I refresh through the browser

In fact, it's normal that you have a 404 error when refreshing your application since the actual address within the browser is updating (and without # / hashbang approach). By default, HTML5 history is used for reusing in Angular2.

To fix the 404 error, you need to update your server to serve the index.html file for each route path you defined.

If you want to switch to the HashBang approach, you need to use this configuration:

import {bootstrap} from 'angular2/platform/browser';
import {provide} from 'angular2/core';
import {ROUTER_PROVIDERS} from 'angular2/router';
import {LocationStrategy, HashLocationStrategy} from '@angular/common';

import {MyApp} from './myapp';

bootstrap(MyApp, [
  ROUTER_PROVIDERS,
  {provide: LocationStrategy, useClass: HashLocationStrategy}
]);

In this case, when you refresh the page, it will be displayed again (but you will have a # in your address).

This link could help you as well: When I refresh my website I get a 404. This is with Angular2 and firebase.

Hope it helps you, Thierry

What's the best practice to "git clone" into an existing folder?

If you are using at least git 1.7.7 (which taught clone the --config option), to turn the current directory into a working copy:

git clone example.com/my.git ./.git --mirror --config core.bare=false

This works by:

  • Cloning the repository into a new .git folder
  • --mirror makes the new clone into a purely metadata folder as .git needs to be
  • --config core.bare=false countermands the implicit bare=true of the --mirror option, thereby allowing the repository to have an associated working directory and act like a normal clone

This obviously won't work if a .git metadata directory already exists in the directory you wish to turn into a working copy.

ASP.Net MVC Redirect To A Different View

 if (true)
 {
   return View();
 }
 else
 {
   return View("another view name");
 }

Javascript switch vs. if...else if...else

Sometimes it's better to use neither. For example, in a "dispatch" situation, Javascript lets you do things in a completely different way:

function dispatch(funCode) {
  var map = {
    'explode': function() {
      prepExplosive();
      if (flammable()) issueWarning();
      doExplode();
    },

    'hibernate': function() {
      if (status() == 'sleeping') return;
      // ... I can't keep making this stuff up
    },
    // ...
  };

  var thisFun = map[funCode];
  if (thisFun) thisFun();
}

Setting up multi-way branching by creating an object has a lot of advantages. You can add and remove functionality dynamically. You can create the dispatch table from data. You can examine it programmatically. You can build the handlers with other functions.

There's the added overhead of a function call to get to the equivalent of a "case", but the advantage (when there are lots of cases) of a hash lookup to find the function for a particular key.

How to scale down a range of numbers with a known min and max value

Here's how I understand it:


What percent does x lie in a range

Let's assume you have a range from 0 to 100. Given an arbitrary number from that range, what "percent" from that range does it lie in? This should be pretty simple, 0 would be 0%, 50 would be 50% and 100 would be 100%.

Now, what if your range was 20 to 100? We cannot apply the same logic as above (divide by 100) because:

20 / 100

doesn't give us 0 (20 should be 0% now). This should be simple to fix, we just need to make the numerator 0 for the case of 20. We can do that by subtracting:

(20 - 20) / 100

However, this doesn't work for 100 anymore because:

(100 - 20) / 100

doesn't give us 100%. Again, we can fix this by subtracting from the denominator as well:

(100 - 20) / (100 - 20)

A more generalized equation for finding out what % x lies in a range would be:

(x - MIN) / (MAX - MIN)

Scale range to another range

Now that we know what percent a number lies in a range, we can apply it to map the number to another range. Let's go through an example.

old range = [200, 1000]
new range = [10, 20]

If we have a number in the old range, what would the number be in the new range? Let's say the number is 400. First, figure out what percent 400 is within the old range. We can apply our equation above.

(400 - 200) / (1000 - 200) = 0.25

So, 400 lies in 25% of the old range. We just need to figure out what number is 25% of the new range. Think about what 50% of [0, 20] is. It would be 10 right? How did you arrive at that answer? Well, we can just do:

20 * 0.5 = 10

But, what about from [10, 20]? We need to shift everything by 10 now. eg:

((20 - 10) * 0.5) + 10

a more generalized formula would be:

((MAX - MIN) * PERCENT) + MIN

To the original example of what 25% of [10, 20] is:

((20 - 10) * 0.25) + 10 = 12.5

So, 400 in the range [200, 1000] would map to 12.5 in the range [10, 20]


TLDR

To map x from old range to new range:

OLD PERCENT = (x - OLD MIN) / (OLD MAX - OLD MIN)
NEW X = ((NEW MAX - NEW MIN) * OLD PERCENT) + NEW MIN

A failure occurred while executing com.android.build.gradle.internal.tasks

I got an stacktrace similar to yours only when building to Lollipop or Marshmallow, and the solution was to disable Advanved profiling.

Find it here:

Run -> Edit Configurations -> Profiling -> Enable advanced profiling

https://stackoverflow.com/a/58029739/860488

What are named pipes?

Unix and Windows both have things called "Named pipes", but they behave differently. On Unix, a named pipe is a one-way street which typically has just one reader and one writer - the writer writes, and the reader reads, you get it?

On Windows, the thing called a "Named pipe" is an IPC object more like a TCP socket - things can flow both ways and there is some metadata (You can obtain the credentials of the thing on the other end etc).

Unix named pipes appear as a special file in the filesystem and can be accessed with normal file IO commands including the shell. Windows ones don't, and need to be opened with a special system call (after which they behave mostly like a normal win32 handle).

Even more confusing, Unix has something called a "Unix socket" or AF_UNIX socket, which works more like (but not completely like) a win32 "named pipe", being bidirectional.

How do I fix the indentation of an entire file in Vi?

The master of all commands is

gg=G

This indents the entire file!

And below are some of the simple and elegant commands used to indent lines quickly in Vim or gVim.

To indent the all the lines below the current line

=G

To indent the current line

==

To indent n lines below the current line

n==

For example, to indent 4 lines below the current line

4==

To indent a block of code, go to one of the braces and use command

=%

Practical uses for the "internal" keyword in C#

Saw an interesting one the other day, maybe week, on a blog that I can't remember. Basically I can't take credit for this but I thought it might have some useful application.

Say you wanted an abstract class to be seen by another assembly but you don't want someone to be able to inherit from it. Sealed won't work because it's abstract for a reason, other classes in that assembly do inherit from it. Private won't work because you might want to declare a Parent class somewhere in the other assembly.

namespace Base.Assembly
{
  public abstract class Parent
  {
    internal abstract void SomeMethod();
  }

  //This works just fine since it's in the same assembly.
  public class ChildWithin : Parent
  {
    internal override void SomeMethod()
    {
    }
  }
}

namespace Another.Assembly
{
  //Kaboom, because you can't override an internal method
  public class ChildOutside : Parent
  {
  }

  public class Test 
  { 

    //Just fine
    private Parent _parent;

    public Test()
    {
      //Still fine
      _parent = new ChildWithin();
    }
  }
}

As you can see, it effectively allows someone to use the Parent class without being able to inherit from.

Update query with PDO and MySQL

  1. Your UPDATE syntax is wrong
  2. You probably meant to update a row not all of them so you have to use WHERE clause to target your specific row

Change

UPDATE `access_users`   
      (`contact_first_name`,`contact_surname`,`contact_email`,`telephone`) 
      VALUES (:firstname, :surname, :telephone, :email)

to

UPDATE `access_users`   
   SET `contact_first_name` = :firstname,
       `contact_surname` = :surname,
       `contact_email` = :email,
       `telephone` = :telephone 
 WHERE `user_id` = :user_id -- you probably have some sort of id 

Google Maps JavaScript API RefererNotAllowedMapError

This worked for me. There are 2 major categories of restrictions under api key settings:

  • Application restrictions
  • API restrictions

Application restrictions:

At the bottom in the Referrer section add your website url " http://www.grupocamaleon.com/boceto/aerial-simple.html " .There are example rules on the right hand side of the section based on various requirements.

Application restrictions

API restrictions:

Under API restrictions you have to explicitly select 'Maps Javascript API' from the dropdown list since our unique key will only be used for calling the Google maps API(probably) and save it as you can see in the below snap. I hope this works for you.....worked for me

enter image description here

Check your Script:

Also the issue may arise due to improper key feeding inside the script tag. It should be something like:

  <script async defer src="https://maps.googleapis.com/maps/api/jskey=YOUR_API_KEY&callback=initMap"
  type="text/javascript"></script>

Javascript - removing undefined fields from an object

This solution also avoids hasOwnProperty() as Object.keys returns an array of a given object's own enumerable properties.

Object.keys(obj).forEach(function (key) {
 if(typeof obj[key] === 'undefined'){
    delete obj[key];
  }
});

and you can add this as null or '' for stricter cleaning.

Center image using text-align center?

I came across this post, and it worked for me:

_x000D_
_x000D_
img {_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  bottom: 0;_x000D_
  left: 0;_x000D_
  right: 0;_x000D_
  margin: auto;_x000D_
}
_x000D_
<div style="border: 1px solid black; position:relative; min-height: 200px">_x000D_
  <img src="https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-icon.png?v=c78bd457575a">_x000D_
_x000D_
</div>
_x000D_
_x000D_
_x000D_

(Vertical and horizontal alignment)

How do DATETIME values work in SQLite?

Store it in a field of type long. See Date.getTime() and new Date(long)

How to use MD5 in javascript to transmit a password

crypto-js is a rich javascript library containing many cryptography algorithms.

All you have to do is just call CryptoJS.MD5(password)

$.post(
  'includes/login.php', 
  { user: username, pass: CryptoJS.MD5(password) },
  onLogin, 
  'json' );

How do I make a relative reference to another workbook in Excel?

Using =worksheetname() and =Indirect() function, and naming the worksheets in the parent Excel file with the name of the externally referenced Excel file. Each externally referenced excel file were in their own folders with same name. These sub-folders were only to create more clarity.


What I did was as follows:-

|----Column B---------------|----Column C------------|

R2) Parent folder --------> "C:\TEMP\Excel\"

R3) Sub folder name ---> =worksheetname()

R5) Full path --------------> ="'"&C2&C3&"["&C3&".xlsx]Sheet1'!$A$1"

R7) Indirect function-----> =INDIRECT(C5,TRUE)

In the main file, I had say, 5 worksheets labeled as Ext-1, Ext-2, Ext-3, Ext-4, Ext-5. Copy pasted the above formulas into all the five worksheets. Opened all the respectively named Excel files in the background. For some reason the results were not automatically computing, hence had to force a change by editing any cell. Volla, the value in cell A1 of each externally referenced Excel file were in the Main file.

How to remove spaces from a string using JavaScript?

Regex + Replace()

Although regex can be slower, in many use cases the developer is only manipulating a few strings at once so considering speed is irrelevant. Even though / / is faster than /\s/, having the '\s' explains what is going on to another developer perhaps more clearly.

let string = '/var/www/site/Brand new document.docx';
let path = string.replace(/\s/g, '');
// path => '/var/www/site/Brandnewdocument.docx'

Split() + Join()

Using Split + Join allows for further chained manipulation of the string.

let string = '/var/www/site/Brand new document.docx';
let path => string.split('').map(char => /(\s|\.)/.test(char) ? '/' : char).join('');
// "/var/www/site/Brand/new/document/docx";

C compiling - "undefined reference to"?

Make sure your declare the tolayer5 function as a prototype, or define the full function definition, earlier in the file where you use it.

Can Selenium WebDriver open browser windows silently in the background?

This is a simple Node.js solution that works in the new version 4.x (maybe also 3.x) of Selenium.

Chrome

const { Builder } = require('selenium-webdriver')
const chrome = require('selenium-webdriver/chrome');

let driver = await new Builder().forBrowser('chrome').setChromeOptions(new chrome.Options().headless()).build()

await driver.get('https://example.com')

Firefox

const { Builder } = require('selenium-webdriver')
const firefox = require('selenium-webdriver/firefox');

let driver = await new Builder().forBrowser('firefox').setFirefoxOptions(new firefox.Options().headless()).build()

await driver.get('https://example.com')

The whole thing just runs in the background. It is exactly what we want.