Programs & Examples On #Open flash chart

Open Flash Chart - JSON based very flexible flash chart renderer.

How to call a Parent Class's method from Child Class in Python?

class department:
    campus_name="attock"
    def printer(self):
        print(self.campus_name)

class CS_dept(department):
    def overr_CS(self):
        department.printer(self)
        print("i am child class1")

c=CS_dept()
c.overr_CS()

$(document).on("click"... not working?

You are using the correct syntax for binding to the document to listen for a click event for an element with id="test-element".

It's probably not working due to one of:

  • Not using recent version of jQuery
  • Not wrapping your code inside of DOM ready
  • or you are doing something which causes the event not to bubble up to the listener on the document.

To capture events on elements which are created AFTER declaring your event listeners - you should bind to a parent element, or element higher in the hierarchy.

For example:

$(document).ready(function() {
    // This WILL work because we are listening on the 'document', 
    // for a click on an element with an ID of #test-element
    $(document).on("click","#test-element",function() {
        alert("click bound to document listening for #test-element");
    });

    // This will NOT work because there is no '#test-element' ... yet
    $("#test-element").on("click",function() {
        alert("click bound directly to #test-element");
    });

    // Create the dynamic element '#test-element'
    $('body').append('<div id="test-element">Click mee</div>');
});

In this example, only the "bound to document" alert will fire.

JSFiddle with jQuery 1.9.1

How to save a base64 image to user's disk using JavaScript?

In JavaScript you cannot have the direct access to the filesystem. However, you can make browser to pop up a dialog window allowing the user to pick the save location. In order to do this, use the replace method with your Base64String and replace "image/png" with "image/octet-stream":

"data:image/png;base64,iVBORw0KG...".replace("image/png", "image/octet-stream");

Also, W3C-compliant browsers provide 2 methods to work with base64-encoded and binary data:

Probably, you will find them useful in a way...


Here is a refactored version of what I understand you need:

_x000D_
_x000D_
window.addEventListener('DOMContentLoaded', () => {_x000D_
  const img = document.getElementById('embedImage');_x000D_
  img.src = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA' +_x000D_
    'AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO' +_x000D_
    '9TXL0Y4OHwAAAABJRU5ErkJggg==';_x000D_
_x000D_
  img.addEventListener('load', () => button.removeAttribute('disabled'));_x000D_
  _x000D_
  const button = document.getElementById('saveImage');_x000D_
  button.addEventListener('click', () => {_x000D_
    window.location.href = img.src.replace('image/png', 'image/octet-stream');_x000D_
  });_x000D_
});
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
<body>_x000D_
  <img id="embedImage" alt="Red dot" />_x000D_
  <button id="saveImage" disabled="disabled">save image</button>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

Send email using the GMail SMTP server from a PHP page

To install PEAR's Mail.php in Ubuntu, run following set of commands:

    sudo apt-get install php-pear
    sudo pear install mail
    sudo pear install Net_SMTP
    sudo pear install Auth_SASL
    sudo pear install mail_mime

Using a bitmask in C#

The traditional way to do this is to use the Flags attribute on an enum:

[Flags]
public enum Names
{
    None = 0,
    Susan = 1,
    Bob = 2,
    Karen = 4
}

Then you'd check for a particular name as follows:

Names names = Names.Susan | Names.Bob;

// evaluates to true
bool susanIsIncluded = (names & Names.Susan) != Names.None;

// evaluates to false
bool karenIsIncluded = (names & Names.Karen) != Names.None;

Logical bitwise combinations can be tough to remember, so I make life easier on myself with a FlagsHelper class*:

// The casts to object in the below code are an unfortunate necessity due to
// C#'s restriction against a where T : Enum constraint. (There are ways around
// this, but they're outside the scope of this simple illustration.)
public static class FlagsHelper
{
    public static bool IsSet<T>(T flags, T flag) where T : struct
    {
        int flagsValue = (int)(object)flags;
        int flagValue = (int)(object)flag;

        return (flagsValue & flagValue) != 0;
    }

    public static void Set<T>(ref T flags, T flag) where T : struct
    {
        int flagsValue = (int)(object)flags;
        int flagValue = (int)(object)flag;

        flags = (T)(object)(flagsValue | flagValue);
    }

    public static void Unset<T>(ref T flags, T flag) where T : struct
    {
        int flagsValue = (int)(object)flags;
        int flagValue = (int)(object)flag;

        flags = (T)(object)(flagsValue & (~flagValue));
    }
}

This would allow me to rewrite the above code as:

Names names = Names.Susan | Names.Bob;

bool susanIsIncluded = FlagsHelper.IsSet(names, Names.Susan);

bool karenIsIncluded = FlagsHelper.IsSet(names, Names.Karen);

Note I could also add Karen to the set by doing this:

FlagsHelper.Set(ref names, Names.Karen);

And I could remove Susan in a similar way:

FlagsHelper.Unset(ref names, Names.Susan);

*As Porges pointed out, an equivalent of the IsSet method above already exists in .NET 4.0: Enum.HasFlag. The Set and Unset methods don't appear to have equivalents, though; so I'd still say this class has some merit.


Note: Using enums is just the conventional way of tackling this problem. You can totally translate all of the above code to use ints instead and it'll work just as well.

Create two-dimensional arrays and access sub-arrays in Ruby

a = Array.new(Array.new(4))

0.upto(a.length-1) do |i|
  0.upto(a.length-1) do |j|
    a[i[j]] = 1
  end
end

0.upto(a.length-1) do |i|
  0.upto(a.length-1) do |j|
    print a[i[j]] = 1 #It's not a[i][j], but a[i[j]]
  end
  puts "\n"
end

Linker Command failed with exit code 1 (use -v to see invocation), Xcode 8, Swift 3

Here is my problem and solution:

I removed two files from the source code using source tree(Version controller). After applying the diff, that contains the two classes I removed, Xcode didn't add it automatically. So I got linker error.

I manually added the files, by right click on group name and select "Add files to ". Now my error got resolved.

If anyone faced the linker error regarding class file, then try to add it manually.

Changing text color of menu item in navigation drawer

You can use drawables in

app:itemTextColor app:itemIconTint

then you can control the checked state and normal state using a drawable

<android.support.design.widget.NavigationView
            android:id="@+id/nav_view"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_gravity="start"
            app:itemHorizontalPadding="@dimen/margin_30"
            app:itemIconTint="@drawable/drawer_item_color"
            app:itemTextColor="@drawable/drawer_item_color"
            android:theme="@style/NavigationView"
            app:headerLayout="@layout/nav_header"
            app:menu="@menu/drawer_menu">

drawer_item_color.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:color="@color/selectedColor" android:state_checked="true" />
    <item android:color="@color/normalColor" />
</selector>

Remove 'standalone="yes"' from generated XML

If you are using only the default javax.xml package, you could set the JAXB_FRAGMENT option of the marshaller to 'true' (this omits the default xml processing instruction) and use the writeProcessingInstruction method of the XMLStreamWriter to insert your own:

xmlStreamWriter.writeProcessingInstruction("xml", "version=\"1.0\" encoding=\"UTF-8\"");
jaxbMarshaller.setProperty( Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
jaxbMarshaller.marshal(object, xmlStreamWriter);
xmlStreamWriter.writeEndDocument();

Inverse of matrix in R

Note that if you care about speed and do not need to worry about singularities, solve() should be preferred to ginv() because it is much faster, as you can check:

require(MASS)
mat <- matrix(rnorm(1e6),nrow=1e3,ncol=1e3)

t0 <- proc.time()
inv0 <- ginv(mat)
proc.time() - t0 

t1 <- proc.time()
inv1 <- solve(mat)
proc.time() - t1 

How to use passive FTP mode in Windows command prompt?

According to this Egnyte article, Passive FTP is supported from Windows 8.1 onwards.

The Registry key:

"HKEY_CURRENT_USER\Software\Microsoft\FTP\Use PASV"

should be set with the value: yes

If you don't like poking around in the Registry, do the following:

  1. Press WinKey+R to open the Run dialog.
  2. Type inetcpl.cpl and press Enter. The Internet Options dialog will open.
  3. Click on the Advanced tab.
  4. Make your way down to the Browsing secction of the tree view, and ensure the Use Passive FTP item is set to on.
  5. Click on the OK button.

Every time you use ftp.exe, remember to pass the

quote pasv

command immediately after logging in to a remote host.

PS: Grant ftp.exe access to private networks if your Firewall complains.

Concatenate a NumPy array to another NumPy array

I found this link while looking for something slightly different, how to start appending array objects to an empty numpy array, but tried all the solutions on this page to no avail.

Then I found this question and answer: How to add a new row to an empty numpy array

The gist here:

The way to "start" the array that you want is:

arr = np.empty((0,3), int)

Then you can use concatenate to add rows like so:

arr = np.concatenate( ( arr, [[x, y, z]] ) , axis=0)

See also https://docs.scipy.org/doc/numpy/reference/generated/numpy.concatenate.html

A monad is just a monoid in the category of endofunctors, what's the problem?

The answers here do an excellent job in defining both monoids and monads, however, they still don't seem to answer the question:

And on a less important note, is this true and if so could you give an explanation (hopefully one that can be understood by someone who doesn't have much Haskell experience)?

The crux of the matter that is missing here, is the different notion of "monoid", the so-called categorification more precisely -- the one of monoid in a monoidal category. Sadly Mac Lane's book itself makes it very confusing:

All told, a monad in X is just a monoid in the category of endofunctors of X, with product × replaced by composition of endofunctors and unit set by the identity endofunctor.

Main confusion

Why is this confusing? Because it does not define what is "monoid in the category of endofunctors" of X. Instead, this sentence suggests taking a monoid inside the set of all endofunctors together with the functor composition as binary operation and the identity functor as a monoidal unit. Which works perfectly fine and turns into a monoid any subset of endofunctors that contains the identity functor and is closed under functor composition.

Yet this is not the correct interpretation, which the book fails to make clear at that stage. A Monad f is a fixed endofunctor, not a subset of endofunctors closed under composition. A common construction is to use f to generate a monoid by taking the set of all k-fold compositions f^k = f(f(...)) of f with itself, including k=0 that corresponds to the identity f^0 = id. And now the set S of all these powers for all k>=0 is indeed a monoid "with product × replaced by composition of endofunctors and unit set by the identity endofunctor".

And yet:

  • This monoid S can be defined for any functor f or even literally for any self-map of X. It is the monoid generated by f.
  • The monoidal structure of S given by the functor composition and the identity functor has nothing do with f being or not being a monad.

And to make things more confusing, the definition of "monoid in monoidal category" comes later in the book as you can see from the table of contents. And yet understanding this notion is absolutely critical to understanding the connection with monads.

(Strict) monoidal categories

Going to Chapter VII on Monoids (which comes later than Chapter VI on Monads), we find the definition of the so-called strict monoidal category as triple (B, *, e), where B is a category, *: B x B-> B a bifunctor (functor with respect to each component with other component fixed) and e is a unit object in B, satisfying the associativity and unit laws:

(a * b) * c = a * (b * c)
a * e = e * a = a

for any objects a,b,c of B, and the same identities for any morphisms a,b,c with e replaced by id_e, the identity morphism of e. It is now instructive to observe that in our case of interest, where B is the category of endofunctors of X with natural transformations as morphisms, * the functor composition and e the identity functor, all these laws are satisfied, as can be directly verified.

What comes after in the book is the definition of the "relaxed" monoidal category, where the laws only hold modulo some fixed natural transformations satisfying so-called coherence relations, which is however not important for our cases of the endofunctor categories.

Monoids in monoidal categories

Finally, in section 3 "Monoids" of Chapter VII, the actual definition is given:

A monoid c in a monoidal category (B, *, e) is an object of B with two arrows (morphisms)

mu: c * c -> c
nu: e -> c

making 3 diagrams commutative. Recall that in our case, these are morphisms in the category of endofunctors, which are natural transformations corresponding to precisely join and return for a monad. The connection becomes even clearer when we make the composition * more explicit, replacing c * c by c^2, where c is our monad.

Finally, notice that the 3 commutative diagrams (in the definition of a monoid in monoidal category) are written for general (non-strict) monoidal categories, while in our case all natural transformations arising as part of the monoidal category are actually identities. That will make the diagrams exactly the same as the ones in the definition of a monad, making the correspondence complete.

Conclusion

In summary, any monad is by definition an endofunctor, hence an object in the category of endofunctors, where the monadic join and return operators satisfy the definition of a monoid in that particular (strict) monoidal category. Vice versa, any monoid in the monoidal category of endofunctors is by definition a triple (c, mu, nu) consisting of an object and two arrows, e.g. natural transformations in our case, satisfying the same laws as a monad.

Finally, note the key difference between the (classical) monoids and the more general monoids in monoidal categories. The two arrows mu and nu above are not anymore a binary operation and a unit in a set. Instead, you have one fixed endofunctor c. The functor composition * and the identity functor alone do not provide the complete structure needed for the monad, despite that confusing remark in the book.

Another approach would be to compare with the standard monoid C of all self-maps of a set A, where the binary operation is the composition, that can be seen to map the standard cartesian product C x C into C. Passing to the categorified monoid, we are replacing the cartesian product x with the functor composition *, and the binary operation gets replaced with the natural transformation mu from c * c to c, that is a collection of the join operators

join: c(c(T))->c(T)

for every object T (type in programming). And the identity elements in classical monoids, which can be identified with images of maps from a fixed one-point-set, get replaced with the collection of the return operators

return: T->c(T) 

But now there are no more cartesian products, so no pairs of elements and thus no binary operations.

How to toggle boolean state of react component?

Use checked to get the value. During onChange, checked will be true and it will be a type of boolean.

Hope this helps!

_x000D_
_x000D_
class A extends React.Component {_x000D_
  constructor() {_x000D_
    super()_x000D_
    this.handleCheckBox = this.handleCheckBox.bind(this)_x000D_
    this.state = {_x000D_
      checked: false_x000D_
    }_x000D_
  }_x000D_
  _x000D_
  handleCheckBox(e) {_x000D_
    this.setState({_x000D_
      checked: e.target.checked_x000D_
    })_x000D_
  }_x000D_
  _x000D_
  render(){_x000D_
    return <input type="checkbox" onChange={this.handleCheckBox} checked={this.state.checked} />_x000D_
  }_x000D_
}_x000D_
_x000D_
ReactDOM.render(<A/>, document.getElementById('app'))
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
<div id="app"></div>
_x000D_
_x000D_
_x000D_

new Image(), how to know if image 100% loaded or not?

Use the load event:

img = new Image();

img.onload = function(){
  // image  has been loaded
};

img.src = image_url;

Also have a look at:

Why is my Spring @Autowired field null?

Your problem is new (object creation in java style)

MileageFeeCalculator calc = new MileageFeeCalculator();

With annotation @Service, @Component, @Configuration beans are created in the
application context of Spring when server is started. But when we create objects using new operator the object is not registered in application context which is already created. For Example Employee.java class i have used.

Check this out:

public class ConfiguredTenantScopedBeanProcessor implements BeanFactoryPostProcessor {

@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
    String name = "tenant";
    System.out.println("Bean factory post processor is initialized"); 
    beanFactory.registerScope("employee", new Employee());

    Assert.state(beanFactory instanceof BeanDefinitionRegistry,
            "BeanFactory was not a BeanDefinitionRegistry, so CustomScope cannot be used.");
    BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;

    for (String beanName : beanFactory.getBeanDefinitionNames()) {
        BeanDefinition definition = beanFactory.getBeanDefinition(beanName);
        if (name.equals(definition.getScope())) {
            BeanDefinitionHolder proxyHolder = ScopedProxyUtils.createScopedProxy(new BeanDefinitionHolder(definition, beanName), registry, true);
            registry.registerBeanDefinition(beanName, proxyHolder.getBeanDefinition());
        }
    }
}

}

How to prevent buttons from submitting forms

return false;

You can return false at the end of the function or after the function call.

Just as long as it's the last thing that happens, the form will not submit.

Getting only Month and Year from SQL DATE

Query :- Select datename(m,GETDATE())+'-'+cast(datepart(yyyy,GETDATE()) as varchar) as FieldName

Output :- January-2019

general datefield we can use

datename(m,<DateField>)+' '+cast(datepart(yyyy,<DateField>) as varchar) as FieldName

Serializing and submitting a form with jQuery and PHP

The problem can be PHP configuration:

Please check the setting max_input_vars in the php.ini file.

Try to increase the value of this setting to 5000 as example.

max_input_vars = 5000

Then restart your web-server and try.

Can an ASP.NET MVC controller return an Image?

Look at ContentResult. This returns a string, but can be used to make your own BinaryResult-like class.

Get value from hashmap based on key to JSTL

could you please try below code

<c:forEach var="hash" items="${map['key']}">
        <option><c:out value="${hash}"/></option>
  </c:forEach>

Removing input background colour for Chrome autocomplete?

This worked for me:

padding: 5px;
background-clip: content-box;

How to convert DATE to UNIX TIMESTAMP in shell script on MacOS

I wrote a set of scripts that provides a uniform interface for both BSD and GNU version of date.

Follow command will output the Epoch seconds for the date 2010-10-02, and it works with both BSD and GNU version of date.

$ xsh /date/convert "2010-10-02" "+%s"
1286020263

It's an equivalent of the command with GNU version of date:

date -d "2010-10-02" "+%s"

and also the command with BSD version of date:

date -j -f "%F" 2010-10-02 "+%s"

The scripts can be found at:

It's a part of a library called xsh-lib/core. To use them you need both repos xsh and xsh-lib/core, I list them below:

How to JUnit test that two List<E> contain the same elements in the same order?

The equals() method on your List implementation should do elementwise comparison, so

assertEquals(argumentComponents, returnedComponents);

is a lot easier.

Java: how to represent graphs?

Time ago I had the same problem and did my own implementation. What I suggest you is to implement another class: Edge. Then, a Vertex will have a List of Edge.

public class Edge {
    private Node a, b;
    private directionEnum direction;     // AB, BA or both
    private int weight;
    ...
}

It worked for me. But maybe is so simple. There is this library that maybe can help you if you look into its code: http://jgrapht.sourceforge.net/

"NOT IN" clause in LINQ to Entities

I created it in a more similar way to the SQL, I think it is easier to understand

var list = (from a in listA.AsEnumerable()
            join b in listB.AsEnumerable() on a.id equals b.id into ab
            from c in ab.DefaultIfEmpty()
            where c != null
            select new { id = c.id, name = c.nome }).ToList();

"And" and "Or" troubles within an IF statement

The problem is probably somewhere else. Try this code for example:

Sub test()

  origNum = "006260006"
  creditOrDebit = "D"

  If (origNum = "006260006" Or origNum = "30062600006") And creditOrDebit = "D" Then
    MsgBox "OK"
  End If

End Sub

And you will see that your Or works as expected. Are you sure that your ElseIf statement is executed (it will not be executed if any of the if/elseif before is true)?

add/remove active class for ul list with jquery?

this will point to the <ul> selected by .nav-list. You can use delegation instead!

$('.nav-list').on('click', 'li', function() {
    $('.nav-list li.active').removeClass('active');
    $(this).addClass('active');
});

T-SQL: Selecting rows to delete via joins

you can run this query:-

Delete from TableA 
from 
TableA a, TableB b 
where a.Bid=b.Bid
AND [my filter condition]

How to send an email with Gmail as provider using Python?

There is a gmail API now, which lets you send email, read email and create drafts via REST. Unlike the SMTP calls, it is non-blocking which can be a good thing for thread-based webservers sending email in the request thread (like python webservers). The API is also quite powerful.

  • Of course, email should be handed off to a non-webserver queue, but it's nice to have options.

It's easiest to setup if you have Google Apps administrator rights on the domain, because then you can give blanket permission to your client. Otherwise you have to fiddle with OAuth authentication and permission.

Here is a gist demonstrating it:

https://gist.github.com/timrichardson/1154e29174926e462b7a

phpinfo() is not working on my CentOS server

I had the same problem.

The solution in my case was to set default_mimetype = "text/html" inside the php.ini file.

Is it necessary to use # for creating temp tables in SQL server?

Yes. You need to prefix the table name with "#" (hash) to create temporary tables.

If you do NOT need the table later, go ahead & create it. Temporary Tables are very much like normal tables. However, it gets created in tempdb. Also, it is only accessible via the current session i.e. For EG: if another user tries to access the temp table created by you, he'll not be able to do so.

"##" (double-hash creates "Global" temp table that can be accessed by other sessions as well.

Refer the below link for the Basics of Temporary Tables: http://www.codeproject.com/Articles/42553/Quick-Overview-Temporary-Tables-in-SQL-Server-2005

If the content of your table is less than 5000 rows & does NOT contain data types such as nvarchar(MAX), varbinary(MAX), consider using Table Variables.

They are the fastest as they are just like any other variables which are stored in the RAM. They are stored in tempdb as well, not in RAM.

DECLARE @ItemBack1 TABLE
(
 column1 int,
 column2 int,
 someInt int,
 someVarChar nvarchar(50)
);

INSERT INTO @ItemBack1
SELECT column1, 
       column2, 
       someInt, 
       someVarChar 
  FROM table2
 WHERE table2.ID = 7;

More Info on Table Variables: http://odetocode.com/articles/365.aspx

Creating/writing into a new file in Qt

It can happen that the cause is not that you don't find the right directory. For example, you can read from the file (even without absolute path) but it seems you cannot write into it.

In that case, it might be that you program exits before the writing can be finished.

If your program uses an event loop (like with a GUI application, e.g. QMainWindow) it's not a problem. However, if your program exits immediately after writing to the file, you should flush the text stream, closing the file is not always enough (and it's unnecessary, as it is closed in the destructor).

stream << "something" << endl;
stream.flush();

This guarantees that the changes are committed to the file before the program continues from this instruction.

The problem seems to be that the QFile is destructed before the QTextStream. So, even if the stream is flushed in the QTextStream destructor, it's too late, as the file is already closed.

How to convert a selection to lowercase or uppercase in Sublime Text

For others needing a key binding:

{ "keys": ["ctrl+="], "command": "upper_case" },
{ "keys": ["ctrl+-"], "command": "lower_case" }

Load More Posts Ajax Button in WordPress

UPDATE 24.04.2016.

I've created tutorial on my page https://madebydenis.com/ajax-load-posts-on-wordpress/ about implementing this on Twenty Sixteen theme, so feel free to check it out :)

EDIT

I've tested this on Twenty Fifteen and it's working, so it should be working for you.

In index.php (assuming that you want to show the posts on the main page, but this should work even if you put it in a page template) I put:

    <div id="ajax-posts" class="row">
        <?php
            $postsPerPage = 3;
            $args = array(
                    'post_type' => 'post',
                    'posts_per_page' => $postsPerPage,
                    'cat' => 8
            );

            $loop = new WP_Query($args);

            while ($loop->have_posts()) : $loop->the_post();
        ?>

         <div class="small-12 large-4 columns">
                <h1><?php the_title(); ?></h1>
                <p><?php the_content(); ?></p>
         </div>

         <?php
                endwhile;
        wp_reset_postdata();
         ?>
    </div>
    <div id="more_posts">Load More</div>

This will output 3 posts from category 8 (I had posts in that category, so I used it, you can use whatever you want to). You can even query the category you're in with

$cat_id = get_query_var('cat');

This will give you the category id to use in your query. You could put this in your loader (load more div), and pull with jQuery like

<div id="more_posts" data-category="<?php echo $cat_id; ?>">>Load More</div>

And pull the category with

var cat = $('#more_posts').data('category');

But for now, you can leave this out.

Next in functions.php I added

wp_localize_script( 'twentyfifteen-script', 'ajax_posts', array(
    'ajaxurl' => admin_url( 'admin-ajax.php' ),
    'noposts' => __('No older posts found', 'twentyfifteen'),
));

Right after the existing wp_localize_script. This will load WordPress own admin-ajax.php so that we can use it when we call it in our ajax call.

At the end of the functions.php file I added the function that will load your posts:

function more_post_ajax(){

    $ppp = (isset($_POST["ppp"])) ? $_POST["ppp"] : 3;
    $page = (isset($_POST['pageNumber'])) ? $_POST['pageNumber'] : 0;

    header("Content-Type: text/html");

    $args = array(
        'suppress_filters' => true,
        'post_type' => 'post',
        'posts_per_page' => $ppp,
        'cat' => 8,
        'paged'    => $page,
    );

    $loop = new WP_Query($args);

    $out = '';

    if ($loop -> have_posts()) :  while ($loop -> have_posts()) : $loop -> the_post();
        $out .= '<div class="small-12 large-4 columns">
                <h1>'.get_the_title().'</h1>
                <p>'.get_the_content().'</p>
         </div>';

    endwhile;
    endif;
    wp_reset_postdata();
    die($out);
}

add_action('wp_ajax_nopriv_more_post_ajax', 'more_post_ajax');
add_action('wp_ajax_more_post_ajax', 'more_post_ajax');

Here I've added paged key in the array, so that the loop can keep track on what page you are when you load your posts.

If you've added your category in the loader, you'd add:

$cat = (isset($_POST['cat'])) ? $_POST['cat'] : '';

And instead of 8, you'd put $cat. This will be in the $_POST array, and you'll be able to use it in ajax.

Last part is the ajax itself. In functions.js I put inside the $(document).ready(); enviroment

var ppp = 3; // Post per page
var cat = 8;
var pageNumber = 1;


function load_posts(){
    pageNumber++;
    var str = '&cat=' + cat + '&pageNumber=' + pageNumber + '&ppp=' + ppp + '&action=more_post_ajax';
    $.ajax({
        type: "POST",
        dataType: "html",
        url: ajax_posts.ajaxurl,
        data: str,
        success: function(data){
            var $data = $(data);
            if($data.length){
                $("#ajax-posts").append($data);
                $("#more_posts").attr("disabled",false);
            } else{
                $("#more_posts").attr("disabled",true);
            }
        },
        error : function(jqXHR, textStatus, errorThrown) {
            $loader.html(jqXHR + " :: " + textStatus + " :: " + errorThrown);
        }

    });
    return false;
}

$("#more_posts").on("click",function(){ // When btn is pressed.
    $("#more_posts").attr("disabled",true); // Disable the button, temp.
    load_posts();
});

Saved it, tested it, and it works :)

Images as proof (don't mind the shoddy styling, it was done quickly). Also post content is gibberish xD

enter image description here

enter image description here

enter image description here

UPDATE

For 'infinite load' instead on click event on the button (just make it invisible, with visibility: hidden;) you can try with

$(window).on('scroll', function () {
    if ($(window).scrollTop() + $(window).height()  >= $(document).height() - 100) {
        load_posts();
    }
});

This should run the load_posts() function when you're 100px from the bottom of the page. In the case of the tutorial on my site you can add a check to see if the posts are loading (to prevent firing of the ajax twice), and you can fire it when the scroll reaches the top of the footer

$(window).on('scroll', function(){
    if($('body').scrollTop()+$(window).height() > $('footer').offset().top){
        if(!($loader.hasClass('post_loading_loader') || $loader.hasClass('post_no_more_posts'))){
                load_posts();
        }
    }
});

Now the only drawback in these cases is that you could never scroll to the value of $(document).height() - 100 or $('footer').offset().top for some reason. If that should happen, just increase the number where the scroll goes to.

You can easily check it by putting console.logs in your code and see in the inspector what they throw out

$(window).on('scroll', function () {
    console.log($(window).scrollTop() + $(window).height());
    console.log($(document).height() - 100);
    if ($(window).scrollTop() + $(window).height()  >= $(document).height() - 100) {
        load_posts();
    }
});

And just adjust accordingly ;)

Hope this helps :) If you have any questions just ask.

