Programs & Examples On #Nspopupbuttoncell

The NSPopUpButtonCell class defines the visual appearance of pop-up buttons that display pop-up or pull-down menus.

Automate scp file transfer using a shell script

This will work:

#!/usr/bin/expect -f

spawn scp -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no file1 file2 file3 user@host:/path/
expect "password:"
send "xyz123\r"
expect "*\r"
expect "\r"
interact

Detecting a mobile browser

var isMobile = {
    Android: function() {
        return navigator.userAgent.match(/Android/i);
    },
    BlackBerry: function() {
        return navigator.userAgent.match(/BlackBerry/i);
    },
    iOS: function() {
        return navigator.userAgent.match(/iPhone|iPad|iPod/i);
    },
    Opera: function() {
        return navigator.userAgent.match(/Opera Mini/i);
    },
    Windows: function() {
        return navigator.userAgent.match(/IEMobile/i) || navigator.userAgent.match(/WPDesktop/i);
    },
    any: function() {
        return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows());
    }
};

How to use

if( isMobile.any() ) alert('Mobile');

To check to see if the user is on a specific mobile device:

if( isMobile.iOS() ) alert('iOS');

Ref: http://www.abeautifulsite.net/blog/2011/11/detecting-mobile-devices-with-javascript

Enhanced version on github : https://github.com/smali-kazmi/detect-mobile-browser

Efficiently replace all accented characters in a string?

I just wanted to post my solution using String#localeCompare

_x000D_
_x000D_
const base_chars = [_x000D_
  '1', '2', '3', '4', '5', '6', '7', '8', '9',_x000D_
  '0', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',_x000D_
  'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q',_x000D_
  'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',_x000D_
  '-', '_', ' '_x000D_
];_x000D_
const fix = str => str.normalize('NFKD').split('')_x000D_
    .map(c => base_chars.find(bc => bc.localeCompare(c, 'en', { sensitivity: 'base' })==0))_x000D_
    .join('');_x000D_
_x000D_
const str = 'OÒ óëå-123';_x000D_
console.log(`fix(${str}) = ${fix(str)}`);
_x000D_
_x000D_
_x000D_

How can I update window.location.hash without jumping the document?

I used a combination of Attila Fulop (Lea Verou) solution for modern browsers and Gavin Brock solution for old browsers as follows:

if (history.pushState) {
    // IE10, Firefox, Chrome, etc.
    window.history.pushState(null, null, '#' + id);
} else {
    // IE9, IE8, etc
    window.location.hash = '#!' + id;
}

As observed by Gavin Brock, to capture the id back you will have to treat the string (which in this case can have or not the "!") as follows:

id = window.location.hash.replace(/^#!?/, '');

Before that, I tried a solution similar to the one proposed by user706270, but it did not work well with Internet Explorer: as its Javascript engine is not very fast, you can notice the scroll increase and decrease, which produces a nasty visual effect.

How to open a file / browse dialog using javascript?

How about make clicking the a tag, to click on the file button?

There is more browser support for this, but I use ES6, so if you really want to make it work in older and any browser, try to transpile it using babel, or just simply use ES5:

_x000D_
_x000D_
const aTag = document.getElementById("open-file-uploader");_x000D_
const fileInput = document.getElementById("input-button");_x000D_
aTag.addEventListener("click", () => fileInput.click());
_x000D_
#input-button {_x000D_
  position: abosulte;_x000D_
  width: 1px;_x000D_
  height: 1px;_x000D_
  clip: rect(1px 1px 1px 1px);_x000D_
  clip: rect(1px, 1px, 1px, 1px);_x000D_
}
_x000D_
<a href="#" id="open-file-uploader">Open file uploader</a>_x000D_
<input type="file" id="input-button" />
_x000D_
_x000D_
_x000D_

Setting up a websocket on Apache?

The new version 2.4 of Apache HTTP Server has a module called mod_proxy_wstunnel which is a websocket proxy.

http://httpd.apache.org/docs/2.4/mod/mod_proxy_wstunnel.html

Pandas timeseries plot setting x-axis major and minor ticks and labels

Both pandas and matplotlib.dates use matplotlib.units for locating the ticks.

But while matplotlib.dates has convenient ways to set the ticks manually, pandas seems to have the focus on auto formatting so far (you can have a look at the code for date conversion and formatting in pandas).

So for the moment it seems more reasonable to use matplotlib.dates (as mentioned by @BrenBarn in his comment).

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt 
import matplotlib.dates as dates

idx = pd.date_range('2011-05-01', '2011-07-01')
s = pd.Series(np.random.randn(len(idx)), index=idx)

fig, ax = plt.subplots()
ax.plot_date(idx.to_pydatetime(), s, 'v-')
ax.xaxis.set_minor_locator(dates.WeekdayLocator(byweekday=(1),
                                                interval=1))
ax.xaxis.set_minor_formatter(dates.DateFormatter('%d\n%a'))
ax.xaxis.grid(True, which="minor")
ax.yaxis.grid()
ax.xaxis.set_major_locator(dates.MonthLocator())
ax.xaxis.set_major_formatter(dates.DateFormatter('\n\n\n%b\n%Y'))
plt.tight_layout()
plt.show()

pandas_like_date_fomatting

(my locale is German, so that Tuesday [Tue] becomes Dienstag [Di])

Powershell command to hide user from exchange address lists

You will have to pass one of the valid Identity values like DN, domain\user etc to the Set-Mailbox cmdlet. Currently you are not passing anything.

Get source jar files attached to Eclipse for Maven-managed dependencies

mvn eclipse:eclipse -DdownloadSources=true

or

mvn eclipse:eclipse -DdownloadJavadocs=true

or you can add both flags, as Spencer K points out.

Additionally, the =true portion is not required, so you can use

mvn eclipse:eclipse -DdownloadSources -DdownloadJavadocs

docker run <IMAGE> <MULTIPLE COMMANDS>

If you want to store the result in one file outside the container, in your local machine, you can do something like this.

RES_FILE=$(readlink -f /tmp/result.txt)

docker run --rm -v ${RES_FILE}:/result.txt img bash -c "cat /etc/passwd | grep root > /result.txt"

The result of your commands will be available in /tmp/result.txt in your local machine.

Setting Custom ActionBar Title from Fragment

Save ur Answer in String[] object and set it OnTabChange() in MainActivity as Belowwww

String[] object = {"Fragment1","Fragment2","Fragment3"};

public void OnTabChange(String tabId)
{
int pos =mTabHost.getCurrentTab();     //To get tab position
 actionbar.setTitle(object.get(pos));
}


//Setting in View Pager
public void onPageSelected(int arg0) {
    mTabHost.setCurrentTab(arg0);
actionbar.setTitle(object.get(pos));
}

C pass int array pointer as parameter into a function

Make use of *(B) instead of *B[0]. Here, *(B+i) implies B[i] and *(B) implies B[0], that is
*(B+0)=*(B)=B[0].

#include <stdio.h>

int func(int *B){
    *B = 5;     
    // if you want to modify ith index element in the array just do *(B+i)=<value>
}

int main(void){

    int B[10] = {};
    printf("b[0] = %d\n\n", B[0]);
    func(B);
    printf("b[0] = %d\n\n", B[0]);
    return 0;
}

How to set the default value for radio buttons in AngularJS?

In Angular 2 this is how we can set the default value for radio button:

HTML:

<label class="form-check-label">
          <input type="radio" class="form-check-input" name="gender" 
          [(ngModel)]="gender" id="optionsRadios1" value="male">
          Male
</label>

In the Component Class set the value of 'gender' variable equal to the value of radio button:

gender = 'male';

In Laravel, the best way to pass different types of flash messages in the session

If you want to use Bootstrap Alert to make your view more interactive. You can do something like this:

In your function:-

