Programs & Examples On #Django fixtures

A fixture is a collection of data that Django knows how to import into a database, can be written as XML, YAML, or JSON documents. They can be used to provide initial data for models.

val() doesn't trigger change() in jQuery

It looks like the events are not bubbling. Try this:

$("#mybutton").click(function(){
  var oldval=$("#mytext").val();
  $("#mytext").val('Changed by button');
  var newval=$("#mytext").val();
  if (newval != oldval) {
    $("#mytext").trigger('change');
  }
});

I hope this helps.

I tried just a plain old $("#mytext").trigger('change') without saving the old value, and the .change fires even if the value didn't change. That is why I saved the previous value and called $("#mytext").trigger('change') only if it changes.

Is it better to return null or empty collection?

Empty collection. Always.

This sucks:

if(myInstance.CollectionProperty != null)
{
  foreach(var item in myInstance.CollectionProperty)
    /* arrgh */
}

It is considered a best practice to NEVER return null when returning a collection or enumerable. ALWAYS return an empty enumerable/collection. It prevents the aforementioned nonsense, and prevents your car getting egged by co-workers and users of your classes.

When talking about properties, always set your property once and forget it

public List<Foo> Foos {public get; private set;}

public Bar() { Foos = new List<Foo>(); }

In .NET 4.6.1, you can condense this quite a lot:

public List<Foo> Foos { get; } = new List<Foo>();

When talking about methods that return enumerables, you can easily return an empty enumerable instead of null...

public IEnumerable<Foo> GetMyFoos()
{
  return InnerGetFoos() ?? Enumerable.Empty<Foo>();
}

Using Enumerable.Empty<T>() can be seen as more efficient than returning, for example, a new empty collection or array.

Getting new Twitter API consumer and secret keys

consumer_key = API key

consumer_secret = API key secret

Found it hidden in Twitter API Docs

Twitter Docs screenshot

Twitter's naming is just too confusing.

Equivalent of typedef in C#

Both C++ and C# are missing easy ways to create a new type which is semantically identical to an exisiting type. I find such 'typedefs' totally essential for type-safe programming and its a real shame c# doesn't have them built-in. The difference between void f(string connectionID, string username) to void f(ConID connectionID, UserName username) is obvious ...

(You can achieve something similar in C++ with boost in BOOST_STRONG_TYPEDEF)

It may be tempting to use inheritance but that has some major limitations:

  • it will not work for primitive types
  • the derived type can still be casted to the original type, ie we can send it to a function receiving our original type, this defeats the whole purpose
  • we cannot derive from sealed classes (and ie many .NET classes are sealed)

The only way to achieve a similar thing in C# is by composing our type in a new class:

Class SomeType { 
  public void Method() { .. }
}

sealed Class SomeTypeTypeDef {
  public SomeTypeTypeDef(SomeType composed) { this.Composed = composed; }

  private SomeType Composed { get; }

  public override string ToString() => Composed.ToString();
  public override int GetHashCode() => HashCode.Combine(Composed);
  public override bool Equals(object obj) => obj is TDerived o && Composed.Equals(o.Composed); 
  public bool Equals(SomeTypeTypeDefo) => object.Equals(this, o);

  // proxy the methods we want
  public void Method() => Composed.Method();
}

While this will work it is very verbose for just a typedef. In addition we have a problem with serializing (ie to Json) as we want to serialize the class through its Composed property.

Below is a helper class that uses the "Curiously Recurring Template Pattern" to make this much simpler:

namespace Typedef {

  [JsonConverter(typeof(JsonCompositionConverter))]
  public abstract class Composer<TDerived, T> : IEquatable<TDerived> where TDerived : Composer<TDerived, T> {
    protected Composer(T composed) { this.Composed = composed; }
    protected Composer(TDerived d) { this.Composed = d.Composed; }

    protected T Composed { get; }

    public override string ToString() => Composed.ToString();
    public override int GetHashCode() => HashCode.Combine(Composed);
    public override bool Equals(object obj) => obj is Composer<TDerived, T> o && Composed.Equals(o.Composed); 
    public bool Equals(TDerived o) => object.Equals(this, o);
  }

  class JsonCompositionConverter : JsonConverter {
    static FieldInfo GetCompositorField(Type t) {
      var fields = t.BaseType.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.FlattenHierarchy);
      if (fields.Length!=1) throw new JsonSerializationException();
      return fields[0];
    }

    public override bool CanConvert(Type t) {
      var fields = t.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.FlattenHierarchy);
      return fields.Length == 1;
    }

    // assumes Compositor<T> has either a constructor accepting T or an empty constructor
    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) {
      while (reader.TokenType == JsonToken.Comment && reader.Read()) { };
      if (reader.TokenType == JsonToken.Null) return null; 
      var compositorField = GetCompositorField(objectType);
      var compositorType = compositorField.FieldType;
      var compositorValue = serializer.Deserialize(reader, compositorType);
      var ctorT = objectType.GetConstructor(new Type[] { compositorType });
      if (!(ctorT is null)) return Activator.CreateInstance(objectType, compositorValue);
      var ctorEmpty = objectType.GetConstructor(new Type[] { });
      if (ctorEmpty is null) throw new JsonSerializationException();
      var res = Activator.CreateInstance(objectType);
      compositorField.SetValue(res, compositorValue);
      return res;
    }

    public override void WriteJson(JsonWriter writer, object o, JsonSerializer serializer) {
      var compositorField = GetCompositorField(o.GetType());
      var value = compositorField.GetValue(o);
      serializer.Serialize(writer, value);
    }
  }

}

With Composer the above class becomes simply:

sealed Class SomeTypeTypeDef : Composer<SomeTypeTypeDef, SomeType> {
   public SomeTypeTypeDef(SomeType composed) : base(composed) {}

   // proxy the methods we want
   public void Method() => Composed.Method();
}

And in addition the SomeTypeTypeDef will serialize to Json in the same way that SomeType does.

Hope this helps !

Adding hours to JavaScript Date object?

JavaScript itself has terrible Date/Time API's. Nonetheless, you can do this in pure JavaScript:

Date.prototype.addHours = function(h) {
  this.setTime(this.getTime() + (h*60*60*1000));
  return this;
}

Importing a csv into mysql via command line

For importing csv with a header row using mysqlimport, just add

--ignore-lines=N

(ignores the first N lines of the data file)

This option is described in the page you've linked.

Get root view from current activity

For those of you who are using the Data Binding Library, to get the root of the current activity, simply use:

View rootView = dataBinding.getRoot();

And for Kotlin users, it's even simpler:

val rootView = dataBinding.root

How to prevent favicon.ico requests?

Personally I used this in my HTML head tag:

<link rel="shortcut icon" href="#" />

JUnit 4 compare Sets

with hamcrest:

assertThat(s1, is(s2));

with plain assert:

assertEquals(s1, s2);

NB:t the equals() method of the concrete set class is used

How to convert string to double with proper cultureinfo

I have this function in my toolbelt since years ago (all the function and variable names are messy and mixing Spanish and English, sorry for that).

It lets the user use , and . to separate the decimals and will try to do the best if both symbols are used.

    Public Shared Function TryCDec(ByVal texto As String, Optional ByVal DefaultValue As Decimal = 0) As Decimal

        If String.IsNullOrEmpty(texto) Then
            Return DefaultValue
        End If

        Dim CurAsTexto As String = texto.Trim.Replace("$", "").Replace(" ", "")

        ''// You can probably use a more modern way to find out the
        ''// System current locale, this function was done long time ago
        Dim SepDecimal As String, SepMiles As String
        If CDbl("3,24") = 324 Then
            SepDecimal = "."
            SepMiles = ","
        Else
            SepDecimal = ","
            SepMiles = "."
        End If

        If InStr(CurAsTexto, SepDecimal) > 0 Then
            If InStr(CurAsTexto, SepMiles) > 0 Then
                ''//both symbols was used find out what was correct
                If InStr(CurAsTexto, SepDecimal) > InStr(CurAsTexto, SepMiles) Then
                    ''// The usage was correct, but get rid of thousand separator
                    CurAsTexto = Replace(CurAsTexto, SepMiles, "")
                Else
                    ''// The usage was incorrect, but get rid of decimal separator and then replace it
                    CurAsTexto = Replace(CurAsTexto, SepDecimal, "")
                    CurAsTexto = Replace(CurAsTexto, SepMiles, SepDecimal)
                End If
            End If
        Else
            CurAsTexto = Replace(CurAsTexto, SepMiles, SepDecimal)
        End If
        ''// At last we try to tryParse, just in case
        Dim retval As Decimal = DefaultValue
        Decimal.TryParse(CurAsTexto, retval)
        Return retval
    End Function

How to align a div inside td element using CSS class

div { margin: auto; }

This will center your div.

Div by itself is a blockelement. Therefor you need to define the style to the div how to behave.

How can I make SMTP authenticated in C#

Set the Credentials property before sending the message.

What does ON [PRIMARY] mean?

To add a very important note on what Mark S. has mentioned in his post. In the specific SQL Script that has been mentioned in the question you can NEVER mention two different file groups for storing your data rows and the index data structure.

The reason why is due to the fact that the index being created in this case is a clustered Index on your primary key column. The clustered index data and the data rows of your table can NEVER be on different file groups.

So in case you have two file groups on your database e.g. PRIMARY and SECONDARY then below mentioned script will store your row data and clustered index data both on PRIMARY file group itself even though I've mentioned a different file group ([SECONDARY]) for the table data. More interestingly the script runs successfully as well (when I was expecting it to give an error as I had given two different file groups :P). SQL Server does the trick behind the scene silently and smartly.