How to linebreak an svg text within javascript?

use HTML instead of javascript

_x000D_
_x000D_
<html>_x000D_
  <head><style> * { margin: 0; padding: 0; } </style></head>_x000D_
  <body>_x000D_
    <h1>svg foreignObject to embed html</h1>_x000D_
_x000D_
    <svg_x000D_
      xmlns="http://www.w3.org/2000/svg"_x000D_
      viewBox="0 0 300 300"_x000D_
      x="0" y="0" height="300" width="300"_x000D_
    >_x000D_
_x000D_
      <circle_x000D_
        r="142" cx="150" cy="150"_x000D_
        fill="none" stroke="#000000" stroke-width="2"_x000D_
      />_x000D_
_x000D_
      <foreignObject_x000D_
        x="50" y="50" width="200" height="200"_x000D_
      >_x000D_
        <div_x000D_
          xmlns="http://www.w3.org/1999/xhtml"_x000D_
          style="_x000D_
            width: 196px; height: 196px;_x000D_
            border: solid 2px #000000;_x000D_
            font-size: 32px;_x000D_
            overflow: auto; /* scroll */_x000D_
          "_x000D_
        >_x000D_
          <p>this is html in svg 1</p>_x000D_
          <p>this is html in svg 2</p>_x000D_
          <p>this is html in svg 3</p>_x000D_
          <p>this is html in svg 4</p>_x000D_
        </div>_x000D_
      </foreignObject>_x000D_
_x000D_
    </svg>_x000D_
_x000D_
</body></html>
_x000D_
_x000D_
_x000D_

How does PHP 'foreach' actually work?

In example 3 you don't modify the array. In all other examples you modify either the contents or the internal array pointer. This is important when it comes to PHP arrays because of the semantics of the assignment operator.

The assignment operator for the arrays in PHP works more like a lazy clone. Assigning one variable to another that contains an array will clone the array, unlike most languages. However, the actual cloning will not be done unless it is needed. This means that the clone will take place only when either of the variables is modified (copy-on-write).

Here is an example:

$a = array(1,2,3);
$b = $a;  // This is lazy cloning of $a. For the time
          // being $a and $b point to the same internal
          // data structure.

$a[] = 3; // Here $a changes, which triggers the actual
          // cloning. From now on, $a and $b are two
          // different data structures. The same would
          // happen if there were a change in $b.

Coming back to your test cases, you can easily imagine that foreach creates some kind of iterator with a reference to the array. This reference works exactly like the variable $b in my example. However, the iterator along with the reference live only during the loop and then, they are both discarded. Now you can see that, in all cases but 3, the array is modified during the loop, while this extra reference is alive. This triggers a clone, and that explains what's going on here!

Here is an excellent article for another side effect of this copy-on-write behaviour: The PHP Ternary Operator: Fast or not?

How to remove single character from a String

I just implemented this utility class that removes a char or a group of chars from a String. I think it's fast because doesn't use Regexp. I hope that it helps someone!

package your.package.name;

/**
 * Utility class that removes chars from a String.
 * 
 */
public class RemoveChars {

    public static String remove(String string, String remove) {
        return new String(remove(string.toCharArray(), remove.toCharArray()));
    }

    public static char[] remove(final char[] chars, char[] remove) {

        int count = 0;
        char[] buffer = new char[chars.length];

        for (int i = 0; i < chars.length; i++) {

            boolean include = true;
            for (int j = 0; j < remove.length; j++) {
                if ((chars[i] == remove[j])) {
                    include = false;
                    break;
                }
            }

            if (include) {
                buffer[count++] = chars[i];
            }
        }

        char[] output = new char[count];
        System.arraycopy(buffer, 0, output, 0, count);

        return output;
    }

    /**
     * For tests!
     */
    public static void main(String[] args) {

        String string = "THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG";
        String remove = "AEIOU";

        System.out.println();
        System.out.println("Remove AEIOU: " + string);
        System.out.println("Result:       " + RemoveChars.remove(string, remove));
    }
}

This is the output:

Remove AEIOU: THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG
Result:       TH QCK BRWN FX JMPS VR TH LZY DG

How to get distinct values for non-key column fields in Laravel?

$users = User::select('column1', 'column2', 'column3')->distinct()->get(); retrieves all three coulmns for distinct rows in the table. You can add as many columns as you wish.

How to get row from R data.frame

10 years later ---> Using tidyverse we could achieve this simply and borrowing a leaf from Christopher Bottoms. For a better grasp, see slice().

library(tidyverse)
x <- structure(list(A = c(5,    3.5, 3.25, 4.25,  1.5 ), 
                    B = c(4.25, 4,   4,    4.5,   4.5 ),
                    C = c(4.5,  2.5, 4,    2.25,  3   )
),
.Names    = c("A", "B", "C"),
class     = "data.frame",
row.names = c(NA, -5L)
)

x
#>      A    B    C
#> 1 5.00 4.25 4.50
#> 2 3.50 4.00 2.50
#> 3 3.25 4.00 4.00
#> 4 4.25 4.50 2.25
#> 5 1.50 4.50 3.00

y<-c(A=5, B=4.25, C=4.5)
y
#>    A    B    C 
#> 5.00 4.25 4.50

#The slice() verb allows one to subset data row-wise. 
x <- x %>% slice(1) #(n) for the nth row, or (i:n) for range i to n, (i:n()) for i to last row...