if($author->save()){
    Session::flash('message', 'Author has been successfully added');
    Session::flash('class', 'success'); //you can replace success by [info,warning,danger]
    return redirect('main/successlogin');

In your views:-

@if(Session::has('message'))
    <div class="alert alert-{{Session::get('class')}} alert-dismissible fade show w-50 ml-auto alert-custom"
        role="alert">
        {{ Session::get('message') }}
        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
            <span aria-hidden="true">&times;</span>
        </button>
    </div>
@endif

No connection could be made because the target machine actively refused it 127.0.0.1:3446

I had a similar problem rejecting localhost and 127.0.0.1. cmd(admin) netstat -anb found the port running on 169.254.80.80 (dont know were that ip came from because my network ip was 10.0.0.5. after putting in this IP it worked. This Gives correct IP:

IPAddress ipAddress = ipHostInfo.AddressList[0];
Console.WriteLine(ipAddress.ToString());

Convert text to columns in Excel using VBA

Try this

Sub Txt2Col()
    Dim rng As Range

    Set rng = [C7]
    Set rng = Range(rng, Cells(Rows.Count, rng.Column).End(xlUp))

    rng.TextToColumns Destination:=rng, DataType:=xlDelimited, ' rest of your settings

Update: button click event to act on another sheet

Private Sub CommandButton1_Click()
    Dim rng As Range
    Dim sh As Worksheet

    Set sh = Worksheets("Sheet2")
    With sh
        Set rng = .[C7]
        Set rng = .Range(rng, .Cells(.Rows.Count, rng.Column).End(xlUp))

        rng.TextToColumns Destination:=rng, DataType:=xlDelimited, _
        TextQualifier:=xlDoubleQuote,  _
        ConsecutiveDelimiter:=False, _
        Tab:=False, _
        Semicolon:=False, _
        Comma:=True, 
        Space:=False, 
        Other:=False, _
        FieldInfo:=Array(Array(1, xlGeneralFormat), Array(2, xlGeneralFormat), Array(3, xlGeneralFormat)), _
        TrailingMinusNumbers:=True
    End With
End Sub

Note the .'s (eg .Range) they refer to the With statement object

How can I pipe stderr, and not stdout?

If you are using Bash, then use:

command >/dev/null |& grep "something"

http://www.gnu.org/software/bash/manual/bashref.html#Pipelines

Clearing an input text field in Angular2

This is a solution for reactive forms. Then there is no need to use @ViewChild decorator:

  clear() {
    this.myForm.get('someControlName').reset()
  }

How to combine two byte arrays

You can do this by using Apace common lang package (org.apache.commons.lang.ArrayUtils class ). You need to do the following

byte[] concatBytes = ArrayUtils.addAll(one,two);

How do I set 'semi-bold' font via CSS? Font-weight of 600 doesn't make it look like the semi-bold I see in my Photoshop file

Select fonts by specifying the weights you need on load

Font-families consist of several distinct fonts

For example, extra-bold will make the font look quite different in say, Photoshop, because you're selecting a different font. The same applies to italic font, which can look very different indeed. Setting font-weight:800 or font-style:italic may result in just a best effort of the web browser to fatten or slant the normal font in the family.

Even though you're loading a font-family, you must specify the weights and styles you need for some web browsers to let you select a different font in the family with font-weight and font-style.

Example

This example specifies the light, normal, normal italic, bold, and extra-bold fonts in the font family Open Sans:

_x000D_
_x000D_
<html>_x000D_
  <head>_x000D_
    <link rel="stylesheet"_x000D_
          href="https://fonts.googleapis.com/css?family=Open+Sans:100,400,400i,600,800">_x000D_
    <style>_x000D_
      body {_x000D_
        font-family: 'Open Sans', serif;_x000D_
        font-size: 48px;_x000D_
      }_x000D_
    </style>_x000D_
  </head>_x000D_
  <body>    _x000D_
    <div style="font-weight:400">Didn't work with all the fonts</div>_x000D_
   <div style="font-weight:600">Didn't work with all the fonts</div>_x000D_
   <div style="font-weight:800">Didn't work with all the fonts</div>_x000D_
  </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Reference

(Quora warning, please remove if not allowed.)

https://www.quora.com/How-do-I-make-Open-Sans-extra-bold-once-imported-from-Google-Fonts

Testing

Tested working in Firefox 66.0.3 on Mac and Firefox 36.0.1 in Windows.

Non-Google fonts

Other fonts must be uploaded to the server, style and weight specified by their individual names.

System fonts

Assume nothing, font-wise, about what device is visiting your website or what fonts are installed on its OS.

(You may use the fall-backs of serif and sans-serif, but you will get the font mapped to these by the individual web browser version used, within the fonts available in the OS version it's running under, and not what you designed.)

Testing should be done with the font temporarily uninstalled from your system, to be sure that your design is in effect.

Using LINQ to group a list of objects

The desired result can be obtained using IGrouping, which represents a collection of objects that have a common key in this case a GroupID

 var newCustomerList = CustomerList.GroupBy(u => u.GroupID)
                                                  .Select(group => new { GroupID = group.Key, Customers = group.ToList() })
                                                  .ToList();

Regex: Use start of line/end of line signs (^ or $) in different context

Just use look-arounds to solve this:

(?<=^|,)garp(?=$|,)

The difference with look-arounds and just regular groups are that with regular groups the comma would be part of the match, and with look-arounds it wouldn't. In this case it doesn't make a difference though.

Negation in Python

Combining the input from everyone else (use not, no parens, use os.mkdir) you'd get...

special_path_for_john = "/usr/share/sounds/blues"
if not os.path.exists(special_path_for_john):
    os.mkdir(special_path_for_john)

PHP foreach with Nested Array?

Both syntaxes are correct. But the result would be Array. You probably want to do something like this:

foreach ($tmpArray[1] as $value) {
  echo $value[0];
  foreach($value[1] as $val){
    echo $val;
  }
}

This will print out the string "two" ($value[0]) and the integers 4, 5 and 6 from the array ($value[1]).

What is the most appropriate way to store user settings in Android application

you need to use the sqlite, security apit to store the passwords. here is best example, which stores passwords, -- passwordsafe. here is link for the source and explanation -- http://code.google.com/p/android-passwordsafe/

Ruby on Rails: Where to define global constants?

For application-wide settings and for global constants I recommend to use Settingslogic. This settings are stored in YML file and can be accessed from models, views and controllers. Furthermore, you can create different settings for all your environments:

  # app/config/application.yml
  defaults: &defaults
    cool:
      sweet: nested settings
    neat_setting: 24
    awesome_setting: <%= "Did you know 5 + 5 = #{5 + 5}?" %>

    colors: "white blue black red green"

  development:
    <<: *defaults
    neat_setting: 800

  test:
    <<: *defaults

  production:
    <<: *defaults

Somewhere in the view (I prefer helper methods for such kind of stuff) or in a model you can get, for ex., array of colors Settings.colors.split(/\s/). It's very flexible. And you don't need to invent a bike.

Custom exception type

I often use an approach with prototypal inheritance. Overriding toString() gives you the advantage that tools like Firebug will log the actual information instead of [object Object] to the console for uncaught exceptions.

Use instanceof to determine the type of exception.

main.js

// just an exemplary namespace
var ns = ns || {};

// include JavaScript of the following
// source files here (e.g. by concatenation)

var someId = 42;
throw new ns.DuplicateIdException('Another item with ID ' +
    someId + ' has been created');
// Firebug console:
// uncaught exception: [Duplicate ID] Another item with ID 42 has been created

Exception.js

ns.Exception = function() {
}

/**
 * Form a string of relevant information.
 *
 * When providing this method, tools like Firebug show the returned 
 * string instead of [object Object] for uncaught exceptions.
 *
 * @return {String} information about the exception
 */
ns.Exception.prototype.toString = function() {
    var name = this.name || 'unknown';
    var message = this.message || 'no description';
    return '[' + name + '] ' + message;
};

DuplicateIdException.js

ns.DuplicateIdException = function(message) {
    this.name = 'Duplicate ID';
    this.message = message;
};

ns.DuplicateIdException.prototype = new ns.Exception();

How to get Node.JS Express to listen only on localhost?

You are having this problem because you are attempting to console log app.address() before the connection has been made. You just have to be sure to console log after the connection is made, i.e. in a callback or after an event signaling that the connection has been made.

Fortunately, the 'listening' event is emitted by the server after the connection is made so just do this:

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

var app = express();
var server = http.createServer(app);

app.get('/', function(req, res) {
    res.send("Hello World!");
});

server.listen(3000, 'localhost');
server.on('listening', function() {
    console.log('Express server started on port %s at %s', server.address().port, server.address().address);
});

This works just fine in nodejs v0.6+ and Express v3.0+.

How to preventDefault on anchor tags?

Or if you need inline then you can do this:

<a href="#" ng-click="show = !show; $event.preventDefault()">Click to show</a>

How to force Hibernate to return dates as java.util.Date instead of Timestamp?

Approaches 1 and 2 obviously don't work, because you get java.sql.Date objects, per JPA/Hibernate spec, and not java.util.Date. From approaches 3 and 4, I would rather choose the latter one, because it's more declarative, and will work with both field and getter annotations.

You have already laid out the solution 4 in your referenced blog post, as @tscho was kind to point out. Maybe defaultForType (see below) should give you the centralized solution you were looking for. Of course will will still need to differentiate between date (without time) and timestamp fields.

For future reference I will leave the summary of using your own Hibernate UserType here:

To make Hibernate give you java.util.Date instances, you can use the @Type and @TypeDef annotations to define a different mapping of your java.util.Date java types to and from the database.

See the examples in the core reference manual here.

  1. Implement a UserType to do the actual plumbing (conversion to/from java.util.Date), named e.g. TimestampAsJavaUtilDateType
  2. Add a @TypeDef annotation on one entity or in a package-info.java - both will be available globally for the session factory (see manual link above). You can use defaultForType to apply the type conversion on all mapped fields of type java.util.Date.

    @TypeDef
      name = "timestampAsJavaUtilDate",
      defaultForType = java.util.Date.class, /* applied globally */
      typeClass = TimestampAsJavaUtilDateType.class
    )
    
  3. Optionally, instead of defaultForType, you can annotate your fields/getters with @Type individually:

    @Entity
    public class MyEntity {
       [...]
       @Type(type="timestampAsJavaUtilDate")
       private java.util.Date myDate;
       [...]
    }
    

P.S. To suggest a totally different approach: we usually just don't compare Date objects using equals() anyway. Instead we use a utility class with methods to compare e.g. only the calendar date of two Date instances (or another resolution such as seconds), regardless of the exact implementation type. That as worked well for us.

What exactly is Apache Camel?

Camel sends messages from A to B:

enter image description here

Why a whole framework for this? Well, what if you have:

  • many senders and many receivers
  • a dozen of protocols (ftp, http, jms, etc.)
  • many complex rules
    • Send a message A to Receivers A and B only
    • Send a message B to Receiver C as XML, but partly translate it, enrich it (add metadata) and IF condition X, then send it to Receiver D too, but as CSV.

So now you need:

  • translate between protocols
  • glue components together
  • define routes - what goes where
  • filter some things in some cases

Camel gives you the above (and more) out of the box:

enter image description here

with a cool DSL language for you to define the what and how:

  new DefaultCamelContext().addRoutes(new RouteBuilder() {
        public void configure() {
            from("jms:incomingMessages")
                    .choice() // start router rules
                    .when(header("CamelFileName")
                            .endsWith(".xml"))
                    .to("jms:xmlMessages")
                    .when(header("CamelFileName")
                            .endsWith(".csv"))
                    .to("ftp:csvMessages");
}

See also this and this and Camel in Action (as others have said, an excellent book!)

How to set TextView textStyle such as bold, italic

Since I want to use a custom font only conjunction of several answers works for me. Obviously settings in my layout.xml like android:textStlyle="italic" was ignored by AOS. So finally I had to do as follows: in strings.xml the target string was declared as:

<string name="txt_sign"><i>The information blah blah ...</i></string>

then additionally in code:

TextView textSign = (TextView) findViewById(R.id.txt_sign);
FontHelper.setSomeCustomFont(textSign);
textSign.setTypeface(textSign.getTypeface(), Typeface.ITALIC);

I didn't try the Spannable option (which I assume MUST work) but

textSign.setText(Html.fromHtml(getString(R.string.txt_sign))) 

had no effect. Also if I remove the italic tag from strings.xml leaving the setTypeface() all alone it has no effect either. Tricky Android...

comparing elements of the same array in java

for (int i = 0; i < a.length; i++) {
    for (int k = 0; k < a.length; k++) {
        if (a[i] != a[k]) {
            System.out.println(a[i] + " not the same with  " + a[k + 1] + "\n");
        }
    }
}

You can start from k=1 & keep "a.length-1" in outer for loop, in order to reduce two comparisions,but that doesnt make any significant difference.

Default optional parameter in Swift function

Swift is not like languages like JavaScript, where you can call a function without passing the parameters and it will still be called. So to call a function in Swift, you need to assign a value to its parameters.

Default values for parameters allow you to assign a value without specifying it when calling the function. That's why test() works when you specify a default value on test's declaration.

If you don't include that default value, you need to provide the value on the call: test(nil).

Also, and not directly related to this question, but probably worth to note, you are using the "C++" way of dealing with possibly null pointers, for dealing with possible nil optionals in Swift. The following code is safer (specially in multithreading software), and it allows you to avoid the forced unwrapping of the optional:

func test(firstThing: Int? = nil) {
    if let firstThing = firstThing {
        print(firstThing)
    }
    print("done")
}
test()

String literals and escape characters in postgresql

Partially. The text is inserted, but the warning is still generated.

I found a discussion that indicated the text needed to be preceded with 'E', as such:

insert into EscapeTest (text) values (E'This is the first part \n And this is the second');

This suppressed the warning, but the text was still not being returned correctly. When I added the additional slash as Michael suggested, it worked.

As such:

insert into EscapeTest (text) values (E'This is the first part \\n And this is the second');

Parse large JSON file in Nodejs

To process a file line-by-line, you simply need to decouple the reading of the file and the code that acts upon that input. You can accomplish this by buffering your input until you hit a newline. Assuming we have one JSON object per line (basically, format B):

var stream = fs.createReadStream(filePath, {flags: 'r', encoding: 'utf-8'});
var buf = '';

stream.on('data', function(d) {
    buf += d.toString(); // when data is read, stash it in a string buffer
    pump(); // then process the buffer
});

function pump() {
    var pos;

    while ((pos = buf.indexOf('\n')) >= 0) { // keep going while there's a newline somewhere in the buffer
        if (pos == 0) { // if there's more than one newline in a row, the buffer will now start with a newline
            buf = buf.slice(1); // discard it
            continue; // so that the next iteration will start with data
        }
        processLine(buf.slice(0,pos)); // hand off the line
        buf = buf.slice(pos+1); // and slice the processed data off the buffer
    }
}

function processLine(line) { // here's where we do something with a line

    if (line[line.length-1] == '\r') line=line.substr(0,line.length-1); // discard CR (0x0D)

    if (line.length > 0) { // ignore empty lines
        var obj = JSON.parse(line); // parse the JSON
        console.log(obj); // do something with the data here!
    }
}

Each time the file stream receives data from the file system, it's stashed in a buffer, and then pump is called.

If there's no newline in the buffer, pump simply returns without doing anything. More data (and potentially a newline) will be added to the buffer the next time the stream gets data, and then we'll have a complete object.

If there is a newline, pump slices off the buffer from the beginning to the newline and hands it off to process. It then checks again if there's another newline in the buffer (the while loop). In this way, we can process all of the lines that were read in the current chunk.

Finally, process is called once per input line. If present, it strips off the carriage return character (to avoid issues with line endings – LF vs CRLF), and then calls JSON.parse one the line. At this point, you can do whatever you need to with your object.

Note that JSON.parse is strict about what it accepts as input; you must quote your identifiers and string values with double quotes. In other words, {name:'thing1'} will throw an error; you must use {"name":"thing1"}.

Because no more than a chunk of data will ever be in memory at a time, this will be extremely memory efficient. It will also be extremely fast. A quick test showed I processed 10,000 rows in under 15ms.

Excel: VLOOKUP that returns true or false?

We've always used an

if(iserror(vlookup,"n/a",vlookup))

Excel 2007 introduced IfError which allows you to do the vlookup and add output in case of error, but that doesn't help you with 2003...

TSQL How do you output PRINT in a user defined function?

No, you can not.

You can call a function from a stored procedure and debug a stored procedure (this will step into the function)

'\r': command not found - .bashrc / .bash_profile

For those who don't have dos2unix installed (and don't want to install it):

Remove trailing \r character that causes this error:

sed -i 's/\r$//' filename


Explanation:

Option -i is for in-place editing, we delete the trailing \r directly in the input file. Thus be careful to type the pattern correctly.

Scatter plot and Color mapping in Python

Here is an example

import numpy as np
import matplotlib.pyplot as plt

x = np.random.rand(100)
y = np.random.rand(100)
t = np.arange(100)

plt.scatter(x, y, c=t)
plt.show()

Here you are setting the color based on the index, t, which is just an array of [1, 2, ..., 100]. enter image description here

Perhaps an easier-to-understand example is the slightly simpler

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(100)
y = x
t = x
plt.scatter(x, y, c=t)
plt.show()

enter image description here

Note that the array you pass as c doesn't need to have any particular order or type, i.e. it doesn't need to be sorted or integers as in these examples. The plotting routine will scale the colormap such that the minimum/maximum values in c correspond to the bottom/top of the colormap.

Colormaps

You can change the colormap by adding

import matplotlib.cm as cm
plt.scatter(x, y, c=t, cmap=cm.cmap_name)

Importing matplotlib.cm is optional as you can call colormaps as cmap="cmap_name" just as well. There is a reference page of colormaps showing what each looks like. Also know that you can reverse a colormap by simply calling it as cmap_name_r. So either

plt.scatter(x, y, c=t, cmap=cm.cmap_name_r)
# or
plt.scatter(x, y, c=t, cmap="cmap_name_r")

will work. Examples are "jet_r" or cm.plasma_r. Here's an example with the new 1.5 colormap viridis:

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(100)
y = x
t = x
fig, (ax1, ax2) = plt.subplots(1, 2)
ax1.scatter(x, y, c=t, cmap='viridis')
ax2.scatter(x, y, c=t, cmap='viridis_r')
plt.show()

enter image description here

Colorbars

You can add a colorbar by using

plt.scatter(x, y, c=t, cmap='viridis')
plt.colorbar()
plt.show()

enter image description here

Note that if you are using figures and subplots explicitly (e.g. fig, ax = plt.subplots() or ax = fig.add_subplot(111)), adding a colorbar can be a bit more involved. Good examples can be found here for a single subplot colorbar and here for 2 subplots 1 colorbar.

How to use enums as flags in C++?

I found myself asking the same question and came up with a generic C++11 based solution, similar to soru's:

template <typename TENUM>
class FlagSet {

private:
    using TUNDER = typename std::underlying_type<TENUM>::type;
    std::bitset<std::numeric_limits<TUNDER>::max()> m_flags;

public:
    FlagSet() = default;

    template <typename... ARGS>
    FlagSet(TENUM f, ARGS... args) : FlagSet(args...)
    {   
        set(f);
    }   
    FlagSet& set(TENUM f)
    {   
        m_flags.set(static_cast<TUNDER>(f));
        return *this;
    }   
    bool test(TENUM f)
    {   
        return m_flags.test(static_cast<TUNDER>(f));
    }   
    FlagSet& operator|=(TENUM f)
    {   
        return set(f);
    }   
};

The interface can be improved to taste. Then it can be used like so:

FlagSet<Flags> flags{Flags::FLAG_A, Flags::FLAG_C};
flags |= Flags::FLAG_D;

Could not find tools.jar. Please check that C:\Program Files\Java\jre1.8.0_151 contains a valid JDK installation

Please make sure both JDK and jre are on same version for example if you have JRE version 1.8.0_201 then JDK version should be 1.8.0_201 version.

Rename all files in a folder with a prefix in a single command

I think this is just what you'er looking for:

ls | xargs -I {} mv {} Unix_{}

Yes, it is simple yet elegant and powerful, and also one-liner. You can get more detailed intro from me on the page:Rename Files and Directories (Add Prefix)

Get names of all files from a folder with Ruby

This is what works for me:

Dir.entries(dir).select { |f| File.file?(File.join(dir, f)) }

Dir.entries returns an array of strings. Then, we have to provide a full path of the file to File.file?, unless dir is equal to our current working directory. That's why this File.join().

Oracle insert from select into table with more columns

Just add in the '0' in your select.

INSERT INTO table_name (a,b,c,d)
    SELECT
       other_table.a AS a,
       other_table.b AS b,
       other_table.c AS c,
       '0' AS d
    FROM other_table

os.walk without digging into directories below

The suggestion to use listdir is a good one. The direct answer to your question in Python 2 is root, dirs, files = os.walk(dir_name).next().

The equivalent Python 3 syntax is root, dirs, files = next(os.walk(dir_name))

How to get the Mongo database specified in connection string in C#

In this moment with the last version of the C# driver (2.3.0) the only way I found to get the database name specified in connection string is this:

var connectionString = @"mongodb://usr:[email protected],srv2.acme.net,srv3.acme.net/dbName?replicaSet=rset";
var mongoUrl = new MongoUrl(connectionString);
var dbname = mongoUrl.DatabaseName;
var db = new MongoClient(mongoUrl).GetDatabase(dbname);
db.GetCollection<MyType>("myCollectionName");

Read .mat files in Python

There is a nice package called mat4py which can easily be installed using

pip install mat4py

It is straightforward to use (from the website):

Load data from a MAT-file

The function loadmat loads all variables stored in the MAT-file into a simple Python data structure, using only Python’s dict and list objects. Numeric and cell arrays are converted to row-ordered nested lists. Arrays are squeezed to eliminate arrays with only one element. The resulting data structure is composed of simple types that are compatible with the JSON format.

Example: Load a MAT-file into a Python data structure:

from mat4py import loadmat

data = loadmat('datafile.mat')

The variable data is a dict with the variables and values contained in the MAT-file.

Save a Python data structure to a MAT-file

Python data can be saved to a MAT-file, with the function savemat. Data has to be structured in the same way as for loadmat, i.e. it should be composed of simple data types, like dict, list, str, int, and float.

Example: Save a Python data structure to a MAT-file:

from mat4py import savemat

savemat('datafile.mat', data)

The parameter data shall be a dict with the variables.

Convert JavaScript String to be all lower case?

Opt 1: using toLowerCase()

var x = 'ABC';
x = x.toLowerCase();

Opt 2: Using your own function

function convertToLowerCase(str) {
  var result = '';

  for (var i = 0; i < str.length; i++) {
    var code = str.charCodeAt(i);
    if (code > 64 && code < 91) {
      result += String.fromCharCode(code + 32);
    } else {
      result += str.charAt(i);
    }
  }
  return result;
}

Call it as:

x = convertToLowerCase(x);

The instance of entity type cannot be tracked because another instance of this type with the same key is already being tracked

Arhhh this got me and I spent a lot of time troubleshooting it. The problem was my tests were being executed in Parellel (the default with XUnit).

To make my test run sequentially I decorated each class with this attribute:

[Collection("Sequential")]

This is how I worked it out: Execute unit tests serially (rather than in parallel)


I mock up my EF In Memory context with GenFu:

private void CreateTestData(TheContext dbContext)
{
    GenFu.GenFu.Configure<Employee>()
       .Fill(q => q.EmployeeId, 3);
    var employee = GenFu.GenFu.ListOf<Employee>(1);

    var id = 1;
    GenFu.GenFu.Configure<Team>()
        .Fill(p => p.TeamId, () => id++).Fill(q => q.CreatedById, 3).Fill(q => q.ModifiedById, 3);
    var Teams = GenFu.GenFu.ListOf<Team>(20);
    dbContext.Team.AddRange(Teams);

    dbContext.SaveChanges();
}

When Creating Test Data, from what I can deduct, it was alive in two scopes (once in the Employee's Tests while the Team tests were running):

public void Team_Index_should_return_valid_model()
{
    using (var context = new TheContext(CreateNewContextOptions()))
    {
        //Arrange
        CreateTestData(context);
        var controller = new TeamController(context);

        //Act
        var actionResult = controller.Index();

        //Assert
        Assert.NotNull(actionResult);
        Assert.True(actionResult.Result is ViewResult);
        var model = ModelFromActionResult<List<Team>>((ActionResult)actionResult.Result);
        Assert.Equal(20, model.Count);
    }
}

Wrapping both Test Classes with this sequential collection attribute has cleared the apparent conflict.

[Collection("Sequential")]

Additional references:

https://github.com/aspnet/EntityFrameworkCore/issues/7340
EF Core 2.1 In memory DB not updating records
http://www.jerriepelser.com/blog/unit-testing-aspnet5-entityframework7-inmemory-database/
http://gunnarpeipman.com/2017/04/aspnet-core-ef-inmemory/
https://github.com/aspnet/EntityFrameworkCore/issues/12459
Preventing tracking issues when using EF Core SqlLite in Unit Tests

How to unmount, unrender or remove a component, from itself in a React/Redux/Typescript notification message

This isn't appropriate in all situations but you can conditionally return false inside the component itself if a certain criteria is or isn't met.

It doesn't unmount the component, but it removes all rendered content. This would only be bad, in my mind, if you have event listeners in the component that should be removed when the component is no longer needed.

import React, { Component } from 'react';

export default class MyComponent extends Component {
    constructor(props) {
        super(props);

        this.state = {
            hideComponent: false
        }
    }

    closeThis = () => {
        this.setState(prevState => ({
            hideComponent: !prevState.hideComponent
        })
    });

    render() {
        if (this.state.hideComponent === true) {return false;}

        return (
            <div className={`content`} onClick={() => this.closeThis}>
                YOUR CODE HERE
            </div>
        );
    }
}

Pass Javascript Array -> PHP

Here's a function to convert js array or object into a php-compatible array to be sent as http get request parameter:

function obj2url(prefix, obj) {
        var args=new Array();
        if(typeof(obj) == 'object'){
            for(var i in obj)
                args[args.length]=any2url(prefix+'['+encodeURIComponent(i)+']', obj[i]);
        }
        else
            args[args.length]=prefix+'='+encodeURIComponent(obj);
        return args.join('&');
    }

prefix is a parameter name.

EDIT:

var a = {
    one: two,
    three: four
};

alert('/script.php?'+obj2url('a', a)); 

Will produce

/script.php?a[one]=two&a[three]=four

which will allow you to use $_GET['a'] as an array in script.php. You will need to figure your way into your favorite ajax engine on supplying the url to call script.php from js.

json and empty array

"location" : null // this is not really an array it's a null object
"location" : []   // this is an empty array

It looks like this API returns null when there is no location defined - instead of returning an empty array, not too unusual really - but they should tell you if they're going to do this.

generate days from date range

Alright.. Try this: http://www.devshed.com/c/a/MySQL/Delving-Deeper-into-MySQL-50/
http://dev.mysql.com/doc/refman/5.0/en/loop-statement.html
http://www.roseindia.net/sql/mysql-example/mysql-loop.shtml

Use that to, say, generate a temp table, and then do a select * on the temp table. Or output the results one at a time.
What you say you want to do can't be done with a SELECT statement, but it might be doable with things specific to MySQL.
Then again, maybe you need cursors: http://dev.mysql.com/doc/refman/5.0/en/cursors.html

Why can't I define a default constructor for a struct in .NET?

A struct is a value type and a value type must have a default value as soon as it is declared.

MyClass m;
MyStruct m2;

If you declare two fields as above without instantiating either, then break the debugger, m will be null but m2 will not. Given this, a parameterless constructor would make no sense, in fact all any constructor on a struct does is assign values, the thing itself already exists just by declaring it. Indeed m2 could quite happily be used in the above example and have its methods called, if any, and its fields and properties manipulated!

Enable CORS in Web API 2

I'm most definitely hitting this issue with attribute routing. The issue was fixed as of 5.0.0-rtm-130905. But still, you can try out the nightly builds which will most certainly have the fix.

To add nightlies to your NuGet package source, go to Tools -> Library Package Manager -> Package Manager Settings and add the following URL under Package Sources: http://myget.org/F/aspnetwebstacknightly

Update TensorFlow

This is official recommendation for upgrading Tensorflow.

To get TensorFlow 1.5, you can use the standard pip installation (or pip3 if you use python3)

$  pip install --ignore-installed --upgrade tensorflow

div inside table

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
  <head>
    <title>test</title>
  </head>
  <body>
    <table>
      <tr>
        <td>
          <div>content</div>
        </td>
      </tr>
    </table>
  </body>
</html>

This document was successfully checked as XHTML 1.0 Transitional!

Tracking changes in Windows registry

PhiLho has mentioned AutoRuns in passing, but I think it deserves elaboration.

It doesn't scan the whole registry, just the parts containing references to things which get loaded automatically (EXEs, DLLs, drivers etc.) which is probably what you are interested in. It doesn't track changes but can export to a text file, so you can run it before and after installation and do a diff.

How to use a variable for the database name in T-SQL?

Put the entire script into a template string, with {SERVERNAME} placeholders. Then edit the string using:

SET @SQL_SCRIPT = REPLACE(@TEMPLATE, '{SERVERNAME}', @DBNAME)

and then run it with

EXECUTE (@SQL_SCRIPT)

It's hard to believe that, in the course of three years, nobody noticed that my code doesn't work!

You can't EXEC multiple batches. GO is a batch separator, not a T-SQL statement. It's necessary to build three separate strings, and then to EXEC each one after substitution.

I suppose one could do something "clever" by breaking the single template string into multiple rows by splitting on GO; I've done that in ADO.NET code.

And where did I get the word "SERVERNAME" from?

Here's some code that I just tested (and which works):

DECLARE @DBNAME VARCHAR(255)
SET @DBNAME = 'TestDB'

DECLARE @CREATE_TEMPLATE VARCHAR(MAX)
DECLARE @COMPAT_TEMPLATE VARCHAR(MAX)
DECLARE @RECOVERY_TEMPLATE VARCHAR(MAX)

SET @CREATE_TEMPLATE = 'CREATE DATABASE {DBNAME}'
SET @COMPAT_TEMPLATE='ALTER DATABASE {DBNAME} SET COMPATIBILITY_LEVEL = 90'
SET @RECOVERY_TEMPLATE='ALTER DATABASE {DBNAME} SET RECOVERY SIMPLE'

DECLARE @SQL_SCRIPT VARCHAR(MAX)

SET @SQL_SCRIPT = REPLACE(@CREATE_TEMPLATE, '{DBNAME}', @DBNAME)
EXECUTE (@SQL_SCRIPT)

SET @SQL_SCRIPT = REPLACE(@COMPAT_TEMPLATE, '{DBNAME}', @DBNAME)
EXECUTE (@SQL_SCRIPT)

SET @SQL_SCRIPT = REPLACE(@RECOVERY_TEMPLATE, '{DBNAME}', @DBNAME)
EXECUTE (@SQL_SCRIPT)

Remove background drawable programmatically in Android

I try this code in android 4+:

view.setBackgroundDrawable(0);

Send email with PHP from html form on submit with the same script

You need to add an action into your form like:

<form name='form1' method='post' action='<?php echo($_SERVER['PHP_SELF']);'>
    <!-- All your input for the form here -->
</form>

Then put your snippet at the top of the document en send the mail. What echo($_SERVER['PHP_SELF']); does is that it sends your information to the top of your script so you could use it.

jquery ui Dialog: cannot call methods on dialog prior to initialization

This is also some work around:

$("div[aria-describedby='divDialog'] .ui-button.ui-widget.ui-state-default.ui-corner-all.ui-button-icon-only.ui-dialog-titlebar-close").click();

Bootstrap Dropdown menu is not working

In case anyone still facing same problem be sure to check your your view Page source in your browser to check whether all the jquery and bootstrap files are loaded and paths to the file are correct. Most important! make sure to use latest stable jquery file.

Best way to store chat messages in a database?

You could create a database for x conversations which contains all messages of these conversations. This would allow you to add a new Database (or server) each time x exceeds. X is the number conversations your infrastructure supports (depending on your hardware,...).

The problem is still, that there may be big conversations (with a lot of messages) on the same database. e.g. you have database A and database B an each stores e.g. 1000 conversations. It my be possible that there are far more "big" conversations on server A than on server B (since this is user created content). You could add a "master" database that contains a lookup, on which database/server the single conversations can be found (or you have a schema to assign a database from hash/modulo or something).

Maybe you can find real world architectures that deal with the same problems (you may not be the first one), and that have already been solved.

Pandas DataFrame to List of Dictionaries

Use df.to_dict('records') -- gives the output without having to transpose externally.

In [2]: df.to_dict('records')
Out[2]:
[{'customer': 1L, 'item1': 'apple', 'item2': 'milk', 'item3': 'tomato'},
 {'customer': 2L, 'item1': 'water', 'item2': 'orange', 'item3': 'potato'},
 {'customer': 3L, 'item1': 'juice', 'item2': 'mango', 'item3': 'chips'}]

How do I run a single test using Jest?

If you have jest running as a script command, something like npm test, you need to use the following command to make it work:

npm test -- -t "fix order test"

How do I get only directories using Get-ChildItem?

You'll want to use Get-ChildItem to recursively get all folders and files first. And then pipe that output into a Where-Object clause which only take the files.

# one of several ways to identify a file is using GetType() which
# will return "FileInfo" or "DirectoryInfo"
$files = Get-ChildItem E:\ -Recurse | Where-Object {$_.GetType().Name -eq "FileInfo"} ;

foreach ($file in $files) {
  echo $file.FullName ;
}

Ignore duplicates when producing map using streams

Assuming you have people is List of object

  Map<String, String> phoneBook=people.stream()
                                        .collect(toMap(Person::getName, Person::getAddress));

Now you need two steps :

1)

people =removeDuplicate(people);

2)

Map<String, String> phoneBook=people.stream()
                                        .collect(toMap(Person::getName, Person::getAddress));

Here is method to remove duplicate

public static List removeDuplicate(Collection<Person>  list) {
        if(list ==null || list.isEmpty()){
            return null;
        }

        Object removedDuplicateList =
                list.stream()
                     .distinct()
                     .collect(Collectors.toList());
     return (List) removedDuplicateList;

      }

Adding full example here

 package com.example.khan.vaquar;

import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class RemovedDuplicate {

    public static void main(String[] args) {
        Person vaquar = new Person(1, "Vaquar", "Khan");
        Person zidan = new Person(2, "Zidan", "Khan");
        Person zerina = new Person(3, "Zerina", "Khan");

        // Add some random persons
        Collection<Person> duplicateList = Arrays.asList(vaquar, zidan, zerina, vaquar, zidan, vaquar);

        //
        System.out.println("Before removed duplicate list" + duplicateList);
        //
        Collection<Person> nonDuplicateList = removeDuplicate(duplicateList);
        //
        System.out.println("");
        System.out.println("After removed duplicate list" + nonDuplicateList);
        ;

        // 1) solution Working code
        Map<Object, Object> k = nonDuplicateList.stream().distinct()
                .collect(Collectors.toMap(s1 -> s1.getId(), s1 -> s1));
        System.out.println("");
        System.out.println("Result 1 using method_______________________________________________");
        System.out.println("k" + k);
        System.out.println("_____________________________________________________________________");

        // 2) solution using inline distinct()
        Map<Object, Object> k1 = duplicateList.stream().distinct()
                .collect(Collectors.toMap(s1 -> s1.getId(), s1 -> s1));
        System.out.println("");
        System.out.println("Result 2 using inline_______________________________________________");
        System.out.println("k1" + k1);
        System.out.println("_____________________________________________________________________");

        //breacking code
        System.out.println("");
        System.out.println("Throwing exception _______________________________________________");
        Map<Object, Object> k2 = duplicateList.stream()
                .collect(Collectors.toMap(s1 -> s1.getId(), s1 -> s1));
        System.out.println("");
        System.out.println("k2" + k2);
        System.out.println("_____________________________________________________________________");
    }

    public static List removeDuplicate(Collection<Person> list) {
        if (list == null || list.isEmpty()) {
            return null;
        }

        Object removedDuplicateList = list.stream().distinct().collect(Collectors.toList());
        return (List) removedDuplicateList;

    }

}

// Model class
class Person {
    public Person(Integer id, String fname, String lname) {
        super();
        this.id = id;
        this.fname = fname;
        this.lname = lname;
    }

    private Integer id;
    private String fname;
    private String lname;

    // Getters and Setters

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getFname() {
        return fname;
    }

    public void setFname(String fname) {
        this.fname = fname;
    }

    public String getLname() {
        return lname;
    }

    public void setLname(String lname) {
        this.lname = lname;
    }

    @Override
    public String toString() {
        return "Person [id=" + id + ", fname=" + fname + ", lname=" + lname + "]";
    }

}

Results :

Before removed duplicate list[Person [id=1, fname=Vaquar, lname=Khan], Person [id=2, fname=Zidan, lname=Khan], Person [id=3, fname=Zerina, lname=Khan], Person [id=1, fname=Vaquar, lname=Khan], Person [id=2, fname=Zidan, lname=Khan], Person [id=1, fname=Vaquar, lname=Khan]]

After removed duplicate list[Person [id=1, fname=Vaquar, lname=Khan], Person [id=2, fname=Zidan, lname=Khan], Person [id=3, fname=Zerina, lname=Khan]]

Result 1 using method_______________________________________________
k{1=Person [id=1, fname=Vaquar, lname=Khan], 2=Person [id=2, fname=Zidan, lname=Khan], 3=Person [id=3, fname=Zerina, lname=Khan]}
_____________________________________________________________________

Result 2 using inline_______________________________________________
k1{1=Person [id=1, fname=Vaquar, lname=Khan], 2=Person [id=2, fname=Zidan, lname=Khan], 3=Person [id=3, fname=Zerina, lname=Khan]}
_____________________________________________________________________

Throwing exception _______________________________________________
Exception in thread "main" java.lang.IllegalStateException: Duplicate key Person [id=1, fname=Vaquar, lname=Khan]
    at java.util.stream.Collectors.lambda$throwingMerger$0(Collectors.java:133)
    at java.util.HashMap.merge(HashMap.java:1253)
    at java.util.stream.Collectors.lambda$toMap$58(Collectors.java:1320)
    at java.util.stream.ReduceOps$3ReducingSink.accept(ReduceOps.java:169)
    at java.util.Spliterators$ArraySpliterator.forEachRemaining(Spliterators.java:948)
    at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481)
    at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471)
    at java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:708)
    at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
    at java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:499)
    at com.example.khan.vaquar.RemovedDuplicate.main(RemovedDuplicate.java:48)

