Programs & Examples On #Lme4

lme4 is an R package for fitting and analyzing linear, nonlinear and generalized linear mixed models.

Tools for making latex tables in R

I have a few tricks and work arounds to interesting 'features' of xtable and Latex that I'll share here.

Trick #1: Removing Duplicates in Columns and Trick #2: Using Booktabs

First, load packages and define my clean function

<<label=first, include=FALSE, echo=FALSE>>= 
    library(xtable)
    library(plyr)

    cleanf <- function(x){     
        oldx <- c(FALSE, x[-1]==x[-length(x)])  
        # is the value equal to the previous?    
        res <- x
        res[oldx] <- NA
        return(res)} 

Now generate some fake data

data<-data.frame(animal=sample(c("elephant", "dog", "cat", "fish", "snake"), 100,replace=TRUE),
            colour=sample(c("red", "blue", "green", "yellow"), 100,replace=TRUE),
            size=rnorm(100,mean=500, sd=150),
            age=rlnorm(100, meanlog=3, sdlog=0.5))

    #generate a table
    datatable<-ddply(data, .(animal, colour), function(df) {
                return(data.frame(size=mean(df$size), age=mean(df$age)))
            })

Now we can generate a table, and use the clean function to remove duplicate entries in the label columns.

cleandata<-datatable
cleandata$animal<-cleanf(cleandata$animal)
cleandata$colour<-cleanf(cleandata$colour)
@ 

this is a normal xtable

<<label=normal, results=tex, echo=FALSE>>=
print(
    xtable(
        datatable
        ),
        tabular.environment='longtable',
        latex.environments=c("center"), 
        floating=FALSE, 
        include.rownames=FALSE
    )
@ 

this is a normal xtable where a custom function has turned duplicates to NA

<<label=cleandata, results=tex, echo=FALSE>>=
print(
    xtable(
        cleandata
        ),
        tabular.environment='longtable',
        latex.environments=c("center"), 
        floating=FALSE, 
        include.rownames=FALSE
    )
@ 

This table uses the booktab package (and needs a \usepackage{booktabs} in the headers)

\begin{table}[!h] 
        \centering
        \caption{table using booktabs.}
        \label{tab:mytable}
<<label=booktabs, echo=F,results=tex>>= 
            mat <- xtable(cleandata,digits=rep(2,ncol(cleandata)+1))
            foo<-0:(length(mat$animal))
            bar<-foo[!is.na(mat$animal)]
            print(mat, 
                  sanitize.text.function = function(x){x},
                  floating=FALSE,
                  include.rownames=FALSE,
                  hline.after=NULL, 
                  add.to.row=list(pos=list(-1,bar,nrow(mat)), 
                  command=c("\\toprule ", "\\midrule ", "\\bottomrule ")))
  #could extend this with \cmidrule to have a partial line over
  #a sub category column and \addlinespace to add space before a total row
@ 

Git on Bitbucket: Always asked for password, even after uploading my public SSH key

I was having other weirdness around logging in. I came across something that seemed totally dumb but worked in my case. Simply go to MacOS's keychain. Find the login lock icon in the sidebar. Click it to logout and then click to login. Sounds dumb but it solved my issues. Worth a shot.

Javascript querySelector vs. getElementById

The functions getElementById and getElementsByClassName are very specific, while querySelector and querySelectorAll are more elaborate. My guess is that they will actually have a worse performance.

Also, you need to check for the support of each function in the browsers you are targetting. The newer it is, the higher probability of lack of support or the function being "buggy".

Event detect when css property changed using Jquery

You can use jQuery's css function to test the CSS properties, eg. if ($('node').css('display') == 'block').

Colin is right, that there is no explicit event that gets fired when a specific CSS property gets changed. But you may be able to flip it around, and trigger an event that sets the display, and whatever else.

Also consider using adding CSS classes to get the behavior you want. Often you can add a class to a containing element, and use CSS to affect all elements. I often slap a class onto the body element to indicate that an AJAX response is pending. Then I can use CSS selectors to get the display I want.

Not sure if this is what you're looking for.

How do I add FTP support to Eclipse?

Eclipse natively supports FTP and SSH. Aptana is not necessary.

Native FTP and SSH support in Eclipse is in the "Remote System Explorer End-User Runtime" Plugin.

Install it through Eclipse itself. These instructions may vary slightly with your version of Eclipse:

  1. Go to 'Help' -> 'Install New Software' (in older Eclipses, this is called something a bit different)
  2. In the 'Work with:' drop-down, select your version's plugin release site. Example: for Kepler, this is
    Kepler - http://download.eclipse.org/releases/kepler
  3. In the filter field, type 'remote'.
  4. Check the box next to 'Remote System Explorer End-User Runtime'
  5. Click 'Next', and accept the terms. It should now download and install.
  6. After install, Eclipse may want to restart.

Using it, in Eclipse:

  1. Window -> Open Perspective -> (perhaps select 'Other') -> Remote System Explorer
  2. File -> New -> Other -> Remote System Explorer (folder) -> Connection (or type Connection into the filter field)
  3. Choose FTP from the 'Select Remote System Type' panel.
  4. Fill in your FTP host info in the next panel (username and password come later).
  5. In the Remote Systems panel, right-click the hostname and click 'connect'.
  6. Enter username + password and you're good!
  7. Well, not exactly 'good'. The RSE system is fairly unusual, but you're connected.
  8. And you're one smart cookie! You'll figure out the rest.

Edit: To change the default port, follow the instructions on this page: http://ikool.wordpress.com/2008/07/25/tips-to-access-ftpssh-on-different-ports-using-eclipse-rse/

How to suppress binary file matching results in grep

There are three options, that you can use. -I is to exclude binary files in grep. Other are for line numbers and file names.

grep -I -n -H 


-I -- process a binary file as if it did not contain matching data; 
-n -- prefix each line of output with the 1-based line number within its input file
-H -- print the file name for each match

So this might be a way to run grep:

grep -InH your-word *

How can I add a volume to an existing Docker container?

The best way is to copy all the files and folders inside a directory on your local file system by: docker cp [OPTIONS] CONTAINER:SRC_PATH DEST_PATH

SRC_PATH is on container DEST_PATH is on localhost

Then do docker-compose down attach a volume to the same DEST_PATH and run Docker containers by using docker-compose up -d

Add volume by following in docker-compose.yml

volumes:
 - DEST_PATH:SRC_PATH

HTTP error 403 in Python 3 Web Scraping

If you feel guilty about faking the user-agent as Mozilla (comment in the top answer from Stefano), it could work with a non-urllib User-Agent as well. This worked for the sites I reference:

    req = urlrequest.Request(link, headers={'User-Agent': 'XYZ/3.0'})
    urlrequest.urlopen(req, timeout=10).read()

My application is to test validity by scraping specific links that I refer to, in my articles. Not a generic scraper.

What is reflection and why is it useful?

As name itself suggest it reflects what it holds for example class method,etc apart from providing feature to invoke method creating instance dynamically at runtime.

It is used by many frameworks and application under the wood to invoke services without actually knowing the code.

How to hide keyboard in swift on pressing return key?

The return true part of this only tells the text field whether or not it is allowed to return.
You have to manually tell the text field to dismiss the keyboard (or what ever its first responder is), and this is done with resignFirstResponder(), like so:

// Called on 'Return' pressed. Return false to ignore.

func textFieldShouldReturn(_ textField: UITextField) -> Bool { 
    textField.resignFirstResponder()
    return true
}

Sending files using POST with HttpURLConnection

I found using okHttp a lot easier as I could not get any of these solutions to work: https://stackoverflow.com/a/37942387/447549

python requests file upload

Client Upload

If you want to upload a single file with Python requests library, then requests lib supports streaming uploads, which allow you to send large files or streams without reading into memory.

with open('massive-body', 'rb') as f:
    requests.post('http://some.url/streamed', data=f)

Server Side

Then store the file on the server.py side such that save the stream into file without loading into the memory. Following is an example with using Flask file uploads.

@app.route("/upload", methods=['POST'])
def upload_file():
    from werkzeug.datastructures import FileStorage
    FileStorage(request.stream).save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
    return 'OK', 200

Or use werkzeug Form Data Parsing as mentioned in a fix for the issue of "large file uploads eating up memory" in order to avoid using memory inefficiently on large files upload (s.t. 22 GiB file in ~60 seconds. Memory usage is constant at about 13 MiB.).

@app.route("/upload", methods=['POST'])
def upload_file():
    def custom_stream_factory(total_content_length, filename, content_type, content_length=None):
        import tempfile
        tmpfile = tempfile.NamedTemporaryFile('wb+', prefix='flaskapp', suffix='.nc')
        app.logger.info("start receiving file ... filename => " + str(tmpfile.name))
        return tmpfile

    import werkzeug, flask
    stream, form, files = werkzeug.formparser.parse_form_data(flask.request.environ, stream_factory=custom_stream_factory)
    for fil in files.values():
        app.logger.info(" ".join(["saved form name", fil.name, "submitted as", fil.filename, "to temporary file", fil.stream.name]))
        # Do whatever with stored file at `fil.stream.name`
    return 'OK', 200

How to read until end of file (EOF) using BufferedReader in Java?

You are consuming a line at, which is discarded

while((str=input.readLine())!=null && str.length()!=0)

and reading a bigint at

BigInteger n = new BigInteger(input.readLine());

so try getting the bigint from string which is read as

BigInteger n = new BigInteger(str);

   Constructor used: BigInteger(String val)

Aslo change while((str=input.readLine())!=null && str.length()!=0) to

while((str=input.readLine())!=null)

see related post string to bigint

readLine()
Returns:
    A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached 

see javadocs

Rotate label text in seaborn factorplot

You can also use plt.setp as follows:

import matplotlib.pyplot as plt
import seaborn as sns

plot=sns.barplot(data=df,  x=" ", y=" ")
plt.setp(plot.get_xticklabels(), rotation=90)

to rotate the labels 90 degrees.

Converting between strings and ArrayBuffers

I'd recommend NOT using deprecated APIs like BlobBuilder

BlobBuilder has long been deprecated by the Blob object. Compare the code in Dennis' answer — where BlobBuilder is used — with the code below:

function arrayBufferGen(str, cb) {

  var b = new Blob([str]);
  var f = new FileReader();

  f.onload = function(e) {
    cb(e.target.result);
  }

  f.readAsArrayBuffer(b);

}

Note how much cleaner and less bloated this is compared to the deprecated method... Yeah, this is definitely something to consider here.

How to find the path of Flutter SDK

If you installed flutter via the snap on linux then the sdk is likely to be in

~/snap/flutter/common/flutter

Error: 'int' object is not subscriptable - Python

When you type x = 0 that is creating a new int variable (name) and assigning a zero to it.

When you type x[age1] that is trying to access the age1'th entry, as if x were an array.

When should we implement Serializable interface?

The answer to this question is, perhaps surprisingly, never, or more realistically, only when you are forced to for interoperability with legacy code. This is the recommendation in Effective Java, 3rd Edition by Joshua Bloch:

There is no reason to use Java serialization in any new system you write

Oracle's chief architect, Mark Reinhold, is on record as saying removing the current Java serialization mechanism is a long-term goal.


Why Java serialization is flawed

Java provides as part of the language a serialization scheme you can opt in to, by using the Serializable interface. This scheme however has several intractable flaws and should be treated as a failed experiment by the Java language designers.

  • It fundamentally pretends that one can talk about the serialized form of an object. But there are infinitely many serialization schemes, resulting in infinitely many serialized forms. By imposing one scheme, without any way of changing the scheme, applications can not use a scheme most appropriate for them.
  • It is implemented as an additional means of constructing objects, which bypasses any precondition checks your constructors or factory methods perform. Unless tricky, error prone, and difficult to test extra deserialization code is written, your code probably has a gaping security weakness.
  • Testing interoperability of different versions of the serialized form is very difficult.
  • Handling of immutable objects is troublesome.

What to do instead

Instead, use a serialization scheme that you can explicitly control. Such as Protocol Buffers, JSON, XML, or your own custom scheme.

Shrinking navigation bar when scrolling down (bootstrap3)

For those not willing to use jQuery here is a Vanilla Javascript way of doing the same using classList:

function runOnScroll() {
    var element = document.getElementsByTagName('nav')  ;
    if(document.body.scrollTop >= 50) {
        element[0].classList.add('shrink')
    } else {
        element[0].classList.remove('shrink')
    }
    console.log(topMenu[0].classList)

};

There might be a nicer way of doing it using toggle, but the above works fine in Chrome

twitter-bootstrap: how to get rid of underlined button text when hovering over a btn-group within an <a>-tag?

{ text-decoration: none !important}


EDIT 1:

For you example only a{text-decoration: none} will works

You can use a class not to interfere with the default behaviour of <a> tags.

<a href="#" class="nounderline">
  <div class="btn-group">
    <button class="btn">Text</button>
    <button class="btn">Text</button>
  </div>
</a>

CSS:

.nounderline {
  text-decoration: none !important
}

Android get Current UTC time

System.currentTimeMillis() does give you the number of milliseconds since January 1, 1970 00:00:00 UTC. The reason you see local times might be because you convert a Date instance to a string before using it. You can use DateFormats to convert Dates to Strings in any timezone:

DateFormat df = DateFormat.getTimeInstance();
df.setTimeZone(TimeZone.getTimeZone("gmt"));
String gmtTime = df.format(new Date());

Also see this related question.

Calculate correlation for more than two variables?

You can also calculate correlations for all variables but exclude selected ones, for example:

mtcars <- data.frame(mtcars)
# here we exclude gear and carb variables
cors <- cor(subset(mtcars, select = c(-gear,-carb)))

Also, to calculate correlation between each variable and one column you can use sapply()

# sapply effectively calls the corelation function for each column of mtcars and mtcars$mpg
cors2 <- sapply(mtcars, cor, y=mtcars$mpg)

How to remove an appended element with Jquery and why bind or live is causing elements to repeat

The live function is registering a click event handler. It'll do so every time you click the object. So if you click it twice, you're assigning two click handlers to the object. You're also assigning a click handler here:

onclick="feedback('the message html')";

And then that click handler is assigning another click handler via live().

Really what I think you want to do is this:

function feedback(message)
{
    $('#feedback').remove();

    $('.answers').append('<div id="feedback">'+message+'</div>');
}