x
#>   A    B   C
#> 1 5 4.25 4.5

#Test that the items in the row match the vector you wanted
x[1,]==y
#>      A    B    C
#> 1 TRUE TRUE TRUE

Created on 2020-08-06 by the reprex package (v0.3.0)

Equivalent of LIMIT and OFFSET for SQL Server?

-- @RowsPerPage  can be a fixed number and @PageNumber number can be passed 
DECLARE @RowsPerPage INT = 10, @PageNumber INT = 2

SELECT *

FROM MemberEmployeeData

ORDER BY EmployeeNumber

OFFSET @PageNumber*@RowsPerPage ROWS

FETCH NEXT 10 ROWS ONLY

How would I extract a single file (or changes to a file) from a git stash?

$ git checkout stash@{0} -- <filename>

Notes:

  1. Make sure you put space after the "--" and the file name parameter

  2. Replace zero(0) with your specific stash number. To get stash list, use:

    git stash list
    

Based on Jakub Narebski's answer -- Shorter version

Setting the default ssh key location

man ssh gives me this options would could be useful.

-i identity_file Selects a file from which the identity (private key) for RSA or DSA authentication is read. The default is ~/.ssh/identity for protocol version 1, and ~/.ssh/id_rsa and ~/.ssh/id_dsa for pro- tocol version 2. Identity files may also be specified on a per- host basis in the configuration file. It is possible to have multiple -i options (and multiple identities specified in config- uration files).

So you could create an alias in your bash config with something like

alias ssh="ssh -i /path/to/private_key"

I haven't looked into a ssh configuration file, but like the -i option this too could be aliased

-F configfile Specifies an alternative per-user configuration file. If a configuration file is given on the command line, the system-wide configuration file (/etc/ssh/ssh_config) will be ignored. The default for the per-user configuration file is ~/.ssh/config.

Call javascript from MVC controller action

You can call a controller action from a JavaScript function but not vice-versa. How would the server know which client to target? The server simply responds to requests.

An example of calling a controller action from JavaScript (using the jQuery JavaScript library) in the response sent to the client.

$.ajax({
           type: "POST",
           url: "/Controller/Action", // the URL of the controller action method
           data: null, // optional data
           success: function(result) {
                // do something with result
           },                
           error : function(req, status, error) {
                // do something with error   
           }
       });

Format bytes to kilobytes, megabytes, gigabytes

Albeit a bit stale, this library offers a tested and robust conversion API:

https://github.com/gabrielelana/byte-units

Once installed:

\ByteUnits\Binary::bytes(1024)->format();

// Output: "1.00KiB"

And to convert in the other direction:

\ByteUnits\Binary::parse('1KiB')->numberOfBytes();

// Output: "1024"

Beyond basic conversion, it offers methods for addition, subtraction, comparison, etc.

I am no way affiliated with this library.

Example for boost shared_mutex (multiple reads/one write)?

Just to add some more empirical info, I have been investigating the whole issue of upgradable locks, and Example for boost shared_mutex (multiple reads/one write)? is a good answer adding the important info that only one thread can have an upgrade_lock even if it is not upgraded, that is important as it means you cannot upgrade from a shared lock to a unique lock without releasing the shared lock first. (This has been discussed elsewhere but the most interesting thread is here http://thread.gmane.org/gmane.comp.lib.boost.devel/214394)

However I did find an important (undocumented) difference between a thread waiting for an upgrade to a lock (ie needs to wait for all readers to release the shared lock) and a writer lock waiting for the same thing (ie a unique_lock).

  1. The thread that is waiting for a unique_lock on the shared_mutex blocks any new readers coming in, they have to wait for the writers request. This ensures readers do not starve writers (however I believe writers could starve readers).

  2. The thread that is waiting for an upgradeable_lock to upgrade allows other threads to get a shared lock, so this thread could be starved if readers are very frequent.

This is an important issue to consider, and probably should be documented.

How to darken an image on mouseover?

Or, similar to erikkallen's idea, make the background of the A tag black, and make the image semitransparent on mouseover. That way you won't have to create additional divs.


Source for the CSS-based solution:

a.darken {
    display: inline-block;
    background: black;
    padding: 0;
}

a.darken img {
    display: block;

    -webkit-transition: all 0.5s linear;
       -moz-transition: all 0.5s linear;
        -ms-transition: all 0.5s linear;
         -o-transition: all 0.5s linear;
            transition: all 0.5s linear;
}

a.darken:hover img {
    opacity: 0.7;

}

And the image:

<a href="http://google.com" class="darken">
    <img src="http://www.prelovac.com/vladimir/wp-content/uploads/2008/03/example.jpg" width="200">
</a>

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

You need to encode Unicode explicitly before writing to a file, otherwise Python does it for you with the default ASCII codec.

Pick an encoding and stick with it:

f.write(printinfo.encode('utf8') + '\n')

or use io.open() to create a file object that'll encode for you as you write to the file:

import io

f = io.open(filename, 'w', encoding='utf8')

You may want to read:

before continuing.

How to Set Focus on Input Field using JQuery

Justin's answer did not work for me (Chromium 18, Firefox 43.0.1). jQuery's .focus() creates visual highlight, but text cursor does not appear in the field (jquery 3.1.0).

Inspired by https://www.sitepoint.com/jqueryhtml5-input-focus-cursor-positions/ , I added autofocus attribute to the input field and voila!

function addfield() {
    n=$('table tr').length;
    $('table').append('<tr><td><input name=field'+n+' autofocus></td><td><input name=value'+n+'></td></tr>');
    $('input[name="aa"'+n+']').focus();
}

MySQL selecting yesterday's date

Last or next date, week, month & year calculation. It might be helpful for anyone.

Current Date:

select curdate();

Yesterday:

select subdate(curdate(), 1)

Tomorrow:

select adddate(curdate(), 1)

Last 1 week:

select between subdate(curdate(), 7) and subdate(curdate(), 1)

Next 1 week:

between adddate(curdate(), 7) and adddate(curdate(), 1)

Last 1 month:

between subdate(curdate(), 30) and subdate(curdate(), 1)

Next 1 month:

between adddate(curdate(), 30) and adddate(curdate(), 1)

Current month:

subdate(curdate(),day(curdate())-1) and last_day(curdate());

Last 1 year:

between subdate(curdate(), 365) and subdate(curdate(), 1)

Next 1 year:

between adddate(curdate(), 365) and adddate(curdate(), 1)

Best way to use Google's hosted jQuery, but fall back to my hosted library on Google fail

The inability to load the resource from an external data store beyond your control is difficult. Looking for missing functions is totally fallacious as a means to avoid suffering a timeout, as described herein: http://www.tech-101.com/support/topic/4499-issues-using-a-cdn/

How to start an Android application from the command line?

Example here.

Pasted below:

This is about how to launch android application from the adb shell.

Command: am

Look for invoking path in AndroidManifest.xml

Browser app::

# am start -a android.intent.action.MAIN -n com.android.browser/.BrowserActivity
Starting: Intent { action=android.intent.action.MAIN comp={com.android.browser/com.android.browser.BrowserActivity} }
Warning: Activity not started, its current task has been brought to the front

Settings app::

# am start -a android.intent.action.MAIN -n com.android.settings/.Settings
Starting: Intent { action=android.intent.action.MAIN comp={com.android.settings/com.android.settings.Settings} }

Angular 4/5/6 Global Variables

I use environment for that. It works automatically and you don't have to create new injectable service and most usefull for me, don't need to import via constructor.

1) Create environment variable in your environment.ts

export const environment = {
    ...
    // runtime variables
    isContentLoading: false,
    isDeployNeeded: false
}

2) Import environment.ts in *.ts file and create public variable (i.e. "env") to be able to use in html template

import { environment } from 'environments/environment';

@Component(...)
export class TestComponent {
    ...
    env = environment;
}

3) Use it in template...

<app-spinner *ngIf='env.isContentLoading'></app-spinner>

in *.ts ...

env.isContentLoading = false 