CREATE TABLE [dbo].[be_Categories](
    [CategoryID] [uniqueidentifier] ROWGUIDCOL  NOT NULL CONSTRAINT [DF_be_Categories_CategoryID]  DEFAULT (newid()),
    [CategoryName] [nvarchar](50) NULL,
    [Description] [nvarchar](200) NULL,
    [ParentID] [uniqueidentifier] NULL,
 CONSTRAINT [PK_be_Categories] PRIMARY KEY CLUSTERED 
(
    [CategoryID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [SECONDARY]
GO

NOTE: Your index can reside on a different file group ONLY if the index being created is non-clustered in nature.

The below script which creates a non-clustered index will get created on [SECONDARY] file group instead when the table data already resides on [PRIMARY] file group:

CREATE NONCLUSTERED INDEX [IX_Categories] ON [dbo].[be_Categories]
(
    [CategoryName] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Secondary]
GO

You can get more information on how storing non-clustered indexes on a different file group can help your queries perform better. Here is one such link.

How do you clear the focus in javascript?

You can call window.focus();

but moving or losing the focus is bound to interfere with anyone using the tab key to get around the page.

you could listen for keycode 13, and forego the effect if the tab key is pressed.

How to install PHP intl extension in Ubuntu 14.04

May be universe repository is disabled, here is your package in it

Enable it

sudo add-apt-repository universe

Update

sudo apt-get update

And install

sudo apt-get install php5-intl

Is there a cross-browser onload event when clicking the back button?

Guys, I found that JQuery has only one effect: the page is reloaded when the back button is pressed. This has nothing to do with "ready".

How does this work? Well, JQuery adds an onunload event listener.

// http://code.jquery.com/jquery-latest.js
jQuery(window).bind("unload", function() { // ...

By default, it does nothing. But somehow this seems to trigger a reload in Safari, Opera and Mozilla -- no matter what the event handler contains.

[edit(Nickolay): here's why it works that way: webkit.org, developer.mozilla.org. Please read those articles (or my summary in a separate answer below) and consider whether you really need to do this and make your page load slower for your users.]

Can't believe it? Try this:

<body onunload=""><!-- This does the trick -->
<script type="text/javascript">
    alert('first load / reload');
    window.onload = function(){alert('onload')};
</script>
<a href="http://stackoverflow.com">click me, then press the back button</a>
</body>

You will see similar results when using JQuery.

You may want to compare to this one without onunload

<body><!-- Will not reload on back button -->
<script type="text/javascript">
    alert('first load / reload');
    window.onload = function(){alert('onload')};
</script>
<a href="http://stackoverflow.com">click me, then press the back button</a>
</body>

PHP session lost after redirect

First, carry out these usual checks:

  1. Make sure session_start(); is called before any sessions are being called. So a safe bet would be to put it at the beginning of your page, immediately after the opening <?php declaration before anything else. Also ensure there are no whitespaces/tabs before the opening <?php declaration.
  2. After the header redirect, end the current script using exit(); (Others have also suggested session_write_close(); and session_regenerate_id(true), you can try those as well, but I'd use exit();)
  3. Make sure cookies are enabled in the browser you are using to test it on.
  4. Ensure register_globals is off, you can check this on the php.ini file and also using phpinfo(). Refer to this as to how to turn it off.
  5. Make sure you didn't delete or empty the session
  6. Make sure the key in your $_SESSION superglobal array is not overwritten anywhere
  7. Make sure you redirect to the same domain. So redirecting from a www.yourdomain.com to yourdomain.com doesn't carry the session forward.
  8. Make sure your file extension is .php (it happens!)

Now, these are the most common mistakes, but if they didn't do the trick, the problem is most likely to do with your hosting company. If everything works on localhost but not on your remote/testing server, then this is most likely the culprit. So check the knowledge base of your hosting provider (also try their forums etc). For companies like FatCow and iPage, they require you to specify session_save_path. So like this:

session_save_path('"your home directory path"/cgi-bin/tmp');
session_start();

(replace "your home directory path" with your actual home directory path. This is usually within your control panel (or equivalent), but you can also create a test.php file on your root directory and type:

<?php echo $_SERVER['SCRIPT_FILENAME']; ?>

The bit before 'test.php' is your home directory path. And of course, make sure that the folder actually exists within your root directory. (Some programs do not upload empty folders when synchronizing)

Change a Rails application to production

It is not a good way to run rails server in production environment by "rails server -e production", because then rails runs as a single-threaded application, and can only respond to one HTTP request at a time.

The best article about production environment for rails is Production Environments - Rails 3

grep from tar.gz without extracting [faster one]

Am trying to grep pattern from dozen files .tar.gz but its very slow

tar -ztf file.tar.gz | while read FILENAME
do
        if tar -zxf file.tar.gz "$FILENAME" -O | grep "string" > /dev/null
        then
                echo "$FILENAME contains string"
        fi
done

That's actually very easy with ugrep option -z:

-z, --decompress
        Decompress files to search, when compressed.  Archives (.cpio,
        .pax, .tar, and .zip) and compressed archives (e.g. .taz, .tgz,
        .tpz, .tbz, .tbz2, .tb2, .tz2, .tlz, and .txz) are searched and
        matching pathnames of files in archives are output in braces.  If
        -g, -O, -M, or -t is specified, searches files within archives
        whose name matches globs, matches file name extensions, matches
        file signature magic bytes, or matches file types, respectively.
        Supported compression formats: gzip (.gz), compress (.Z), zip,
        bzip2 (requires suffix .bz, .bz2, .bzip2, .tbz, .tbz2, .tb2, .tz2),
        lzma and xz (requires suffix .lzma, .tlz, .xz, .txz).

Which requires just one command to search file.tar.gz as follows:

ugrep -z "string" file.tar.gz

This greps each of the archived files to display matches. Archived filenames are shown in braces to distinguish them from ordinary filenames. For example:

$ ugrep -z "Hello" archive.tgz
{Hello.bat}:echo "Hello World!"
Binary file archive.tgz{Hello.class} matches
{Hello.java}:public class Hello // prints a Hello World! greeting
{Hello.java}:  { System.out.println("Hello World!");
{Hello.pdf}:(Hello)
{Hello.sh}:echo "Hello World!"
{Hello.txt}:Hello

If you just want the file names, use option -l (--files-with-matches) and customize the filename output with option --format="%z%~" to get rid of the braces:

$ ugrep -z Hello -l --format="%z%~" archive.tgz
Hello.bat
Hello.class
Hello.java
Hello.pdf
Hello.sh
Hello.txt

How can I change the user on Git Bash?

For any OS

This helped me so I'll put it here, just in case. Once you are done with adding the rsa keys for both the accounts, add a config file in your .ssh directory for both the accounts (.ssh/config)

# First account
Host github.com-<FIRST_ACCOUNT_USERNAME_HERE>
   HostName github.com
   User git
   IdentityFile ~/.ssh/id_rsa_user1
   
# Second account
Host github.com-<SECOND_ACCOUNT_USERNAME_HERE>   
   HostName github.com
   User git
   IdentityFile ~/.ssh/id_rsa_user2

Make sure you use the correct usernames and RSA files. Next, you can open the terminal/git bash on the repository root and check which account you would be pushing from

git config user.email

Suppose this returns the first user email and you want to push from the second user. Change the local user.name and user.email :

git config user.name "SECOND_USER"
git config user.email "[email protected]"

(This won't change the global config and you can have the first user set up as the global user). Once done, you can confirm with git config user.email and it should return the email of the second user. You're all set to push to GitHub with the second user. The rest is all the same old git add , git commit and git push. To push from the first user, change the local user.name again and follow the same steps. Hope it helps :)


If the above steps are still not working for you, check to see if you have uploaded the RSA keys within GitHub portal. Refer to GitHub documentation:

Then, clear your ssh cached keys Reference

ssh-add -D

Then add you 2 ssh keys

ssh-add ~/.ssh/id_rsa_user1
ssh-add ~/.ssh/id_rsa_user2

Then type in your terminal:

ssh -T [email protected]<SECOND_ACCOUNT_USERNAME_HERE>

You should see the following output:

Hi <SECOND_USERNAME>! You've successfully authenticated, but GitHub does not provide shell access.

Then, assign the correct remote to your local repository. Make sure you put the same username as the one you gave in your .ssh/config file next to Host. In the following case [email protected]<SECOND_ACCOUNT_USERNAME_HERE>.

git remote rm origin
git remote add origin [email protected]<SECOND_ACCOUNT_USERNAME_HERE>:/your_username/your_repository.git

How to change legend title in ggplot

Adding this to the mix, for when you have changed the colors. This also worked for me in a qplot with two discrete variables:

p+ scale_fill_manual(values = Main_parties_color, name = "Main Parties")

How to load an external webpage into a div of a html page

Using simple html,

 <div> 
    <object type="text/html" data="http://validator.w3.org/" width="800px" height="600px" style="overflow:auto;border:5px ridge blue">
    </object>
 </div>

Or jquery,

<script>
        $("#mydiv")
            .html('<object data="http://your-website-domain"/>');
</script>

JSFIDDLE DEMO

Log to the base 2 in python

Try this ,

import math
print(math.log(8,2))  # math.log(number,base) 

Normal arguments vs. keyword arguments

I was looking for an example that had default kwargs using type annotation:

def test_var_kwarg(a: str, b: str='B', c: str='', **kwargs) -> str:
     return ' '.join([a, b, c, str(kwargs)])

example:

>>> print(test_var_kwarg('A', c='okay'))
A B okay {}
>>> d = {'f': 'F', 'g': 'G'}
>>> print(test_var_kwarg('a', c='c', b='b', **d))
a b c {'f': 'F', 'g': 'G'}
>>> print(test_var_kwarg('a', 'b', 'c'))
a b c {}

How to check if div element is empty

var empty = $("#cartContent").html().trim().length == 0;

How to stop java process gracefully?

Ok, after all the possibilities I have chosen to work with "Java Monitoring and Management"
Overview is here
That allows you to control one application from another one in relatively easy way. You can call the controlling application from a script to stop controlled application gracefully before killing it.

Here is the simplified code:

Controlled application:
run it with the folowing VM parameters:
-Dcom.sun.management.jmxremote
-Dcom.sun.management.jmxremote.port=9999
-Dcom.sun.management.jmxremote.authenticate=false
-Dcom.sun.management.jmxremote.ssl=false

//ThreadMonitorMBean.java
public interface ThreadMonitorMBean
{
String getName();
void start();
void stop();
boolean isRunning();
}

// ThreadMonitor.java
public class ThreadMonitor implements ThreadMonitorMBean
{
private Thread m_thrd = null;

public ThreadMonitor(Thread thrd)
{
    m_thrd = thrd;
}

@Override
public String getName()
{
    return "JMX Controlled App";
}

@Override
public void start()
{
    // TODO: start application here
    System.out.println("remote start called");
}

@Override
public void stop()
{
    // TODO: stop application here
    System.out.println("remote stop called");

    m_thrd.interrupt();
}

public boolean isRunning()
{
    return Thread.currentThread().isAlive();
}

public static void main(String[] args)
{
    try
    {
        System.out.println("JMX started");

        ThreadMonitorMBean monitor = new ThreadMonitor(Thread.currentThread());

        MBeanServer server = ManagementFactory.getPlatformMBeanServer();

        ObjectName name = new ObjectName("com.example:type=ThreadMonitor");

        server.registerMBean(monitor, name);

        while(!Thread.interrupted())
        {
            // loop until interrupted
            System.out.println(".");
            try 
            {
                Thread.sleep(1000);
            } 
            catch(InterruptedException ex) 
            {
                Thread.currentThread().interrupt();
            }
        }
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }
    finally
    {
        // TODO: some final clean up could be here also
        System.out.println("JMX stopped");
    }
}
}

Controlling application:
run it with the stop or start as the command line argument

public class ThreadMonitorConsole
{

public static void main(String[] args)
{
    try
    {   
        // connecting to JMX
        System.out.println("Connect to JMX service.");
        JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://:9999/jmxrmi");
        JMXConnector jmxc = JMXConnectorFactory.connect(url, null);
        MBeanServerConnection mbsc = jmxc.getMBeanServerConnection();

        // Construct proxy for the the MBean object
        ObjectName mbeanName = new ObjectName("com.example:type=ThreadMonitor");
        ThreadMonitorMBean mbeanProxy = JMX.newMBeanProxy(mbsc, mbeanName, ThreadMonitorMBean.class, true);

        System.out.println("Connected to: "+mbeanProxy.getName()+", the app is "+(mbeanProxy.isRunning() ? "" : "not ")+"running");

        // parse command line arguments
        if(args[0].equalsIgnoreCase("start"))
        {
            System.out.println("Invoke \"start\" method");
            mbeanProxy.start();
        }
        else if(args[0].equalsIgnoreCase("stop"))
        {
            System.out.println("Invoke \"stop\" method");
            mbeanProxy.stop();
        }

        // clean up and exit
        jmxc.close();
        System.out.println("Done.");    
    }
    catch(Exception e)
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
}


That's it. :-)

How to get and set the current web page scroll position?

You're looking for the document.documentElement.scrollTop property.

Most efficient way to reverse a numpy array

When you create reversed_arr you are creating a view into the original array. You can then change the original array, and the view will update to reflect the changes.

Are you re-creating the view more often than you need to? You should be able to do something like this:

arr = np.array(some_sequence)
reversed_arr = arr[::-1]

do_something(arr)
look_at(reversed_arr)
do_something_else(arr)
look_at(reversed_arr)

I'm not a numpy expert, but this seems like it would be the fastest way to do things in numpy. If this is what you are already doing, I don't think you can improve on it.

P.S. Great discussion of numpy views here:

View onto a numpy array?

What is the difference between "is None" and "== None"

The answer is explained here.

To quote:

A class is free to implement comparison any way it chooses, and it can choose to make comparison against None mean something (which actually makes sense; if someone told you to implement the None object from scratch, how else would you get it to compare True against itself?).

Practically-speaking, there is not much difference since custom comparison operators are rare. But you should use is None as a general rule.

Asp.Net WebApi2 Enable CORS not working with AspNet.WebApi.Cors 5.2.3

No-one of safe solution work for me so to be safer than Neeraj and easier than Matthew just add: System.Web.HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");

In your controller's method. That work for me.

public IHttpActionResult Get()
{
    System.Web.HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
    return Ok("value");
}

Android- Error:Execution failed for task ':app:transformClassesWithDexForRelease'

I fixed mine I added to my project > app > libs android volley.jar and my problem was solved

How to: "Separate table rows with a line"

If you don't want to use CSS try this one between your rows:

    <tr>
    <td class="divider"><hr /></td>
    </tr>

Cheers!!

Showing empty view when ListView is empty

A programmatically solution will be:

TextView textView = new TextView(context);
textView.setId(android.R.id.empty);
textView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
textView.setText("No result found");
listView.setEmptyView(textView);

How to make a form close when pressing the escape key?

Button cancelBTN = new Button();
cancelBTN.Size = new Size(0, 0);
cancelBTN.TabStop = false;
this.Controls.Add(cancelBTN);
this.CancelButton = cancelBTN;

How do I automatically scroll to the bottom of a multiline text box?

This will scroll to the end of the textbox when the text is changed, but still allows the user to scroll up

outbox.SelectionStart = outbox.Text.Length;
outbox.ScrollToEnd();

tested on Visual Studio Enterprise 2017

How to strip HTML tags with jQuery?

You can use the existing split function

One easy and choppy exemple:

var str = '<p> example ive got a string</P>';
var substr = str.split('<p> ');
// substr[0] contains ""
// substr[1] contains "example ive got a string</P>"
var substr2 = substr [1].split('</p>');
// substr2[0] contains "example ive got a string"
// substr2[1] contains ""

The example is just to show you how the split works.

How to set image on QPushButton?

You can do this in QtDesigner. Just click on your button then go to icon property and then choose your image file.

How to perform mouseover function in Selenium WebDriver using Java?

This code works perfectly well:

 Actions builder = new Actions(driver);
 WebElement element = driver.findElement(By.linkText("Put your text here"));
 builder.moveToElement(element).build().perform();

After the mouse over, you can then go on to perform the next action you want on the revealed information

Rollback to an old Git commit in a public repo

Let's say you work on a project and after a day or so. You notice one feature is still giving you errors. But you do not know what change you made that caused the error. So you have to fish previous working commits. To revert to a specific commit:

git checkout 8a0fe5191b7dfc6a81833bfb61220d7204e6b0a9 .

Ok, so that commit works for you. No more error. You pinpointed the issue. Now you can go back to latest commit:

git checkout 792d9294f652d753514dc2033a04d742decb82a5 .

And checkout a specific file before it caused the error (in my case I use example Gemfile.lock):

git checkout 8a0fe5191b7dfc6a81833bfb61220d7204e6b0a9 -- /projects/myproject/Gemfile.lock

And this is one way to handle errors you created in commits without realizing the errors until later.

What is the correct Performance Counter to get CPU and Memory Usage of a Process?

Pelo Hyper-V:

private PerformanceCounter theMemCounter = new PerformanceCounter(
    "Hyper-v Dynamic Memory VM",
    "Physical Memory",
    Process.GetCurrentProcess().ProcessName); 

using href links inside <option> tag

The accepted solution looks good, but there is one case it cannot handle:

The "onchange" event will not be triggered when the same option is reselected. So, I came up with the following improvement:

HTML

<select id="sampleSelect" >
  <option value="Home.php">Home</option>
  <option value="Contact.php">Contact</option>
  <option value="Sitemap.php">Sitemap</option>
</select>

jQuery

$("select").click(function() {
  var open = $(this).data("isopen");
  if(open) {
    window.location.href = $(this).val()
  }
  //set isopen to opposite so next time when use clicked select box
  //it wont trigger this event
  $(this).data("isopen", !open);
});

comparing 2 strings alphabetically for sorting purposes

Lets look at some test cases - try running the following expressions in your JS console:

"a" < "b"

"aa" < "ab"

"aaa" < "aab"

All return true.

JavaScript compares strings character by character and "a" comes before "b" in the alphabet - hence less than.

In your case it works like so -

1 . "a?aaa" < "?a?b"

compares the first two "a" characters - all equal, lets move to the next character.

2 . "a?a??aa" < "a?b??"

compares the second characters "a" against "b" - whoop! "a" comes before "b". Returns true.

Entity Framework and Connection Pooling

Below code helped my object to be refreshed with fresh database values. The Entry(object).Reload() command forces the object to recall database values

GM_MEMBERS member = DatabaseObjectContext.GM_MEMBERS.FirstOrDefault(p => p.Username == username && p.ApplicationName == this.ApplicationName);
DatabaseObjectContext.Entry(member).Reload();

Best way to simulate "group by" from bash?

Most of the other solutions count duplicates. If you really need to group key value pairs, try this:

Here is my example data:

find . | xargs md5sum
fe4ab8e15432161f452e345ff30c68b0 a.txt
30c68b02161e15435ff52e34f4fe4ab8 b.txt
30c68b02161e15435ff52e34f4fe4ab8 c.txt
fe4ab8e15432161f452e345ff30c68b0 d.txt
fe4ab8e15432161f452e345ff30c68b0 e.txt

This will print the key value pairs grouped by the md5 checksum.

cat table.txt | awk '{print $1}' | sort | uniq  | xargs -i grep {} table.txt
30c68b02161e15435ff52e34f4fe4ab8 b.txt
30c68b02161e15435ff52e34f4fe4ab8 c.txt
fe4ab8e15432161f452e345ff30c68b0 a.txt
fe4ab8e15432161f452e345ff30c68b0 d.txt
fe4ab8e15432161f452e345ff30c68b0 e.txt

Spring MVC @PathVariable with dot (.) is getting truncated

In addition to Martin Frey's answer, this can also be fixed by adding a trailing slash in the RequestMapping value:

/path/{variable}/

Keep in mind that this fix does not support maintainability. It now requires all URI's to have a trailing slash - something that may not be apparent to API users / new developers. Because it's likely not all parameters may have a . in them, it may also create intermittent bugs

Escape @ character in razor view engine

@@ is the escape character for @ in Razor views as stated above.

Razor does however try to work out when an '@' is just an '@' and where it marks C# (or VB.Net) code. One of the main uses for this is to identify email addresses within a Razor view - it should not be necessary to escape the @ character in an email address.

Mongoose: Find, modify, save

findOne, modify fields & save

User.findOne({username: oldUsername})
  .then(user => {
    user.username = newUser.username;
    user.password = newUser.password;
    user.rights = newUser.rights;

    user.markModified('username');
    user.markModified('password');
    user.markModified('rights');

    user.save(err => console.log(err));
});

OR findOneAndUpdate

User.findOneAndUpdate({username: oldUsername}, {$set: { username: newUser.username, user: newUser.password, user:newUser.rights;}}, {new: true}, (err, doc) => {
    if (err) {
        console.log("Something wrong when updating data!");
    }
    console.log(doc);
});

Also see updateOne

How can I change cols of textarea in twitter-bootstrap?

This works for me with twitter bootstrap 2 and simple_form 2.0.4
Result is a span6 text area in a span9 row

 <div class="row" >
   <div class="span9">
     <%= f.input :some_text, :input_html => {:rows => 5, :placeholder => "Enter some text.", :class => "span6"}%>
   </div>
 </div>

Eclipse - Installing a new JRE (Java SE 8 1.8.0)

You can have many java versions in your system.

I think you should add the java 8 in yours JREs installed or edit.

Take a look my screen:

enter image description here

If you click in edit (check your java 8 path):

enter image description here

How to replace item in array?

var items = Array(523,3452,334,31,5346);

If you know the value then use,

items[items.indexOf(334)] = 1010;

If you want to know that value is present or not, then use,

var point = items.indexOf(334);

if (point !== -1) {
    items[point] = 1010;
}

If you know the place (position) then directly use,

items[--position] = 1010;

If you want replace few elements, and you know only starting position only means,

items.splice(2, 1, 1010, 1220);

for more about .splice

SQL Server Creating a temp table for this query

If you want to query the results from a temporary table inside the same query, you can use # temp tables, or @ table variables (I personally prefer @), for querying outside of the scope you would either want to use ## global temp tables or create a new table with the results.

DECLARE 
@ProjectID int = 3,
@Year int = 2010,
@MeterTypeID int = 1,
@StartDate datetime,
@EndDate datetime

SET @StartDate = '07/01/' + CAST(@Year as VARCHAR)
SET @EndDate = '06/30/' + CAST(@Year+1 as VARCHAR)

DECLARE @MyTempTable TABLE (SiteName varchar(50), BillingMonth varchar(10), Consumption float)

INSERT INTO @MyTempTable (SiteName, BillingMonth, Consumption)
SELECT  tblMEP_Sites.Name AS SiteName, convert(varchar(10),BillingMonth ,101) AS BillingMonth, SUM(Consumption) AS Consumption
FROM tblMEP_Projects

SQL Server 2012 can't start because of a login failure

This happened to me. A policy on the domain was taking away the SQL Server user account's "Log on as a service" rights. You can work around this using JLo's solution, but does not address the group policy problem specifically and it will return next time the group policies are refreshed on the machine.

The specific policy causing the issue for me was: Under, Computer Configuration -> Windows Settings -> Security Settings -> Local Policies -> User Rights Assignments: Log on as a service

You can see which policies are being applied to your machine by running the command "rsop" from the command line. Follow the path to the policy listed above and you will see its current value as well as which GPO set the value.

reading HttpwebResponse json response, C#

If you're getting source in Content Use the following method

try
{
    var response = restClient.Execute<List<EmpModel>>(restRequest);

    var jsonContent = response.Content;

    var data = JsonConvert.DeserializeObject<List<EmpModel>>(jsonContent);

    foreach (EmpModel item in data)
    {
        listPassingData?.Add(item);
    }
}
catch (Exception ex)
{
    Console.WriteLine($"Data get mathod problem {ex} ");
}

jquery fill dropdown with json data

If your data is already in array form, it's really simple using jQuery:

 $(data.msg).each(function()
 {
     alert(this.value);
     alert(this.label);

     //this refers to the current item being iterated over

     var option = $('<option />');
     option.attr('value', this.value).text(this.label);

     $('#myDropDown').append(option);
 });

.ajax() is more flexible than .getJSON() - for one, getJson is targeted specifically as a GET request to retrieve json; ajax() can request on any verb to get back any content type (although sometimes that's not useful). getJSON internally calls .ajax().

Serializing enums with Jackson

I've found a very nice and concise solution, especially useful when you cannot modify enum classes as it was in my case. Then you should provide a custom ObjectMapper with a certain feature enabled. Those features are available since Jackson 1.6.

public class CustomObjectMapper extends ObjectMapper {
    @PostConstruct
    public void customConfiguration() {
        // Uses Enum.toString() for serialization of an Enum
        this.enable(WRITE_ENUMS_USING_TO_STRING);
        // Uses Enum.toString() for deserialization of an Enum
        this.enable(READ_ENUMS_USING_TO_STRING);
    }
}

There are more enum-related features available, see here:

https://github.com/FasterXML/jackson-databind/wiki/Serialization-features https://github.com/FasterXML/jackson-databind/wiki/Deserialization-Features

How to overload functions in javascript?

Overloading a function in JavaScript can be done in many ways. All of them involve a single master function that either performs all the processes, or delegates to sub-functions/processes.

One of the most common simple techniques involves a simple switch:

function foo(a, b) {
    switch (arguments.length) {
    case 0:
        //do basic code
        break;
    case 1:
        //do code with `a`
        break;
    case 2:
    default:
        //do code with `a` & `b`
        break;
    }
}

A more elegant technique would be to use an array (or object if you're not making overloads for every argument count):

fooArr = [
    function () {
    },
    function (a) {
    },
    function (a,b) {
    }
];
function foo(a, b) {
    return fooArr[arguments.length](a, b);
}

That previous example isn't very elegant, anyone could modify fooArr, and it would fail if someone passes in more than 2 arguments to foo, so a better form would be to use a module pattern and a few checks:

var foo = (function () {
    var fns;
    fns = [
        function () {
        },
        function (a) {
        },
        function (a, b) {
        }
    ];
    function foo(a, b) {
        var fnIndex;
        fnIndex = arguments.length;
        if (fnIndex > foo.length) {
            fnIndex = foo.length;
        }
        return fns[fnIndex].call(this, a, b);
    }
    return foo;
}());

Of course your overloads might want to use a dynamic number of parameters, so you could use an object for the fns collection.

var foo = (function () {
    var fns;
    fns = {};
    fns[0] = function () {
    };
    fns[1] = function (a) {
    };
    fns[2] = function (a, b) {
    };
    fns.params = function (a, b /*, params */) {
    };
    function foo(a, b) {
        var fnIndex;
        fnIndex = arguments.length;
        if (fnIndex > foo.length) {
            fnIndex = 'params';
        }
        return fns[fnIndex].apply(this, Array.prototype.slice.call(arguments));
    }
    return foo;
}());

My personal preference tends to be the switch, although it does bulk up the master function. A common example of where I'd use this technique would be a accessor/mutator method:

function Foo() {} //constructor
Foo.prototype = {
    bar: function (val) {
        switch (arguments.length) {
        case 0:
            return this._bar;
        case 1:
            this._bar = val;
            return this;
        }
    }
}

Setting up Eclipse with JRE Path

Add this to eclipse.ini:

-vm
your_java_path\bin\javaw.exe

...but be aware that you must add these lines before -vmargs

How to get filename without extension from file path in Ruby

Try File.basename

Returns the last component of the filename given in file_name, which must be formed using forward slashes (``/’’) regardless of the separator used on the local file system. If suffix is given and present at the end of file_name, it is removed.

File.basename("/home/gumby/work/ruby.rb")          #=> "ruby.rb"
File.basename("/home/gumby/work/ruby.rb", ".rb")   #=> "ruby"

In your case:

File.basename("C:\\projects\\blah.dll", ".dll")  #=> "blah"

[Vue warn]: Property or method is not defined on the instance but referenced during render

I had two methods: in the <script>, goes to show, that you can spend hours looking for something that was such a simple mistake.

How to check if a string contains only numbers?

You could use a regular expression like this

If Regex.IsMatch(number, "^[0-9 ]+$") Then

...

End If

What does void* mean and how to use it?

You can have a look at this article about pointers http://www.cplusplus.com/doc/tutorial/pointers/ and read the chapter : void pointers.

This also works for C language.

The void type of pointer is a special type of pointer. In C++, void represents the absence of type, so void pointers are pointers that point to a value that has no type (and thus also an undetermined length and undetermined dereference properties).

This allows void pointers to point to any data type, from an integer value or a float to a string of characters. But in exchange they have a great limitation: the data pointed by them cannot be directly dereferenced (which is logical, since we have no type to dereference to), and for that reason we will always have to cast the address in the void pointer to some other pointer type that points to a concrete data type before dereferencing it.

Magento - Retrieve products with a specific attribute value

Almost all Magento Models have a corresponding Collection object that can be used to fetch multiple instances of a Model.

To instantiate a Product collection, do the following

$collection = Mage::getModel('catalog/product')->getCollection();

Products are a Magento EAV style Model, so you'll need to add on any additional attributes that you want to return.

$collection = Mage::getModel('catalog/product')->getCollection();

//fetch name and orig_price into data
$collection->addAttributeToSelect('name');  
$collection->addAttributeToSelect('orig_price');    

There's multiple syntaxes for setting filters on collections. I always use the verbose one below, but you might want to inspect the Magento source for additional ways the filtering methods can be used.

The following shows how to filter by a range of values (greater than AND less than)

$collection = Mage::getModel('catalog/product')->getCollection();
$collection->addAttributeToSelect('name');  
$collection->addAttributeToSelect('orig_price');    

//filter for products whose orig_price is greater than (gt) 100
$collection->addFieldToFilter(array(
    array('attribute'=>'orig_price','gt'=>'100'),
)); 

//AND filter for products whose orig_price is less than (lt) 130
$collection->addFieldToFilter(array(
    array('attribute'=>'orig_price','lt'=>'130'),
));

While this will filter by a name that equals one thing OR another.

$collection = Mage::getModel('catalog/product')->getCollection();
$collection->addAttributeToSelect('name');  
$collection->addAttributeToSelect('orig_price');    

//filter for products who name is equal (eq) to Widget A, or equal (eq) to Widget B
$collection->addFieldToFilter(array(
    array('attribute'=>'name','eq'=>'Widget A'),
    array('attribute'=>'name','eq'=>'Widget B'),        
));

A full list of the supported short conditionals (eq,lt, etc.) can be found in the _getConditionSql method in lib/Varien/Data/Collection/Db.php

Finally, all Magento collections may be iterated over (the base collection class implements on of the the iterator interfaces). This is how you'll grab your products once filters are set.

$collection = Mage::getModel('catalog/product')->getCollection();
$collection->addAttributeToSelect('name');  
$collection->addAttributeToSelect('orig_price');    

//filter for products who name is equal (eq) to Widget A, or equal (eq) to Widget B
$collection->addFieldToFilter(array(
    array('attribute'=>'name','eq'=>'Widget A'),
    array('attribute'=>'name','eq'=>'Widget B'),        
));

foreach ($collection as $product) {
    //var_dump($product);
    var_dump($product->getData());
}

Mismatch Detected for 'RuntimeLibrary'

I downloaded and extracted Crypto++ in C:\cryptopp. I used Visual Studio Express 2012 to build all the projects inside (as instructed in readme), and everything was built successfully. Then I made a test project in some other folder and added cryptolib as a dependency.

The conversion was probably not successful. The only thing that was successful was the running of VCUpgrade. The actual conversion itself failed but you don't know until you experience the errors you are seeing. For some of the details, see Visual Studio on the Crypto++ wiki.


Any ideas how to fix this?

To resolve your issues, you should download vs2010.zip if you want static C/C++ runtime linking (/MT or /MTd), or vs2010-dynamic.zip if you want dynamic C/C++ runtime linking (/MT or /MTd). Both fix the latent, silent failures produced by VCUpgrade.


vs2010.zip, vs2010-dynamic.zip and vs2005-dynamic.zip are built from the latest GitHub sources. As of this writing (JUN 1 2016), that's effectively pre-Crypto++ 5.6.4. If you are using the ZIP files with a down level Crypto++, like 5.6.2 or 5.6.3, then you will run into minor problems.

There are two minor problems I am aware. First is a rename of bench.cpp to bench1.cpp. Its error is either:

  • C1083: Cannot open source file: 'bench1.cpp': No such file or directory
  • LNK2001: unresolved external symbol "void __cdecl OutputResultOperations(char const *,char const *,bool,unsigned long,double)" (?OutputResultOperations@@YAXPBD0_NKN@Z)

The fix is to either (1) open cryptest.vcxproj in notepad, find bench1.cpp, and then rename it to bench.cpp. Or (2) rename bench.cpp to bench1.cpp on the filesystem. Please don't delete this file.

The second problem is a little trickier because its a moving target. Down level releases, like 5.6.2 or 5.6.3, are missing the latest classes available in GitHub. The missing class files include HKDF (5.6.3), RDRAND (5.6.3), RDSEED (5.6.3), ChaCha (5.6.4), BLAKE2 (5.6.4), Poly1305 (5.6.4), etc.

The fix is to remove the missing source files from the Visual Studio project files since they don't exist for the down level releases.

Another option is to add the missing class files from the latest sources, but there could be complications. For example, many of the sources subtly depend upon the latest config.h, cpu.h and cpu.cpp. The "subtlety" is you won't realize you are getting an under-performing class.

An example of under-performing class is BLAKE2. config.h adds compile time ARM-32 and ARM-64 detection. cpu.h and cpu.cpp adds runtime ARM instruction detection, which depends upon compile time detection. If you add BLAKE2 without the other files, then none of the detection occurs and you get a straight C/C++ implementation. You probably won't realize you are missing the NEON opportunity, which runs around 9 to 12 cycles-per-byte versus 40 cycles-per-byte or so for vanilla C/C++.

How to uninstall jupyter

When you $ pip install jupyter several dependencies are installed. The best way to uninstall it completely is by running:

  1. $ pip install pip-autoremove
  2. $ pip-autoremove jupyter -y

Kindly refer to this related question.

pip-autoremove removes a package and its unused dependencies. Here are the docs.

Format date in a specific timezone

.zone() has been deprecated, and you should use utcOffset instead:

// for a timezone that is +7 UTC hours
moment(1369266934311).utcOffset(420).format('YYYY-MM-DD HH:mm')

How do I get into a Docker container's shell?

docker exec will definitely be a solution. An easy way to work with the question you asked is by mounting the directory inside Docker to the local system's directory.

So that you can view the changes in local path instantly.

docker run -v /Users/<path>:/<container path> 

What is the equivalent of the C# 'var' keyword in Java?

This feature is now available in Java SE 10. The static, type-safe var has finally made it into the java world :)

source: https://www.oracle.com/corporate/pressrelease/Java-10-032018.html

SoapFault exception: Could not connect to host

In my case, disabled SELINUX allow PHP to call my WebService. I run PHP in FPM with Apache2

SELinux status :

# sestatus

Disable SELinux :

setenforce 0

Enable SELinux :

# setenforce 1

Permanent disable :

edit this file /etc/selinux/config

jQuery equivalent of JavaScript's addEventListener method

The closest thing would be the bind function:

http://api.jquery.com/bind/

$('#foo').bind('click', function() {
  alert('User clicked on "foo."');
});

When do you use map vs flatMap in RxJava?

In your case you need map, since there is only 1 input and 1 output.

map - supplied function simply accepts an item and returns an item which will be emitted further (only once) down.

flatMap - supplied function accepts an item then returns an "Observable", meaning each item of the new "Observable" will be emitted separately further down.

May be code will clear things up for you:

Observable.just("item1").map( str -> {
    System.out.println("inside the map " + str);
    return str;
}).subscribe(System.out::println);

Observable.just("item2").flatMap( str -> {
    System.out.println("inside the flatMap " + str);
    return Observable.just(str + "+", str + "++" , str + "+++");
}).subscribe(System.out::println);

Output:

inside the map item1
item1
inside the flatMap item2
item2+
item2++
item2+++

How to select the rows with maximum values in each group with dplyr?

More generally, I think you might want to get "top" of the rows that are sorted within a given group.

For the case of where a single value is max'd out, you have essentially sorted by only one column. However, it's often useful to hierarchically sort by multiple columns (for example: a date column and a time-of-day column).

# Answering the question of getting row with max "value".
df %>% 
  # Within each grouping of A and B values.
  group_by( A, B) %>% 
  # Sort rows in descending order by "value" column.
  arrange( desc(value) ) %>% 
  # Pick the top 1 value
  slice(1) %>% 
  # Remember to ungroup in case you want to do further work without grouping.
  ungroup()

# Answering an extension of the question of 
# getting row with the max value of the lowest "C".
df %>% 
  # Within each grouping of A and B values.
  group_by( A, B) %>% 
  # Sort rows in ascending order by C, and then within that by 
  # descending order by "value" column.
  arrange( C, desc(value) ) %>% 
  # Pick the one top row based on the sort
  slice(1) %>% 
  # Remember to ungroup in case you want to do further work without grouping.
  ungroup()

Passing Arrays to Function in C++

The syntaxes

int[]

and

int[X] // Where X is a compile-time positive integer

are exactly the same as

int*

when in a function parameter list (I left out the optional names).

Additionally, an array name decays to a pointer to the first element when passed to a function (and not passed by reference) so both int firstarray[3] and int secondarray[5] decay to int*s.

It also happens that both an array dereference and a pointer dereference with subscript syntax (subscript syntax is x[y]) yield an lvalue to the same element when you use the same index.

These three rules combine to make the code legal and work how you expect; it just passes pointers to the function, along with the length of the arrays which you cannot know after the arrays decay to pointers.

Visual Studio: ContextSwitchDeadlock

In Visual Studio 2017 Spanish version.

"Depurar" -> "Ventanas" -> "Configuración de Excepciones"

and search "ContextSwitchDeadlock". Then, uncheck it. Or shortcut

Ctrl+D,E

Best.

Declare a constant array

As others have mentioned, there is no official Go construct for this. The closest I can imagine would be a function that returns a slice. In this way, you can guarantee that no one will manipulate the elements of the original slice (as it is "hard-coded" into the array).

I have shortened your slice to make it...shorter...:

func GetLetterGoodness() []float32 {
    return []float32 { .0817,.0149,.0278,.0425,.1270,.0223 }
}

Unable to start Service Intent

I hope I can help someone with this info as well: I moved my service class into another package and I fixed the references. The project was perfectly fine, BUT the service class could not be found by the activity.

By watching the log in logcat I noticed the warning about the issue: the activity could not find the service class, but the funny thing was that the package was incorrect, it contained a "/" char. The compiler was looking for

com.something./service.MyService

instead of

com.something.service.MyService

I moved the service class out from the package and back in and everything worked just fine.

How to return a class object by reference in C++?

Well, it is maybe not a really beautiful solution in the code, but it is really beautiful in the interface of your function. And it is also very efficient. It is ideal if the second is more important for you (for example, you are developing a library).

The trick is this:

  1. A line A a = b.make(); is internally converted to a constructor of A, i.e. as if you had written A a(b.make());.
  2. Now b.make() should result a new class, with a callback function.
  3. This whole thing can be fine handled only by classes, without any template.

Here is my minimal example. Check only the main(), as you can see it is simple. The internals aren't.

From the viewpoint of the speed: the size of a Factory::Mediator class is only 2 pointers, which is more that 1 but not more. And this is the only object in the whole thing which is transferred by value.

#include <stdio.h>

class Factory {
  public:
    class Mediator;

    class Result {
      public:
        Result() {
          printf ("Factory::Result::Result()\n");
        };

        Result(Mediator fm) {
          printf ("Factory::Result::Result(Mediator)\n");
          fm.call(this);
        };
    };

    typedef void (*MakeMethod)(Factory* factory, Result* result);

    class Mediator {
      private:
        Factory* factory;
        MakeMethod makeMethod;

      public:
        Mediator(Factory* factory, MakeMethod makeMethod) {
          printf ("Factory::Mediator::Mediator(Factory*, MakeMethod)\n");
          this->factory = factory;
          this->makeMethod = makeMethod;
        };

        void call(Result* result) {
          printf ("Factory::Mediator::call(Result*)\n");
          (*makeMethod)(factory, result);
        };
    };
};

class A;

class B : private Factory {
  private:
    int v;

  public:
    B(int v) {
      printf ("B::B()\n");
      this->v = v;
    };

    int getV() const {
      printf ("B::getV()\n");
      return v;
    };

    static void makeCb(Factory* f, Factory::Result* a);

    Factory::Mediator make() {
      printf ("Factory::Mediator B::make()\n");
      return Factory::Mediator(static_cast<Factory*>(this), &B::makeCb);
    };
};

class A : private Factory::Result {
  friend class B;

  private:
    int v;

  public:
    A() {
      printf ("A::A()\n");
      v = 0;
    };

    A(Factory::Mediator fm) : Factory::Result(fm) {
      printf ("A::A(Factory::Mediator)\n");
    };

    int getV() const {
      printf ("A::getV()\n");
      return v;
    };

    void setV(int v) {
      printf ("A::setV(%i)\n", v);
      this->v = v;
    };
};

void B::makeCb(Factory* f, Factory::Result* r) {
      printf ("B::makeCb(Factory*, Factory::Result*)\n");
      B* b = static_cast<B*>(f);
      A* a = static_cast<A*>(r);
      a->setV(b->getV()+1);
    };

int main(int argc, char **argv) {
  B b(42);
  A a = b.make();
  printf ("a.v = %i\n", a.getV());
  return 0;
}

Remove decimal values using SQL query

If it's a decimal data type and you know it will never contain decimal places you can consider setting the scale property to 0. For example to decimal(18, 0). This will save you from replacing the ".00" characters and the query will be faster. In such case, don't forget to to check if the "prevent saving option" is disabled (SSMS menu "Tools>Options>Designers>Table and database designer>prevent saving changes that require table re-creation").

Othewise, you of course remove it using SQL query:

select replace(cast([height] as varchar), '.00', '') from table

Conditionally hide CommandField or ButtonField in Gridview

<asp:GridView ID="gv_Document" CssClass="gridstyle" runat="server" OnRowDataBound="gv_Document_RowDataBound" AutoGenerateColumns="false" DataKeyNames="SourceGUID,Source,FilePath" ShowHeaderWhenEmpty="false" OnRowDeleting="gv_Document_RowDeleting">
   <Columns>
       <asp:BoundField HeaderText="ItemID" DataField="ItemID" ItemStyle-CssClass="hidden-field" HeaderStyle-CssClass="hidden-field" />
       <asp:BoundField HeaderText="SourceGUID" DataField="SourceGUID" ItemStyle-CssClass="hidden-field" HeaderStyle-CssClass="hidden-field" />
       <asp:BoundField HeaderText="Source" DataField="Source" ItemStyle-CssClass="hidden-field" HeaderStyle-CssClass="hidden-field" />
           <asp:TemplateField HeaderText="">
               <ItemTemplate>
                    <asp:HyperLink ID="hyperLink" runat="server" Target="_blank" NavigateUrl='<%# Bind("FilePath")%>'
                                                                Text='<%# Bind("FileName")%>'>  </asp:HyperLink>
               </ItemTemplate>
           </asp:TemplateField>
      <asp:BoundField HeaderText="Type" DataField="FileExtension" ItemStyle-CssClass="hidden-field" HeaderStyle-CssClass="hidden-field" />
      <asp:BoundField HeaderText="Content type" DataField="FileMimeType" ItemStyle-CssClass="hidden-field" HeaderStyle-CssClass="hidden-field" />
      <asp:BoundField HeaderText="File Path" DataField="FilePath" ItemStyle-CssClass="hidden-field" HeaderStyle-CssClass="hidden-field" />
      <asp:CommandField ShowDeleteButton="True" DeleteText="Delete" />
   </Columns>

Use this code to disable delete button in gridview from code behind.

protected void gv_Document_RowDataBound(object sender, GridViewRowEventArgs e)
{ 
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        ((LinkButton)e.Row.Cells[7].Controls[0]).Visible = false;            
    }
}

Convert bytes to a string

If you don't know the encoding, then to read binary input into string in Python 3 and Python 2 compatible way, use the ancient MS-DOS CP437 encoding:

PY3K = sys.version_info >= (3, 0)

lines = []
for line in stream:
    if not PY3K:
        lines.append(line)
    else:
        lines.append(line.decode('cp437'))

Because encoding is unknown, expect non-English symbols to translate to characters of cp437 (English characters are not translated, because they match in most single byte encodings and UTF-8).

Decoding arbitrary binary input to UTF-8 is unsafe, because you may get this:

>>> b'\x00\x01\xffsd'.decode('utf-8')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 2: invalid
start byte

The same applies to latin-1, which was popular (the default?) for Python 2. See the missing points in Codepage Layout - it is where Python chokes with infamous ordinal not in range.

UPDATE 20150604: There are rumors that Python 3 has the surrogateescape error strategy for encoding stuff into binary data without data loss and crashes, but it needs conversion tests, [binary] -> [str] -> [binary], to validate both performance and reliability.

UPDATE 20170116: Thanks to comment by Nearoo - there is also a possibility to slash escape all unknown bytes with backslashreplace error handler. That works only for Python 3, so even with this workaround you will still get inconsistent output from different Python versions:

PY3K = sys.version_info >= (3, 0)

lines = []
for line in stream:
    if not PY3K:
        lines.append(line)
    else:
        lines.append(line.decode('utf-8', 'backslashreplace'))

See Python’s Unicode Support for details.

UPDATE 20170119: I decided to implement slash escaping decode that works for both Python 2 and Python 3. It should be slower than the cp437 solution, but it should produce identical results on every Python version.

# --- preparation

import codecs

def slashescape(err):
    """ codecs error handler. err is UnicodeDecode instance. return
    a tuple with a replacement for the unencodable part of the input
    and a position where encoding should continue"""
    #print err, dir(err), err.start, err.end, err.object[:err.start]
    thebyte = err.object[err.start:err.end]
    repl = u'\\x'+hex(ord(thebyte))[2:]
    return (repl, err.end)

codecs.register_error('slashescape', slashescape)

# --- processing

stream = [b'\x80abc']

lines = []
for line in stream:
    lines.append(line.decode('utf-8', 'slashescape'))

Wait 5 seconds before executing next line

setTimeout(function() {
     $('.message').hide();
}, 2000);

This will hide the '.message' div after 2 seconds.

Xcode 6 Storyboard the wrong size?

For anyone using XCode 7, it's very easy to design for a specific device size (instead of the default square-ish canvas).

In Interface Builder, select your ViewController or Scene from the left menu. Then under Show the Attributes Inspector, go to the Simulated Metrics, and pick the desired Size from the dropdown menu.

error: expected declaration or statement at end of input in c

You probably have syntax error. You most likely forgot to put a } or ; somewhere above this function.

How to set the max size of upload file

For Spring Boot 2.+, make sure you are using spring.servlet instead of spring.http.

---
spring:
  servlet:
    multipart:
      max-file-size: 10MB
      max-request-size: 10MB

If you have to use tomcat, you might end up creating EmbeddedServletContainerCustomizer, which is not really nice thing to do.

If you can live without tomat, you could replace tomcat with e.g. undertow and avoid this issue at all.

How to put a link on a button with bootstrap?

If you don't really need the button element, just move the classes to a regular link:

<div class="btn-group">
    <a href="/save/1" class="btn btn-primary active">
        <i class="glyphicon glyphicon-floppy-disk" aria-hidden="true"></i> Save
    </a>
    <a href="/cancel/1" class="btn btn-default">Cancel</a>
</div>

Conversely, you can also change a button to appear like a link:

<button type="button" class="btn btn-link">Link</button>

How to delete all files from a specific folder?

You can do it via FileInfo or DirectoryInfo:

DirectoryInfo di = new DirectoryInfo("TempDir");
di.Delete(true);

And then recreate the directory

"Incorrect string value" when trying to insert UTF-8 into MySQL via JDBC?

Got the same problem, to save the data with utf8mb4 needs to make sure:

  1. character_set_client, character_set_connection, character_set_results are utf8mb4: character_set_client and character_set_connection indicate the character set in which statements are sent by the client, character_set_results indicates the character set in which the server returns query results to the client.
    See charset-connection.

  2. the table and column encoding is utf8mb4

For JDBC, there are two solutions:

Solution 1 (need to restart MySQL):

  1. modify my.cnf like the following and restart MySQL:

    [mysql]
    default-character-set=utf8mb4
    
    [mysqld]
    character-set-server=utf8mb4
    collation-server=utf8mb4_unicode_ci
    

this can make sure the database and character_set_client, character_set_connection, character_set_results are utf8mb4 by default.

  1. restart MySQL

  2. change the table and column encoding to utf8mb4

  3. STOP specifying characterEncoding=UTF-8 and characterSetResults=UTF-8 in the jdbc connector,cause this will override character_set_client, character_set_connection, character_set_results to utf8

Solution two (don't need to restart MySQL):

  1. change the table and column encoding to utf8mb4

  2. specifying characterEncoding=UTF-8 in the jdbc connector,cause the jdbc connector doesn't suport utf8mb4.

  3. write your sql statment like this (need to add allowMultiQueries=true to jdbc connector):

    'SET NAMES utf8mb4;INSERT INTO Mytable ...';
    

this will make sure each connection to the server, character_set_client,character_set_connection,character_set_results are utf8mb4.
Also see charset-connection.

Get the filePath from Filename using Java

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

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

How to run a javascript function during a mouseover on a div

I'm assuming you want to display the welcome when you mouse over "some text".

As a message box, this will be:

<div id="sub1" onmouseover="javascript:alert('Welcome!');">some text</div>

As a tooltip, it should be:

<div id="sub1" title="Welcome!">some text</div>

As a new div, you can use:

<div id="sub1" onmouseover="javascript:var mydiv = document.createElement('div'); mydiv.height = 100; mydiv.width = 100; mydiv.zindex = 1000; mydiv.innerHTML = 'Welcome!'; mydiv.position = 'absolute'; mydiv.top = 0; mydiv.left = 0;">some text</div>

You should NEVER contain spaces in the id of an element.

MAX function in where clause mysql

SELECT firstName, Lastname, MAX(id) as max WHERE YOUR_CONDITIONS_HERE HAVING id=max(id) 

Check if date is a valid one

Try this one. It is not nice but it will work as long as the input is constant format from your date picker.

It is badDate coming from your picker in this example

https://jsfiddle.net/xs8tvox9/

var dateFormat = 'DD-MM-YYYY'
var badDate = "2016-10-19";

var splittedDate = badDate.split('-');

if (splittedDate.length == 3) {
  var d = moment(splittedDate[2]+"-"+splittedDate[1]+"-"+splittedDate[0], dateFormat);
  alert(d.isValid())
} else {
  //incorrectFormat
}

How to make all controls resize accordingly proportionally when window is maximized?

Well, it's fairly simple to do.

On the window resize event handler, calculate how much the window has grown/shrunk, and use that fraction to adjust 1) Height, 2) Width, 3) Canvas.Top, 4) Canvas.Left properties of all the child controls inside the canvas.

Here's the code:

private void window1_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            myCanvas.Width = e.NewSize.Width;
            myCanvas.Height = e.NewSize.Height;

            double xChange = 1, yChange = 1;

            if (e.PreviousSize.Width != 0)
            xChange = (e.NewSize.Width/e.PreviousSize.Width);

            if (e.PreviousSize.Height != 0)
            yChange = (e.NewSize.Height / e.PreviousSize.Height);

            foreach (FrameworkElement fe in myCanvas.Children )
            {   
                /*because I didn't want to resize the grid I'm having inside the canvas in this particular instance. (doing that from xaml) */            
                if (fe is Grid == false)
                {
                    fe.Height = fe.ActualHeight * yChange;
                    fe.Width = fe.ActualWidth * xChange;

                    Canvas.SetTop(fe, Canvas.GetTop(fe) * yChange);
                    Canvas.SetLeft(fe, Canvas.GetLeft(fe) * xChange);

                }
            }
        }

How to access /storage/emulated/0/

Android recommends that you call Environment.getExternalStorageDirectory.getPath() instead of hardcoding /sdcard/ in path name. This returns the primary shared/external storage directory. So, if storage is emulated, this will return /storage/emulated/0. If you explore the device storage with a file explorer, the said directory will be /mnt/sdcard (confirmed on Xperia Z2 running Android 6).

How to merge multiple dicts with same key or different key?

assuming all keys are always present in all dicts:

ds = [d1, d2]
d = {}
for k in d1.iterkeys():
    d[k] = tuple(d[k] for d in ds)

Note: In Python 3.x use below code:

ds = [d1, d2]
d = {}
for k in d1.keys():
  d[k] = tuple(d[k] for d in ds)

and if the dic contain numpy arrays:

ds = [d1, d2]
d = {}
for k in d1.keys():
  d[k] = np.concatenate(list(d[k] for d in ds))

How to deploy a React App on Apache web server

As said in the post, React is a browser based technology. It only renders a view in an HTML document.

To be able to have access to your "React App", you need to:

  1. Bundle your React app in a bundle
  2. Have Apache pointing to your html file in your server, and allowing access externally.

You might have all the informations here: https://httpd.apache.org/docs/trunk/getting-started.html for the Apache server, and here to make your javascript bundle https://www.codementor.io/tamizhvendan/beginner-guide-setup-reactjs-environment-npm-babel-6-webpack-du107r9zr

Angular 4 default radio button checked by default

getting following error

_x000D_
_x000D_
It happens:  Error: 
      ngModel cannot be used to register form controls with a parent formGroup directive.  Try using
      formGroup's partner directive "formControlName" instead.  Example:
_x000D_
_x000D_
_x000D_

Gson: How to exclude specific fields from Serialization without annotations

I used this strategy: i excluded every field which is not marked with @SerializedName annotation, i.e.:

public class Dummy {

    @SerializedName("VisibleValue")
    final String visibleValue;
    final String hiddenValue;

    public Dummy(String visibleValue, String hiddenValue) {
        this.visibleValue = visibleValue;
        this.hiddenValue = hiddenValue;
    }
}


public class SerializedNameOnlyStrategy implements ExclusionStrategy {

    @Override
    public boolean shouldSkipField(FieldAttributes f) {
        return f.getAnnotation(SerializedName.class) == null;
    }

    @Override
    public boolean shouldSkipClass(Class<?> clazz) {
        return false;
    }
}


Gson gson = new GsonBuilder()
                .setExclusionStrategies(new SerializedNameOnlyStrategy())
                .create();

Dummy dummy = new Dummy("I will see this","I will not see this");
String json = gson.toJson(dummy);

It returns

{"VisibleValue":"I will see this"}

Difference between Fact table and Dimension table?

In the simplest form, I think a dimension table is something like a 'Master' table - that keeps a list of all 'items', so to say.

A fact table is a transaction table which describes all the transactions. In addition, aggregated (grouped) data like total sales by sales person, total sales by branch - such kinds of tables also might exist as independent fact tables.

How to check if a string contains a specific text

You can use strpos() or stripos() to check if the string contain the given needle. It will return the position where it was found, otherwise will return FALSE.

Use the operators === or `!== to differ FALSE from 0 in PHP.

Is Constructor Overriding Possible?

No it is not possible to override a constructor. If we try to do this then compiler error will come. And it is never possible in Java. Lets see the example. It will ask please write a return type o the method. means it will treat that overriden constructor as a method not as a constructor.

package com.sample.test;

class Animal{

    public static void showMessage()
    {
        System.out.println("we are in Animal class");
    }
}

class Dog extends Animal{

    public void DogShow() 
    {
        System.out.println("we are in Dog show class");
    } 

    public static void showMessage()
    {
        System.out.println("we are in overriddn method of dog class");
    }
}

public class AnimalTest { 

    public static void main(String [] args)
    {
        Animal animal = new Animal();
        animal.showMessage();

        Dog dog = new Dog();
        dog.DogShow();

        Animal animal2 = new Dog();
        animal2.showMessage();
    }

}

How to determine the number of days in a month in SQL Server?

I upvoted Mehrdad, but this works as well. :)

CREATE function dbo.IsLeapYear
(
    @TestYear int
)
RETURNS bit
AS
BEGIN
    declare @Result bit
    set @Result = 
    cast(
        case when ((@TestYear % 4 = 0) and (@testYear % 100 != 0)) or (@TestYear % 400 = 0)
        then 1
        else 0
        end
    as bit )
    return @Result
END
GO

CREATE FUNCTION dbo.GetDaysInMonth
(
    @TestDT datetime
)
RETURNS INT
AS
BEGIN

    DECLARE @Result int 
    DECLARE @MonthNo int

    Set @MonthNo = datepart(m,@TestDT)

    Set @Result = 
    case @MonthNo
        when  1 then 31
        when  2 then 
            case 
                when dbo.IsLeapYear(datepart(yyyy,@TestDT)) = 0
                then 28
                else 29
            end
        when  3 then 31
        when  4 then 30
        when  5 then 31
        when  6 then 30
        when  7 then 31
        when  8 then 31
        when  9 then 30 
        when 10 then 31
        when 11 then 30 
        when 12 then 31
    end

    RETURN @Result
END
GO

To Test

declare @testDT datetime;

set @testDT = '2404-feb-15';

select dbo.GetDaysInMonth(@testDT)

How to generate a create table script for an existing table in phpmyadmin?

Using PHP Function.

Of course query function ($this->model) you have to change to your own.

/**
 * Creating a copy table based on the current one
 * 
 * @param type $table_to_copy
 * @param type $new_table_name
 * @return type
 * @throws Exception
 */
public function create($table_to_copy, $new_table_name)
{
    $sql = "SHOW CREATE TABLE ".$table_to_copy;

    $res = $this->model->queryRow($sql, PDO::FETCH_ASSOC);

    if(!filled($res['Create Table']))
        throw new Exception('Could not get the create code for '.$table_to_copy);

    $newCreateSql = preg_replace(array(
        '@CREATE TABLE `'.$table_to_copy.'`@',
        '@KEY `'.$table_to_copy.'(.*?)`@',
        '@CONSTRAINT `'.$table_to_copy.'(.*?)`@',
        '@AUTO_INCREMENT=(.*?) @',
    ), array(
        'CREATE TABLE `'.$new_table_name.'`',
        'KEY `'.$new_table_name.'$1`',
        'CONSTRAINT `'.$new_table_name.'$1`',
        'AUTO_INCREMENT=1 ',
    ), $res['Create Table']);

    return $this->model->exec($newCreateSql);
}

Formatting DataBinder.Eval data

To format the date using the local date format use:

<%#((DateTime)Eval("ExpDate")).ToString("d")%>

How to Format an Eval Statement to Display a Date using Date Locale

What's the difference between SoftReference and WeakReference in Java?

Weak Reference http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/ref/WeakReference.html

Principle: weak reference is related to garbage collection. Normally, object having one or more reference will not be eligible for garbage collection.
The above principle is not applicable when it is weak reference. If an object has only weak reference with other objects, then its ready for garbage collection.

Let's look at the below example: We have an Map with Objects where Key is reference a object.

import java.util.HashMap;   
public class Test {

    public static void main(String args[]) {
        HashMap<Employee, EmployeeVal> aMap = new 
                       HashMap<Employee, EmployeeVal>();

        Employee emp = new Employee("Vinoth");
        EmployeeVal val = new EmployeeVal("Programmer");

        aMap.put(emp, val);

        emp = null;

        System.gc();
        System.out.println("Size of Map" + aMap.size());

    }
}

Now, during the execution of the program we have made emp = null. The Map holding the key makes no sense here as it is null. In the above situation, the object is not garbage collected.

WeakHashMap

WeakHashMap is one where the entries (key-to-value mappings) will be removed when it is no longer possible to retrieve them from the Map.

Let me show the above example same with WeakHashMap

import java.util.WeakHashMap;

public class Test {

    public static void main(String args[]) {
        WeakHashMap<Employee, EmployeeVal> aMap = 
                    new WeakHashMap<Employee, EmployeeVal>();

        Employee emp = new Employee("Vinoth");
        EmployeeVal val = new EmployeeVal("Programmer");

        aMap.put(emp, val);

        emp = null;

        System.gc();
        int count = 0;
        while (0 != aMap.size()) {
            ++count;
            System.gc();
        }
        System.out.println("Took " + count
                + " calls to System.gc() to result in weakHashMap size of : "
                + aMap.size());
    }
}

Output: Took 20 calls to System.gc() to result in aMap size of : 0.

WeakHashMap has only weak references to the keys, not strong references like other Map classes. There are situations which you have to take care when the value or key is strongly referenced though you have used WeakHashMap. This can avoided by wrapping the object in a WeakReference.

import java.lang.ref.WeakReference;
import java.util.HashMap;

public class Test {

    public static void main(String args[]) {
        HashMap<Employee, EmployeeVal> map = 
                      new HashMap<Employee, EmployeeVal>();
        WeakReference<HashMap<Employee, EmployeeVal>> aMap = 
                       new WeakReference<HashMap<Employee, EmployeeVal>>(
                map);

        map = null;

        while (null != aMap.get()) {
            aMap.get().put(new Employee("Vinoth"),
                    new EmployeeVal("Programmer"));
            System.out.println("Size of aMap " + aMap.get().size());
            System.gc();
        }
        System.out.println("Its garbage collected");
    }
}

Soft References.

Soft Reference is slightly stronger that weak reference. Soft reference allows for garbage collection, but begs the garbage collector to clear it only if there is no other option.

The garbage collector does not aggressively collect softly reachable objects the way it does with weakly reachable ones -- instead it only collects softly reachable objects if it really "needs" the memory. Soft references are a way of saying to the garbage collector, "As long as memory isn't too tight, I'd like to keep this object around. But if memory gets really tight, go ahead and collect it and I'll deal with that." The garbage collector is required to clear all soft references before it can throw OutOfMemoryError.

How to get current date time in milliseconds in android

I think leverage this functionality using Java

long time= System.currentTimeMillis();

this will return current time in milliseconds mode . this will surely work

long time= System.currentTimeMillis();
android.util.Log.i("Time Class ", " Time value in millisecinds "+time);

Here is my logcat using the above function

05-13 14:38:03.149: INFO/Time Class(301): Time value in millisecinds 1368436083157

If you got any doubt with millisecond value .Check Here

EDIT : Time Zone I used to demo the code IST(+05:30) ,So if you check milliseconds that mentioned in log to match with time in log you might get a different value based your system timezone

EDIT: This is easy approach .but if you need time zone or any other details I think this won't be enough Also See this approach using android api support

What's the difference between ngOnInit and ngAfterViewInit of Angular2?

Content is what is passed as children. View is the template of the current component.

The view is initialized before the content and ngAfterViewInit() is therefore called before ngAfterContentInit().

** ngAfterViewInit() is called when the bindings of the children directives (or components) have been checked for the first time. Hence its perfect for accessing and manipulating DOM with Angular 2 components. As @Günter Zöchbauer mentioned before is correct @ViewChild() hence runs fine inside it.

Example:

@Component({
    selector: 'widget-three',
    template: `<input #input1 type="text">`
})
export class WidgetThree{
    @ViewChild('input1') input1;

    constructor(private renderer:Renderer){}

    ngAfterViewInit(){
        this.renderer.invokeElementMethod(
            this.input1.nativeElement,
            'focus',
            []
        )
    }
}

How do I check if file exists in jQuery or pure JavaScript?

i used this script to add alternative image

function imgError()
{
alert('The image could not be loaded.');
}

HTML:

<img src="image.gif" onerror="imgError()" />

http://wap.w3schools.com/jsref/event_onerror.asp

Convert js Array() to JSon object for use with JQuery .ajax

There is actuly a difference between array object and JSON object. Instead of creating array object and converting it into a json object(with JSON.stringify(arr)) you can do this:

var sels = //Here is your array of SELECTs
var json = { };

for(var i = 0, l = sels.length; i < l; i++) {
  json[sels[i].id] = sels[i].value;
}

There is no need of converting it into JSON because its already a json object. To view the same use json.toSource();

How to get exact browser name and version?

Since some codes gave a wrong result for Edge and Opera, I suggest to try this code:

$popularBrowsers = ["Opera","OPR/", "Edg", "Chrome", "Safari", "Firefox", "MSIE", "Trident"];

$userAgent = $_SERVER['HTTP_USER_AGENT'];
$userBrowser = 'Other less popular browsers';
foreach ($popularBrowsers as $browser) {
    if (strpos($userAgent, $browser) !== false) {
        $userBrowser = $browser;
        break;
    }
}

switch ($userBrowser) {
    case 'OPR/':
        $userBrowser = 'Opera';
        break;
    case 'MSIE':
        $userBrowser = 'Internet Explorer';
        break;

    case 'Trident':
        $userBrowser = 'Internet Explorer';
        break;

    case 'Edg':
        $userBrowser = 'Microsoft Edge';
        break;
}

echo "Your browser: " . $userBrowser;

For information about agent strings for different browsers and some similarities in them, please refer to: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/User-Agent

Removing all unused references from a project in Visual Studio projects

You can use Reference Assistant extension from the Visual Studio extension gallery.

Used and works for Visual Studio 2010.

Changing the default icon in a Windows Forms application

You can change the app icon under project properties. Individual form icons under form properties.

How does one use glide to download an image into a bitmap?

This is what worked for me: https://github.com/bumptech/glide/wiki/Custom-targets#overriding-default-behavior

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.transition.Transition;
import com.bumptech.glide.request.target.BitmapImageViewTarget;

...

Glide.with(yourFragment)
  .load("yourUrl")
  .asBitmap()
  .into(new BitmapImageViewTarget(yourImageView) {
    @Override
    public void onResourceReady(Bitmap bitmap, Transition<? super Bitmap> anim) {
        super.onResourceReady(bitmap, anim);
        Palette.generateAsync(bitmap, new Palette.PaletteAsyncListener() {  
            @Override
            public void onGenerated(Palette palette) {
                // Here's your generated palette
                Palette.Swatch swatch = palette.getDarkVibrantSwatch();
                int color = palette.getDarkVibrantColor(swatch.getTitleTextColor());
            }
        });
    }
});

In PHP, how can I add an object element to an array?

Just do:

$object = new stdClass();
$object->name = "My name";
$myArray[] = $object;

You need to create the object first (the new line) and then push it onto the end of the array (the [] line).

You can also do this:

$myArray[] = (object) ['name' => 'My name'];

However I would argue that's not as readable, even if it is more succinct.

How do I remove a library from the arduino environment?

Quote from official documentation as of August 2013:

User-created libraries as of version 0017 go in a subdirectory of your default sketch directory. For example, on OSX, the new directory would be ~/Documents/Arduino/libraries/. On Windows, it would be My Documents\Arduino\libraries\. To add your own library, create a new directory in the libraries directory with the name of your library. The folder should contain a C or C++ file with your code and a header file with your function and variable declarations. It will then appear in the Sketch | Import Library menu in the Arduino IDE.

To remove a library, stop the Arduino IDE and remove the library directory from the aforementioned location.

Change the Right Margin of a View Programmatically?

Update: Android KTX

The Core KTX module provides extensions for common libraries that are part of the Android framework, androidx.core.view among them.

dependencies {
    implementation "androidx.core:core-ktx:{latest-version}"
}

The following extension functions are handy to deal with margins:

Note: they are all extension functions of MarginLayoutParams, so first you need to get and cast the layoutParams of your view:

val params = (myView.layoutParams as ViewGroup.MarginLayoutParams)

Sets the margins of all axes in the ViewGroup's MarginLayoutParams. (The dimension has to be provided in pixels, see the last section if you want to work with dp)

inline fun MarginLayoutParams.setMargins(@Px size: Int): Unit
// E.g. 16px margins
params.setMargins(16)

Updates the margins in the ViewGroup's ViewGroup.MarginLayoutParams.

inline fun MarginLayoutParams.updateMargins(
    @Px left: Int = leftMargin, 
    @Px top: Int = topMargin, 
    @Px right: Int = rightMargin, 
    @Px bottom: Int = bottomMargin
): Unit
// Example: 8px left margin 
params.updateMargins(left = 8)

Updates the relative margins in the ViewGroup's MarginLayoutParams (start/end instead of left/right).

inline fun MarginLayoutParams.updateMarginsRelative(
    @Px start: Int = marginStart, 
    @Px top: Int = topMargin, 
    @Px end: Int = marginEnd, 
    @Px bottom: Int = bottomMargin
): Unit
// E.g: 8px start margin 
params.updateMargins(start = 8)

The following extension properties are handy to get the current margins:

inline val View.marginBottom: Int
inline val View.marginEnd: Int
inline val View.marginLeft: Int
inline val View.marginRight: Int
inline val View.marginStart: Int
inline val View.marginTop: Int
// E.g: get margin bottom
val bottomPx = myView1.marginBottom
  • Using dp instead of px:

If you want to work with dp (density-independent pixels) instead of px, you will need to convert them first. You can easily do that with the following extension property:

val Int.px: Int
    get() = (this * Resources.getSystem().displayMetrics.density).toInt()

Then you can call the previous extension functions like:

params.updateMargins(start = 16.px, end = 16.px, top = 8.px, bottom = 8.px)
val bottomDp = myView1.marginBottom.dp

Old answer:

In Kotlin you can declare an extension function like:

fun View.setMargins(
    leftMarginDp: Int? = null,
    topMarginDp: Int? = null,
    rightMarginDp: Int? = null,
    bottomMarginDp: Int? = null
) {
    if (layoutParams is ViewGroup.MarginLayoutParams) {
        val params = layoutParams as ViewGroup.MarginLayoutParams
        leftMarginDp?.run { params.leftMargin = this.dpToPx(context) }
        topMarginDp?.run { params.topMargin = this.dpToPx(context) }
        rightMarginDp?.run { params.rightMargin = this.dpToPx(context) }
        bottomMarginDp?.run { params.bottomMargin = this.dpToPx(context) }
        requestLayout()
    }
}

fun Int.dpToPx(context: Context): Int {
    val metrics = context.resources.displayMetrics
    return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, this.toFloat(), metrics).toInt()
}

Then you can call it like:

myView1.setMargins(8, 16, 34, 42)

Or:

myView2.setMargins(topMarginDp = 8) 

Output data with no column headings using PowerShell

In your case, when you just select a single property, the easiest way is probably to bypass any formatting altogether:

get-qadgroupmember 'Domain Admins' | foreach { $_.Name }

This will get you a simple string[] without column headings or empty lines. The Format-* cmdlets are mainly for human consumption and thus their output is not designed to be easily machine-readable or -parseable.

For multiple properties I'd probably go with the -f format operator. Something along the lines of

alias | %{ "{0,-10}{1,-10}{2,-60}" -f $_.COmmandType,$_.Name,$_.Definition }

which isn't pretty but gives you easy and complete control over the output formatting. And no empty lines :-)

Back to previous page with header( "Location: " ); in PHP

Its so simple just use this

header("location:javascript://history.go(-1)");

Its working fine for me

How to tell CRAN to install package dependencies automatically?

On your own system, try

install.packages("foo", dependencies=...)

with the dependencies= argument is documented as

dependencies: logical indicating to also install uninstalled packages
      which these packages depend on/link to/import/suggest (and so
      on recursively).  Not used if ‘repos = NULL’.  Can also be a
      character vector, a subset of ‘c("Depends", "Imports",
      "LinkingTo", "Suggests", "Enhances")’.

      Only supported if ‘lib’ is of length one (or missing), so it
      is unambiguous where to install the dependent packages.  If
      this is not the case it is ignored, with a warning.

      The default, ‘NA’, means ‘c("Depends", "Imports",
      "LinkingTo")’.

      ‘TRUE’ means (as from R 2.15.0) to use ‘c("Depends",
      "Imports", "LinkingTo", "Suggests")’ for ‘pkgs’ and
      ‘c("Depends", "Imports", "LinkingTo")’ for added
      dependencies: this installs all the packages needed to run
      ‘pkgs’, their examples, tests and vignettes (if the package
      author specified them correctly).

so you probably want a value TRUE.

In your package, list what is needed in Depends:, see the Writing R Extensions manual which is pretty clear on this.

Why does jQuery or a DOM method such as getElementById not find the element?

The element you were trying to find wasn’t in the DOM when your script ran.

The position of your DOM-reliant script can have a profound effect upon its behavior. Browsers parse HTML documents from top to bottom. Elements are added to the DOM and scripts are (generally) executed as they're encountered. This means that order matters. Typically, scripts can't find elements which appear later in the markup because those elements have yet to be added to the DOM.

Consider the following markup; script #1 fails to find the <div> while script #2 succeeds:

_x000D_
_x000D_
<script>_x000D_
  console.log("script #1: %o", document.getElementById("test")); // null_x000D_
</script>_x000D_
<div id="test">test div</div>_x000D_
<script>_x000D_
  console.log("script #2: %o", document.getElementById("test")); // <div id="test" ..._x000D_
</script>
_x000D_
_x000D_
_x000D_

So, what should you do? You've got a few options:


Option 1: Move your script

Move your script further down the page, just before the closing body tag. Organized in this fashion, the rest of the document is parsed before your script is executed:

_x000D_
_x000D_
<body>_x000D_
  <button id="test">click me</button>_x000D_
  <script>_x000D_
    document.getElementById("test").addEventListener("click", function() {_x000D_
      console.log("clicked: %o", this);_x000D_
    });_x000D_
  </script>_x000D_
</body><!-- closing body tag -->
_x000D_
_x000D_
_x000D_

Note: Placing scripts at the bottom is generally considered a best practice.


Option 2: jQuery's ready()

Defer your script until the DOM has been completely parsed, using $(handler):

_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script>_x000D_
  $(function() {_x000D_
    $("#test").click(function() {_x000D_
      console.log("clicked: %o", this);_x000D_
    });_x000D_
  });_x000D_
</script>_x000D_
<button id="test">click me</button>
_x000D_
_x000D_
_x000D_

Note: You could simply bind to DOMContentLoaded or window.onload but each has its caveats. jQuery's ready() delivers a hybrid solution.


Option 3: Event Delegation

Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time.

When an element raises an event (provided that it's a bubbling event and nothing stops its propagation), each parent in that element's ancestry receives the event as well. That allows us to attach a handler to an existing element and sample events as they bubble up from its descendants... even those added after the handler is attached. All we have to do is check the event to see whether it was raised by the desired element and, if so, run our code.

jQuery's on() performs that logic for us. We simply provide an event name, a selector for the desired descendant, and an event handler:

_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script>_x000D_
  $(document).on("click", "#test", function(e) {_x000D_
    console.log("clicked: %o",  this);_x000D_
  });_x000D_
</script>_x000D_
<button id="test">click me</button>
_x000D_
_x000D_
_x000D_

Note: Typically, this pattern is reserved for elements which didn't exist at load-time or to avoid attaching a large amount of handlers. It's also worth pointing out that while I've attached a handler to document (for demonstrative purposes), you should select the nearest reliable ancestor.


Option 4: The defer attribute

Use the defer attribute of <script>.

[defer, a Boolean attribute,] is set to indicate to a browser that the script is meant to be executed after the document has been parsed, but before firing DOMContentLoaded.

_x000D_
_x000D_
<script src="https://gh-canon.github.io/misc-demos/log-test-click.js" defer></script>_x000D_
<button id="test">click me</button>
_x000D_
_x000D_
_x000D_

For reference, here's the code from that external script:

document.getElementById("test").addEventListener("click", function(e){
   console.log("clicked: %o", this); 
});

Note: The defer attribute certainly seems like a magic bullet but it's important to be aware of the caveats...
1. defer can only be used for external scripts, i.e.: those having a src attribute.
2. be aware of browser support, i.e.: buggy implementation in IE < 10

Changing the current working directory in Java?

You can use

new File("relative/path").getAbsoluteFile()

after

System.setProperty("user.dir", "/some/directory")

System.setProperty("user.dir", "C:/OtherProject");
File file = new File("data/data.csv").getAbsoluteFile();
System.out.println(file.getPath());

Will print

C:\OtherProject\data\data.csv

Java constant examples (Create a java file having only constants)

You can also use the Properties class

Here's the constants file called

# this will hold all of the constants
frameWidth = 1600
frameHeight = 900

Here is the code that uses the constants

public class SimpleGuiAnimation {

    int frameWidth;
    int frameHeight;


    public SimpleGuiAnimation() {
        Properties properties = new Properties();

        try {
            File file = new File("src/main/resources/dataDirectory/gui_constants.properties");
            FileInputStream fileInputStream = new FileInputStream(file);
            properties.load(fileInputStream);
        }
        catch (FileNotFoundException fileNotFoundException) {
            System.out.println("Could not find the properties file" + fileNotFoundException);
        }
        catch (Exception exception) {
            System.out.println("Could not load properties file" + exception.toString());
        }


        this.frameWidth = Integer.parseInt(properties.getProperty("frameWidth"));
        this.frameHeight = Integer.parseInt(properties.getProperty("frameHeight"));
    }

Best practices for API versioning?

There are a few places you can do versioning in a REST API:

  1. As noted, in the URI. This can be tractable and even esthetically pleasing if redirects and the like are used well.

  2. In the Accepts: header, so the version is in the filetype. Like 'mp3' vs 'mp4'. This will also work, though IMO it works a bit less nicely than...

  3. In the resource itself. Many file formats have their version numbers embedded in them, typically in the header; this allows newer software to 'just work' by understanding all existing versions of the filetype while older software can punt if an unsupported (newer) version is specified. In the context of a REST API, it means that your URIs never have to change, just your response to the particular version of data you were handed.

I can see reasons to use all three approaches:

  1. if you like doing 'clean sweep' new APIs, or for major version changes where you want such an approach.
  2. if you want the client to know before it does a PUT/POST whether it's going to work or not.
  3. if it's okay if the client has to do its PUT/POST to find out if it's going to work.

Complete list of reasons why a css file might not be working

  1. I had the same problem, and I used the UTF-8 coding for both of my files as follows:

    add @charset "UTF-8"; in CSS file and <meta charset="UTF-8"> under <head> tag in HTML file. and it worked for me.

    it makes the same encoding for both the files i.e HTML and CSS.

    You can also do the same for "UTF-16" encoding.

  2. If it is still not working check for the <link type="text/css" rel="stylesheet" href="style.css"/> under <head> tag in HTML File where you should mention type="text/css"

How do I use two submit buttons, and differentiate between which one was used to submit the form?

Give each input a name attribute. Only the clicked input's name attribute will be sent to the server.

<input type="submit" name="publish" value="Publish">
<input type="submit" name="save" value="Save">

And then

<?php
    if (isset($_POST['publish'])) {
        # Publish-button was clicked
    }
    elseif (isset($_POST['save'])) {
        # Save-button was clicked
    }
?>

Edit: Changed value attributes to alt. Not sure this is the best approach for image buttons though, any particular reason you don't want to use input[type=image]?

Edit: Since this keeps getting upvotes I went ahead and changed the weird alt/value code to real submit inputs. I believe the original question asked for some sort of image buttons but there are so much better ways to achieve that nowadays instead of using input[type=image].

Extracting Nupkg files using command line

did the same thing like this:

clear
cd PACKAGE_DIRECTORY

function Expand-ZIPFile($file, $destination)
{
    $shell = New-Object -ComObject Shell.Application
    $zip = $shell.NameSpace($file)
    foreach($item in $zip.items())
    {
        $shell.Namespace($destination).copyhere($item)
    }
}

Dir *.nupkg | rename-item -newname {  $_.name  -replace ".nupkg",".zip"  }

Expand-ZIPFile "Package.1.0.0.zip" “DESTINATION_PATH”

How do I put an image into my picturebox using ImageLocation?

Setting the image using picture.ImageLocation() works fine, but you are using a relative path. Check your path against the location of the .exe after it is built.

For example, if your .exe is located at:

<project folder>/bin/Debug/app.exe

The image would have to be at:

<project folder>/bin/Image/1.jpg


Of course, you could just set the image at design-time (the Image property on the PictureBox property sheet).

If you must set it at run-time, one way to make sure you know the location of the image is to add the image file to your project. For example, add a new folder to your project, name it Image. Right-click the folder, choose "Add existing item" and browse to your image (be sure the file filter is set to show image files). After adding the image, in the property sheet set the Copy to Output Directory to Copy if newer.

At this point the image file will be copied when you build the application and you can use

picture.ImageLocation = @"Image\1.jpg"; 

Javascript Equivalent to C# LINQ Select

I know it is a late answer but it was useful to me! Just to complete, using the $.grep function you can emulate the linq where().

Linq:

var maleNames = people
.Where(p => p.Sex == "M")
.Select(p => p.Name)

Javascript:

// replace where  with $.grep
//         select with $.map
var maleNames = $.grep(people, function (p) { return p.Sex == 'M'; })
            .map(function (p) { return p.Name; });

Unable to load Private Key. (PEM routines:PEM_read_bio:no start line:pem_lib.c:648:Expecting: ANY PRIVATE KEY)

Had same issue today, and noticed that this occurs when owner/group of file is not the one running app that reads key. Maybe is your issue too.

How to change the font and font size of an HTML input tag?

<input type ="text" id="txtComputer">

css

input[type="text"]
{
    font-size:24px;
}

Server unable to read htaccess file, denying access to be safe

This is a common problem with GoDaddy virtual server hosting when you bring up a new website.

Assuming you have SSH access to the server (you have to enable it on cPanel), login to your account. Upon successful login, you will be placed in the home directory for your account. The DocumentRoot for your website is located in a subdirectory named public_html. GoDaddy defaults the permissions for this directory to 750, but those permissions are inadequate to allow Apache to read the files for website. You need to change the permissions for this directory to 755 (chmod 755 public_html).

Copy the files for your website into the public_html directory (both scp and rsync work for copying files to a GoDaddy Linux server).

Next, make sure all of the files under public_html are world readable. To do this, use this command:

cd public_html
chmod -R o+r *

If you have other subdirectories (like css, js, and img), make sure they are world accessible by enabling both read and execute for world access:

chmod o+rx css
chmod o+rx img
chmod o+rx js

Last, you will need to have a .htaccess file in the public_html file. GoDaddy enforces a rule that prohibits the site for loading if you do not have a .htaccess file in your public_html directory. You can use vi to create this file ("vi .htaccess"). Enter the following lines in the file:

Order allow,deny
Allow from all
Require all granted

This config will work for both Apache 2.2 and Apache 2.4. Save the file (ZZ), and then make sure the file has permissions of 644:

chmod 644 .htaccess

Works like a charm.

How to skip the first n rows in sql query

Query: in

DECLARE @N INT = 5 --Any random number

SELECT * FROM (
        SELECT ROW_NUMBER() OVER(ORDER BY ID) AS RoNum
              , ID --Add any fields needed here (or replace ID by *)
        FROM TABLE_NAME
) AS tbl 
WHERE @N < RoNum
ORDER BY tbl.ID

This will give rows of Table, where rownumber is starting from @N + 1.

How to uninstall Golang?

For Windows 10:

  1. Go to Apps in the Settings App.
  2. Look for Go Programming Language * in the list and uninstall it.
  3. Remove C:\Go\bin from your PATH environment variable (only if you don't plan on installing another version of golang)

Get width in pixels from element with style set with %?

You want to get the computed width. Try: .offsetWidth

(I.e: this.offsetWidth='50px' or var w=this.offsetWidth)

You might also like this answer on SO.

How do I handle ImeOptions' done button click?

If you use Android Annotations https://github.com/androidannotations/androidannotations

You can use @EditorAction annotation

@EditorAction(R.id.your_component_id)
void onDoneAction(EditText view, int actionId){
    if(actionId == EditorInfo.IME_ACTION_DONE){
        //Todo: Do your work or call a method
    }
}

Multiple left joins on multiple tables in one query

The JOIN statements are also part of the FROM clause, more formally a join_type is used to combine two from_item's into one from_item, multiple one of which can then form a comma-separated list after the FROM. See http://www.postgresql.org/docs/9.1/static/sql-select.html .

So the direct solution to your problem is:

SELECT something
FROM
    master as parent LEFT JOIN second as parentdata
        ON parent.secondary_id = parentdata.id,
    master as child LEFT JOIN second as childdata
        ON child.secondary_id = childdata.id
WHERE parent.id = child.parent_id AND parent.parent_id = 'rootID'

A better option would be to only use JOIN's, as it has already been suggested.

How do you share code between projects/solutions in Visual Studio?

You would simply create a separate Class Library project to contain the common code. It need not be part of any solution that uses it. Reference the class library from any project that needs it.

The only trick at all is that you will need to use a file reference to reference the project, since it will not be part of the solutions that refer to it. This means that the actual output assembly will have to be placed in a location that can be accessed by anyone building a project that references it. This can be done by placing the assembly on a share, for instance.

how to pass value from one php page to another using session

Use something like this:

page1.php

<?php
session_start();
$_SESSION['myValue']=3; // You can set the value however you like.
?>

Any other PHP page:

<?php
session_start();
echo $_SESSION['myValue'];
?>

A few notes to keep in mind though: You need to call session_start() BEFORE any output, HTML, echos - even whitespace.

You can keep changing the value in the session - but it will only be able to be used after the first page - meaning if you set it in page 1, you will not be able to use it until you get to another page or refresh the page.

The setting of the variable itself can be done in one of a number of ways:

$_SESSION['myValue']=1;
$_SESSION['myValue']=$var;
$_SESSION['myValue']=$_GET['YourFormElement'];

And if you want to check if the variable is set before getting a potential error, use something like this:

if(!empty($_SESSION['myValue'])
{
    echo $_SESSION['myValue'];
}
else
{
    echo "Session not set yet.";
}

visual c++: #include files from other projects in the same solution

Settings for compiler

In the project where you want to #include the header file from another project, you will need to add the path of the header file into the Additional Include Directories section in the project configuration.

To access the project configuration:

  1. Right-click on the project, and select Properties.
  2. Select Configuration Properties->C/C++->General.
  3. Set the path under Additional Include Directories.

How to include

To include the header file, simply write the following in your code:

#include "filename.h"

Note that you don't need to specify the path here, because you include the directory in the Additional Include Directories already, so Visual Studio will know where to look for it.

If you don't want to add every header file location in the project settings, you could just include a directory up to a point, and then #include relative to that point:

// In project settings
Additional Include Directories    ..\..\libroot

// In code
#include "lib1/lib1.h"    // path is relative to libroot
#include "lib2/lib2.h"    // path is relative to libroot

Setting for linker

If using static libraries (i.e. .lib file), you will also need to add the library to the linker input, so that at linkage time the symbols can be linked against (otherwise you'll get an unresolved symbol):

  1. Right-click on the project, and select Properties.
  2. Select Configuration Properties->Linker->Input
  3. Enter the library under Additional Dependencies.

PHP: How to check if image file exists?

you can use cURL. You can get cURL to only give you the headers, and not the body, which might make it faster. A bad domain could always take a while because you will be waiting for the request to time-out; you could probably change the timeout length using cURL.

Here is example:

function remoteFileExists($url) {
$curl = curl_init($url);

//don't fetch the actual page, you only want to check the connection is ok
curl_setopt($curl, CURLOPT_NOBODY, true);

//do request
$result = curl_exec($curl);

$ret = false;

//if request did not fail
if ($result !== false) {
    //if request was ok, check response code
    $statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);  

    if ($statusCode == 200) {
        $ret = true;   
    }
}

curl_close($curl);

return $ret;
}
$exists = remoteFileExists('http://stackoverflow.com/favicon.ico');
if ($exists) {
echo 'file exists';
} else {
   echo 'file does not exist';   
}

How to use ArrayList's get() method

Would this help?

final List<String> l = new ArrayList<String>();
for (int i = 0; i < 10; i++) l.add("Number " + i);
for (int i = 0; i < 10; i++) System.out.println(l.get(i));

What's the difference between a 302 and a 307 redirect?

Flowchart

  • 301: permanent redirect: the URL is old and should be replaced. Browsers will cache this.
    Example usage: URL moved from /register-form.html to signup-form.html.
    The method will change to GET, as per RFC 7231: "For historical reasons, a user agent MAY change the request method from POST to GET for the subsequent request."
  • 302: temporary redirect. Only use for HTTP/1.0 clients. This status code should not change the method, but browsers did it anyway. The RFC says: "Many pre-HTTP/1.1 user agents do not understand [303]. When interoperability with such clients is a concern, the 302 status code may be used instead, since most user agents react to a 302 response as described here for 303." Of course, some clients may implement it according to the spec, so if interoperability with such ancient clients is not a real concern, 303 is better for consistent results.
  • 303: temporary redirect, changing the method to GET.
    Example usage: if the browser sent POST to /register.php, then now load (GET) /success.html.
  • 307: temporary redirect, repeating the request identically.
    Example usage: if the browser sent a POST to /register.php, then this tells it to redo the POST at /signup.php.
  • 308: permanent redirect, repeating the request identically. Where 307 is the "no method change" counterpart of 303, this 308 status is the "no method change" counterpart of 301.

RFC 7231 (from 2014) is very readable and not overly verbose. If you want to know the exact answer, it's a recommended read. Some other answers use RFC 2616 from 1999, but nothing changed.

RFC 7238 specifies the 308 status. It is considered experimental, but it was already supported by all major browsers in 2016.

JavaScript for handling Tab Key press

You need to use Regular Expression For Website URL it is

var urlPattern = /(http|ftp|https)://[\w-]+(.[\w-]+)+([\w.,@?^=%&:/~+#-]*[\w@?^=%&/~+#-])?/

Use this Expression as in example

var regex = new RegExp(urlPattern ); var t = 'www.google.com';
var res = t.match(regex /g);

For You have to pass your web page as string to this javascript in variable t and get array

How do you see the entire command history in interactive Python?

If you want to write the history to a file:

import readline
readline.write_history_file('python_history.txt')

The help function gives:

Help on built-in function write_history_file in module readline:

write_history_file(...)
    write_history_file([filename]) -> None
    Save a readline history file.
    The default filename is ~/.history.

std::wstring VS std::string

  1. when you want to use Unicode strings and not just ascii, helpful for internationalisation
  2. yes, but it doesn't play well with 0
  3. not aware of any that don't
  4. wide character is the compiler specific way of handling the fixed length representation of a unicode character, for MSVC it is a 2 byte character, for gcc I understand it is 4 bytes. and a +1 for http://www.joelonsoftware.com/articles/Unicode.html

How to align absolutely positioned element to center?

try this method, working fine for me

position: absolute;
left: 50%;
transform: translateX(-50%); 

Fire event on enter key press for a textbox

Try follow: Aspx:

<asp:TextBox ID="TextBox1" clientidmode="Static" runat="server" onkeypress="EnterEvent(event, someMethod)"></asp:TextBox>    
<asp:Button ID="Button1" onclick="someMethod()" runat="server" Text="Button" />

JS:

function EnterEvent(e, callback) {
        if (e.keyCode == 13) {
            callback();
        }
    }

Adding a custom header to HTTP request using angular.js

If you want to add your custom headers to ALL requests, you can change the defaults on $httpProvider to always add this header…

app.config(['$httpProvider', function ($httpProvider) {
    $httpProvider.defaults.headers.common = { 
        'Authorization': 'Basic d2VudHdvcnRobWFuOkNoYW5nZV9tZQ==',
        'Accept': 'application/json;odata=verbose'
      };
}]);

java.io.FileNotFoundException: (Access is denied)

You cannot open and read a directory, use the isFile() and isDirectory() methods to distinguish between files and folders. You can get the contents of folders using the list() and listFiles() methods (for filenames and Files respectively) you can also specify a filter that selects a subset of files listed.

Decode HTML entities in Python string?

This probably isnt relevant here. But to eliminate these html entites from an entire document, you can do something like this: (Assume document = page and please forgive the sloppy code, but if you have ideas as to how to make it better, Im all ears - Im new to this).

import re
import HTMLParser

regexp = "&.+?;" 
list_of_html = re.findall(regexp, page) #finds all html entites in page
for e in list_of_html:
    h = HTMLParser.HTMLParser()
    unescaped = h.unescape(e) #finds the unescaped value of the html entity
    page = page.replace(e, unescaped) #replaces html entity with unescaped value

How to convert image file data in a byte array to a Bitmap?

Just try this:

Bitmap bitmap = BitmapFactory.decodeFile("/path/images/image.jpg");
ByteArrayOutputStream blob = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.PNG, 0 /* Ignored for PNGs */, blob);
byte[] bitmapdata = blob.toByteArray();

If bitmapdata is the byte array then getting Bitmap is done like this:

Bitmap bitmap = BitmapFactory.decodeByteArray(bitmapdata, 0, bitmapdata.length);

Returns the decoded Bitmap, or null if the image could not be decoded.

Is it good practice to use the xor operator for boolean checks?

You could always just wrap it in a function to give it a verbose name:

public static boolean XOR(boolean A, boolean B) {
    return A ^ B;
}

But, it seems to me that it wouldn't be hard for anyone who didn't know what the ^ operator is for to Google it really quick. It's not going to be hard to remember after the first time. Since you asked for other uses, its common to use the XOR for bit masking.

You can also use XOR to swap the values in two variables without using a third temporary variable.

// Swap the values in A and B
A ^= B;
B ^= A;
A ^= B;

Here's a Stackoverflow question related to XOR swapping.

How can I get a value from a map?

The main problem is that operator [] is used to insert and read a value into and from the map, so it cannot be const. If the key does not exist, it will create a new entry with a default value in it, incrementing the size of the map, that will contain a new key with an empty string ,in this particular case, as a value if the key does not exist yet. You should avoid operator[] when reading from a map and use, as was mention before, "map.at(key)" to ensure bound checking. This is one of the most common mistakes people often do with maps. You should use "insert" and "at" unless your code is aware of this fact. Check this talk about common bugs Curiously Recurring C++ Bugs at Facebook

How can I keep Bootstrap popovers alive while being hovered?

I recently needed to get this working with KO and the above solutions didn't work well when having a delay on show and hide. The below should fix this. Based on how bootstrap tooltips work. Hope this helps someone.

var options = {
                delay: { show: 1000, hide: 50 },
                trigger: 'manual',                      
                html: true
            };
var $popover = $(element).popover(options);

$popover.on('mouseenter', function () { // This is entering the triggering element
    var self = this;

    clearTimeout(self.timeout);
    self.hoverState = 'in';

    self.timeout = setTimeout(function () {
        if (self.hoverState == 'in') {
            $(self).popover("show");

            $(".popover, .popover *").on('mouseover', function () { // This is moving over the popover
                clearTimeout(self.timeout);
            });                                                                 

            $(".popover").on('mouseleave', function () { // This is leaving the popover
                self.timeout = setTimeout(function () {
                    if (self.hoverState == 'out') {
                        $(self).popover('hide');
                    }
                }, options.delay.hide);
            });
        }
    }, options.delay.show);
}).on('mouseleave', function (event) { // This is leaving the triggering element
    var self = this;

    clearTimeout(self.timeout);
    self.hoverState = 'out';

    self.timeout = setTimeout(function () {                             
        if (self.hoverState == 'out') {
            $(self).popover('hide');
        }

    }, options.delay.hide);
});

Returning first x items from array

You can use array_slice function, but do you will use another values? or only the first 5? because if you will use only the first 5 you can use the LIMIT on SQL.

Are duplicate keys allowed in the definition of binary search trees?

I just want to add some more information to what @Robert Paulson answered.

Let's assume that node contains key & data. So nodes with the same key might contain different data.
(So the search must find all nodes with the same key)

  1. left <= cur < right
  1. left < cur <= right
  1. left <= cur <= right
  1. left < cur < right && cur contain sibling nodes with the same key.
  1. left < cur < right, such that no duplicate keys exist.

1 & 2. works fine if the tree does not have any rotation-related functions to prevent skewness.
But this form doesn't work with AVL tree or Red-Black tree, because rotation will break the principal.
And even if search() finds the node with the key, it must traverse down to the leaf node for the nodes with duplicate key.
Making time complexity for search = theta(logN)

3. will work well with any form of BST with rotation-related functions.
But the search will take O(n), ruining the purpose of using BST.
Say we have the tree as below, with 3) principal.

         12
       /    \
     10     20
    /  \    /
   9   11  12 
      /      \
    10       12

If we do search(12) on this tree, even tho we found 12 at the root, we must keep search both left & right child to seek for the duplicate key.
This takes O(n) time as I've told.

4. is my personal favorite. Let's say sibling means the node with the same key.
We can change above tree into below.

         12 - 12 - 12
       /    \
10 - 10     20
    /  \
   9   11

Now any search will take O(logN) because we don't have to traverse children for the duplicate key.
And this principal also works well with AVL or RB tree.

What does the @ symbol before a variable name mean in C#?

The @ symbol allows you to use reserved word. For example:

int @class = 15;

The above works, when the below wouldn't:

int class = 15;

On logout, clear Activity history stack, preventing "back" button from opening logged-in-only Activities

Start you activity with StartActivityForResult and while you logout set your result and according to you result finish your activity

intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivityForResult(intent, BACK_SCREEN);

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch (requestCode) {
    case BACK_SCREEN:
        if (resultCode == REFRESH) {
            setResult(REFRESH);
            finish();
        }
        break;
    }
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        AlertDialog alertDialog = builder.create();

        alertDialog
                .setTitle((String) getResources().getText(R.string.home));
        alertDialog.setMessage((String) getResources().getText(
                R.string.gotoHome));
        alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "Yes",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog,
                            int whichButton) {

                        setResult(REFRESH);
                        finish();
                    }

                });

        alertDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "No",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog,
                            int whichButton) {
                    }
                });
        alertDialog.show();
        return true;
    } else
        return super.onKeyDown(keyCode, event);

}

