Programs & Examples On #Vendors

Managing jQuery plugin dependency in webpack

This works for me on the webpack.config.js

    new webpack.ProvidePlugin({
        $: 'jquery',
        jQuery: 'jquery',
        'window.jQuery': 'jquery'
    }),

in another javascript or into HTML add:

global.jQuery = require('jquery');

Redirect to external URL with return in laravel

If you're using InertiaJS, the away() approach won't work as seen on the inertiaJS github, they are discussing the best way to create a "external redirect" on inertiaJS, the solution for now is return a 409 status with X-Inertia-Location header informing the url, like this:

return response('', 409)
            ->header('X-Inertia-Location', $paymentLink);

Where paymentLink is the link you want to send the user to.

SOURCE: https://github.com/inertiajs/inertia-laravel/issues/57#issuecomment-570581851

Composer Update Laravel

When you run composer update, composer generates a file called composer.lock which lists all your packages and the currently installed versions. This allows you to later run composer install, which will install the packages listed in that file, recreating the environment that you were last using.

It appears from your log that some of the versions of packages that are listed in your composer.lock file are no longer available. Thus, when you run composer install, it complains and fails. This is usually no big deal - just run composer update and it will attempt to build a set of packages that work together and write a new composer.lock file.

However, you're running into a different problem. It appears that, in your composer.json file, the original developer has added some pre- or post- update actions that are failing, specifically a php artisan migrate command. This can be avoided by running the following: composer update --no-scripts

This will run the composer update but will skip over the scripts added to the file. You should be able to successfully run the update this way.

However, this does not solve the problem long-term. There are two problems:

  1. A migration is for database changes, not random stuff like compiling assets. Go through the migrations and remove that code from there.

  2. Assets should not be compiled each time you run composer update. Remove that step from the composer.json file.

From what I've read, best practice seems to be compiling assets on an as-needed basis during development (ie. when you're making changes to your LESS files - ideally using a tool like gulp.js) and before deployment.

Sending JSON object to Web API

Try this:

jquery

    $('#save-source').click(function (e) {
        e.preventDefault();
        var source = {
            'ID': 0,
            //'ProductID': $('#ID').val(),
            'PartNumber': $('#part-number').val(),
            //'VendorID': $('#Vendors').val()
        }
        $.ajax({
            type: "POST",
            dataType: "json",
            url: "/api/PartSourceAPI",
            data: source,
            success: function (data) {
                alert(data);
            },
            error: function (error) {
                jsonValue = jQuery.parseJSON(error.responseText);
                //jError('An error has occurred while saving the new part source: ' + jsonValue, { TimeShown: 3000 });
            }
        });
    });

Controller

    public string Post(PartSourceModel model)
    {
        return model.PartNumber;
    }

View

<label>Part Number</label>
<input type="text" id="part-number" name="part-number" />

<input type="submit" id="save-source" name="save-source" value="Add" />

Now when you click 'Add' after you fill out the text box, the controller will spit back out what you wrote in the PartNumber box in an alert.

Query error with ambiguous column name in SQL

This happens because there are fields with the same name in more than one table, in the query, because of the joins, so you should reference the fields differently, giving names (aliases) to the tables.

Jackson - How to process (deserialize) nested JSON?

I'm quite late to the party, but one approach is to use a static inner class to unwrap values:

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

class Scratch {
    private final String aString;
    private final String bString;
    private final String cString;
    private final static String jsonString;

    static {
        jsonString = "{\n" +
                "  \"wrap\" : {\n" +
                "    \"A\": \"foo\",\n" +
                "    \"B\": \"bar\",\n" +
                "    \"C\": \"baz\"\n" +
                "  }\n" +
                "}";
    }

    @JsonCreator
    Scratch(@JsonProperty("A") String aString,
            @JsonProperty("B") String bString,
            @JsonProperty("C") String cString) {
        this.aString = aString;
        this.bString = bString;
        this.cString = cString;
    }

    @Override
    public String toString() {
        return "Scratch{" +
                "aString='" + aString + '\'' +
                ", bString='" + bString + '\'' +
                ", cString='" + cString + '\'' +
                '}';
    }

    public static class JsonDeserializer {
        private final Scratch scratch;

        @JsonCreator
        public JsonDeserializer(@JsonProperty("wrap") Scratch scratch) {
            this.scratch = scratch;
        }

        public Scratch getScratch() {
            return scratch;
        }
    }

    public static void main(String[] args) throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();
        Scratch scratch = objectMapper.readValue(jsonString, Scratch.JsonDeserializer.class).getScratch();
        System.out.println(scratch.toString());
    }
}

However, it's probably easier to use objectMapper.configure(SerializationConfig.Feature.UNWRAP_ROOT_VALUE, true); in conjunction with @JsonRootName("aName"), as pointed out by pb2q

LDAP root query syntax to search more than one specific OU

The answer is NO you can't. Why?

Because the LDAP standard describes a LDAP-SEARCH as kind of function with 4 parameters:

  1. The node where the search should begin, which is a Distinguish Name (DN)
  2. The attributes you want to be brought back
  3. The depth of the search (base, one-level, subtree)
  4. The filter

You are interested in the filter. You've got a summary here (it's provided by Microsoft for Active Directory, it's from a standard). The filter is composed, in a boolean way, by expression of the type Attribute Operator Value.

So the filter you give does not mean anything.

On the theoretical point of view there is ExtensibleMatch that allows buildind filters on the DN path, but it's not supported by Active Directory.

As far as I know, you have to use an attribute in AD to make the distinction for users in the two OUs.

It can be any existing discriminator attribute, or, for example the attribute called OU which is inherited from organizationalPerson class. you can set it (it's not automatic, and will not be maintained if you move the users) with "staff" for some users and "vendors" for others and them use the filter:

(&(objectCategory=person)(|(ou=staff)(ou=vendors)))

How to determine if Javascript array contains an object with an attribute that equals a given value?

var without2 = (arr, args) => arr.filter(v => v.id !== args.id); Example:

without2([{id:1},{id:1},{id:2}],{id:2})

Result: without2([{id:1},{id:1},{id:2}],{id:2})

Fastest way to count exact number of rows in a very large table?

I use

select /*+ parallel(a) */  count(1) from table_name a;

How to implement the factory method pattern in C++ correctly

extern std::pair<std::string_view, Base*(*)()> const factories[2];

decltype(factories) factories{
  {"blah", []() -> Base*{return new Blah;}},
  {"foo", []() -> Base*{return new Foo;}}
};

How to do sed like text replace with python?

Cecil Curry has a great answer, however his answer only works for multiline regular expressions. Multiline regular expressions are more rarely used, but they are handy sometimes.

Here is an improvement upon his sed_inplace function that allows it to function with multiline regular expressions if asked to do so.

WARNING: In multiline mode, it will read the entire file in, and then perform the regular expression substitution, so you'll only want to use this mode on small-ish files - don't try to run this on gigabyte-sized files when running in multiline mode.

import re, shutil, tempfile

def sed_inplace(filename, pattern, repl, multiline = False):
    '''
    Perform the pure-Python equivalent of in-place `sed` substitution: e.g.,
    `sed -i -e 's/'${pattern}'/'${repl}' "${filename}"`.
    '''
    re_flags = 0
    if multiline:
        re_flags = re.M

    # For efficiency, precompile the passed regular expression.
    pattern_compiled = re.compile(pattern, re_flags)

    # For portability, NamedTemporaryFile() defaults to mode "w+b" (i.e., binary
    # writing with updating). This is usually a good thing. In this case,
    # however, binary writing imposes non-trivial encoding constraints trivially
    # resolved by switching to text writing. Let's do that.
    with tempfile.NamedTemporaryFile(mode='w', delete=False) as tmp_file:
        with open(filename) as src_file:
            if multiline:
                content = src_file.read()
                tmp_file.write(pattern_compiled.sub(repl, content))
            else:
                for line in src_file:
                    tmp_file.write(pattern_compiled.sub(repl, line))

    # Overwrite the original file with the munged temporary file in a
    # manner preserving file attributes (e.g., permissions).
    shutil.copystat(filename, tmp_file.name)
    shutil.move(tmp_file.name, filename)

from os.path import expanduser
sed_inplace('%s/.gitconfig' % expanduser("~"), r'^(\[user\]$\n[ \t]*name = ).*$(\n[ \t]*email = ).*', r'\1John Doe\[email protected]', multiline=True)

Random / noise functions for GLSL

A straight, jagged version of 1d Perlin, essentially a random lfo zigzag.

half  rn(float xx){         
    half x0=floor(xx);
    half x1=x0+1;
    half v0 = frac(sin (x0*.014686)*31718.927+x0);
    half v1 = frac(sin (x1*.014686)*31718.927+x1);          

    return (v0*(1-frac(xx))+v1*(frac(xx)))*2-1*sin(xx);
}

I also have found 1-2-3-4d perlin noise on shadertoy owner inigo quilez perlin tutorial website, and voronoi and so forth, he has full fast implementations and codes for them.

Why aren't variable-length arrays part of the C++ standard?

I have a solution that actually worked for me. I did not want to allocate memory because of fragmentation on a routine that needed to run many times. The answer is extremely dangerous, so use it at your own risk, but it takes advantage of assembly to reserve space on the stack. My example below uses a character array (obviously other sized variable would require more memory).

void varTest(int iSz)
{
    char *varArray;
    __asm {
        sub esp, iSz       // Create space on the stack for the variable array here
        mov varArray, esp  // save the end of it to our pointer
    }

    // Use the array called varArray here...  

    __asm {
        add esp, iSz       // Variable array is no longer accessible after this point
    } 
}

The dangers here are many but I'll explain a few: 1. Changing the variable size half way through would kill the stack position 2. Overstepping the array bounds would destroy other variables and possible code 3. This does not work in a 64 bit build... need different assembly for that one (but a macro might solve that problem). 4. Compiler specific (may have trouble moving between compilers). I haven't tried so I really don't know.

Difference between an API and SDK

How about... It's like if you wanted to install a home theatre system in your house. Using an API is like getting all the wires, screws, bits, and pieces. The possibilities are endless (constrained only by the pieces you receive), but sometimes overwhelming. An SDK is like getting a kit. You still have to put it together, but it's more like getting pre-cut pieces and instructions for an IKEA bookshelf than a box of screws.

Linq to Sql: Multiple left outer joins

In VB.NET using Function,

Dim query = From order In dc.Orders
            From vendor In 
            dc.Vendors.Where(Function(v) v.Id = order.VendorId).DefaultIfEmpty()
            From status In 
            dc.Status.Where(Function(s) s.Id = order.StatusId).DefaultIfEmpty()
            Select Order = order, Vendor = vendor, Status = status 

Intro to GPU programming

I think the others have answered your second question. As for the first, the "Hello World" of CUDA, I don't think there is a set standard, but personally, I'd recommend a parallel adder (i.e. a programme that sums N integers).

If you look the "reduction" example in the NVIDIA SDK, the superficially simple task can be extended to demonstrate numerous CUDA considerations such as coalesced reads, memory bank conflicts and loop unrolling.

See this presentation for more info:

http://www.gpgpu.org/sc2007/SC07_CUDA_5_Optimization_Harris.pdf

Good PHP ORM Library?

I am currently working on phpDataMapper, which is an ORM designed to have simple syntax like Ruby's Datamapper project. It's still in early development as well, but it works great.

java.util.regex - importance of Pattern.compile()?

The compile() method is always called at some point; it's the only way to create a Pattern object. So the question is really, why should you call it explicitly? One reason is that you need a reference to the Matcher object so you can use its methods, like group(int) to retrieve the contents of capturing groups. The only way to get ahold of the Matcher object is through the Pattern object's matcher() method, and the only way to get ahold of the Pattern object is through the compile() method. Then there's the find() method which, unlike matches(), is not duplicated in the String or Pattern classes.

The other reason is to avoid creating the same Pattern object over and over. Every time you use one of the regex-powered methods in String (or the static matches() method in Pattern), it creates a new Pattern and a new Matcher. So this code snippet:

for (String s : myStringList) {
    if ( s.matches("\\d+") ) {
        doSomething();
    }
}

...is exactly equivalent to this:

for (String s : myStringList) {
    if ( Pattern.compile("\\d+").matcher(s).matches() ) {
        doSomething();
    }
}

Obviously, that's doing a lot of unnecessary work. In fact, it can easily take longer to compile the regex and instantiate the Pattern object, than it does to perform an actual match. So it usually makes sense to pull that step out of the loop. You can create the Matcher ahead of time as well, though they're not nearly so expensive:

Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher("");
for (String s : myStringList) {
    if ( m.reset(s).matches() ) {
        doSomething();
    }
}

If you're familiar with .NET regexes, you may be wondering if Java's compile() method is related to .NET's RegexOptions.Compiled modifier; the answer is no. Java's Pattern.compile() method is merely equivalent to .NET's Regex constructor. When you specify the Compiled option:

Regex r = new Regex(@"\d+", RegexOptions.Compiled); 

...it compiles the regex directly to CIL byte code, allowing it to perform much faster, but at a significant cost in up-front processing and memory use--think of it as steroids for regexes. Java has no equivalent; there's no difference between a Pattern that's created behind the scenes by String#matches(String) and one you create explicitly with Pattern#compile(String).

(EDIT: I originally said that all .NET Regex objects are cached, which is incorrect. Since .NET 2.0, automatic caching occurs only with static methods like Regex.Matches(), not when you call a Regex constructor directly. ref)

css divide width 100% to 3 column

A perfect 1/3 cannot exist in CSS with full cross browser support (anything below IE9). I personally would do: (It's not the perfect solution, but it's about as good as you'll get for all browsers)

#c1, #c2 {
    width: 33%;
}

#c3 {
    width: auto;
}

MySQL select one column DISTINCT, with corresponding other columns

Not sure if you can do this with MySQL, but you can use a CTE in T-SQL

; WITH tmpPeople AS (
 SELECT 
   DISTINCT(FirstName),
   MIN(Id)      
 FROM People
)
SELECT
 tP.Id,
 tP.FirstName,
 P.LastName
FROM tmpPeople tP
JOIN People P ON tP.Id = P.Id

Otherwise you might have to use a temporary table.

Get the Highlighted/Selected text

Use window.getSelection().toString().

You can read more on developer.mozilla.org

Location of hibernate.cfg.xml in project?

My problem was that i had a exculding patern in the resorces folder. After removing it the

config.configure(); 

worked for me. With the structure src/java/...HibernateUtil.java and cfg file under src/resources.

Converting newline formatting from Mac to Windows

This is an improved version of Anne's answer -- if you use perl, you can do the edit on the file 'in-place' rather than generating a new file:

perl -pi -e 's/\r\n|\n|\r/\r\n/g' file-to-convert  # Convert to DOS
perl -pi -e 's/\r\n|\n|\r/\n/g'   file-to-convert  # Convert to UNIX

jquery: $(window).scrollTop() but no $(window).scrollBottom()

I would say that a scrollBottom as a direct opposite of scrollTop should be:

var scrollBottom = $(document).height() - $(window).height() - $(window).scrollTop();

Here is a small ugly test that works for me:

// SCROLLTESTER START //
$('<h1 id="st" style="position: fixed; right: 25px; bottom: 25px;"></h1>').insertAfter('body');

$(window).scroll(function () {
  var st = $(window).scrollTop();
  var scrollBottom = $(document).height() - $(window).height() - $(window).scrollTop();

  $('#st').replaceWith('<h1 id="st" style="position: fixed; right: 25px; bottom: 25px;">scrollTop: ' + st + '<br>scrollBottom: ' + scrollBottom + '</h1>');
});
// SCROLLTESTER END //

Please initialize the log4j system properly. While running web service

If you are using Logger.getLogger(ClassName.class) then place your log4j.properties file in your class path:

yourproject/javaresoures/src/log4j.properties (Put inside src folder)

How to control border height?

not bad .. but try this one ... (should works for all but ist just -webkit included)

<br>
<input type="text" style="
  background: transparent;
border-bottom: 1px solid #B5D5FF;
border-left: 1px solid;
border-right: 1px solid;
border-left-color: #B5D5FF;
border-image: -webkit-linear-gradient(top, #fff 50%, #B5D5FF 0%) 1 repeat;
">

//Feel free to edit and add all other browser..

Sending a notification from a service in Android

This type of Notification is deprecated as seen from documents:

@java.lang.Deprecated
public Notification(int icon, java.lang.CharSequence tickerText, long when) { /* compiled code */ }

public Notification(android.os.Parcel parcel) { /* compiled code */ }

@java.lang.Deprecated
public void setLatestEventInfo(android.content.Context context, java.lang.CharSequence contentTitle, java.lang.CharSequence contentText, android.app.PendingIntent contentIntent) { /* compiled code */ }

Better way
You can send a notification like this:

// prepare intent which is triggered if the
// notification is selected

Intent intent = new Intent(this, NotificationReceiver.class);
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0);

// build notification
// the addAction re-use the same intent to keep the example short
Notification n  = new Notification.Builder(this)
        .setContentTitle("New mail from " + "[email protected]")
        .setContentText("Subject")
        .setSmallIcon(R.drawable.icon)
        .setContentIntent(pIntent)
        .setAutoCancel(true)
        .addAction(R.drawable.icon, "Call", pIntent)
        .addAction(R.drawable.icon, "More", pIntent)
        .addAction(R.drawable.icon, "And more", pIntent).build();