Ok, per your comment, try taking out the onclick part of the <a> element and instead, putting this in a document.ready() handler.

$('#answer').live('click',function(){
                     $('#feedback').remove();
                     $('.answers').append('<div id="feedback">'+message+'</div>');
                 });

bootstrap 3 tabs not working properly

When I removed the smooth scroll script (https://github.com/cferdinandi/smooth-scroll), it worked.

Text to speech(TTS)-Android

Try this, its simple : **speakout.xml : **

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#3498db"
android:weightSum="1"
android:orientation="vertical" >
<TextView
android:id="@+id/txtheader"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_gravity="center"
android:layout_weight=".1"
android:gravity="center"
android:padding="3dp"
android:text="Speak Out!!!"
android:textColor="#fff"
android:textSize="25sp"
android:textStyle="bold" />
<EditText
android:id="@+id/edtTexttoSpeak"
android:layout_width="match_parent"
android:layout_weight=".5"
android:background="#fff"
android:textColor="#2c3e50"
android:text="Hi there!!!"
android:padding="5dp"
android:gravity="top|left"
android:layout_height="0dp"/>
<Button
android:id="@+id/btnspeakout"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight=".1"
android:background="#e74c3c"
android:textColor="#fff"
android:text="SPEAK OUT"/>
</LinearLayout>

And Your SpeakOut.java :

import android.app.Activity;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class SpeakOut extends Activity implements OnInitListener {
private TextToSpeech repeatTTS;
Button btnspeakout;
EditText edtTexttoSpeak;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.speakout);
    btnspeakout = (Button) findViewById(R.id.btnspeakout);
    edtTexttoSpeak = (EditText) findViewById(R.id.edtTexttoSpeak);
    repeatTTS = new TextToSpeech(this, this);
    btnspeakout.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            repeatTTS.speak(edtTexttoSpeak.getText().toString(),
            TextToSpeech.QUEUE_FLUSH, null);
        }
    });
}

@Override
    public void onInit(int arg0) {
        // TODO Auto-generated method stub
    }
}

SOURCE Parallelcodes.com's Post

How to download image from url

For anyone who wants to download an image WITHOUT saving it to a file:

Image DownloadImage(string fromUrl)
{
    using (System.Net.WebClient webClient = new System.Net.WebClient())
    {
        using (Stream stream = webClient.OpenRead(fromUrl))
        {
            return Image.FromStream(stream);
        }
    }
}

Java regex capturing groups indexes

Capturing and grouping

Capturing group (pattern) creates a group that has capturing property.

A related one that you might often see (and use) is (?:pattern), which creates a group without capturing property, hence named non-capturing group.

A group is usually used when you need to repeat a sequence of patterns, e.g. (\.\w+)+, or to specify where alternation should take effect, e.g. ^(0*1|1*0)$ (^, then 0*1 or 1*0, then $) versus ^0*1|1*0$ (^0*1 or 1*0$).

A capturing group, apart from grouping, will also record the text matched by the pattern inside the capturing group (pattern). Using your example, (.*):, .* matches ABC and : matches :, and since .* is inside capturing group (.*), the text ABC is recorded for the capturing group 1.

Group number

The whole pattern is defined to be group number 0.

Any capturing group in the pattern start indexing from 1. The indices are defined by the order of the opening parentheses of the capturing groups. As an example, here are all 5 capturing groups in the below pattern:

(group)(?:non-capturing-group)(g(?:ro|u)p( (nested)inside)(another)group)(?=assertion)
|     |                       |          | |      |      ||       |     |
1-----1                       |          | 4------4      |5-------5     |
                              |          3---------------3              |
                              2-----------------------------------------2

The group numbers are used in back-reference \n in pattern and $n in replacement string.

In other regex flavors (PCRE, Perl), they can also be used in sub-routine calls.

You can access the text matched by certain group with Matcher.group(int group). The group numbers can be identified with the rule stated above.

In some regex flavors (PCRE, Perl), there is a branch reset feature which allows you to use the same number for capturing groups in different branches of alternation.

Group name

From Java 7, you can define a named capturing group (?<name>pattern), and you can access the content matched with Matcher.group(String name). The regex is longer, but the code is more meaningful, since it indicates what you are trying to match or extract with the regex.

The group names are used in back-reference \k<name> in pattern and ${name} in replacement string.

Named capturing groups are still numbered with the same numbering scheme, so they can also be accessed via Matcher.group(int group).

Internally, Java's implementation just maps from the name to the group number. Therefore, you cannot use the same name for 2 different capturing groups.

jQuery jump or scroll to certain position, div or target on the page from button onclick

$("html, body").scrollTop($(element).offset().top); // <-- Also integer can be used

POI setting Cell Background to a Custom Color

You get this error because pallete is full. What you need to do is override preset color. Here is an example of function I'm using:

public HSSFColor setColor(HSSFWorkbook workbook, byte r,byte g, byte b){
    HSSFPalette palette = workbook.getCustomPalette();
    HSSFColor hssfColor = null;
    try {
        hssfColor= palette.findColor(r, g, b); 
        if (hssfColor == null ){
            palette.setColorAtIndex(HSSFColor.LAVENDER.index, r, g,b);
            hssfColor = palette.getColor(HSSFColor.LAVENDER.index);
        }
    } catch (Exception e) {
        logger.error(e);
    }

    return hssfColor;
}

And later use it for background color:

HSSFColor lightGray =  setColor(workbook,(byte) 0xE0, (byte)0xE0,(byte) 0xE0);
style2.setFillForegroundColor(lightGray.getIndex());
style2.setFillPattern(CellStyle.SOLID_FOREGROUND);

JsonParseException: Unrecognized token 'http': was expecting ('true', 'false' or 'null')

It might be obvious, but make sure that you are sending to the parser URL object not a String containing www adress. This will not work:

    ObjectMapper mapper = new ObjectMapper();
    String www = "www.sample.pl";
    Weather weather = mapper.readValue(www, Weather.class);

But this will:

    ObjectMapper mapper = new ObjectMapper();
    URL www = new URL("http://www.oracle.com/");
    Weather weather = mapper.readValue(www, Weather.class);

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

I just wanted to share some of my results...

I have text files, which apparently came from a Linux system, so I only have a vbLF/Chr(10) at the end of each line and not vbCR/Chr(13).

Note 1:

  • This meant that the Line Input method would read in the entire file, instead of just one line at a time.

From my research testing small (152KB) & large (2778LB) files, both on and off the network I found the following:

Open FileName For Input: Line Input was the slowest (See Note 1 above)

Open FileName For Binary Access Read: Input was the fastest for reading the whole file

FSO.OpenTextFile: ReadLine was fast, but a bit slower then Binary Input

Note 2:

  • If I just needed to check the file header (first 1-2 lines) to check if I had the proper file/format, then FSO.OpenTextFile was the fastest, followed very closely by Binary Input.

  • The drawback with the Binary Input is that you have to know how many characters you want to read.

  • On normal files, Line Input would also be a good option as well, but I couldn't test due to Note 1.

 

Note 3:

  • Obviously, the files on the network showed the largest difference in read speed. They also showed the greatest benefit from reading the file a second time (although there are certainly memory buffers that come into play here).

How do I install pip on macOS or OS X?

Install without the need for sudo

If you want to install pip without the need for sudo, which is always frustrating when trying to install packages globally, install pip in your local folder /usr/local like this:

curl https://bootstrap.pypa.io/get-pip.py > get-pip.py
python get-pip.py --prefix=/usr/local/

and then:

pip install <package-of-choice> without sudo

nodejs get file name from absolute path?

If you already know that the path separator is / (i.e. you are writing for a specific platform/environment), as implied by the example in your question, you could keep it simple and split the string by separator:

'/foo/bar/baz/asdf/quux.html'.split('/').pop()

That would be faster (and cleaner imo) than replacing by regular expression.

Again: Only do this if you're writing for a specific environment, otherwise use the path module, as paths are surprisingly complex. Windows, for instance, supports / in many cases but not for e.g. the \\?\? style prefixes used for shared network folders and the like. On Windows the above method is doomed to fail, sooner or later.

When should I use a trailing slash in my URL?

It is not a question of preference. /base and /base/ have different semantics. In many cases, the difference is unimportant. But it is important when there are relative URLs.

  • child relative to /base/ is /base/child.
  • child relative to /base is (perhaps surprisingly) /child.

How do I edit $PATH (.bash_profile) on OSX?

Mac OS X doesn't store the path in .bash_profile, but .profile, since Mac OS X is a branch of *BSD family. You should be able to see the export blah blah blah in .profile once you do cat .profile on your terminal.

How to encode the plus (+) symbol in a URL

Is you want a plus (+) symbol in the body you have to encode it as 2B.

For example: Try this

How to redirect single url in nginx?

Put this in your server directive:

location /issue {
   rewrite ^/issue(.*) http://$server_name/shop/issues/custom_issue_name$1 permanent;
 }

Or duplicate it:

location /issue1 {
   rewrite ^/.* http://$server_name/shop/issues/custom_issue_name1 permanent;
}
location /issue2 {
   rewrite ^.* http://$server_name/shop/issues/custom_issue_name2 permanent;
}
 ...

Difference between char* and const char*?

CASE 1:

char *str = "Hello";
str[0] = 'M'  //Warning may be issued by compiler, and will cause segmentation fault upon running the programme

The above sets str to point to the literal value "Hello" which is hard-coded in the program's binary image, which is flagged as read-only in memory, means any change in this String literal is illegal and that would throw segmentation faults.

CASE 2:

const char *str = "Hello";
str[0] = 'M'  //Compile time error

CASE 3:

char str[] = "Hello";
str[0] = 'M'; // legal and change the str = "Mello".

How do I replace part of a string in PHP?

You can try

$string = "this is the test for string." ;
$string = str_replace(' ', '_', $string);
$string = substr($string,0,10);

var_dump($string);

Output

this_is_th

How to change value for innodb_buffer_pool_size in MySQL on Mac OS?

I had to put the statement under the [mysqld] block to make it work. Otherwise the change was not reflected. I have a REL distribution.

C++ equivalent of StringBuffer/StringBuilder?

std::string's += doesn't work with const char* (what stuff like "string to add" appear to be), so definitely using stringstream is the closest to what is required - you just use << instead of +

How to avoid java.util.ConcurrentModificationException when iterating through and removing elements from an ArrayList

You are trying to remove value from list in advanced "for loop", which is not possible, even if you apply any trick (which you did in your code). Better way is to code iterator level as other advised here.

I wonder how people have not suggested traditional for loop approach.

for( int i = 0; i < lStringList.size(); i++ )
{
    String lValue = lStringList.get( i );
    if(lValue.equals("_Not_Required"))
    {
         lStringList.remove(lValue);
         i--; 
    }  
}

This works as well.

how to set imageview src?

What you are looking for is probably this:

ImageView myImageView;
myImageView = mDialog.findViewById(R.id.image_id);
String src = "imageFileName"

int drawableId = this.getResources().getIdentifier(src, "drawable", context.getPackageName())
popupImageView.setImageResource(drawableId);

Let me know if this was helpful :)

Less than or equal to

In batch, the > is a redirection sign used to output data into a text file. The compare op's available (And recommended) for cmd are below (quoted from the if /? help):

where compare-op may be one of:

    EQU - equal
    NEQ - not equal
    LSS - less than
    LEQ - less than or equal
    GTR - greater than
    GEQ - greater than or equal

That should explain what you want. The only other compare-op is == which can be switched with the if not parameter. Other then that rely on these three letter ones.

git returns http error 407 from proxy after CONNECT

Maybe you are already using the system proxy setting - in this case unset all git proxies will work:

git config --global --unset http.proxy
git config --global --unset https.proxy

ERROR 1698 (28000): Access denied for user 'root'@'localhost'

This has happened to me as well. The problem is with the mysql repo that comes already with the linux distro. So when you simply do: $ sudo apt install mysql-server it installs mysql from their default repo which gives this problem. So to overcome that you need to uninstall that installed mysql $ sudo apt remove mysql* --purge --auto-remove

Then download mysql repo from official mysql website MySQL APT Repo Follow their documentation on how to add repo and install it. This gives no issue. Also as answered by @zetacu, you can verify that mysql root now indeed uses mysql_native_password plugin

Html table with button on each row

Put a single listener on the table. When it gets a click from an input with a button that has a name of "edit" and value "edit", change its value to "modify". Get rid of the input's id (they aren't used for anything here), or make them all unique.

<script type="text/javascript">

function handleClick(evt) {
  var node = evt.target || evt.srcElement;
  if (node.name == 'edit') {
    node.value = "Modify";
  }
}

</script>

<table id="table1" border="1" onclick="handleClick(event);">
    <thead>
      <tr>
          <th>Select
    </thead>
    <tbody>
       <tr> 
           <td>
               <form name="f1" action="#" >
                <input id="edit1" type="submit" name="edit" value="Edit">
               </form>
       <tr> 
           <td>
               <form name="f2" action="#" >
                <input id="edit2" type="submit" name="edit" value="Edit">
               </form>
       <tr> 
           <td>
               <form name="f3" action="#" >
                <input id="edit3" type="submit" name="edit" value="Edit">
               </form>

   </tbody>
</table>

useState set method not reflecting change immediately

You can solve it by using the useRef hook but then it's will not re-render when it' updated. I have created a hooks called useStateRef, that give you the good from both worlds. It's like a state that when it's updated the Component re-render, and it's like a "ref" that always have the latest value.

See this example:

var [state,setState,ref]=useStateRef(0)

It works exactly like useState but in addition, it gives you the current state under ref.current

Learn more:

Accessing the last entry in a Map

A SortedMap is the logical/best choice, however another option is to use a LinkedHashMap which maintains two order modes, most-recently-added goes last, and most-recently-accessed goes last. See the Javadocs for more details.

Retrieving a List from a java.util.stream.Stream in Java 8

A little more efficient way (avoid the creating the source List and the auto-unboxing by the filter):

List<Long> targetLongList = LongStream.of(1L, 10L, 50L, 80L, 100L, 120L, 133L, 333L)
    .filter(l -> l > 100)
    .boxed()
    .collect(Collectors.toList());

Check whether a string contains a substring

To find out if a string contains substring you can use the index function:

if (index($str, $substr) != -1) {
    print "$str contains $substr\n";
} 