Whether a variable is undefined

jQuery.val() and .text() will never return 'undefined' for an empty selection. It always returns an empty string (i.e. ""). .html() will return null if the element doesn't exist though.You need to do:

if(page_name != '')

For other variables that don't come from something like jQuery.val() you would do this though:

if(typeof page_name != 'undefined')

You just have to use the typeof operator.

Can my enums have friendly names?

You could use the Description attribute, as Yuriy suggested. The following extension method makes it easy to get the description for a given value of the enum:

public static string GetDescription(this Enum value)
{
    Type type = value.GetType();
    string name = Enum.GetName(type, value);
    if (name != null)
    {
        FieldInfo field = type.GetField(name);
        if (field != null)
        {
            DescriptionAttribute attr = 
                   Attribute.GetCustomAttribute(field, 
                     typeof(DescriptionAttribute)) as DescriptionAttribute;
            if (attr != null)
            {
                return attr.Description;
            }
        }
    }
    return null;
}

You can use it like this:

public enum MyEnum
{
    [Description("Description for Foo")]
    Foo,
    [Description("Description for Bar")]
    Bar
}

MyEnum x = MyEnum.Foo;
string description = x.GetDescription();

How do I get elapsed time in milliseconds in Ruby?

The answer is something like:

t_start = Time.now
# time-consuming operation
t_end = Time.now