NotificationManager notificationManager = 
  (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

notificationManager.notify(0, n); 

Best way
Code above needs minimum API level 11 (Android 3.0).
If your minimum API level is lower than 11, you should you use support library's NotificationCompat class like this.

So if your minimum target API level is 4+ (Android 1.6+) use this:

    import android.support.v4.app.NotificationCompat;
    -------------
    NotificationCompat.Builder builder =
            new NotificationCompat.Builder(this)
                    .setSmallIcon(R.drawable.mylogo)
                    .setContentTitle("My Notification Title")
                    .setContentText("Something interesting happened");
    int NOTIFICATION_ID = 12345;

    Intent targetIntent = new Intent(this, MyFavoriteActivity.class);
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, targetIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    builder.setContentIntent(contentIntent);
    NotificationManager nManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    nManager.notify(NOTIFICATION_ID, builder.build());

Significance of ios_base::sync_with_stdio(false); cin.tie(NULL);

It's just common stuff for making cin input work faster.

For a quick explanation: the first line turns off buffer synchronization between the cin stream and C-style stdio tools (like scanf or gets) — so cin works faster, but you can't use it simultaneously with stdio tools.

The second line unties cin from cout — by default the cout buffer flushes each time when you read something from cin. And that may be slow when you repeatedly read something small then write something small many times. So the line turns off this synchronization (by literally tying cin to null instead of cout).

How to fix "unable to open stdio.h in Turbo C" error?

Check your environment include path. The file is not in the locations pointed by that environment variable.

How do I get indices of N maximum values in a NumPy array?

The simplest I've been able to come up with is:

In [1]: import numpy as np

In [2]: arr = np.array([1, 3, 2, 4, 5])

In [3]: arr.argsort()[-3:][::-1]
Out[3]: array([4, 3, 1])

This involves a complete sort of the array. I wonder if numpy provides a built-in way to do a partial sort; so far I haven't been able to find one.

If this solution turns out to be too slow (especially for small n), it may be worth looking at coding something up in Cython.

What is the instanceof operator in JavaScript?

I think it's worth noting that instanceof is defined by the use of the "new" keyword when declaring the object. In the example from JonH;

var color1 = new String("green");
color1 instanceof String; // returns true
var color2 = "coral";
color2 instanceof String; // returns false (color2 is not a String object)

What he didn't mention is this;

var color1 = String("green");
color1 instanceof String; // returns false

Specifying "new" actually copied the end state of the String constructor function into the color1 var, rather than just setting it to the return value. I think this better shows what the new keyword does;

function Test(name){
    this.test = function(){
        return 'This will only work through the "new" keyword.';
    }
    return name;
}

var test = new Test('test');
test.test(); // returns 'This will only work through the "new" keyword.'
test // returns the instance object of the Test() function.

var test = Test('test');
test.test(); // throws TypeError: Object #<Test> has no method 'test'
test // returns 'test'

Using "new" assigns the value of "this" inside the function to the declared var, while not using it assigns the return value instead.

Sharing a URL with a query string on Twitter

I reference all the methods.

Encode the query twice is the fast solution.

const query = a=123&b=456;
const url = `https://example.com/test?${encodeURIComponent(encodeURIComponent(query),)}`;


const twitterSharingURL=`https://twitter.com/intent/tweet?&url=${url}`

install cx_oracle for python

The alternate way, that doesn't require RPMs. You need to be root.

  1. Dependencies

    Install the following packages:

    apt-get install python-dev build-essential libaio1
    
  2. Download Instant Client for Linux x86-64

    Download the following files from Oracle's download site:

    files preview

  3. Extract the zip files

    Unzip the downloaded zip files to some directory, I'm using:

    /opt/ora/
    
  4. Add environment variables

    Create a file in /etc/profile.d/oracle.sh that includes

    export ORACLE_HOME=/opt/ora/instantclient_11_2
    export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$ORACLE_HOME
    

    Create a file in /etc/ld.so.conf.d/oracle.conf that includes

    /opt/ora/instantclient_11_2
    

    Execute the following command

    sudo ldconfig
    

    Note: you may need to reboot to apply settings

  5. Create a symlink

    cd $ORACLE_HOME 
    ln -s libclntsh.so.11.1 libclntsh.so
    
  6. Install cx_Oracle python package

    • You may install using pip

      pip install cx_Oracle
      
    • Or install manually

      Download the cx_Oracle source zip that corresponds with your Python and Oracle version. Then expand the archive, and run from the extracted directory:

      python setup.py build 
      python setup.py install
      

CSS Selector "(A or B) and C"?

I found success using the :is() selector:

*:is(.a, .b).c{...}

this is error ORA-12154: TNS:could not resolve the connect identifier specified?

The database must have a name (example DB1), try this one:

OracleConnection con = new OracleConnection("data source=DB1;user id=fastecit;password=fastecit"); 

In case the TNS is not defined you can also try this one:

OracleConnection con = new OracleConnection("Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=localhost)(PORT=1521)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=DB1)));
User Id=fastecit;Password=fastecit"); 

How do I get the real .height() of a overflow: hidden or overflow: scroll div?

Use the .scrollHeight property of the DOM node: $('#your_div')[0].scrollHeight

Show percent % instead of counts in charts of categorical variables

Note that if your variable is continuous, you will have to use geom_histogram(), as the function will group the variable by "bins".

df <- data.frame(V1 = rnorm(100))

ggplot(df, aes(x = V1)) +  
  geom_histogram(aes(y = 100*(..count..)/sum(..count..))) 

# if you use geom_bar(), with factor(V1), each value of V1 will be treated as a
# different category. In this case this does not make sense, as the variable is 
# really continuous. With the hp variable of the mtcars (see previous answer), it 
# worked well since hp was not really continuous (check unique(mtcars$hp)), and one 
# can want to see each value of this variable, and not to group it in bins.
ggplot(df, aes(x = factor(V1))) +  
  geom_bar(aes(y = (..count..)/sum(..count..))) 

How to persist a property of type List<String> in JPA?

Thiago answer is correct, adding sample more specific to question, @ElementCollection will create new table in your database, but without mapping two tables, It means that the collection is not a collection of entities, but a collection of simple types (Strings, etc.) or a collection of embeddable elements (class annotated with @Embeddable).

Here is the sample to persist list of String

@ElementCollection
private Collection<String> options = new ArrayList<String>();

Here is the sample to persist list of Custom object

@Embedded
@ElementCollection
private Collection<Car> carList = new ArrayList<Car>();

For this case we need to make class Embeddable

@Embeddable
public class Car {
}

Purpose of installing Twitter Bootstrap through npm?

If you NPM those modules you can serve them using static redirect.

First install the packages:

npm install jquery
npm install bootstrap

Then on the server.js:

var express = require('express');
var app = express();

// prepare server
app.use('/api', api); // redirect API calls
app.use('/', express.static(__dirname + '/www')); // redirect root
app.use('/js', express.static(__dirname + '/node_modules/bootstrap/dist/js')); // redirect bootstrap JS
app.use('/js', express.static(__dirname + '/node_modules/jquery/dist')); // redirect JS jQuery
app.use('/css', express.static(__dirname + '/node_modules/bootstrap/dist/css')); // redirect CSS bootstrap

Then, finally, at the .html:

<link rel="stylesheet" href="/css/bootstrap.min.css">
<script src="/js/jquery.min.js"></script>
<script src="/js/bootstrap.min.js"></script>

I would not serve pages directly from the folder where your server.js file is (which is usually the same as node_modules) as proposed by timetowonder, that way people can access your server.js file.

Of course you can simply download and copy & paste on your folder, but with NPM you can simply update when needed... easier, I think.

Access to Image from origin 'null' has been blocked by CORS policy

The problem was actually solved by providing crossOrigin: null to OpenLayers OSM source:

var newLayer = new ol.layer.Tile({
source: new ol.source.OSM({
    url: 'E:/Maperitive/Tiles/vychod/{z}/{x}/{y}.png',
    crossOrigin: null
    })
});

Command to run a .bat file

You can use Cmd command to run Batch file.

Here is my way =>

cmd /c ""Full_Path_Of_Batch_Here.cmd" "

More information => cmd /?

Spring-boot default profile for integration tests

A delarative way to do that (In fact, a minor tweek to @Compito's original answer):

  1. Set spring.profiles.active=test in test/resources/application-default.properties.
  2. Add test/resources/application-test.properties for tests and override only the properties you need.

Convert month name to month number in SQL Server

You can create a function and then refer to it in the select statement. The function may look similar to this:

if OBJECT_ID('fn_month_name_to_number', 'IF') is not null
drop function fn_month_name_to_number
go
create function fn_month_name_to_number (@monthname varchar(25))
returns int as
begin
declare @monthno as int;
select @monthno =
case @monthname
when 'January' then 1
when 'February' then 2
when 'March' then 3
when 'April' then 4
when 'May' then 5
when 'June' then 6
when 'July' then 7
when 'August' then 8
when 'September' then 9
when 'October' then 10
when 'November' then 11
when 'December' then 12
end
return @monthno
end

Then you can query it.

select fn_month_name_to_number ('February') as month_no

This query will return 2 as month number. You can pass values from a column as parameters to the function.

select fn_month_name_to_number (*columnname*) as month_no from *tablename*

Have a good day!

Android open pdf file

The problem is that there is no app installed to handle opening the PDF. You should use the Intent Chooser, like so:

File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() +"/"+ filename);
Intent target = new Intent(Intent.ACTION_VIEW);
target.setDataAndType(Uri.fromFile(file),"application/pdf");
target.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);

Intent intent = Intent.createChooser(target, "Open File");
try {
    startActivity(intent);
} catch (ActivityNotFoundException e) {
    // Instruct the user to install a PDF reader here, or something
}   

What is the difference between a var and val definition in Scala?

val means immutable and var means mutable

you can think val as java programming language final key world or c++ language const key world?

What is the best way to extract the first word from a string in Java?

import org.apache.commons.lang3.StringUtils;

...
StringUtils.substringBefore("Grigory Kislin", " ")

How to use cURL to send Cookies?

This worked for me:

curl -v --cookie "USER_TOKEN=Yes" http://127.0.0.1:5000/

I could see the value in backend using

print request.cookies

Node.js EACCES error when listening on most ports

On Windows System, restarting the service "Host Network Service", resolved the issue.

A fatal error occurred while creating a TLS client credential. The internal error state is 10013

Basically we had to enable TLS 1.2 for .NET 4.x. Making this registry changed worked for me, and stopped the event log filling up with the Schannel error.

More information on the answer can be found here

Linked Info Summary

Enable TLS 1.2 at the system (SCHANNEL) level:

Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2]
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Client]
"DisabledByDefault"=dword:00000000
"Enabled"=dword:00000001
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Server]
"DisabledByDefault"=dword:00000000
"Enabled"=dword:00000001

(equivalent keys are probably also available for other TLS versions)

Tell .NET Framework to use the system TLS versions:

Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework\v4.0.30319]
"SystemDefaultTlsVersions"=dword:00000001
[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\.NETFramework\v4.0.30319]
"SystemDefaultTlsVersions"=dword:00000001

This may not be desirable for edge cases where .NET Framework 4.x applications need to have different protocols enabled and disabled than the OS does.

Can (a== 1 && a ==2 && a==3) ever evaluate to true?

Example without getters or valueOf:

_x000D_
_x000D_
a = [1,2,3];_x000D_
a.join = a.shift;_x000D_
console.log(a == 1 && a == 2 && a == 3);
_x000D_
_x000D_
_x000D_

This works because == invokes toString which calls .join for Arrays.

Another solution, using Symbol.toPrimitive which is an ES6 equivalent of toString/valueOf:

_x000D_
_x000D_
let i = 0;_x000D_
let a = { [Symbol.toPrimitive]: () => ++i };_x000D_
_x000D_
console.log(a == 1 && a == 2 && a == 3);
_x000D_
_x000D_
_x000D_

Download and open PDF file using Ajax

This is how i solve this issue.
The answer of Jonathan Amend on this post helped me a lot.
The example below is simplified.

For more details, the above source code is able to download a file using a JQuery Ajax request (GET, POST, PUT etc). It, also, helps to upload parameters as JSON and to change the content type to application/json (my default).

The html source:

<form method="POST">
    <input type="text" name="startDate"/>
    <input type="text" name="endDate"/>
    <input type="text" name="startDate"/>
    <select name="reportTimeDetail">
        <option value="1">1</option>
    </select>
    <button type="submit"> Submit</button>
</form>  

A simple form with two input text, one select and a button element.

The javascript page source:

<script type="text/javascript" src="JQuery 1.11.0 link"></script>
<script type="text/javascript">
    // File Download on form submition.
    $(document).on("ready", function(){
        $("form button").on("click", function (event) {
            event.stopPropagation(); // Do not propagate the event.

            // Create an object that will manage to download the file.
            new AjaxDownloadFile({
                url: "url that returns a file",
                data: JSON.stringify($("form").serializeObject())
            });

            return false; // Do not submit the form.
        });
    });
</script>  

A simple event on button click. It creates an AjaxDownloadFile object. The AjaxDownloadFile class source is below.

The AjaxDownloadFile class source:

var AjaxDownloadFile = function (configurationSettings) {
    // Standard settings.
    this.settings = {
        // JQuery AJAX default attributes.
        url: "",
        type: "POST",
        headers: {
            "Content-Type": "application/json; charset=UTF-8"
        },
        data: {},
        // Custom events.
        onSuccessStart: function (response, status, xhr, self) {
        },
        onSuccessFinish: function (response, status, xhr, self, filename) {
        },
        onErrorOccured: function (response, status, xhr, self) {
        }
    };
    this.download = function () {
        var self = this;
        $.ajax({
            type: this.settings.type,
            url: this.settings.url,
            headers: this.settings.headers,
            data: this.settings.data,
            success: function (response, status, xhr) {
                // Start custom event.
                self.settings.onSuccessStart(response, status, xhr, self);

                // Check if a filename is existing on the response headers.
                var filename = "";
                var disposition = xhr.getResponseHeader("Content-Disposition");
                if (disposition && disposition.indexOf("attachment") !== -1) {
                    var filenameRegex = /filename[^;=\n]*=(([""]).*?\2|[^;\n]*)/;
                    var matches = filenameRegex.exec(disposition);
                    if (matches != null && matches[1])
                        filename = matches[1].replace(/[""]/g, "");
                }

                var type = xhr.getResponseHeader("Content-Type");
                var blob = new Blob([response], {type: type});

                if (typeof window.navigator.msSaveBlob !== "undefined") {
                    // IE workaround for "HTML7007: One or more blob URLs were revoked by closing the blob for which they were created. These URLs will no longer resolve as the data backing the URL has been freed.
                    window.navigator.msSaveBlob(blob, filename);
                } else {
                    var URL = window.URL || window.webkitURL;
                    var downloadUrl = URL.createObjectURL(blob);

                    if (filename) {
                        // Use HTML5 a[download] attribute to specify filename.
                        var a = document.createElement("a");
                        // Safari doesn"t support this yet.
                        if (typeof a.download === "undefined") {
                            window.location = downloadUrl;
                        } else {
                            a.href = downloadUrl;
                            a.download = filename;
                            document.body.appendChild(a);
                            a.click();
                        }
                    } else {
                        window.location = downloadUrl;
                    }

                    setTimeout(function () {
                        URL.revokeObjectURL(downloadUrl);
                    }, 100); // Cleanup
                }

                // Final custom event.
                self.settings.onSuccessFinish(response, status, xhr, self, filename);
            },
            error: function (response, status, xhr) {
                // Custom event to handle the error.
                self.settings.onErrorOccured(response, status, xhr, self);
            }
        });
    };
    // Constructor.
    {
        // Merge settings.
        $.extend(this.settings, configurationSettings);
        // Make the request.
        this.download();
    }
};

I created this class to added to my JS library. It is reusable. Hope that helps.

How to Convert JSON object to Custom C# object?

To keep your options open, if you're using .NET 3.5 or later, here is a wrapped up example you can use straight from the framework using Generics. As others have mentioned, if it's not just simple objects you should really use JSON.net.

public static string Serialize<T>(T obj)
{
    DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
    MemoryStream ms = new MemoryStream();
    serializer.WriteObject(ms, obj);
    string retVal = Encoding.UTF8.GetString(ms.ToArray());
    return retVal;
}

public static T Deserialize<T>(string json)
{
    T obj = Activator.CreateInstance<T>();
    MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json));
    DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
    obj = (T)serializer.ReadObject(ms);
    ms.Close();
    return obj;
}

You'll need:

using System.Runtime.Serialization;

using System.Runtime.Serialization.Json;

Vue JS mounted()

Abstract your initialization into a method, and call the method from mounted and wherever else you want.

new Vue({
  methods:{
    init(){
      //call API
      //Setup game
    }
  },
  mounted(){
    this.init()
  }
})

Then possibly have a button in your template to start over.

<button v-if="playerWon" @click="init">Play Again</button>

In this button, playerWon represents a boolean value in your data that you would set when the player wins the game so the button appears. You would set it back to false in init.

How to terminate a window in tmux?

For me solution looks like:

  1. ctrl+b q to show pane numbers.
  2. ctrl+b x to kill pane.

Killing last pane will kill window.

jQuery change input text value

Just adding to Jason's answer, the . selector is only for classes. If you want to select something other than the element, id, or class, you need to wrap it in square brackets.

e.g.

$('element[attr=val]')

How do you add a timer to a C# console application

Use the System.Threading.Timer class.

System.Windows.Forms.Timer is designed primarily for use in a single thread usually the Windows Forms UI thread.

There is also a System.Timers class added early on in the development of the .NET framework. However it is generally recommended to use the System.Threading.Timer class instead as this is just a wrapper around System.Threading.Timer anyway.

It is also recommended to always use a static (shared in VB.NET) System.Threading.Timer if you are developing a Windows Service and require a timer to run periodically. This will avoid possibly premature garbage collection of your timer object.

Here's an example of a timer in a console application:

using System; 
using System.Threading; 
public static class Program 
{ 
    public static void Main() 
    { 
       Console.WriteLine("Main thread: starting a timer"); 
       Timer t = new Timer(ComputeBoundOp, 5, 0, 2000); 
       Console.WriteLine("Main thread: Doing other work here...");
       Thread.Sleep(10000); // Simulating other work (10 seconds)
       t.Dispose(); // Cancel the timer now
    }
    // This method's signature must match the TimerCallback delegate
    private static void ComputeBoundOp(Object state) 
    { 
       // This method is executed by a thread pool thread 
       Console.WriteLine("In ComputeBoundOp: state={0}", state); 
       Thread.Sleep(1000); // Simulates other work (1 second)
       // When this method returns, the thread goes back 
       // to the pool and waits for another task 
    }
}

From the book CLR Via C# by Jeff Richter. By the way this book describes the rationale behind the 3 types of timers in Chapter 23, highly recommended.

Iframe transparent background

Why not just load the frame off screen or hidden and then display it once it has finished loading. You could show a loading icon in its place to begin with to give the user immediate feedback that it's loading.

Default instance name of SQL Server Express

The default instance name after installing is,

Server name:

.\SQLExpress

Authentication:

Windows Authentication

Note: The period in the server Name field means your local machine. For remote machines, use the machine name instead of the period.

This video also helps you to Find your sql server name (instance) for Management Studio .

writing to existing workbook using xlwt

Here's some sample code I used recently to do just that.

It opens a workbook, goes down the rows, if a condition is met it writes some data in the row. Finally it saves the modified file.

from xlutils.copy import copy # http://pypi.python.org/pypi/xlutils
from xlrd import open_workbook # http://pypi.python.org/pypi/xlrd

START_ROW = 297 # 0 based (subtract 1 from excel row number)
col_age_november = 1
col_summer1 = 2
col_fall1 = 3

rb = open_workbook(file_path,formatting_info=True)
r_sheet = rb.sheet_by_index(0) # read only copy to introspect the file
wb = copy(rb) # a writable copy (I can't read values out of this, only write to it)
w_sheet = wb.get_sheet(0) # the sheet to write to within the writable copy

for row_index in range(START_ROW, r_sheet.nrows):
    age_nov = r_sheet.cell(row_index, col_age_november).value
    if age_nov == 3:
        #If 3, then Combo I 3-4 year old  for both summer1 and fall1
        w_sheet.write(row_index, col_summer1, 'Combo I 3-4 year old')
        w_sheet.write(row_index, col_fall1, 'Combo I 3-4 year old')

wb.save(file_path + '.out' + os.path.splitext(file_path)[-1])

setTimeout or setInterval?

Your code will have different execution intevals, and in some projects, such as online games it's not acceptable. First, what should you do, to make your code work with same intevals, you should change "myTimeoutFunction" to this:

function myTimeoutFunction()
{
    setTimeout(myTimeoutFunction, 1000);
    doStuff();
}
myTimeoutFunction()

After this change, it will be equal to

function myTimeoutFunction()
{
    doStuff();
}
myTimeoutFunction();
setInterval(myTimeoutFunction, 1000);

But, you will still have not stable result, because JS is single-threaded. For now, if JS thread will be busy with something, it will not be able to execute your callback function, and execution will be postponed for 2-3 msec. Is you have 60 executions per second, and each time you have random 1-3 sec delay, it will be absolutely not acceptable (after one minute it will be around 7200 msec delay), and I can advice to use something like this:

    function Timer(clb, timeout) {
        this.clb = clb;
        this.timeout = timeout;
        this.stopTimeout = null;
        this.precision = -1;
    }

    Timer.prototype.start = function() {
        var me = this;
        var now = new Date();
        if(me.precision === -1) {
            me.precision = now.getTime();
        }
        me.stopTimeout = setTimeout(function(){
            me.start()
        }, me.precision - now.getTime() + me.timeout);
        me.precision += me.timeout;
        me.clb();
    };

    Timer.prototype.stop = function() {
        clearTimeout(this.stopTimeout);
        this.precision = -1;
    };

    function myTimeoutFunction()
    {
        doStuff();
    }

    var timer = new Timer(myTimeoutFunction, 1000);
    timer.start();

This code will guarantee stable execution period. Even thread will be busy, and your code will be executed after 1005 mseconds, next time it will have timeout for 995 msec, and result will be stable.

Prevent BODY from scrolling when a modal is opened

Bootstrap's modal automatically adds the class modal-open to the body when a modal dialog is shown and removes it when the dialog is hidden. You can therefore add the following to your CSS:

body.modal-open {
    overflow: hidden;
}

You could argue that the code above belongs to the Bootstrap CSS code base, but this is an easy fix to add it to your site.

Update 8th feb, 2013
This has now stopped working in Twitter Bootstrap v. 2.3.0 -- they no longer add the modal-open class to the body.

A workaround would be to add the class to the body when the modal is about to be shown, and remove it when the modal is closed:

$("#myModal").on("show", function () {
  $("body").addClass("modal-open");
}).on("hidden", function () {
  $("body").removeClass("modal-open")
});

Update 11th march, 2013 Looks like the modal-open class will return in Bootstrap 3.0, explicitly for the purpose of preventing the scroll:

Reintroduces .modal-open on the body (so we can nuke the scroll there)

See this: https://github.com/twitter/bootstrap/pull/6342 - look at the Modal section.

How can a Jenkins user authentication details be "passed" to a script which uses Jenkins API to create jobs?

In order to use API tokens, users will have to obtain their own tokens, each from https://<jenkins-server>/me/configure or https://<jenkins-server>/user/<user-name>/configure. It is up to you, as the author of the script, to determine how users supply the token to the script. For example, in a Bourne Shell script running interactively inside a Git repository, where .gitignore contains /.jenkins_api_token, you might do something like:

api_token_file="$(git rev-parse --show-cdup).jenkins_api_token"
api_token=$(cat "$api_token_file" || true)
if [ -z "$api_token" ]; then
    echo
    echo "Obtain your API token from $JENKINS_URL/user/$user/configure"
    echo "After entering here, it will be saved in $api_token_file; keep it safe!"
    read -p "Enter your Jenkins API token: " api_token
    echo $api_token > "$api_token_file"
fi
curl -u $user:$api_token $JENKINS_URL/someCommand

Inserting data to table (mysqli insert)

Okay, of course the question has been answered, but no-one seems to notice the third line of your code. It continuosly bugged me.

    <?php
    mysqli_connect("localhost","root","","web_table");
    mysql_select_db("web_table") or die(mysql_error());

for some reason, you made a mysqli connection to server, but you are trying to make a mysql connection to database.To get going, rather use

       $link = mysqli_connect("localhost","root","","web_table");
       mysqli_select_db ($link , "web_table" ) or die.....

or for where i began

     <?php $connection = mysqli_connect("localhost","root","","web_table");       
      global $connection; // global connection to databases - kill it once you're done

or just query with a $connection parameter as the other argument like above. Get rid of that third line.

Is "delete this" allowed in C++?

Delete this is legal as long as object is in heap. You would need to require object to be heap only. The only way to do that is to make the destructor protected - this way delete may be called ONLY from class , so you would need a method that would ensure deletion

Print number of keys in Redis

Go to redis-cli and use below command

info keyspace

It may help someone

Android 'Unable to add window -- token null is not for an application' exception

Use this and context not worked for me..but MyActivityName.this worked. Hope this helps anyone who need it.

How to split a dos path into its components in Python

In Python >=3.4 this has become much simpler. You can now use pathlib.Path.parts to get all the parts of a path.

Example:

>>> from pathlib import Path
>>> Path('C:/path/to/file.txt').parts
('C:\\', 'path', 'to', 'file.txt')
>>> Path(r'C:\path\to\file.txt').parts
('C:\\', 'path', 'to', 'file.txt')

On a Windows install of Python 3 this will assume that you are working with Windows paths, and on *nix it will assume that you are working with posix paths. This is usually what you want, but if it isn't you can use the classes pathlib.PurePosixPath or pathlib.PureWindowsPath as needed:

>>> from pathlib import PurePosixPath, PureWindowsPath
>>> PurePosixPath('/path/to/file.txt').parts
('/', 'path', 'to', 'file.txt')
>>> PureWindowsPath(r'C:\path\to\file.txt').parts
('C:\\', 'path', 'to', 'file.txt')
>>> PureWindowsPath(r'\\host\share\path\to\file.txt').parts
('\\\\host\\share\\', 'path', 'to', 'file.txt')

Edit: There is also a backport to python 2 available: pathlib2

Angularjs prevent form submission when input validation fails

HTML:

<div class="control-group">
    <input class="btn" type="submit" value="Log in" ng-click="login.onSubmit($event)">
</div>

In your controller:

$scope.login = {
    onSubmit: function(event) {
        if (dataIsntValid) {
            displayErrors();
            event.preventDefault();
        }
        else {
            submitData();
        }
    }
}

Cannot lower case button text in android studio

in XML Code
add this line android:textAllCaps="false" like bellow code

 <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/button_1_name"
        android:id="@+id/button2"
        android:layout_marginTop="140dp"
        android:layout_below="@+id/textView"
        android:layout_centerHorizontal="true"
       ** android:textAllCaps="false" ** />

or

in Java code (programmatically)
add this line to your button setAllCaps(false)

Button btn = (Button) findViewById(R.id.button2);
btn.setAllCaps(false);

Swift addsubview and remove it

You have to use the viewWithTag function to find the view with the given tag.

override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
    let touch = touches.anyObject() as UITouch
    let point = touch.locationInView(self.view)

    if let viewWithTag = self.view.viewWithTag(100) {
        print("Tag 100")
        viewWithTag.removeFromSuperview()
    } else {
        print("tag not found")
    }
}

How to iterate through SparseArray?

Seems I found the solution. I hadn't properly noticed the keyAt(index) function.

So I'll go with something like this:

for(int i = 0; i < sparseArray.size(); i++) {
   int key = sparseArray.keyAt(i);
   // get the object by the key.
   Object obj = sparseArray.get(key);
}

Getting value GET OR POST variable using JavaScript?

You can't get the value of POST variables using Javascript, although you can insert it in the document when you process the request on the server.

<script type="text/javascript">
    window.some_variable = '<?=$_POST['some_value']?>'; // That's for a string
</script>

GET variables are available through the window.location.href, and some frameworks even have methods ready to parse them.

List vs tuple, when to use each?

Must it be mutable? Use a list. Must it not be mutable? Use a tuple.

Otherwise, it's a question of choice.

For collections of heterogeneous objects (like a address broken into name, street, city, state and zip) I prefer to use a tuple. They can always be easily promoted to named tuples.

Likewise, if the collection is going to be iterated over, I prefer a list. If it's just a container to hold multiple objects as one, I prefer a tuple.

JavaScript variable number of arguments to function

Be aware that passing an Object with named properties as Ken suggested adds the cost of allocating and releasing the temporary object to every call. Passing normal arguments by value or reference will generally be the most efficient. For many applications though the performance is not critical but for some it can be.

onMeasure custom view explanation

If you don't need to change something onMeasure - there's absolutely no need for you to override it.

Devunwired code (the selected and most voted answer here) is almost identical to what the SDK implementation already does for you (and I checked - it had done that since 2009).

You can check the onMeasure method here :

protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
            getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
}

public static int getDefaultSize(int size, int measureSpec) {
    int result = size;
    int specMode = MeasureSpec.getMode(measureSpec);
    int specSize = MeasureSpec.getSize(measureSpec);

    switch (specMode) {
    case MeasureSpec.UNSPECIFIED:
        result = size;
        break;
    case MeasureSpec.AT_MOST:
    case MeasureSpec.EXACTLY:
        result = specSize;
        break;
    }
    return result;
}

Overriding SDK code to be replaced with the exact same code makes no sense.

This official doc's piece that claims "the default onMeasure() will always set a size of 100x100" - is wrong.

How to extract extension from filename string in Javascript?

I would recommend using lastIndexOf() as opposed to indexOf()

var myString = "this.is.my.file.txt"
alert(myString.substring(myString.lastIndexOf(".")+1))

Creating a new column based on if-elif-else condition

For this particular relationship, you could use np.sign:

>>> df["C"] = np.sign(df.A - df.B)
>>> df
   A  B  C
a  2  2  0
b  3  1  1
c  1  3 -1

jQuery onclick toggle class name

jQuery has a toggleClass function:

<button class="switch">Click me</button>

<div class="text-block collapsed pressed">some text</div>

<script>    
    $('.switch').on('click', function(e) {
      $('.text-block').toggleClass("collapsed pressed"); //you can list several class names 
      e.preventDefault();
    });
</script>

How can I run an external command asynchronously from Python?

If you want to run many processes in parallel and then handle them when they yield results, you can use polling like in the following:

from subprocess import Popen, PIPE
import time

running_procs = [
    Popen(['/usr/bin/my_cmd', '-i %s' % path], stdout=PIPE, stderr=PIPE)
    for path in '/tmp/file0 /tmp/file1 /tmp/file2'.split()]

while running_procs:
    for proc in running_procs:
        retcode = proc.poll()
        if retcode is not None: # Process finished.
            running_procs.remove(proc)
            break
        else: # No process is done, wait a bit and check again.
            time.sleep(.1)
            continue

    # Here, `proc` has finished with return code `retcode`
    if retcode != 0:
        """Error handling."""
    handle_results(proc.stdout)

The control flow there is a little bit convoluted because I'm trying to make it small -- you can refactor to your taste. :-)

This has the advantage of servicing the early-finishing requests first. If you call communicate on the first running process and that turns out to run the longest, the other running processes will have been sitting there idle when you could have been handling their results.

Aren't Python strings immutable? Then why does a + " " + b work?

l = [1,2,3]
print id(l)
l.append(4)
print id(l) #object l is the same

a = "dog"
print id(a)
a = "cat"
print id(a) #object a is a new object, previous one is deleted

What is a mutex?

In C#, the common mutex used is the Monitor. The type is 'System.Threading.Monitor'. It may also be used implicitly via the 'lock(Object)' statement. One example of its use is when constructing a Singleton class.

private static readonly Object instanceLock = new Object();
private static MySingleton instance;
public static MySingleton Instance
{
    lock(instanceLock)
    {
        if(instance == null)
        {
            instance = new MySingleton();
        }
        return instance;
    }
}

The lock statement using the private lock object creates a critical section. Requiring each thread to wait until the previous is finished. The first thread will enter the section and initialize the instance. The second thread will wait, get into the section, and get the initialized instance.

Any sort of synchronization of a static member may use the lock statement similarly.

How can I write to the console in PHP?

Short and easy, for arrays, strings or also objects.

function console_log( $data ) {
  $output  = "<script>console.log( 'PHP debugger: ";
  $output .= json_encode(print_r($data, true));
  $output .= "' );</script>";
  echo $output;
}

Java generating Strings with placeholders

StrSubstitutor from Apache Commons Lang may be used for string formatting with named placeholders:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-text</artifactId>
    <version>1.1</version>
</dependency>

https://commons.apache.org/proper/commons-lang/javadocs/api-3.4/org/apache/commons/lang3/text/StrSubstitutor.html :

Substitutes variables within a string by values.

This class takes a piece of text and substitutes all the variables within it. The default definition of a variable is ${variableName}. The prefix and suffix can be changed via constructors and set methods.

Variable values are typically resolved from a map, but could also be resolved from system properties, or by supplying a custom variable resolver.

Example:

String template = "Hi ${name}! Your number is ${number}";

Map<String, String> data = new HashMap<String, String>();
data.put("name", "John");
data.put("number", "1");

String formattedString = StrSubstitutor.replace(template, data);

Git Ignores and Maven targets

add following lines in gitignore, from all undesirable files

/target/
*/target/**
**/META-INF/
!.mvn/wrapper/maven-wrapper.jar

### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache

### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr

### NetBeans ###
/nbproject/private/
/build/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/

jQuery’s .bind() vs. .on()

From the jQuery documentation:

As of jQuery 1.7, the .on() method is the preferred method for attaching event handlers to a document. For earlier versions, the .bind() method is used for attaching an event handler directly to elements. Handlers are attached to the currently selected elements in the jQuery object, so those elements must exist at the point the call to .bind() occurs. For more flexible event binding, see the discussion of event delegation in .on() or .delegate().

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

String field value length in mongoDB

Here is one of the way in mongodb you can achieve this.

db.usercollection.find({ $where: 'this.name.length < 4' })

Jquery Chosen plugin - dynamically populate list by Ajax

Chosen API has changed a lot.

If non of the solution given works for you, you can try this one: https://github.com/goFrendiAsgard/gofrendi.chosen.ajaxify

Here is the function:

// USAGE:
// $('#some_input_id').chosen();
// chosen_ajaxify('some_input_id', 'http://some_url.com/contain/');

// REQUEST WILL BE SENT TO THIS URL: http://some_url.com/contain/some_term

// AND THE EXPECTED RESULT (WHICH IS GOING TO BE POPULATED IN CHOSEN) IS IN JSON FORMAT
// CONTAINING AN ARRAY WHICH EACH ELEMENT HAS "value" AND "caption" KEY. EX:
// [{"value":"1", "caption":"Go Frendi Gunawan"}, {"value":"2", "caption":"Kira Yamato"}]