converting numbers in to words C#

When I had to solve this problem, I created a hard-coded data dictionary to map between numbers and their associated words. For example, the following might represent a few entries in the dictionary:

{1, "one"}
{2, "two"}
{30, "thirty"}

You really only need to worry about mapping numbers in the 10^0 (1,2,3, etc.) and 10^1 (10,20,30) positions because once you get to 100, you simply have to know when to use words like hundred, thousand, million, etc. in combination with your map. For example, when you have a number like 3,240,123, you get: three million two hundred forty thousand one hundred twenty three.

After you build your map, you need to work through each digit in your number and figure out the appropriate nomenclature to go with it.

How can I find an element by CSS class with XPath?

I'm just providing this as an answer, as Tomalak provided as a comment to meder's answer a long time ago

//div[contains(concat(' ', @class, ' '), ' Test ')]

Extracting extension from filename in Python

For simple use cases one option may be splitting from dot:

>>> filename = "example.jpeg"
>>> filename.split(".")[-1]
'jpeg'

No error when file doesn't have an extension:

>>> "filename".split(".")[-1]
'filename'

But you must be careful:

>>> "png".split(".")[-1]
'png'    # But file doesn't have an extension

Also will not work with hidden files in Unix systems:

>>> ".bashrc".split(".")[-1]
'bashrc'    # But this is not an extension

For general use, prefer os.path.splitext

How to perform Join between multiple tables in LINQ lambda

it has been a while but my answer may help someone:

if you already defined the relation properly you can use this:

        var res = query.Products.Select(m => new
        {
            productID = product.Id,
            categoryID = m.ProductCategory.Select(s => s.Category.ID).ToList(),
        }).ToList();

The application was unable to start correctly (0xc000007b)

Actually this error indicates to an invalid image format. However, why this is happening and what the error code usually means? Actually this could be appear when you are trying to run a program that is made for or intended to work with a 64 bit Windows operating system, but your computer is running on 32 bit Operating system.

Possible Reasons:

  • Microsoft Visual C++
  • Need to restart
  • DirectX
  • .NET Framework
  • Need to Re-Install
  • Need to Run the application as an administrator

Source: http://www.solveinweb.com/solved-the-application-was-unable-to-start-correctly-0xc000007b-click-ok-to-close-the-application/

How to handle change text of span

Found the solution here

Lets say you have span1 as <span id='span1'>my text</span>
text change events can be captured with:

$(document).ready(function(){
    $("#span1").on('DOMSubtreeModified',function(){
         // text change handler
     });

 });
 

How do I auto-resize an image to fit a 'div' container?

I fixed this problem using the following code:

<div class="container"><img src="image_url" /></div>
.container {
    height: 75px;
    width: 75px;
}

.container img {
    object-fit: cover;
    object-position: top;
    display: block;
    height: 100%;
    width: 100%;
}

What are the calling conventions for UNIX & Linux system calls (and user-space functions) on i386 and x86-64