milliseconds = (t_start - t_end) * 1000.0

However, the Time.now approach risks to be inaccurate. I found this post by Luca Guidi:

https://blog.dnsimple.com/2018/03/elapsed-time-with-ruby-the-right-way/

system clock is constantly floating and it doesn't move only forwards. If your calculation of elapsed time is based on it, you're very likely to run into calculation errors or even outages.

So, it is recommended to use Process.clock_gettime instead. Something like:

def measure_time
  start_time = Process.clock_gettime(Process::CLOCK_MONOTONIC)
  yield
  end_time = Process.clock_gettime(Process::CLOCK_MONOTONIC)
  elapsed_time = end_time - start_time
  elapsed_time.round(3)
end

Example:

elapsed = measure_time do
    # your time-consuming task here:
    sleep 2.2321
end

=> 2.232

SQL Add foreign key to existing column

MySQL / SQL Server / Oracle / MS Access:

ALTER TABLE Orders
ADD FOREIGN KEY (P_Id)
REFERENCES Persons(P_Id)

To allow naming of a FOREIGN KEY constraint, and for defining a FOREIGN KEY constraint on multiple columns, use the following SQL syntax:

MySQL / SQL Server / Oracle / MS Access:

ALTER TABLE Orders
ADD CONSTRAINT fk_PerOrders
FOREIGN KEY (P_Id)
REFERENCES Persons(P_Id)