It will return the position of the first occurrence of $substr in $str, or -1 if the substring is not found.

Defining a `required` field in Bootstrap

Use 'needs-validation' apart from form-group, it will work.

Playing a MP3 file in a WinForm application

You can use the mciSendString API to play an MP3 or a WAV file:

[DllImport("winmm.dll")]
public static extern uint mciSendString( 
    string lpstrCommand,
    StringBuilder lpstrReturnString,
    int uReturnLength,
    IntPtr hWndCallback
);

mciSendString(@"close temp_alias", null, 0, IntPtr.Zero);
mciSendString(@"open ""music.mp3"" alias temp_alias", null, 0, IntPtr.Zero);
mciSendString("play temp_alias repeat", null, 0, IntPtr.Zero);

Copy and paste content from one file to another file in vi

Goal: save a piece of one file to another file.

Solution:

  1. Select the text you want to save:
    • Position the cursor where you want to start selection
    • Press v to select characters OR uppercase V to select whole lines
    • Move the cursor to the end of what you want to select
  2. Save selected text to the new file. Type :wSpace and the name of the new file. Actually you'll see

    :'<,'>w new.txt

    Then press Enter

How to fix "namespace x already contains a definition for x" error? Happened after converting to VS2010

I had this problem. It was due to me renaming a folder in the App_Code directory and releasing to my iis site folder. The original named folder was still present in my target directory - hence duplicate - (I don't do a full delete of target before copying) Anyway removing the old folder fixed this.

How to save a figure in MATLAB from the command line?

imwrite(A,filename) writes image data A to the file specified by filename, inferring the file format from the extension

Get Number of Rows returned by ResultSet in Java

You could count with sql and retrieve the answer from the resultset like so:

Statment stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, 
                                     ResultSet.CONCUR_READ_ONLY);
ResultSet ct = stmt.executeQuery("SELECT COUNT(*) FROM [table_name]");
if(ct.next()){
   td.setTotalNumRows(ct.getInt(1));
}

Here I'm counting everything but you can easily modify the SQL to count based on a criteria.

Groovy Shell warning "Could not open/create prefs root node ..."

I was getting the following message:

Could not open/create prefs root node Software\JavaSoft\Prefs at root 0x80000002

and it was gone after creating one of these registry keys, mine is 64 bit so I tried only that.

32 bit Windows
HKEY_LOCAL_MACHINE\Software\JavaSoft\Prefs

64 bit Windows
HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\JavaSoft\Prefs

Node.js + Nginx - What now?

Nginx can act as a reverse proxy server which works just like a project manager. When it gets a request it analyses it and forwards the request to upstream(project members) or handles itself. Nginx has two ways of handling a request based on how its configured.

  • serve the request
  • forward the request to another server

    server{
     server_name mydomain.com sub.mydomain.com;
    
     location /{ 
      proxy_pass http://127.0.0.1:8000;  
      proxy_set_header Host $host;
      proxy_pass_request_headers on;  
     }
    
     location /static/{
       alias /my/static/files/path;
     }
    

    }

Server the request

With this configuration, when the request url is mydomain.com/static/myjs.js it returns the myjs.js file in /my/static/files/path folder. When you configure nginx to serve static files, it handles the request itself.

forward the request to another server

When the request url is mydomain.com/dothis nginx will forwards the request to http://127.0.0.1:8000. The service which is running on the localhost 8000 port will receive the request and returns the response to nginx and nginx returns the response to the client.

When you run node.js server on the port 8000 nginx will forward the request to node.js. Write node.js logic and handle the request. That's it you have your nodejs server running behind the nginx server.

If you wish to run any other services other than nodejs just run another service like Django, flask, php on different ports and config it in nginx.

How to add a reference programmatically

There are two ways to add references using VBA. .AddFromGuid(Guid, Major, Minor) and .AddFromFile(Filename). Which one is best depends on what you are trying to add a reference to. I almost always use .AddFromFile because the things I am referencing are other Excel VBA Projects and they aren't in the Windows Registry.

The example code you are showing will add a reference to the workbook the code is in. I generally don't see any point in doing that because 90% of the time, before you can add the reference, the code has already failed to compile because the reference is missing. (And if it didn't fail-to-compile, you are probably using late binding and you don't need to add a reference.)

If you are having problems getting the code to run, there are two possible issues.

  1. In order to easily use the VBE's object model, you need to add a reference to Microsoft Visual Basic for Application Extensibility. (VBIDE)
  2. In order to run Excel VBA code that changes anything in a VBProject, you need to Trust access to the VBA Project Object Model. (In Excel 2010, it is located in the Trust Center - Macro Settings.)

Aside from that, if you can be a little more clear on what your question is or what you are trying to do that isn't working, I could give a more specific answer.

bootstrap 3 wrap text content within div for horizontal alignment

Now Update word-wrap is replace by :

overflow-wrap:break-word;

Compatible old navigator and css 3 it's good alternative !

it's evolution of word-wrap ( since 2012... )

See more information : https://www.w3.org/TR/css-text-3/#overflow-wrap

See compatibility full : http://caniuse.com/#search=overflow-wrap

Angularjs simple file download causes router to redirect

in template

<md-button class="md-fab md-mini md-warn md-ink-ripple" ng-click="export()" aria-label="Export">
<md-icon class="material-icons" alt="Export" title="Export" aria-label="Export">
    system_update_alt
</md-icon></md-button>

in controller

     $scope.export = function(){ $window.location.href = $scope.export; };

HTML CSS Button Positioning

Use margins instead of line-height and then apply float to the buttons. By default they are displaying as inline-block, so when one is pushed down the hole line is pushed down with him. Float fixes this:

#header button {
    float:left;
}

Here's a working jsfidle.

Commands out of sync; you can't run this command now

I often hit this error and it's always when I run a stored procedure that I have been debugging in phpmyadmin or SQL Workbench (I am working in php connecting with mysqli).

The error results from the fact that the debugging involves inserting SELECT statements at strategic points in the code to tell me the state of variables, etc. Running a stored procedure that produces multiple results sets in these client environments is fine, but it produces the "Commands out of sync" error when called from php. The solution is always to comment-out or remove the debugging selects so the procedure has only one result set.

Access to file download dialog in Firefox

I had the same problem, I wanted no access of Save Dialogue.

Below code can help:

    FirefoxProfile fp = new FirefoxProfile();
    fp.setPreference("browser.download.folderList",2);
    fp.setPreference("browser.download.manager.showWhenStarting",false);
    fp.setPreference("browser.helperApps.alwaysAsk.force", false);
    // Below you have to set the content-type of downloading file(I have set simple CSV file)
    fp.setPreference("browser.helperApps.neverAsk.saveToDisk","text/csv");

According to the file type which is being downloaded, You need to specify content types.

You can specify multiple content-types separated with ' ; '

e.g:

    fp.setPreference("browser.helperApps.neverAsk.saveToDisk","text/csv;application/vnd.ms-excel;application/msword");

Ruby array to string conversion

irb(main):027:0> puts ['12','34','35','231'].inspect.to_s[1..-2].gsub('"', "'")
'12', '34', '35', '231'
=> nil

How to increase request timeout in IIS?

In IIS >= 7, a <webLimits> section has replaced ConnectionTimeout, HeaderWaitTimeout, MaxGlobalBandwidth, and MinFileBytesPerSec IIS 6 metabase settings.

Example Configuration:

<configuration>
   <system.applicationHost>
      <webLimits connectionTimeout="00:01:00"
         dynamicIdleThreshold="150"
         headerWaitTimeout="00:00:30"
         minBytesPerSecond="500"
      />
   </system.applicationHost>
</configuration>

For reference: more information regarding these settings in IIS can be found here. Also, I was unable to add this section to the web.config via the IIS manager's "configuration editor", though it did show up once I added it and searched the configuration.

matplotlib error - no module named tkinter

For windows users, re-run the installer. Select Modify. Check the box for tcl/tk and IDLE. The description for this says "Installs tkinter"

Bloomberg BDH function with ISIN

The problem is that an isin does not identify the exchange, only an issuer.

Let's say your isin is US4592001014 (IBM), one way to do it would be:

  • get the ticker (in A1):

    =BDP("US4592001014 ISIN", "TICKER") => IBM
    
  • get a proper symbol (in A2)

    =BDP("US4592001014 ISIN", "PARSEKYABLE_DES") => IBM XX Equity
    

    where XX depends on your terminal settings, which you can check on CNDF <Go>.

  • get the main exchange composite ticker, or whatever suits your need (in A3):

    =BDP(A2,"EQY_PRIM_SECURITY_COMP_EXCH") => US
    
  • and finally:

    =BDP(A1&" "&A3&" Equity", "LAST_PRICE") => the last price of IBM US Equity
    

When to use dynamic vs. static libraries

A static library must be linked into the final executable; it becomes part of the executable and follows it wherever it goes. A dynamic library is loaded every time the executable is executed and remains separate from the executable as a DLL file.

You would use a DLL when you want to be able to change the functionality provided by the library without having to re-link the executable (just replace the DLL file, without having to replace the executable file).

You would use a static library whenever you don't have a reason to use a dynamic library.

'"SDL.h" no such file or directory found' when compiling

If the header file is /usr/include/sdl/SDL.h and your code has:

#include "SDL.h"

You need to either fix your code:

#include "sdl/SDL.h"

Or tell the preprocessor where to find include files:

CFLAGS = ... -I/usr/include/sdl ...

Open file by its full path in C++

The code seems working to me. I think the same with @Iothar.

Check to see if you include the required headers, to compile. If it is compiled, check to see if there is such a file, and everything, names etc, matches, and also check to see that you have a right to read the file.

To make a cross check, check if you can open it with fopen..

FILE *f = fopen("C:/Demo.txt", "r");
if (f)
  printf("fopen success\n");

How many characters in varchar(max)

See the MSDN reference table for maximum numbers/sizes.

Bytes per varchar(max), varbinary(max), xml, text, or image column: 2^31-1

There's a two-byte overhead for the column, so the actual data is 2^31-3 max bytes in length. Assuming you're using a single-byte character encoding, that's 2^31-3 characters total. (If you're using a character encoding that uses more than one byte per character, divide by the total number of bytes per character. If you're using a variable-length character encoding, all bets are off.)

Looping through list items with jquery

Try this code. By using the parent>child selector "#productList li" it should find all li elements. Then, you can iterate through the result object using the each() method which will only alter li elements that have been found.

listItems = $("#productList li").each(function(){

        var product = $(this);
        var productid = product.children(".productId").val();
        var productPrice = product.find(".productPrice").val();
        var productMSRP = product.find(".productMSRP").val();

        totalItemsHidden.val(parseInt(totalItemsHidden.val(), 10) + 1);
        subtotalHidden.val(parseFloat(subtotalHidden.val()) + parseFloat(productMSRP));
        savingsHidden.val(parseFloat(savingsHidden.val()) + parseFloat(productMSRP - productPrice));
        totalHidden.val(parseFloat(totalHidden.val()) + parseFloat(productPrice));

    });

How can I clone a JavaScript object except for one key?

Lodash omit

let source = //{a: 1, b: 2, c: 3, ..., z:26}
let copySansProperty = _.omit(source, 'b');
// {a: 1, c: 3, ..., z:26}

How to read connection string in .NET Core?

This is how I did it:

I added the connection string at appsettings.json

"ConnectionStrings": {
"conStr": "Server=MYSERVER;Database=MYDB;Trusted_Connection=True;MultipleActiveResultSets=true"},

I created a class called SqlHelper

public class SqlHelper
{
    //this field gets initialized at Startup.cs
    public static string conStr;

    public static SqlConnection GetConnection()
    {
        try
        {
            SqlConnection connection = new SqlConnection(conStr);
            return connection;
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
            throw;
        }
    }
}

At the Startup.cs I used ConfigurationExtensions.GetConnectionString to get the connection,and I assigned it to SqlHelper.conStr

public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
        SqlHelper.connectionString = ConfigurationExtensions.GetConnectionString(this.Configuration, "conStr");
    }

Now wherever you need the connection string you just call it like this:

SqlHelper.GetConnection();

Loop through an array in JavaScript

Use the while loop...

var i = 0, item, items = ['one', 'two', 'three'];
while(item = items[i++]){
    console.log(item);
}

It logs: 'one', 'two', and 'three'

And for the reverse order, an even more efficient loop:

var items = ['one', 'two', 'three'], i = items.length;
while(i--){
    console.log(items[i]);
}

It logs: 'three', 'two', and 'one'

Or the classical for loop:

var items = ['one', 'two', 'three']
for(var i=0, l = items.length; i < l; i++){
    console.log(items[i]);
}

It logs: 'one','two','three'

Reference: Google Closure: How not to write JavaScript

CSS media queries: max-width OR max-height

Use a comma to specify two (or more) different rules:

@media screen and (max-width: 995px), 
       screen and (max-height: 700px) {
  ...
}

From https://developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries/Using_media_queries

Commas are used to combine multiple media queries into a single rule. Each query in a comma-separated list is treated separately from the others. Thus, if any of the queries in a list is true, the entire media statement returns true. In other words, lists behave like a logical or operator.

How do I get the last word in each line with bash

Try

$ awk 'NF>1{print $NF}' file
example.
line.
file.

To get the result in one line as in your example, try:

{
    sub(/\./, ",", $NF)
    str = str$NF
}
END { print str }

output:

$ awk -f script.awk file
example, line, file, 

Pure bash:

$ while read line; do [ -z "$line" ] && continue ;echo ${line##* }; done < file
example.
line.
file.

How can I align text directly beneath an image?

Your HTML:

<div class="img-with-text">
    <img src="yourimage.jpg" alt="sometext" />
    <p>Some text</p>
</div>

If you know the width of your image, your CSS:

.img-with-text {
    text-align: justify;
    width: [width of img];
}

.img-with-text img {
    display: block;
    margin: 0 auto;
}

Otherwise your text below the image will free-flow. To prevent this, just set a width to your container.

What is the difference between atan and atan2 in C++?

atan(x) Returns the principal value of the arc tangent of x, expressed in radians.

atan2(y,x) Returns the principal value of the arc tangent of y/x, expressed in radians.

Notice that because of the sign ambiguity, a function cannot determine with certainty in which quadrant the angle falls only by its tangent value (atan alone). You can use atan2 if you need to determine the quadrant.

Difference between Fact table and Dimension table?

From my point of view,

  • Dimension table : Master Data
  • Fact table : Transactional Data

MySQL Trigger: Delete From Table AFTER DELETE

Why not set ON CASCADE DELETE on Foreign Key patron_info.pid?

Checking Bash exit status of several commands efficiently

For what it's worth, a shorter way to write code to check each command for success is:

command1 || echo "command1 borked it"
command2 || echo "command2 borked it"

It's still tedious but at least it's readable.

ERROR 1049 (42000): Unknown database 'mydatabasename'

I had the same issue, i run this command on command line and just like you i had added the ';' at the end. Removing it solved the issue. Instead of this

mysql -uroot -pmypassword mydatabase<mydatabase.sql;

try this

mysql -uroot -pmypassword mydatabase<mydatabase.sql

Visual Studio 2008 Product Key in Registry?

For 32 bit Windows:


Visual Studio 2003:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\7.0\Registration\PIDKEY

Visual Studio 2005:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\8.0\Registration\PIDKEY

Visual Studio 2008:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\9.0\Registration\PIDKEY


For 64 bit Windows:


Visual Studio 2003:

HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\VisualStudio\7.0\Registration\PIDKEY

Visual Studio 2005:

HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\VisualStudio\8.0\Registration\PIDKEY

Visual Studio 2008:

HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\VisualStudio\9.0\Registration\PIDKEY


Notes:

  • Data is a GUID without dashes. Put a dash ( – ) after every 5 characters to convert to product key.
  • If PIDKEY value is empty try to look at the subfolders e.g.

    ...\Registration\1000.0x0000\PIDKEY

    or

    ...\Registration\2000.0x0000\PIDKEY

BSTR to std::string (std::wstring) and vice versa

Simply pass the BSTR directly to the wstring constructor, it is compatible with a wchar_t*:

BSTR btest = SysAllocString(L"Test");
assert(btest != NULL);
std::wstring wtest(btest);
assert(0 == wcscmp(wtest.c_str(), btest));

Converting BSTR to std::string requires a conversion to char* first. That's lossy since BSTR stores a utf-16 encoded Unicode string. Unless you want to encode in utf-8. You'll find helper methods to do this, as well as manipulate the resulting string, in the ICU library.

How to set the thumbnail image on HTML5 video?

That seems to be an extra image being shown there.

You can try using this

<img src="/images/image_of_video.png" alt="image" />
/* write your code for the video here */

Now using jQuery play the video and hide the image as

$('img').click(function () {
  $(this).hide();
  // use the parameters to play the video now..
})

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

Sometime finish() not working

I have solved that issue with

finishAffinity()

Uninitialized Constant MessagesController

Your model is @Messages, change it to @message.

To change it like you should use migration:

def change   rename_table :old_table_name, :new_table_name end 

Of course do not create that file by hand but use rails generator:

rails g migration ChangeMessagesToMessage 

That will generate new file with proper timestamp in name in 'db dir. Then run:

rake db:migrate 

And your app should be fine since then.

How to downgrade python from 3.7 to 3.6

For those who want to add multiple Python version in their system: I easily add multiple interpreters by running the following commands:

  • sudo apt update
  • sudo apt install software-properties-common
  • sudo add-apt-repository ppa:deadsnakes/ppa
  • sudo apt install python 3.x.x
  • then while making your virtual environment choose the interpreter of your choice.

Create tap-able "links" in the NSAttributedString of a UILabel?

    NSString *string = name;
    NSError *error = NULL;
    NSDataDetector *detector =
    [NSDataDetector dataDetectorWithTypes:(NSTextCheckingTypes)NSTextCheckingTypeLink | NSTextCheckingTypePhoneNumber
                                    error:&error];
    NSArray *matches = [detector matchesInString:string
                                         options:0
                                           range:NSMakeRange(0, [string length])];
    for (NSTextCheckingResult *match in matches)
    {
        if (([match resultType] == NSTextCheckingTypePhoneNumber))
        {
            NSString *phoneNumber = [match phoneNumber];
            NSLog(@" Phone Number is :%@",phoneNumber);
            label.enabledTextCheckingTypes = NSTextCheckingTypePhoneNumber;
        }

        if(([match resultType] == NSTextCheckingTypeLink))
        {
            NSURL *email = [match URL];
            NSLog(@"Email is  :%@",email);
            label.enabledTextCheckingTypes = NSTextCheckingTypeLink;
        }

        if (([match resultType] == NSTextCheckingTypeLink))
        {
            NSURL *url = [match URL];
            NSLog(@"URL is  :%@",url);
            label.enabledTextCheckingTypes = NSTextCheckingTypeLink;
        }
    }

    label.text =name;
}

How to "inverse match" with regex?

Negative lookahead assertion

(?!Andrea)

This is not exactly an inverted match, but it's the best you can directly do with regex. Not all platforms support them though.

How to use null in switch

You can also use String.valueOf((Object) nullableString) like

switch (String.valueOf((Object) nullableString)) {
case "someCase"
    //...
    break;
...
case "null": // or default:
    //...
        break;
}

See interesting SO Q/A: Why does String.valueOf(null) throw a NullPointerException

awk - concatenate two string variable and assign to a third

Concatenating strings in awk can be accomplished by the print command AWK manual page, and you can do complicated combination. Here I was trying to change the 16 char to A and used string concatenation:

echo    CTCTCTGAAATCACTGAGCAGGAGAAAGATT | awk -v w=15 -v BA=A '{OFS=""; print substr($0, 1, w), BA, substr($0,w+2)}'
Output: CTCTCTGAAATCACTAAGCAGGAGAAAGATT

I used the substr function to extract a portion of the input (STDIN). I passed some external parameters (here I am using hard-coded values) that are usually shell variable. In the context of shell programming, you can write -v w=$width -v BA=$my_charval. The key is the OFS which stands for Output Field Separate in awk. Print function take a list of values and write them to the STDOUT and glue them with the OFS. This is analogous to the perl join function.

It looks that in awk, string can be concatenated by printing variable next to each other:

echo xxx | awk -v a="aaa" -v b="bbb" '{ print a b $1 "string literal"}'
# will produce: aaabbbxxxstring literal

What's the difference between primitive and reference types?

Primitives vs. References

First :-

Primitive types are the basic types of data: byte, short, int, long, float, double, boolean, char. Primitive variables store primitive values. Reference types are any instantiable class as well as arrays: String, Scanner, Random, Die, int[], String[], etc. Reference variables store addresses to locations in memory for where the data is stored.

Second:-

Primitive types store values but Reference type store handles to objects in heap space. Remember, reference variables are not pointers like you might have seen in C and C++, they are just handles to objects, so that you can access them and make some change on object's state.

Read more: http://javarevisited.blogspot.com/2015/09/difference-between-primitive-and-reference-variable-java.html#ixzz3xVBhi2cr

remove legend title in ggplot

Since you may have more than one legends in a plot, a way to selectively remove just one of the titles without leaving an empty space is to set the name argument of the scale_ function to NULL, i.e.

scale_fill_discrete(name = NULL)

(kudos to @pascal for a comment on another thread)

Calculate mean across dimension in a 2D array

Here is a non-numpy solution:

>>> a = [[40, 10], [50, 11]]
>>> [float(sum(l))/len(l) for l in zip(*a)]
[45.0, 10.5]

"psql: could not connect to server: Connection refused" Error when connecting to remote database

In my case I had removed a locale and generated another locale. Database failed to open because of fatal errors in the postgresql.conf file, on 'lc_messages', 'lc_monetary', 'lc_numberic', and 'lc_time'.

Restoring the locale sorted it out for me.

Finding an elements XPath using IE Developer tool

You can find/debug XPath/CSS locators in the IE as well as in different browsers with the tool called SWD Page Recorder

The only restrictions/limitations:

  1. The browser should be started from the tool
  2. Internet Explorer Driver Server - IEDriverServer.exe - should be downloaded separately and placed near SwdPageRecorder.exe

Using the AND and NOT Operator in Python

You should write :

if (self.a != 0) and (self.b != 0) :

"&" is the bit wise operator and does not suit for boolean operations. The equivalent of "&&" is "and" in Python.

A shorter way to check what you want is to use the "in" operator :

if 0 not in (self.a, self.b) :

You can check if anything is part of a an iterable with "in", it works for :

  • Tuples. I.E : "foo" in ("foo", 1, c, etc) will return true
  • Lists. I.E : "foo" in ["foo", 1, c, etc] will return true
  • Strings. I.E : "a" in "ago" will return true
  • Dict. I.E : "foo" in {"foo" : "bar"} will return true

As an answer to the comments :

Yes, using "in" is slower since you are creating an Tuple object, but really performances are not an issue here, plus readability matters a lot in Python.

For the triangle check, it's easier to read :

0 not in (self.a, self.b, self.c)

Than

(self.a != 0) and (self.b != 0) and (self.c != 0) 

It's easier to refactor too.

Of course, in this example, it really is not that important, it's very simple snippet. But this style leads to a Pythonic code, which leads to a happier programmer (and losing weight, improving sex life, etc.) on big programs.

How do you post to an iframe?

This function creates a temporary form, then send data using jQuery :

function postToIframe(data,url,target){
    $('body').append('<form action="'+url+'" method="post" target="'+target+'" id="postToIframe"></form>');
    $.each(data,function(n,v){
        $('#postToIframe').append('<input type="hidden" name="'+n+'" value="'+v+'" />');
    });
    $('#postToIframe').submit().remove();
}

target is the 'name' attr of the target iFrame, and data is a JS object :

data={last_name:'Smith',first_name:'John'}

how to get the last character of a string?

You can get the last char like this :

var lastChar=yourString.charAt(yourString.length-1);

Rails - passing parameters in link_to

Try this

link_to "+ Service", my_services_new_path(:account_id => acct.id)

it will pass the account_id as you want.

For more details on link_to use this http://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#method-i-link_to

Stuck at ".android/repositories.cfg could not be loaded."

Windows 10 Solution:

For me this issue was due to downloading and creating an AVD using Android Studio and then trying to use that virtual device with the Ionic command line. I resolved this by deleting all existing emulators and creating a new one from the command line.

(the avdmanager file typically lives in C:\Users\\Android\sdk\tools\bin)

List existing emulators: avdmanager list avd

Delete an existing emulator: avdmanager delete avd -n emulator_name

Add system image: sdkmanager "system-images;android-24;default;x86_64"

Create new emulator: sdkmanager "system-images;android-27;google_apis_playstore;x86"

JavaScript, get date of the next day

Copy-pasted from here: Incrementing a date in JavaScript

Three options for you:

Using just JavaScript's Date object (no libraries):

var today = new Date();
var tomorrow = new Date(today.getTime() + (24 * 60 * 60 * 1000));

Or if you don't mind changing the date in place (rather than creating a new date):

var dt = new Date();
dt.setTime(dt.getTime() + (24 * 60 * 60 * 1000));

Edit: See also Jigar's answer and David's comment below: var tomorrow = new Date(); tomorrow.setDate(tomorrow.getDate() + 1);

Using MomentJS:

var today = moment();
var tomorrow = moment(today).add(1, 'days');

(Beware that add modifies the instance you call it on, rather than returning a new instance, so today.add(1, 'days') would modify today. That's why we start with a cloning op on var tomorrow = ....)

Using DateJS, but it hasn't been updated in a long time:

var today = new Date(); // Or Date.today()
var tomorrow = today.add(1).day();

Create Elasticsearch curl query for not null and not empty("")

On elasticsearch 5.6, I have to use command below to filter out empty string:

    GET /_search
    {
        "query" : {
            "regexp":{
                "<your_field_name_here>": ".+"
            }
        }
    }  

Rotating a point about another point (2D)

If you rotate point (px, py) around point (ox, oy) by angle theta you'll get:

p'x = cos(theta) * (px-ox) - sin(theta) * (py-oy) + ox

p'y = sin(theta) * (px-ox) + cos(theta) * (py-oy) + oy

this is an easy way to rotate a point in 2D.

What exactly does the T and Z mean in timestamp?

The T doesn't really stand for anything. It is just the separator that the ISO 8601 combined date-time format requires. You can read it as an abbreviation for Time.

The Z stands for the Zero timezone, as it is offset by 0 from the Coordinated Universal Time (UTC).

Both characters are just static letters in the format, which is why they are not documented by the datetime.strftime() method. You could have used Q or M or Monty Python and the method would have returned them unchanged as well; the method only looks for patterns starting with % to replace those with information from the datetime object.

Load image from resources

You can add an image resource in the project then (right click on the project and choose the Properties item) access that in this way:

this.picturebox.image = projectname.properties.resources.imagename;

sql how to cast a select query

Yes you can do.

Syntax for CAST:

CAST ( expression AS data_type [ ( length ) ] )

For example:

CAST(MyColumn AS Varchar(10))

CAST in SELECT Statement:

Select CAST(MyColumn AS Varchar(10)) AS MyColumn
FROM MyTable

See for more information CAST and CONVERT (Transact-SQL)

Visual Studio debugging/loading very slow

Another last resort solution with respect to time is to repair the VS installation.

  • Go to Tools => Get Tools and Features
  • Locate the existing VS installation, and choose repair under the more button.
    • For example: Visual Studio Enterprise 2019 installation.

Warning: mysqli_connect(): (HY000/1045): Access denied for user 'username'@'localhost' (using password: YES)

try

define("DB_PASSWORD", null);

and those are warnings try

$db = @mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE);

But i will recommend you to set a root password

Multiple Where clauses in Lambda expressions

x=> x.Lists.Include(l => l.Title).Where(l=>l.Title != String.Empty).Where(l => l.Internal NAme != String.Empty)

or

x=> x.Lists.Include(l => l.Title).Where(l=>l.Title != String.Empty && l.Internal NAme != String.Empty)

Any implementation of Ordered Set in Java?

I had a similar problem. I didn't quite need an ordered set but more a list with a fast indexOf/contains. As I didn't find anything out there I implemented one myself. Here's the code, it implements both Set and List, though not all bulk list operations are as fast as the ArrayList versions.

disclaimer: not tested

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Set;
import java.util.Collection;
import java.util.Comparator;
import java.util.function.Predicate;
import java.util.function.UnaryOperator;
import static java.util.Objects.requireNonNull;