Further reading for any of the topics here: The Definitive Guide to Linux System Calls


I verified these using GNU Assembler (gas) on Linux.

Kernel Interface

x86-32 aka i386 Linux System Call convention:

In x86-32 parameters for Linux system call are passed using registers. %eax for syscall_number. %ebx, %ecx, %edx, %esi, %edi, %ebp are used for passing 6 parameters to system calls.

The return value is in %eax. All other registers (including EFLAGS) are preserved across the int $0x80.

I took following snippet from the Linux Assembly Tutorial but I'm doubtful about this. If any one can show an example, it would be great.

If there are more than six arguments, %ebx must contain the memory location where the list of arguments is stored - but don't worry about this because it's unlikely that you'll use a syscall with more than six arguments.

For an example and a little more reading, refer to http://www.int80h.org/bsdasm/#alternate-calling-convention. Another example of a Hello World for i386 Linux using int 0x80: Hello, world in assembly language with Linux system calls?

There is a faster way to make 32-bit system calls: using sysenter. The kernel maps a page of memory into every process (the vDSO), with the user-space side of the sysenter dance, which has to cooperate with the kernel for it to be able to find the return address. Arg to register mapping is the same as for int $0x80. You should normally call into the vDSO instead of using sysenter directly. (See The Definitive Guide to Linux System Calls for info on linking and calling into the vDSO, and for more info on sysenter, and everything else to do with system calls.)

x86-32 [Free|Open|Net|DragonFly]BSD UNIX System Call convention:

Parameters are passed on the stack. Push the parameters (last parameter pushed first) on to the stack. Then push an additional 32-bit of dummy data (Its not actually dummy data. refer to following link for more info) and then give a system call instruction int $0x80

http://www.int80h.org/bsdasm/#default-calling-convention


x86-64 Linux System Call convention:

(Note: x86-64 Mac OS X is similar but different from Linux. TODO: check what *BSD does)

Refer to section: "A.2 AMD64 Linux Kernel Conventions" of System V Application Binary Interface AMD64 Architecture Processor Supplement. The latest versions of the i386 and x86-64 System V psABIs can be found linked from this page in the ABI maintainer's repo. (See also the tag wiki for up-to-date ABI links and lots of other good stuff about x86 asm.)

Here is the snippet from this section:

  1. User-level applications use as integer registers for passing the sequence %rdi, %rsi, %rdx, %rcx, %r8 and %r9. The kernel interface uses %rdi, %rsi, %rdx, %r10, %r8 and %r9.
  2. A system-call is done via the syscall instruction. This clobbers %rcx and %r11 as well as the %rax return value, but other registers are preserved.
  3. The number of the syscall has to be passed in register %rax.
  4. System-calls are limited to six arguments, no argument is passed directly on the stack.
  5. Returning from the syscall, register %rax contains the result of the system-call. A value in the range between -4095 and -1 indicates an error, it is -errno.
  6. Only values of class INTEGER or class MEMORY are passed to the kernel.

Remember this is from the Linux-specific appendix to the ABI, and even for Linux it's informative not normative. (But it is in fact accurate.)

This 32-bit int $0x80 ABI is usable in 64-bit code (but highly not recommended). What happens if you use the 32-bit int 0x80 Linux ABI in 64-bit code? It still truncates its inputs to 32-bit, so it's unsuitable for pointers, and it zeros r8-r11.

User Interface: function calling

x86-32 Function Calling convention:

In x86-32 parameters were passed on stack. Last parameter was pushed first on to the stack until all parameters are done and then call instruction was executed. This is used for calling C library (libc) functions on Linux from assembly.

Modern versions of the i386 System V ABI (used on Linux) require 16-byte alignment of %esp before a call, like the x86-64 System V ABI has always required. Callees are allowed to assume that and use SSE 16-byte loads/stores that fault on unaligned. But historically, Linux only required 4-byte stack alignment, so it took extra work to reserve naturally-aligned space even for an 8-byte double or something.

Some other modern 32-bit systems still don't require more than 4 byte stack alignment.


x86-64 System V user-space Function Calling convention:

x86-64 System V passes args in registers, which is more efficient than i386 System V's stack args convention. It avoids the latency and extra instructions of storing args to memory (cache) and then loading them back again in the callee. This works well because there are more registers available, and is better for modern high-performance CPUs where latency and out-of-order execution matter. (The i386 ABI is very old).

In this new mechanism: First the parameters are divided into classes. The class of each parameter determines the manner in which it is passed to the called function.

For complete information refer to : "3.2 Function Calling Sequence" of System V Application Binary Interface AMD64 Architecture Processor Supplement which reads, in part:

Once arguments are classified, the registers get assigned (in left-to-right order) for passing as follows:

  1. If the class is MEMORY, pass the argument on the stack.
  2. If the class is INTEGER, the next available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8 and %r9 is used

So %rdi, %rsi, %rdx, %rcx, %r8 and %r9 are the registers in order used to pass integer/pointer (i.e. INTEGER class) parameters to any libc function from assembly. %rdi is used for the first INTEGER parameter. %rsi for 2nd, %rdx for 3rd and so on. Then call instruction should be given. The stack (%rsp) must be 16B-aligned when call executes.

If there are more than 6 INTEGER parameters, the 7th INTEGER parameter and later are passed on the stack. (Caller pops, same as x86-32.)

The first 8 floating point args are passed in %xmm0-7, later on the stack. There are no call-preserved vector registers. (A function with a mix of FP and integer arguments can have more than 8 total register arguments.)

Variadic functions (like printf) always need %al = the number of FP register args.

There are rules for when to pack structs into registers (rdx:rax on return) vs. in memory. See the ABI for details, and check compiler output to make sure your code agrees with compilers about how something should be passed/returned.


Note that the Windows x64 function calling convention has multiple significant differences from x86-64 System V, like shadow space that must be reserved by the caller (instead of a red-zone), and call-preserved xmm6-xmm15. And very different rules for which arg goes in which register.

SQL providerName in web.config

 WebConfigurationManager.ConnectionStrings["YourConnectionString"].ProviderName;

How to get Printer Info in .NET?

As dowski suggested, you could use WMI to get printer properties. The following code displays all properties for a given printer name. Among them you will find: PrinterStatus, Comment, Location, DriverName, PortName, etc.

using System.Management;

...

string printerName = "YourPrinterName";
string query = string.Format("SELECT * from Win32_Printer WHERE Name LIKE '%{0}'", printerName);

using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(query))
using (ManagementObjectCollection coll = searcher.Get())
{
    try
    {
        foreach (ManagementObject printer in coll)
        {
            foreach (PropertyData property in printer.Properties)
            {
                Console.WriteLine(string.Format("{0}: {1}", property.Name, property.Value));
            }
        }
    }
    catch (ManagementException ex)
    {
        Console.WriteLine(ex.Message);
    }
}

How to search JSON tree with jQuery

Once you have the JSON loaded into a JavaScript object, it's no longer a jQuery problem but is now a JavaScript problem. In JavaScript you could for instance write a search such as:

var people = myJson["people"];
var persons = people["person"];
for(var i=0; i < persons.length; ++i) {
    var person_i = persons[i];
    if(person_i["name"] == mySearchForName) {
        // found ! do something with 'person_i'.
        break;
    }
}
// not found !

Post Build exited with code 1

My reason for the Code 1 was that the target folder was read only. Hope this helps someone! I had a post build event to do a copy from one directory to another and the destination was read only. So I just went and unchecked the read-only attribute on the directory and all its subdirectories! Just make sure that its a directory that's safe to do so!

How to make ng-repeat filter out duplicate results

None of the above filters fixed my issue so I had to copy the filter from official github doc. And then use it as explained in the above answers

angular.module('yourAppNameHere').filter('unique', function () {

return function (items, filterOn) {

if (filterOn === false) {
  return items;
}

if ((filterOn || angular.isUndefined(filterOn)) && angular.isArray(items)) {
  var hashCheck = {}, newItems = [];

  var extractValueToCompare = function (item) {
    if (angular.isObject(item) && angular.isString(filterOn)) {
      return item[filterOn];
    } else {
      return item;
    }
  };

  angular.forEach(items, function (item) {
    var valueToCheck, isDuplicate = false;

    for (var i = 0; i < newItems.length; i++) {
      if (angular.equals(extractValueToCompare(newItems[i]), extractValueToCompare(item))) {
        isDuplicate = true;
        break;
      }
    }
    if (!isDuplicate) {
      newItems.push(item);
    }

  });
  items = newItems;
}
return items;
  };

});

How do I record audio on iPhone with AVAudioRecorder?

Great Thanks to @Massimo Cafaro and Shaybc I was able achieve below tasks

in iOS 8 :

Record audio & Save

Play Saved Recording

1.Add "AVFoundation.framework" to your project

in .h file

2.Add below import statement 'AVFoundation/AVFoundation.h'.

3.Define "AVAudioRecorderDelegate"

4.Create a layout with Record, Play buttons and their action methids

5.Define Recorder and Player etc.

Here is the complete example code which may help you.

ViewController.h

#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>

@interface ViewController : UIViewController <AVAudioRecorderDelegate>

@property(nonatomic,strong) AVAudioRecorder *recorder;
@property(nonatomic,strong) NSMutableDictionary *recorderSettings;
@property(nonatomic,strong) NSString *recorderFilePath;
@property(nonatomic,strong) AVAudioPlayer *audioPlayer;
@property(nonatomic,strong) NSString *audioFileName;

- (IBAction)startRecording:(id)sender;
- (IBAction)stopRecording:(id)sender;

- (IBAction)startPlaying:(id)sender;
- (IBAction)stopPlaying:(id)sender;

@end

Then do the job in

ViewController.m

#import "ViewController.h"

#define DOCUMENTS_FOLDER [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"]

@interface ViewController ()
@end

@implementation ViewController

@synthesize recorder,recorderSettings,recorderFilePath;
@synthesize audioPlayer,audioFileName;


#pragma mark - View Controller Life cycle methods
- (void)viewDidLoad
{
    [super viewDidLoad];
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}


#pragma mark - Audio Recording
- (IBAction)startRecording:(id)sender
{
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    NSError *err = nil;
    [audioSession setCategory :AVAudioSessionCategoryPlayAndRecord error:&err];
    if(err)
    {
        NSLog(@"audioSession: %@ %ld %@", [err domain], (long)[err code], [[err userInfo] description]);
        return;
    }
    [audioSession setActive:YES error:&err];
    err = nil;
    if(err)
    {
        NSLog(@"audioSession: %@ %ld %@", [err domain], (long)[err code], [[err userInfo] description]);
        return;
    }
    
    recorderSettings = [[NSMutableDictionary alloc] init];
    [recorderSettings setValue :[NSNumber numberWithInt:kAudioFormatLinearPCM] forKey:AVFormatIDKey];
    [recorderSettings setValue:[NSNumber numberWithFloat:44100.0] forKey:AVSampleRateKey];
    [recorderSettings setValue:[NSNumber numberWithInt: 2] forKey:AVNumberOfChannelsKey];
    [recorderSettings setValue :[NSNumber numberWithInt:16] forKey:AVLinearPCMBitDepthKey];
    [recorderSettings setValue :[NSNumber numberWithBool:NO] forKey:AVLinearPCMIsBigEndianKey];
    [recorderSettings setValue :[NSNumber numberWithBool:NO] forKey:AVLinearPCMIsFloatKey];
    
    // Create a new audio file
    audioFileName = @"recordingTestFile";
    recorderFilePath = [NSString stringWithFormat:@"%@/%@.caf", DOCUMENTS_FOLDER, audioFileName] ;
    
    NSURL *url = [NSURL fileURLWithPath:recorderFilePath];
    err = nil;
    recorder = [[ AVAudioRecorder alloc] initWithURL:url settings:recorderSettings error:&err];
    if(!recorder){
        NSLog(@"recorder: %@ %ld %@", [err domain], (long)[err code], [[err userInfo] description]);
        UIAlertView *alert =
        [[UIAlertView alloc] initWithTitle: @"Warning" message: [err localizedDescription] delegate: nil
                         cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alert show];
        return;
    }
    
    //prepare to record
    [recorder setDelegate:self];
    [recorder prepareToRecord];
    recorder.meteringEnabled = YES;
    
    BOOL audioHWAvailable = audioSession.inputIsAvailable;
    if (! audioHWAvailable) {
        UIAlertView *cantRecordAlert =
        [[UIAlertView alloc] initWithTitle: @"Warning"message: @"Audio input hardware not available"
                                  delegate: nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [cantRecordAlert show];
        return;
    }
    
    // start recording
    [recorder recordForDuration:(NSTimeInterval) 60];//Maximum recording time : 60 seconds default
    NSLog(@"Recroding Started");
}

- (IBAction)stopRecording:(id)sender
{
    [recorder stop];
    NSLog(@"Recording Stopped");
}

- (void)audioRecorderDidFinishRecording:(AVAudioRecorder *) aRecorder successfully:(BOOL)flag
{
    NSLog (@"audioRecorderDidFinishRecording:successfully:");
}


#pragma mark - Audio Playing
- (IBAction)startPlaying:(id)sender
{
    NSLog(@"playRecording");
    
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    [audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];
    
     NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/%@.caf", DOCUMENTS_FOLDER, audioFileName]];
    NSError *error;
    audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
    audioPlayer.numberOfLoops = 0;
    [audioPlayer play];
    NSLog(@"playing");
}
- (IBAction)stopPlaying:(id)sender
{
    [audioPlayer stop];
    NSLog(@"stopped");
}

@end

enter image description here

enable or disable checkbox in html

<input type="checkbox" value="" ng-model="t.IsPullPoint" onclick="return false;" onkeydown="return false;"><span class="cr"></span></label>

How can I make visible an invisible control with jquery? (hide and show not work)

You can't do this with jQuery, visible="false" in asp.net means the control isn't rendered into the page. If you want the control to go to the client, you need to do style="display: none;" so it's actually in the HTML, otherwise there's literally nothing for the client to show, since the element wasn't in the HTML your server sent.

If you remove the visible attribute and add the style attribute you can then use jQuery to show it, like this:

$("#elementID").show();

Old Answer (before patrick's catch)

To change visibility, you need to use .css(), like this:

$("#elem").css('visibility', 'visible');

Unless you need to have the element occupy page space though, use display: none; instead of visibility: hidden; in your CSS, then just do:

$("#elem").show();

The .show() and .hide() functions deal with display instead of visibility, like most of the jQuery functions :)

changing default x range in histogram matplotlib

the following code is for making the same y axis limit on two subplots

f ,ax = plt.subplots(1,2,figsize = (30, 13),gridspec_kw={'width_ratios': [5, 1]})
df.plot(ax = ax[0], linewidth = 2.5)
ylim = [lower_limit,upper_limit]
ax[0].set_ylim(ylim)
ax[1].hist(data,normed =1, bins = num_bin, color = 'yellow' ,alpha = 1) 
ax[1].set_ylim(ylim)

just a reminder, plt.hist(range=[low, high]) the histogram auto crops the range if the specified range is larger than the max&min of the data points. So if you want to specify the y-axis range number, i prefer to use set_ylim

Sort a Map<Key, Value> by values

Three 1-line answers...

I would use Google Collections Guava to do this - if your values are Comparable then you can use

valueComparator = Ordering.natural().onResultOf(Functions.forMap(map))

Which will create a function (object) for the map [that takes any of the keys as input, returning the respective value], and then apply natural (comparable) ordering to them [the values].

If they're not comparable, then you'll need to do something along the lines of

valueComparator = Ordering.from(comparator).onResultOf(Functions.forMap(map)) 

These may be applied to a TreeMap (as Ordering extends Comparator), or a LinkedHashMap after some sorting

NB: If you are going to use a TreeMap, remember that if a comparison == 0, then the item is already in the list (which will happen if you have multiple values that compare the same). To alleviate this, you could add your key to the comparator like so (presuming that your keys and values are Comparable):

valueComparator = Ordering.natural().onResultOf(Functions.forMap(map)).compound(Ordering.natural())

= Apply natural ordering to the value mapped by the key, and compound that with the natural ordering of the key

Note that this will still not work if your keys compare to 0, but this should be sufficient for most comparable items (as hashCode, equals and compareTo are often in sync...)

See Ordering.onResultOf() and Functions.forMap().

Implementation

So now that we've got a comparator that does what we want, we need to get a result from it.

map = ImmutableSortedMap.copyOf(myOriginalMap, valueComparator);

Now this will most likely work work, but:

  1. needs to be done given a complete finished map
  2. Don't try the comparators above on a TreeMap; there's no point trying to compare an inserted key when it doesn't have a value until after the put, i.e., it will break really fast

Point 1 is a bit of a deal-breaker for me; google collections is incredibly lazy (which is good: you can do pretty much every operation in an instant; the real work is done when you start using the result), and this requires copying a whole map!

"Full" answer/Live sorted map by values

Don't worry though; if you were obsessed enough with having a "live" map sorted in this manner, you could solve not one but both(!) of the above issues with something crazy like the following:

Note: This has changed significantly in June 2012 - the previous code could never work: an internal HashMap is required to lookup the values without creating an infinite loop between the TreeMap.get() -> compare() and compare() -> get()

import static org.junit.Assert.assertEquals;

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

import com.google.common.base.Functions;
import com.google.common.collect.Ordering;

class ValueComparableMap<K extends Comparable<K>,V> extends TreeMap<K,V> {
    //A map for doing lookups on the keys for comparison so we don't get infinite loops
    private final Map<K, V> valueMap;

    ValueComparableMap(final Ordering<? super V> partialValueOrdering) {
        this(partialValueOrdering, new HashMap<K,V>());
    }

    private ValueComparableMap(Ordering<? super V> partialValueOrdering,
            HashMap<K, V> valueMap) {
        super(partialValueOrdering //Apply the value ordering
                .onResultOf(Functions.forMap(valueMap)) //On the result of getting the value for the key from the map
                .compound(Ordering.natural())); //as well as ensuring that the keys don't get clobbered
        this.valueMap = valueMap;
    }

    public V put(K k, V v) {
        if (valueMap.containsKey(k)){
            //remove the key in the sorted set before adding the key again
            remove(k);
        }
        valueMap.put(k,v); //To get "real" unsorted values for the comparator
        return super.put(k, v); //Put it in value order
    }

    public static void main(String[] args){
        TreeMap<String, Integer> map = new ValueComparableMap<String, Integer>(Ordering.natural());
        map.put("a", 5);
        map.put("b", 1);
        map.put("c", 3);
        assertEquals("b",map.firstKey());
        assertEquals("a",map.lastKey());
        map.put("d",0);
        assertEquals("d",map.firstKey());
        //ensure it's still a map (by overwriting a key, but with a new value) 
        map.put("d", 2);
        assertEquals("b", map.firstKey());
        //Ensure multiple values do not clobber keys
        map.put("e", 2);
        assertEquals(5, map.size());
        assertEquals(2, (int) map.get("e"));
        assertEquals(2, (int) map.get("d"));
    }
 }

When we put, we ensure that the hash map has the value for the comparator, and then put to the TreeSet for sorting. But before that we check the hash map to see that the key is not actually a duplicate. Also, the comparator that we create will also include the key so that duplicate values don't delete the non-duplicate keys (due to == comparison). These 2 items are vital for ensuring the map contract is kept; if you think you don't want that, then you're almost at the point of reversing the map entirely (to Map<V,K>).

The constructor would need to be called as

 new ValueComparableMap(Ordering.natural());
 //or
 new ValueComparableMap(Ordering.from(comparator));

Dictionary text file

For an English dictionary .txt file, you can use Custom Dictionary.

You can also generate a list aspell or wordlist with own settings.

Also you can take a look at http://wordlist.sourceforge.net/

Only english words: http://www.math.sjsu.edu/~foster/dictionary.txt

Make child visible outside an overflow:hidden parent

You can use the clearfix to do "layout preserving" the same way overflow: hidden does.

.clearfix:before,
.clearfix:after {
    content: ".";    
    display: block;    
    height: 0;    
    overflow: hidden; 
}
.clearfix:after { clear: both; }
.clearfix { zoom: 1; } /* IE < 8 */

add class="clearfix" class to the parent, and remove overflow: hidden;

How to implement DrawerArrowToggle from Android appcompat v7 21 library

First, you should know now the android.support.v4.app.ActionBarDrawerToggle is deprecated.

You must replace that with android.support.v7.app.ActionBarDrawerToggle.

Here is my example and I use the new Toolbar to replace the ActionBar.

MainActivity.java

public class MainActivity extends ActionBarActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Toolbar mToolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(mToolbar);
    DrawerLayout mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle mDrawerToggle = new ActionBarDrawerToggle(
        this,  mDrawerLayout, mToolbar,
        R.string.navigation_drawer_open, R.string.navigation_drawer_close
    );
    mDrawerLayout.setDrawerListener(mDrawerToggle);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setHomeButtonEnabled(true);
    mDrawerToggle.syncState();
}