function chosen_ajaxify(id, ajax_url){
    console.log($('.chosen-search input').autocomplete);
    $('div#' + id + '_chosen .chosen-search input').keyup(function(){
        var keyword = $(this).val();
        var keyword_pattern = new RegExp(keyword, 'gi');
        $('div#' + id + '_chosen ul.chosen-results').empty();
        $("#"+id).empty();
        $.ajax({
            url: ajax_url + keyword,
            dataType: "json",
            success: function(response){
                // map, just as in functional programming :). Other way to say "foreach"
                $.map(response, function(item){
                    $('#'+id).append('<option value="' + item.value + '">' + item.caption + '</option>');
                });
                $("#"+id).trigger("chosen:updated");
                $('div#' + id + '_chosen').removeClass('chosen-container-single-nosearch');
                $('div#' + id + '_chosen .chosen-search input').val(keyword);
                $('div#' + id + '_chosen .chosen-search input').removeAttr('readonly');
                $('div#' + id + '_chosen .chosen-search input').focus();
                // put that underscores
                $('div#' + id + '_chosen .active-result').each(function(){
                    var html = $(this).html();
                    $(this).html(html.replace(keyword_pattern, function(matched){
                        return '<em>' + matched + '</em>';
                    }));
                });
            }
        });
    });
}

Here is your HTML:

<select id="ajax_select"></select>

And here is your javasscript:

// This is also how you usually use chosen
$('#ajax_select').chosen({allow_single_deselect:true, width:"200px", search_contains: true});
// And this one is how you add AJAX capability
chosen_ajaxify('ajax_select', 'server.php?keyword=');

For more information, please refer to https://github.com/goFrendiAsgard/gofrendi.chosen.ajaxify#how-to-use

Return index of greatest value in an array

If you are utilizing underscore, you can use this nice short one-liner:

_.indexOf(arr, _.max(arr))

It will first find the value of the largest item in the array, in this case 22. Then it will return the index of where 22 is within the array, in this case 2.

Display Adobe pdf inside a div

may be you can do by using AJAX or jquery...
just send that file url on one page and then open like normally open pdf file in that page and use ajax.

1)so as soon as user will click on the button. then u call that function in which u above tast. So by this way there will be only one page and by that you can show as many pdf without refreshing page.

2) if u don't have many pdf and if u don't know then just upload that file on google docs and then just put the share link file....and then just use ajax or jquery.

i prefer jquery if u don't have use AJAX.

How can I replace non-printable Unicode characters in Java?

I have used this simple function for this:

private static Pattern pattern = Pattern.compile("[^ -~]");
private static String cleanTheText(String text) {
    Matcher matcher = pattern.matcher(text);
    if ( matcher.find() ) {
        text = text.replace(matcher.group(0), "");
    }
    return text;
}

Hope this is useful.

How to convert date in to yyyy-MM-dd Format?

You can't format the Date itself. You can only get the formatted result in String. Use SimpleDateFormat as mentioned by others.

Moreover, most of the getter methods in Date are deprecated.

Make cross-domain ajax JSONP request with jQuery

alert(xml.data[0].city);

use xml.data["Data"][0].city instead

Write a mode method in Java to find the most frequently occurring element in an array

You should use a hashmap for such problems. it will take O(n) time to enter each element into the hashmap and o(1) to retrieve the element. In the given code, I am basically taking a global max and comparing it with the value received on 'get' from the hashmap, each time I am entering an element into it, have a look:

hashmap has two parts, one is the key, the second is the value when you do a get operation on the key, its value is returned.

public static int mode(int []array)
{
    HashMap<Integer,Integer> hm = new HashMap<Integer,Integer>();
    int max  = 1;
    int temp = 0;

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

        if (hm.get(array[i]) != null) {

            int count = hm.get(array[i]);
            count++;
            hm.put(array[i], count);

            if(count > max) {
                max  = count;
                temp = array[i];
            }
        }

        else 
            hm.put(array[i],1);
    }
    return temp;
}

Counting the number of non-NaN elements in a numpy ndarray in Python

Quick-to-write alterantive

Even though is not the fastest choice, if performance is not an issue you can use:

sum(~np.isnan(data)).

Performance:

In [7]: %timeit data.size - np.count_nonzero(np.isnan(data))
10 loops, best of 3: 67.5 ms per loop

In [8]: %timeit sum(~np.isnan(data))
10 loops, best of 3: 154 ms per loop

In [9]: %timeit np.sum(~np.isnan(data))
10 loops, best of 3: 140 ms per loop

Bash: If/Else statement in one line

You can make full use of the && and || operators like this:

ps aux | grep some_proces[s] > /tmp/test.txt && echo 1 || echo 0

For excluding grep itself, you could also do something like:

ps aux | grep some_proces | grep -vw grep > /tmp/test.txt && echo 1 || echo 0

JavaScript Nested function

_x000D_
_x000D_
function foo() {_x000D_
  function bar() {_x000D_
    return 1;_x000D_
  }_x000D_
}_x000D_
bar();
_x000D_
_x000D_
_x000D_
Will throw an error. Since bar is defined inside foo, bar will only be accessible inside foo.
To use bar you need to run it inside foo.

_x000D_
_x000D_
function foo() {_x000D_
  function bar() {_x000D_
    return 1;_x000D_
  }_x000D_
  bar();_x000D_
}
_x000D_
_x000D_
_x000D_

How to expand and compute log(a + b)?

In general, one doesn't expand out log(a + b); you just deal with it as is. That said, there are occasionally circumstances where it makes sense to use the following identity:

log(a + b) = log(a * (1 + b/a)) = log a + log(1 + b/a)

(In fact, this identity is often used when implementing log in math libraries).

Return a 2d array from a function

The function returns a static 2D array

const int N = 6;
int (*(MakeGridOfCounts)())[N] {
 static int cGrid[N][N] = {{0, }, {0, }, {0, }, {0, }, {0, }, {0, }};
 return cGrid;
}

int main() {
int (*arr)[N];
arr = MakeGridOfCounts();
}

You need to make the array static since it will be having a block scope, when the function call ends, the array will be created and destroyed. Static scope variables last till the end of program.

read file in classpath

Try getting Spring to inject it, assuming you're using Spring as a dependency-injection framework.

In your class, do something like this:

public void setSqlResource(Resource sqlResource) {
    this.sqlResource = sqlResource;
}

And then in your application context file, in the bean definition, just set a property:

<bean id="someBean" class="...">
    <property name="sqlResource" value="classpath:com/somecompany/sql/sql.txt" />
</bean>

And Spring should be clever enough to load up the file from the classpath and give it to your bean as a resource.

You could also look into PropertyPlaceholderConfigurer, and store all your SQL in property files and just inject each one separately where needed. There are lots of options.

how to measure running time of algorithms in python

The module timeit is useful for this and is included in the standard Python distribution.

Example:

import timeit
timeit.Timer('for i in xrange(10): oct(i)').timeit()

Failed to authenticate on SMTP server error using gmail

Change the .env file as follow

MAIL_DRIVER=smtp
MAIL_HOST=smtp.googlemail.com
MAIL_PORT=587
[email protected]
MAIL_PASSWORD=password
MAIL_ENCRYPTION=tls

And the go to the gmail security section ->Allow Less secure app access

Then run

php artisan config:clear

Refresh the site

MySQL, Check if a column exists in a table with SQL

Following is another way of doing it using plain PHP without the information_schema database:

$chkcol = mysql_query("SELECT * FROM `my_table_name` LIMIT 1");
$mycol = mysql_fetch_array($chkcol);
if(!isset($mycol['my_new_column']))
  mysql_query("ALTER TABLE `my_table_name` ADD `my_new_column` BOOL NOT NULL DEFAULT '0'");

Passing an array by reference in C?

Hey guys here is a simple test program that shows how to allocate and pass an array using new or malloc. Just cut, paste and run it. Have fun!

struct Coordinate
{
    int x,y;
};

void resize( int **p, int size )
{
   free( *p );
   *p = (int*) malloc( size * sizeof(int) );
}

void resizeCoord( struct Coordinate **p, int size )
{
   free( *p );
   *p = (Coordinate*) malloc( size * sizeof(Coordinate) );
}

void resizeCoordWithNew( struct Coordinate **p, int size )
{
   delete [] *p;
   *p = (struct Coordinate*) new struct Coordinate[size];
}

void SomeMethod(Coordinate Coordinates[])
{
    Coordinates[0].x++;
    Coordinates[0].y = 6;
}

void SomeOtherMethod(Coordinate Coordinates[], int size)
{
    for (int i=0; i<size; i++)
    {
        Coordinates[i].x = i;
        Coordinates[i].y = i*2;
    }
}

int main()
{
    //static array
    Coordinate tenCoordinates[10];
    tenCoordinates[0].x=0;
    SomeMethod(tenCoordinates);
    SomeMethod(&(tenCoordinates[0]));
    if(tenCoordinates[0].x - 2  == 0)
    {
        printf("test1 coord change successful\n");
    }
    else
    {
        printf("test1 coord change unsuccessful\n");
    }


   //dynamic int
   int *p = (int*) malloc( 10 * sizeof(int) );
   resize( &p, 20 );

   //dynamic struct with malloc
   int myresize = 20;
   int initSize = 10;
   struct Coordinate *pcoord = (struct Coordinate*) malloc (initSize * sizeof(struct Coordinate));
   resizeCoord(&pcoord, myresize); 
   SomeOtherMethod(pcoord, myresize);
   bool pass = true;
   for (int i=0; i<myresize; i++)
   {
       if (! ((pcoord[i].x == i) && (pcoord[i].y == i*2)))
       {        
           printf("Error dynamic Coord struct [%d] failed with (%d,%d)\n",i,pcoord[i].x,pcoord[i].y);
           pass = false;
       }
   }
   if (pass)
   {
       printf("test2 coords for dynamic struct allocated with malloc worked correctly\n");
   }


   //dynamic struct with new
   myresize = 20;
   initSize = 10;
   struct Coordinate *pcoord2 = (struct Coordinate*) new struct Coordinate[initSize];
   resizeCoordWithNew(&pcoord2, myresize); 
   SomeOtherMethod(pcoord2, myresize);
   pass = true;
   for (int i=0; i<myresize; i++)
   {
       if (! ((pcoord2[i].x == i) && (pcoord2[i].y == i*2)))
       {        
           printf("Error dynamic Coord struct [%d] failed with (%d,%d)\n",i,pcoord2[i].x,pcoord2[i].y);
           pass = false;
       }
   }
   if (pass)
   {
       printf("test3 coords for dynamic struct with new worked correctly\n");
   }


   return 0;
}

Attach Authorization header for all axios requests

There are multiple ways to achieve this. Here, I have explained the two most common approaches.

1. You can use axios interceptors to intercept any requests and add authorization headers.

// Add a request interceptor
axios.interceptors.request.use(function (config) {
    const token = store.getState().session.token;
    config.headers.Authorization =  token;

    return config;
});

2. From the documentation of axios you can see there is a mechanism available which allows you to set default header which will be sent with every request you make.

axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;

So in your case:

axios.defaults.headers.common['Authorization'] = store.getState().session.token;

If you want, you can create a self-executable function which will set authorization header itself when the token is present in the store.

(function() {
     String token = store.getState().session.token;
     if (token) {
         axios.defaults.headers.common['Authorization'] = token;
     } else {
         axios.defaults.headers.common['Authorization'] = null;
         /*if setting null does not remove `Authorization` header then try     
           delete axios.defaults.headers.common['Authorization'];
         */
     }
})();

Now you no longer need to attach token manually to every request. You can place the above function in the file which is guaranteed to be executed every time (e.g: File which contains the routes).

Hope it helps :)

How to use Console.WriteLine in ASP.NET (C#) during debug?

using System.Diagnostics;

The following will print to your output as long as the dropdown is set to 'Debug' as shown below.

Debug.WriteLine("Hello, world!");


enter image description here

Convert HTML to PDF in .NET

There's also a new web-based document generation app - DocRaptor.com. Seems easy to use, and there's a free option.

Get changes from master into branch in Git

You can also do this by running a single line.
git merge aq master

This is equivalent to

git checkout aq
git merge master

git add, commit and push commands in one?

This is perfect for command grouping.

Grouping Commands

{ list; } Placing a list of commands between curly braces causes the list to be executed in the current shell context. No subshell is created. The semicolon (or newline) following list is required.

legit(){ git add --all; git commit -m "$1"; git push origin master; }
legit 'your commit message here'

How do I customize Facebook's sharer.php

Facebook sharer.php parameters for sharing posts.

<a href="javascript: void(0);"
   data-layout="button"
   onclick="window.open('https://www.facebook.com/sharer.php?u=MyPageUrl&summary=MySummary&title=MyTitle&description=MyDescription&picture=MyYmageUrl', 'ventanacompartir', 'toolbar=0, status=0, width=650, height=450');"> Share </a>

Don't use spaces, use &nbsp.

Why can't I shrink a transaction log file, even after backup?

Put the DB back into Full mode, run the transaction log backup (not just a full backup) and then the shrink.

After it's shrunk, you can put the DB back into simple mode and it txn log will stay the same size.

remove empty lines from text file with PowerShell

Not specifically using -replace, but you get the same effect parsing the content using -notmatch and regex.

(get-content 'c:\FileWithEmptyLines.txt') -notmatch '^\s*$' > c:\FileWithNoEmptyLines.txt

How to add 'libs' folder in Android Studio?

Another strange thing. You wont see the libs folder in Android Studio, unless you have at least 1 file in the folder. So, I had to go to the libs folder using File Explorer, and then place the jar file there. Then, it showed up in Android Studio.

When and why do I need to use cin.ignore() in C++?

Short answer

Why? Because there is still whitespace (carriage returns, tabs, spaces, newline) left in the input stream.

When? When you are using some function which does not on their own ignores the leading whitespaces. Cin by default ignores and removes the leading whitespace but getline does not ignore the leading whitespace on its own.

Now a detailed answer.

Everything you input in the console is read from the standard stream stdin. When you enter something, let's say 256 in your case and press enter, the contents of the stream become 256\n. Now cin picks up 256 and removes it from the stream and \n still remaining in the stream. Now next when you enter your name, let's say Raddicus, the new contents of the stream is \nRaddicus.

Now here comes the catch. When you try to read a line using getline, if not provided any delimiter as the third argument, getline by default reads till the newline character and removes the newline character from the stream. So on calling new line, getline reads and discards \n from the stream and resulting in an empty string read in mystr which appears like getline is skipped (but it's not) because there was already an newline in the stream, getline will not prompt for input as it has already read what it was supposed to read.

Now, how does cin.ignore help here?

According to the ignore documentation extract from cplusplus.com-

istream& ignore (streamsize n = 1, int delim = EOF);

Extracts characters from the input sequence and discards them, until either n characters have been extracted, or one compares equal to delim.

The function also stops extracting characters if the end-of-file is reached. If this is reached prematurely (before either extracting n characters or finding delim), the function sets the eofbit flag.

So, cin.ignore(256, '\n');, ignores first 256 characters or all the character untill it encounters delimeter (here \n in your case), whichever comes first (here \n is the first character, so it ignores until \n is encountered).

Just for your reference, If you don't exactly know how many characters to skip and your sole purpose is to clear the stream to prepare for reading a string using getline or cin you should use cin.ignore(numeric_limits<streamsize>::max(),'\n').

Quick explanation: It ignores the characters equal to maximum size of stream or until a '\n' is encountered, whichever case happens first.

How can I turn a DataTable to a CSV?

4 lines of code:

public static string ToCSV(DataTable tbl)
{
    StringBuilder strb = new StringBuilder();

    //column headers
    strb.AppendLine(string.Join(",", tbl.Columns.Cast<DataColumn>()
        .Select(s => "\"" + s.ColumnName + "\"")));

    //rows
    tbl.AsEnumerable().Select(s => strb.AppendLine(
        string.Join(",", s.ItemArray.Select(
            i => "\"" + i.ToString() + "\"")))).ToList();

    return strb.ToString();
}

Note that the ToList() at the end is important; I need something to force an expression evaluation. If I was code golfing, I could use Min() instead.

Also note that the result will have a newline at the end because of the last call to AppendLine(). You may not want this. You can simply call TrimEnd() to remove it.

php variable in html no other way than: <?php echo $var; ?>

In a php section before the HTML section, use sprinf() to create a constant string from the variables:

$mystuff = sprinf("My name is %s and my mother's name is %s","Suzy","Caroline");

Then in the HTML section you can do whatever you like, such as:

<p>$mystuff</p> 

What is the difference between compileSdkVersion and targetSdkVersion?

compileSdkVersion

The compileSdkVersion is the version of the API the app is compiled against. This means you can use Android API features included in that version of the API (as well as all previous versions, obviously). If you try and use API 16 features but set compileSdkVersion to 15, you will get a compilation error. If you set compileSdkVersion to 16 you can still run the app on a API 15 device as long as your app's execution paths do not attempt to invoke any APIs specific to API 16.

targetSdkVersion

The targetSdkVersion has nothing to do with how your app is compiled or what APIs you can utilize. The targetSdkVersion is supposed to indicate that you have tested your app on (presumably up to and including) the version you specify. This is more like a certification or sign off you are giving the Android OS as a hint to how it should handle your app in terms of OS features.

For example, as the documentation states:

For example, setting this value to "11" or higher allows the system to apply a new default theme (Holo) to your app when running on Android 3.0 or higher...

The Android OS, at runtime, may change how your app is stylized or otherwise executed in the context of the OS based on this value. There are a few other known examples that are influenced by this value and that list is likely to only increase over time.

For all practical purposes, most apps are going to want to set targetSdkVersion to the latest released version of the API. This will ensure your app looks as good as possible on the most recent Android devices. If you do not specify the targetSdkVersion, it defaults to the minSdkVersion.

Reorder bars in geom_bar ggplot2 by value

Your code works fine, except that the barplot is ordered from low to high. When you want to order the bars from high to low, you will have to add a -sign before value:

ggplot(corr.m, aes(x = reorder(miRNA, -value), y = value, fill = variable)) + 
  geom_bar(stat = "identity")

which gives:

enter image description here


Used data:

corr.m <- structure(list(miRNA = structure(c(5L, 2L, 3L, 6L, 1L, 4L), .Label = c("mmu-miR-139-5p", "mmu-miR-1983", "mmu-miR-301a-3p", "mmu-miR-5097", "mmu-miR-532-3p", "mmu-miR-96-5p"), class = "factor"),
                         variable = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = "pos", class = "factor"),
                         value = c(7L, 75L, 70L, 5L, 10L, 47L)),
                    class = "data.frame", row.names = c("1", "2", "3", "4", "5", "6"))

How to test a variable is null in python

Testing for name pointing to None and name existing are two semantically different operations.

To check if val is None:

if val is None:
    pass  # val exists and is None

To check if name exists:

try:
    val
except NameError:
    pass  # val does not exist at all

How to check currently internet connection is available or not in android

public static   boolean isInternetConnection(Context mContext)
{
    ConnectivityManager connectivityManager = (ConnectivityManager)mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
    if(connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED ||
            connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED) {
        //we are connected to a network
        return  true;
    }
    else {
        return false;
    }
}

How to set the min and max height or width of a Frame?

A workaround - at least for the minimum size: You can use grid to manage the frames contained in root and make them follow the grid size by setting sticky='nsew'. Then you can use root.grid_rowconfigure and root.grid_columnconfigure to set values for minsize like so:

from tkinter import Frame, Tk

class MyApp():
    def __init__(self):
        self.root = Tk()

        self.my_frame_red = Frame(self.root, bg='red')
        self.my_frame_red.grid(row=0, column=0, sticky='nsew')

        self.my_frame_blue = Frame(self.root, bg='blue')
        self.my_frame_blue.grid(row=0, column=1, sticky='nsew')

        self.root.grid_rowconfigure(0, minsize=200, weight=1)
        self.root.grid_columnconfigure(0, minsize=200, weight=1)
        self.root.grid_columnconfigure(1, weight=1)

        self.root.mainloop()

if __name__ == '__main__':
    app = MyApp()

But as Brian wrote (in 2010 :D) you can still resize the window to be smaller than the frame if you don't limit its minsize.

Python Brute Force algorithm

A solution using recursion:

def brute(string, length, charset):
    if len(string) == length:
        return
    for char in charset:
        temp = string + char
        print(temp)
        brute(temp, length, charset)

Usage:

brute("", 4, "rce")

Best method to download image from url in Android

Try this code to download an image from a URL on Android:

DownloadManager downloadManager = (DownloadManager)getSystemService(Context.DOWNLOAD_SERVICE);
Uri uri = Uri.parse(imageName);
DownloadManager.Request request = new DownloadManager.Request(uri);
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
Long reference = downloadManager.enqueue(request);

How Should I Declare Foreign Key Relationships Using Code First Entity Framework (4.1) in MVC3?

If you have an Order class, adding a property that references another class in your model, for instance Customer should be enough to let EF know there's a relationship in there:

public class Order
{
    public int ID { get; set; }

    // Some other properties

    // Foreign key to customer
    public virtual Customer Customer { get; set; }
}

You can always set the FK relation explicitly:

public class Order
{
    public int ID { get; set; }

    // Some other properties

    // Foreign key to customer
    [ForeignKey("Customer")]
    public string CustomerID { get; set; }
    public virtual Customer Customer { get; set; }
}

The ForeignKeyAttribute constructor takes a string as a parameter: if you place it on a foreign key property it represents the name of the associated navigation property. If you place it on the navigation property it represents the name of the associated foreign key.

What this means is, if you where to place the ForeignKeyAttribute on the Customer property, the attribute would take CustomerID in the constructor:

public string CustomerID { get; set; }
[ForeignKey("CustomerID")]
public virtual Customer Customer { get; set; }

EDIT based on Latest Code You get that error because of this line:

[ForeignKey("Parent")]
public Patient Patient { get; set; }

EF will look for a property called Parent to use it as the Foreign Key enforcer. You can do 2 things:

1) Remove the ForeignKeyAttribute and replace it with the RequiredAttribute to mark the relation as required:

[Required]
public virtual Patient Patient { get; set; }

Decorating a property with the RequiredAttribute also has a nice side effect: The relation in the database is created with ON DELETE CASCADE.

I would also recommend making the property virtual to enable Lazy Loading.

2) Create a property called Parent that will serve as a Foreign Key. In that case it probably makes more sense to call it for instance ParentID (you'll need to change the name in the ForeignKeyAttribute as well):

public int ParentID { get; set; }

In my experience in this case though it works better to have it the other way around:

[ForeignKey("Patient")]
public int ParentID { get; set; }

public virtual Patient Patient { get; set; }

What is the difference between URL parameters and query strings?

Parameters are key-value pairs that can appear inside URL path, and start with a semicolon character (;).

Query string appears after the path (if any) and starts with a question mark character (?).

Both parameters and query string contain key-value pairs.

In a GET request, parameters appear in the URL itself:

<scheme>://<username>:<password>@<host>:<port>/<path>;<parameters>?<query>#<fragment>

In a POST request, parameters can appear in the URL itself, but also in the datastream (as known as content).

Query string is always a part of the URL.

Parameters can be buried in form-data datastream when using POST method so they may not appear in the URL. Yes a POST request can define parameters as form data and in the URL, and this is not inconsistent because parameters can have several values.

I've found no explaination for this behavior so far. I guess it might be useful sometimes to "unhide" parameters from a POST request, or even let the code handling a GET request share some parts with the code handling a POST. Of course this can work only with server code supporting parameters in a URL.

Until you get better insights, I suggest you to use parameters only in form-data datastream of POST requests.

Sources:

What Every Developer Should Know About URLs

RFC 3986

Form submit with AJAX passing form data to PHP without page refresh

JS Code

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/   libs/jquery/1.3.0/jquery.min.js">
</script>

<script type="text/javascript" >
  $(function() {
  $(".submit").click(function() {
  var time = $("#time").val();
  var date = $("#date").val();
  var dataString = 'time='+ time + '&date=' + date;

if(time=='' || date=='')
{
  $('.success').fadeOut(200).hide();
  $('.error').fadeOut(200).show();
}
else
{
  $.ajax({
    type: "POST",
    url: "post.php",
    data: dataString,
    success: function(){
     $('.success').fadeIn(200).show();
     $('.error').fadeOut(200).hide();
    }
  });
}
return false;
});
});
</script>

HTML Form

   <form>
      <input id="time" value="00:00:00.00"><br>
      <input id="date" value="0000-00-00"><br>
      <input name="submit" type="button" value="Submit">
    </form>
<span class="error" style="display:none"> Please Enter Valid Data</span>
<span class="success" style="display:none"> Form Submitted Success</span>
</div>

PHP Code

<?php
if($_POST)
{
$date=$_POST['date'];
$time=$_POST['time'];
mysql_query("SQL insert statement.......");
}else { }

?>

Taken From Here

How to get visitor's location (i.e. country) using geolocation?

You don't need to locate the user if you only need their country. You can look their IP address up in any IP-to-location service (like maxmind, ipregistry or ip2location). This will be accurate most of the time.

If you really need to get their location, you can get their lat/lng with that method, then query Google's or Yahoo's reverse geocoding service.

Given a DateTime object, how do I get an ISO 8601 date in string format?

To convert DateTime.UtcNow to a string representation of yyyy-MM-ddTHH:mm:ssZ, you can use the ToString() method of the DateTime structure with a custom formatting string. When using custom format strings with a DateTime, it is important to remember that you need to escape your seperators using single quotes.

The following will return the string represention you wanted:

DateTime.UtcNow.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'", DateTimeFormatInfo.InvariantInfo)

Refused to apply inline style because it violates the following Content Security Policy directive

As per http://content-security-policy.com/ The best place to start:

    default-src 'none'; 
    script-src 'self'; 
    connect-src 'self'; 
    img-src 'self'; 
    style-src 'self';
    font-src 'self';

Never inline styles or scripts as it undermines the purpose of CSP. You can use a stylesheet to set a style property and then use a function in a .js file to change the style property (if need be).

Remove a cookie

Just set the value of cookie to false in order to unset it,

setcookie('cookiename', false);

PS:- That's the easiest way to do it.

How do I change a TCP socket to be non-blocking?

On Linux and BSD you can directly create the socket in non-blocking mode (https://www.man7.org/linux/man-pages/man7/socket.7.html):

int fd = socket(res->ai_family, res->ai_socktype | SOCK_NONBLOCK | SOCK_CLOEXEC, res->ai_protocol);
if (fd == -1) {
    perror("socket");
    return -1;
}

When accepting connections you can use the accept4 function to directly accept new connections in non-blocking mode (https://man7.org/linux/man-pages/man2/accept.2.html):

int fd = accept4(lfd, NULL, 0, SOCK_NONBLOCK | SOCK_CLOEXEC);
if (fd == -1) {
    perror("accept4");
    return -1;
}

I don't know why the accepted answer doesn't mention this.

Output grep results to text file, need cleaner output

Redirection of program output is performed by the shell.

grep ... > output.txt

grep has no mechanism for adding blank lines between each match, but does provide options such as context around the matched line and colorization of the match itself. See the grep(1) man page for details, specifically the -C and --color options.

$_POST Array from html form

You should get the array like in $_POST['id']. So you should be able to do this:

foreach ($_POST['id'] as $key => $value) {
    echo $value . "<br />";
}

Input names should be same:

<input name='id[]' type='checkbox' value='1'>
<input name='id[]' type='checkbox' value='2'>
...

Closing pyplot windows

plt.close() will close current instance.

plt.close(2) will close figure 2

plt.close(plot1) will close figure with instance plot1

plt.close('all') will close all fiures

Found here.

Remember that plt.show() is a blocking function, so in the example code you used above, plt.close() isn't being executed until the window is closed, which makes it redundant.

You can use plt.ion() at the beginning of your code to make it non-blocking, although this has other implications.

EXAMPLE

After our discussion in the comments, I've put together a bit of an example just to demonstrate how the plot functionality can be used.

Below I create a plot:

fig = plt.figure(figsize=plt.figaspect(0.75))
ax = fig.add_subplot(1, 1, 1)
....
par_plot, = plot(x_data,y_data, lw=2, color='red')

In this case, ax above is a handle to a pair of axes. Whenever I want to do something to these axes, I can change my current set of axes to this particular set by calling axes(ax).

par_plot is a handle to the line2D instance. This is called an artist. If I want to change a property of the line, like change the ydata, I can do so by referring to this handle.

I can also create a slider widget by doing the following:

axsliderA = axes([0.12, 0.85, 0.16, 0.075])
sA = Slider(axsliderA, 'A', -1, 1.0, valinit=0.5)
sA.on_changed(update)

The first line creates a new axes for the slider (called axsliderA), the second line creates a slider instance sA which is placed in the axes, and the third line specifies a function to call when the slider value changes (update).

My update function could look something like this:

def update(val):
    A = sA.val
    B = sB.val
    C = sC.val
    y_data = A*x_data*x_data + B*x_data + C
    par_plot.set_ydata(y_data)
    draw()

The par_plot.set_ydata(y_data) changes the ydata property of the Line2D object with the handle par_plot.

The draw() function updates the current set of axes.

Putting it all together:

from pylab import *
import matplotlib.pyplot as plt
import numpy

def update(val):
    A = sA.val
    B = sB.val
    C = sC.val
    y_data = A*x_data*x_data + B*x_data + C
    par_plot.set_ydata(y_data)
    draw()


x_data = numpy.arange(-100,100,0.1);

fig = plt.figure(figsize=plt.figaspect(0.75))
ax = fig.add_subplot(1, 1, 1)
subplots_adjust(top=0.8)

ax.set_xlim(-100, 100);
ax.set_ylim(-100, 100);
ax.set_xlabel('X')
ax.set_ylabel('Y')

axsliderA = axes([0.12, 0.85, 0.16, 0.075])
sA = Slider(axsliderA, 'A', -1, 1.0, valinit=0.5)
sA.on_changed(update)

axsliderB = axes([0.43, 0.85, 0.16, 0.075])
sB = Slider(axsliderB, 'B', -30, 30.0, valinit=2)
sB.on_changed(update)

axsliderC = axes([0.74, 0.85, 0.16, 0.075])
sC = Slider(axsliderC, 'C', -30, 30.0, valinit=1)
sC.on_changed(update)

axes(ax)
A = 1;
B = 2;
C = 1;
y_data = A*x_data*x_data + B*x_data + C;

par_plot, = plot(x_data,y_data, lw=2, color='red')

show()

A note about the above: When I run the application, the code runs sequentially right through (it stores the update function in memory, I think), until it hits show(), which is blocking. When you make a change to one of the sliders, it runs the update function from memory (I think?).

This is the reason why show() is implemented in the way it is, so that you can change values in the background by using functions to process the data.

Dropping Unique constraint from MySQL table

You can DROP a unique constraint from a table using phpMyAdmin as requested as shown in the table below. A unique constraint has been placed on the Wingspan field. The name of the constraint is the same as the field name, in this instance.

alt text

HTML/JavaScript: Simple form validation on submit

You need to return the validating function. Something like:

onsubmit="return validateForm();"

Then the validating function should return false on errors. If everything is OK return true. Remember that the server has to validate as well.

Hibernate throws MultipleBagFetchException - cannot simultaneously fetch multiple bags

We tried Set instead of List and it is a nightmare: when you add two new objects, equals() and hashCode() fail to distinguish both of them ! Because they don't have any id.

typical tools like Eclipse generate that kind of code from Database tables:

@Override
public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + ((id == null) ? 0 : id.hashCode());
    return result;
}

You may also read this article that explains properly how messed up JPA/Hibernate is. After reading this, I think this is the last time I use any ORM in my life.

I've also encounter Domain Driven Design guys that basically say ORM are a terrible thing.

Gradients in Internet Explorer 9

Looks like I'm a little late to the party, but here's an example for some of the top browsers:

/* IE10 */ 
background-image: -ms-linear-gradient(top, #444444 0%, #999999 100%);

/* Mozilla Firefox */ 
background-image: -moz-linear-gradient(top, #444444 0%, #999999 100%);

/* Opera */ 
background-image: -o-linear-gradient(top, #444444 0%, #999999 100%);

/* Webkit (Safari/Chrome 10) */ 
background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0, #444444), color-stop(1, #999999));

/* Webkit (Chrome 11+) */ 
background-image: -webkit-linear-gradient(top, #444444 0%, #999999 100%);

/* Proposed W3C Markup */ 
background-image: linear-gradient(top, #444444 0%, #999999 100%);

Source: http://ie.microsoft.com/testdrive/Graphics/CSSGradientBackgroundMaker/Default.html

Note: all of these browsers also support rgb/rgba in place of hexadecimal notation.

Server.MapPath("."), Server.MapPath("~"), Server.MapPath(@"\"), Server.MapPath("/"). What is the difference?

Server.MapPath specifies the relative or virtual path to map to a physical directory.

  • Server.MapPath(".")1 returns the current physical directory of the file (e.g. aspx) being executed
  • Server.MapPath("..") returns the parent directory
  • Server.MapPath("~") returns the physical path to the root of the application
  • Server.MapPath("/") returns the physical path to the root of the domain name (is not necessarily the same as the root of the application)

An example:

Let's say you pointed a web site application (http://www.example.com/) to

C:\Inetpub\wwwroot

and installed your shop application (sub web as virtual directory in IIS, marked as application) in

D:\WebApps\shop

For example, if you call Server.MapPath() in following request:

http://www.example.com/shop/products/GetProduct.aspx?id=2342

then:

  • Server.MapPath(".")1 returns D:\WebApps\shop\products
  • Server.MapPath("..") returns D:\WebApps\shop
  • Server.MapPath("~") returns D:\WebApps\shop
  • Server.MapPath("/") returns C:\Inetpub\wwwroot
  • Server.MapPath("/shop") returns D:\WebApps\shop

If Path starts with either a forward slash (/) or backward slash (\), the MapPath() returns a path as if Path was a full, virtual path.

If Path doesn't start with a slash, the MapPath() returns a path relative to the directory of the request being processed.

Note: in C#, @ is the verbatim literal string operator meaning that the string should be used "as is" and not be processed for escape sequences.

Footnotes

  1. Server.MapPath(null) and Server.MapPath("") will produce this effect too.

Spring MVC Controller redirect using URL parameters instead of in response

Hey you can just do one simple thing instead of using model to send parameter use HttpServletRequest object and do this

HttpServletRequest request;
request.setAttribute("param", "value")

now your parametrs will not be shown in your url header hope it works :)

Android basics: running code in the UI thread

The answer by Pomber is acceptable, however I'm not a big fan of creating new objects repeatedly. The best solutions are always the ones that try to mitigate memory hog. Yes, there is auto garbage collection but memory conservation in a mobile device falls within the confines of best practice. The code below updates a TextView in a service.

TextViewUpdater textViewUpdater = new TextViewUpdater();
Handler textViewUpdaterHandler = new Handler(Looper.getMainLooper());
private class TextViewUpdater implements Runnable{
    private String txt;
    @Override
    public void run() {
        searchResultTextView.setText(txt);
    }
    public void setText(String txt){
        this.txt = txt;
    }

}

It can be used from anywhere like this:

textViewUpdater.setText("Hello");
        textViewUpdaterHandler.post(textViewUpdater);

ORA-06508: PL/SQL: could not find program unit being called

I suspect you're only reporting the last error in a stack like this:

ORA-04068: existing state of packages has been discarded
ORA-04061: existing state of package body "schema.package" has been invalidated
ORA-04065: not executed, altered or dropped package body "schema.package"
ORA-06508: PL/SQL: could not find program unit being called: "schema.package"

If so, that's because your package is stateful:

The values of the variables, constants, and cursors that a package declares (in either its specification or body) comprise its package state. If a PL/SQL package declares at least one variable, constant, or cursor, then the package is stateful; otherwise, it is stateless.

When you recompile the state is lost:

If the body of an instantiated, stateful package is recompiled (either explicitly, with the "ALTER PACKAGE Statement", or implicitly), the next invocation of a subprogram in the package causes Oracle Database to discard the existing package state and raise the exception ORA-04068.

After PL/SQL raises the exception, a reference to the package causes Oracle Database to re-instantiate the package, which re-initializes it...

You can't avoid this if your package has state. I think it's fairly rare to really need a package to be stateful though, so you should revisit anything you have declared in the package, but outside a function or procedure, to see if it's really needed at that level. Since you're on 10g though, that includes constants, not just variables and cursors.

But the last paragraph from the quoted documentation means that the next time you reference the package in the same session, you won't get the error and it will work as normal (until you recompile again).

Counting in a FOR loop using Windows Batch script

for a = 1 to 100 step 1

Command line in Windows . Please use %%a if running in Batch file.

    for /L %a in (1,1,100) Do echo %a 

Set background colour of cell to RGB value of data in cell

Cells cannot be changed from within a VBA function used as a worksheet formula. Except via this workaround...

Put this function into a new module:

Function SetRGB(x As Range, R As Byte, G As Byte, B As Byte)
  On Error Resume Next
  x.Interior.Color = RGB(R, G, B)
  x.Font.Color = IIf(0.299 * R + 0.587 * G + 0.114 * B < 128, vbWhite, vbBlack)
End Function

Then use this formula in your sheet, for example in cell D2:

=HYPERLINK(SetRGB(D2;A2;B2;C2);"HOVER!")

Once you hover the mouse over the cell (try it!), the background color updates to the RGB taken from cells A2 to C2. The font color is a contrasting white or black.

Adding values to an array in java

No, you're re-initializing x in every loop. Change to:

int[] tall = new int[28123];
int x = 0;

for (int j = 1;j<=28123;j++){
    tall[x] = j;
    x++;
}

Or, even better (since x is always equal to j-1):

int[] tall = new int[28123];

for (int j = 1;j<=28123;j++){
    tall[j-1] = j;
}

hardcoded string "row three", should use @string resource

You can go to Design mode and select "Fix" at the bottom of the warning. Then a pop up will appear (seems like it's going to register the new string) and voila, the error is fixed.

Resolve host name to an ip address

Try tracert to resolve the hostname. IE you have Ip address 8.8.8.8 so you would use; tracert 8.8.8.8

Subtract a value from every number in a list in Python?

If are you working with numbers a lot, you might want to take a look at NumPy. It lets you perform all kinds of operation directly on numerical arrays. For example:

>>> import numpy
>>> array = numpy.array([49, 51, 53, 56])
>>> array - 13
array([36, 38, 40, 43])

How to grep with a list of words

You need to use the option -f:

$ grep -f A B

The option -F does a fixed string search where as -f is for specifying a file of patterns. You may want both if the file only contains fixed strings and not regexps.

$ grep -Ff A B

You may also want the -w option for matching whole words only:

$ grep -wFf A B

Read man grep for a description of all the possible arguments and what they do.

Why doesn't JUnit provide assertNotEquals methods?

I agree totally with the OP point of view. Assert.assertFalse(expected.equals(actual)) is not a natural way to express an inequality.
But I would argue that further than Assert.assertEquals(), Assert.assertNotEquals() works but is not user friendly to document what the test actually asserts and to understand/debug as the assertion fails.
So yes JUnit 4.11 and JUnit 5 provides Assert.assertNotEquals() (Assertions.assertNotEquals() in JUnit 5) but I really avoid using them.

As alternative, to assert the state of an object I general use a matcher API that digs into the object state easily, that document clearly the intention of the assertions and that is very user friendly to understand the cause of the assertion failure.

Here is an example.
Suppose I have an Animal class which I want to test the createWithNewNameAndAge() method, a method that creates a new Animal object by changing its name and its age but by keeping its favorite food.
Suppose I use Assert.assertNotEquals() to assert that the original and the new objects are different.
Here is the Animal class with a flawed implementation of createWithNewNameAndAge() :

public class Animal {

    private String name;
    private int age;
    private String favoriteFood;

    public Animal(String name, int age, String favoriteFood) {
        this.name = name;
        this.age = age;
        this.favoriteFood = favoriteFood;
    }

    // Flawed implementation : use this.name and this.age to create the 
    // new Animal instead of using the name and age parameters
    public Animal createWithNewNameAndAge(String name, int age) {
        return new Animal(this.name, this.age, this.favoriteFood);
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    public String getFavoriteFood() {
        return favoriteFood;
    }

    @Override
    public String toString() {
        return "Animal [name=" + name + ", age=" + age + ", favoriteFood=" + favoriteFood + "]";
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + age;
        result = prime * result + ((favoriteFood == null) ? 0 : favoriteFood.hashCode());
        result = prime * result + ((name == null) ? 0 : name.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (!(obj instanceof Animal)) return false;

        Animal other = (Animal) obj;
        return age == other.age && favoriteFood.equals(other.favoriteFood) &&
                name.equals(other.name);
    }

}

JUnit 4.11+ (or JUnit 5) both as test runner and assertion tool

@Test
void assertListNotEquals_JUnit_way() {
    Animal scoubi = new Animal("scoubi", 10, "hay");
    Animal littleScoubi = scoubi.createWithNewNameAndAge("little scoubi", 1);
    Assert.assertNotEquals(scoubi, littleScoubi);
}

The test fails as expected but the cause provided to the developer is really not helpful. It just says that the values should be different and output the toString() result invoked on the actual Animal parameter :

java.lang.AssertionError: Values should be different. Actual: Animal

[name=scoubi, age=10, favoriteFood=hay]

at org.junit.Assert.fail(Assert.java:88)

Ok the objects are not equals. But where is the problem ?
Which field is not correctly valued in the tested method ? One ? Two ? All of them ?
To discover it you have to dig in the createWithNewNameAndAge() implementation/use a debugger while the testing API would be much more friendly if it would make for us the differential between which is expected and which is gotten.


JUnit 4.11 as test runner and a test Matcher API as assertion tool

Here the same scenario of test but that uses AssertJ (an excellent test matcher API) to make the assertion of the Animal state: :

import org.assertj.core.api.Assertions;

@Test
void assertListNotEquals_AssertJ() {
    Animal scoubi = new Animal("scoubi", 10, "hay");
    Animal littleScoubi = scoubi.createWithNewNameAndAge("little scoubi", 1);
    Assertions.assertThat(littleScoubi)
              .extracting(Animal::getName, Animal::getAge, Animal::getFavoriteFood)
              .containsExactly("little scoubi", 1, "hay");
}

Of course the test still fails but this time the reason is clearly stated :

java.lang.AssertionError:

Expecting:

<["scoubi", 10, "hay"]>

to contain exactly (and in same order):

<["little scoubi", 1, "hay"]>

but some elements were not found:

<["little scoubi", 1]>

and others were not expected:

<["scoubi", 10]>

at junit5.MyTest.assertListNotEquals_AssertJ(MyTest.java:26)

We can read that for Animal::getName, Animal::getAge, Animal::getFavoriteFood values of the returned Animal, we expect to have these value :

"little scoubi", 1, "hay" 

but we have had these values :

"scoubi", 10, "hay"

So we know where investigate : name and age are not correctly valued. Additionally, the fact of specifying the hay value in the assertion of Animal::getFavoriteFood() allows also to more finely assert the returned Animal. We want that the objects be not the same for some properties but not necessarily for every properties.
So definitely, using a matcher API is much more clear and flexible.

Latex Multiple Linebreaks

Line break accepts an optional argument in brackets, a vertical length:

line 1
\\[4in]
line 2

To make this more scalable with respect to font size, you can use other lengths, such as \\[3\baselineskip], or \\[3ex].

How can I load the contents of a text file into a batch file variable?

If your set command supports the /p switch, then you can pipe input that way.

set /p VAR1=<test.txt
set /? |find "/P"

The /P switch allows you to set the value of a variable to a line of input entered by the user. Displays the specified promptString before reading the line of input. The promptString can be empty.

This has the added benefit of working for un-registered file types (which the accepted answer does not).

HQL ERROR: Path expected for join

select u from UserGroup ug inner join ug.user u 
where ug.group_id = :groupId 
order by u.lastname

As a named query:

@NamedQuery(
  name = "User.findByGroupId",
  query =
    "SELECT u FROM UserGroup ug " +
    "INNER JOIN ug.user u WHERE ug.group_id = :groupId ORDER BY u.lastname"
)

Use paths in the HQL statement, from one entity to the other. See the Hibernate documentation on HQL and joins for details.

How to store image in SQL Server database tables column

give this a try,

insert into tableName (ImageColumn) 
SELECT BulkColumn 
FROM Openrowset( Bulk 'image..Path..here', Single_Blob) as img

INSERTING

enter image description here

REFRESHING THE TABLE

enter image description here

How to display request headers with command line curl

The verbose option is handy, but if you want to see everything that curl does (including the HTTP body that is transmitted, and not just the headers), I suggest using one of the below options:

  • --trace-ascii - # stdout
  • --trace-ascii output_file.txt # file

Undefined reference to pow( ) in C, despite including math.h

You need to link with the math library:

gcc -o sphere sphere.c -lm

The error you are seeing: error: ld returned 1 exit status is from the linker ld (part of gcc that combines the object files) because it is unable to find where the function pow is defined.

Including math.h brings in the declaration of the various functions and not their definition. The def is present in the math library libm.a. You need to link your program with this library so that the calls to functions like pow() are resolved.

Bootstrap 4 navbar color

You can just use "!important" to get your custom color

.navbar {
 background-color: yourcolor !important;
 }

how to parse xml to java object?

For performing Unmarshall using JAXB:

1) Convert given XML to XSD(by yourself or by online convertor),

2) Create a JAXB project in eclipse,

3) Create XSD file and paste that converted XSD content in it,

4) Right click on **XSD file--> Generate--> JAXB Classes-->follow the instructions(this will create all nessasary .java files in src, i.e., one package-info, object factory and pojo class),

5) Create another .java file in src to operate unmarshall operation, and run it.

Happy Coding !!

How get data from material-ui TextField, DropDownMenu components?

Here's the simplest solution i came up with, we get the value of the input created by material-ui textField :

      create(e) {
        e.preventDefault();
        let name = this.refs.name.input.value;
        alert(name);
      }

      constructor(){
        super();
        this.create = this.create.bind(this);
      }

      render() {
        return (
              <form>
                <TextField ref="name" hintText="" floatingLabelText="Your name" /><br/>
                <RaisedButton label="Create" onClick={this.create} primary={true} />
              </form>
        )}

hope this helps.

UnsatisfiedDependencyException: Error creating bean with name 'entityManagerFactory'

Well, you're getting a java.lang.NoClassDefFoundError. In your pom.xml, hibernate-core version is 3.3.2.GA and declared after hibernate-entitymanager, so it prevails. You can remove that dependency, since will be inherited version 3.6.7.Final from hibernate-entitymanager.

You're using spring-boot as parent, so no need to declare version of some dependencies, since they are managed by spring-boot.

Also, hibernate-commons-annotations is inherited from hibernate-entitymanager and hibernate-annotations is an old version of hibernate-commons-annotations, you can remove both.

Finally, your pom.xml can look like this:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.elsys.internetprogramming.trafficspy.server</groupId>
    <artifactId>TrafficSpyService</artifactId>
    <version>0.1.0</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.2.3.RELEASE</version>
    </parent>

    <dependencies>
        <!-- Spring -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cloud-connectors</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <dependency>
            <groupId>org.eclipse.persistence</groupId>
            <artifactId>javax.persistence</artifactId>
            <version>2.0.0</version>
        </dependency>

        <!-- Hibernate -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
        </dependency>
        <dependency>
            <groupId>commons-dbcp</groupId>
            <artifactId>commons-dbcp</artifactId>
        </dependency>
        <dependency>
            <groupId>commons-pool</groupId>
            <artifactId>commons-pool</artifactId>
        </dependency>

        <!-- MySQL -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
    </dependencies>

    <properties>
        <java.version>1.7</java.version>
    </properties>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

    <repositories>
        <repository>
            <id>spring-releases</id>
            <url>https://repo.spring.io/libs-release</url>
        </repository>

        <repository>
            <id>codehaus</id>
            <url>http://repository.codehaus.org/org/codehaus</url>
        </repository>
    </repositories>
    <pluginRepositories>
        <pluginRepository>
            <id>spring-releases</id>
            <url>https://repo.spring.io/libs-release</url>
        </pluginRepository>
    </pluginRepositories>

</project>

Let me know if you have a problem.

What does if [ $? -eq 0 ] mean for shell scripts?

It is an extremely overused way to check for the success/failure of a command. Typically, the code snippet you give would be refactored as:

if grep -e ERROR ${LOG_DIR_PATH}/${LOG_NAME} > /dev/null; then
   ...
fi

(Although you can use 'grep -q' in some instances instead of redirecting to /dev/null, doing so is not portable. Many implementations of grep do not support the -q option, so your script may fail if you use it.)

How to parse XML and count instances of a particular node attribute?

#If the xml is in the form of a string as shown below then
from lxml  import etree, objectify
'''sample xml as a string with a name space {http://xmlns.abc.com}'''
message =b'<?xml version="1.0" encoding="UTF-8"?>\r\n<pa:Process xmlns:pa="http://xmlns.abc.com">\r\n\t<pa:firsttag>SAMPLE</pa:firsttag></pa:Process>\r\n'  # this is a sample xml which is a string


print('************message coversion and parsing starts*************')

message=message.decode('utf-8') 
message=message.replace('<?xml version="1.0" encoding="UTF-8"?>\r\n','') #replace is used to remove unwanted strings from the 'message'
message=message.replace('pa:Process>\r\n','pa:Process>')
print (message)

print ('******Parsing starts*************')
parser = etree.XMLParser(remove_blank_text=True) #the name space is removed here
root = etree.fromstring(message, parser) #parsing of xml happens here
print ('******Parsing completed************')


dict={}
for child in root: # parsed xml is iterated using a for loop and values are stored in a dictionary
    print(child.tag,child.text)
    print('****Derving from xml tree*****')
    if child.tag =="{http://xmlns.abc.com}firsttag":
        dict["FIRST_TAG"]=child.text
        print(dict)


### output
'''************message coversion and parsing starts*************
<pa:Process xmlns:pa="http://xmlns.abc.com">

    <pa:firsttag>SAMPLE</pa:firsttag></pa:Process>
******Parsing starts*************
******Parsing completed************
{http://xmlns.abc.com}firsttag SAMPLE
****Derving from xml tree*****
{'FIRST_TAG': 'SAMPLE'}'''

PHP file_get_contents() returns "failed to open stream: HTTP request failed!"

You basically are required to send some information with the request.

Try this,

$opts = array('http'=>array('header' => "User-Agent:MyAgent/1.0\r\n")); 
//Basically adding headers to the request
$context = stream_context_create($opts);
$html = file_get_contents($url,false,$context);
$html = htmlspecialchars($html);

This worked out for me

Run bash command on jenkins pipeline

According to this document, you should be able to do it like so:

node {
    sh "#!/bin/bash \n" + 
       "echo \"Hello from \$SHELL\""
}

Could not reliably determine the server's fully qualified domain name

  1. sudo vim /etc/apache2/httpd.conf
  2. Insert the following line at the httpd.conf: ServerName localhost
  3. Just restart the Apache: sudo /etc/init.d/apache2 restart

Windows 7 - Add Path

Try this in cmd:

cd address_of_sumatrapdf.exe_file && sumatrapdf.exe

Where you should put the address of your .exe file instead of adress_of_sumatrapdf.exe_file.

What is a clean, Pythonic way to have multiple constructors in Python?

This is a pretty clean way I guess and tricky

class A(object):
    def __init__(self, e, f, g):

        self.__dict__.update({k: v for k,v in locals().items() if k!='self'})
    def bc(self):
        print(self.f)


k = A(e=5, f=6, g=12)
k.bc() # >>>6

C++: Converting Hexadecimal to Decimal

    std::cout << "Enter decimal number: " ;
    std::cin >> input ;

    std::cout << "0x" << std::hex << input << '\n' ;

if your adding a input that can be a boolean or float or int it will be passed back in the int main function call...

With function templates, based on argument types, C generates separate functions to handle each type of call appropriately. All function template definitions begin with the keyword template followed by arguments enclosed in angle brackets < and >. A single formal parameter T is used for the type of data to be tested.

Consider the following program where the user is asked to enter an integer and then a float, each uses the square function to determine the square. With function templates, based on argument types, C generates separate functions to handle each type of call appropriately. All function template definitions begin with the keyword template followed by arguments enclosed in angle brackets < and >. A single formal parameter T is used for the type of data to be tested.

Consider the following program where the user is asked to enter an integer and then a float, each uses the square function to determine the square.

#include <iostream>
 using namespace std;
template <class T>      // function template
T square(T);    /* returns a value of type T and accepts                  type T     (int or float or whatever) */
  void main()
{
int x, y;
float w, z;
cout << "Enter a integer:  ";
cin >> x;
y = square(x);
cout << "The square of that number is:  " << y << endl;
cout << "Enter a float:  ";
cin >> w;
z = square(w);
cout << "The square of that number is:  " << z << endl;
}

template <class T>      // function template
T square(T u) //accepts a parameter u of type T (int or float)
{
return u * u;
}

Here is the output:

Enter a integer:  5
The square of that number is:  25
Enter a float:  5.3
The square of that number is:  28.09

Constructor overloading in Java - best practice

If you have a very complex class with a lot of options of which only some combinations are valid, consider using a Builder. Works very well both codewise but also logically.

The Builder is a nested class with methods only designed to set fields, and then the ComplexClass constructor only takes such a Builder as an argument.


Edit: The ComplexClass constructor can ensure that the state in the Builder is valid. This is very hard to do if you just use setters on ComplexClass.

Start / Stop a Windows Service from a non-Administrator user account

There is a free GUI Tool ServiceSecurityEditor

Which allows you to edit Windows Service permissions. I have successfully used it to give a non-Administrator user the rights to start and stop a service.

I had used "sc sdset" before I knew about this tool.

ServiceSecurityEditor feels like cheating, it's that easy :)

Use placeholders in yaml

With Yglu Structural Templating, your example can be written:

foo: !()
  !? $.propname: 
     type: number 
     default: !? $.default

bar:
  !apply .foo: 
    propname: "some_prop"
    default: "some default"

Disclaimer: I am the author or Yglu.

Writing .csv files from C++

You must ";" separator, CSV => Comma Separator Value

 ofstream Morison_File ("linear_wave_loading.csv");         //Opening file to print info to
    Morison_File << "'Time'; 'Force(N/m)' " << endl;          //Headings for file
    for (t = 0; t <= 20; t++) {
      u = sin(omega * t);
      du = cos(omega * t); 
      F = (0.5 * rho * C_d * D * u * fabs(u)) + rho * Area * C_m * du; 

      cout << "t = " << t << "\t\tF = " << F << endl;
      Morison_File << t << ";" << F;

    }

     Morison_File.close();

Field 'browser' doesn't contain a valid alias configuration

Changed my entry to

entry: path.resolve(__dirname, './src/js/index.js'),

and it worked.

Export to xls using angularjs

A cheap way to do this is to use Angular to generate a <table> and use FileSaver.js to output the table as an .xls file for the user to download. Excel will be able to open the HTML table as a spreadsheet.

<div id="exportable">
    <table width="100%">
        <thead>
            <tr>
                <th>Name</th>
                <th>Email</th>
                <th>DoB</th>
            </tr>
        </thead>
        <tbody>
            <tr ng-repeat="item in items">
                <td>{{item.name}}</td>
                <td>{{item.email}}</td>
                <td>{{item.dob | date:'MM/dd/yy'}}</td>
            </tr>
        </tbody>
    </table>
</div>

Export call:

var blob = new Blob([document.getElementById('exportable').innerHTML], {
        type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8"
    });
    saveAs(blob, "Report.xls");
};

Demo: http://jsfiddle.net/TheSharpieOne/XNVj3/1/

Updated demo with checkbox functionality and question's data. Demo: http://jsfiddle.net/TheSharpieOne/XNVj3/3/

how to get docker-compose to use the latest image from repository

Since 2020-05-07, the docker-compose spec also defines the "pull_policy" property for a service:

version: '3.7'

services:
  my-service:
    image: someimage/somewhere
    pull_policy: always

The docker-compose spec says:

pull_policy defines the decisions Compose implementations will make when it starts to pull images.

Possible values are (tl;dr, check spec for more details):

  • always: always pull
  • never: don't pull (breaks if the image can not be found)
  • missing: pulls if the image is not cached
  • build: always build or rebuild

How can I turn a JSONArray into a JSONObject?

Typically, a Json object would contain your values (including arrays) as named fields within. So, something like:

JSONObject jo = new JSONObject();
JSONArray ja = new JSONArray();
// populate the array
jo.put("arrayName",ja);

Which in JSON will be {"arrayName":[...]}.

iOS Remote Debugging

Open Safari Desktop iOS

Develop -> Responsive Design Mode

Click "Other" under device

Paste this: Mozilla/5.0 (iPad; CPU OS 10_2_1 like Mac OS X) AppleWebKit/602.1.50 (KHTML, like Gecko) CriOS/56.0.2924.79 Mobile/14D27 Safari/602.1

Use Safari inspect tools.

How to execute an Oracle stored procedure via a database link

The syntax is

EXEC mySchema.myPackage.myProcedure@myRemoteDB( 'someParameter' );

How to upgrade rubygems

I wouldn't use the debian packages, have a look at RVM or Rbenv.

How do I move a file (or folder) from one folder to another in TortoiseSVN?

To move a file or set of files using Tortoise SVN, right-click-and-drag the target files to their destination and release the right mouse button. The popup menu will have a SVN move versioned files here option.

Note that the destination folder must have already been added to the repository for the SVN move versioned files here option to appear.

Genymotion, "Unable to load VirtualBox engine." on Mavericks. VBox is setup correctly

Uninstall VirtualBox with uninstaller (it comes with dmg), then install VirtualBox again. This has solved that issue for me.

Unzip a file with php

Use below PHP code, with file name in the URL param "name"

<?php

$fileName = $_GET['name'];

if (isset($fileName)) {


    $zip = new ZipArchive;
    $res = $zip->open($fileName);
    if ($res === TRUE) {
      $zip->extractTo('./');
      $zip->close();
      echo 'Extracted file "'.$fileName.'"';
    } else {
      echo 'Cannot find the file name "'.$fileName.'" (the file name should include extension (.zip, ...))';
    }
}
else {
    echo 'Please set file name in the "name" param';
}

?>

Immutable vs Mutable types

I haven't read all the answers, but the selected answer is not correct and I think the author has an idea that being able to reassign a variable means that whatever datatype is mutable. That is not the case. Mutability has to do with passing by reference rather than passing by value.

Lets say you created a List

a = [1,2]

If you were to say:

b = a
b[1] = 3

Even though you reassigned a value on B, it will also reassign the value on a. Its because when you assign "b = a". You are passing the "Reference" to the object rather than a copy of the value. This is not the case with strings, floats etc. This makes list, dictionaries and the likes mutable, but booleans, floats etc immutable.

How to prevent robots from automatically filling up a form?

With the emergence of headless browsers (like phantomjs) which can emulate anything, you can't suppose that :

  • spam bots do not use javascript,
  • you can track mouse events to detect bot,
  • they won't see that a field is visually hidden,
  • they won't wait a given time before submitting.

If that used to be true, it is no longer true.

If you wan't an user friendly solution, just give them a beautiful "i am a spammer" submit button:

 <input type="submit" name="ignore" value="I am a spammer!" />
 <input type="image" name="accept" value="submit.png" alt="I am not a spammer" />

Of course you can play with two image input[type=image] buttons, changing the order after each load, the text alternatives, the content of the images (and their size) or the name of the buttons; which will require some server work.

 <input type="image" name="random125454548" value="random125454548.png"
      alt="I perfectly understand that clicking on this link will send the
      e-mail to the expected person" />
 <input type="image" name="random125452548" value="random125452548.png"
      alt="I really want to cancel the submission of this form" />

For accessibility reasons, you have to put a correct textual alternative, but I think that a long sentence is better for screenreaders users than being considered as a bot.

Additional note: those examples illustrate that understanding english (or any language), and having to make a simple choice, is harder for a spambot than : waiting 10 seconds, handling CSS or javascript, knowing that a field is hidden, emulating mouse move or emulating keyboard typing, ...

What does PermGen actually stand for?

Permanent Generation. See the java GC tuning guide for more details on the garbage collector.

What exactly does the "u" do? "git push -u origin master" vs "git push origin master"

The key is "argument-less git-pull". When you do a git pull from a branch, without specifying a source remote or branch, git looks at the branch.<name>.merge setting to know where to pull from. git push -u sets this information for the branch you're pushing.

To see the difference, let's use a new empty branch:

$ git checkout -b test

First, we push without -u:

$ git push origin test
$ git pull
You asked me to pull without telling me which branch you
want to merge with, and 'branch.test.merge' in
your configuration file does not tell me, either. Please
specify which branch you want to use on the command line and
try again (e.g. 'git pull <repository> <refspec>').
See git-pull(1) for details.

If you often merge with the same branch, you may want to
use something like the following in your configuration file:

    [branch "test"]
    remote = <nickname>
    merge = <remote-ref>

    [remote "<nickname>"]
    url = <url>
    fetch = <refspec>

See git-config(1) for details.

Now if we add -u:

$ git push -u origin test
Branch test set up to track remote branch test from origin.
Everything up-to-date
$ git pull
Already up-to-date.

Note that tracking information has been set up so that git pull works as expected without specifying the remote or branch.

Update: Bonus tips:

  • As Mark mentions in a comment, in addition to git pull this setting also affects default behavior of git push. If you get in the habit of using -u to capture the remote branch you intend to track, I recommend setting your push.default config value to upstream.
  • git push -u <remote> HEAD will push the current branch to a branch of the same name on <remote> (and also set up tracking so you can do git push after that).

md-table - How to update the column width

I'm using FlexLayout to update the column width according query media that FlexLayout gives us.

fxFlex="30" fxFlex.gt-xs="15" fxFlex.gt-sm="20" fxFlex.gt-md="25"

means that this column will use the 30% of the row width by default, when gt-xs @mediaQuery is met, the new width will be 15% and similar behavior for other conditions

<!-- CURRENTBALANCE COLUMN-->
  <ng-container cdkColumnDef="balance_2">
    <mat-header-cell fxFlex="30" fxFlex.gt-xs="15" fxFlex.gt-sm="20"
       fxFlex.gt-md="25" fxLayout="row" fxLayoutAlign="center center"
       *cdkHeaderCellDef>{{ balanceTable.datesHeaders[2] }}</mat-header-cell>
    <mat-cell fxFlex="30" fxFlex.gt-xs="15" fxFlex.gt-sm="20" fxFlex.gt-md="25" 
      *cdkCellDef="let eventTop">
      <div fxLayout="column" fxLayoutAlign="center center">
        <!-- CELL_CONTENT-->
      </div>
    </mat-cell>
  </ng-container>
<!-- CURRENTBALANCE COLUMN-->

Read more about FlexLayout and @MediaQueries at https://github.com/angular/flex-layout/wiki/Responsive-API

Auto increment primary key in SQL Server Management Studio 2012

You have to expand the Identity section to expose increment and seed.

enter image description here

Edit: I assumed that you'd have an integer datatype, not char(10). Which is reasonable I'd say and valid when I posted this answer

I'm getting an error "invalid use of incomplete type 'class map'

Your first usage of Map is inside a function in the combat class. That happens before Map is defined, hence the error.

A forward declaration only says that a particular class will be defined later, so it's ok to reference it or have pointers to objects, etc. However a forward declaration does not say what members a class has, so as far as the compiler is concerned you can't use any of them until Map is fully declared.

The solution is to follow the C++ pattern of the class declaration in a .h file and the function bodies in a .cpp. That way all the declarations appear before the first definitions, and the compiler knows what it's working with.

How to programmatically click a button in WPF?

When using the MVVM Command pattern for Button function (recommended practice), a simple way to trigger the effect of the Button is as follows:

someButton.Command.Execute(someButton.CommandParameter);

This will use the Command object which the button triggers and pass the CommandParameter defined by the XAML.

java.lang.ClassNotFoundException: javax.servlet.jsp.jstl.core.Config

I had the same problem. Go to Project Properties -> Deployment Assemplbly and add jstl jar

How to put space character into a string name in XML?

As already mentioned the correct way to have a space in an XML file is by using \u0020 which is the unicode character for a space.

Example:

<string name="spelatonertext3">-4,\u00205,\u0020-5,\u00206,\u0020-6</string>

Other suggestions have said to use &#160; or &#032; but there is two downsides to this. The first downside is that these are ASCII characters so you are relying on something like a TextView to parse them. The second downside is that &#160; can sometimes cause strange wrapping in TextViews.

No route matches "/users/sign_out" devise rails 3

In your routes.rb :

 devise_for :users do
    get '/sign_out' => 'devise/sessions#destroy'
    get '/log_in' => 'devise/sessions#new'
    get '/log_out' => 'devise/sessions#destroy'
    get '/sign_up' => 'devise/registrations#new'
    get '/edit_profile' => 'devise/registrations#edit'
 end

and in your application.html.erb:

<%if user_signed_in?%>
          <li><%= link_to "Sign_out", sign_out_path %></li>
<% end %>

Split function in oracle to comma separated values with automatic sequence

Here is how you could create such a table:

 SELECT LEVEL AS id, REGEXP_SUBSTR('A,B,C,D', '[^,]+', 1, LEVEL) AS data
   FROM dual
CONNECT BY REGEXP_SUBSTR('A,B,C,D', '[^,]+', 1, LEVEL) IS NOT NULL;

With a little bit of tweaking (i.e., replacing the , in [^,] with a variable) you could write such a function to return a table.

Java image resize, maintain aspect ratio

I have found the selected answer to have problems with upscaling, and so I have made (yet) another version (which I have tested):

public static Point scaleFit(Point src, Point bounds) {
  int newWidth = src.x;
  int newHeight = src.y;
  double boundsAspectRatio = bounds.y / (double) bounds.x;
  double srcAspectRatio = src.y / (double) src.x;

  // first check if we need to scale width
  if (boundsAspectRatio < srcAspectRatio) {
    // scale width to fit
    newWidth = bounds.x;
    //scale height to maintain aspect ratio
    newHeight = (newWidth * src.y) / src.x;
  } else {
    //scale height to fit instead
    newHeight = bounds.y;
    //scale width to maintain aspect ratio
    newWidth = (newHeight * src.x) / src.y;
  }

  return new Point(newWidth, newHeight);
}

Written in Android terminology :-)

as for the tests:

@Test public void scaleFit() throws Exception {
  final Point displaySize = new Point(1080, 1920);
  assertEquals(displaySize, Util.scaleFit(displaySize, displaySize));
  assertEquals(displaySize, Util.scaleFit(new Point(displaySize.x / 2, displaySize.y / 2), displaySize));
  assertEquals(displaySize, Util.scaleFit(new Point(displaySize.x * 2, displaySize.y * 2), displaySize));
  assertEquals(new Point(displaySize.x, displaySize.y * 2), Util.scaleFit(new Point(displaySize.x / 2, displaySize.y), displaySize));
  assertEquals(new Point(displaySize.x * 2, displaySize.y), Util.scaleFit(new Point(displaySize.x, displaySize.y / 2), displaySize));
  assertEquals(new Point(displaySize.x, displaySize.y * 3 / 2), Util.scaleFit(new Point(displaySize.x / 3, displaySize.y / 2), displaySize));
}

Writing a list to a file with Python

Using Python 3 and Python 2.6+ syntax:

with open(filepath, 'w') as file_handler:
    for item in the_list:
        file_handler.write("{}\n".format(item))

This is platform-independent. It also terminates the final line with a newline character, which is a UNIX best practice.

Starting with Python 3.6, "{}\n".format(item) can be replaced with an f-string: f"{item}\n".

Is it possible to simulate key press events programmatically?

Building on the answer from alex2k8, here's a revised version that works in all browsers that jQuery supports (the problem was in missing arguments to jQuery.event.trigger, which is easy to forget when using that internal function).

// jQuery plugin. Called on a jQuery object, not directly.
jQuery.fn.simulateKeyPress = function (character) {
  // Internally calls jQuery.event.trigger with arguments (Event, data, elem).
  // That last argument, 'elem', is very important!
  jQuery(this).trigger({ type: 'keypress', which: character.charCodeAt(0) });
};

jQuery(function ($) {
  // Bind event handler
  $('body').keypress(function (e) {
    alert(String.fromCharCode(e.which));
    console.log(e);
  });
  // Simulate the key press
  $('body').simulateKeyPress('x');
});

You could even push this further and let it not only simulate the event but actually insert the character (if it is an input element), however there are many cross-browser gotcha's when trying to do that. Better use a more elaborate plugin like SendKeys.

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

ngOnInit() is called after ngOnChanges() was called the first time. ngOnChanges() is called every time inputs are updated by change detection.

ngAfterViewInit() is called after the view is initially rendered. This is why @ViewChild() depends on it. You can't access view members before they are rendered.

Setting a div's height in HTML with CSS

I can think of 2 options

  1. Use javascript to resize the smaller column on page load.
  2. Fake the equal heights by setting the background-color for the column on the container <div/> instead (<div class="separator"/>) with repeat-y

Java Security: Illegal key size or default parameters?

For JAVA 7 the download link is jce-7-download

Copy the two downloaded jars in Java\jdk1.7.0_10\jre\lib\security
Take a backup of older jars to be on safer side.

For JAVA 8 the download link is jce-8-download
Copy the downloaded jars in Java\jdk1.8.0_45\jre\lib\security
Take a backup of older jars to be on safer side.

How to support placeholder attribute in IE8 and 9

I use thisone, it's only Javascript.

I simply have an input element with a value, and when the user clicks on the input element, it changes it to an input element without a value.

You can easily change the color of the text using CSS. The color of the placeholder is the color in the id #IEinput, and the color your typed text will be is the color in the id #email. Don't use getElementsByClassName, because the versions of IE that don't support a placeholder, don't support getElementsByClassName either!

You can use a placeholder in a password input by setting the type of the original password input to text.

Tinker: http://tinker.io/4f7c5/1 - JSfiddle servers are down!

*sorry for my bad english

JAVASCRIPT

function removeValue() {
    document.getElementById('mailcontainer')
        .innerHTML = "<input id=\"email\" type=\"text\" name=\"mail\">";
    document.getElementById('email').focus(); }

HTML

<span id="mailcontainer">
    <input id="IEinput" onfocus="removeValue()" type="text" name="mail" value="mail">
</span>

JFrame background image

You can do:

setContentPane(new JLabel(new ImageIcon("resources/taverna.jpg")));

At first line of the Jframe class constructor, that works fine for me

How can I disable editing cells in a WPF Datagrid?

The DataGrid has an XAML property IsReadOnly that you can set to true:

<my:DataGrid
    IsReadOnly="True"
/>

SpringApplication.run main method

One more way is to extend the application (as my application was to inherit and customize the parent). It invokes the parent and its commandlinerunner automatically.

@SpringBootApplication
public class ChildApplication extends ParentApplication{
    public static void main(String[] args) {
        SpringApplication.run(ChildApplication.class, args);
    }
}

cannot import name patterns

Seems you are using outdated version of django.. Simply update django and try again.. Following command will update your django version..

pip install --upgrade django

T-SQL get SELECTed value of stored procedure

There is also a combination, you can use a return value with a recordset:

--Stored Procedure--

CREATE PROCEDURE [TestProc]

AS
BEGIN

    DECLARE @Temp TABLE
    (
        [Name] VARCHAR(50)
    )

    INSERT INTO @Temp VALUES ('Mark') 
    INSERT INTO @Temp VALUES ('John') 
    INSERT INTO @Temp VALUES ('Jane') 
    INSERT INTO @Temp VALUES ('Mary') 

    -- Get recordset
    SELECT * FROM @Temp

    DECLARE @ReturnValue INT
    SELECT @ReturnValue = COUNT([Name]) FROM @Temp

    -- Return count
    RETURN @ReturnValue

END

--Calling Code--

DECLARE @SelectedValue int
EXEC @SelectedValue = [TestProc] 

SELECT @SelectedValue

--Results--

enter image description here

Python 2.7: %d, %s, and float()

See String Formatting Operations:

%d is the format code for an integer. %f is the format code for a float.

%s prints the str() of an object (What you see when you print(object)).

%r prints the repr() of an object (What you see when you print(repr(object)).

For a float %s, %r and %f all display the same value, but that isn't the case for all objects. The other fields of a format specifier work differently as well:

>>> print('%10.2s' % 1.123) # print as string, truncate to 2 characters in a 10-place field.
        1.
>>> print('%10.2f' % 1.123) # print as float, round to 2 decimal places in a 10-place field.
      1.12

What is the Windows equivalent of the diff command?

Well, on Windows I happily run diff and many other of the GNU tools. You can do it with cygwin, but I personally prefer GnuWin32 because it is a much lighter installation experience.

So, my answer is that the Windows equivalent of diff, is none other than diff itself!

Bash checking if string does not contain other string

Use !=.

if [[ ${testmystring} != *"c0"* ]];then
    # testmystring does not contain c0
fi

See help [[ for more information.

How do I pass a unique_ptr argument to a constructor or a function?

Let me try to state the different viable modes of passing pointers around to objects whose memory is managed by an instance of the std::unique_ptr class template; it also applies to the the older std::auto_ptr class template (which I believe allows all uses that unique pointer does, but for which in addition modifiable lvalues will be accepted where rvalues are expected, without having to invoke std::move), and to some extent also to std::shared_ptr.

As a concrete example for the discussion I will consider the following simple list type

struct node;
typedef std::unique_ptr<node> list;
struct node { int entry; list next; }

Instances of such list (which cannot be allowed to share parts with other instances or be circular) are entirely owned by whoever holds the initial list pointer. If client code knows that the list it stores will never be empty, it may also choose to store the first node directly rather than a list. No destructor for node needs to be defined: since the destructors for its fields are automatically called, the whole list will be recursively deleted by the smart pointer destructor once the lifetime of initial pointer or node ends.

This recursive type gives the occasion to discuss some cases that are less visible in the case of a smart pointer to plain data. Also the functions themselves occasionally provide (recursively) an example of client code as well. The typedef for list is of course biased towards unique_ptr, but the definition could be changed to use auto_ptr or shared_ptr instead without much need to change to what is said below (notably concerning exception safety being assured without the need to write destructors).

Modes of passing smart pointers around

Mode 0: pass a pointer or reference argument instead of a smart pointer

If your function is not concerned with ownership, this is the preferred method: don't make it take a smart pointer at all. In this case your function does not need to worry who owns the object pointed to, or by what means that ownership is managed, so passing a raw pointer is both perfectly safe, and the most flexible form, since regardless of ownership a client can always produce a raw pointer (either by calling the get method or from the address-of operator &).

For instance the function to compute the length of such list, should not be give a list argument, but a raw pointer:

size_t length(const node* p)
{ size_t l=0; for ( ; p!=nullptr; p=p->next.get()) ++l; return l; }

A client that holds a variable list head can call this function as length(head.get()), while a client that has chosen instead to store a node n representing a non-empty list can call length(&n).

If the pointer is guaranteed to be non null (which is not the case here since lists may be empty) one might prefer to pass a reference rather than a pointer. It might be a pointer/reference to non-const if the function needs to update the contents of the node(s), without adding or removing any of them (the latter would involve ownership).

An interesting case that falls in the mode 0 category is making a (deep) copy of the list; while a function doing this must of course transfer ownership of the copy it creates, it is not concerned with the ownership of the list it is copying. So it could be defined as follows:

list copy(const node* p)
{ return list( p==nullptr ? nullptr : new node{p->entry,copy(p->next.get())} ); }

This code merits a close look, both for the question as to why it compiles at all (the result of the recursive call to copy in the initialiser list binds to the rvalue reference argument in the move constructor of unique_ptr<node>, a.k.a. list, when initialising the next field of the generated node), and for the question as to why it is exception-safe (if during the recursive allocation process memory runs out and some call of new throws std::bad_alloc, then at that time a pointer to the partly constructed list is held anonymously in a temporary of type list created for the initialiser list, and its destructor will clean up that partial list). By the way one should resist the temptation to replace (as I initially did) the second nullptr by p, which after all is known to be null at that point: one cannot construct a smart pointer from a (raw) pointer to constant, even when it is known to be null.

Mode 1: pass a smart pointer by value

A function that takes a smart pointer value as argument takes possession of the object pointed to right away: the smart pointer that the caller held (whether in a named variable or an anonymous temporary) is copied into the argument value at function entrance and the caller's pointer has become null (in the case of a temporary the copy might have been elided, but in any case the caller has lost access to the pointed to object). I would like to call this mode call by cash: caller pays up front for the service called, and can have no illusions about ownership after the call. To make this clear, the language rules require the caller to wrap the argument in std::move if the smart pointer is held in a variable (technically, if the argument is an lvalue); in this case (but not for mode 3 below) this function does what its name suggests, namely move the value from the variable to a temporary, leaving the variable null.

For cases where the called function unconditionally takes ownership of (pilfers) the pointed-to object, this mode used with std::unique_ptr or std::auto_ptr is a good way of passing a pointer together with its ownership, which avoids any risk of memory leaks. Nonetheless I think that there are only very few situations where mode 3 below is not to be preferred (ever so slightly) over mode 1. For this reason I shall provide no usage examples of this mode. (But see the reversed example of mode 3 below, where it is remarked that mode 1 would do at least as well.) If the function takes more arguments than just this pointer, it may happen that there is in addition a technical reason to avoid mode 1 (with std::unique_ptr or std::auto_ptr): since an actual move operation takes place while passing a pointer variable p by the expression std::move(p), it cannot be assumed that p holds a useful value while evaluating the other arguments (the order of evaluation being unspecified), which could lead to subtle errors; by contrast, using mode 3 assures that no move from p takes place before the function call, so other arguments can safely access a value through p.

When used with std::shared_ptr, this mode is interesting in that with a single function definition it allows the caller to choose whether to keep a sharing copy of the pointer for itself while creating a new sharing copy to be used by the function (this happens when an lvalue argument is provided; the copy constructor for shared pointers used at the call increases the reference count), or to just give the function a copy of the pointer without retaining one or touching the reference count (this happens when a rvalue argument is provided, possibly an lvalue wrapped in a call of std::move). For instance

void f(std::shared_ptr<X> x) // call by shared cash
{ container.insert(std::move(x)); } // store shared pointer in container

void client()
{ std::shared_ptr<X> p = std::make_shared<X>(args);
  f(p); // lvalue argument; store pointer in container but keep a copy
  f(std::make_shared<X>(args)); // prvalue argument; fresh pointer is just stored away
  f(std::move(p)); // xvalue argument; p is transferred to container and left null
}

The same could be achieved by separately defining void f(const std::shared_ptr<X>& x) (for the lvalue case) and void f(std::shared_ptr<X>&& x) (for the rvalue case), with function bodies differing only in that the first version invokes copy semantics (using copy construction/assignment when using x) but the second version move semantics (writing std::move(x) instead, as in the example code). So for shared pointers, mode 1 can be useful to avoid some code duplication.

Mode 2: pass a smart pointer by (modifiable) lvalue reference

Here the function just requires having a modifiable reference to the smart pointer, but gives no indication of what it will do with it. I would like to call this method call by card: caller ensures payment by giving a credit card number. The reference can be used to take ownership of the pointed-to object, but it does not have to. This mode requires providing a modifiable lvalue argument, corresponding to the fact that the desired effect of the function may include leaving a useful value in the argument variable. A caller with an rvalue expression that it wishes to pass to such a function would be forced to store it in a named variable to be able to make the call, since the language only provides implicit conversion to a constant lvalue reference (referring to a temporary) from an rvalue. (Unlike the opposite situation handled by std::move, a cast from Y&& to Y&, with Y the smart pointer type, is not possible; nonetheless this conversion could be obtained by a simple template function if really desired; see https://stackoverflow.com/a/24868376/1436796). For the case where the called function intends to unconditionally take ownership of the object, stealing from the argument, the obligation to provide an lvalue argument is giving the wrong signal: the variable will have no useful value after the call. Therefore mode 3, which gives identical possibilities inside our function but asks callers to provide an rvalue, should be preferred for such usage.

However there is a valid use case for mode 2, namely functions that may modify the pointer, or the object pointed to in a way that involves ownership. For instance, a function that prefixes a node to a list provides an example of such use:

void prepend (int x, list& l) { l = list( new node{ x, std::move(l)} ); }

Clearly it would be undesirable here to force callers to use std::move, since their smart pointer still owns a well defined and non-empty list after the call, though a different one than before.

Again it is interesting to observe what happens if the prepend call fails for lack of free memory. Then the new call will throw std::bad_alloc; at this point in time, since no node could be allocated, it is certain that the passed rvalue reference (mode 3) from std::move(l) cannot yet have been pilfered, as that would be done to construct the next field of the node that failed to be allocated. So the original smart pointer l still holds the original list when the error is thrown; that list will either be properly destroyed by the smart pointer destructor, or in case l should survive thanks to a sufficiently early catch clause, it will still hold the original list.

That was a constructive example; with a wink to this question one can also give the more destructive example of removing the first node containing a given value, if any:

void remove_first(int x, list& l)
{ list* p = &l;
  while ((*p).get()!=nullptr and (*p)->entry!=x)
    p = &(*p)->next;
  if ((*p).get()!=nullptr)
    (*p).reset((*p)->next.release()); // or equivalent: *p = std::move((*p)->next); 
}

Again the correctness is quite subtle here. Notably, in the final statement the pointer (*p)->next held inside the node to be removed is unlinked (by release, which returns the pointer but makes the original null) before reset (implicitly) destroys that node (when it destroys the old value held by p), ensuring that one and only one node is destroyed at that time. (In the alternative form mentioned in the comment, this timing would be left to the internals of the implementation of the move-assignment operator of the std::unique_ptr instance list; the standard says 20.7.1.2.3;2 that this operator should act "as if by calling reset(u.release())", whence the timing should be safe here too.)

Note that prepend and remove_first cannot be called by clients who store a local node variable for an always non-empty list, and rightly so since the implementations given could not work for such cases.

Mode 3: pass a smart pointer by (modifiable) rvalue reference

This is the preferred mode to use when simply taking ownership of the pointer. I would like to call this method call by check: caller must accept relinquishing ownership, as if providing cash, by signing the check, but the actual withdrawal is postponed until the called function actually pilfers the pointer (exactly as it would when using mode 2). The "signing of the check" concretely means callers have to wrap an argument in std::move (as in mode 1) if it is an lvalue (if it is an rvalue, the "giving up ownership" part is obvious and requires no separate code).

Note that technically mode 3 behaves exactly as mode 2, so the called function does not have to assume ownership; however I would insist that if there is any uncertainty about ownership transfer (in normal usage), mode 2 should be preferred to mode 3, so that using mode 3 is implicitly a signal to callers that they are giving up ownership. One might retort that only mode 1 argument passing really signals forced loss of ownership to callers. But if a client has any doubts about intentions of the called function, she is supposed to know the specifications of the function being called, which should remove any doubt.

It is surprisingly difficult to find a typical example involving our list type that uses mode 3 argument passing. Moving a list b to the end of another list a is a typical example; however a (which survives and holds the result of the operation) is better passed using mode 2:

void append (list& a, list&& b)
{ list* p=&a;
  while ((*p).get()!=nullptr) // find end of list a
    p=&(*p)->next;
  *p = std::move(b); // attach b; the variable b relinquishes ownership here
}

A pure example of mode 3 argument passing is the following that takes a list (and its ownership), and returns a list containing the identical nodes in reverse order.

list reversed (list&& l) noexcept // pilfering reversal of list
{ list p(l.release()); // move list into temporary for traversal
  list result(nullptr);
  while (p.get()!=nullptr)
  { // permute: result --> p->next --> p --> (cycle to result)
    result.swap(p->next);
    result.swap(p);
  }
  return result;
}

This function might be called as in l = reversed(std::move(l)); to reverse the list into itself, but the reversed list can also be used differently.

Here the argument is immediately moved to a local variable for efficiency (one could have used the parameter l directly in the place of p, but then accessing it each time would involve an extra level of indirection); hence the difference with mode 1 argument passing is minimal. In fact using that mode, the argument could have served directly as local variable, thus avoiding that initial move; this is just an instance of the general principle that if an argument passed by reference only serves to initialise a local variable, one might just as well pass it by value instead and use the parameter as local variable.

Using mode 3 appears to be advocated by the standard, as witnessed by the fact that all provided library functions that transfer ownership of smart pointers using mode 3. A particular convincing case in point is the constructor std::shared_ptr<T>(auto_ptr<T>&& p). That constructor used (in std::tr1) to take a modifiable lvalue reference (just like the auto_ptr<T>& copy constructor), and could therefore be called with an auto_ptr<T> lvalue p as in std::shared_ptr<T> q(p), after which p has been reset to null. Due to the change from mode 2 to 3 in argument passing, this old code must now be rewritten to std::shared_ptr<T> q(std::move(p)) and will then continue to work. I understand that the committee did not like the mode 2 here, but they had the option of changing to mode 1, by defining std::shared_ptr<T>(auto_ptr<T> p) instead, they could have ensured that old code works without modification, because (unlike unique-pointers) auto-pointers can be silently dereferenced to a value (the pointer object itself being reset to null in the process). Apparently the committee so much preferred advocating mode 3 over mode 1, that they chose to actively break existing code rather than to use mode 1 even for an already deprecated usage.

When to prefer mode 3 over mode 1

Mode 1 is perfectly usable in many cases, and might be preferred over mode 3 in cases where assuming ownership would otherwise takes the form of moving the smart pointer to a local variable as in the reversed example above. However, I can see two reasons to prefer mode 3 in the more general case:

  • It is slightly more efficient to pass a reference than to create a temporary and nix the old pointer (handling cash is somewhat laborious); in some scenarios the pointer may be passed several times unchanged to another function before it is actually pilfered. Such passing will generally require writing std::move (unless mode 2 is used), but note that this is just a cast that does not actually do anything (in particular no dereferencing), so it has zero cost attached.

  • Should it be conceivable that anything throws an exception between the start of the function call and the point where it (or some contained call) actually moves the pointed-to object into another data structure (and this exception is not already caught inside the function itself), then when using mode 1, the object referred to by the smart pointer will be destroyed before a catch clause can handle the exception (because the function parameter was destructed during stack unwinding), but not so when using mode 3. The latter gives the caller has the option to recover the data of the object in such cases (by catching the exception). Note that mode 1 here does not cause a memory leak, but may lead to an unrecoverable loss of data for the program, which might be undesirable as well.

Returning a smart pointer: always by value

To conclude a word about returning a smart pointer, presumably pointing to an object created for use by the caller. This is not really a case comparable with passing pointers into functions, but for completeness I would like to insist that in such cases always return by value (and don't use std::move in the return statement). Nobody wants to get a reference to a pointer that probably has just been nixed.

Why is Thread.Sleep so harmful

SCENARIO 1 - wait for async task completion: I agree that WaitHandle/Auto|ManualResetEvent should be used in scenario where a thread is waiting for task on another thread to complete.

SCENARIO 2 - timing while loop: However, as a crude timing mechanism (while+Thread.Sleep) is perfectly fine for 99% of applications which does NOT require knowing exactly when the blocked Thread should "wake up*. The argument that it takes 200k cycles to create the thread is also invalid - the timing loop thread needs be created anyway and 200k cycles is just another big number (tell me how many cycles to open a file/socket/db calls?).

So if while+Thread.Sleep works, why complicate things? Only syntax lawyers would, be practical!

Difference between signed / unsigned char

The same way how an int can be positive or negative. There is no difference. Actually on many platforms unqualified char is signed.

How do you test that a Python function throws an exception?

Use TestCase.assertRaises (or TestCase.failUnlessRaises) from the unittest module, for example:

import mymod

class MyTestCase(unittest.TestCase):
    def test1(self):
        self.assertRaises(SomeCoolException, mymod.myfunc)

How to insert table values from one database to another database?

INSERT
INTO    remotedblink.remotedatabase.remoteschema.remotetable
SELECT  *
FROM    mytable

There is no such thing as "the end of the table" in relational databases.