/**
 * An ArrayList that keeps an index of its content so that contains()/indexOf() are fast. Duplicate entries are
 * ignored as most other java Set's do.
 */
public class IndexedArraySet<E> extends ArrayList<E> implements Set<E> {

    public IndexedArraySet() { super(); }

    public IndexedArraySet(Iterable<E> c) {
        super();
        addAll(c);
    }

    private HashMap<E, Integer> indexMap = new HashMap<>();

    private void reindex() {
        indexMap.clear();
        int idx = 0;
        for (E item: this) {
            addToIndex(item, idx++);
        }
    }

    private E addToIndex(E e, int idx) {
        indexMap.putIfAbsent(requireNonNull(e), idx);
        return e;
    }

    @Override
    public boolean add(E e) {
        if(indexMap.putIfAbsent(requireNonNull(e), size()) != null) return false;
        super.add(e);
        return true;
    }

    @Override
    public boolean addAll(Collection<? extends E> c) {
        return addAll((Iterable<? extends E>) c);
    }
    public boolean addAll(Iterable<? extends E> c) {
        boolean rv = false;
        for (E item: c) {
            rv |= add(item);
        }
        return rv;
    }

    @Override
    public boolean contains(Object e) {
        return indexMap.containsKey(e);
    }

    @Override

    public int indexOf(Object e) {
        if (e == null) return -1;
        Integer i = indexMap.get(e);
        return (i == null) ? -1 : i;
    }

    @Override
    public int lastIndexOf(Object e) {
        return indexOf(e);
    }

    @Override @SuppressWarnings("unchecked")
    public Object clone() {
        IndexedArraySet clone = (IndexedArraySet) super.clone();
        clone.indexMap = (HashMap) indexMap.clone();
        return clone;
    }

    @Override
    public void add(int idx, E e) {
        if(indexMap.putIfAbsent(requireNonNull(e), -1) != null) return;
        super.add(idx, e);
        reindex();
    }

    @Override
    public boolean remove(Object e) {
        boolean rv;
        try { rv = super.remove(e); }
        finally { reindex(); }
        return rv;
    }

    @Override
    public void clear() {
        super.clear();
        indexMap.clear();
    }

    @Override
    public boolean addAll(int idx, Collection<? extends E> c) {
        boolean rv;
        try {
            for(E item : c) {
                // check uniqueness
                addToIndex(item, -1);
            }
            rv = super.addAll(idx, c);
        } finally {
            reindex();
        }
        return rv;
    }

    @Override
    public boolean removeAll(Collection<?> c) {
        boolean rv;
        try { rv = super.removeAll(c); }
        finally { reindex(); }
        return rv;
    }

    @Override
    public boolean retainAll(Collection<?> c) {
        boolean rv;
        try { rv = super.retainAll(c); }
        finally { reindex(); }
        return rv;
    }

    @Override
    public boolean removeIf(Predicate<? super E> filter) {
        boolean rv;
        try { rv = super.removeIf(filter); }
        finally { reindex(); }
        return rv;
    }

    @Override
    public void replaceAll(final UnaryOperator<E> operator) {
        indexMap.clear();
        try {
            int duplicates = 0;
            for (int i = 0; i < size(); i++) {
                E newval = requireNonNull(operator.apply(this.get(i)));
                if(indexMap.putIfAbsent(newval, i-duplicates) == null) {
                    super.set(i-duplicates, newval);
                } else {
                    duplicates++;
                }
            }
            removeRange(size()-duplicates, size());
        } catch (Exception ex) {
            // If there's an exception the indexMap will be inconsistent
            reindex();
            throw ex;
        }

    }

    @Override
    public void sort(Comparator<? super E> c) {
        try { super.sort(c); }
        finally { reindex(); }
    }
}

TSQL select into Temp table from dynamic sql

declare @sql varchar(100);

declare @tablename as varchar(100);

select @tablename = 'your_table_name';

create table #tmp 
    (col1 int, col2 int, col3 int);

set @sql = 'select aa, bb, cc from ' + @tablename;

insert into #tmp(col1, col2, col3) exec( @sql );

select * from #tmp;

htaccess remove index.php from url

Assuming the existent url is

http://example.com/index.php/foo/bar

and we want to convert it into

 http://example.com/foo/bar

You can use the following rule :

RewriteEngine on
#1) redirect the client from "/index.php/foo/bar" to "/foo/bar"
RewriteCond %{THE_REQUEST} /index\.php/(.+)\sHTTP [NC]
RewriteRule ^ /%1 [NE,L,R]
#2)internally map "/foo/bar" to "/index.php/foo/bar"
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.+)$ /index.php/$1 [L]

In the spep #1 we first match against the request string and capture everything after the /index.php/ and the captured value is saved in %1 var. We then send the browser to a new url. The #2 processes the request internally. When the browser arrives at /foo/bar , #2rule rewrites the new url to the orignal location.

how to get the ipaddress of a virtual box running on local machine

Login to virtual machine use below command to check ip address. (anyone will work)

  1. ifconfig
  2. ip addr show

If you used NAT for your virtual machine settings(your machine ip will be 10.0.2.15), then you have to use port forwarding to connect to machine. IP address will be 127.0.0.1

If you used bridged networking/Host only networking, then you will have separate Ip address. Use that IP address to connect virtual machine

Initializing a static std::map<int, int> in C++

You can try:

std::map <int, int> mymap = 
{
        std::pair <int, int> (1, 1),
        std::pair <int, int> (2, 2),
        std::pair <int, int> (2, 2)
};

Easy way to convert a unicode list to a list containing python strings?

You can do this by using json and ast modules as follows

>>> import json, ast
>>>
>>> EmployeeList =  [u'1001', u'Karick', u'14-12-2020', u'1$']
>>>
>>> result_list = ast.literal_eval(json.dumps(EmployeeList))
>>> result_list
['1001', 'Karick', '14-12-2020', '1$']

Android sqlite how to check if a record exists

I have tried all methods mentioned in this page, but only below method worked well for me.

Cursor c=db.rawQuery("SELECT * FROM user WHERE idno='"+txtID.getText()+"'", null);
if(c.moveToFirst())
{
 showMessage("Error", "Record exist");
}
else
{
 // Inserting record
}

What does this format means T00:00:00.000Z?

i suggest you use moment.js for this. In moment.js you can:

var localTime = moment().format('YYYY-MM-DD'); // store localTime
var proposedDate = localTime + "T00:00:00.000Z";

now that you have the right format for a time, parse it if it's valid:

var isValidDate = moment(proposedDate).isValid();
// returns true if valid and false if it is not.

and to get time parts you can do something like:

var momentDate = moment(proposedDate)
var hour = momentDate.hours();
var minutes = momentDate.minutes();
var seconds = momentDate.seconds();

// or you can use `.format`:
console.log(momentDate.format("YYYY-MM-DD hh:mm:ss A Z"));

More info about momentjs http://momentjs.com/

How can one use multi threading in PHP applications

pcntl_fork won't work in a web server environment if it has safe mode turned on. In this case, it will only work in the CLI version of PHP.

Is there a good jQuery Drag-and-drop file upload plugin?

How about the latest version of jQuery Fileuploader: http://pixelcone.com/fileuploader/

Its a powerful file upload plugin, very easy to setup compared to other plugin, and its now support html5 api.

A circular reference was detected while serializing an object of type 'SubSonic.Schema .DatabaseColumn'.

I had the same problem and solved by using Newtonsoft.Json;

var list = JsonConvert.SerializeObject(model,
    Formatting.None,
    new JsonSerializerSettings() {
        ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
});

return Content(list, "application/json");

SQL alias for SELECT statement

Yes, but you can select only one column in your subselect

SELECT (SELECT id FROM bla) AS my_select FROM bla2

Links in <select> dropdown options

Maybe this will help:

<select onchange="location = this.value;">
 <option value="home.html">Home</option>
 <option value="contact.html">Contact</option>
 <option value="about.html">About</option>
</select>

How do you find the current user in a Windows environment?

%USERNAME% is the correct answer in batch and other in Windows environments.

Another option is to use %USERPROFILE% to get the user's path, like C:\Users\username.

The right way of setting <a href=""> when it's a local file

Organize your files in hierarchical directories and then just use relative paths.

Demo:

HTML (index.html)

<a href='inner/file.html'>link</a>

Directory structure:

base/
base/index.html
base/inner/file.html
....

Writing a new line to file in PHP (line feed)

Use PHP_EOL which outputs \r\n or \n depending on the OS.

How to execute a java .class from the command line

If you have in your java source

package mypackage;

and your class is hello.java with

public class hello {

and in that hello.java you have

 public static void main(String[] args) {

Then (after compilation) changeDir (cd) to the directory where your hello.class is. Then

java -cp . mypackage.hello

Mind the current directory and the package name before the class name. It works for my on linux mint and i hope on the other os's also

Thanks Stack overflow for a wealth of info.

Entitlements file do not match those specified in your provisioning profile.(0xE8008016)

This happened to me when I was trying to build an App-store ipa exported file on my device, I had to export ad-hoc instead.

How to access SOAP services from iPhone

Have a look at here this link and their roadmap. They have RO|C on the way, and that can connect to their web services, which probably includes SOAP (I use the VCL version which definitely includes it).

Using Image control in WPF to display System.Drawing.Bitmap

It's easy for disk file, but harder for Bitmap in memory.

System.Drawing.Bitmap bmp;
Image image;
...
MemoryStream ms = new MemoryStream();
bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
ms.Position = 0;
BitmapImage bi = new BitmapImage();
bi.BeginInit();
bi.StreamSource = ms;
bi.EndInit();

image.Source = bi;

Stealed here

How to add column if not exists on PostgreSQL?

Simply check if the query returned a column_name.

If not, execute something like this:

ALTER TABLE x ADD COLUMN y int;

Where you put something useful for 'x' and 'y' and of course a suitable datatype where I used int.

How to manage exceptions thrown in filters in Spring?

You do not need to create a custom Filter for this. We solved this by creating custom exceptions that extend ServletException (which is thrown from the doFilter method, shown in the declaration). These are then caught and handled by our global error handler.

edit: grammar

Difference between using "chmod a+x" and "chmod 755"

Indeed there is.

chmod a+x is relative to the current state and just sets the x flag. So a 640 file becomes 751 (or 750?), a 644 file becomes 755.

chmod 755, however, sets the mask as written: rwxr-xr-x, no matter how it was before. It is equivalent to chmod u=rwx,go=rx.

HTML image bottom alignment inside DIV container

Set the parent div as position:relative and the inner element to position:absolute; bottom:0

Boto3 Error: botocore.exceptions.NoCredentialsError: Unable to locate credentials

I had the same issue and found out that the format of my ~/.aws/credentials file was wrong.

It worked with a file containing:

[default]
aws_access_key_id=XXXXXXXXXXXXXX
aws_secret_access_key=YYYYYYYYYYYYYYYYYYYYYYYYYYY

Note that the profile name must be "[default]". Some official documentation make reference to a profile named "[credentials]", which did not work for me.

PHP Include for HTML?

You don't need to be echoing the info within the php file. A php include will automatically include any HTML within that file.

Make sure you're actually using a index file with a .php extension, .html won't work with php includes. (Unless you're telling your server to treat .html files otherwise)

Make sure your paths are correctly set up. From your description, the way you've set it up your header.php/navbar.php/image.php files should be in your root directory. So your root directory should look like this:

index.php
navbar.php
image.php
header.php

Otherwise if those PHP files are in a folder called /includes/, it should look like so:

<?php include ('includes/headings.php'); ?>

Python json.loads shows ValueError: Extra data

One-liner for your problem:

data = [json.loads(line) for line in open('tweets.json', 'r')]

use Lodash to sort array of object by value

This method orderBy does not change the input array, you have to assign the result to your array :

var chars = this.state.characters;

chars = _.orderBy(chars, ['name'],['asc']); // Use Lodash to sort array by 'name'

 this.setState({characters: chars})

Regex empty string or email

matching empty string or email

(^$|^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.(?:[a-zA-Z]{2}|com|org|net|edu|gov|mil|biz|info|mobi|name|aero|asia|jobs|museum)$)

matching empty string or email but also matching any amount of whitespace

(^\s*$|^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.(?:[a-zA-Z]{2}|com|org|net|edu|gov|mil|biz|info|mobi|name|aero|asia|jobs|museum)$)

see more about the email matching regex itself:

http://www.regular-expressions.info/email.html

At runtime, find all classes in a Java application that extend a base class

Thanks all who answered this question.

It seems this is indeed a tough nut to crack. I ended up giving up and creating a static array and getter in my baseclass.

public abstract class Animal{
    private static Animal[] animals= null;
    public static Animal[] getAnimals(){
        if (animals==null){
            animals = new Animal[]{
                new Dog(),
                new Cat(),
                new Lion()
            };
        }
        return animals;
    }
}

It seems that Java just isn't set up for self-discoverability the way C# is. I suppose the problem is that since a Java app is just a collection of .class files out in a directory / jar file somewhere, the runtime doesn't know about a class until it's referenced. At that time the loader loads it -- what I'm trying to do is discover it before I reference it which is not possible without going out to the file system and looking.

I always like code that can discover itself instead of me having to tell it about itself, but alas this works too.

Thanks again!

Align Div at bottom on main Div

Please try this:

#b {
display: -webkit-inline-flex;
display: -moz-inline-flex;
display: inline-flex;

-webkit-flex-flow: row nowrap;
-moz-flex-flow: row nowrap;
flex-flow: row nowrap;

-webkit-align-items: flex-end;
-moz-align-items: flex-end;
align-items: flex-end;}

Here's a JSFiddle demo: http://jsfiddle.net/rudiedirkx/7FGKN/.

How do I change selected value of select2 dropdown with JqGrid?

For V4 Select2 if you want to change both the value of the select2 and the text representation of the drop down.

var intValueOfFruit = 1;
var selectOption = new Option("Fruit", intValueOfFruit, true, true);
$('#select').append(selectOption).trigger('change');

This will set not only the value behind the scenes but also the text display for the select2.

Pulled from https://select2.github.io/announcements-4.0.html#removed-methods

Calling a java method from c++ in Android

Solution posted by Denys S. in the question post:

I quite messed it up with c to c++ conversion (basically env variable stuff), but I got it working with the following code for C++:

#include <string.h>
#include <stdio.h>
#include <jni.h>

jstring Java_the_package_MainActivity_getJniString( JNIEnv* env, jobject obj){

    jstring jstr = (*env)->NewStringUTF(env, "This comes from jni.");
    jclass clazz = (*env)->FindClass(env, "com/inceptix/android/t3d/MainActivity");
    jmethodID messageMe = (*env)->GetMethodID(env, clazz, "messageMe", "(Ljava/lang/String;)Ljava/lang/String;");
    jobject result = (*env)->CallObjectMethod(env, obj, messageMe, jstr);

    const char* str = (*env)->GetStringUTFChars(env,(jstring) result, NULL); // should be released but what a heck, it's a tutorial :)
    printf("%s\n", str);

    return (*env)->NewStringUTF(env, str);
}

And next code for java methods:

    public class MainActivity extends Activity {
    private static String LIB_NAME = "thelib";

    static {
        System.loadLibrary(LIB_NAME);
    }

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        TextView tv = (TextView) findViewById(R.id.textview);
        tv.setText(this.getJniString());
    }

    // please, let me live even though I used this dark programming technique
    public String messageMe(String text) {
        System.out.println(text);
        return text;
    }

    public native String getJniString();
}

How to deal with bad_alloc in C++?

You can catch it like any other exception:

try {
  foo();
}
catch (const std::bad_alloc&) {
  return -1;
}

Quite what you can usefully do from this point is up to you, but it's definitely feasible technically.



In general you cannot, and should not try, to respond to this error. bad_alloc indicates that a resource cannot be allocated because not enough memory is available. In most scenarios your program cannot hope to cope with that, and terminating soon is the only meaningful behaviour.

Worse, modern operating systems often over-allocate: on such systems, malloc and new can return a valid pointer even if there is not enough free memory left – std::bad_alloc will never be thrown, or is at least not a reliable sign of memory exhaustion. Instead, attempts to access the allocated memory will then result in a segmentation fault, which is not catchable (you can handle the segmentation fault signal, but you cannot resume the program afterwards).

The only thing you could do when catching std::bad_alloc is to perhaps log the error, and try to ensure a safe program termination by freeing outstanding resources (but this is done automatically in the normal course of stack unwinding after the error gets thrown if the program uses RAII appropriately).

In certain cases, the program may attempt to free some memory and try again, or use secondary memory (= disk) instead of RAM but these opportunities only exist in very specific scenarios with strict conditions:

  1. The application must ensure that it runs on a system that does not overcommit memory, i.e. it signals failure upon allocation rather than later.
  2. The application must be able to free memory immediately, without any further accidental allocations in the meantime.

It’s exceedingly rare that applications have control over point 1 — userspace applications never do, it’s a system-wide setting that requires root permissions to change.1

OK, so let’s assume you’ve fixed point 1. What you can now do is for instance use a LRU cache for some of your data (probably some particularly large business objects that can be regenerated or reloaded on demand). Next, you need to put the actual logic that may fail into a function that supports retry — in other words, if it gets aborted, you can just relaunch it:

lru_cache<widget> widget_cache;

double perform_operation(int widget_id) {
    std::optional<widget> maybe_widget = widget_cache.find_by_id(widget_id);
    if (not maybe_widget) {
        maybe_widget = widget_cache.store(widget_id, load_widget_from_disk(widget_id));
    }
    return maybe_widget->frobnicate();
}

…

for (int num_attempts = 0; num_attempts < MAX_NUM_ATTEMPTS; ++num_attempts) {
    try {
        return perform_operation(widget_id);
    } catch (std::bad_alloc const&) {
        if (widget_cache.empty()) throw; // memory error elsewhere.
        widget_cache.remove_oldest();
    }
}

// Handle too many failed attempts here.

But even here, using std::set_new_handler instead of handling std::bad_alloc provides the same benefit and would be much simpler.


1 If you’re creating an application that does control point 1, and you’re reading this answer, please shoot me an email, I’m genuinely curious about your circumstances.


What is the C++ Standard specified behavior of new in c++?

The usual notion is that if new operator cannot allocate dynamic memory of the requested size, then it should throw an exception of type std::bad_alloc.
However, something more happens even before a bad_alloc exception is thrown:

C++03 Section 3.7.4.1.3: says

An allocation function that fails to allocate storage can invoke the currently installed new_handler(18.4.2.2), if any. [Note: A program-supplied allocation function can obtain the address of the currently installed new_handler using the set_new_handler function (18.4.2.3).] If an allocation function declared with an empty exception-specification (15.4), throw(), fails to allocate storage, it shall return a null pointer. Any other allocation function that fails to allocate storage shall only indicate failure by throw-ing an exception of class std::bad_alloc (18.4.2.1) or a class derived from std::bad_alloc.

Consider the following code sample:

#include <iostream>
#include <cstdlib>

// function to call if operator new can't allocate enough memory or error arises
void outOfMemHandler()
{
    std::cerr << "Unable to satisfy request for memory\n";

    std::abort();
}

int main()
{
    //set the new_handler
    std::set_new_handler(outOfMemHandler);

    //Request huge memory size, that will cause ::operator new to fail
    int *pBigDataArray = new int[100000000L];

    return 0;
}

In the above example, operator new (most likely) will be unable to allocate space for 100,000,000 integers, and the function outOfMemHandler() will be called, and the program will abort after issuing an error message.

As seen here the default behavior of new operator when unable to fulfill a memory request, is to call the new-handler function repeatedly until it can find enough memory or there is no more new handlers. In the above example, unless we call std::abort(), outOfMemHandler() would be called repeatedly. Therefore, the handler should either ensure that the next allocation succeeds, or register another handler, or register no handler, or not return (i.e. terminate the program). If there is no new handler and the allocation fails, the operator will throw an exception.

What is the new_handler and set_new_handler?

new_handler is a typedef for a pointer to a function that takes and returns nothing, and set_new_handler is a function that takes and returns a new_handler.

Something like:

typedef void (*new_handler)();
new_handler set_new_handler(new_handler p) throw();

set_new_handler's parameter is a pointer to the function operator new should call if it can't allocate the requested memory. Its return value is a pointer to the previously registered handler function, or null if there was no previous handler.

How to handle out of memory conditions in C++?

Given the behavior of newa well designed user program should handle out of memory conditions by providing a proper new_handlerwhich does one of the following:

Make more memory available: This may allow the next memory allocation attempt inside operator new's loop to succeed. One way to implement this is to allocate a large block of memory at program start-up, then release it for use in the program the first time the new-handler is invoked.

Install a different new-handler: If the current new-handler can't make any more memory available, and of there is another new-handler that can, then the current new-handler can install the other new-handler in its place (by calling set_new_handler). The next time operator new calls the new-handler function, it will get the one most recently installed.

(A variation on this theme is for a new-handler to modify its own behavior, so the next time it's invoked, it does something different. One way to achieve this is to have the new-handler modify static, namespace-specific, or global data that affects the new-handler's behavior.)

Uninstall the new-handler: This is done by passing a null pointer to set_new_handler. With no new-handler installed, operator new will throw an exception ((convertible to) std::bad_alloc) when memory allocation is unsuccessful.

Throw an exception convertible to std::bad_alloc. Such exceptions are not be caught by operator new, but will propagate to the site originating the request for memory.

Not return: By calling abort or exit.

How to refresh or show immediately in datagridview after inserting?

Use LoadPatientRecords() after a successful insertion.

Try the below code

private void btnSubmit_Click(object sender, EventArgs e)
{
        if (btnSubmit.Text == "Clear")
        {
            btnSubmit.Text = "Submit";

            txtpFirstName.Focus();
        }
        else
        {
           btnSubmit.Text = "Clear";
           int result = AddPatientRecord();
           if (result > 0)
           {
               MessageBox.Show("Insert Successful");

               LoadPatientRecords();
           }
           else
               MessageBox.Show("Insert Fail");
         }
}

Windows equivalent to UNIX pwd

It is cd for "current directory".

Difference between <context:annotation-config> and <context:component-scan>

<context:annotation-config>:

This tells Spring that I am going to use Annotated beans as spring bean and those would be wired through @Autowired annotation, instead of declaring in spring config xml file.

<context:component-scan base-package="com.test..."> :

This tells Spring container, where to start searching those annotated beans. Here spring will search all sub packages of the base package.

Detect if HTML5 Video element is playing

var video_switch  = 0;

function play() {

    var media = document.getElementById('video');

    if (video_switch == 0)
    {
        media.play();
        video_switch = 1;
    }
    else if (video_switch == 1)
    {
        media.pause();
        video_switch = 0;
    }
}

Tomcat: How to find out running tomcat version

The version of currently running Tomcat

If you set the environtment variable - %CATALINA_HOME%, then Windows :

>> cd %CATALINA_HOME%\bin
>> version

Alternatively,

java.exe -cp lib\catalina.jar org.apache.catalina.util.ServerInfo

MY SETTING --- Hope yours will be similar to as follows

%CATALINA_HOME% --- C:\Program Files\Tomcat\apache-tomcat-8.0.28

OUTPUT

Server version: Apache Tomcat/8.0.28 Server built: Oct 7 2015 18:25:21 UTC Server number: 8.0.28.0 OS Name: Windows 7 OS Version: 6.1 Architecture: amd64 JVM Version: 1.8.0_111-b14 JVM Vendor: Oracle Corporation

Tomcat Server Error - Port 8080 already in use

Open CMD or Powershell in Administrator mode, then run...

netstat -ab

The output should be able to point you in the direction of which process is holding port 8080. Entry may likely be 127.0.0.1:8080 You may still have a running instance of Tomcat at port 8080.

You can either use Stop-Process in PowerShell or taskKill in CMD to stop that process and should be able to execute the program at that point.

How to check if an email address is real or valid using PHP

I have been searching for this same answer all morning and have pretty much found out that it's probably impossible to verify if every email address you ever need to check actually exists at the time you need to verify it. So as a work around, I kind of created a simple PHP script to verify that the email address is formatted correct and it also verifies that the domain name used is correct as well.

GitHub here https://github.com/DukeOfMarshall/PHP---JSON-Email-Verification/tree/master

<?php

# What to do if the class is being called directly and not being included in a script     via PHP
# This allows the class/script to be called via other methods like JavaScript

if(basename(__FILE__) == basename($_SERVER["SCRIPT_FILENAME"])){
$return_array = array();

if($_GET['address_to_verify'] == '' || !isset($_GET['address_to_verify'])){
    $return_array['error']              = 1;
    $return_array['message']            = 'No email address was submitted for verification';
    $return_array['domain_verified']    = 0;
    $return_array['format_verified']    = 0;
}else{
    $verify = new EmailVerify();

    if($verify->verify_formatting($_GET['address_to_verify'])){
        $return_array['format_verified']    = 1;

        if($verify->verify_domain($_GET['address_to_verify'])){
            $return_array['error']              = 0;
            $return_array['domain_verified']    = 1;
            $return_array['message']            = 'Formatting and domain have been verified';
        }else{
            $return_array['error']              = 1;
            $return_array['domain_verified']    = 0;
            $return_array['message']            = 'Formatting was verified, but verification of the domain has failed';
        }
    }else{
        $return_array['error']              = 1;
        $return_array['domain_verified']    = 0;
        $return_array['format_verified']    = 0;
        $return_array['message']            = 'Email was not formatted correctly';
    }
}

echo json_encode($return_array);

exit();
}

class EmailVerify {
public function __construct(){

}

public function verify_domain($address_to_verify){
    // an optional sender  
    $record = 'MX';
    list($user, $domain) = explode('@', $address_to_verify);
    return checkdnsrr($domain, $record);
}

public function verify_formatting($address_to_verify){
    if(strstr($address_to_verify, "@") == FALSE){
        return false;
    }else{
        list($user, $domain) = explode('@', $address_to_verify);

        if(strstr($domain, '.') == FALSE){
            return false;
        }else{
            return true;
        }
    }
    }
}
?>

Can constructors throw exceptions in Java?

Yes, it can throw an exception and you can declare that in the signature of the constructor too as shown in the example below:

public class ConstructorTest
{
    public ConstructorTest() throws InterruptedException
    {
        System.out.println("Preparing object....");
        Thread.sleep(1000);
        System.out.println("Object ready");
    }

    public static void main(String ... args)
    {
        try
        {
            ConstructorTest test = new ConstructorTest();
        }
        catch (InterruptedException e)
        {
            System.out.println("Got interrupted...");
        }
    }
}

Where can I get a virtual machine online?

Try this:

http://aws.amazon.com/free/

one year free. I do use this for a while.

How do you count the elements of an array in java

What do you mean by "the count"? The number of elements with a non-zero value? You'd just have to count them.

There's no distinction between that array and one which has explicitly been set with zero values. For example, these arrays are indistinguishable:

int[] x = { 0, 0, 0 };
int[] y = new int[3];

Arrays in Java always have a fixed size - accessed via the length field. There's no concept of "the amount of the array currently in use".

Should I use "camel case" or underscores in python?

Function names should be lowercase, with words separated by underscores as necessary to improve readability. mixedCase is allowed only in contexts where that's already the prevailing style

Check out its already been answered, click here

How to parse JSON in Java

There are many JSON libraries available in Java.

The most notorious ones are: Jackson, GSON, Genson, FastJson and org.json.

There are typically three things one should look at for choosing any library:

  1. Performance
  2. Ease of use (code is simple to write and legible) - that goes with features.
  3. For mobile apps: dependency/jar size

Specifically for JSON libraries (and any serialization/deserialization libs), databinding is also usually of interest as it removes the need of writing boiler-plate code to pack/unpack the data.

For 1, see this benchmark: https://github.com/fabienrenaud/java-json-benchmark I did using JMH which compares (jackson, gson, genson, fastjson, org.json, jsonp) performance of serializers and deserializers using stream and databind APIs. For 2, you can find numerous examples on the Internet. The benchmark above can also be used as a source of examples...

Quick takeaway of the benchmark: Jackson performs 5 to 6 times better than org.json and more than twice better than GSON.

For your particular example, the following code decodes your json with jackson:

public class MyObj {

    private PageInfo pageInfo;
    private List<Post> posts;

    static final class PageInfo {
        private String pageName;
        private String pagePic;
    }