<> And Not In VB.NET

in fact the Is is really good, since to the developpers, you may want to override the operator ==, to compare with the value. say you have a class A, operator == of A is to compare some of the field of A to the parameter. then you will be in trouble in c# to verify whether the object of A is null with following code,

    A a = new A();
...
    if (a != null)
it will totally wrong, you always need to use if((object)a != null)
but in vb.net you cannot write in this way, you always need to write
    if not a is nothing then
or
    if a isnot nothing then

which just as Christian said, vb.net does not 'expected' anything.

Connection to SQL Server Works Sometimes

Try a simple SQL Server restart first before doing anything drastic. Might fix it. It did for me

Visual Studio 64 bit?

No, but the 32-bit version runs just fine on 64-bit Windows.

Number of elements in a javascript object

if you are already using jQuery in your build just do this:

$(yourObject).length

It works nicely for me on objects, and I already had jQuery as a dependancy.

Sending HTTP POST with System.Net.WebClient

As far as the http verb is concerned the WebRequest might be easier. You could go for something like:

    WebRequest r = WebRequest.Create("http://some.url");
    r.Method = "POST";
    using (var s = r.GetResponse().GetResponseStream())
    {
        using (var reader = new StreamReader(r, FileMode.Open))
        {
            var content = reader.ReadToEnd();
        }
    }