styles.xml

<style name="AppTheme" parent="Theme.AppCompat.Light">
    <item name="drawerArrowStyle">@style/DrawerArrowStyle</item>
</style>

<style name="DrawerArrowStyle" parent="Widget.AppCompat.DrawerArrowToggle">
    <item name="spinBars">true</item>
    <item name="color">@android:color/white</item>
</style>

You can read the documents on AndroidDocument#DrawerArrowToggle_spinBars

This attribute is the key to implement the menu-to-arrow animation.

public static int DrawerArrowToggle_spinBars

Whether bars should rotate or not during transition
Must be a boolean value, either "true" or "false".

So, you set this: <item name="spinBars">true</item>.

Then the animation can be presented.

Hope this can help you.

How to pass an array into a function, and return the results with an array

I always return multiple values by using a combination of list() and array()s:

function DecideStuffToReturn() {
    $IsValid = true;
    $AnswerToLife = 42;

    // Build the return array.
    return array($IsValid, $AnswerToLife);
}

// Part out the return array in to multiple variables.
list($IsValid, $AnswerToLife) = DecideStuffToReturn();

You can name them whatever you like. I chose to keep the function variables and the return variables the same for consistency but you can call them whatever you like.

See list() for more information.

select unique rows based on single distinct column

Since you don't care which id to return I stick with MAX id for each email to simplify SQL query, give it a try

;WITH ue(id)
 AS
 (
   SELECT MAX(id)
   FROM table
   GROUP BY email
 )
 SELECT * FROM table t
 INNER JOIN ue ON ue.id = t.id

Error when creating a new text file with python?

This works just fine, but instead of

name = input('Enter name of text file: ')+'.txt' 

you should use

name = raw_input('Enter name of text file: ')+'.txt'

along with

open(name,'a') or open(name,'w')

Error "package android.support.v7.app does not exist"

If your app is AndroidX, This response may apply to your problem:

npm install --save-dev jetifier
npx jetify (may take a while)
npx react-native run-android

How can I sort one set of data to match another set of data in Excel?

You could also simply link both cells, and have an =Cell formula in each column like, =Sheet2!A2 in Sheet 1 A2 and =Sheet2!B2 in Sheet 1 B2, and drag it down, and then sort those two columns the way you want.

  • If they don't sort the way you want, put the order you want to sort them in another column and sort all three columns by that.
  • If you drag it down further and get zeros you can edit the =Cell formula to show "" IF there is nothing. =(if(cell="","",cell)
  • Cutting, pasting, deleting, and inserting rows is something to be weary of. #REF! errors could occur.

This would be better if your unique items change also, then all you would do is sort and be done.

How to use sessions in an ASP.NET MVC 4 application?

This is how session state works in ASP.NET and ASP.NET MVC:

ASP.NET Session State Overview

Basically, you do this to store a value in the Session object:

Session["FirstName"] = FirstNameTextBox.Text;

To retrieve the value:

var firstName = Session["FirstName"];

How do I use properly CASE..WHEN in MySQL

There are two variants of CASE, and you're not using the one that you think you are.

What you're doing

CASE case_value
    WHEN when_value THEN statement_list
    [WHEN when_value THEN statement_list] ...
    [ELSE statement_list]
END CASE

Each condition is loosely equivalent to a if (case_value == when_value) (pseudo-code).

However, you've put an entire condition as when_value, leading to something like:

if (case_value == (case_value > 100))

Now, (case_value > 100) evaluates to FALSE, and is the only one of your conditions to do so. So, now you have:

if (case_value == FALSE)

FALSE converts to 0 and, through the resulting full expression if (case_value == 0) you can now see why the third condition fires.

What you're supposed to do

Drop the first course_enrollment_settings so that there's no case_value, causing MySQL to know that you intend to use the second variant of CASE:

CASE
    WHEN search_condition THEN statement_list
    [WHEN search_condition THEN statement_list] ...
    [ELSE statement_list]
END CASE

Now you can provide your full conditionals as search_condition.

Also, please read the documentation for features that you use.

How do you calculate program run time in python?

You might want to take a look at the timeit module:

http://docs.python.org/library/timeit.html

or the profile module:

http://docs.python.org/library/profile.html

There are some additionally some nice tutorials here:

http://www.doughellmann.com/PyMOTW/profile/index.html

http://www.doughellmann.com/PyMOTW/timeit/index.html

And the time module also might come in handy, although I prefer the later two recommendations for benchmarking and profiling code performance:

http://docs.python.org/library/time.html

Add an image in a WPF button

I also had the same issue. I've fixed it by using the following code.

        <Button Width="30" Margin="0,5" HorizontalAlignment="Stretch"  Click="OnSearch" >
            <DockPanel>
                <Image Source="../Resources/Back.jpg"/>
            </DockPanel>
        </Button>

Note: Make sure the build action of the image in the property window, should be Resource.

enter image description here

Android Studio Gradle project "Unable to start the daemon process /initialization of VM"

I had the same problem. Starting Android Studio as Administrator fixed it.

Regular Expression to match every new line character (\n) inside a <content> tag

Actually... you can't use a simple regex here, at least not one. You probably need to worry about comments! Someone may write:

<!-- <content> blah </content> -->

You can take two approaches here:

  1. Strip all comments out first. Then use the regex approach.
  2. Do not use regular expressions and use a context sensitive parsing approach that can keep track of whether or not you are nested in a comment.

Be careful.

I am also not so sure you can match all new lines at once. @Quartz suggested this one:

<content>([^\n]*\n+)+</content>

This will match any content tags that have a newline character RIGHT BEFORE the closing tag... but I'm not sure what you mean by matching all newlines. Do you want to be able to access all the matched newline characters? If so, your best bet is to grab all content tags, and then search for all the newline chars that are nested in between. Something more like this:

<content>.*</content>

BUT THERE IS ONE CAVEAT: regexes are greedy, so this regex will match the first opening tag to the last closing one. Instead, you HAVE to suppress the regex so it is not greedy. In languages like python, you can do this with the "?" regex symbol.

I hope with this you can see some of the pitfalls and figure out how you want to proceed. You are probably better off using an XML parsing library, then iterating over all the content tags.

I know I may not be offering the best solution, but at least I hope you will see the difficulty in this and why other answers may not be right...

UPDATE 1:

Let me summarize a bit more and add some more detail to my response. I am going to use python's regex syntax because it is what I am more used to (forgive me ahead of time... you may need to escape some characters... comment on my post and I will correct it):

To strip out comments, use this regex: Notice the "?" suppresses the .* to make it non-greedy.

Similarly, to search for content tags, use: .*?

Also, You may be able to try this out, and access each newline character with the match objects groups():

<content>(.*?(\n))+.*?</content>

I know my escaping is off, but it captures the idea. This last example probably won't work, but I think it's your best bet at expressing what you want. My suggestion remains: either grab all the content tags and do it yourself, or use a parsing library.

UPDATE 2:

So here is python code that ought to work. I am still unsure what you mean by "find" all newlines. Do you want the entire lines? Or just to count how many newlines. To get the actual lines, try:

#!/usr/bin/python

import re

def FindContentNewlines(xml_text):
    # May want to compile these regexes elsewhere, but I do it here for brevity
    comments = re.compile(r"<!--.*?-->", re.DOTALL)
    content = re.compile(r"<content>(.*?)</content>", re.DOTALL)
    newlines = re.compile(r"^(.*?)$", re.MULTILINE|re.DOTALL)

    # strip comments: this actually may not be reliable for "nested comments"
    # How does xml handle <!--  <!-- --> -->. I am not sure. But that COULD
    # be trouble.
    xml_text = re.sub(comments, "", xml_text)

    result = []
    all_contents = re.findall(content, xml_text)
    for c in all_contents:
        result.extend(re.findall(newlines, c))

    return result

if __name__ == "__main__":
    example = """

<!-- This stuff
ought to be omitted
<content>
  omitted
</content>
-->

This stuff is good
<content>
<p>
  haha!
</p>
</content>

This is not found
"""
    print FindContentNewlines(example)

This program prints the result:

 ['', '<p>', '  haha!', '</p>', '']

The first and last empty strings come from the newline chars immediately preceeding the first <p> and the one coming right after the </p>. All in all this (for the most part) does the trick. Experiment with this code and refine it for your needs. Print out stuff in the middle so you can see what the regexes are matching and not matching.

Hope this helps :-).

PS - I didn't have much luck trying out my regex from my first update to capture all the newlines... let me know if you do.

Get everything after the dash in a string in JavaScript

How I would do this:

// function you can use:
function getSecondPart(str) {
    return str.split('-')[1];
}
// use the function:
alert(getSecondPart("sometext-20202"));

if (select count(column) from table) > 0 then

You cannot directly use a SQL statement in a PL/SQL expression:

SQL> begin
  2     if (select count(*) from dual) >= 1 then
  3        null;
  4     end if;
  5  end;
  6  /
        if (select count(*) from dual) >= 1 then
            *
ERROR at line 2:
ORA-06550: line 2, column 6:
PLS-00103: Encountered the symbol "SELECT" when expecting one of the following:
...
...

You must use a variable instead:

SQL> set serveroutput on
SQL>
SQL> declare
  2     v_count number;
  3  begin
  4     select count(*) into v_count from dual;
  5
  6     if v_count >= 1 then
  7             dbms_output.put_line('Pass');
  8     end if;
  9  end;
 10  /
Pass

PL/SQL procedure successfully completed.

Of course, you may be able to do the whole thing in SQL:

update my_table
set x = y
where (select count(*) from other_table) >= 1;

It's difficult to prove that something is not possible. Other than the simple test case above, you can look at the syntax diagram for the IF statement; you won't see a SELECT statement in any of the branches.

How do I put a border around an Android textview?

You can add something like this in your code:

<shape xmlns:android="http://schemas.android.com/apk/res/android"
       android:shape="rectangle" >
    <solid android:color="#ffffff" />
    <stroke android:width="1dip" android:color="#4fa5d5"/>
</shape>

How to obtain the last index of a list?

Did you mean len(list1)-1?

If you're searching for other method, you can try list1.index(list1[-1]), but I don't recommend this one. You will have to be sure, that the list contains NO duplicates.

How do I install command line MySQL client on mac?

If you have already installed MySQL from the disk image (dmg) from http://dev.mysql.com/downloads/), open a terminal, run:

echo 'export PATH=/usr/local/mysql/bin:$PATH' >> ~/.bash_profile

then, reload .bash_profile by running following command:

 . ~/.bash_profile

You can now use mysql to connect to any mysql server:

mysql -h xxx.xxx.xxx.xxx -u username -p

Credit & Reference: http://www.gigoblog.com/2011/03/13/add-mysql-to-terminal-shell-in-mac-os-x/

How to remove gem from Ruby on Rails application?

If you're using Rails 3+, remove the gem from the Gemfile and run bundle install.

If you're using Rails 2, hopefully you've put the declaration in config/environment.rb. If so, removing it from there and running rake gems:install should do the trick.

How to get docker-compose to always re-create containers from fresh images?

$docker-compose build

If there is something new it will be rebuilt.

Laravel back button

One of the below solve your problem

URL::previous() 
URL::back()

other

URL::current()

Multipart File Upload Using Spring Rest Template + Spring Web MVC

A correct file upload would like this:

HTTP header:

Content-Type: multipart/form-data; boundary=ABCDEFGHIJKLMNOPQ

Http body:

--ABCDEFGHIJKLMNOPQ

Content-Disposition: form-data; name="file"; filename="my.txt"

Content-Type: application/octet-stream

Content-Length: ...

<...file data in base 64...>

--ABCDEFGHIJKLMNOPQ--

and code is like this:

public void uploadFile(File file) {
        try {
            RestTemplate restTemplate = new RestTemplate();
            String url = "http://localhost:8080/file/user/upload";
            HttpMethod requestMethod = HttpMethod.POST;

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.MULTIPART_FORM_DATA);


            MultiValueMap<String, String> fileMap = new LinkedMultiValueMap<>();
            ContentDisposition contentDisposition = ContentDisposition
                    .builder("form-data")
                    .name("file")
                    .filename(file.getName())
                    .build();

            fileMap.add(HttpHeaders.CONTENT_DISPOSITION, contentDisposition.toString());
            HttpEntity<byte[]> fileEntity = new HttpEntity<>(Files.readAllBytes(file.toPath()), fileMap);

            MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
            body.add("file", fileEntity);

            HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);

            ResponseEntity<String> response = restTemplate.exchange(url, requestMethod, requestEntity, String.class);

            System.out.println("file upload status code: " + response.getStatusCode());

        } catch (IOException e) {
            e.printStackTrace();
        }

}

Regex using javascript to return just numbers

I guess you want to get number(s) from the string. In which case, you can use the following:

// Returns an array of numbers located in the string
function get_numbers(input) {
    return input.match(/[0-9]+/g);
}

var first_test = get_numbers('something102');
var second_test = get_numbers('something102or12');
var third_test = get_numbers('no numbers here!');

alert(first_test); // [102]
alert(second_test); // [102,12]
alert(third_test); // null

How can I see which Git branches are tracking which remote / upstream branch?

Based on Olivier Refalo's answer

if [ $# -eq 2 ] 
then
    echo "Setting tracking for branch " $1 " -> " $2
    git branch --set-upstream $1 $2
else
    echo "-- Local --" 
    git for-each-ref --shell --format="[ %(upstream:short) != '' ] && echo -e '\t%(refname:short) <--> %(upstream:short)'" refs/heads | sh
    echo "-- Remote --" 
    REMOTES=$(git remote -v) 
    if [ "$REMOTES" != '' ]
    then
        echo $REMOTES
    fi  
fi

It shows only local with track configured.

Write it on a script called git-track on your path an you will get a git track command

A more elaborated version on https://github.com/albfan/git-showupstream

Converting string to double in C#

Most people already tried to answer your questions.
If you are still debugging, have you thought about using:

Double.TryParse(String, Double);

This will help you in determining what is wrong in each of the string first before you do the actual parsing.
If you have a culture-related problem, you might consider using:

Double.TryParse(String, NumberStyles, IFormatProvider, Double);

This http://msdn.microsoft.com/en-us/library/system.double.tryparse.aspx has a really good example on how to use them.

If you need a long, Int64.TryParse is also available: http://msdn.microsoft.com/en-us/library/system.int64.tryparse.aspx

Hope that helps.

Android Firebase, simply get one child object's data

I store my data this way:

accountsTable ->
  key1 -> account1
  key2 -> account2

in order to get object data:

accountsDb = mDatabase.child("accountsTable");

accountsDb.child("some   key").addListenerForSingleValueEvent(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot snapshot) {

                    try{

                        Account account  = snapshot.getChildren().iterator().next()
                                  .getValue(Account.class);


                    } catch (Throwable e) {
                        MyLogger.error(this, "onCreate eror", e);
                    }
                }
                @Override public void onCancelled(DatabaseError error) { }
            });

How to crop an image using PIL?

You need to import PIL (Pillow) for this. Suppose you have an image of size 1200, 1600. We will crop image from 400, 400 to 800, 800

from PIL import Image
img = Image.open("ImageName.jpg")
area = (400, 400, 800, 800)
cropped_img = img.crop(area)
cropped_img.show()

Clear android application user data

Hello UdayaLakmal,

public class MyApplication extends Application {
    private static MyApplication instance;

    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
    }

    public static MyApplication getInstance(){
        return instance;
    }

    public void clearApplicationData() {
        File cache = getCacheDir();
        File appDir = new File(cache.getParent());
        if(appDir.exists()){
            String[] children = appDir.list();
            for(String s : children){
                if(!s.equals("lib")){
                    deleteDir(new File(appDir, s));
                    Log.i("TAG", "File /data/data/APP_PACKAGE/" + s +" DELETED");
                }
            }
        }
    }

    public static boolean deleteDir(File dir) {
        if (dir != null && dir.isDirectory()) {
            String[] children = dir.list();
            for (int i = 0; i < children.length; i++) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
        }

        return dir.delete();
    }
}

Please check this and let me know...

You can download code from here

Using jQuery to build table rows from AJAX response(json)

Try it like this:

$.each(response, function(i, item) {
    $('<tr>').html("<td>" + response[i].rank + "</td><td>" + response[i].content + "</td><td>" + response[i].UID + "</td>").appendTo('#records_table');
});

Demo: http://jsfiddle.net/R5bQG/

How to get the body's content of an iframe in Javascript?

it works perfectly for me :

document.getElementById('iframe_id').contentWindow.document.body.innerHTML;

Can I have onScrollListener for a ScrollView?

you can define a custom ScrollView class, & add an interface be called when scrolling like this:

public class ScrollChangeListenerScrollView extends HorizontalScrollView {


private MyScrollListener mMyScrollListener;

public ScrollChangeListenerScrollView(Context context) {
    super(context);
}

public ScrollChangeListenerScrollView(Context context, AttributeSet attrs) {
    super(context, attrs);
}

public ScrollChangeListenerScrollView(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
}


public void setOnMyScrollListener(MyScrollListener myScrollListener){
    this.mMyScrollListener = myScrollListener;
}


@Override
protected void onScrollChanged(int l, int t, int oldl, int oldt) {
    super.onScrollChanged(l, t, oldl, oldt);
    if(mMyScrollListener!=null){
        mMyScrollListener.onScrollChange(this,l,t,oldl,oldt);
    }

}

public interface MyScrollListener {
    void onScrollChange(View view,int scrollX,int scrollY,int oldScrollX, int oldScrollY);
}

}

The best node module for XML parsing

You can try xml2js. It's a simple XML to JavaScript object converter. It gets your XML converted to a JS object so that you can access its content with ease.

Here are some other options:

  1. libxmljs
  2. xml-stream
  3. xmldoc
  4. cheerio – implements a subset of core jQuery for XML (and HTML)

I have used xml2js and it has worked fine for me. The rest you might have to try out for yourself.

File.Move Does Not Work - File Already Exists

Personally I prefer this method. This will overwrite the file on the destination, removes the source file and also prevent removing the source file when the copy fails.

string source = @"c:\test\SomeFile.txt";
string destination = @"c:\test\test\SomeFile.txt";

try
{
    File.Copy(source, destination, true);
    File.Delete(source);
}
catch
{
    //some error handling
}

How can I check for Python version in a program that uses new language features?

For standalone python scripts, the following module docstring trick to enforce a python version (here v2.7.x) works (tested on *nix).

#!/bin/sh
''''python -V 2>&1 | grep -q 2.7 && exec python -u -- "$0" ${1+"$@"}; echo "python 2.7.x missing"; exit 1 # '''

import sys
[...]

This should handle missing python executable as well but has a dependency on grep. See here for background.

Laravel PDOException SQLSTATE[HY000] [1049] Unknown database 'forge'

Here is my response to the problem described in the question.

in cmd write:

php artisan cache:clear

then try to do this code in your terminal

php artisan serve

note: this will start again the server

How do you monitor network traffic on the iPhone?

A man-in-the-middle proxy, like suggested by other answers, is a good solution if you only want to see HTTP/HTTPS traffic.

The best solution for packet sniffing (though it only works for actual iOS devices, not the simulator) I've found is to use rvictl. This blog post has a nice writeup. Basically you do:

rvictl -s <iphone-uid-from-xcode-organizer>

Then you sniff the interface it creates with with Wireshark (or your favorite tool), and when you're done shut down the interface with:

rvictl -x <iphone-uid-from-xcode-organizer>

This is nice because if you want to packet sniff the simulator, you're having to wade through traffic to your local Mac as well, but rvictl creates a virtual interface that just shows you the traffic from the iOS device you've plugged into your USB port.

Note: this only works on a Mac.

Twitter bootstrap hide element on small devices

<div class="small hidden-xs">
    Some Content Here
</div>

This also works for elements not necessarily used in a grid /small column. When it is rendered on larger screens the font-size will be smaller than your default text font-size.

This answer satisfies the question in the OP title (which is how I found this Q/A).

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

Try unbinding the event.

$("span").click(function(){
alert($(this).text());
    $("span").not($(this)).unbind('click');
});

Here is the fiddle

Enable Hibernate logging

Spring Boot, v2.3.0.RELEASE

Recommended (In application.properties):

logging.level.org.hibernate.SQL=DEBUG //logs all SQL DML statements
logging.level.org.hibernate.type=TRACE //logs all JDBC parameters 

parameters

Note:
The above will not give you a pretty-print though.
You can add it as a configuration:

properties.put("hibernate.format_sql", "true");

or as per below.

Works but NOT recommended

spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true

Reason: It's better to let the logging framework manage/optimize the output for you + it doesn't give you the prepared statement parameters.

Cheers

How to add button inside input

The button isn't inside the input. Here:

input[type="text"] {
    width: 200px;
    height: 20px;
    padding-right: 50px;
}

input[type="submit"] {
    margin-left: -50px;
    height: 20px;
    width: 50px;
}

Example: http://jsfiddle.net/s5GVh/

sys.stdin.readline() reads without prompt, returning 'nothing in between'

Simon's answer and Volcano's together explain what you're doing wrong, and Simon explains how you can fix it by redesigning your interface.

But if you really need to read 1 character, and then later read 1 line, you can do that. It's not trivial, and it's different on Windows vs. everything else.

There are actually three cases: a Unix tty, a Windows DOS prompt, or a regular file (redirected file/pipe) on either platform. And you have to handle them differently.

First, to check if stdin is a tty (both Windows and Unix varieties), you just call sys.stdin.isatty(). That part is cross-platform.

For the non-tty case, it's easy. It may actually just work. If it doesn't, you can just read from the unbuffered object underneath sys.stdin. In Python 3, this just means sys.stdin.buffer.raw.read(1) and sys.stdin.buffer.raw.readline(). However, this will get you encoded bytes, rather than strings, so you will need to call .decode(sys.stdin.decoding) on the results; you can wrap that all up in a function.

For the tty case on Windows, however, input will still be line buffered even on the raw buffer. The only way around this is to use the Console I/O functions instead of normal file I/O. So, instead of stdin.read(1), you do msvcrt.getwch().

For the tty case on Unix, you have to set the terminal to raw mode instead of the usual line-discipline mode. Once you do that, you can use the same sys.stdin.buffer.read(1), etc., and it will just work. If you're willing to do that permanently (until the end of your script), it's easy, with the tty.setraw function. If you want to return to line-discipline mode later, you'll need to use the termios module. This looks scary, but if you just stash the results of termios.tcgetattr(sys.stdin.fileno()) before calling setraw, then do termios.tcsetattr(sys.stdin.fileno(), TCSAFLUSH, stash), you don't have to learn what all those fiddly bits mean.

On both platforms, mixing console I/O and raw terminal mode is painful. You definitely can't use the sys.stdin buffer if you've ever done any console/raw reading; you can only use sys.stdin.buffer.raw. You could always replace readline by reading character by character until you get a newline… but if the user tries to edit his entry by using backspace, arrows, emacs-style command keys, etc., you're going to get all those as raw keypresses, which you don't want to deal with.

How to get a barplot with several variables side by side grouped by a factor

You can use aggregate to calculate the means:

means<-aggregate(df,by=list(df$gender),mean)
Group.1      tea     coke     beer    water gender
1       1 87.70171 27.24834 24.27099 37.24007      1
2       2 24.73330 25.27344 25.64657 24.34669      2

Get rid of the Group.1 column

means<-means[,2:length(means)]

Then you have reformat the data to be in long format:

library(reshape2)
means.long<-melt(means,id.vars="gender")
  gender variable    value
1      1      tea 87.70171
2      2      tea 24.73330
3      1     coke 27.24834
4      2     coke 25.27344
5      1     beer 24.27099
6      2     beer 25.64657
7      1    water 37.24007
8      2    water 24.34669

Finally, you can use ggplot2 to create your plot:

library(ggplot2)
ggplot(means.long,aes(x=variable,y=value,fill=factor(gender)))+
  geom_bar(stat="identity",position="dodge")+
  scale_fill_discrete(name="Gender",
                      breaks=c(1, 2),
                      labels=c("Male", "Female"))+
  xlab("Beverage")+ylab("Mean Percentage")

enter image description here

What is difference between monolithic and micro kernel?

Microkernel:

Moves as much from the kernel into “user” space.

Communication takes place between user modules using message passing.

Benefits:

1-Easier to extend a microkernel

2-Easier to port the operating system to new architectures

3-More reliable (less code is running in kernel mode)

4-More secure

Detriments:

1-Performance overhead of user space to kernel space communication

Highest Salary in each department

SELECT empName,empDept,EmpSalary
FROM Employee
WHERE empSalary IN
  (SELECT max(empSalary) AS salary
   From Employee
   GROUP BY EmpDept)

Set Session variable using javascript in PHP

or by pure js, see also on StackOverflow : JavaScript post request like a form submit

BUT WHY try to set $_session with js? any JS variable can be modified by a player with some 3rd party tools (firebug), thus any player can mod the $_session[]! And PHP cant give js any secret codes (or even [rolling] encrypted) to return, it is all visible. Jquery or AJAX can't help, it's all js in the end.

This happens in online game design a lot. (Maybe a bit of Game Theory? forgive me, I have a masters and love to put theory to use :) ) Like in crimegameonline.com, I initialize a minigame puzzle with PHP, saving the initial board in $_SESSION['foo']. Then, I use php to [make html that] shows the initial puzzle start. Then, js takes over, watching buttons and modding element xy's as players make moves. I DONT want to play client-server (like WOW) and ask the server 'hey, my player want's to move to xy, what should I do?'. It's a lot of bandwidth, I don't want the server that involved.

And I can just send POSTs each time the player makes an error (or dies). The player can block outgoing POSTs (and alter local JS vars to make it forget the out count) or simply modify outgoing POST data. YES, people will do this, especially if real money is involved.

If the game is small, you could send post updates EACH move (button click), 1-way, with post vars of the last TWO moves. Then, the server sanity checks last and cats new in a $_SESSION['allMoves']. If the game is massive, you could just send a 'halfway' update of all preceeding moves, and see if it matches in the final update's list.

Then, after a js thinks we have a win, add or mod a button to change pages:

document.getElementById('but1').onclick=Function("leave()");
...
function leave() {
    var line='crimegameonline-p9b.php';
    top.location.href=line;
}

Then the new page's PHP looks at $_SESSION['init'] and plays thru each of the $_SESSION['allMoves'] to see if it is really a winner. The server (PHP) must decide if it is really a winner, not the client (js).

How to convert Json array to list of objects in c#

As others have already pointed out, the reason you are not getting the results you expect is because your JSON does not match the class structure that you are trying to deserialize into. You either need to change your JSON or change your classes. Since others have already shown how to change the JSON, I will take the opposite approach here.

To match the JSON you posted in your question, your classes should be defined like those below. Notice I've made the following changes:

  1. I added a Wrapper class corresponding to the outer object in your JSON.
  2. I changed the Values property of the ValueSet class from a List<Value> to a Dictionary<string, Value> since the values property in your JSON contains an object, not an array.
  3. I added some additional [JsonProperty] attributes to match the property names in your JSON objects.

Class definitions:

class Wrapper
{
    [JsonProperty("JsonValues")]
    public ValueSet ValueSet { get; set; }
}

class ValueSet
{
    [JsonProperty("id")]
    public string Id { get; set; }
    [JsonProperty("values")]
    public Dictionary<string, Value> Values { get; set; }
}

class Value
{
    [JsonProperty("id")]
    public string Id { get; set; }
    [JsonProperty("diaplayName")]
    public string DisplayName { get; set; }
}

You need to deserialize into the Wrapper class, not the ValueSet class. You can then get the ValueSet from the Wrapper.

var valueSet = JsonConvert.DeserializeObject<Wrapper>(jsonString).ValueSet;

Here is a working program to demonstrate:

class Program
{
    static void Main(string[] args)
    {
        string jsonString = @"
        {
            ""JsonValues"": {
                ""id"": ""MyID"",
                ""values"": {
                    ""value1"": {
                        ""id"": ""100"",
                        ""diaplayName"": ""MyValue1""
                    },
                    ""value2"": {
                        ""id"": ""200"",
                        ""diaplayName"": ""MyValue2""
                    }
                }
            }
        }";

        var valueSet = JsonConvert.DeserializeObject<Wrapper>(jsonString).ValueSet;

        Console.WriteLine("id: " + valueSet.Id);
        foreach (KeyValuePair<string, Value> kvp in valueSet.Values)
        {
            Console.WriteLine(kvp.Key + " id: " + kvp.Value.Id);
            Console.WriteLine(kvp.Key + " name: " + kvp.Value.DisplayName);
        }
    }
}