    static final class Post {
        private String post_id;
        @JsonProperty("actor_id");
        private String actorId;
        @JsonProperty("picOfPersonWhoPosted")
        private String pictureOfPoster;
        @JsonProperty("nameOfPersonWhoPosted")
        private String nameOfPoster;
        private String likesCount;
        private List<String> comments;
        private String timeOfPost;
    }

    private static final ObjectMapper JACKSON = new ObjectMapper();
    public static void main(String[] args) throws IOException {
        MyObj o = JACKSON.readValue(args[0], MyObj.class); // assumes args[0] contains your json payload provided in your question.
    }
}

Let me know if you have any questions.

Using StringWriter for XML Serialization

When serialising an XML document to a .NET string, the encoding must be set to UTF-16. Strings are stored as UTF-16 internally, so this is the only encoding that makes sense. If you want to store data in a different encoding, you use a byte array instead.

SQL Server works on a similar principle; any string passed into an xml column must be encoded as UTF-16. SQL Server will reject any string where the XML declaration does not specify UTF-16. If the XML declaration is not present, then the XML standard requires that it default to UTF-8, so SQL Server will reject that as well.

Bearing this in mind, here are some utility methods for doing the conversion.

public static string Serialize<T>(T value) {

    if(value == null) {
        return null;
    }

    XmlSerializer serializer = new XmlSerializer(typeof(T));

    XmlWriterSettings settings = new XmlWriterSettings()
    {
        Encoding = new UnicodeEncoding(false, false), // no BOM in a .NET string
        Indent = false,
        OmitXmlDeclaration = false
    };

    using(StringWriter textWriter = new StringWriter()) {
        using(XmlWriter xmlWriter = XmlWriter.Create(textWriter, settings)) {
            serializer.Serialize(xmlWriter, value);
        }
        return textWriter.ToString();
    }
}

public static T Deserialize<T>(string xml) {

    if(string.IsNullOrEmpty(xml)) {
        return default(T);
    }

    XmlSerializer serializer = new XmlSerializer(typeof(T));

    XmlReaderSettings settings = new XmlReaderSettings();
    // No settings need modifying here

    using(StringReader textReader = new StringReader(xml)) {
        using(XmlReader xmlReader = XmlReader.Create(textReader, settings)) {
            return (T) serializer.Deserialize(xmlReader);
        }
    }
}

Do HttpClient and HttpClientHandler have to be disposed between requests?

If you want to dispose of HttpClient, you can if you set it up as a resource pool. And at the end of your application, you dispose your resource pool.

Code:

// Notice that IDisposable is not implemented here!
public interface HttpClientHandle
{
    HttpRequestHeaders DefaultRequestHeaders { get; }
    Uri BaseAddress { get; set; }
    // ...
    // All the other methods from peeking at HttpClient
}

public class HttpClientHander : HttpClient, HttpClientHandle, IDisposable
{
    public static ConditionalWeakTable<Uri, HttpClientHander> _httpClientsPool;
    public static HashSet<Uri> _uris;

    static HttpClientHander()
    {
        _httpClientsPool = new ConditionalWeakTable<Uri, HttpClientHander>();
        _uris = new HashSet<Uri>();
        SetupGlobalPoolFinalizer();
    }

    private DateTime _delayFinalization = DateTime.MinValue;
    private bool _isDisposed = false;

    public static HttpClientHandle GetHttpClientHandle(Uri baseUrl)
    {
        HttpClientHander httpClient = _httpClientsPool.GetOrCreateValue(baseUrl);
        _uris.Add(baseUrl);
        httpClient._delayFinalization = DateTime.MinValue;
        httpClient.BaseAddress = baseUrl;

        return httpClient;
    }

    void IDisposable.Dispose()
    {
        _isDisposed = true;
        GC.SuppressFinalize(this);

        base.Dispose();
    }

    ~HttpClientHander()
    {
        if (_delayFinalization == DateTime.MinValue)
            _delayFinalization = DateTime.UtcNow;
        if (DateTime.UtcNow.Subtract(_delayFinalization) < base.Timeout)
            GC.ReRegisterForFinalize(this);
    }

    private static void SetupGlobalPoolFinalizer()
    {
        AppDomain.CurrentDomain.ProcessExit +=
            (sender, eventArgs) => { FinalizeGlobalPool(); };
    }

    private static void FinalizeGlobalPool()
    {
        foreach (var key in _uris)
        {
            HttpClientHander value = null;
            if (_httpClientsPool.TryGetValue(key, out value))
                try { value.Dispose(); } catch { }
        }

        _uris.Clear();
        _httpClientsPool = null;
    }
}

var handler = HttpClientHander.GetHttpClientHandle(new Uri("base url")).

  • HttpClient, as an interface, can't call Dispose().
  • Dispose() will be called in a delayed fashion by the Garbage Collector. Or when the program cleans up the object through its destructor.
  • Uses Weak References + delayed cleanup logic so it remains in use so long as it is being reused frequently.
  • It only allocates a new HttpClient for each base URL passed to it. Reasons explained by Ohad Schneider answer below. Bad behavior when changing base url.
  • HttpClientHandle allows for Mocking in tests

Mismatched anonymous define() module

The existing answers explain the problem well but if including your script files using or before requireJS is not an easy option due to legacy code a slightly hacky workaround is to remove require from the window scope before your script tag and then reinstate it afterwords. In our project this is wrapped behind a server-side function call but effectively the browser sees the following:

    <script>
        window.__define = window.define;
        window.__require = window.require;
        window.define = undefined;
        window.require = undefined;
    </script>
    <script src="your-script-file.js"></script>        
    <script>
        window.define = window.__define;
        window.require = window.__require;
        window.__define = undefined;
        window.__require = undefined;
    </script>

Not the neatest but seems to work and has saved a lot of refractoring.

How can I make a DateTimePicker display an empty string?

Just set the property as follows:

When the user press "clear button" or "delete key" do

dtpData.CustomFormat = " "  'An empty SPACE
dtpData.Format = DateTimePickerFormat.Custom

On DateTimePicker1_ValueChanged event do

dtpData.CustomFormat = "dd/MM/yyyy hh:mm:ss"

Deactivate or remove the scrollbar on HTML

put this code in your html header:

<style type="text/css">
html {
        overflow: auto;
}
</style>

Asynchronous method call in Python?

You can use the multiprocessing module added in Python 2.6. You can use pools of processes and then get results asynchronously with:

apply_async(func[, args[, kwds[, callback]]])

E.g.:

from multiprocessing import Pool

def f(x):
    return x*x

if __name__ == '__main__':
    pool = Pool(processes=1)              # Start a worker processes.
    result = pool.apply_async(f, [10], callback) # Evaluate "f(10)" asynchronously calling callback when finished.

This is only one alternative. This module provides lots of facilities to achieve what you want. Also it will be really easy to make a decorator from this.

Can we have multiple "WITH AS" in single sql - Oracle SQL

Aditya or others, can you join or match up t2 with t1 in your example, i.e. translated to my code,

with t1 as (select * from AA where FIRSTNAME like 'Kermit'),
     t2 as (select * from BB B join t1 on t1.FIELD1 = B.FIELD1)

I am not clear whether only WHERE is supported for joining, or what joining approach is supported within the 2nd WITH entity. Some of the examples have the WHERE A=B down in the body of the select "below" the WITH clauses.

The error I'm getting following these WITH declarations is the identifiers (field names) in B are not recognized, down in the body of the rest of the SQL. So the WITH syntax seems to run OK, but cannot access the results from t2.

How can I run NUnit tests in Visual Studio 2017?

You need to install NUnitTestAdapter. The latest version of NUnit is 3.x.y (3.6.1) and you should install NUnit3TestAdapter along with NUnit 3.x.y

To install NUnit3TestAdapter in Visual Studio 2017, follow the steps below:

  1. Right click on menu Project ? click "Manage NuGet Packages..." from the context menu
  2. Go to the Browse tab and search for NUnit
  3. Select NUnit3TestAdapter ? click Install at the right side ? click OK from the Preview pop up

Enter image description here

How to find Port number of IP address?

Quite an old question, but might be helpful to somebody in need.

If you know the url, 1. open the chrome browser, 2. open developer tools in chrome , 3. Put the url in search bar and hit enter 4. look in network tab, you will see the ip and port both

"string could not resolved" error in Eclipse for C++ (Eclipse can't resolve standard library)

You need to ensure your environment is properly setup in Eclipse so it knows the paths to your includes. Otherwise, it underlines them as not found.

How do I filter date range in DataTables?

Here is my solution, there is no way to use momemt.js.Here is DataTable with Two DatePickers for DateRange (To and From) Filter.

$.fn.dataTable.ext.search.push(
  function (settings, data, dataIndex) {
    var min = $('#min').datepicker("getDate");
    var max = $('#max').datepicker("getDate");
    var startDate = new Date(data[4]);
    if (min == null && max == null) { return true; }
    if (min == null && startDate <= max) { return true; }
    if (max == null && startDate >= min) { return true; }
    if (startDate <= max && startDate >= min) { return true; }
    return false;
  }
);
  

    

Windows Application has stopped working :: Event Name CLR20r3

Some times this problem arise when Application is build in one PC and try to run another PC. And also build the application with Visual Studio 2010.I have the following problem

Problem Description
    Stop Working
Problem Signature
  Problem Event Name:   CLR20r3
  Problem Signature 01: diagnosticcentermngr.exe
  Problem Signature 02: 1.0.0.0
  Problem Signature 03: 4f8c1772
  Problem Signature 04: System.Drawing
  Problem Signature 05: 2.0.0.0
  Problem Signature 06: 4a275e83
  Problem Signature 07: 7af
  Problem Signature 08: 6c
  Problem Signature 09: System.ArgumentException
  OS Version:   6.1.7600.2.0.0.256.1
  Locale ID:    1033

Read our privacy statement online:
  http://go.microsoft.com/fwlink/?linkid=104288&clcid=0x0409

If the online privacy statement is not available, please read our privacy statement offline:
  C:\Windows\system32\en-US\erofflps.txt

Dont worry, Please check out following link and install .net framework 4.Although my application .net properties was .net framework 2.

http://www.microsoft.com/download/en/details.aspx?id=17718

restart your PC and try again.

RegEx for matching UK Postcodes

According to this Wikipedia table

enter image description here

This pattern cover all the cases

(?:[A-Za-z]\d ?\d[A-Za-z]{2})|(?:[A-Za-z][A-Za-z\d]\d ?\d[A-Za-z]{2})|(?:[A-Za-z]{2}\d{2} ?\d[A-Za-z]{2})|(?:[A-Za-z]\d[A-Za-z] ?\d[A-Za-z]{2})|(?:[A-Za-z]{2}\d[A-Za-z] ?\d[A-Za-z]{2})

When using it on Android\Java use \\d

TypeError: list indices must be integers or slices, not str

I had same error and the mistake was that I had added list and dictionary into the same list (object) and when I used to iterate over the list of dictionaries and use to hit a list (type) object then I used to get this error.

Its was a code error and made sure that I only added dictionary objects to that list and list typed object into the list, this solved my issue as well.

How to prevent favicon.ico requests?

Personally I used this in my HTML head tag:

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

How to do scanf for single char in C

Use string instead of char like

char c[10];
scanf ("%s", c);

I belive it works nice.

How to pass a parameter like title, summary and image in a Facebook sharer URL

I've used the below before, and it has worked. It isn't very pretty, but you can alter it to suit your needs.

The following JavaScript function grabs the location.href & document.title for the sharer, and you can ultimately change these.

function fbs_click() {
        u=location.href;
        t=document.title;
window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent(u)+'&t='+encodeURIComponent(t),
                'sharer',
                'toolbar=0,status=0,width=626,height=436');

            return false;
        }

Usage:

<a rel="nofollow" href="http://www.facebook.com/share.php?u=<;url>" onclick="return fbs_click()" target="_blank">
    Share on Facebook
</a>

It looks like this is what you could possibly be looking for: Facebook sharer title / desc....

Adding a Scrollable JTextArea (Java)

It doesn't work because you didn't attach the ScrollPane to the JFrame.

Also, you don't need 2 JScrollPanes:

JFrame frame = new JFrame ("Test");
JTextArea textArea = new JTextArea ("Test");

JScrollPane scroll = new JScrollPane (textArea, 
   JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);

frame.add(scroll);
frame.setVisible (true);

Using event.target with React components

First argument in update method is SyntheticEvent object that contains common properties and methods to any event, it is not reference to React component where there is property props.

if you need pass argument to update method you can do it like this

onClick={ (e) => this.props.onClick(e, 'home', 'Home') }

and get these arguments inside update method

update(e, space, txt){
   console.log(e.target, space, txt);
}

Example


event.target gives you the native DOMNode, then you need to use the regular DOM APIs to access attributes. For instance getAttribute or dataset

<button 
  data-space="home" 
  className="home" 
  data-txt="Home" 
  onClick={ this.props.onClick } 
/> 
  Button
</button>

onClick(e) {
   console.log(e.target.dataset.txt, e.target.dataset.space);
}

Example

Visual Studio Code: format is not using indent settings

If you came here from google because tab isnt indenting, this can also be because "Tab Moves Focus" is on. It is at the bottom right, and if you have a large enough monitor you may miss it despite it being highlighted.

enter image description here

Click the Green area or Ctrl + M to make it stop. I'm not sure it can be disabled entirely, then again I dont know why a code editor would want to mess with something like indenting.

How do I use a custom Serializer with Jackson?

Use @JsonValue:

public class User {
    int id;
    String name;

    @JsonValue
    public int getId() {
        return id;
    }
}

@JsonValue only works on methods so you must add the getId method. You should be able to skip your custom serializer altogether.

How to do ToString for a possibly null object?

string s = String.Concat(myObj);

would be the shortest way I guess and also have neglible performance overhead. Keep in mind though it wouldn't be quite clear for the reader of the code what the intention is.

copy from one database to another using oracle sql developer - connection failed

The copy command is a SQL*Plus command (not a SQL Developer command). If you have your tnsname entries setup for SID1 and SID2 (e.g. try a tnsping), you should be able to execute your command.

Another assumption is that table1 has the same columns as the message_table (and the columns have only the following data types: CHAR, DATE, LONG, NUMBER or VARCHAR2). Also, with an insert command, you would need to be concerned about primary keys (e.g. that you are not inserting duplicate records).

I tried a variation of your command as follows in SQL*Plus (with no errors):

copy from scott/tiger@db1 to scott/tiger@db2 create new_emp using select * from emp;

After I executed the above statement, I also truncate the new_emp table and executed this command:

copy from scott/tiger@db1 to scott/tiger@db2 insert new_emp using select * from emp;

With SQL Developer, you could do the following to perform a similar approach to copying objects:

  1. On the tool bar, select Tools>Database copy.

  2. Identify source and destination connections with the copy options you would like. enter image description here

  3. For object type, select table(s). enter image description here

  4. Specify the specific table(s) (e.g. table1). enter image description here

The copy command approach is old and its features are not being updated with the release of new data types. There are a number of more current approaches to this like Oracle's data pump (even for tables).

Importing xsd into wsdl

import vs. include

The primary purpose of an import is to import a namespace. A more common use of the XSD import statement is to import a namespace which appears in another file. You might be gathering the namespace information from the file, but don't forget that it's the namespace that you're importing, not the file (don't confuse an import statement with an include statement).

Another area of confusion is how to specify the location or path of the included .xsd file: An XSD import statement has an optional attribute named schemaLocation but it is not necessary if the namespace of the import statement is at the same location (in the same file) as the import statement itself.

When you do chose to use an external .xsd file for your WSDL, the schemaLocation attribute becomes necessary. Be very sure that the namespace you use in the import statement is the same as the targetNamespace of the schema you are importing. That is, all 3 occurrences must be identical:

WSDL:

xs:import namespace="urn:listing3" schemaLocation="listing3.xsd"/>

XSD:

<xsd:schema targetNamespace="urn:listing3"
            xmlns:xsd="http://www.w3.org/2001/XMLSchema"> 

Another approach to letting know the WSDL about the XSD is through Maven's pom.xml:

<plugin>
  <groupId>org.codehaus.mojo</groupId>
  <artifactId>xmlbeans-maven-plugin</artifactId>
  <executions>
    <execution>
      <id>generate-sources-xmlbeans</id>
      <phase>generate-sources</phase>
      <goals>
    <goal>xmlbeans</goal>
      </goals>
    </execution>
  </executions>
  <version>2.3.3</version>
  <inherited>true</inherited>
  <configuration>
    <schemaDirectory>${basedir}/src/main/xsd</schemaDirectory>
  </configuration>
</plugin>

You can read more on this in this great IBM article. It has typos such as xsd:import instead of xs:import but otherwise it's fine.

How to determine the longest increasing subsequence using dynamic programming?

checkout the code in java for longest increasing subsequence with the array elements

http://ideone.com/Nd2eba

/**
 **    Java Program to implement Longest Increasing Subsequence Algorithm
 **/

import java.util.Scanner;

/** Class  LongestIncreasingSubsequence **/
 class  LongestIncreasingSubsequence
{
    /** function lis **/
    public int[] lis(int[] X)
    {        
        int n = X.length - 1;
        int[] M = new int[n + 1];  
        int[] P = new int[n + 1]; 
        int L = 0;

        for (int i = 1; i < n + 1; i++)
        {
            int j = 0;

            /** Linear search applied here. Binary Search can be applied too.
                binary search for the largest positive j <= L such that 
                X[M[j]] < X[i] (or set j = 0 if no such value exists) **/

            for (int pos = L ; pos >= 1; pos--)
            {
                if (X[M[pos]] < X[i])
                {
                    j = pos;
                    break;
                }
            }            
            P[i] = M[j];
            if (j == L || X[i] < X[M[j + 1]])
            {
                M[j + 1] = i;
                L = Math.max(L,j + 1);
            }
        }

        /** backtrack **/

        int[] result = new int[L];
        int pos = M[L];
        for (int i = L - 1; i >= 0; i--)
        {
            result[i] = X[pos];
            pos = P[pos];
        }
        return result;             
    }

    /** Main Function **/
    public static void main(String[] args) 
    {    
        Scanner scan = new Scanner(System.in);
        System.out.println("Longest Increasing Subsequence Algorithm Test\n");

        System.out.println("Enter number of elements");
        int n = scan.nextInt();
        int[] arr = new int[n + 1];
        System.out.println("\nEnter "+ n +" elements");
        for (int i = 1; i <= n; i++)
            arr[i] = scan.nextInt();

        LongestIncreasingSubsequence obj = new LongestIncreasingSubsequence(); 
        int[] result = obj.lis(arr);       

        /** print result **/ 

        System.out.print("\nLongest Increasing Subsequence : ");
        for (int i = 0; i < result.length; i++)
            System.out.print(result[i] +" ");
        System.out.println();
    }
}

Could not locate Gemfile

Make sure you are in the project directory before running bundle install. For example, after running rails new myproject, you will want to cd myproject before running bundle install.

Create a Bitmap/Drawable from file path

you can't access your drawables via a path, so if you want a human readable interface with your drawables that you can build programatically.

declare a HashMap somewhere in your class:

private static HashMap<String, Integer> images = null;

//Then initialize it in your constructor:

public myClass() {
  if (images == null) {
    images = new HashMap<String, Integer>();
    images.put("Human1Arm", R.drawable.human_one_arm);
    // for all your images - don't worry, this is really fast and will only happen once
  }
}

Now for access -

String drawable = "wrench";
// fill in this value however you want, but in the end you want Human1Arm etc
// access is fast and easy:
Bitmap wrench = BitmapFactory.decodeResource(getResources(), images.get(drawable));
canvas.drawColor(Color .BLACK);
Log.d("OLOLOLO",Integer.toString(wrench.getHeight()));
canvas.drawBitmap(wrench, left, top, null);

How do I negate a condition in PowerShell?

Powershell also accept the C/C++/C* not operator

if ( !(Test-Path C:\Code) ){ write "it doesn't exist!" }

I use it often because I'm used to C*...
allows code compression/simplification...
I also find it more elegant...

Create normal zip file programmatically

.NET has a built functionality for compressing files in the System.IO.Compression namespace. Using this you do not have to take an extra library as a dependency. This functionality is available from .NET 2.0.

Here is the way to do the compressing from the MSDN page I linked:

    public static void Compress(FileInfo fi)
    {
        // Get the stream of the source file.
        using (FileStream inFile = fi.OpenRead())
        {
            // Prevent compressing hidden and already compressed files.
            if ((File.GetAttributes(fi.FullName) & FileAttributes.Hidden)
                    != FileAttributes.Hidden & fi.Extension != ".gz")
            {
                // Create the compressed file.
                using (FileStream outFile = File.Create(fi.FullName + ".gz"))
                {
                    using (GZipStream Compress = new GZipStream(outFile,
                            CompressionMode.Compress))
                    {
                        // Copy the source file into the compression stream.
                        byte[] buffer = new byte[4096];
                        int numRead;
                        while ((numRead = inFile.Read(buffer, 0, buffer.Length)) != 0)
                        {
                            Compress.Write(buffer, 0, numRead);
                        }
                        Console.WriteLine("Compressed {0} from {1} to {2} bytes.",
                            fi.Name, fi.Length.ToString(), outFile.Length.ToString());
                    }
                }
            }
        }

Gson library in Android Studio

Add following dependency or download Gson jar file

implementation 'com.google.code.gson:gson:2.8.6'

Follow github repo for documentation and more.

Plot logarithmic axes with matplotlib in python

First of all, it's not very tidy to mix pylab and pyplot code. What's more, pyplot style is preferred over using pylab.

Here is a slightly cleaned up code, using only pyplot functions:

from matplotlib import pyplot

a = [ pow(10,i) for i in range(10) ]

pyplot.subplot(2,1,1)
pyplot.plot(a, color='blue', lw=2)
pyplot.yscale('log')
pyplot.show()

The relevant function is pyplot.yscale(). If you use the object-oriented version, replace it by the method Axes.set_yscale(). Remember that you can also change the scale of X axis, using pyplot.xscale() (or Axes.set_xscale()).

Check my question What is the difference between ‘log’ and ‘symlog’? to see a few examples of the graph scales that matplotlib offers.

How to change the value of ${user} variable used in Eclipse templates

EGit Solution

One would expect creating or changing template variables on a project-, workspace-, or environment-basis is a standard Eclipse feature. Sadly, it is not. More so, given that Eclipse plugins can define new variables and templates, there should be plugins out there providing a solution. If they are, they must be hard to find. mmm-TemplateVariable, which is available in the Eclipse Marketplace, is a step in the right direction for Maven users, giving the ability to include version, artifactId, etc. in templates.

Fortunately, EGit, which is an Eclipse tool for Git, provides very flexible means for including many different variables in code templates. The only requirement is that your project uses Git. If you don’t use Git, but are serious about software development, now is the time to learn (Pro Git book). If you are forced to use a legacy version control system, try changing some minds.

Thanks to the efforts of harmsk, EGit 4.0 and above includes the ability to use Git configuration key values in templates. This allows setting template values based on repository settings (project), user settings (account), and/or global settings (workstation).

The following example shows how to set up Eclipse and Git for a multi-user development workstation and use a custom Git configuration key in lieu of ${user} to provide more flexibility. Although the example is based on a Windows 10 installation of Eclipse Mars and Git for Windows, the example is applicable to Linux and OSX running Eclipse and Git using their respective command line tools.

To avoid possible confusion between Git’s user.name configuration key and Java’s user.name system property, a custom Git configuration key – user.author – will be used to provide an author’s name and/or credentials.

Configuring Templates

The format of a Git template variable is as follows

${<name>:git_config(<key>)}

where <name> is any arbitrary variable name and <key> is the Git configuration key whose value should be used. Given that, changing the Comments?Types template to

/**
 * @author ${author:git_config(user.author)}
 *
 * ${tags}
 */

will now attempt to resolve the author’s name from Git’s user.author configuration key. Without any further configuration, any newly created comments will not include a name after @author, since none has been defined yet.

Configuring Git

From the command line

Git System Configuration - This configuration step makes changes to Git’s system-wide configuration applicable to all accounts on the workstation unless overridden by user or repository settings. Because system-wide configurations are part the underlying Git application (e.g. Git for Windows), changes will require Administrator privileges. Run Git Bash, cmd, or PowerShell as Administrator. The following command will set the system-wide author.

git config --system user.author “SET ME IN GLOBAL(USER) or REPOSITORY(LOCAL) SETTINGS”

The purpose of this “author” is to serve as a reminder that it should be set elsewhere. This is particularly useful when new user accounts are being used on the workstation.

To verify this setting, create an empty Java project that uses Git or open an existing Git-based project. Create a class and use Source?Generate Element Comment from the context menu, ALT-SHIFT-J, or start a JavaDoc comment. The resulting @author tag should be followed by the warning.

The remaining configuration changes can be performed without Administrator privileges.

Git Global(User) Configuration - Global, or user, configurations are those associated with a specific user and will override system-wide configurations. These settings apply to all Git-based projects unless overridden by repository settings. If the author name is different due to various project types such as for work, open source contributions, or personal, set the most frequently used here.

git config --global user.author “Mr. John Smith”

Having configured the global value, return to the test project used early and apply a class comment. The@author tag should now show the global setting.

Git Repository(Local) Configuration - Lastly, a repository or local configuration can be used to configure an author for a specific project. Unlike the previous configurations, a repository configuration must be done from within the repository. Using Git Bash, PowerShell, etc. navigate into the test project’s repository.

git config --local user.author “smithy”

Given this, new comments in the test project will use the locally defined author name. Other Git-based projects, will still use the global author name.

From Within Eclipse

The configuration changes above can also be set from within Eclipse through its Preferences: Team?Git-Configuration. Eclipse must be run as Administrator to change system-wide Git configurations.

In Sum

Although this example dealt specifically with the most common issue, that of changing ${user}, this approach can be used for more. However, caution should be exercised not to use Git-defined configuration keys, unless it is specifically intended.

Find location of a removable SD card

Is there an universal way to find the location of an external SD card?

By universal way, if you mean official way; yes there is one.

In API level 19 i.e. in Android version 4.4 Kitkat, they have added File[] getExternalFilesDirs (String type) in Context Class that allows apps to store data/files in micro SD cards.

Android 4.4 is the first release of the platform that has actually allowed apps to use SD cards for storage. Any access to SD cards before API level 19 was through private, unsupported APIs.

getExternalFilesDirs(String type) returns absolute paths to application-specific directories on all shared/external storage devices. It means, it will return paths to both internal and external memory. Generally, second returned path would be the storage path for microSD card (if any).

But note that,

Shared storage may not always be available, since removable media can be ejected by the user. Media state can be checked using getExternalStorageState(File).

There is no security enforced with these files. For example, any application holding WRITE_EXTERNAL_STORAGE can write to these files.

The Internal and External Storage terminology according to Google/official Android docs is quite different from what we think.

jQuery click event not working after adding class

You should use the following:

$('#gentab').on('click', 'a.tabclick', function(event) {
    event.preventDefault();
    var liId = $(this).closest("li").attr("id");
    alert(liId);  
});

This will attach your event to any anchors within the #gentab element, reducing the scope of having to check the whole document element tree and increasing efficiency.

how I can show the sum of in a datagridview column?

Fast and clean way using LINQ

int total = dataGridView1.Rows.Cast<DataGridViewRow>()
                .Sum(t => Convert.ToInt32(t.Cells[1].Value));

verified on VS2013

Java math function to convert positive int to negative and negative to positive?

You can use the minus operator or Math.abs. These work for all negative integers EXCEPT for Integer.MIN_VALUE! If you do 0 - MIN_VALUE the answer is still MIN_VALUE.

Multiple files upload (Array) with CodeIgniter 2.0

You should use this library for multi upload in CI https://github.com/stvnthomas/CodeIgniter-Multi-Upload

Installation Simply copy the MY_Upload.php file to your applications library directory.

Use: function test_up in controller

public function test_up(){
if($this->input->post('submit')){
    $path = './public/test_upload/';
    $this->load->library('upload');
    $this->upload->initialize(array(
        "upload_path"=>$path,
        "allowed_types"=>"*"
    ));
    if($this->upload->do_multi_upload("myfile")){
        echo '<pre>';
        print_r($this->upload->get_multi_upload_data());
        echo '</pre>';
    }
}else{
    $this->load->view('test/upload_view');
}

}

upload_view.php in applications/view/test folder

<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="myfile[]" id="myfile" multiple>
<input type="submit" name="submit" id="submit" value="submit"/>