(or just environment.isContentLoading in case you don't need it for template)


You can create your own set of globals within environment.ts like so:

export const globals = {
    isContentLoading: false,
    isDeployNeeded: false
}

and import directly these variables (y)

Javascript setInterval not working

That's because you should pass a function, not a string:

function funcName() {
    alert("test");
}

setInterval(funcName, 10000);

Your code has two problems:

  • var func = funcName(); calls the function immediately and assigns the return value.
  • Just "func" is invalid even if you use the bad and deprecated eval-like syntax of setInterval. It would be setInterval("func()", 10000) to call the function eval-like.

How to delete all instances of a character in a string in python?

Try str.replace():

string = "it is icy"
print string.replace("i", "")

Setting attribute disabled on a SPAN element does not prevent click events

The disabled attribute is not global and is only allowed on form controls. What you could do is set a custom data attribute (perhaps data-disabled) and check for that attribute when you handle the click event.

How does HTTP_USER_AGENT work?

The user agent string is a text that the browsers themselves send to the webserver to identify themselves, so that websites can send different content based on the browser or based on browser compatibility.

Mozilla is a browser rendering engine (the one at the core of Firefox) and the fact that Chrome and IE contain the string Mozilla/4 or /5 identifies them as being compatible with that rendering engine.

Generic XSLT Search and Replace template

Here's one way in XSLT 2

<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">   <xsl:template match="@*|node()">     <xsl:copy>       <xsl:apply-templates select="@*|node()"/>     </xsl:copy>   </xsl:template>   <xsl:template match="text()">     <xsl:value-of select="translate(.,'&quot;','''')"/>   </xsl:template> </xsl:stylesheet> 

Doing it in XSLT1 is a little more problematic as it's hard to get a literal containing a single apostrophe, so you have to resort to a variable:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">   <xsl:template match="@*|node()">     <xsl:copy>       <xsl:apply-templates select="@*|node()"/>     </xsl:copy>   </xsl:template>   <xsl:variable name="apos">'</xsl:variable>   <xsl:template match="text()">     <xsl:value-of select="translate(.,'&quot;',$apos)"/>   </xsl:template> </xsl:stylesheet> 

How to convert an Array to a Set in Java

Java 8:

String[] strArray = {"eins", "zwei", "drei", "vier"};

Set<String> strSet = Arrays.stream(strArray).collect(Collectors.toSet());
System.out.println(strSet);
// [eins, vier, zwei, drei]

Can you set a border opacity in CSS?

Unfortunately the opacity element makes the whole element (including any text) semi-transparent. The best way to make the border semi-transparent is with the rgba color format. For example, this would give a red border with 50% opacity:

div {
    border: 1px solid rgba(255, 0, 0, .5);
    -webkit-background-clip: padding-box; /* for Safari */
    background-clip: padding-box; /* for IE9+, Firefox 4+, Opera, Chrome */
}

The problem with this approach is that some browsers do not understand the rgba format and will not display any border at all if this is the entire declaration. The solution is to provide two border declarations. The first with a fake opacity, and the second with the actual. If a browser is capable, it will use the second, if not, it will use the first.

div {
    border: 1px solid rgb(127, 0, 0);
    border: 1px solid rgba(255, 0, 0, .5);
    -webkit-background-clip: padding-box; /* for Safari */
    background-clip: padding-box; /* for IE9+, Firefox 4+, Opera, Chrome */
}

The first border declaration will be the equivalent color to a 50% opaque red border over a white background (although any graphics under the border will not bleed through).

UPDATE: I've added "background-clip: padding-box;" to this answer (per SooDesuNe's suggestion in the comments) to ensure the border remains transparent even if a solid background color is applied.

Set the maximum character length of a UITextField in Swift

Other solutions posted above produce a retain cycle due to the textfield map. Besides, the maxLength property should be nullable if not set instead of artificial Int.max constructions; and the target will be set multiple times if maxLength is changed.

Here an updated solution for Swift4 with a weak map to prevent memory leaks and the other fixes

private var maxLengths = NSMapTable<UITextField, NSNumber>(keyOptions: NSPointerFunctions.Options.weakMemory, valueOptions: NSPointerFunctions.Options.strongMemory)

extension UITextField {

    var maxLength: Int? {
        get {
            return maxLengths.object(forKey: self)?.intValue
        }
        set {
            removeTarget(self, action: #selector(limitLength), for: .editingChanged)
            if let newValue = newValue {
                maxLengths.setObject(NSNumber(value: newValue), forKey: self)
                addTarget(self, action: #selector(limitLength), for: .editingChanged)
            } else {
                maxLengths.removeObject(forKey: self)
            }
        }
    }

    @IBInspectable var maxLengthInspectable: Int {
        get {
            return maxLength ?? Int.max
        }
        set {
            maxLength = newValue
        }
    }

    @objc private func limitLength(_ textField: UITextField) {
        guard let maxLength = maxLength, let prospectiveText = textField.text, prospectiveText.count > maxLength else {
            return
        }
        let selection = selectedTextRange
        text = String(prospectiveText[..<prospectiveText.index(from: maxLength)])
        selectedTextRange = selection
    }
}

How to read an external local JSON file in JavaScript?

When in Node.js or when using require.js in the browser, you can simply do:

let json = require('/Users/Documents/workspace/test.json');
console.log(json, 'the json obj');

Do note: the file is loaded once, subsequent calls will use the cache.

WHERE Clause to find all records in a specific month

If you're using SQL Server, look into DATEPART.

http://msdn.microsoft.com/en-us/library/ms174420(SQL.90).aspx

DATEPART(mm, [THE DATE YOU'RE LOOKING AT])

You can then use normal integer logic with it. Same for year, just use yy instead of mm.

C# Dictionary get item by index

You can take keys or values per index:

int value = _dict.Values.ElementAt(5);//ElementAt value should be <= _dict.Count - 1
string key = _dict.Keys.ElementAt(5);//ElementAt value should be  < =_dict.Count - 1

How to configure CORS in a Spring Boot + Spring Security application?

If you use JDK 8+, there is a one line lambda solution:

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.cors().configurationSource(request -> new CorsConfiguration().applyPermitDefaultValues());
}

SQL Server 2008 can't login with newly created user

You'll likely need to check the SQL Server error logs to determine the actual state (it's not reported to the client for security reasons.) See here for details.

How can I compare time in SQL Server?

You can create a two variables of datetime, and set only hour of date that your need to compare.

declare  @date1 datetime;
declare  @date2 datetime;

select   @date1 = CONVERT(varchar(20),CONVERT(datetime, '2011-02-11 08:00:00'), 114)
select   @date2 = CONVERT(varchar(20),GETDATE(), 114)

The date will be "1900-01-01" you can compare it

if @date1 <= @date2
   print '@date1 less then @date2'
else
   print '@date1 more then @date2'

What is a superfast way to read large files line-by-line in VBA?

'you can modify above and read full file in one go and then display each line as shown below

Option Explicit

Public Function QuickRead(FName As String) As Variant
    Dim i As Integer
    Dim res As String
    Dim l As Long
    Dim v As Variant

    i = FreeFile
    l = FileLen(FName)
    res = Space(l)
    Open FName For Binary Access Read As #i
    Get #i, , res
    Close i
    'split the file with vbcrlf
    QuickRead = Split(res, vbCrLf)
End Function

Sub Test()
    ' you can replace file for "c:\writename.txt to any file name you desire
    Dim strFilePathName As String: strFilePathName = "C:\writename.txt"
    Dim strFileLine As String
    Dim v As Variant
    Dim i As Long
    v = QuickRead(strFilePathName)
    For i = 0 To UBound(v)
        MsgBox v(i)
    Next
End Sub

CSS display: inline vs inline-block

Inline elements:

  1. respect left & right margins and padding, but not top & bottom
  2. cannot have a width and height set
  3. allow other elements to sit to their left and right.
  4. see very important side notes on this here.

Block elements:

  1. respect all of those
  2. force a line break after the block element
  3. acquires full-width if width not defined

Inline-block elements:

  1. allow other elements to sit to their left and right
  2. respect top & bottom margins and padding
  3. respect height and width

From W3Schools:

  • An inline element has no line break before or after it, and it tolerates HTML elements next to it.

  • A block element has some whitespace above and below it and does not tolerate any HTML elements next to it.

  • An inline-block element is placed as an inline element (on the same line as adjacent content), but it behaves as a block element.

When you visualize this, it looks like this:

CSS block vs inline vs inline-block

The image is taken from this page, which also talks some more about this subject.

How do I access previous promise results in a .then() chain?

Node 7.4 now supports async/await calls with the harmony flag.

Try this:

async function getExample(){

  let response = await returnPromise();

  let response2 = await returnPromise2();

  console.log(response, response2)

}

getExample()

and run the file with:

node --harmony-async-await getExample.js

Simple as can be!

How can I change column types in Spark SQL's DataFrame?

First, if you wanna cast type, then this:

import org.apache.spark.sql
df.withColumn("year", $"year".cast(sql.types.IntegerType))

With same column name, the column will be replaced with new one. You don't need to do add and delete steps.

Second, about Scala vs R.
This is the code that most similar to R I can come up with:

val df2 = df.select(
   df.columns.map {
     case year @ "year" => df(year).cast(IntegerType).as(year)
     case make @ "make" => functions.upper(df(make)).as(make)
     case other         => df(other)
   }: _*
)

Though the code length is a little longer than R's. That is nothing to do with the verbosity of the language. In R the mutate is a special function for R dataframe, while in Scala you can easily ad-hoc one thanks to its expressive power.
In word, it avoid specific solutions, because the language design is good enough for you to quickly and easy build your own domain language.


side note: df.columns is surprisingly a Array[String] instead of Array[Column], maybe they want it look like Python pandas's dataframe.

How to adjust text font size to fit textview

This should be a simple solution:

public void correctWidth(TextView textView, int desiredWidth)
{
    Paint paint = new Paint();
    Rect bounds = new Rect();

    paint.setTypeface(textView.getTypeface());
    float textSize = textView.getTextSize();
    paint.setTextSize(textSize);
    String text = textView.getText().toString();
    paint.getTextBounds(text, 0, text.length(), bounds);

    while (bounds.width() > desiredWidth)
    {
        textSize--;
        paint.setTextSize(textSize);
        paint.getTextBounds(text, 0, text.length(), bounds);
    }

    textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize);
}

lexical or preprocessor issue file not found occurs while archiving?

For what it's worth, my problem was completely unrelated to the error Xcode was giving. I stumbled onto a solution by deleting the .h reference, compiling, adding the reference back and compiling again. The actual error then became evident.

Jquery validation plugin - TypeError: $(...).validate is not a function

for me, the problem was from require('jquery-validation') i added in the begging of that js file which Validate method used which is necessary as an npm module

unfortunately, when web pack compiles the js files, they aren't in order, so that the validate method is before defining it! and the error comes

so better to use another js file for compiling this library or use local validate method file or even using CDN but in all cases make sure you attached jquery before

Renaming part of a filename

for file in *.dat ; do mv $file ${file//ABC/XYZ} ; done

No rename or sed needed. Just bash parameter expansion.

resize font to fit in a div (on one line)

I've make a very little jQuery stuff to adjust the font size of your div. It even works with multiple lines, but will only increase font's size (you can simply set a default font size of 1px if you want). I increases the font size until having a line break, set decreases it 1px. No other fancy stuff, hidden div or so. Simply add the quickfit class to your div.

$(".quickfit").each(function() {
    var jThis=$(this);
    var fontSize=parseInt(jThis.css("font-size"));
    var originalLines=jThis.height()/fontSize;

    for(var i=0;originalLines>=jThis.height()/fontSize && i<30;i++)
    { jThis.css("font-size",""+(++fontSize)+"px"); }
    jThis.css("font-size",""+(fontSize-1)+"px");
});

Input text dialog Android

I found it cleaner and more reusable to extend AlertDialog.Builder to create a custom dialog class. This is for a dialog that asks the user to input a phone number. A preset phone number can also be supplied by calling setNumber() before calling show().

InputSenderDialog.java

public class InputSenderDialog extends AlertDialog.Builder {

    public interface InputSenderDialogListener{
        public abstract void onOK(String number);
        public abstract void onCancel(String number);
    }

    private EditText mNumberEdit;

    public InputSenderDialog(Activity activity, final InputSenderDialogListener listener) {
        super( new ContextThemeWrapper(activity, R.style.AppTheme) );

        @SuppressLint("InflateParams") // It's OK to use NULL in an AlertDialog it seems...
        View dialogLayout = LayoutInflater.from(activity).inflate(R.layout.dialog_input_sender_number, null);
        setView(dialogLayout);

        mNumberEdit = dialogLayout.findViewById(R.id.numberEdit);

        setPositiveButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int id) {
                if( listener != null )
                    listener.onOK(String.valueOf(mNumberEdit.getText()));

            }
        });

        setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int id) {
                if( listener != null )
                    listener.onCancel(String.valueOf(mNumberEdit.getText()));
            }
        });
    }

    public InputSenderDialog setNumber(String number){
        mNumberEdit.setText( number );
        return this;
    }

    @Override
    public AlertDialog show() {
        AlertDialog dialog = super.show();
        Window window = dialog.getWindow();
        if( window != null )
            window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
        return dialog;
    }
}

dialog_input_sender_number.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:padding="10dp">

    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        android:paddingBottom="20dp"
        android:text="Input phone number"
        android:textAppearance="@style/TextAppearance.AppCompat.Large" />

    <TextView
        android:id="@+id/numberLabel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintTop_toBottomOf="@+id/title"
        app:layout_constraintLeft_toLeftOf="parent"
        android:text="Phone number" />

    <EditText
        android:id="@+id/numberEdit"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintTop_toBottomOf="@+id/numberLabel"
        app:layout_constraintLeft_toLeftOf="parent"
        android:inputType="phone" >
        <requestFocus />
    </EditText>

</android.support.constraint.ConstraintLayout>

Usage:

new InputSenderDialog(getActivity(), new InputSenderDialog.InputSenderDialogListener() {
    @Override
    public void onOK(final String number) {
        Log.d(TAG, "The user tapped OK, number is "+number);
    }

    @Override
    public void onCancel(String number) {
        Log.d(TAG, "The user tapped Cancel, number is "+number);
    }
}).setNumber(someNumberVariable).show();

What is the origin of foo and bar?

tl;dr

  • "Foo" and "bar" as metasyntactic variables were popularised by MIT and DEC, the first references are in work on LISP and PDP-1 and Project MAC from 1964 onwards.

  • Many of these people were in MIT's Tech Model Railroad Club, where we find the first documented use of "foo" in tech circles in 1959 (and a variant in 1958).

  • Both "foo" and "bar" (and even "baz") were well known in popular culture, especially from Smokey Stover and Pogo comics, which will have been read by many TMRC members.

  • Also, it seems likely the military FUBAR contributed to their popularity.


The use of lone "foo" as a nonsense word is pretty well documented in popular culture in the early 20th century, as is the military FUBAR. (Some background reading: FOLDOC FOLDOC Jargon File Jargon File Wikipedia RFC3092)


OK, so let's find some references.

STOP PRESS! After posting this answer, I discovered this perfect article about "foo" in the Friday 14th January 1938 edition of The Tech ("MIT's oldest and largest newspaper & the first newspaper published on the web"), Volume LVII. No. 57, Price Three Cents:

On Foo-ism

The Lounger thinks that this business of Foo-ism has been carried too far by its misguided proponents, and does hereby and forthwith take his stand against its abuse. It may be that there's no foo like an old foo, and we're it, but anyway, a foo and his money are some party. (Voice from the bleachers- "Don't be foo-lish!")

As an expletive, of course, "foo!" has a definite and probably irreplaceable position in our language, although we fear that the excessive use to which it is currently subjected may well result in its falling into an early (and, alas, a dark) oblivion. We say alas because proper use of the word may result in such happy incidents as the following.

It was an 8.50 Thermodynamics lecture by Professor Slater in Room 6-120. The professor, having covered the front side of the blackboard, set the handle that operates the lift mechanism, turning meanwhile to the class to continue his discussion. The front board slowly, majestically, lifted itself, revealing the board behind it, and on that board, writ large, the symbols that spelled "FOO"!

The Tech newspaper, a year earlier, the Letter to the Editor, September 1937:

By the time the train has reached the station the neophytes are so filled with the stories of the glory of Phi Omicron Omicron, usually referred to as Foo, that they are easy prey.

...

It is not that I mind having lost my first four sons to the Grand and Universal Brotherhood of Phi Omicron Omicron, but I do wish that my fifth son, my baby, should at least be warned in advance.

Hopefully yours,

Indignant Mother of Five.

And The Tech in December 1938:

General trend of thought might be best interpreted from the remarks made at the end of the ballots. One vote said, '"I don't think what I do is any of Pulver's business," while another merely added a curt "Foo."


The first documented "foo" in tech circles is probably 1959's Dictionary of the TMRC Language:

FOO: the sacred syllable (FOO MANI PADME HUM); to be spoken only when under inspiration to commune with the Deity. Our first obligation is to keep the Foo Counters turning.

These are explained at FOLDOC. The dictionary's compiler Pete Samson said in 2005:

Use of this word at TMRC antedates my coming there. A foo counter could simply have randomly flashing lights, or could be a real counter with an obscure input.

And from 1996's Jargon File 4.0.0:

Earlier versions of this lexicon derived 'baz' as a Stanford corruption of bar. However, Pete Samson (compiler of the TMRC lexicon) reports it was already current when he joined TMRC in 1958. He says "It came from "Pogo". Albert the Alligator, when vexed or outraged, would shout 'Bazz Fazz!' or 'Rowrbazzle!' The club layout was said to model the (mythical) New England counties of Rowrfolk and Bassex (Rowrbazzle mingled with (Norfolk/Suffolk/Middlesex/Essex)."

A year before the TMRC dictionary, 1958's MIT Voo Doo Gazette ("Humor suplement of the MIT Deans' office") (PDF) mentions Foocom, in "The Laws of Murphy and Finagle" by John Banzhaf (an electrical engineering student):

Further research under a joint Foocom and Anarcom grant expanded the law to be all embracing and universally applicable: If anything can go wrong, it will!

Also 1964's MIT Voo Doo (PDF) references the TMRC usage:

Yes! I want to be an instant success and snow customers. Send me a degree in: ...

  • Foo Counters

  • Foo Jung


Let's find "foo", "bar" and "foobar" published in code examples.

So, Jargon File 4.4.7 says of "foobar":

Probably originally propagated through DECsystem manuals by Digital Equipment Corporation (DEC) in 1960s and early 1970s; confirmed sightings there go back to 1972.

The first published reference I can find is from February 1964, but written in June 1963, The Programming Language LISP: its Operation and Applications by Information International, Inc., with many authors, but including Timothy P. Hart and Michael Levin:

Thus, since "FOO" is a name for itself, "COMITRIN" will treat both "FOO" and "(FOO)" in exactly the same way.

Also includes other metasyntactic variables such as: FOO CROCK GLITCH / POOT TOOR / ON YOU / SNAP CRACKLE POP / X Y Z

I expect this is much the same as this next reference of "foo" from MIT's Project MAC in January 1964's AIM-064, or LISP Exercises by Timothy P. Hart and Michael Levin:

car[((FOO . CROCK) . GLITCH)]

It shares many other metasyntactic variables like: CHI / BOSTON NEW YORK / SPINACH BUTTER STEAK / FOO CROCK GLITCH / POOT TOOP / TOOT TOOT / ISTHISATRIVIALEXCERCISE / PLOOP FLOT TOP / SNAP CRACKLE POP / ONE TWO THREE / PLANE SUB THRESHER

For both "foo" and "bar" together, the earliest reference I could find is from MIT's Project MAC in June 1966's AIM-098, or PDP-6 LISP by none other than Peter Samson:

EXPLODE, like PRIN1, inserts slashes, so (EXPLODE (QUOTE FOO/ BAR)) PRIN1's as (F O O // / B A R) or PRINC's as (F O O / B A R).


Some more recallations.

@Walter Mitty recalled on this site in 2008:

I second the jargon file regarding Foo Bar. I can trace it back at least to 1963, and PDP-1 serial number 2, which was on the second floor of Building 26 at MIT. Foo and Foo Bar were used there, and after 1964 at the PDP-6 room at project MAC.

John V. Everett recalls in 1996:

When I joined DEC in 1966, foobar was already being commonly used as a throw-away file name. I believe fubar became foobar because the PDP-6 supported six character names, although I always assumed the term migrated to DEC from MIT. There were many MIT types at DEC in those days, some of whom had worked with the 7090/7094 CTSS. Since the 709x was also a 36 bit machine, foobar may have been used as a common file name there.

Foo and bar were also commonly used as file extensions. Since the text editors of the day operated on an input file and produced an output file, it was common to edit from a .foo file to a .bar file, and back again.

It was also common to use foo to fill a buffer when editing with TECO. The text string to exactly fill one disk block was IFOO$HXA127GA$$. Almost all of the PDP-6/10 programmers I worked with used this same command string.

Daniel P. B. Smith in 1998:

Dick Gruen had a device in his dorm room, the usual assemblage of B-battery, resistors, capacitors, and NE-2 neon tubes, which he called a "foo counter." This would have been circa 1964 or so.

Robert Schuldenfrei in 1996:

The use of FOO and BAR as example variable names goes back at least to 1964 and the IBM 7070. This too may be older, but that is where I first saw it. This was in Assembler. What would be the FORTRAN integer equivalent? IFOO and IBAR?

Paul M. Wexelblat in 1992:

The earliest PDP-1 Assembler used two characters for symbols (18 bit machine) programmers always left a few words as patch space to fix problems. (Jump to patch space, do new code, jump back) That space conventionally was named FU: which stood for Fxxx Up, the place where you fixed Fxxx Ups. When spoken, it was known as FU space. Later Assemblers ( e.g. MIDAS allowed three char tags so FU became FOO, and as ALL PDP-1 programmers will tell you that was FOO space.

Bruce B. Reynolds in 1996:

On the IBM side of FOO(FU)BAR is the use of the BAR side as Base Address Register; in the middle 1970's CICS programmers had to worry out the various xxxBARs...I think one of those was FRACTBAR...

Here's a straight IBM "BAR" from 1955.


Other early references:


I haven't been able to find any references to foo bar as "inverted foo signal" as suggested in RFC3092 and elsewhere.

Here are a some of even earlier F00s but I think they're coincidences/false positives:

How to force table cell <td> content to wrap?

Use table-layout:fixed in the table and word-wrap:break-word in the td.

See this example:

<html>
<head>
   <style>
   table {border-collapse:collapse; table-layout:fixed; width:310px;}
   table td {border:solid 1px #fab; width:100px; word-wrap:break-word;}
   </style>
</head>

<body>
   <table>
      <tr>
         <td>1</td>
         <td>Lorem Ipsum</td>
         <td>Lorem Ipsum is simply dummy text of the printing and typesetting industry. </td>
      </tr>
      <tr>
         <td>2</td>
         <td>LoremIpsumhasbeentheindustry'sstandarddummytexteversincethe1500s,whenanunknown</td>
         <td>Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.</td>
      </tr>
      <tr>
         <td>3</td>
         <td></td>
         <td>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna...</td>
      </tr>
   </table>
</body>
</html>

DEMO:

_x000D_
_x000D_
table {border-collapse:collapse; table-layout:fixed; width:310px;}_x000D_
       table td {border:solid 1px #fab; width:100px; word-wrap:break-word;}
_x000D_
       <table>_x000D_
          <tr>_x000D_
             <td>1</td>_x000D_
             <td>Lorem Ipsum</td>_x000D_
             <td>Lorem Ipsum is simply dummy text of the printing and typesetting industry. </td>_x000D_
          </tr>_x000D_
          <tr>_x000D_
             <td>2</td>_x000D_
             <td>LoremIpsumhasbeentheindustry'sstandarddummytexteversincethe1500s,whenanunknown</td>_x000D_
             <td>Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.</td>_x000D_
          </tr>_x000D_
          <tr>_x000D_
             <td>3</td>_x000D_
             <td></td>_x000D_
             <td>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna...</td>_x000D_
          </tr>_x000D_
       </table>_x000D_
    
_x000D_
_x000D_
_x000D_

Save Dataframe to csv directly to s3 Python

since you are using boto3.client(), try:

import boto3
from io import StringIO #python3 
s3 = boto3.client('s3', aws_access_key_id='key', aws_secret_access_key='secret_key')
def copy_to_s3(client, df, bucket, filepath):
    csv_buf = StringIO()
    df.to_csv(csv_buf, header=True, index=False)
    csv_buf.seek(0)
    client.put_object(Bucket=bucket, Body=csv_buf.getvalue(), Key=filepath)
    print(f'Copy {df.shape[0]} rows to S3 Bucket {bucket} at {filepath}, Done!')

copy_to_s3(client=s3, df=df_to_upload, bucket='abc', filepath='def/test.csv')

Why is AJAX returning HTTP status code 0?

I think I know what may cause this error.

In google chrome there is an in-built feature to prevent ddos attacks for google chrome extensions.

When ajax requests continuously return 500+ status errors, it starts to throttle the requests.

Hence it is possible to receive status 0 on following requests.

Server Client send/receive simple text

   public partial class Form1 : Form
    {
        private Thread n_server;
        private Thread n_client;
        private Thread n_send_server;
        private TcpClient client;
        private TcpListener listener;
        private int port = 2222;
        private string IP = " ";
        private Socket socket;
        byte[] bufferReceive = new byte[4096];
        byte[] bufferSend = new byte[4096];
        public Form1()
        {
            InitializeComponent();
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        public void Server()
        {
            listener = new TcpListener(IPAddress.Any, port);
            listener.Start();
            try
            {
                socket = listener.AcceptSocket();
                if (socket.Connected)
                {
                    textBox3.Invoke((MethodInvoker)delegate { textBox3.Text = "Client        : " + socket.RemoteEndPoint.ToString(); });
                }
                while (true)
                {
                    int length = socket.Receive(bufferReceive);
                    if (length > 0)
                    {
                        label2.Invoke((MethodInvoker)delegate { label2.Text = Encoding.Unicode.GetString(bufferReceive); });
                    }
                }
            }
            catch
            {
            }
        }

        public void Client()
        {
            IP = "localhost";
            client = new TcpClient();
            try
            {
                client.Connect(IP, port);
                while (true)
                {
                    NetworkStream nts = client.GetStream();
                    int length;
                    while ((length = nts.Read(bufferReceive, 0, bufferReceive.Length)) != 0)
                    {
                       label3.Invoke((MethodInvoker)delegate { label3.Text = Encoding.Unicode.GetString(bufferReceive); });
                    }
                }
            }

            catch (Exception ex)
            {
                MessageBox.Show("Error : " + ex.Message);
            }

            if (client.Connected)
            {
                textBox3.Invoke((MethodInvoker)delegate { textBox3.Text = "Connected..."; });

            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            n_server = new Thread(new ThreadStart(Server));
            n_server.IsBackground = true;
            n_server.Start();
            textBox1.Text = "Server up";
        }

        private void button2_Click(object sender, EventArgs e)
        {
            n_client = new Thread(new ThreadStart(Client));
            n_client.IsBackground = true;
            n_client.Start();
        }

        private void send()
        {
            if (socket!=null)
            {
                bufferSend = Encoding.Unicode.GetBytes(textBox2.Text);
                socket.Send(bufferSend);
            }
            else
            {
                if (client.Connected)
                {
                    bufferSend = Encoding.Unicode.GetBytes(textBox3.Text);
                    NetworkStream nts = client.GetStream();
                    if (nts.CanWrite)
                    {
                        nts.Write(bufferSend,0,bufferSend.Length);
                    }

                }
            }
        }



        private void button3_Click(object sender, EventArgs e)
        {
            n_send_server = new Thread(new ThreadStart(send));
            n_send_server.IsBackground = true;
            n_send_server.Start();
        }
    }

Conda uninstall one package and one package only

You can use conda remove --force.

The documentation says:

--force               Forces removal of a package without removing packages
                      that depend on it. Using this option will usually
                      leave your environment in a broken and inconsistent
                      state

Any shortcut to initialize all array elements to zero?

You can save the loop, initialization is already made to 0. Even for a local variable.

But please correct the place where you place the brackets, for readability (recognized best-practice):

int[] arr = new int[10];

Count number of iterations in a foreach loop

If you just want to find out the number of elements in an array, use count. Now, to answer your question...

How to calculate how many items in a foreach?

$i = 0;
foreach ($Contents as $item) {
    $item[number];// if there are 15 $item[number] in this foreach, I want get the value : 15
    $i++;
}

If you only need the index inside the loop, you could use

foreach($Contents as $index=>$item) {
    // $index goes from 0 up to count($Contents) - 1
    // $item iterates over the elements
}

WooCommerce - get category for product page

I literally striped out this line of code from content-single-popup.php located in woocommerce folder in my theme directory.

global $product; 
echo $product->get_categories( ', ', ' ' . _n( ' ', '  ', $cat_count, 'woocommerce' ) . ' ', ' ' );

Since my theme that I am working on has integrated woocommerce in it, this was my solution.

What does functools.wraps do?

this is the source code about wraps:

WRAPPER_ASSIGNMENTS = ('__module__', '__name__', '__doc__')

WRAPPER_UPDATES = ('__dict__',)

def update_wrapper(wrapper,
                   wrapped,
                   assigned = WRAPPER_ASSIGNMENTS,
                   updated = WRAPPER_UPDATES):

    """Update a wrapper function to look like the wrapped function

       wrapper is the function to be updated
       wrapped is the original function
       assigned is a tuple naming the attributes assigned directly
       from the wrapped function to the wrapper function (defaults to
       functools.WRAPPER_ASSIGNMENTS)
       updated is a tuple naming the attributes of the wrapper that
       are updated with the corresponding attribute from the wrapped
       function (defaults to functools.WRAPPER_UPDATES)
    """
    for attr in assigned:
        setattr(wrapper, attr, getattr(wrapped, attr))
    for attr in updated:
        getattr(wrapper, attr).update(getattr(wrapped, attr, {}))
    # Return the wrapper so this can be used as a decorator via partial()
    return wrapper

def wraps(wrapped,
          assigned = WRAPPER_ASSIGNMENTS,
          updated = WRAPPER_UPDATES):
    """Decorator factory to apply update_wrapper() to a wrapper function

   Returns a decorator that invokes update_wrapper() with the decorated
   function as the wrapper argument and the arguments to wraps() as the
   remaining arguments. Default arguments are as for update_wrapper().
   This is a convenience function to simplify applying partial() to
   update_wrapper().
    """
    return partial(update_wrapper, wrapped=wrapped,
                   assigned=assigned, updated=updated)

How to establish a connection pool in JDBC?

I would recommend using the commons-dbcp library. There are numerous examples listed on how to use it, here is the link to the move simple one. The usage is very simple:

 BasicDataSource ds = new BasicDataSource();
 ds.setDriverClassName("oracle.jdbc.driver.OracleDriver")
 ds.setUsername("scott");
 ds.setPassword("tiger");
 ds.setUrl(connectURI);
 ...
 Connection conn = ds.getConnection();

You only need to create the data source once, so make sure you read the documentation if you do not know how to do that. If you are not aware of how to properly write JDBC statements so you do not leak resources, you also might want to read this Wikipedia page.

How to loop through a HashMap in JSP?

Below code works for me

first I defined the partnerTypesMap like below in the server side,

Map<String, String> partnerTypes = new HashMap<>();

after adding values to it I added the object to model,

model.addAttribute("partnerTypesMap", partnerTypes);

When rendering the page I use below foreach to print them one by one.

<c:forEach items="${partnerTypesMap}" var="partnerTypesMap">
      <form:option value="${partnerTypesMap['value']}">${partnerTypesMap['key']}</form:option>
</c:forEach>

Where is my m2 folder on Mac OS X Mavericks

If you have used brew to install maven, create .m2 directory and then copy settings.xml in .m2 directory.

mkdir ~/.m2
cp /usr/local/Cellar/maven32/3.2.5/libexec/conf/settings.xml ~/.m2

You may need to change the maven version in the path, mine is 3.2.5

How to check if the docker engine and a docker container are running?

List all containers:

docker container ls -a

ls = list
-a = all

Check the column "status"

How to set environment variables in Python?

os.environ behaves like a python dictionary, so all the common dictionary operations can be performed. In addition to the get and set operations mentioned in the other answers, we can also simply check if a key exists. The keys and values should be stored as strings.

Python 3

For python 3, dictionaries use the in keyword instead of has_key

>>> import os
>>> 'HOME' in os.environ  # Check an existing env. variable
True
...

Python 2

>>> import os
>>> os.environ.has_key('HOME')  # Check an existing env. variable
True
>>> os.environ.has_key('FOO')   # Check for a non existing variable
False
>>> os.environ['FOO'] = '1'     # Set a new env. variable (String value)
>>> os.environ.has_key('FOO')
True
>>> os.environ.get('FOO')       # Retrieve the value
'1'

There is one important thing to note about using os.environ:

Although child processes inherit the environment from the parent process, I had run into an issue recently and figured out, if you have other scripts updating the environment while your python script is running, calling os.environ again will not reflect the latest values.

Excerpt from the docs:

This mapping is captured the first time the os module is imported, typically during Python startup as part of processing site.py. Changes to the environment made after this time are not reflected in os.environ, except for changes made by modifying os.environ directly.

os.environ.data which stores all the environment variables, is a dict object, which contains all the environment values:

>>> type(os.environ.data)  # changed to _data since v3.2 (refer comment below)
<type 'dict'>

How to: "Separate table rows with a line"

Just style the border of the rows:

?table tr {
    border-bottom: 1px solid black;
}?

table tr:last-child { 
    border-bottom: none; 
}

Here is a fiddle.

Edited as mentioned by @pkyeck. The second style avoids the line under the last row. Maybe you are looking for this.

Replace invalid values with None in Pandas DataFrame

Before proceeding with this post, it is important to understand the difference between NaN and None. One is a float type, the other is an object type. Pandas is better suited to working with scalar types as many methods on these types can be vectorised. Pandas does try to handle None and NaN consistently, but NumPy cannot.

My suggestion (and Andy's) is to stick with NaN.

But to answer your question...

pandas >= 0.18: Use na_values=['-'] argument with read_csv

If you loaded this data from CSV/Excel, I have good news for you. You can quash this at the root during data loading instead of having to write a fix with code as a subsequent step.

Most of the pd.read_* functions (such as read_csv and read_excel) accept a na_values attribute.

file.csv

A,B
-,1
3,-
2,-
5,3
1,-2
-5,4
-1,-1
-,0
9,0

Now, to convert the - characters into NaNs, do,

import pandas as pd
df = pd.read_csv('file.csv', na_values=['-'])
df

     A    B
0  NaN  1.0
1  3.0  NaN
2  2.0  NaN
3  5.0  3.0
4  1.0 -2.0
5 -5.0  4.0
6 -1.0 -1.0
7  NaN  0.0
8  9.0  0.0

And similar for other functions/file formats.

P.S.: On v0.24+, you can preserve integer type even if your column has NaNs (yes, talk about having the cake and eating it too). You can specify dtype='Int32'

df = pd.read_csv('file.csv', na_values=['-'], dtype='Int32')
df

     A    B
0  NaN    1
1    3  NaN
2    2  NaN
3    5    3
4    1   -2
5   -5    4
6   -1   -1
7  NaN    0
8    9    0

df.dtypes

A    Int32
B    Int32
dtype: object

The dtype is not a conventional int type... but rather, a Nullable Integer Type. There are other options.


Handling Numeric Data: pd.to_numeric with errors='coerce

If you're dealing with numeric data, a faster solution is to use pd.to_numeric with the errors='coerce' argument, which coerces invalid values (values that cannot be cast to numeric) to NaN.

pd.to_numeric(df['A'], errors='coerce')

0    NaN
1    3.0
2    2.0
3    5.0
4    1.0
5   -5.0
6   -1.0
7    NaN
8    9.0
Name: A, dtype: float64

To retain (nullable) integer dtype, use

pd.to_numeric(df['A'], errors='coerce').astype('Int32')

0    NaN
1      3
2      2
3      5
4      1
5     -5
6     -1
7    NaN
8      9
Name: A, dtype: Int32 

To coerce multiple columns, use apply:

df[['A', 'B']].apply(pd.to_numeric, errors='coerce').astype('Int32')

     A    B
0  NaN    1
1    3  NaN
2    2  NaN
3    5    3
4    1   -2
5   -5    4
6   -1   -1
7  NaN    0
8    9    0

...and assign the result back after.

More information can be found in this answer.

How to use Bootstrap modal using the anchor tag for Register?

Just replace it:

<li><a href="" data-toggle="modal" data-target="#modalRegister">Register</a></li>

Instead of:

<li><a href="#" data-toggle="modal" data-target="modalRegister">Register</a></li>

How to call javascript function on page load in asp.net

<html>
<head>
<script type="text/javascript">
function GetTimeZoneOffset() {
    var d = new Date()
    var gmtOffSet = -d.getTimezoneOffset();
    var gmtHours = Math.floor(gmtOffSet / 60);
    var GMTMin = Math.abs(gmtOffSet % 60);
    var dot = ".";
    var retVal = "" + gmtHours + dot + GMTMin;
    document.getElementById('<%= offSet.ClientID%>').value = retVal;
}

</script>
</head>
<body onload="GetTimeZoneOffset()">
    <asp:HiddenField ID="clientDateTime" runat="server" />
    <asp:HiddenField ID="offSet" runat="server" />
    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</body>
</html>

key point to notice here is,body has an attribute onload. Just give it a function name and that function will be called on page load.


Alternatively, you can also call the function on page load event like this

<html>
<head>
<script type="text/javascript">

window.onload = load();

function load() {
    var d = new Date()
    var gmtOffSet = -d.getTimezoneOffset();
    var gmtHours = Math.floor(gmtOffSet / 60);
    var GMTMin = Math.abs(gmtOffSet % 60);
    var dot = ".";
    var retVal = "" + gmtHours + dot + GMTMin;
    document.getElementById('<%= offSet.ClientID%>').value = retVal;
}

</script>
</head>
<body >
    <asp:HiddenField ID="clientDateTime" runat="server" />
    <asp:HiddenField ID="offSet" runat="server" />
    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox></body>
</body>
</html>

convert NSDictionary to NSString

Above Solutions will only convert dictionary into string but you can't convert back that string to dictionary. For that it is the better way.

Convert to String

NSError * err;
NSData * jsonData = [NSJSONSerialization  dataWithJSONObject:yourDictionary options:0 error:&err];
NSString * myString = [[NSString alloc] initWithData:jsonData   encoding:NSUTF8StringEncoding];
NSLog(@"%@",myString);

Convert Back to Dictionary

NSError * err;
NSData *data =[myString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary * response;
if(data!=nil){
 response = (NSDictionary *)[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&err];
}

How to Create Multiple Where Clause Query Using Laravel Eloquent?

As per my suggestion if you are doing filter or searching

then you should go with :

        $results = User::query();
        $results->when($request->that, function ($q) use ($request) {
            $q->where('that', $request->that);
        });
        $results->when($request->this, function ($q) use ($request) {
            $q->where('this', $request->that);
        });
        $results->when($request->this_too, function ($q) use ($request) {
            $q->where('this_too', $request->that);
        });
        $results->get();

Parsing HTTP Response in Python

When I printed response.read() I noticed that b was preprended to the string (e.g. b'{"a":1,..). The "b" stands for bytes and serves as a declaration for the type of the object you're handling. Since, I knew that a string could be converted to a dict by using json.loads('string'), I just had to convert the byte type to a string type. I did this by decoding the response to utf-8 decode('utf-8'). Once it was in a string type my problem was solved and I was easily able to iterate over the dict.

I don't know if this is the fastest or most 'pythonic' way of writing this but it works and theres always time later of optimization and improvement! Full code for my solution:

from urllib.request import urlopen
import json

# Get the dataset
url = 'http://www.quandl.com/api/v1/datasets/FRED/GDP.json'
response = urlopen(url)

# Convert bytes to string type and string type to dict
string = response.read().decode('utf-8')
json_obj = json.loads(string)

print(json_obj['source_name']) # prints the string with 'source_name' key

jQuery multiple conditions within if statement

i == 'InvKey' && i == 'PostDate' will never be true, since i can never equal two different things at once.

You're probably trying to write

if (i !== 'InvKey' && i !== 'PostDate')) 

How do I turn off autocommit for a MySQL client?

Perhaps the best way is to write a script that starts the mysql command line client and then automatically runs whatever sql you want before it hands over the control to you.

linux comes with an application called 'expect'. it interacts with the shell in such a way as to mimic your key strokes. it can be set to start mysql, wait for you to enter your password. run further commands such as SET autocommit = 0; then go into interactive mode so you can run any command you want.

for more on the command SET autocommit = 0; see.. http://dev.mysql.com/doc/refman/5.0/en/innodb-transaction-model.html

I use expect to log in to a command line utility in my case it starts ssh, connects to the remote server, starts the application enters my username and password then turns over control to me. saves me heaps of typing :)

http://linux.die.net/man/1/expect

DC

Expect script provided by Michael Hinds

spawn /usr/local/mysql/bin/mysql 
expect "mysql>" 
send "set autocommit=0;\r" 
expect "mysql>" interact

expect is pretty powerful and can make life a lot easier as in this case.

if you want to make the script run without calling expect use the shebang line

insert this as the first line in your script (hint: use which expect to find the location of your expect executable)

#! /usr/bin/expect

then change the permissions of your script with..

chmod 0744 myscript

then call the script

./myscript

DC

HTML5 <video> element on Android

After much research, in many different devices, up to now, I've reached the simple conclusion that MP4 is much less supported than MOV format. So, I'm using MOV format, which is supported by all Android and Apple devices, on all browsers. I've detected weather the device is a mobile device or a desktop browser, and set the SRC accordingly:

if (IsMobile()) {
    $('#vid').attr('src', '/uploads/' + name + '.mov');
}
else {
    $('#vid').attr('src', '/uploads/' + name + '.webm');        
}

function IsMobile() {
    var isMobile = false; //initiate as false

    if (/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|ipad|iris|kindle|Android|Silk|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i.test(navigator.userAgent)
                || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(navigator.userAgent.substr(0, 4))) isMobile = true;
    return isMobile;
}

Single quotes vs. double quotes in Python

Your team's taste or your project's coding guidelines.

If you are in a multilanguage environment, you might wish to encourage the use of the same type of quotes for strings that the other language uses, for instance. Else, I personally like best the look of '

Converting a date string to a DateTime object using Joda Time library

From comments I picked an answer like and also adding TimeZone:

String dateTime = "2015-07-18T13:32:56.971-0400";

DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZZ")
        .withLocale(Locale.ROOT)
        .withChronology(ISOChronology.getInstanceUTC());

DateTime dt = formatter.parseDateTime(dateTime);

Why does one use dependency injection?

As the other answers stated, dependency injection is a way to create your dependencies outside of the class that uses it. You inject them from the outside, and take control about their creation away from the inside of your class. This is also why dependency injection is a realization of the Inversion of control (IoC) principle.

IoC is the principle, where DI is the pattern. The reason that you might "need more than one logger" is never actually met, as far as my experience goes, but the actualy reason is, that you really need it, whenever you test something. An example:

My Feature:

When I look at an offer, I want to mark that I looked at it automatically, so that I don't forget to do so.

You might test this like this:

[Test]
public void ShouldUpdateTimeStamp
{
    // Arrange
    var formdata = { . . . }

    // System under Test
    var weasel = new OfferWeasel();

    // Act
    var offer = weasel.Create(formdata)

    // Assert
    offer.LastUpdated.Should().Be(new DateTime(2013,01,13,13,01,0,0));
}

So somewhere in the OfferWeasel, it builds you an offer Object like this:

public class OfferWeasel
{
    public Offer Create(Formdata formdata)
    {
        var offer = new Offer();
        offer.LastUpdated = DateTime.Now;
        return offer;
    }
}

The problem here is, that this test will most likely always fail, since the date that is being set will differ from the date being asserted, even if you just put DateTime.Now in the test code it might be off by a couple of milliseconds and will therefore always fail. A better solution now would be to create an interface for this, that allows you to control what time will be set:

public interface IGotTheTime
{
    DateTime Now {get;}
}

public class CannedTime : IGotTheTime
{
    public DateTime Now {get; set;}
}

public class ActualTime : IGotTheTime
{
    public DateTime Now {get { return DateTime.Now; }}
}

public class OfferWeasel
{
    private readonly IGotTheTime _time;

    public OfferWeasel(IGotTheTime time)
    {
        _time = time;
    }

    public Offer Create(Formdata formdata)
    {
        var offer = new Offer();
        offer.LastUpdated = _time.Now;
        return offer;
    }
}

The Interface is the abstraction. One is the REAL thing, and the other one allows you to fake some time where it is needed. The test can then be changed like this:

[Test]
public void ShouldUpdateTimeStamp
{
    // Arrange
    var date = new DateTime(2013, 01, 13, 13, 01, 0, 0);
    var formdata = { . . . }

    var time = new CannedTime { Now = date };

    // System under test
    var weasel= new OfferWeasel(time);

    // Act
    var offer = weasel.Create(formdata)

    // Assert
    offer.LastUpdated.Should().Be(date);
}

Like this, you applied the "inversion of control" principle, by injecting a dependency (getting the current time). The main reason to do this is for easier isolated unit testing, there are other ways of doing it. For example, an interface and a class here is unnecessary since in C# functions can be passed around as variables, so instead of an interface you could use a Func<DateTime> to achieve the same. Or, if you take a dynamic approach, you just pass any object that has the equivalent method (duck typing), and you don't need an interface at all.

You will hardly ever need more than one logger. Nonetheless, dependency injection is essential for statically typed code such as Java or C#.

And... It should also be noted that an object can only properly fulfill its purpose at runtime, if all its dependencies are available, so there is not much use in setting up property injection. In my opinion, all dependencies should be satisfied when the constructor is being called, so constructor-injection is the thing to go with.

I hope that helped.

while EOF in JAVA?

The problem is that you're reading nextLine() on the while loop and THEN reading it to a variable. Not only are you getting every 2nd line printed out you're opening yourself to the exception being thrown. An example:

File:

Hello,
Blah blah blah,
Sincerely,
CapnStank
PS. Something something

On first iteration through the loop. The check on while will consume the "Hello," as not equal to null. Inside the loop body you'll see Blah blah blah, printed to the System.

The process will repeat with Sincerely, being consumed and Capnstank printing out.

Finally the while will consume the "PS" line while the String line = fileReader.nextLine() retreives an exception from the file because there's nothing further to read.

To resolve the issue:

String line = fileReader.nextLine();

while (line != null) {
  System.out.println(line);
  line = fileReader.nextLine();
}

Javascript onclick hide div

Simple & Best way:

onclick="parentNode.remove()"

Deletes the complete parent from html

ERROR: Sonar server 'http://localhost:9000' can not be reached

If you use SonarScanner CLI with Docker, you may have this error because the SonarScanner container can not access to the Sonar UI container.

Note that you will have the same error with a simple curl from another container:

docker run --rm byrnedo/alpine-curl 127.0.0.1:9000
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0
curl: (7) Failed to connect to 127.0.0.1 port 8080: Connection refused

The solution is to connect the SonarScanner container to the same docker network of your sonar instance, for instance with --network=host:

docker run --network=host -e SONAR_HOST_URL='http://127.0.0.1:9000' --user="$(id -u):$(id -g)" -v "$PWD:/usr/src" sonarsource/sonar-scanner-cli

(other parameters of this command comes from the SonarScanner CLI documentation)

How to get datas from List<Object> (Java)?

Do like this

List<Object[]> list = HQL.list(); // get your lsit here but in Object array

your query is : "SELECT houses.id, addresses.country, addresses.region,..."

for(Object[] obj : list){
String houseId = String.valueOf(obj[0]); // houseId is at first place in your query
String country = String.valueof(obj[1]); // country is at second and so on....
.......
}

this way you can get the mixed objects with ease, but you should know in advance at which place what value you are getting or you can just check by printing the values to know. sorry for the bad english I hope this help

Static nested class in Java, why?

Non static inner classes can result in memory leaks while static inner class will protect against them. If the outer class holds considerable data, it can lower the performance of the application.

What is the path for the startup folder in windows 2008 server

You can easily reach them by using the Run window and entering:

shell:startup

and

shell:common startup

Source.

Reset push notification settings for app

The plist: /private/var/mobile/Library/RemoteNotification/Clients.plist

... contains the registered clients for push notifications. Removing your app's entry will cause the prompt to re-appear

Convert byte to string in Java

String str = "0x63";
int temp = Integer.parseInt(str.substring(2, 4), 16);
char c = (char)temp;
System.out.print(c);

How to find which version of TensorFlow is installed in my system?

If you have installed via pip, just run the following

$ pip show tensorflow
Name: tensorflow
Version: 1.5.0
Summary: TensorFlow helps the tensors flow

MySQL Select Multiple VALUES

Try this -

 select * from table where id in (3,4) or [name] in ('andy','paul');

When should I use "this" in a class?

“This” keyword in java is used to refer current class objects.

There are 6 uses of “this” keyword in java

  1. Accessing class level variable: mostly used if local and class level variable is same
  2. Accessing class methods : this is default behavior and can be ignored
  3. For calling other constructor of same class
  4. Using ‘this’ keyword as return value : for returning current instance from method
  5. Passing ‘this’ keyword as argument to method Passing : for passing current class instance as argument
  6. this keyword as argument to constructor : for passing current class instance as argument

ref: https://stacktraceguru.com/java/this-keyword-in-java

What is MVC and what are the advantages of it?

One of the major advantages of MVC which has not mentioned here is that MVC provides RESTful urls which enables SEO. When you name your Controllers and Actions wisely, it makes it easier for search engines to find your site if they only take a look at your site Urls. For example you have a car sale website and a page which displays available Lamborghini Veneno cars, instead of having www.MyCarSale.com/product/6548 referring to the page you can choose www.MyCarSale.com/SportCar/Lamborghini-Veneno url for SEO purpose.

Here is a good answer to MVC Advantages and here is an article How to create a SEO friendly Url.

Angular: date filter adds timezone, how to output UTC?

The date filter always formats the dates using the local timezone. You'll have to write your own filter, based on the getUTCXxx() methods of Date, or on a library like moment.js.

"Sources directory is already netbeans project" error when opening a project from existing sources

When you create a NetBeans project from existing sources, NetBeans uses the same directory to add its own files: a netbeans folder with .proj files.

Solution: delete the netbeans folder and restart the IDE. Opening a new project should now work.

Copy to Clipboard for all Browsers using javascript

For security reasons most browsers do not allow to modify the clipboard (except IE, of course...).

The only way to make a copy-to-clipboard function cross-browser compatible is to use Flash.

Python: PIP install path, what is the correct location for this and other addons?

Modules go in site-packages and executables go in your system's executable path. For your environment, this path is /usr/local/bin/.

To avoid having to deal with this, simply use easy_install, distribute or pip. These tools know which files need to go where.

Emulating a do-while loop in Bash

Place the body of your loop after the while and before the test. The actual body of the while loop should be a no-op.

while 
    check_if_file_present
    #do other stuff
    (( current_time <= cutoff ))
do
    :
done

Instead of the colon, you can use continue if you find that more readable. You can also insert a command that will only run between iterations (not before first or after last), such as echo "Retrying in five seconds"; sleep 5. Or print delimiters between values:

i=1; while printf '%d' "$((i++))"; (( i <= 4)); do printf ','; done; printf '\n'

I changed the test to use double parentheses since you appear to be comparing integers. Inside double square brackets, comparison operators such as <= are lexical and will give the wrong result when comparing 2 and 10, for example. Those operators don't work inside single square brackets.

How to change the type of a field?

Starting Mongo 4.2, db.collection.update() can accept an aggregation pipeline, finally allowing the update of a field based on its own value:

// { a: "45", b: "x" }
// { a:  53,  b: "y" }
db.collection.update(
  { a : { $type: 1 } },
  [{ $set: { a: { $toString: "$a" } } }],
  { multi: true }
)
// { a: "45", b: "x" }
// { a: "53", b: "y" }
  • The first part { a : { $type: 1 } } is the match query:

    • It filters which documents to update.
    • In this case, since we want to convert "a" to string when its value is a double, this matches elements for which "a" is of type 1 (double)).
    • This table provides the codes representing the different possible types.
  • The second part [{ $set: { a: { $toString: "$a" } } }] is the update aggregation pipeline:

    • Note the squared brackets signifying that this update query uses an aggregation pipeline.
    • $set is a new aggregation operator (Mongo 4.2) which in this case modifies a field.
    • This can be simply read as "$set" the value of "a" to "$a" converted "$toString".
    • What's really new here, is being able in Mongo 4.2 to reference the document itself when updating it: the new value for "a" is based on the existing value of "$a".
    • Also note "$toString" which is a new aggregation operator introduced in Mongo 4.0.
  • Don't forget { multi: true }, otherwise only the first matching document will be updated.


In case your cast isn't from double to string, you have the choice between different conversion operators introduced in Mongo 4.0 such as $toBool, $toInt, ...

And if there isn't a dedicated converter for your targeted type, you can replace { $toString: "$a" } with a $convert operation: { $convert: { input: "$a", to: 2 } } where the value for to can be found in this table:

db.collection.update(
  { a : { $type: 1 } },
  [{ $set: { a: { $convert: { input: "$a", to: 2 } } } }],
  { multi: true }
)

pandas GroupBy columns with NaN (missing) values

I am not able to add a comment to M. Kiewisch since I do not have enough reputation points (only have 41 but need more than 50 to comment).

Anyway, just want to point out that M. Kiewisch solution does not work as is and may need more tweaking. Consider for example

>>> df = pd.DataFrame({'a': [1, 2, 3, 5], 'b': [4, np.NaN, 6, 4]})
>>> df
   a    b
0  1  4.0
1  2  NaN
2  3  6.0
3  5  4.0
>>> df.groupby(['b']).sum()
     a
b
4.0  6
6.0  3
>>> df.astype(str).groupby(['b']).sum()
      a
b
4.0  15
6.0   3
nan   2

which shows that for group b=4.0, the corresponding value is 15 instead of 6. Here it is just concatenating 1 and 5 as strings instead of adding it as numbers.

Use ASP.NET MVC validation with jquery ajax?

You can do it this way:

(Edit: Considering that you're waiting for a response json with dataType: 'json')

.NET

public JsonResult Edit(EditPostViewModel data)
{
    if(ModelState.IsValid) 
    {
       // Save  
       return Json(new { Ok = true } );
    }

    return Json(new { Ok = false } );
}

JS:

success: function (data) {
    if (data.Ok) {
      alert('success');
    }
    else {
      alert('problem');
    }
},

If you need I can also explain how to do it by returning a error 500, and get the error in the event error (ajax). But in your case this may be an option

Docker and securing passwords

Our team avoids putting credentials in repositories, so that means they're not allowed in Dockerfile. Our best practice within applications is to use creds from environment variables.

We solve for this using docker-compose.

Within docker-compose.yml, you can specify a file that contains the environment variables for the container:

 env_file:
- .env

Make sure to add .env to .gitignore, then set the credentials within the .env file like:

SOME_USERNAME=myUser
SOME_PWD_VAR=myPwd

Store the .env file locally or in a secure location where the rest of the team can grab it.

See: https://docs.docker.com/compose/environment-variables/#/the-env-file

How can I use mySQL replace() to replace strings in multiple records?

This will help you.

UPDATE play_school_data SET title= REPLACE(title, "&#39;", "'") WHERE title = "Elmer&#39;s Parade";

Result:

title = Elmer's Parade

Run chrome in fullscreen mode on Windows

It's very easy.

"your chrome path" -kiosk -fullscreen "your URL"

Example:

"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" -kiosk -fullscreen http://google.com

Close all Chrome sessions first !

To exit: Press ALT-TAB > hold ALT and press X in the windows task. (win10)

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

boolarr.sum(axis=1 or axis=0)

axis = 1 will output number of trues in a row and axis = 0 will count number of trues in columns so

boolarr[[true,true,true],[false,false,true]]
print(boolarr.sum(axis=1))

will be (3,1)

How do I ignore files in Subversion?

  1. open you use JetBrains Product(i.e. Pycharm)
  2. then click the 'commit' button on the top toolbar or use shortcut 'ctrl + k' screenshot_toolbar
  3. on the commit interface, move your unwanted files to another change list as follows. screenshot_commit_change
  4. next time you can only commit default change list.

Drawing an image from a data URL to a canvas

Just to add to the other answers: In case you don't like the onload callback approach, you can "promisify" it like so:

let url = "data:image/gif;base64,R0lGODl...";
let img = new Image();
await new Promise(r => img.onload=r, img.src=url);
// now do something with img

How to copy Docker images from one host to another without using a repository

Transferring a Docker image via SSH, bzipping the content on the fly:

docker save <image> | bzip2 | \
     ssh user@host 'bunzip2 | docker load'

It's also a good idea to put pv in the middle of the pipe to see how the transfer is going:

docker save <image> | bzip2 | pv | \
     ssh user@host 'bunzip2 | docker load'

(More info about pv: home page, man page).

How to initialize private static members in C++?

The class declaration should be in the header file (Or in the source file if not shared).
File: foo.h

class foo
{
    private:
        static int i;
};

But the initialization should be in source file.
File: foo.cpp

int foo::i = 0;

If the initialization is in the header file then each file that includes the header file will have a definition of the static member. Thus during the link phase you will get linker errors as the code to initialize the variable will be defined in multiple source files. The initialisation of the static int i must be done outside of any function.

Note: Matt Curtis: points out that C++ allows the simplification of the above if the static member variable is of const int type (e.g. int, bool, char). You can then declare and initialize the member variable directly inside the class declaration in the header file:

class foo
{
    private:
        static int const i = 42;
};

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

I had a similar problem.

Setting width to "auto" worked fine for me but when the dialog contained a lot of text it made it span the full width of the page, ignoring the maxWidth setting.

Setting maxWidth on create works fine though:

$( ".selector" ).dialog({
  width: "auto",
  // maxWidth: 660, // This won't work
  create: function( event, ui ) {
    // Set maxWidth
    $(this).css("maxWidth", "660px");
  }
});

How to compile makefile using MinGW?

I found a very good example here: https://bigcode.wordpress.com/2016/12/20/compiling-a-very-basic-mingw-windows-hello-world-executable-in-c-with-a-makefile/

It is a simple Hello.c (you can use c++ with g++ instead of gcc) using the MinGW on windows.

The Makefile looking like:

EXECUTABLE = src/Main.cpp

CC = "C:\MinGW\bin\g++.exe"
LDFLAGS = -lgdi32

src = $(wildcard *.cpp)
obj = $(src:.cpp=.o)

all: myprog

myprog: $(obj)
    $(CC) -o $(EXECUTABLE) $^ $(LDFLAGS)

.PHONY: clean
clean:
    del $(obj) $(EXECUTABLE)

Python logging: use milliseconds in time format

A simple expansion that doesn't require the datetime module and isn't handicapped like some other solutions is to use simple string replacement like so:

import logging
import time

class MyFormatter(logging.Formatter):
    def formatTime(self, record, datefmt=None):
        ct = self.converter(record.created)
        if datefmt:
            if "%F" in datefmt:
                msec = "%03d" % record.msecs
                datefmt = datefmt.replace("%F", msec)
            s = time.strftime(datefmt, ct)
        else:
            t = time.strftime("%Y-%m-%d %H:%M:%S", ct)
            s = "%s,%03d" % (t, record.msecs)
        return s

This way a date format can be written however you want, even allowing for region differences, by using %F for milliseconds. For example:

log = logging.getLogger(__name__)
log.setLevel(logging.INFO)

sh = logging.StreamHandler()
log.addHandler(sh)

fm = MyFormatter(fmt='%(asctime)s-%(levelname)s-%(message)s',datefmt='%H:%M:%S.%F')
sh.setFormatter(fm)

log.info("Foo, Bar, Baz")
# 03:26:33.757-INFO-Foo, Bar, Baz

Set value of textarea in jQuery

I think this should work :

$("textarea#ExampleMessage").val(result.exampleMessage);

Refresh Excel VBA Function Results

Public Sub UpdateMyFunctions()
    Dim myRange As Range
    Dim rng As Range

    'Considering The Functions are in Range A1:B10
    Set myRange = ActiveSheet.Range("A1:B10")

    For Each rng In myRange
        rng.Formula = rng.Formula
    Next
End Sub

HTML: How to make a submit button with text + image in it?

You can do this:

HTML code:

    <form action="submit.php" method="get" id="form">        
    <a href="javascript: submitForm()">        
    <img src="save.gif" alt="Save icon"/>        
    <br/>        
    save        
    </a>        
    </form>        

note: you can use and action and method of your choice and Id and any text starting from href="javascript: and ending to ()" but make sure that when I type the same things such as id and some text you type in your replacement in the same places(java script and HTML code).

java script code:

    var form=document.getElementById("form");        
    function submitForm()        
    {        
    form.submit();       
    }         

Writing data into CSV file in C#

Here is another open source library to create CSV file easily, Cinchoo ETL

List<dynamic> objs = new List<dynamic>();

dynamic rec1 = new ExpandoObject();
rec1.Id = 10;
rec1.Name = @"Mark";
rec1.JoinedDate = new DateTime(2001, 2, 2);
rec1.IsActive = true;
rec1.Salary = new ChoCurrency(100000);
objs.Add(rec1);

dynamic rec2 = new ExpandoObject();
rec2.Id = 200;
rec2.Name = "Tom";
rec2.JoinedDate = new DateTime(1990, 10, 23);
rec2.IsActive = false;
rec2.Salary = new ChoCurrency(150000);
objs.Add(rec2);

using (var parser = new ChoCSVWriter("emp.csv").WithFirstLineHeader())
{
    parser.Write(objs);
}

For more information, please read the CodeProject article on usage.

SFTP file transfer using Java JSch

Below code works for me

   public static void sftpsript(String filepath) {

 try {
  String user ="demouser"; // username for remote host
  String password ="demo123"; // password of the remote host

   String host = "demo.net"; // remote host address
  JSch jsch = new JSch();
  Session session = jsch.getSession(user, host);
  session.setPassword(password);
  session.connect();

  ChannelSftp sftpChannel = (ChannelSftp) session.openChannel("sftp");
  sftpChannel.connect();

  sftpChannel.put("I:/demo/myOutFile.txt", "/tmp/QA_Auto/myOutFile.zip");
  sftpChannel.disconnect();
  session.disconnect();
 }catch(Exception ex){
     ex.printStackTrace();
 }
   }

OR using StrictHostKeyChecking as "NO" (security consequences)

public static void sftpsript(String filepath) {

 try {
  String user ="demouser"; // username for remote host
  String password ="demo123"; // password of the remote host

   String host = "demo.net"; // remote host address
  JSch jsch = new JSch();
   Session session = jsch.getSession(user, host, 22);
   Properties config = new Properties();
   config.put("StrictHostKeyChecking", "no");
   session.setConfig(config);;
   session.setPassword(password);
   System.out.println("user=="+user+"\n host=="+host);
   session.connect();

  ChannelSftp sftpChannel = (ChannelSftp) session.openChannel("sftp");
  sftpChannel.connect();

  sftpChannel.put("I:/demo/myOutFile.txt", "/tmp/QA_Auto/myOutFile.zip");
  sftpChannel.disconnect();
  session.disconnect();
 }catch(Exception ex){
     ex.printStackTrace();
 }
   }

Displaying all table names in php from MySQL database

//list_tables means database all table

$tables = $this->db->list_tables();
foreach ($tables as $table)
{
  echo $table;
}

How to use regex in file find

Use -regex not -name, and be aware that the regex matches against what find would print, e.g. "/home/test/test.log" not "test.log"

Phone validation regex

Try this

\+?\(?([0-9]{3})\)?[-.]?\(?([0-9]{3})\)?[-.]?\(?([0-9]{4})\)?

It matches the following cases

  • +123-(456)-(7890)
  • +123.(456).(7890)
  • +(123).(456).(7890)
  • +(123)-(456)-(7890)
  • +123(456)(7890)
  • +(123)(456)(7890)
  • 123-(456)-(7890)
  • 123.(456).(7890)
  • (123).(456).(7890)
  • (123)-(456)-(7890)
  • 123(456)(7890)
  • (123)(456)(7890)

For further explanation on the pattern CLICKME

Remove specific characters from a string in Javascript

Honestly I think this probably the most concise and least confusing, but maybe that is just me:

str = "F0123456";
str.replace("f0", "");

Dont even go the regular expression route and simply do a straight replace.

Upload a file to Amazon S3 with NodeJS

var express = require('express')

app = module.exports = express();
var secureServer = require('http').createServer(app);
secureServer.listen(3001);

var aws = require('aws-sdk')
var multer = require('multer')
var multerS3 = require('multer-s3')

    aws.config.update({
    secretAccessKey: "XXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
    accessKeyId: "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
    region: 'us-east-1'
    });
    s3 = new aws.S3();

   var upload = multer({
   storage: multerS3({
    s3: s3,
    dirname: "uploads",
    bucket: "Your bucket name",
    key: function (req, file, cb) {
        console.log(file);
        cb(null, "uploads/profile_images/u_" + Date.now() + ".jpg"); //use  
     Date.now() for unique file keys
    }
  })
   });

 app.post('/upload', upload.single('photos'), function(req, res, next) {

 console.log('Successfully uploaded ', req.file)

 res.send('Successfully uploaded ' + req.file.length + ' files!')

})

What does it mean when an HTTP request returns status code 0?

As detailed by this answer on this page, a status code of 0 means the request failed for some reason, and a javascript library interpreted the fail as a status code of 0.

To test this you can do either of the following:

1) Use this chrome extension, Requestly to redirect your url from the https version of your url to the http version, as this will cause a mixed content security error, and ultimately generate a status code of 0. The advantage of this approach is that you don't have to change your app at all, and you can simply "rewrite" your url using this extension.

2) Change the code of your app to optionally make your endpoint redirect to the http version of your url instead of the https version (or vice versa). If you do this, the request will fail with status code 0.

How to convert a string Date to long millseconds

Easiest way is used the Date Using Date() and getTime()

    Date dte=new Date();
    long milliSeconds = dte.getTime();
    String strLong = Long.toString(milliSeconds);
    System.out.println(milliSeconds)

Can you call ko.applyBindings to bind a partial view?

I've managed to bind a custom model to an element at runtime. The code is here: http://jsfiddle.net/ZiglioNZ/tzD4T/457/

The interesting bit is that I apply the data-bind attribute to an element I didn't define:

    var handle = slider.slider().find(".ui-slider-handle").first();
    $(handle).attr("data-bind", "tooltip: viewModel.value");
    ko.applyBindings(viewModel.value, $(handle)[0]);

Best database field type for a URL

varchar(max) for SQLServer2005

varchar(65535) for MySQL 5.0.3 and later

This will allocate storage as need and shouldn't affect performance.

How to get these two divs side-by-side?

Best that works for me:

 .left{
   width:140px;
   float:left;
   height:100%;
 }

 .right{
   margin-left:140px;
 }


http://jsfiddle.net/jiantongc/7uVNN/

Get the cell value of a GridView row

Expanding on Dennis R answer above ... This will get the value based on the Heading Text (so you don't need to know what column...especially if its dynamic changing).

Example setting a session variable on SelectedIndexChange.

    protected void gvCustomer_SelectedIndexChanged(object sender, EventArgs e)
    {
        int iCustomerID = Convert.ToInt32(Library.gvGetVal(gvCustomer, "CustomerID"));
        Session[SSS.CustomerID] = iCustomerID;
    }

public class Library
{
    public static string gvGetVal(GridView gvGrid, string sHeaderText)
    {
        string sRetVal = string.Empty;
        if (gvGrid.Rows.Count > 0)
        {
            if (gvGrid.SelectedRow != null)
            {
                GridViewRow row = gvGrid.SelectedRow;
                int iCol = gvGetColumn(gvGrid, sHeaderText);
                if (iCol > -1)
                    sRetVal = row.Cells[iCol].Text;
            }
        }
        return sRetVal;
    }

    private static int gvGetColumn(GridView gvGrid, string sHeaderText)
    {
        int iRetVal = -1;
        for (int i = 0; i < gvGrid.Columns.Count; i++)
        {
            if (gvGrid.Columns[i].HeaderText.ToLower().Trim() == sHeaderText.ToLower().Trim())
            {
                iRetVal = i;
            }
        }
        return iRetVal;
    }
}

Using an array as needles in strpos

This expression searches for all letters:

count(array_filter( 
    array_map("strpos", array_fill(0, count($letters), $str), $letters),
"is_int")) == count($letters)

How to serialize Object to JSON?

After JAVAEE8 published , now you can use the new JAVAEE API JSON-B (JSR367)

Maven dependency :

<dependency>
    <groupId>javax.json.bind</groupId>
    <artifactId>javax.json.bind-api</artifactId>
    <version>1.0</version>
</dependency>

<dependency>
    <groupId>org.eclipse</groupId>
    <artifactId>yasson</artifactId>
    <version>1.0</version>
</dependency>

<dependency>
    <groupId>org.glassfish</groupId>
    <artifactId>javax.json</artifactId>
    <version>1.1</version>
</dependency>

Here is some code snapshot :

Jsonb jsonb = JsonbBuilder.create();
// Two important API : toJson fromJson
String result = jsonb.toJson(listaDePontos);

JSON-P is also updated to 1.1 and more easy to use. JSON-P 1.1 (JSR374)

Maven dependency :

<dependency>
    <groupId>javax.json</groupId>
    <artifactId>javax.json-api</artifactId>
    <version>1.1</version>
</dependency>

<dependency>
    <groupId>org.glassfish</groupId>
    <artifactId>javax.json</artifactId>
    <version>1.1</version>
</dependency>

Here is the runnable code snapshot :

String data = "{\"name\":\"Json\","
                + "\"age\": 29,"
                + " \"phoneNumber\": [10000,12000],"
                + "\"address\": \"test\"}";
        JsonObject original = Json.createReader(new StringReader(data)).readObject();
        /**getValue*/
        JsonPointer pAge = Json.createPointer("/age");
        JsonValue v = pAge.getValue(original);
        System.out.println("age is " + v.toString());
        JsonPointer pPhone = Json.createPointer("/phoneNumber/1");
        System.out.println("phoneNumber 2 is " + pPhone.getValue(original).toString());

Difference between two dates in years, months, days in JavaScript

With dayjs we did it in that way:

export const getAgeDetails = (oldDate: dayjs.Dayjs, newDate: dayjs.Dayjs) => {
  const years = newDate.diff(oldDate, 'year');
  const months = newDate.diff(oldDate, 'month') - years * 12;
  const days = newDate.diff(oldDate.add(years, 'year').add(months, 'month'), 'day');

  return {
    years,
    months,
    days,
    allDays: newDate.diff(oldDate, 'day'),
  };
};

It calculates it perfectly including leap years and different month amount of days.

JSP : JSTL's <c:out> tag

c:out also has an attribute for assigning a default value if the value of person.name happens to be null.

Source: out (TLDDoc Generated Documentation)

Error - is not marked as serializable

If you store an object in session state, that object must be serializable.

http://www.hpenterprisesecurity.com/vulncat/en/vulncat/dotnet/asp_dotnet_bad_practices_non_serializable_object_stored_in_session.html


edit:

In order for the session to be serialized correctly, all objects the application stores as session attributes must declare the [Serializable] attribute. Additionally, if the object requires custom serialization methods, it must also implement the ISerializable interface.

https://vulncat.hpefod.com/en/detail?id=desc.structural.dotnet.asp_dotnet_bad_practices_non_serializable_object_stored_in_session#C%23%2fVB.NET%2fASP.NET

How to install a specific JDK on Mac OS X?

If you installed brew, cmd below will be helpful:

brew cask install java

List all sequences in a Postgres db 8.1 with SQL

This statement lists the table and column that is associated with each sequence:

Code:

    SELECT t.relname as related_table, 
           a.attname as related_column,
           s.relname as sequence_name
    FROM pg_class s 
      JOIN pg_depend d ON d.objid = s.oid 
      JOIN pg_class t ON d.objid = s.oid AND d.refobjid = t.oid 
      JOIN pg_attribute a ON (d.refobjid, d.refobjsubid) = (a.attrelid, a.attnum)
      JOIN pg_namespace n ON n.oid = s.relnamespace 
    WHERE s.relkind     = 'S' 

  AND n.nspname     = 'public'

more see here link to answer

call javascript function on hyperlink click

If you do not wait for the page to be loaded you will not be able to select the element by id. This solution should work for anyone having trouble getting the code to execute

<script type="text/javascript">
window.onload = function() {
    document.getElementById("delete").onclick = function() {myFunction()};

    function myFunction() {
        //your code goes here
        alert('Alert message here');
    }
};
</script>

<a href='#' id='delete'>Delete Document</a>

How to set cursor position in EditText?

some time edit text cursor donot comes at particular position is if we directly use editText.setSelection(position); . In that case you can try

editText.post(new Runnable() {
                @Override
                public void run() {
                    editText.setSelection(string.length());
                }
            });

Scaling a System.Drawing.Bitmap to a given size while maintaining aspect ratio

Target parameters:

float width = 1024;
float height = 768;
var brush = new SolidBrush(Color.Black);

Your original file:

var image = new Bitmap(file);

Target sizing (scale factor):

float scale = Math.Min(width / image.Width, height / image.Height);

The resize including brushing canvas first:

var bmp = new Bitmap((int)width, (int)height);
var graph = Graphics.FromImage(bmp);

// uncomment for higher quality output
//graph.InterpolationMode = InterpolationMode.High;
//graph.CompositingQuality = CompositingQuality.HighQuality;
//graph.SmoothingMode = SmoothingMode.AntiAlias;

var scaleWidth = (int)(image.Width * scale);
var scaleHeight = (int)(image.Height * scale);

graph.FillRectangle(brush, new RectangleF(0, 0, width, height));
graph.DrawImage(image, ((int)width - scaleWidth)/2, ((int)height - scaleHeight)/2, scaleWidth, scaleHeight);

And don't forget to do a bmp.Save(filename) to save the resulting file.

How to source virtualenv activate in a Bash script

You can also do this using a subshell to better contain your usage - here's a practical example:

#!/bin/bash

commandA --args

# Run commandB in a subshell and collect its output in $VAR
# NOTE
#  - PATH is only modified as an example
#  - output beyond a single value may not be captured without quoting
#  - it is important to discard (or separate) virtualenv activation stdout
#    if the stdout of commandB is to be captured
#
VAR=$(
    PATH="/opt/bin/foo:$PATH"
    . /path/to/activate > /dev/null  # activate virtualenv
    commandB  # tool from /opt/bin/ which requires virtualenv
)

# Use the output from commandB later
commandC "$VAR"

This style is especially helpful when

  • a different version of commandA or commandC exists under /opt/bin
  • commandB exists in the system PATH or is very common
  • these commands fail under the virtualenv
  • one needs a variety of different virtualenvs

Modal width (increase)

If you use Sass,

according to the documentation you can customize your default values.

In your case, you can easily override the variable named $modal-lg in your _custom.scss file.

What are the most useful Intellij IDEA keyboard shortcuts?

Ctrl + N : Open class.

Alt + F7 : Find usages.

RestTemplate: How to send URL and query parameters together

String url = "http://test.com/Services/rest/{id}/Identifier";
Map<String, String> params = new HashMap<String, String>();
params.put("id", "1234");
URI uri = UriComponentsBuilder.fromUriString(url)
        .buildAndExpand(params)
        .toUri();
uri = UriComponentsBuilder
        .fromUri(uri)
        .queryParam("name", "myName")
        .build()
        .toUri();
restTemplate.exchange(uri , HttpMethod.PUT, requestEntity, class_p);

The safe way is to expand the path variables first, and then add the query parameters:

For me this resulted in duplicated encoding, e.g. a space was decoded to %2520 (space -> %20 -> %25).

I solved it by:

String url = "http://test.com/Services/rest/{id}/Identifier";
Map<String, String> params = new HashMap<String, String>();
params.put("id", "1234");
UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.fromUriString(url);
uriComponentsBuilder.uriVariables(params);
Uri uri = uriComponentsBuilder.queryParam("name", "myName");
        .build()
        .toUri();
restTemplate.exchange(uri , HttpMethod.PUT, requestEntity, class_p);

Essentially I am using uriComponentsBuilder.uriVariables(params); to add path parameters. The documentation says:

... In contrast to UriComponents.expand(Map) or buildAndExpand(Map), this method is useful when you need to supply URI variables without building the UriComponents instance just yet, or perhaps pre-expand some shared default values such as host and port. ...

Source: https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/util/UriComponentsBuilder.html#uriVariables-java.util.Map-

Reset select value to default

With jquery :

$("#reset").on("click", function() {
    $('#my_select').val($('#my_select').find('option[selected="selected"]').val());
}

How to change sender name (not email address) when using the linux mail command for autosending mail?

It depends on what sender address you are talking about. The sender address visble in the recipients mailprogramm is extracted from the "From:" Header. which can probably easily be set from your program.

If you are talking about the SMTP envelope sender address, you can pass the -f argument to the sendmail binary. Depending on the server configuration you may not be allowed to do that with the apache user.

from the sendmail manpage :

   -f <address>
                 This  option  sets  the  address  of the envelope sender of a
                 locally-generated message (also known as  the  return  path).
                 The  option  can normally be used only by a trusted user, but
                 untrusted_set_sender can be set to allow untrusted  users  to
                 use it. [...]

How often should Oracle database statistics be run?

In the case of a data warehouse-type system you can consider collecting no statistics at all, and relying on dynamic sampling (setting optimizer_dynamic_sampling to level 2 or above).

Why does range(start, end) not include end?

It works well in combination with zero-based indexing and len(). For example, if you have 10 items in a list x, they are numbered 0-9. range(len(x)) gives you 0-9.

Of course, people will tell you it's more Pythonic to do for item in x or for index, item in enumerate(x) rather than for i in range(len(x)).

Slicing works that way too: foo[1:4] is items 1-3 of foo (keeping in mind that item 1 is actually the second item due to the zero-based indexing). For consistency, they should both work the same way.

I think of it as: "the first number you want, followed by the first number you don't want." If you want 1-10, the first number you don't want is 11, so it's range(1, 11).

If it becomes cumbersome in a particular application, it's easy enough to write a little helper function that adds 1 to the ending index and calls range().

SQL Server stored procedure parameters

You are parsing wrong parameter combination.here you passing @TaskName = and @ID instead of @TaskName = .SP need only one parameter.

Error: No default engine was specified and no extension was provided

The res.render stuff will throw an error if you're not using a view engine.

If you just want to serve json replace the res.render('error', { error: err }); lines in your code with:

res.json({ error: err })

PS: People usually also have message in the returned object:

res.status(err.status || 500);
res.json({
  message: err.message,
  error: err
});

IE8 crashes when loading website - res://ieframe.dll/acr_error.htm

It may be a background image on the body. Check this link for more informations : http://drupal.org/node/1323608

How to handle Uncaught (in promise) DOMException: The play() request was interrupted by a call to pause()

For Chrome they changed autoplay policy, so you can read about here:

var promise = document.querySelector('audio').play();

if (promise !== undefined) {
    promise.then(_ => {
        // Autoplay started!
    }).catch(error => {
        // Autoplay was prevented.
        // Show a "Play" button so that user can start playback.
    });
}

Incorrect integer value: '' for column 'id' at row 1

To let MySql generate sequence numbers for an AUTO_INCREMENT field you have three options:

  1. specify list a column list and omit your auto_incremented column from it as njk suggested. That would be the best approach. See comments.
  2. explicitly assign NULL
  3. explicitly assign 0

3.6.9. Using AUTO_INCREMENT:

...No value was specified for the AUTO_INCREMENT column, so MySQL assigned sequence numbers automatically. You can also explicitly assign NULL or 0 to the column to generate sequence numbers.

These three statements will produce the same result:

$insertQuery = "INSERT INTO workorders (`priority`, `request_type`) VALUES('$priority', '$requestType', ...)";
$insertQuery = "INSERT INTO workorders VALUES(NULL, '$priority', ...)";
$insertQuery = "INSERT INTO workorders VALUES(0, '$priority', ...";

How to recursively delete an entire directory with PowerShell 2.0?

When deleting files recursively using a simple Remove-Item "folder" -Recurse I sometimes see an intermittent error : [folder] cannot be removed because it is not empty.

This answer attempts to prevent that error by individually deleting the files.

function Get-Tree($Path,$Include='*') { 
    @(Get-Item $Path -Include $Include -Force) + 
        (Get-ChildItem $Path -Recurse -Include $Include -Force) | 
        sort pspath -Descending -unique
} 

function Remove-Tree($Path,$Include='*') { 
    Get-Tree $Path $Include | Remove-Item -force -recurse
} 

Remove-Tree some_dir

An important detail is the sorting of all the items with pspath -Descending so that the leaves are deleted before the roots. The sorting is done on the pspath parameter since that has more chance of working for providers other than the file system. The -Include parameter is just a convenience if you want to filter the items to delete.

It's split into two functions since I find it useful to see what I'm about to delete by running

Get-Tree some_dir | select fullname

Use PHP composer to clone git repo

At the time of writing in 2013, this was one way to do it. Composer has added support for better ways: See @igorw 's answer

DO YOU HAVE A REPOSITORY?

Git, Mercurial and SVN is supported by Composer.

DO YOU HAVE WRITE ACCESS TO THE REPOSITORY?

Yes?

DOES THE REPOSITORY HAVE A composer.json FILE

If you have a repository you can write to: Add a composer.json file, or fix the existing one, and DON'T use the solution below.

Go to @igorw 's answer

ONLY USE THIS IF YOU DON'T HAVE A REPOSITORY
OR IF THE REPOSITORY DOES NOT HAVE A composer.json AND YOU CANNOT ADD IT

This will override everything that Composer may be able to read from the original repository's composer.json, including the dependencies of the package and the autoloading.

Using the package type will transfer the burden of correctly defining everything onto you. The easier way is to have a composer.json file in the repository, and just use it.

This solution really only is for the rare cases where you have an abandoned ZIP download that you cannot alter, or a repository you can only read, but it isn't maintained anymore.

"repositories": [
    {
        "type":"package",
        "package": {
          "name": "l3pp4rd/doctrine-extensions",
          "version":"master",
          "source": {
              "url": "https://github.com/l3pp4rd/DoctrineExtensions.git",
              "type": "git",
              "reference":"master"
            }
        }
    }
],
"require": {
    "l3pp4rd/doctrine-extensions": "master"
}

Shell command to tar directory excluding certain files/folders

Possible redundant answer but since I found it useful, here it is:

While a FreeBSD root (i.e. using csh) I wanted to copy my whole root filesystem to /mnt but without /usr and (obviously) /mnt. This is what worked (I am at /):

tar --exclude ./usr --exclude ./mnt --create --file - . (cd /mnt && tar xvd -)

My whole point is that it was necessary (by putting the ./) to specify to tar that the excluded directories where part of the greater directory being copied.

My €0.02

assign multiple variables to the same value in Javascript

The original variables you listed can be declared and assigned to the same value in a short line of code using destructuring assignment. The keywords let, const, and var can all be used for this type of assignment.

let [moveUp, moveDown, moveLeft, moveRight, mouseDown, touchDown] = Array(6).fill(false);

nodejs - first argument must be a string or Buffer - when using response.write with http.request

Request takes a callback method, its async! So I am assuming, by the time the callback is executed the res.end() might get called. Try closing the request within the callback.

Read data from a text file using Java

In Java 8 you could easily turn your text file into a List of Strings with streams by using Files.lines and collect:

private List<String> loadFile() {
    URI uri = null;
    try {
        uri = ClassLoader.getSystemResource("example.txt").toURI();
    } catch (URISyntaxException e) {
        LOGGER.error("Failed to load file.", e);
    }
    List<String> list = null;
    try (Stream<String> lines = Files.lines(Paths.get(uri))) {
        list = lines.collect(Collectors.toList());
    } catch (IOException e) {
        LOGGER.error("Failed to load file.", e);
    }
    return list;
}

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

Named instances?

URL: jdbc:sqlserver://[serverName][\instanceName][:portNumber][;property=value]

Note: backward slash

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

In SQL Server 2012 you can use EOMONTH (Transact-SQL) to get the last day of the month and then you can use DAY (Transact-SQL) to get the number of days in the month.

DECLARE @ADate DATETIME

SET @ADate = GETDATE()

SELECT DAY(EOMONTH(@ADate)) AS DaysInMonth

How to connect from windows command prompt to mysql command line

The cd in your question is invalid (quoting it here because you've removed it once, and it was there when this answer was posted):

cd CD:\MYSQL\bin\

You can't cd to CD:\ anything, because CD:\ isn't a valid directory in Windows. CD: would indicate a drive, except that drives are restricted to a single letter between A and Z.

If your \MYSQL\BIN is on drive C:, then your commands need to be:

C:\>cd \MYSQL\Bin
C:\MYSQL\Bin>mysql -u root -p admin

If you're not already on C: (which you'll know by looking at the prompt in the cmd window), or your MySQL folder is on another drive (for instance, D:), change to that drive too:

C:\> cd /d D:\MYSQL\Bin
D:\MYSQL\Bin>mysql -u root -p admin

The .exe after mysql is optional, since .exe is an executable extension on Windows. If you type mysql, Windows will automatically look for an executable file with that name and run it if it finds it.

Note that in both my examples of running mysql, there are no = signs. You should just use -p with no password, and wait to be prompted for it instead.

In Powershell what is the idiomatic way of converting a string to an int?

Building up on Shavy Levy answer:

[bool]($var -as [int])

Because $null is evaluated to false (in bool), this statement Will give you true or false depending if the casting succeeds or not.

Android SQLite SELECT Query

Try trimming the string to make sure there is no extra white space:

Cursor c = db.rawQuery("SELECT * FROM tbl1 WHERE TRIM(name) = '"+name.trim()+"'", null);

Also use c.moveToFirst() like @thinksteep mentioned.


This is a complete code for select statements.

SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery("SELECT column1,column2,column3 FROM table ", null);
if (c.moveToFirst()){
    do {
        // Passing values 
        String column1 = c.getString(0);
        String column2 = c.getString(1);
        String column3 = c.getString(2); 
        // Do something Here with values
    } while(c.moveToNext());
}
c.close();
db.close();

Lumen: get URL parameter in a Blade view

As per official 5.8 docs:

The request() function returns the current request instance or obtains an input item:

$request = request();

$value = request('key', $default);

Docs

Can I use tcpdump to get HTTP requests, response header and response body?

Here is another choice: Chaosreader

So I need to debug an application which posts xml to a 3rd party application. I found a brilliant little perl script which does all the hard work – you just chuck it a tcpdump output file, and it does all the manipulation and outputs everything you need...

The script is called chaosreader0.94. See http://www.darknet.org.uk/2007/11/chaosreader-trace-tcpudp-sessions-from-tcpdump/

It worked like a treat, I did the following:

tcpdump host www.blah.com -s 9000 -w outputfile; perl chaosreader0.94 outputfile

Converting between strings and ArrayBuffers

The "native" binary string that atob() returns is a 1-byte-per-character Array.

So we shouldn't store 2 byte into a character.

var arrayBufferToString = function(buffer) {
  return String.fromCharCode.apply(null, new Uint8Array(buffer));
}

var stringToArrayBuffer = function(str) {
  return (new Uint8Array([].map.call(str,function(x){return x.charCodeAt(0)}))).buffer;
}

Looping through all the properties of object php

Here is another way to express the object property.

foreach ($obj as $key=>$value) {
    echo "$key => $obj[$key]\n";
}

Difference between "@id/" and "@+id/" in Android

From the Developer Guide:

android:id="@+id/my_button"

The at-symbol (@) at the beginning of the string indicates that the XML parser should parse and expand the rest of the ID string and identify it as an ID resource. The plus-symbol (+) means that this is a new resource name that must be created and added to our resources (in the R.java file). There are a number of other ID resources that are offered by the Android framework. When referencing an Android resource ID, you do not need the plus-symbol, but must add the android package namespace, like so:

android:id="@android:id/empty"

libxml/tree.h no such file or directory

As of Mavericks (OS X 10.9) the /usr/include directory is gone. Half of the answers here are obsolete, as the application will not compile until you sort out the include directory.

I solved the problem creating a symbolic link to MacOSX SDK in terminal, using the following command:

sudo ln -s /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.9.sdk/usr/include /usr/include

The application now compiles again.

How can I remove a character from a string using JavaScript?

A simple functional javascript way would be

mystring = mystring.split('/r').join('/')

simple, fast, it replace globally and no need for functions or prototypes

Not connecting to SQL Server over VPN

On a default instance, SQL Server listens on TCP/1433 by default. This can be changed. On a named instance, unless configured differently, SQL Server listens on a dynamic TCP port. What that means is should SQL Server discover that the port is in use, it will pick another TCP port. How clients usually find the right port in the case of a named instance is by talking to the SQL Server Listener Service/SQL Browser. That listens on UDP/1434 and cannot be changed. If you have a named instance, you can configure a static port and if you have a need to use Kerberos authentication/delegation, you should.

What you'll need to determine is what port your SQL Server is listening on. Then you'll need to get with your networking/security folks to determine if they allow communication to that port via VPN. If they are, as indicated, check your firewall settings. Some systems have multiple firewalls (my laptop is an example). If so, you'll need to check all the firewalls on your system.

If all of those are correct, verify the server doesn't have an IPSEC policy that restricts access to the SQL Server port via IP address. That also could result in you being blocked.

How to use EditText onTextChanged event when I press the number?

To change the text;

multipleLine.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            MainActivity.myArray.set(pickId,String.valueOf(s));
            MainActivity.myAdapt.notifyDataSetChanged();
        }

        @Override
        public void afterTextChanged(Editable s) {

        }

Get Current date & time with [NSDate date]

NSLocale* currentLocale = [NSLocale currentLocale];
[[NSDate date] descriptionWithLocale:currentLocale];  

or use

NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init]; 
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
// or @"yyyy-MM-dd hh:mm:ss a" if you prefer the time with AM/PM 
NSLog(@"%@",[dateFormatter stringFromDate:[NSDate date]]);

How to get first and last element in an array in java?

Check this

double[] myarray = ...;
System.out.println(myarray[myarray.length-1]); //last
System.out.println(myarray[0]); //first