And here is the output:

id: MyID
value1 id: 100
value1 name: MyValue1
value2 id: 200
value2 name: MyValue2

CSS text-overflow: ellipsis; not working?

I faced the same issue and it seems like none of the solution above works for Safari. For non-safari browser, this works just fine:

display: block; /* or in-line block according to your requirement */
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;

For Safari, this is the one that works for me. Note that the media query to check if the browser is Safari might change over time, so just tinker with the media query if it doesn't work for you. With line-clamp property, it would also be possible to have multiple lines in the web with ellipsis, see here.

// Media-query for Safari-only browser.
@media not all and (min-resolution: 0.001dpcm) {
  @media {
    -webkit-line-clamp: 1;
    -webkit-box-orient: vertical;
    display: -webkit-box;
    white-space: normal;
  }
}

iOS 7: UITableView shows under status bar

I was facing this issue in ios 11 but layout was correct for ios 8 - 10.3.3 . For my case I set a Vertical Space Constraint to Superview.Top Margin instead of Superview.Top which works for ios 8 - 11.

enter image description here

How can I create a correlation matrix in R?

The cor function will use the columns of the matrix in the calculation of correlation. So, the number of rows must be the same between your matrix x and matrix y. Ex.:

set.seed(1)
x <- matrix(rnorm(20), nrow=5, ncol=4)
y <- matrix(rnorm(15), nrow=5, ncol=3)
COR <- cor(x,y)
COR
image(x=seq(dim(x)[2]), y=seq(dim(y)[2]), z=COR, xlab="x column", ylab="y column")
text(expand.grid(x=seq(dim(x)[2]), y=seq(dim(y)[2])), labels=round(c(COR),2))

enter image description here

Edit:

Here is an example of custom row and column labels on a correlation matrix calculated with a single matrix:

png("corplot.png", width=5, height=5, units="in", res=200)
op <- par(mar=c(6,6,1,1), ps=10)
COR <- cor(iris[,1:4])
image(x=seq(nrow(COR)), y=seq(ncol(COR)), z=cor(iris[,1:4]), axes=F, xlab="", ylab="")
text(expand.grid(x=seq(dim(COR)[1]), y=seq(dim(COR)[2])), labels=round(c(COR),2))
box()
axis(1, at=seq(nrow(COR)), labels = rownames(COR), las=2)
axis(2, at=seq(ncol(COR)), labels = colnames(COR), las=1)
par(op)
dev.off()

enter image description here

How to copy part of an array to another array in C#?

In case if you want to implement your own Array.Copy method.

Static method which is of generic type.

 static void MyCopy<T>(T[] sourceArray, long sourceIndex, T[] destinationArray, long destinationIndex, long copyNoOfElements)
 {
  long totaltraversal = sourceIndex + copyNoOfElements;
  long sourceArrayLength = sourceArray.Length;

  //to check all array's length and its indices properties before copying
  CheckBoundaries(sourceArray, sourceIndex, destinationArray, copyNoOfElements, sourceArrayLength);
   for (long i = sourceIndex; i < totaltraversal; i++)
     {
      destinationArray[destinationIndex++] = sourceArray[i]; 
     } 
  }

Boundary method implementation.

private static void CheckBoundaries<T>(T[] sourceArray, long sourceIndex, T[] destinationArray, long copyNoOfElements, long sourceArrayLength)
        {
            if (sourceIndex >= sourceArray.Length)
            {
                throw new IndexOutOfRangeException();
            }
            if (copyNoOfElements > sourceArrayLength)
            {
                throw new IndexOutOfRangeException();
            }
            if (destinationArray.Length < copyNoOfElements)
            {
                throw new IndexOutOfRangeException();
            }
        }

Loop and get key/value pair for JSON array using jQuery

You can get the values directly in case of one array like this:

var resultJSON = '{"FirstName":"John","LastName":"Doe","Email":"[email protected]","Phone":"123 dead drive"}';
var result = $.parseJSON(resultJSON);
result['FirstName']; // return 'John'
result['LastName'];  // return ''Doe'
result['Email']; // return '[email protected]'
result['Phone'];  // return '123'

Check if a string is a date value

None of the answers here address checking whether the date is invalid such as February 31. This function addresses that by checking if the returned month is equivalent to the original month and making sure a valid year was presented.

//expected input dd/mm/yyyy or dd.mm.yyyy or dd-mm-yyyy
function isValidDate(s) {
  var separators = ['\\.', '\\-', '\\/'];
  var bits = s.split(new RegExp(separators.join('|'), 'g'));
  var d = new Date(bits[2], bits[1] - 1, bits[0]);
  return d.getFullYear() == bits[2] && d.getMonth() + 1 == bits[1];
} 

How to get current user in asp.net core

Perhaps I didn't see the answer, but this is how I do it.

  1. .Net Core --> Properties --> launchSettings.json

You need to have change these values

"windowsAuthentication": true, // needs to be true
"anonymousAuthentication": false,  // needs to be false 

Startup.cs --> ConfigureServices(...)

services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

MVC or Web Api Controller

private readonly IHttpContextAccessor _httpContextAccessor;
//constructor then
_httpContextAccessor = httpContextAccessor;

Controller method:

string userName = _httpContextAccessor.HttpContext.User.Identity.Name;

Result is userName e.g. = Domain\username

ASP.NET postback with JavaScript

While Phairoh's solution seems theoretically sound, I have also found another solution to this problem. By passing the UpdatePanels id as a paramater (event target) for the doPostBack function the update panel will post back but not the entire page.

__doPostBack('myUpdatePanelId','')

*note: second parameter is for addition event args

hope this helps someone!

EDIT: so it seems this same piece of advice was given above as i was typing :)

How to select some rows with specific rownames from a dataframe?

Assuming that you have a data frame called students, you can select individual rows or columns using the bracket syntax, like this:

  • students[1,2] would select row 1 and column 2, the result here would be a single cell.
  • students[1,] would select all of row 1, students[,2] would select all of column 2.

If you'd like to select multiple rows or columns, use a list of values, like this:

  • students[c(1,3,4),] would select rows 1, 3 and 4,
  • students[c("stu1", "stu2"),] would select rows named stu1 and stu2.

Hope I could help.

jQuery get specific option tag text

I needed this answer as I was dealing with a dynamically cast object, and the other methods here did not seem to work:

element.options[element.selectedIndex].text

This of course uses the DOM object instead of parsing its HTML with nodeValue, childNodes, etc.

Python equivalent to 'hold on' in Matlab

Just call plt.show() at the end:

import numpy as np
import matplotlib.pyplot as plt

plt.axis([0,50,60,80])
for i in np.arange(1,5):
    z = 68 + 4 * np.random.randn(50)
    zm = np.cumsum(z) / range(1,len(z)+1)
    plt.plot(zm)    

n = np.arange(1,51)
su = 68 + 4 / np.sqrt(n)
sl = 68 - 4 / np.sqrt(n)

plt.plot(n,su,n,sl)

plt.show()

Android open camera from button

For me this worked perfectly fine .

 Intent intent=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
 startActivity(intent);

and add this permission to mainfest file:

<uses-permission android:name="android.permission.CAMERA">

It opens the camera,after capturing the image it saves the image to gallery with a new image set.

How to use ng-repeat for dictionaries in AngularJs?

In Angular 7, the following simple example would work (assuming dictionary is in a variable called d):

my.component.ts:

keys: string[] = [];  // declaration of class member 'keys'
// component code ...

this.keys = Object.keys(d);

my.component.html: (will display list of key:value pairs)

<ul *ngFor="let key of keys">
    {{key}}: {{d[key]}}
</ul>

How to create and handle composite primary key in JPA

The MyKey class must implement Serializable if you are using @IdClass

Byte Array to Hex String

If you have a numpy array, you can do the following:

>>> import numpy as np
>>> a = np.array([133, 53, 234, 241])
>>> a.astype(np.uint8).data.hex()
'8535eaf1'

How to convert a list of numbers to jsonarray in Python

import json
row = [1L,[0.1,0.2],[[1234L,1],[134L,2]]]
row_json = json.dumps(row)

C++ performance vs. Java/C#

Some good answers here about the specific question you asked. I'd like to step back and look at the bigger picture.

Keep in mind that your user's perception of the speed of the software you write is affected by many other factors than just how well the codegen optimizes. Here are some examples:

  • Manual memory management is hard to do correctly (no leaks), and even harder to do effeciently (free memory soon after you're done with it). Using a GC is, in general, more likely to produce a program that manages memory well. Are you willing to work very hard, and delay delivering your software, in an attempt to out-do the GC?

  • My C# is easier to read & understand than my C++. I also have more ways to convince myself that my C# code is working correctly. That means I can optimize my algorithms with less risk of introducing bugs (and users don't like software that crashes, even if it does it quickly!)

  • I can create my software faster in C# than in C++. That frees up time to work on performance, and still deliver my software on time.

  • It's easier to write good UI in C# than C++, so I'm more likely to be able to push work to the background while UI stays responsive, or to provide progress or hearbeat UI when the program has to block for a while. This doesn't make anything faster, but it makes users happier about waiting.

Everything I said about C# is probably true for Java, I just don't have the experience to say for sure.

'NOT NULL constraint failed' after adding to models.py

Since you added a new property to the model, you must first delete the database. Then manage.py migrations then manage.py migrate.

In Java, how do I parse XML as a String instead of a file?

One way is to use the version of parse that takes an InputSource rather than a file

A SAX InputSource can be constructed from a Reader object. One Reader object is the StringReader

So something like

parse(new InputSource(new StringReader(myString))) may work. 

Capture event onclose browser

You're looking for the onclose event.

see: https://developer.mozilla.org/en/DOM/window.onclose

note that not all browsers support this (for example firefox 2)

Get the second largest number in a list in linear time

You can find the 2nd largest by any of the following ways:

Option 1:

numbers = set(numbers)
numbers.remove(max(numbers))
max(numbers)

Option 2:

sorted(set(numbers))[-2]

How to validate a form with multiple checkboxes to have atleast one checked

Here is the a quick solution for multiple checkbox validation using jquery validation plugin:

jQuery.validator.addMethod('atLeastOneChecked', function(value, element) {
  return ($('.cbgroup input:checked').length > 0);
});

$('#subscribeForm').validate({
  rules: {
    list0: { atLeastOneChecked: true }
  },
  messages: {
    list0: { 'Please check at least one option' }
  }
});

$('.cbgroup input').click(function() {
  $('#list0').valid();
});

How to style child components from parent component's CSS file?

Had same issue, so if you're using angular2-cli with scss/sass use '/deep/' instead of '>>>', last selector isn't supported yet (but works great with css).

How to make an app's background image repeat

Expanding on plowman's answer, here is the non-deprecated version of changing the background image with java.

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Bitmap bmp = BitmapFactory.decodeResource(getResources(),
            R.drawable.texture);
    BitmapDrawable bitmapDrawable = new BitmapDrawable(getResources(),bmp);
    bitmapDrawable.setTileModeXY(Shader.TileMode.REPEAT,
            Shader.TileMode.REPEAT);
    setBackground(bitmapDrawable);
}

jQuery class within class selector

For this html:

<div class="outer">
     <div class="inner"></div>
</div>

This selector should work:

$('.outer > .inner')

Difference between framework vs Library vs IDE vs API vs SDK vs Toolkits?

Consider Android Development:

IDE: Eclipse etc..

Library: android.app.Activity library (Class with all code)

API: Interface basically all functions with which we call

SDK: The Android SDK provides you the API libraries and developer tools necessary to build, test, and debug apps for Android (----tools - DDMS,Emulator ----platforms - Android OS versions, ----platform-tools - ADB, ----API docs)

ToolKit: Could be ADT Bundle

Framework: Big library but more of architecture-oriented

matplotlib: colorbars and its text labels

To add to tacaswell's answer, the colorbar() function has an optional cax input you can use to pass an axis on which the colorbar should be drawn. If you are using that input, you can directly set a label using that axis.

import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable

fig, ax = plt.subplots()
heatmap = ax.imshow(data)
divider = make_axes_locatable(ax)
cax = divider.append_axes('bottom', size='10%', pad=0.6)
cb = fig.colorbar(heatmap, cax=cax, orientation='horizontal')

cax.set_xlabel('data label')  # cax == cb.ax

Move the mouse pointer to a specific position?

You can't move a mouse but can lock it. Note: that you must call requestPointerLock in click event.

Small Example:

var canvas = document.getElementById('mycanvas');
canvas.requestPointerLock = canvas.requestPointerLock || canvas.mozRequestPointerLock || canvas.webkitRequestPointerLock;
canvas.requestPointerLock();

Documentation and full code example:

https://developer.mozilla.org/en-US/docs/Web/API/Pointer_Lock_API

maven compilation failure

It COULD be due to insufficient heap memory.

It sounds strange, but try it, it might just work:

export MAVEN_OPTS='-Xms384M -Xmx512M -XX:MaxPermSize=256M'

Source: https://groups.google.com/group/neo4j/msg/e208be9ee1c101d7)

github changes not staged for commit

This command may solve the problem :

git add -A

All the files and subdirectories will be added to be tracked.

Hope it helps

segmentation fault : 11

This declaration:

double F[1000][1000000];

would occupy 8 * 1000 * 1000000 bytes on a typical x86 system. This is about 7.45 GB. Chances are your system is running out of memory when trying to execute your code, which results in a segmentation fault.

Removing black dots from li and ul

There you go, this is what I used to fix your problem:

CSS CODE

nav ul { list-style-type: none; }

HTML CODE

<nav>
<ul>
<li><a href="#">Milk</a>
   <ul>
   <li><a href="#">Goat</a></li>
   <li><a href="#">Cow</a></li>
   </ul>
</li>
<li><a href="#">Eggs</a>
   <ul>
   <li><a href="#">Free-range</a></li>
   <li><a href="#">Other</a></li>
   </ul>
</li>
<li><a href="#">Cheese</a>
   <ul>
   <li><a href="#">Smelly</a></li>
   <li><a href="#">Extra smelly</a></li>
   </ul>
</li>
</ul>
</nav>

PHP DOMDocument loadHTML not encoding UTF-8 correctly

The problem is that when you add a parameter to DOMDocument::saveHTML() function, you lose the encoding. In a few cases, you'll need to avoid the use of the parameter and use old string function to find what your are looking for.

I think the previous answer works for you, but since this workaround didn't work for me, I'm adding that answer to help people who may be in my case.

Android java.lang.NoClassDefFoundError

Did you recently updated your eclipse android plugin (adt r17)? Then the following link might help:

How to fix the classdefnotfounderror with adt-17

Update: One year has passed since the question arose. I will keep the link, because even in 2013 it seem to help some people to solve the problem. But please take care what you are doing, see Erics comment below. Current ADT-Version is 22, I recommend using the most current version.

Flask - Calling python function on button OnClick event

It sounds like you want to use this web application as a remote control for your robot, and a core issue is that you won't want a page reload every time you perform an action, in which case, the last link you posted answers your problem.

I think you may be misunderstanding a few things about Flask. For one, you can't nest multiple functions in a single route. You're not making a set of functions available for a particular route, you're defining the one specific thing the server will do when that route is called.

With that in mind, you would be able to solve your problem with a page reload by changing your app.py to look more like this:

from flask import Flask, render_template, Response, request, redirect, url_for
app = Flask(__name__)

@app.route("/")
def index():
    return render_template('index.html')

@app.route("/forward/", methods=['POST'])
def move_forward():
    #Moving forward code
    forward_message = "Moving Forward..."
    return render_template('index.html', forward_message=forward_message);

Then in your html, use this:

<form action="/forward/" method="post">
    <button name="forwardBtn" type="submit">Forward</button>
</form>

...To execute your moving forward code. And include this:

{{ forward_message }} 

... where you want the moving forward message to appear on your template.

This will cause your page to reload, which is inevitable without using AJAX and Javascript.

Work with a time span in Javascript

If you're not too worried in accuracy after days, you can simply do the maths

function timeSince(when) { // this ignores months
    var obj = {};
    obj._milliseconds = (new Date()).valueOf() - when.valueOf();
    obj.milliseconds = obj._milliseconds % 1000;
    obj._seconds = (obj._milliseconds - obj.milliseconds) / 1000;
    obj.seconds = obj._seconds % 60;
    obj._minutes = (obj._seconds - obj.seconds) / 60;
    obj.minutes = obj._minutes % 60;
    obj._hours = (obj._minutes - obj.minutes) / 60;
    obj.hours = obj._hours % 24;
    obj._days = (obj._hours - obj.hours) / 24;
    obj.days = obj._days % 365;
    // finally
    obj.years = (obj._days - obj.days) / 365;
    return obj;
}