Obviously this lacks exception handling and writing the request body (for which you can use r.GetRequestStream() and write it like a regular stream, but I hope it may be of some help.

Javascript/DOM: How to remove all events of a DOM object?

You can add a hook function to intercept all calls to addEventHandler. The hook will push the handler to a list that can be used for cleanup. For example,

if (EventTarget.prototype.original_addEventListener == null) {
    EventTarget.prototype.original_addEventListener = EventTarget.prototype.addEventListener;

    function addEventListener_hook(typ, fn, opt) {
        console.log('--- add event listener',this.nodeName,typ);
        this.all_handlers = this.all_handlers || [];
        this.all_handlers.push({typ,fn,opt});
        this.original_addEventListener(typ, fn, opt);  
    }

    EventTarget.prototype.addEventListener = addEventListener_hook;
}

You should insert this code near the top of your main web page (e.g. index.html). During cleanup, you can loop thru all_handlers, and call removeEventHandler for each. Don't worry about calling removeEventHandler multiple times with the same function. It is harmless.

For example,

function cleanup(elem) {
    for (let t in elem) if (t.startsWith('on') && elem[t] != null) {
        elem[t] = null;
        console.log('cleanup removed listener from '+elem.nodeName,t);
    } 
    for (let t of elem.all_handlers || []) {
        elem.removeEventListener(t.typ, t.fn, t.opt);
        console.log('cleanup removed listener from '+elem.nodeName,t.typ);
    } 
}

Note: for IE use Element instead of EventTarget, and change => to function, and various other things.

Oracle: is there a tool to trace queries, like Profiler for sql server?

The Catch is Capture all SQL run between two points in time. Like the way SQL Server also does.

There are situations where it is useful to capture the SQL that a particular user is running in the database. Usually you would simply enable session tracing for that user, but there are two potential problems with that approach.

  1. The first is that many web based applications maintain a pool of persistent database connections which are shared amongst multiple users.
  2. The second is that some applications connect, run some SQL and disconnect very quickly, making it tricky to enable session tracing at all (you could of course use a logon trigger to enable session tracing in this case).

A quick and dirty solution to the problem is to capture all SQL statements that are run between two points in time.

The following procedure will create two tables, each containing a snapshot of the database at a particular point. The tables will then be queried to produce a list of all SQL run during that period.

If possible, you should do this on a quiet development system - otherwise you risk getting way too much data back.

  1. Take the first snapshot Run the following sql to create the first snapshot:

    create table sql_exec_before as
    select executions,hash_value
    from v$sqlarea
    /
    
  2. Get the user to perform their task within the application.

  3. Take the second snapshot.

    create table sql_exec_after as
    select executions, hash_value
    from v$sqlarea
    /
    
  4. Check the results Now that you have captured the SQL it is time to query the results.

This first query will list all query hashes that have been executed:

select  aft.hash_value
from sql_exec_after aft
left outer join sql_exec_before bef
  on aft.hash_value  =  bef.hash_value 
where aft.executions > bef.executions
   or bef.executions is null;
/

This one will display the hash and the SQL itself: set pages 999 lines 100 break on hash_value

select  hash_value, sql_text
from    v$sqltext
where   hash_value in (
    select  aft.hash_value
    from sql_exec_after aft
    left outer join sql_exec_before bef
      on aft.hash_value  =  bef.hash_value
    where aft.executions > bef.executions
       or bef.executions is null;
)
order by
    hash_value, piece
/

5. Tidy up Don't forget to remove the snapshot tables once you've finished:

drop table sql_exec_before
/

drop table sql_exec_after
/

CSS - center two images in css side by side

I've just done this for a project, and achieved it by using the h6 tag which I wasn't using for anything else:

in html code:

<h6><img alt="small drawing" src="../Images/image1.jpg" width="50%"/> <img alt="small drawing" src="../Images/image2.jpg" width="50%"/><br/>Optional caption text</h6>

The space between the image tags puts a vertical gap between the images. The width argument in each img tag is optional, but it neatly sizes the images to fill the width of the page. Notice that each image must be set to take up only 50% of the width. (Or 33% if you're using 3 images.) The width argument must come after the alt and src arguments or it won't work.

in css code:

/* h6: set presentation of images */
h6
  {
  font-family: "Franklin Gothic Demi", serif;
  font-size: 1.0em;
  font-weight: normal;
  line-height: 1.25em;
  text-align: center;
  }

The text items set the look of the caption text, and the text-align property centers both the images and the caption text.

Spring Boot without the web server

if you want to run spring boot without a servlet container, but with one on the classpath (e.g. for tests), use the following, as described in the spring boot documentation:

@Configuration
@EnableAutoConfiguration
public class MyClass{
    public static void main(String[] args) throws JAXBException {
                 SpringApplication app = new SpringApplication(MyClass.class);
         app.setWebEnvironment(false); //<<<<<<<<<
         ConfigurableApplicationContext ctx = app.run(args);
    }
}

also, I just stumbled across this property:

spring.main.web-environment=false

Converting Milliseconds to Minutes and Seconds?

After converting millis to seconds (by dividing by 1000), you can use / 60 to get the minutes value, and % 60 (remainder) to get the "seconds in minute" value.

long millis = .....;  // obtained from StopWatch
long minutes = (millis / 1000)  / 60;
int seconds = (int)((millis / 1000) % 60);

Failed to resolve: com.google.android.gms:play-services in IntelliJ Idea with gradle

I had the issue when I put jcenter() before google() in project level build.gradle. When I changed the order and put google() before jcenter() in build.gradle the problem disappeared

Here is my final build.gradle

// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {

    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.1.3'


        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

What are advantages of Artificial Neural Networks over Support Vector Machines?

One answer I'm missing here: Multi-layer perceptron is able to find relation between features. For example it is necessary in computer vision when a raw image is provided to the learning algorithm and now Sophisticated features are calculated. Essentially the intermediate levels can calculate new unknown features.

Test class with a new() call in it with Mockito

I happened to be in a particular situation where my usecase resembled the one of Mureinik but I ended-up using the solution of Tomasz Nurkiewicz.

Here is how:

class TestedClass extends AARRGGHH {
    public LoginContext login(String user, String password) {
        LoginContext lc = new LoginContext("login", callbackHandler);
        lc.doThis();
        lc.doThat();
        return lc;
    }
}

Now, PowerMockRunner failed to initialize TestedClass because it extends AARRGGHH, which in turn does more contextual initialization... You see where this path was leading me: I would have needed to mock on several layers. Clearly a HUGE smell.

I found a nice hack with minimal refactoring of TestedClass: I created a small method

LoginContext initLoginContext(String login, CallbackHandler callbackHandler) {
    new lc = new LoginContext(login, callbackHandler);
}

The scope of this method is necessarily package.

Then your test stub will look like:

LoginContext lcMock = mock(LoginContext.class)
TestedClass testClass = spy(new TestedClass(withAllNeededArgs))
doReturn(lcMock)
    .when(testClass)
    .initLoginContext("login", callbackHandler)

and the trick is done...

Declaring an enum within a class

If you are creating a code library, then I would use namespace. However, you can still only have one Color enum inside that namespace. If you need an enum that might use a common name, but might have different constants for different classes, use your approach.

Is there a function to copy an array in C/C++?

You can use the memcpy(),

void * memcpy ( void * destination, const void * source, size_t num );

memcpy() copies the values of num bytes from the location pointed by source directly to the memory block pointed by destination.

If the destination and source overlap, then you can use memmove().

void * memmove ( void * destination, const void * source, size_t num );

memmove() copies the values of num bytes from the location pointed by source to the memory block pointed by destination. Copying takes place as if an intermediate buffer were used, allowing the destination and source to overlap.

vba listbox multicolumn add

Simplified example (with counter):

With Me.lstbox
    .ColumnCount = 2
    .ColumnWidths = "60;60"
    .AddItem
    .List(i, 0) = Company_ID
    .List(i, 1) = Company_name 
    i = i + 1

end with

Make sure to start the counter with 0, not 1 to fill up a listbox.

What is the preferred syntax for initializing a dict: curly brace literals {} or the dict() function?

FYI, in case you need to add attributes to your dictionary (things that are attached to the dictionary, but are not one of the keys), then you'll need the second form. In that case, you can initialize your dictionary with keys having arbitrary characters, one at a time, like so:

    class mydict(dict): pass
    a = mydict()        
    a["b=c"] = 'value'
    a.test = False

How to manually install a pypi module without pip/easy_install?

To further explain Sheena's answer, I needed to have setup-tools installed as a dependency of another tool e.g. more-itertools.

Download

Click the Clone or download button and choose your method. I placed these into a dev/py/libs directory in my user home directory. It does not matter where they are saved, because they will not be installed there.

Installing setup-tools

You will need to run the following inside the setup-tools directory.

python bootstrap.py
python setup.py install

General dependencies installation

Now you can navigate to the more-itertools direcotry and install it as normal.

  1. Download the package
  2. Unpackage it if it's an archive
  3. Navigate (cd ...) into the directory containing setup.py
  4. If there are any installation instructions contained in the documentation contained herein, read and follow the instructions OTHERWISE
  5. Type in: python setup.py install

Make Bootstrap Popover Appear/Disappear on Hover instead of Click

If you want to hover the popover itself as well you have to use a manual trigger.

This is what i came up with:

function enableThumbPopover() {
    var counter;

    $('.thumbcontainer').popover({
        trigger: 'manual',
        animation: false,
        html: true,
        title: function () {
            return $(this).parent().find('.thumbPopover > .title').html();
        },
        content: function () {
            return $(this).parent().find('.thumbPopover > .body').html();
        },
        container: 'body',
        placement: 'auto'
    }).on("mouseenter",function () {
        var _this = this; // thumbcontainer

        console.log('thumbcontainer mouseenter')
        // clear the counter
        clearTimeout(counter);
        // Close all other Popovers
        $('.thumbcontainer').not(_this).popover('hide');

        // start new timeout to show popover
        counter = setTimeout(function(){
            if($(_this).is(':hover'))
            {
                $(_this).popover("show");
            }
            $(".popover").on("mouseleave", function () {
                $('.thumbcontainer').popover('hide');
            });
        }, 400);

    }).on("mouseleave", function () {
        var _this = this;

        setTimeout(function () {
            if (!$(".popover:hover").length) {
                if(!$(_this).is(':hover')) // change $(this) to $(_this) 
                {
                    $(_this).popover('hide');
                }
            }
        }, 200);
    });
}

How to check if a variable is both null and /or undefined in JavaScript

You can wrap it in your own function:

function isNullAndUndef(variable) {

    return (variable !== null && variable !== undefined);
}

C++ error : terminate called after throwing an instance of 'std::bad_alloc'

The problem in your code is that you can't store the memory address of a local variable (local to a function, for example) in a globlar variable:

RectInvoice rect(vect,im,x, y, w ,h);
this->rectInvoiceVector.push_back(&rect);

There, &rect is a temporary address (stored in the function's activation registry) and will be destroyed when that function end.

The code should create a dynamic variable:

RectInvoice *rect =  new RectInvoice(vect,im,x, y, w ,h);
this->rectInvoiceVector.push_back(rect);

There you are using a heap address that will not be destroyed in the end of the function's execution. Tell me if it worked for you.

Cheers

Git error on git pull (unable to update local ref)

I fixed this by deleting the locked branch file. It may seem crude, and I have no idea why it worked, but it fixed my issue (i.e. the same error you are getting)

Deleted: .git/refs/remotes/origin/[locked branch name]

Then I simply ran

git fetch

and the git file restored itself, fully repaired

Change multiple files

I'm using find for similar task. It is quite simple: you have to pass it as an argument for sed like this:

sed -i 's/EXPRESSION/REPLACEMENT/g' `find -name "FILE.REGEX"`

This way you don't have to write complex loops, and it is simple to see, which files you are going to change, just run find before you run sed.

jQuery: using a variable as a selector

You're thinking too complicated. It's actually just $('#'+openaddress).

What's a .sh file?

Typically a .sh file is a shell script which you can execute in a terminal. Specifically, the script you mentioned is a bash script, which you can see if you open the file and look in the first line of the file, which is called the shebang or magic line.

How do I load external fonts into an HTML document?

Paul Irish has a way to do this that covers most of the common problems. See his bullet-proof @font-face article:

The final variant, which stops unnecessary data from being downloaded by IE, and works in IE8, Firefox, Opera, Safari, and Chrome looks like this:

@font-face {
  font-family: 'Graublau Web';
  src: url('GraublauWeb.eot');
  src: local('Graublau Web Regular'), local('Graublau Web'),
    url("GraublauWeb.woff") format("woff"),
    url("GraublauWeb.otf") format("opentype"),
    url("GraublauWeb.svg#grablau") format("svg");
}

He also links to a generator that will translate the fonts into all the formats you need.

As others have already specified, this will only work in the latest generation of browsers. Your best bet is to use this in conjunction with something like Cufon, and only load Cufon if the browser doesn't support @font-face.

how do I use an enum value on a switch statement in C++

You're on the right track. You may read the user input into an integer and switch on that:

enum Choice
{
  EASY = 1, 
  MEDIUM = 2, 
  HARD = 3
};

int i = -1;

// ...<present the user with a menu>...

cin >> i;

switch(i)
{
  case EASY:
    cout << "Easy\n";
    break;
  case MEDIUM:
    cout << "Medium\n";
    break;
  case HARD:
    cout << "Hard\n";
    break;
  default:
    cout << "Invalid Selection\n";
    break;
}

Adding Google Translate to a web site

<div id="google_translate_element"></div><script type="text/javascript">
function googleTranslateElementInit() {
  new google.translate.TranslateElement({pageLanguage: 'en', includedLanguages: 'th,zh-CN,zh-TW', layout: google.translate.TranslateElement.InlineLayout.SIMPLE}, 'google_translate_element');
}
</script><script type="text/javascript" src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>

Using PHP with Socket.io

Erm, why would you want to? Leave PHP on the backend and NodeJS/Sockets to do its non-blocking thing.

Here is something to get you started: http://groups.google.com/group/socket_io/browse_thread/thread/74a76896d2b72ccc

Personally I have express running with an endpoint that is listening expressly for interaction from PHP.

For example, if I have sent a user an email, I want socket.io to display a real-time notification to the user.

Want interaction from socket.io to php, well you can just do something like this:

var http = require('http'),
            host = WWW_HOST,
            clen = 'userid=' + userid,
            site = http.createClient(80, host),
            request = site.request("POST", "/modules/nodeim/includes/signonuser.inc.php",  
                {'host':host,'Content-Length':clen.length,'Content-Type':'application/x-www-form-urlencoded'});                     

request.write('userid=' + userid);      
request.end();  

Seriously, PHP is great for doing server side stuff and let it be with the connections it has no place in this domain now. Why do anything long-polling when you have websockets or flashsockets.

Oracle: Call stored procedure inside the package

To those that are incline to use GUI:

Click Right mouse button on procecdure name then select Test

enter image description here

Then in new window you will see script generated just add the parameters and click on Start Debugger or F9

enter image description here

Hope this saves you some time.

How do you run a single test/spec file in RSpec?

Or you can skip rake and use the 'rspec' command:

rspec path/to/spec/file.rb

In your case I think as long as your ./spec/db_spec.rb file includes the appropriate helpers, it should work fine.

If you're using an older version of rspec it is:

spec path/to/spec/file.rb

How to create a release signed apk file using Gradle?

This is a reply to user672009 and addition to sdqali's post (his code will crash on building debug version by IDE's "Run" button):

You can use the following code:

final Console console = System.console();
if (console != null) {

    // Building from console 
    signingConfigs {
        release {
            storeFile file(console.readLine("Enter keystore path: "))
            storePassword console.readLine("Enter keystore password: ")
            keyAlias console.readLine("Enter alias key: ")
            keyPassword console.readLine("Enter key password: ")
        }
    }

} else {

    // Building from IDE's "Run" button
    signingConfigs {
        release {

        }
    }

}

How do you comment out code in PowerShell?

You can make:

 (Some basic code) # Use "#" after a line and use:

 <#
    for more lines
    ...
    ...
    ...
    ..
    .
 #>

Subtract 1 day with PHP

Object oriented version

$dateObject = new DateTime( $date_raw );
print('Next Date ' . $dateObject->sub( new DateInterval('P1D') )->format('Y-m-d');

@AspectJ pointcut for all methods of a class with specific annotation

Using annotations, as described in the question.

Annotation: @Monitor

Annotation on class, app/PagesController.java:

package app;
@Controller
@Monitor
public class PagesController {
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public @ResponseBody String home() {
        return "w00t!";
    }
}

Annotation on method, app/PagesController.java:

package app;
@Controller
public class PagesController {
    @Monitor
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public @ResponseBody String home() {
        return "w00t!";
    }
}

Custom annotation, app/Monitor.java:

package app;
@Component
@Target(value = {ElementType.METHOD, ElementType.TYPE})
@Retention(value = RetentionPolicy.RUNTIME)
public @interface Monitor {
}

Aspect for annotation, app/MonitorAspect.java:

package app;
@Component
@Aspect
public class MonitorAspect {
    @Before(value = "@within(app.Monitor) || @annotation(app.Monitor)")
    public void before(JoinPoint joinPoint) throws Throwable {
        LogFactory.getLog(MonitorAspect.class).info("monitor.before, class: " + joinPoint.getSignature().getDeclaringType().getSimpleName() + ", method: " + joinPoint.getSignature().getName());
    }

    @After(value = "@within(app.Monitor) || @annotation(app.Monitor)")
    public void after(JoinPoint joinPoint) throws Throwable {
        LogFactory.getLog(MonitorAspect.class).info("monitor.after, class: " + joinPoint.getSignature().getDeclaringType().getSimpleName() + ", method: " + joinPoint.getSignature().getName());
    }
}

Enable AspectJ, servlet-context.xml:

<aop:aspectj-autoproxy />

Include AspectJ libraries, pom.xml:

<artifactId>spring-aop</artifactId>
<artifactId>aspectjrt</artifactId>
<artifactId>aspectjweaver</artifactId>
<artifactId>cglib</artifactId>