then timeSince(pastDate); and use the properties as you like.

Otherwise you can use .getUTC* to calculate it, but note it may be slightly slower to calculate

function timeSince(then) {
    var now = new Date(), obj = {};
    obj.milliseconds = now.getUTCMilliseconds() - then.getUTCMilliseconds();
    obj.seconds = now.getUTCSeconds() - then.getUTCSeconds();
    obj.minutes = now.getUTCMinutes() - then.getUTCMinutes();
    obj.hours = now.getUTCHours() - then.getUTCHours();
    obj.days = now.getUTCDate() - then.getUTCDate();
    obj.months = now.getUTCMonth() - then.getUTCMonth();
    obj.years = now.getUTCFullYear() - then.getUTCFullYear();
    // fix negatives
    if (obj.milliseconds < 0) --obj.seconds, obj.milliseconds = (obj.milliseconds + 1000) % 1000;
    if (obj.seconds < 0) --obj.minutes, obj.seconds = (obj.seconds + 60) % 60;
    if (obj.minutes < 0) --obj.hours, obj.minutes = (obj.minutes + 60) % 60;
    if (obj.hours < 0) --obj.days, obj.hours = (obj.hours + 24) % 24;
    if (obj.days < 0) { // months have different lengths
        --obj.months;
        now.setUTCMonth(now.getUTCMonth() + 1);
        now.setUTCDate(0);
        obj.days = (obj.days + now.getUTCDate()) % now.getUTCDate();
    }
    if (obj.months < 0)  --obj.years, obj.months = (obj.months + 12) % 12;
    return obj;
}

jQuery map vs. each

i understood it by this:

function fun1() {
    return this + 1;
}
function fun2(el) {
    return el + 1;
}

var item = [5,4,3,2,1];

var newitem1 = $.each(item, fun1);
var newitem2 = $.map(item, fun2);

console.log(newitem1); // [5, 4, 3, 2, 1] 
console.log(newitem2); // [6, 5, 4, 3, 2] 

so, "each" function returns the original array while "map" function returns a new array

jQuery ajax call to REST service

I think there is no need to specify

'http://localhost:8080`" 

in the URI part.. because. if you specify it, You'll have to change it manually for every environment.

Only

"/restws/json/product/get" also works

Convert json to a C# array?

just take the string and use the JavaScriptSerializer to deserialize it into a native object. For example, having this json:

string json = "[{Name:'John Simith',Age:35},{Name:'Pablo Perez',Age:34}]"; 

You'd need to create a C# class called, for example, Person defined as so:

public class Person
{
 public int Age {get;set;}
 public string Name {get;set;}
}

You can now deserialize the JSON string into an array of Person by doing:

JavaScriptSerializer js = new JavaScriptSerializer();
Person [] persons =  js.Deserialize<Person[]>(json);

Here's a link to JavaScriptSerializer documentation.

Note: my code above was not tested but that's the idea Tested it. Unless you are doing something "exotic", you should be fine using the JavascriptSerializer.

Spring Boot application in eclipse, the Tomcat connector configured to listen on port XXXX failed to start

Find the process and terminate it. On Windows do a Control+Alt+Delete and then find the "Java(TM) Platform SE Binary" process under the Processes Tab. For example: enter image description here

On Ubuntu, you can use "ps aux | grep java" to find the process and "kill -9 PID_NUMBER" to kill the process.

OR

If you're using a Spring boot application, go to application.properties and add this:

server.port = 8081

Is there a way to delete all the data from a topic or delete the topic before every run?

Below are scripts for emptying and deleting a Kafka topic assuming localhost as the zookeeper server and Kafka_Home is set to the install directory:

The script below will empty a topic by setting its retention time to 1 second and then removing the configuration:

#!/bin/bash
echo "Enter name of topic to empty:"
read topicName
/$Kafka_Home/bin/kafka-configs --zookeeper localhost:2181 --alter --entity-type topics --entity-name $topicName --add-config retention.ms=1000
sleep 5
/$Kafka_Home/bin/kafka-configs --zookeeper localhost:2181 --alter --entity-type topics --entity-name $topicName --delete-config retention.ms

To fully delete topics you must stop any applicable kafka broker(s) and remove it's directory(s) from the kafka log dir (default: /tmp/kafka-logs) and then run this script to remove the topic from zookeeper. To verify it's been deleted from zookeeper the output of ls /brokers/topics should no longer include the topic:

#!/bin/bash
echo "Enter name of topic to delete from zookeeper:"
read topicName
/$Kafka_Home/bin/zookeeper-shell localhost:2181 <<EOF
rmr /brokers/topics/$topicName
ls /brokers/topics
quit
EOF

Can't use Swift classes inside Objective-C

I had issues in that I would add classes to my objective-c bridging header, and in those objective-c headers that were imported, they were trying to import the swift header. It didn't like that.

So in all my objective-c classes that use swift, but are also bridged, the key was to make sure that you use forward class declarations in the headers, then import the "*-Swift.h" file in the .m file.

Add swipe to delete UITableViewCell

use it :

func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
    if editingStyle == UITableViewCellEditingStyle.Delete {
        langData.removeAtIndex(indexPath.row) //langData is array from i delete values
        tableView.deleteRowsAtIndexPaths([indexPath],  withRowAnimation: UITableViewRowAnimation.Automatic)
    }
}

hope it helps you

Dynamic function name in javascript?

The syntax function[i](){} implies an object with property values that are functions, function[], indexed by the name, [i].
Thus
{"f:1":function(){}, "f:2":function(){}, "f:A":function(){}, ... } ["f:"+i].

{"f:1":function f1(){}, "f:2":function f2(){}, "f:A":function fA(){}} ["f:"+i] will preserve function name identification. See notes below regarding :.

So,

javascript: alert(
  new function(a){
    this.f={"instance:1":function(){}, "instance:A":function(){}} ["instance:"+a]
  }("A") . toSource()
);

displays ({f:(function () {})}) in FireFox.
(This is almost the same idea as this solution, only it uses a generic object and no longer directly populates the window object with the functions.)

This method explicitly populates the environment with instance:x.

javascript: alert(
  new function(a){
    this.f=eval("instance:"+a+"="+function(){})
  }("A") . toSource()
);
alert(eval("instance:A"));

displays

({f:(function () {})})

and

function () {
}

Though the property function f references an anonymous function and not instance:x, this method avoids several problems with this solution.

javascript: alert(
  new function(a){
    eval("this.f=function instance"+a+"(){}")
  }("A") . toSource()
);
alert(instanceA);    /* is undefined outside the object context */

displays only

({f:(function instanceA() {})})
  • The embedded : makes the javascript function instance:a(){} invalid.
  • Instead of a reference, the function's actual text definition is parsed and interpreted by eval.

The following is not necessarily problematic,

  • The instanceA function is not directly available for use as instanceA()

and so is much more consistent with the original problem context.

Given these considerations,

this.f = {"instance:1": function instance1(){},
          "instance:2": function instance2(){},
          "instance:A": function instanceA(){},
          "instance:Z": function instanceZ(){}
         } [ "instance:" + a ]

maintains the global computing environment with the semantics and syntax of the OP example as much as possible.

Java: How to convert a File object to a String object in java?

Readin file with file inputstream and append file content to string.

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class CopyOffileInputStream {

    public static void main(String[] args) {

        //File file = new File("./store/robots.txt");
        File file = new File("swingloggingsscce.log");

        FileInputStream fis = null;
        String str = "";

        try {
            fis = new FileInputStream(file);
            int content;
            while ((content = fis.read()) != -1) {
                // convert to char and display it
                str += (char) content;
            }

            System.out.println("After reading file");
            System.out.println(str);

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fis != null)
                    fis.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
}

XSL substring and indexOf

I want to select the text of a string that is located after the occurrence of substring

You could use:

substring-after($string,$match)

If you want a subtring of the above with some length then use:

substring(substring-after($string,$match),1,$length)

But problems begin if there is no ocurrence of the matching substring... So, if you want a substring with specific length located after the occurrence of a substring, or from the whole string if there is no match, you could use:

substring(substring-after($string,substring-before($string,$match)),
          string-length($match) * contains($string,$match) + 1,
          $length) 

Returning http status code from Web Api controller

I know there are several good answers here but this is what I needed so I figured I'd add this code in case anyone else needs to return whatever status code and response body they wanted in 4.7.x with webAPI.

public class DuplicateResponseResult<TResponse> : IHttpActionResult
{
    private TResponse _response;
    private HttpStatusCode _statusCode;
    private HttpRequestMessage _httpRequestMessage;
    public DuplicateResponseResult(HttpRequestMessage httpRequestMessage, TResponse response, HttpStatusCode statusCode)
    {
        _httpRequestMessage = httpRequestMessage;
        _response = response;
        _statusCode = statusCode;
    }

    public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
    {
        var response = new HttpResponseMessage(_statusCode);
        return Task.FromResult(_httpRequestMessage.CreateResponse(_statusCode, _response));
    }
}

How To have Dynamic SQL in MySQL Stored Procedure

I don't believe MySQL supports dynamic sql. You can do "prepared" statements which is similar, but different.

Here is an example:

mysql> PREPARE stmt FROM 
    -> 'select count(*) 
    -> from information_schema.schemata 
    -> where schema_name = ? or schema_name = ?'
;
Query OK, 0 rows affected (0.00 sec)
Statement prepared
mysql> EXECUTE stmt 
    -> USING @schema1,@schema2
+----------+
| count(*) |
+----------+
|        2 |
+----------+
1 row in set (0.00 sec)
mysql> DEALLOCATE PREPARE stmt;

The prepared statements are often used to see an execution plan for a given query. Since they are executed with the execute command and the sql can be assigned to a variable you can approximate the some of the same behavior as dynamic sql.

Here is a good link about this:

Don't forget to deallocate the stmt using the last line!

Good Luck!

jQuery: Test if checkbox is NOT checked

Here I have a snippet for this question.

_x000D_
_x000D_
$(function(){_x000D_
   $("#buttoncheck").click(function(){_x000D_
        if($('[type="checkbox"]').is(":checked")){_x000D_
            $('.checkboxStatus').html("Congratulations! "+$('[type="checkbox"]:checked').length+" checkbox checked");_x000D_
        }else{_x000D_
            $('.checkboxStatus').html("Sorry! Checkbox is not checked");_x000D_
         }_x000D_
         return false;_x000D_
   })_x000D_
    _x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<form>_x000D_
  <p>_x000D_
    <label>_x000D_
      <input type="checkbox" name="CheckboxGroup1" value="checkbox" id="CheckboxGroup1_0">_x000D_
      Checkbox</label>_x000D_
    <br>_x000D_
    <label>_x000D_
      <input type="checkbox" name="CheckboxGroup1_" value="checkbox" id="CheckboxGroup1_1">_x000D_
      Checkbox</label>_x000D_
    <br>_x000D_
  </p>_x000D_
  <p>_x000D_
    <input type="reset" value="Reset">_x000D_
    <input type="submit" id="buttoncheck" value="Check">_x000D_
  </p>_x000D_
  <p class="checkboxStatus"></p>_x000D_
</form>
_x000D_
_x000D_
_x000D_

SQL Current month/ year question

How about:

Select *
from some_table st
where st.month = to_char(sysdate,'MM') and
    st.year = to_char(sysdate,'YYYY');

should work in Oracle. What database are you using? I ask because not all databases have the same date functions.

get selected value in datePicker and format it

Use jquery-dateFormat. It will solve your problem.

You need to include the jquery.dateFormat in your html file.

<script>
var date = $('#scheduleDate').val();
document.write($.format.date(date, "dd,MM,yyyy"));

var dateTypeVar = $('#scheduleDate').datepicker('getDate');
document.write($.format.date(dateTypeVar, "dd-MM-yy"));
</script>

How do I list all the columns in a table?

SQL Server

To list all the user defined tables of a database:

use [databasename]
select name from sysobjects where type = 'u'

To list all the columns of a table:

use [databasename]
select name from syscolumns where id=object_id('tablename')

Where will log4net create this log file?

If you want your log file to be place at a specified location which will be decided at run time may be your project output directory then you can configure your .config file entry in that way

<file type="log4net.Util.PatternString" value="%property{LogFileName}.txt" />

and then in the code before calling log4net configure, set the new path like below

 log4net.GlobalContext.Properties["LogFileName"] = @"E:\\file1"; //log file path
 log4net.Config.XmlConfigurator.Configure();

How simple is it? :)

What's the idiomatic syntax for prepending to a short python list?

If you can go the functional way, the following is pretty clear

new_list = [x] + your_list

Of course you haven't inserted x into your_list, rather you have created a new list with x preprended to it.

how to access master page control from content page

This is more complicated if you have a nested MasterPage. You need to first find the content control that contains the nested MasterPage, and then find the control on your nested MasterPage from that.

Crucial bit: Master.Master.

See here: http://forums.asp.net/t/1059255.aspx?Nested+master+pages+and+Master+FindControl

Example:

'Find the content control

Dim ct As ContentPlaceHolder = Me.Master.Master.FindControl("cphMain")

'now find controls inside that content

Dim lbtnSave As LinkButton = ct.FindControl("lbtnSave")

Git merge with force overwrite

You can try "ours" option in git merge,

git merge branch -X ours

This option forces conflicting hunks to be auto-resolved cleanly by favoring our version. Changes from the other tree that do not conflict with our side are reflected to the merge result. For a binary file, the entire contents are taken from our side.

How to center absolute div horizontally using CSS?

Centering div with position: absolute and width: unknown:

HTML:

<div class="center">
  <span></span>

  <div>
    content...
  </div>

</div>

CSS:

.center{
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: grid;
  grid-template-columns: auto auto;
  overflow: auto;
}

PermissionError: [Errno 13] in python

When doing;

a_file = open('E:\Python Win7-64-AMD 3.3\Test', encoding='utf-8')

...you're trying to open a directory as a file, which may (and on most non UNIX file systems will) fail.

Your other example though;

a_file = open('E:\Python Win7-64-AMD 3.3\Test\a.txt', encoding='utf-8')

should work well if you just have the permission on a.txt. You may want to use a raw (r-prefixed) string though, to make sure your path does not contain any escape characters like \n that will be translated to special characters.

a_file = open(r'E:\Python Win7-64-AMD 3.3\Test\a.txt', encoding='utf-8')

How to make EditText not editable through XML in Android?

This way did the job for me, i can selec and copy to clipboard, but i can't modify or paste.

android:enable="true"
android:textIsSelectable="true"
android:inputType="none"

<div> cannot appear as a descendant of <p>

Based on the warning message, the component ReactTooltip renders an HTML that might look like this:

<p>
   <div>...</div>
</p>

According to this document, a <p></p> tag can only contain inline elements. That means putting a <div></div> tag inside it should be improper, since the div tag is a block element. Improper nesting might cause glitches like rendering extra tags, which can affect your javascript and css.

If you want to get rid of this warning, you might want to customize the ReactTooltip component, or wait for the creator to fix this warning.

COPYing a file in a Dockerfile, no such file or directory?

For following error,

COPY failed: stat /<**path**> :no such file or directory

I got it around by restarting docker service.

sudo service docker restart

Text in Border CSS HTML

You can use a fieldset tag.

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<body>_x000D_
_x000D_
<form>_x000D_
 <fieldset>_x000D_
  <legend>Personalia:</legend>_x000D_
  Name: <input type="text"><br>_x000D_
  Email: <input type="text"><br>_x000D_
  Date of birth: <input type="text">_x000D_
 </fieldset>_x000D_
</form>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Check this link: HTML Tag

Why is a "GRANT USAGE" created the first time I grant a user privileges?

In addition mysql passwords when not using the IDENTIFIED BY clause, may be blank values, if non-blank, they may be encrypted. But yes USAGE is used to modify an account by granting simple resource limiters such as MAX_QUERIES_PER_HOUR, again this can be specified by also using the WITH clause, in conjuction with GRANT USAGE(no privileges added) or GRANT ALL, you can also specify GRANT USAGE at the global level, database level, table level,etc....

Should methods in a Java interface be declared with or without a public access modifier?

I prefer skipping it, I read somewhere that interfaces are by default, public and abstract.

To my surprise the book - Head First Design Patterns, is using public with interface declaration and interface methods... that made me rethink once again and I landed up on this post.

Anyways, I think redundant information should be ignored.