Programs & Examples On #Jstat

A JavaScript statistical library. Also a Java Virtual Machine Statistics Monitoring Tool.

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
@ 

Getting the parameters of a running JVM

Windows 10 or Windows Server 2016 provide such information in their standard task manager. A rare case for production, but if the target JVM is running on Windows, the simplest way to see its parameters is to press Ctrl+Alt+Delete, choose the Processes tab and add the Command line column (by clicking the right mouse button on any existing column header).

How to analyze information from a Java core dump?

Actually, VisualVM can process application core dump.

Just invoke "File/Add VM Coredump" and will add a new application in the application explorer. You can then take thread dump or heap dump of that JVM.

How to expand a list to function arguments in Python

Try the following:

foo(*values)

This can be found in the Python docs as Unpacking Argument Lists.

Python: call a function from string name

If it's in a class, you can use getattr:

class MyClass(object):
    def install(self):
          print "In install"

method_name = 'install' # set by the command line options
my_cls = MyClass()

method = None
try:
    method = getattr(my_cls, method_name)
except AttributeError:
    raise NotImplementedError("Class `{}` does not implement `{}`".format(my_cls.__class__.__name__, method_name))

method()

or if it's a function:

def install():
       print "In install"

method_name = 'install' # set by the command line options
possibles = globals().copy()
possibles.update(locals())
method = possibles.get(method_name)
if not method:
     raise NotImplementedError("Method %s not implemented" % method_name)
method()

How to pass a value to razor variable from javascript variable?

Step: 1 Your Html, First Store the value in your localstorage using javascript then add the line like below ,this is where you going to display the value in your html, my example is based on boostrap :

<label for="stringName" class="cols-sm-2 control-
label">@Html.Hidden("stringName", "")</label>

Step:2 Javascript

 $('#stringName').replaceWith(localStorage.getItem("itemName"));

Flask Value error view function did not return a response

The following does not return a response:

You must return anything like return afunction() or return 'a string'.

This can solve the issue

how to print a string to console in c++

All you have to do is add:

#include <string>
using namespace std;

at the top. (BTW I know this was posted in 2013 but I just wanted to answer)

Force browser to clear cache

Here is the MDSN page on setting caching in ASP.NET.

Response.Cache.SetExpires(DateTime.Now.AddSeconds(60))
Response.Cache.SetCacheability(HttpCacheability.Public)
Response.Cache.SetValidUntilExpires(False)
Response.Cache.VaryByParams("Category") = True

If Response.Cache.VaryByParams("Category") Then
   '...
End If

Passing command line arguments to R CMD BATCH

My impression is that R CMD BATCH is a bit of a relict. In any case, the more recent Rscript executable (available on all platforms), together with commandArgs() makes processing command line arguments pretty easy.

As an example, here is a little script -- call it "myScript.R":

## myScript.R
args <- commandArgs(trailingOnly = TRUE)
rnorm(n=as.numeric(args[1]), mean=as.numeric(args[2]))

And here is what invoking it from the command line looks like

> Rscript myScript.R 5 100
[1]  98.46435 100.04626  99.44937  98.52910 100.78853

Edit:

Not that I'd recommend it, but ... using a combination of source() and sink(), you could get Rscript to produce an .Rout file like that produced by R CMD BATCH. One way would be to create a little R script -- call it RscriptEcho.R -- which you call directly with Rscript. It might look like this:

## RscriptEcho.R
args <- commandArgs(TRUE)
srcFile <- args[1]
outFile <- paste0(make.names(date()), ".Rout")
args <- args[-1]

sink(outFile, split = TRUE)
source(srcFile, echo = TRUE)

To execute your actual script, you would then do:

Rscript RscriptEcho.R myScript.R 5 100
[1]  98.46435 100.04626  99.44937  98.52910 100.78853

which will execute myScript.R with the supplied arguments and sink interleaved input, output, and messages to a uniquely named .Rout.

Edit2:
You can run Rscript verbosely and place the verbose output in a file.

Rscript --verbose myScript.R 5 100 > myScript.Rout

Selecting a row in DataGridView programmatically

When setting a Selected row of a DataGridView at load time, consider handling this in the DataBindingComplete event, because it can be overwritten by default.

How do I get the file extension of a file in Java?

// Modified from EboMike's answer

String extension = "/path/to/file/foo.txt".substring("/path/to/file/foo.txt".lastIndexOf('.'));

extension should have ".txt" in it when run.

How to use background thread in swift?

dispatch_async(dispatch_get_global_queue(QOS_CLASS_BACKGROUND, 0), {
    // Conversion into base64 string
    self.uploadImageString =  uploadPhotoDataJPEG.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.EncodingEndLineWithCarriageReturn)
})

Difference between FetchType LAZY and EAGER in Java Persistence API?

public enum FetchType extends java.lang.Enum Defines strategies for fetching data from the database. The EAGER strategy is a requirement on the persistence provider runtime that data must be eagerly fetched. The LAZY strategy is a hint to the persistence provider runtime that data should be fetched lazily when it is first accessed. The implementation is permitted to eagerly fetch data for which the LAZY strategy hint has been specified. Example: @Basic(fetch=LAZY) protected String getName() { return name; }

Source

How do I use a custom deleter with a std::unique_ptr member?

Unless you need to be able to change the deleter at runtime, I would strongly recommend using a custom deleter type. For example, if use a function pointer for your deleter, sizeof(unique_ptr<T, fptr>) == 2 * sizeof(T*). In other words, half of the bytes of the unique_ptr object are wasted.

Writing a custom deleter to wrap every function is a bother, though. Thankfully, we can write a type templated on the function:

Since C++17:

template <auto fn>
using deleter_from_fn = std::integral_constant<decltype(fn), fn>;

template <typename T, auto fn>
using my_unique_ptr = std::unique_ptr<T, deleter_from_fn<fn>>;

// usage:
my_unique_ptr<Bar, destroy> p{create()};

Prior to C++17:

template <typename D, D fn>
using deleter_from_fn = std::integral_constant<D, fn>;

template <typename T, typename D, D fn>
using my_unique_ptr = std::unique_ptr<T, deleter_from_fn<D, fn>>;

// usage:
my_unique_ptr<Bar, decltype(destroy), destroy> p{create()};

Populate dropdown select with array using jQuery

function validateForm(){
    var success = true;
    resetErrorMessages();
    var myArray = [];
    $(".linkedServiceDonationPurpose").each(function(){
        myArray.push($(this).val())
    });

    $(".linkedServiceDonationPurpose").each(function(){
    for ( var i = 0; i < myArray.length; i = i + 1 ) {
        for ( var j = i+1; j < myArray.length; j = j + 1 )
            if(myArray[i] == myArray[j] &&  $(this).val() == myArray[j]){
                $(this).next( "div" ).html('Duplicate item selected');
                success=false;
           }
        } 
    });
    if (success) {
        return true;
    } else {
        return false;
    }
    function resetErrorMessages() {
        $(".error").each(function(){
            $(this).html('');
        });``
    }
}

Java logical operator short-circuiting

Java provides two interesting Boolean operators not found in most other computer languages. These secondary versions of AND and OR are known as short-circuit logical operators. As you can see from the preceding table, the OR operator results in true when A is true, no matter what B is.

Similarly, the AND operator results in false when A is false, no matter what B is. If you use the || and && forms, rather than the | and & forms of these operators, Java will not bother to evaluate the right-hand operand alone. This is very useful when the right-hand operand depends on the left one being true or false in order to function properly.

For example, the following code fragment shows how you can take advantage of short-circuit logical evaluation to be sure that a division operation will be valid before evaluating it:

if ( denom != 0 && num / denom >10)

Since the short-circuit form of AND (&&) is used, there is no risk of causing a run-time exception from dividing by zero. If this line of code were written using the single & version of AND, both sides would have to be evaluated, causing a run-time exception when denom is zero.

It is standard practice to use the short-circuit forms of AND and OR in cases involving Boolean logic, leaving the single-character versions exclusively for bitwise operations. However, there are exceptions to this rule. For example, consider the following statement:

 if ( c==1 & e++ < 100 ) d = 100;

Here, using a single & ensures that the increment operation will be applied to e whether c is equal to 1 or not.

How can I throw a general exception in Java?

It really depends on what you want to do with that exception after you catch it. If you need to differentiate your exception then you have to create your custom Exception. Otherwise you could just throw new Exception("message goes here");

Using DataContractSerializer to serialize, but can't deserialize back

Here is how I've always done it:

    public static string Serialize(object obj) {
        using(MemoryStream memoryStream = new MemoryStream())
        using(StreamReader reader = new StreamReader(memoryStream)) {
            DataContractSerializer serializer = new DataContractSerializer(obj.GetType());
            serializer.WriteObject(memoryStream, obj);
            memoryStream.Position = 0;
            return reader.ReadToEnd();
        }
    }

    public static object Deserialize(string xml, Type toType) {
        using(Stream stream = new MemoryStream()) {
            byte[] data = System.Text.Encoding.UTF8.GetBytes(xml);
            stream.Write(data, 0, data.Length);
            stream.Position = 0;
            DataContractSerializer deserializer = new DataContractSerializer(toType);
            return deserializer.ReadObject(stream);
        }
    }

Decrypt password created with htpasswd

.htpasswd entries are HASHES. They are not encrypted passwords. Hashes are designed not to be decryptable. Hence there is no way (unless you bruteforce for a loooong time) to get the password from the .htpasswd file.

What you need to do is apply the same hash algorithm to the password provided to you and compare it to the hash in the .htpasswd file. If the user and hash are the same then you're a go.

Why does git revert complain about a missing -m option?

By default git revert refuses to revert a merge commit as what that actually means is ambiguous. I presume that your HEAD is in fact a merge commit.

If you want to revert the merge commit, you have to specify which parent of the merge you want to consider to be the main trunk, i.e. what you want to revert to.

Often this will be parent number one, for example if you were on master and did git merge unwanted and then decided to revert the merge of unwanted. The first parent would be your pre-merge master branch and the second parent would be the tip of unwanted.

In this case you could do:

git revert -m 1 HEAD

Add missing dates to pandas dataframe

Here's a nice method to fill in missing dates into a dataframe, with your choice of fill_value, days_back to fill in, and sort order (date_order) by which to sort the dataframe:

def fill_in_missing_dates(df, date_col_name = 'date',date_order = 'asc', fill_value = 0, days_back = 30):

    df.set_index(date_col_name,drop=True,inplace=True)
    df.index = pd.DatetimeIndex(df.index)
    d = datetime.now().date()
    d2 = d - timedelta(days = days_back)
    idx = pd.date_range(d2, d, freq = "D")
    df = df.reindex(idx,fill_value=fill_value)
    df[date_col_name] = pd.DatetimeIndex(df.index)

    return df

In c# what does 'where T : class' mean?

T represents an object type of, it implies that you can give any type of. IList : if IList s=new IList; Now s.add("Always accept string.").

How to get PHP $_GET array?

I think i know what you mean, if you want to send an array through a URL you can use serialize

for example:

$foo = array(1,2,3);
$serialized_array = serialize($foo);
$url = "http://www.foo.whatever/page.php?vars=".urlencode($serialized_array);

and on page.php

$vars = unserialize($_GET['vars']);

CSS: Set Div height to 100% - Pixels

I'm guessing that you are trying to get sticky footer

CSS text-decoration underline color

You can't change the color of the line (you can't specify different foreground colors for the same element, and the text and its decoration form a single element). However there are some tricks:

a:link, a:visited {text-decoration: none; color: red; border-bottom: 1px solid #006699; }
a:hover, a:active {text-decoration: none; color: red; border-bottom: 1px solid #1177FF; }

Also you can make some cool effects this way:

a:link {text-decoration: none; color: red; border-bottom: 1px dashed #006699; }

Hope it helps.

Is there a limit on number of tcp/ip connections between machines on linux?

The quick answer is 2^16 TCP ports, 64K.

The issues with system imposed limits is a configuration issue, already touched upon in previous comments.

The internal implications to TCP is not so clear (to me). Each port requires memory for it's instantiation, goes onto a list and needs network buffers for data in transit.

Given 64K TCP sessions the overhead for instances of the ports might be an issue on a 32-bit kernel, but not a 64-bit kernel (correction here gladly accepted). The lookup process with 64K sessions can slow things a bit and every packet hits the timer queues, which can also be problematic. Storage for in transit data can theoretically swell to the window size times ports (maybe 8 GByte).

The issue with connection speed (mentioned above) is probably what you are seeing. TCP generally takes time to do things. However, it is not required. A TCP connect, transact and disconnect can be done very efficiently (check to see how the TCP sessions are created and closed).

There are systems that pass tens of gigabits per second, so the packet level scaling should be OK.

There are machines with plenty of physical memory, so that looks OK.

The performance of the system, if carefully configured should be OK.

The server side of things should scale in a similar fashion.

I would be concerned about things like memory bandwidth.

Consider an experiment where you login to the local host 10,000 times. Then type a character. The entire stack through user space would be engaged on each character. The active footprint would likely exceed the data cache size. Running through lots of memory can stress the VM system. The cost of context switches could approach a second!

This is discussed in a variety of other threads: https://serverfault.com/questions/69524/im-designing-a-system-to-handle-10000-tcp-connections-per-second-what-problems

What is the C++ function to raise a number to a power?

#include <iostream>
#include <conio.h>

using namespace std;

double raiseToPow(double ,int) //raiseToPow variable of type double which takes arguments (double, int)

void main()
{
    double x; //initializing the variable x and i 
    int i;
    cout<<"please enter the number"; 
    cin>>x;
    cout<<"plese enter the integer power that you want this number raised to";
    cin>>i;
    cout<<x<<"raise to power"<<i<<"is equal to"<<raiseToPow(x,i);
}

//definition of the function raiseToPower

double raiseToPow(double x, int power)
{
    double result;
    int i;
    result =1.0;
    for (i=1, i<=power;i++)
    {
        result = result*x;
    }
    return(result);
}

How to check if a socket is connected/disconnected in C#?

I made an extension method based on this MSDN article. This is how you can determine whether a socket is still connected.

public static bool IsConnected(this Socket client)
{
    bool blockingState = client.Blocking;

    try
    {
        byte[] tmp = new byte[1];

        client.Blocking = false;
        client.Send(tmp, 0, 0);
        return true;
    }
    catch (SocketException e)
    {
        // 10035 == WSAEWOULDBLOCK
        if (e.NativeErrorCode.Equals(10035))
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    finally
    {
        client.Blocking = blockingState;
    }
}

Correct Semantic tag for copyright info - html5

Put it inside your <footer> by all means, but the most fitting element is the small element.

The HTML5 spec for this says:

Small print typically features disclaimers, caveats, legal restrictions, or copyrights. Small print is also sometimes used for attribution, or for satisfying licensing requirements.

Naming Conventions: What to name a boolean variable?

Two issues to think about

  1. What is the scope of the variable (in other words: are you speaking about a local variable or a field?) ? A local variable has a narrower scope compared to a field. In particular, if the variable is used inside a relatively short method I would not care so much about its name. When the scope is large naming is more important.

  2. I think there's an inherent conflict in the way you treat this variable. On the one hand you say "false when an object is the last in a list", where on the other hand you also want to call it "inFront". An object that is (not) last in the list does not strike me as (not) inFront. This I would go with isLast.

Getting all documents from one collection in Firestore

Try following LOCs

    let query = firestore.collection('events');
    let response = [];
    await query.get().then(querySnapshot => {
          let docs = querySnapshot.docs;
          for (let doc of docs) {
              const selectedEvent = {
                     id: doc.id,
                     item: doc.data().event
                  };
             response.push(selectedEvent);
          }
   return response;

How to read a file and write into a text file?

If you want to do it line by line:

Dim sFileText As String
Dim iInputFile As Integer, iOutputFile as integer

iInputFile = FreeFile
Open "C:\Clients\Converter\Clockings.mis" For Input As #iInputFile 
iOutputFile = FreeFile
Open "C:\Clients\Converter\2.txt" For Output As #iOutputFile 
Do While Not EOF(iInputFile)
   Line Input #iInputFile , sFileText
   ' sFileTextis a single line of the original file
   ' you can append anything to it before writing to the other file
   Print #iOutputFile, sFileText 
Loop
Close #iInputFile 
Close #iOutputFile 

Fine control over the font size in Seaborn plots for academic papers

You are right. This is a badly documented issue. But you can change the font size parameter (by opposition to font scale) directly after building the plot. Check the following example:

import seaborn as sns
tips = sns.load_dataset("tips")

b = sns.boxplot(x=tips["total_bill"])
b.axes.set_title("Title",fontsize=50)
b.set_xlabel("X Label",fontsize=30)
b.set_ylabel("Y Label",fontsize=20)
b.tick_params(labelsize=5)
sns.plt.show()

, which results in this:

Different font sizes for different labels

To make it consistent in between plots I think you just need to make sure the DPI is the same. By the way it' also a possibility to customize a bit the rc dictionaries since "font.size" parameter exists but I'm not too sure how to do that.

NOTE: And also I don't really understand why they changed the name of the font size variables for axis labels and ticks. Seems a bit un-intuitive.

Android intent for playing video?

following code works just fine for me.

Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(movieurl));
startActivity(intent);

What is the incentive for curl to release the library for free?

I'm Daniel Stenberg.

I made curl

I founded the curl project back in 1998, I wrote the initial curl version and I created libcurl. I've written more than half of all the 24,000 commits done in the source code repository up to this point in time. I'm still the lead developer of the project. To a large extent, curl is my baby.

I shipped the first version of curl as open source since I wanted to "give back" to the open source world that had given me so much code already. I had used so much open source and I wanted to be as cool as the other open source authors.

Thanks to it being open source, literally thousands of people have been able to help us out over the years and have improved the products, the documentation. the web site and just about every other detail around the project. curl and libcurl would never have become the products that they are today were they not open source. The list of contributors now surpass 1900 names and currently the list grows with a few hundred names per year.

Thanks to curl and libcurl being open source and liberally licensed, they were immediately adopted in numerous products and soon shipped by operating systems and Linux distributions everywhere thus getting a reach beyond imagination.

Thanks to them being "everywhere", available and liberally licensed they got adopted and used everywhere and by everyone. It created a defacto transfer library standard.

At an estimated six billion installations world wide, we can safely say that curl is the most widely used internet transfer library in the world. It simply would not have gone there had it not been open source. curl runs in billions of mobile phones, a billion Windows 10 installations, in a half a billion games and several hundred million TVs - and more.

Should I have released it with proprietary license instead and charged users for it? It never occured to me, and it wouldn't have worked because I would never had managed to create this kind of stellar project on my own. And projects and companies wouldn't have used it.

Why do I still work on curl?

Now, why do I and my fellow curl developers still continue to develop curl and give it away for free to the world?

  1. I can't speak for my fellow project team members. We all participate in this for our own reasons.
  2. I think it's still the right thing to do. I'm proud of what we've accomplished and I truly want to make the world a better place and I think curl does its little part in this.
  3. There are still bugs to fix and features to add!
  4. curl is free but my time is not. I still have a job and someone still has to pay someone for me to get paid every month so that I can put food on the table for my family. I charge customers and companies to help them with curl. You too can get my help for a fee, which then indirectly helps making sure that curl continues to evolve, remain free and the kick-ass product it is.
  5. curl was my spare time project for twenty years before I started working with it full time. I've had great jobs and worked on awesome projects. I've been in a position of luxury where I could continue to work on curl on my spare time and keep shipping a quality product for free. My work on curl has given me friends, boosted my career and taken me to places I would not have been at otherwise.
  6. I would not do it differently if I could back and do it again.

Am I proud of what we've done?

Yes. So insanely much.

But I'm not satisfied with this and I'm not just leaning back, happy with what we've done. I keep working on curl every single day, to improve, to fix bugs, to add features and to make sure curl keeps being the number one file transfer solution for the world even going forward.

We do mistakes along the way. We make the wrong decisions and sometimes we implement things in crazy ways. But to win in the end and to conquer the world is about patience and endurance and constantly going back and reconsidering previous decisions and correcting previous mistakes. To continuously iterate, polish off rough edges and gradually improve over time.

Never give in. Never stop. Fix bugs. Add features. Iterate. To the end of time.

For real?

Yeah. For real.

Do I ever get tired? Is it ever done?

Sure I get tired at times. Working on something every day for over twenty years isn't a paved downhill road. Sometimes there are obstacles. During times things are rough. Occasionally people are just as ugly and annoying as people can be.

But curl is my life's project and I have patience. I have thick skin and I don't give up easily. The tough times pass and most days are awesome. I get to hang out with awesome people and the reward is knowing that my code helps driving the Internet revolution everywhere is an ego boost above normal.

curl will never be "done" and so far I think work on curl is pretty much the most fun I can imagine. Yes, I still think so even after twenty years in the driver's seat. And as long as I think it's fun I intend to keep at it.

How to make a new List in Java

//simple example creating a list form a string array

String[] myStrings = new String[] {"Elem1","Elem2","Elem3","Elem4","Elem5"};

List mylist = Arrays.asList(myStrings );

//getting an iterator object to browse list items

Iterator itr= mylist.iterator();

System.out.println("Displaying List Elements,");

while(itr.hasNext())

  System.out.println(itr.next());

_csv.Error: field larger than field limit (131072)

I just had this happen to me on a 'plain' CSV file. Some people might call it an invalid formatted file. No escape characters, no double quotes and delimiter was a semicolon.

A sample line from this file would look like this:

First cell; Second " Cell with one double quote and leading space;'Partially quoted' cell;Last cell

the single quote in the second cell would throw the parser off its rails. What worked was:

csv.reader(inputfile, delimiter=';', doublequote='False', quotechar='', quoting=csv.QUOTE_NONE)

Verifying a specific parameter with Moq

Had one of these as well, but the parameter of the action was an interface with no public properties. Ended up using It.Is() with a seperate method and within this method had to do some mocking of the interface

public interface IQuery
{
    IQuery SetSomeFields(string info);
}

void DoSomeQuerying(Action<IQuery> queryThing);

mockedObject.Setup(m => m.DoSomeQuerying(It.Is<Action<IQuery>>(q => MyCheckingMethod(q)));

private bool MyCheckingMethod(Action<IQuery> queryAction)
{
    var mockQuery = new Mock<IQuery>();
    mockQuery.Setup(m => m.SetSomeFields(It.Is<string>(s => s.MeetsSomeCondition())
    queryAction.Invoke(mockQuery.Object);
    mockQuery.Verify(m => m.SetSomeFields(It.Is<string>(s => s.MeetsSomeCondition(), Times.Once)
    return true
}

JSON, REST, SOAP, WSDL, and SOA: How do they all link together

Imagine you are developing a web-application and you decide to decouple the functionality from the presentation of the application, because it affords greater freedom.

You create an API and let others implement their own front-ends over it as well. What you just did here is implement an SOA methodology, i.e. using web-services.

Web services make functional building-blocks accessible over standard Internet protocols independent of platforms and programming languages.

So, you design an interchange mechanism between the back-end (web-service) that does the processing and generation of something useful, and the front-end (which consumes the data), which could be anything. (A web, mobile, or desktop application, or another web-service). The only limitation here is that the front-end and back-end must "speak" the same "language".


That's where SOAP and REST come in. They are standard ways you'd pick communicate with the web-service.

SOAP:

SOAP internally uses XML to send data back and forth. SOAP messages have rigid structure and the response XML then needs to be parsed. WSDL is a specification of what requests can be made, with which parameters, and what they will return. It is a complete specification of your API.

REST:

REST is a design concept.

The World Wide Web represents the largest implementation of a system conforming to the REST architectural style.

It isn't as rigid as SOAP. RESTful web-services use standard URIs and methods to make calls to the webservice. When you request a URI, it returns the representation of an object, that you can then perform operations upon (e.g. GET, PUT, POST, DELETE). You are not limited to picking XML to represent data, you could pick anything really (JSON included)

Flickr's REST API goes further and lets you return images as well.


JSON and XML, are functionally equivalent, and common choices. There are also RPC-based frameworks like GRPC based on Protobufs, and Apache Thrift that can be used for communication between the API producers and consumers. The most common format used by web APIs is JSON because of it is easy to use and parse in every language.

How to format html table with inline styles to look like a rendered Excel table?

This is quick-and-dirty (and not formally valid HTML5), but it seems to work -- and it is inline as per the question:

<table border='1' style='border-collapse:collapse'>

No further styling of <tr>/<td> tags is required (for a basic table grid).

hidden field in php

You absolutely can, I use this approach a lot w/ both JavaScript and PHP.

Field definition:

<input type="hidden" name="foo" value="<?php echo $var;?>" />

Access w/ PHP:

$_GET['foo'] or $_POST['foo']

Also: Don't forget to sanitize your inputs if they are going into a database. Feel free to use my routine: https://github.com/niczak/PHP-Sanitize-Post/blob/master/sanitize.php

Cheers!

Split and join C# string

You can use string.Split and string.Join:

string theString = "Some Very Large String Here";
var array = theString.Split(' ');
string firstElem = array.First();
string restOfArray = string.Join(" ", array.Skip(1));

If you know you always only want to split off the first element, you can use:

var array = theString.Split(' ', 2);

This makes it so you don't have to join:

string restOfArray = array[1];

Test for array of string type in TypeScript

Here is the most concise solution so far:

function isArrayOfStrings(value: any): boolean {
   return Array.isArray(value) && value.every(item => typeof item === "string");
}

Note that value.every will return true for an empty array. If you need to return false for an empty array, you should add value.length to the condition clause:

function isNonEmptyArrayOfStrings(value: any): boolean {
    return Array.isArray(value) && value.length && value.every(item => typeof item === "string");
}

There is no any run-time type information in TypeScript (and there won't be, see TypeScript Design Goals > Non goals, 5), so there is no way to get the type of an empty array. For a non-empty array all you can do is to check the type of its items, one by one.

Convert factor to integer

Quoting directly from the help page for factor:

To transform a factor f to its original numeric values, as.numeric(levels(f))[f] is recommended and slightly more efficient than as.numeric(as.character(f)).

Is key-value observation (KVO) available in Swift?

Overview

It is possible using Combine without using NSObject or Objective-C

Availability: iOS 13.0+, macOS 10.15+, tvOS 13.0+, watchOS 6.0+, Mac Catalyst 13.0+, Xcode 11.0+

Note: Needs to be used only with classes not with value types.

Code:

Swift Version: 5.1.2

import Combine //Combine Framework

//Needs to be a class doesn't work with struct and other value types
class Car {

    @Published var price : Int = 10
}

let car = Car()

//Option 1: Automatically Subscribes to the publisher

let cancellable1 = car.$price.sink {
    print("Option 1: value changed to \($0)")
}

//Option 2: Manually Subscribe to the publisher
//Using this option multiple subscribers can subscribe to the same publisher

let publisher = car.$price

let subscriber2 : Subscribers.Sink<Int, Never>

subscriber2 = Subscribers.Sink(receiveCompletion: { print("completion \($0)")}) {
    print("Option 2: value changed to \($0)")
}

publisher.subscribe(subscriber2)

//Assign a new value

car.price = 20

Output:

Option 1: value changed to 10
Option 2: value changed to 10
Option 1: value changed to 20
Option 2: value changed to 20

Refer:

How to configure encoding in Maven?

This would be in addition to previous, if someone meets a problem with scandic letters that isn't solved with the solution above.

If the java source files contain scandic letters they need to be interpreted correctly by the Java used for compiling. (e.g. scandic letters used in constants)

Even that the files are stored in UTF-8 and the Maven is configured to use UTF-8, the System Java used by the Maven will still use the system default (eg. in Windows: cp1252).

This will be visible only running the tests via maven (possibly printing the values of these constants in tests. The printed scandic letters would show as '< ?>') If not tested properly, this would corrupt the class files as compile result and be left unnoticed.

To prevent this, you have to set the Java used for compiling to use UTF-8 encoding. It is not enough to have the encoding settings in the maven pom.xml, you need to set the environment variable: JAVA_TOOL_OPTIONS = -Dfile.encoding=UTF8

Also, if using Eclipse in Windows, you may need to set the encoding used in addition to this (if you run individual test via eclipse).

Returning a value from callback function in Node.js

I am facing small trouble in returning a value from callback function in Node.js

This is not a "small trouble", it is actually impossible to "return" a value in the traditional sense from an asynchronous function.

Since you cannot "return the value" you must call the function that will need the value once you have it. @display_name already answered your question, but I just wanted to point out that the return in doCall is not returning the value in the traditional way. You could write doCall as follow:

function doCall(urlToCall, callback) {
    urllib.request(urlToCall, { wd: 'nodejs' }, function (err, data, response) {                              
        var statusCode = response.statusCode;
        finalData = getResponseJson(statusCode, data.toString());
        // call the function that needs the value
        callback(finalData);
        // we are done
        return;
    });
}

Line callback(finalData); is what calls the function that needs the value that you got from the async function. But be aware that the return statement is used to indicate that the function ends here, but it does not mean that the value is returned to the caller (the caller already moved on.)

SQL Server 2012 Install or add Full-text search

You can add full text to an existing instance by changing the SQL Server program in Programs and Features. Follow the steps below. You might need the original disk or ISO for the installation to complete. (Per HotN's comment: If you have SQL Server Express, make sure it is SQL Server Express With Advanced Services.)

Directions:

  1. Open the Programs and Features control panel.
  2. Select Microsoft SQL Server 2012 and click Change.
  3. When prompted to Add/Repair/Remove, select Add.
  4. Advance through the wizard until the Feature Selection screen. Then select Full-Text Search.

Step 1 Step 2

enter image description here

  1. On the Installation Type screen, select the appropriate SQL Server instance.

  2. Advance through the rest of the wizard.

Source (with screenshots): http://www.techrepublic.com/blog/networking/adding-sql-full-text-search-to-an-existing-sql-server/5546

How to store command results in a shell variable?

The syntax to store the command output into a variable is var=$(command).

So you can directly do:

result=$(ls -l | grep -c "rahul.*patle")

And the variable $result will contain the number of matches.

Android TextView Text not getting wrapped

I finally managed to add some pixels to the height of the TextView to solve this issue.

First you need to actually get the height of the TextView. It's not straightforward because it's 0 before it's already painted.

Add this code to onCreate:

mReceiveInfoTextView = (TextView) findViewById(R.id.receive_info_txt);
if (mReceiveInfoTextView != null) { 
    final ViewTreeObserver observer = mReceiveInfoTextView.getViewTreeObserver();
    observer.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            int height = mReceiveInfoTextView.getHeight();
            int addHeight = getResources().getDimensionPixelSize(R.dimen.view_add_height);
            mReceiveInfoTextView.setHeight(height + addHeight);

            // Remove the listener if possible
            ViewTreeObserver viewTreeObserver = mReceiveInfoTextView.getViewTreeObserver();
            if (viewTreeObserver.isAlive()) {
                viewTreeObserver.removeOnGlobalLayoutListener(this);
            }
        }
    });
}

You need to add this line to dimens.xml

<dimen name="view_add_height">10dp</dimen>

Hope it helps.

C++ array initialization

Yes, I believe it should work and it can also be applied to other data types.

For class arrays though, if there are fewer items in the initializer list than elements in the array, the default constructor is used for the remaining elements. If no default constructor is defined for the class, the initializer list must be complete — that is, there must be one initializer for each element in the array.

How to display tables on mobile using Bootstrap?

You might also consider trying one of these approaches, since larger tables aren't exactly friendly on mobile even if it works:

http://elvery.net/demo/responsive-tables/

I'm partial to 'No More Tables' but that obviously depends on your application.

Array or List in Java. Which is faster?

None of the answers had information that I was interested in - repetitive scan of the same array many many times. Had to create a JMH test for this.

Results (Java 1.8.0_66 x32, iterating plain array is at least 5 times quicker than ArrayList):

Benchmark                    Mode  Cnt   Score   Error  Units
MyBenchmark.testArrayForGet  avgt   10   8.121 ? 0.233  ms/op
MyBenchmark.testListForGet   avgt   10  37.416 ? 0.094  ms/op
MyBenchmark.testListForEach  avgt   10  75.674 ? 1.897  ms/op

Test

package my.jmh.test;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Warmup;

@State(Scope.Benchmark)
@Fork(1)
@Warmup(iterations = 5, timeUnit = TimeUnit.SECONDS)
@Measurement(iterations = 10)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
public class MyBenchmark {

    public final static int ARR_SIZE = 100;
    public final static int ITER_COUNT = 100000;

    String arr[] = new String[ARR_SIZE];
    List<String> list = new ArrayList<>(ARR_SIZE);

    public MyBenchmark() {
        for( int i = 0; i < ARR_SIZE; i++ ) {
            list.add(null);
        }
    }

    @Benchmark
    public void testListForEach() {
        int count = 0;
        for( int i = 0; i < ITER_COUNT; i++ ) {
            for( String str : list ) {
                if( str != null )
                    count++;
            }
        }
        if( count > 0 )
            System.out.print(count);
    }

    @Benchmark
    public void testListForGet() {
        int count = 0;
        for( int i = 0; i < ITER_COUNT; i++ ) {
            for( int j = 0; j < ARR_SIZE; j++ ) {
                if( list.get(j) != null )
                    count++;
            }
        }
        if( count > 0 )
            System.out.print(count);
    }

    @Benchmark
    public void testArrayForGet() {
        int count = 0;
        for( int i = 0; i < ITER_COUNT; i++ ) {
            for( int j = 0; j < ARR_SIZE; j++ ) {
                if( arr[j] != null )
                    count++;
            }
        }
        if( count > 0 )
            System.out.print(count);
    }

}

Send a file via HTTP POST with C#

To post files as from byte arrays:

private static string UploadFilesToRemoteUrl(string url, IList<byte[]> files, NameValueCollection nvc) {

        string boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x");

        var request = (HttpWebRequest) WebRequest.Create(url);
        request.ContentType = "multipart/form-data; boundary=" + boundary;
        request.Method = "POST";
        request.KeepAlive = true;
        var postQueue = new ByteArrayCustomQueue();

        var formdataTemplate = "\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\";\r\n\r\n{1}";

        foreach (string key in nvc.Keys) {
            var formitem = string.Format(formdataTemplate, key, nvc[key]);
            var formitembytes = Encoding.UTF8.GetBytes(formitem);
            postQueue.Write(formitembytes);
        }

        var headerTemplate = "\r\n--" + boundary + "\r\n" +
            "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n" + 
            "Content-Type: application/zip\r\n\r\n";

        var i = 0;
        foreach (var file in files) {
            var header = string.Format(headerTemplate, "file" + i, "file" + i + ".zip");
            var headerbytes = Encoding.UTF8.GetBytes(header);
            postQueue.Write(headerbytes);
            postQueue.Write(file);
            i++;
        }

        postQueue.Write(Encoding.UTF8.GetBytes("\r\n--" + boundary + "--"));

        request.ContentLength = postQueue.Length;

        using (var requestStream = request.GetRequestStream()) {
            postQueue.CopyToStream(requestStream);
            requestStream.Close();
        }

        var webResponse2 = request.GetResponse();

        using (var stream2 = webResponse2.GetResponseStream())
        using (var reader2 = new StreamReader(stream2)) {

            var res =  reader2.ReadToEnd();
            webResponse2.Close();
            return res;
        }
    }

public class ByteArrayCustomQueue {

    private LinkedList<byte[]> arrays = new LinkedList<byte[]>();

    /// <summary>
    /// Writes the specified data.
    /// </summary>
    /// <param name="data">The data.</param>
    public void Write(byte[] data) {
        arrays.AddLast(data);
    }

    /// <summary>
    /// Gets the length.
    /// </summary>
    /// <value>
    /// The length.
    /// </value>
    public int Length { get { return arrays.Sum(x => x.Length); } }

    /// <summary>
    /// Copies to stream.
    /// </summary>
    /// <param name="requestStream">The request stream.</param>
    /// <exception cref="System.NotImplementedException"></exception>
    public void CopyToStream(Stream requestStream) {
        foreach (var array in arrays) {
            requestStream.Write(array, 0, array.Length);
        }
    }
}

Generate random string/characters in JavaScript

Above All answers are perfect. but I am adding which is very good and rapid to generate any random string value

_x000D_
_x000D_
function randomStringGenerator(stringLength) {_x000D_
  var randomString = ""; // Empty value of the selective variable_x000D_
  const allCharacters = "'`~!@#$%^&*()_+-={}[]:;\'<>?,./|\\ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'"; // listing of all alpha-numeric letters_x000D_
  while (stringLength--) {_x000D_
    randomString += allCharacters.substr(Math.floor((Math.random() * allCharacters.length) + 1), 1); // selecting any value from allCharacters varible by using Math.random()_x000D_
  }_x000D_
  return randomString; // returns the generated alpha-numeric string_x000D_
}_x000D_
_x000D_
console.log(randomStringGenerator(10));//call function by entering the random string you want
_x000D_
_x000D_
_x000D_

or

_x000D_
_x000D_
console.log(Date.now())// it will produce random thirteen numeric character value every time._x000D_
console.log(Date.now().toString().length)// print length of the generated string
_x000D_
_x000D_
_x000D_

How to make a radio button look like a toggle button

Inspired by Michal B. answer. If you use bootstrap..

_x000D_
_x000D_
label.btn {_x000D_
  padding: 0;_x000D_
}_x000D_
_x000D_
label.btn input {_x000D_
  opacity: 0;_x000D_
  position: absolute;_x000D_
}_x000D_
_x000D_
label.btn span {_x000D_
  text-align: center;_x000D_
  padding: 6px 12px;_x000D_
  display: block;_x000D_
}_x000D_
_x000D_
label.btn input:checked+span {_x000D_
  background-color: rgb(80, 110, 228);_x000D_
  color: #fff;_x000D_
}
_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">_x000D_
<div>_x000D_
  <label class="btn btn-outline-primary"><input type="radio" name="toggle"><span>One</span></label>_x000D_
  <label class="btn btn-outline-primary"><input type="radio" name="toggle"><span>Two</span></label>_x000D_
  <label class="btn btn-outline-primary"><input type="radio" name="toggle"><span>Three</span></label>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Is It Possible to NSLog C Structs (Like CGRect or CGPoint)?

You can use NSValue for this. An NSValue object is a simple container for a single C or Objective-C data item. It can hold any of the scalar types such as int, float, and char, as well as pointers, structures, and object ids.

Example:

  CGPoint cgPoint = CGPointMake(10,30);
    NSLog(@"%@",[NSValue valueWithCGPoint:cgPoint]);

OUTPUT : NSPoint: {10, 30}

Hope it helps you.

How to center buttons in Twitter Bootstrap 3?

You can do it by giving margin or by positioning those elements absolutely.

For example

.button{
  margin:0px auto; //it will center them 
}

0px will be from top and bottom and auto will be from left and right.

SQL Query for Logins

Starting with SQL 2008, you should use sys.server_principals instead of sys.syslogins, which has been deprecated.

Why use Ruby's attr_accessor, attr_reader and attr_writer?

You may use the different accessors to communicate your intent to someone reading your code, and make it easier to write classes which will work correctly no matter how their public API is called.

class Person
  attr_accessor :age
  ...
end

Here, I can see that I may both read and write the age.

class Person
  attr_reader :age
  ...
end

Here, I can see that I may only read the age. Imagine that it is set by the constructor of this class and after that remains constant. If there were a mutator (writer) for age and the class were written assuming that age, once set, does not change, then a bug could result from code calling that mutator.

But what is happening behind the scenes?

If you write:

attr_writer :age

That gets translated into:

def age=(value)
  @age = value
end

If you write:

attr_reader :age

That gets translated into:

def age
  @age
end

If you write:

attr_accessor :age

That gets translated into:

def age=(value)
  @age = value
end

def age
  @age
end

Knowing that, here's another way to think about it: If you did not have the attr_... helpers, and had to write the accessors yourself, would you write any more accessors than your class needed? For example, if age only needed to be read, would you also write a method allowing it to be written?

Cordova app not displaying correctly on iPhone X (Simulator)

In my case where each splash screen was individually designed instead of autogenerated or laid out in a story board format, I had to stick with my Legacy Launch screen configuration and add portrait and landscape images to target iPhoneX 1125×2436 orientations to the config.xml like so:

<splash height="2436" src="resources/ios/splash/Default-2436h.png" width="1125" />
<splash height="1125" src="resources/ios/splash/Default-Landscape-2436h.png" width="2436" />

After adding these to config.xml ("viewport-fit=cover" was already set in index.hml) my app built with Ionic Pro fills the entire screen on iPhoneX devices.

Android widget: How to change the text of a button

This is very easy

Button btn = (Button) findViewById(R.id.btn);
btn.setText("MyText");

How to store .pdf files into MySQL as BLOBs using PHP?

//Pour inserer :
            $pdf = addslashes(file_get_contents($_FILES['inputname']['tmp_name']));
            $filetype = addslashes($_FILES['inputname']['type']);//pour le test 
            $namepdf = addslashes($_FILES['inputname']['name']);            
            if (substr($filetype, 0, 11) == 'application'){
            $mysqli->query("insert into tablepdf(pdf_nom,pdf)value('$namepdf','$pdf')");
            }
//Pour afficher :
            $row = $mysqli->query("SELECT * FROM tablepdf where id=(select max(id) from tablepdf)");
            foreach($row as $result){
                 $file=$result['pdf'];
            }
            header('Content-type: application/pdf');
            echo file_get_contents('data:application/pdf;base64,'.base64_encode($file));

Android Studio - Auto complete and other features not working

There is a power saver mode in android studio if accidentally you click on that it will disable code analysis which will reduce the battery consumption and performance will also increase but it will not detect any errors and do auto complete operations.

To disable power saver mode

- Go to File Menu of Studio
- Uncheck The Power Saver Mode

In your IDE code analysis will be shown using an eye symbol at the right corner of your android studio.

If Green means it is enabled and there is no error in your code.
If Red Means It is enabled but there are few errors in your code.
If It is white or blur then code analysis is disabled

Is there a Python caching library?

import time

class CachedItem(object):
    def __init__(self, key, value, duration=60):
        self.key = key
        self.value = value
        self.duration = duration
        self.timeStamp = time.time()

    def __repr__(self):
        return '<CachedItem {%s:%s} expires at: %s>' % (self.key, self.value, time.time() + self.duration)

class CachedDict(dict):

    def get(self, key, fn, duration):
        if key not in self \
            or self[key].timeStamp + self[key].duration < time.time():
                print 'adding new value'
                o = fn(key)
                self[key] = CachedItem(key, o, duration)
        else:
            print 'loading from cache'

        return self[key].value



if __name__ == '__main__':

    fn = lambda key: 'value of %s  is None' % key

    ci = CachedItem('a', 12)
    print ci 
    cd = CachedDict()
    print cd.get('a', fn, 5)
    time.sleep(2)
    print cd.get('a', fn, 6)
    print cd.get('b', fn, 6)
    time.sleep(2)
    print cd.get('a', fn, 7)
    print cd.get('b', fn, 7)

Background image jumps when address bar hides iOS/Android/Mobile Chrome

I found that Jason's answer wasn't quite working for me and I was still getting a jump. The Javascript ensured there was no gap at the top of the page but the background was still jumping whenever the address bar disappeared/reappeared. So as well as the Javascript fix, I applied transition: height 999999s to the div. This creates a transition with a duration so long that it virtually freezes the element.

Wordpress - Images not showing up in the Media Library

Check Screen Options (dropdown tab in the upper right hand corner of the page), and make sure there are sane settings for what to show on screen. All the column settings should be checked, and there should be a positive number of media items being shown on screen.

If that is ok, then check Settings ? Media and make sure that Uploading Files folder is set to wp-content/uploads.

I believe these are the only settings that can be changed from the administrative screens.

Binding a WPF ComboBox to a custom list

To bind the data to ComboBox

List<ComboData> ListData = new List<ComboData>();
ListData.Add(new ComboData { Id = "1", Value = "One" });
ListData.Add(new ComboData { Id = "2", Value = "Two" });
ListData.Add(new ComboData { Id = "3", Value = "Three" });
ListData.Add(new ComboData { Id = "4", Value = "Four" });
ListData.Add(new ComboData { Id = "5", Value = "Five" });

cbotest.ItemsSource = ListData;
cbotest.DisplayMemberPath = "Value";
cbotest.SelectedValuePath = "Id";

cbotest.SelectedValue = "2";

ComboData looks like:

public class ComboData
{ 
  public int Id { get; set; } 
  public string Value { get; set; } 
}

(note that Id and Value have to be properties, not class fields)

POST: sending a post request in a url itself

If you are sending a request through url from browser(like consuming webservice) without using html pages by default it will be GET because GET has/needs no body. if you want to make url as POST you need html/jsp pages and you have to mention in form tag as "method=post" beacause post will have body and data will be transferred in that body for security reasons. So you need a medium (like html page) to make a POST request. You cannot make an URL as POST manually unless you specify it as POST through some medium. For example in URL (http://example.com/details?name=john&phonenumber=445566)you have attached data(name, phone number) so server will identify it as a GET data because server is receiving data is through URL but not inside a request body

How to "add existing frameworks" in Xcode 4?

In Project

  1. Select the project navigator
  2. Click on Build Phases
  3. Click on link binary with libraries
  4. Click on + Button and add your Frameworks

No connection string named 'MyEntities' could be found in the application config file

Make sure you've placed the connection string in the startup project's ROOT web.config.

I know I'm kinda stating the obvious here, but it happened to me too - though I already HAD the connection string in my MVC project's Web.Config (the .edmx file was placed at a different, class library project) and I couldn't figure out why I keep getting an exception... Long story short, I copied the connection string to the Views\Web.Config by mistake, in a strange combination of tiredness and not-scrolling-to-the-bottom-of-the-solution-explorer scenario. Yeah, these things happen to veteran developers as well :)

App.Config Transformation for projects which are not Web Projects in Visual Studio?

I have created another alternative to the one posted by Vishal Joshi where the requirement to change the build action to Content is removed and also implemented basic support for ClickOnce deployment. I say basic, because I didn't test it thoroughly but it should work in the typical ClickOnce deployment scenario.

The solution consists of a single MSBuild project that once imported to an existent windows application project (*.csproj) extends the build process to contemplate app.config transformation.

You can read a more detailed explanation at Visual Studio App.config XML Transformation and the MSBuild project file can be downloaded from GitHub.

Plot width settings in ipython notebook

This is way I did it:

%matplotlib inline
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = (12, 9) # (w, h)

You can define your own sizes.

How to use new PasswordEncoder from Spring Security

Having just gone round the internet to read up on this and the options in Spring I'd second Luke's answer, use BCrypt (it's mentioned in the source code at Spring).

The best resource I found to explain why to hash/salt and why use BCrypt is a good choice is here: Salted Password Hashing - Doing it Right.

How to know if .keyup() is a character key (jQuery)

I never liked the key code validation. My approach was to see if the input have text (any character), confirming that the user is entering text and no other characters

_x000D_
_x000D_
$('#input').on('keyup', function() {_x000D_
    var words = $(this).val();_x000D_
    // if input is empty, remove the word count data and return_x000D_
    if(!words.length) {_x000D_
        $(this).removeData('wcount');_x000D_
        return true;_x000D_
    }_x000D_
    // if word count data equals the count of the input, return_x000D_
    if(typeof $(this).data('wcount') !== "undefined" && ($(this).data('wcount') == words.length)){_x000D_
        return true;_x000D_
    }_x000D_
    // update or initialize the word count data_x000D_
    $(this).data('wcount', words.length);_x000D_
    console.log('user tiped ' + words);_x000D_
    // do you stuff..._x000D_
});
_x000D_
<html lang="en">_x000D_
  <head>_x000D_
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
  </head>_x000D_
  <body>_x000D_
  <input type="text" name="input" id="input">_x000D_
  </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Difference between \b and \B in regex

\B is not \b e.g. negative \b

pass-key here is no word boundary beside - so it matches \B in your first example there are word boundary beside cat so it matches \b

similar rules apply for others too. \W is negative of \w \UPPER CASE is negative of \LOWER CASE

One or more types required to compile a dynamic expression cannot be found. Are you missing references to Microsoft.CSharp.dll and System.Core.dll?

I had the same problem and solved it by removing "Microsoft.CSharp" reference from the project and then added it again.

What is the worst programming language you ever worked with?

For my senior design, we programmed a Canon camera to produce depth maps using CHDK. Most of the code was written in C, but you have to interface to it with this ridiculous language called uBasic. Basically, it wasn't implemented with a proper parser, and so variables can only be 1 letter, it's insanely slow, and if you make a mistake, the camera just shuts off.

How do I use a C# Class Library in a project?

  1. Add a reference to your library
  2. Import the namespace
  3. Consume the types in your library

Multiple INNER JOIN SQL ACCESS

Access requires parentheses in the FROM clause for queries which include more than one join. Try it this way ...

FROM
    ((tbl_employee
    INNER JOIN tbl_netpay
    ON tbl_employee.emp_id = tbl_netpay.emp_id)
    INNER JOIN tbl_gross
    ON tbl_employee.emp_id = tbl_gross.emp_ID)
    INNER JOIN tbl_tax
    ON tbl_employee.emp_id = tbl_tax.emp_ID;

If possible, use the Access query designer to set up your joins. The designer will add parentheses as required to keep the db engine happy.

Set min-width in HTML table's <td>

One way should be to add a <div style="min-width:XXXpx"> within the td, and let the <td style="width:100%">

How to remove the bottom border of a box with CSS

Just add in: border-bottom: none;

#index-03 {
    position:absolute;
    border: .1px solid #900;
    border-bottom: none;
    left:0px;
    top:102px;
    width:900px;
    height:27px;
}

Get Bitmap attached to ImageView

This code is better.

public static  byte[] getByteArrayFromImageView(ImageView imageView)
    {
        BitmapDrawable bitmapDrawable = ((BitmapDrawable) imageView.getDrawable());
        Bitmap bitmap;
        if(bitmapDrawable==null){
            imageView.buildDrawingCache();
            bitmap = imageView.getDrawingCache();
            imageView.buildDrawingCache(false);
        }else
        {
            bitmap = bitmapDrawable .getBitmap();
        }
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
        return stream.toByteArray();
    }

Number of days between two dates in Joda-Time

The accepted answer builds two LocalDate objects, which are quite expensive if you are reading lot of data. I use this:

  public static int getDaysBetween(DateTime earlier, DateTime later)
  {
    return (int) TimeUnit.MILLISECONDS.toDays(later.getMillis()- earlier.getMillis());
  }

By calling getMillis() you use already existing variables.
MILLISECONDS.toDays() then, uses a simple arithmetic calculation, does not create any object.

How to run function in AngularJS controller on document ready?

Why not try with what angular docs mention https://docs.angularjs.org/api/ng/function/angular.element.

angular.element(callback)

I've used this inside my $onInit(){...} function.

 var self = this;

 angular.element(function () {
        var target = document.getElementsByClassName('unitSortingModule');
        target[0].addEventListener("touchstart", self.touchHandler, false);
        ...
    });

This worked for me.

Call Stored Procedure within Create Trigger in SQL Server

You pass an undefined rAgent_IP parameter in EXEC instead of the local variable @rAgent_IP.

Still, this trigger will fail if you perform a multi-record INSERT statement.

Dynamically generating a QR code with PHP

qrcode-generator on Github. Simplest script and works like charm.

Pros:

  • No third party dependency
  • No limitations for the number of QR code generations

How to add a Java Properties file to my Java Project in Eclipse

To create a property class please select your package where you wants to create your property file.

Right click on the package and select other. Now select File and type your file name with (.properties) suffix. For example: db.properties. Than click finish. Now you can write your code inside this property file.

python object() takes no parameters error

I too got this error. Incidentally, i typed __int__ instead of __init__.

I think, in many mistype cases the IDE i am using (IntelliJ) would have changed the color to the default set for Function definition. But, in my case __int__ being another dunder/magic method, color remained same as the one which IDE displays for __init__ (default Predefined item definition color), which took me some time in spotting the missing i.

How to skip "are you sure Y/N" when deleting files in batch files

Use del /F /Q to force deletion of read-only files (/F) and directories and not ask to confirm (/Q) when deleting via wildcard.

fix java.net.SocketTimeoutException: Read timed out

I don't think it's enough merely to get the response. I think you need to read it (get the entity and read it via EntityUtils.consume()).

e.g. (from the doc)

     System.out.println("<< Response: " + response.getStatusLine());
     System.out.println(EntityUtils.toString(response.getEntity()));

Table variable error: Must declare the scalar variable "@temp"

Either use an Allias in the table like T and use T.ID, or use just the column name.

declare @TEMP table (ID int, Name varchar(max))
insert into @temp SELECT ID, Name FROM Table

SELECT * FROM @TEMP 
WHERE ID  = 1 

SVG fill color transparency / alpha?

You use an addtional attribute; fill-opacity: This attribute takes a decimal number between 0.0 and 1.0, inclusive; where 0.0 is completely transparent.

For example:

<rect ... fill="#044B94" fill-opacity="0.4"/>

Additionally you have the following:

  • stroke-opacity attribute for the stroke
  • opacity for the entire object

"Cross origin requests are only supported for HTTP." error when loading a local file

It simply says that the application should be run on a web server. I had the same problem with chrome, I started tomcat and moved my application there, and it worked.

Is there a math nCr function in python?

Do you want iteration? itertools.combinations. Common usage:

>>> import itertools
>>> itertools.combinations('abcd',2)
<itertools.combinations object at 0x01348F30>
>>> list(itertools.combinations('abcd',2))
[('a', 'b'), ('a', 'c'), ('a', 'd'), ('b', 'c'), ('b', 'd'), ('c', 'd')]
>>> [''.join(x) for x in itertools.combinations('abcd',2)]
['ab', 'ac', 'ad', 'bc', 'bd', 'cd']

If you just need to compute the formula, use math.factorial:

import math

def nCr(n,r):
    f = math.factorial
    return f(n) / f(r) / f(n-r)

if __name__ == '__main__':
    print nCr(4,2)

In Python 3, use the integer division // instead of / to avoid overflows:

return f(n) // f(r) // f(n-r)

Output

6

How to determine the last Row used in VBA including blank spaces in between

I use the following:

lastrow = ActiveSheet.Columns("A").Cells.Find("*", SearchOrder:=xlByRows, LookIn:=xlValues, SearchDirection:=xlPrevious).Row

It'll find the last row in a specific column. If you want the last used row for any column then:

lastrow = ActiveSheet.Cells.Find("*", SearchOrder:=xlByRows, LookIn:=xlValues, SearchDirection:=xlPrevious).Row

How to use dashes in HTML-5 data-* attributes in ASP.NET MVC

You can implement this with a new Html helper extension function which will then be used similarly to the existing ActionLinks.

public static MvcHtmlString ActionLinkHtml5Data(this HtmlHelper htmlHelper, string linkText, string actionName, string controllerName, object routeValues, object htmlAttributes, object htmlDataAttributes)
{
    if (string.IsNullOrEmpty(linkText))
    {
        throw new ArgumentException(string.Empty, "linkText");
    }

    var html = new RouteValueDictionary(htmlAttributes);
    var data = new RouteValueDictionary(htmlDataAttributes);

    foreach (var attributes in data)
    {
        html.Add(string.Format("data-{0}", attributes.Key), attributes.Value);
    }

    return MvcHtmlString.Create(HtmlHelper.GenerateLink(htmlHelper.ViewContext.RequestContext, htmlHelper.RouteCollection, linkText, null, actionName, controllerName, new RouteValueDictionary(routeValues), html));
}

And you call it like so ...

<%: Html.ActionLinkHtml5Data("link display", "Action", "Controller", new { id = Model.Id }, new { @class="link" }, new { extra = "some extra info" })  %>

Simples :-)

edit

bit more of a write up here

How to connect wireless network adapter to VMWare workstation?

Change your network adapter to a bridged connection, this will directly connect to your computers physical network.

How do I define a method in Razor?

It's very simple to define a function inside razor.

@functions {

    public static HtmlString OrderedList(IEnumerable<string> items)
    { }
}

So you can call a the function anywhere. Like

@Functions.OrderedList(new[] { "Blue", "Red", "Green" })

However, this same work can be done through helper too. As an example

@helper OrderedList(IEnumerable<string> items){
    <ol>
        @foreach(var item in items){
            <li>@item</li>
        }
    </ol>
}

So what is the difference?? According to this previous post both @helpers and @functions do share one thing in common - they make code reuse a possibility within Web Pages. They also share another thing in common - they look the same at first glance, which is what might cause a bit of confusion about their roles. However, they are not the same. In essence, a helper is a reusable snippet of Razor sytnax exposed as a method, and is intended for rendering HTML to the browser, whereas a function is static utility method that can be called from anywhere within your Web Pages application. The return type for a helper is always HelperResult, whereas the return type for a function is whatever you want it to be.

PHP cURL custom headers

$subscription_key  ='';
    $host = '';    
    $request_headers = array(
                    "X-Mashape-Key:" . $subscription_key,
                    "X-Mashape-Host:" . $host
                );

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $request_headers);

    $season_data = curl_exec($ch);

    if (curl_errno($ch)) {
        print "Error: " . curl_error($ch);
        exit();
    }

    // Show me the result
    curl_close($ch);
    $json= json_decode($season_data, true);

docker container ssl certificates

As was suggested in a comment above, if the certificate store on the host is compatible with the guest, you can just mount it directly.

On a Debian host (and container), I've successfully done:

docker run -v /etc/ssl/certs:/etc/ssl/certs:ro ...

What is the difference between functional and non-functional requirements?

functional requirements are the main things that the user expects from the software for example if the application is a banking application that application should be able to create a new account, update the account, delete an account, etc. functional requirements are detailed and are specified in the system design

Non-functional requirement are not straight forward the requirement of the system rather it is related to usability( in some way ) for example for a banking application a major non-functional requirement will be available the application should be available 24/7 with no downtime if possible.

Create a branch in Git from another branch

Various ways to create a branch in git from another branch:

This answer adds some additional insight, not already present in the existing answers, regarding just the title of the question itself (Create a branch in Git from another branch), but does not address the more narrow specifics of the question which already have sufficient answers here.

I'm adding this because I really needed to know how to do #1 below just now (create a new branch from a branch I do NOT have checked out), and it wasn't obvious how to do it, and Google searches led to here as a top search result. So, I'll share my findings here. This isn't touched upon well, if at all, by any other answer here.

While I'm at it, I'll also add my other most-common git branch commands I use in my regular workflow, below.

1. To create a new branch from a branch you do NOT have checked out:

Create branch2 from branch1 while you have any branch whatsoever checked out (ex: let's say you have master checked out):

git branch branch2 branch1

The general format is:

git branch <new_branch> [from_branch]

man git branch shows it as:

git branch [--track | --no-track] [-l] [-f] <branchname> [<start-point>]

2. To create a new branch from the branch you DO have checked out:

git branch new_branch

This is great for making backups before rebasing, squashing, hard resetting, etc.--before doing anything which could mess up your branch badly.

Ex: I'm on feature_branch1, and I'm about to squash 20 commits into 1 using git rebase -i master. In case I ever want to "undo" this, let's back up this branch first! I do this ALL...THE...TIME and find it super helpful and comforting to know I can always easily go back to this backup branch and re-branch off of it to try again in case I mess up feature_branch1 in the process:

git branch feature_branch1_BAK_20200814-1320hrs_about_to_squash

The 20200814-1120hrs part is the date and time in format YYYYMMDD-HHMMhrs, so that would be 13:20hrs (1:20pm) on 14 Aug. 2020. This way I have an easy way to find my backup branches until I'm sure I'm ready to delete them. If you don't do this and you mess up badly, you have to use git reflog to go find your branch prior to messing it up, which is much harder, more stressful, and more error-prone.

3. To create and check out a new branch from the branch you DO have checked out:

git checkout -b new_branch

4. To rename a branch

Just like renaming a regular file or folder in the terminal, git considered "renaming" to be more like a 'm'ove command, so you use git branch -m to rename a branch. Here's the general format:

git branch -m <old_name> <new_name>

man git branch shows it like this:

git branch (-m | -M) [<oldbranch>] <newbranch>

Example: let's rename branch_1 to branch_1.5:

git branch -m branch_1 branch_1.5

SQL Insert Query Using C#

static SqlConnection myConnection;

    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        myConnection = new SqlConnection("server=localhost;" +
                                                      "Trusted_Connection=true;" +
             "database=zxc; " +
                                                      "connection timeout=30");
        try
        {

            myConnection.Open();
            label1.Text = "connect successful";

        }
        catch (SqlException ex)
        {
            label1.Text = "connect fail";
            MessageBox.Show(ex.Message);
        }
    }

    private void Form1_Load(object sender, EventArgs e)
    {

    }

    private void button2_Click(object sender, EventArgs e)
    {
        String st = "INSERT INTO supplier(supplier_id, supplier_name)VALUES(" + textBox1.Text + ", " + textBox2.Text + ")";
        SqlCommand sqlcom = new SqlCommand(st, myConnection);
        try
        {
            sqlcom.ExecuteNonQuery();
            MessageBox.Show("insert successful");
        }
        catch (SqlException ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

Why is "using namespace std;" considered bad practice?

It depends on where it is located. If it is a common header, then you are diminishing the value of the namespace by merging it into the global namespace. Keep in mind, this could be a neat way of making module globals.

How do I convert a single character into it's hex ascii value in python

To use the hex encoding in Python 3, use

>>> import codecs
>>> codecs.encode(b"c", "hex")
b'63'

In legacy Python, there are several other ways of doing this:

>>> hex(ord("c"))
'0x63'
>>> format(ord("c"), "x")
'63'
>>> "c".encode("hex")
'63'

Android: How to handle right to left swipe gestures

I know its a bit late since 2012 but I hope it will help someone since I think it's a shorter and cleaner code than most of the answers:

view.setOnTouchListener((v, event) -> {
        
int action = MotionEventCompat.getActionMasked(event);

switch(action) {
    case (MotionEvent.ACTION_DOWN) :
        Log.d(DEBUG_TAG,"Action was DOWN");
        return true;

    case (MotionEvent.ACTION_MOVE) :
        Log.d(DEBUG_TAG,"Action was MOVE");
        return true;

    case (MotionEvent.ACTION_UP) :
        Log.d(DEBUG_TAG,"Action was UP");
        return true;

    case (MotionEvent.ACTION_CANCEL) :
        Log.d(DEBUG_TAG,"Action was CANCEL");
        return true;

    case (MotionEvent.ACTION_OUTSIDE) :
        Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
                "of current screen element");
        return true;

    default :
        return super.onTouchEvent(event);
}
    });

of course you can leave only the relevant gestures to you.

src: https://developer.android.com/training/gestures/detector

How to simulate a mouse click using JavaScript?

JavaScript Code

   //this function is used to fire click event
    function eventFire(el, etype){
      if (el.fireEvent) {
        el.fireEvent('on' + etype);
      } else {
        var evObj = document.createEvent('Events');
        evObj.initEvent(etype, true, false);
        el.dispatchEvent(evObj);
      }
    }

function showPdf(){
  eventFire(document.getElementById('picToClick'), 'click');
}

HTML Code

<img id="picToClick" data-toggle="modal" data-target="#pdfModal" src="img/Adobe-icon.png" ng-hide="1===1">
  <button onclick="showPdf()">Click me</button>

Distribution certificate / private key not installed

If you are being stuck on this problem. After switch the computer and not able to upload your build to App Store. Simply click manage certificate on the error page, the + plus on the bottom left corner and create a new distribution certificate. Then you'll be good to go.

Which to use <div class="name"> or <div id="name">?

ID's must be unique (only be given to one element in the DOM at a time), whereas classes don't have to be. You've already discovered the CSS . class and # ID prefixes, so that's pretty much it.

how to check if a file is a directory or regular file in python?

An educational example from the stat documentation:

import os, sys
from stat import *

def walktree(top, callback):
    '''recursively descend the directory tree rooted at top,
       calling the callback function for each regular file'''

    for f in os.listdir(top):
        pathname = os.path.join(top, f)
        mode = os.stat(pathname)[ST_MODE]
        if S_ISDIR(mode):
            # It's a directory, recurse into it
            walktree(pathname, callback)
        elif S_ISREG(mode):
            # It's a file, call the callback function
            callback(pathname)
        else:
            # Unknown file type, print a message
            print 'Skipping %s' % pathname

def visitfile(file):
    print 'visiting', file

if __name__ == '__main__':
    walktree(sys.argv[1], visitfile)

Make an image follow mouse pointer

Ok, here's a simple box that follows the cursor

Doing the rest is a simple case of remembering the last cursor position and applying a formula to get the box to move other than exactly where the cursor is. A timeout would also be handy if the box has a limited acceleration and must catch up to the cursor after it stops moving. Replacing the box with an image is simple CSS (which can replace most of the setup code for the box). I think the actual thinking code in the example is about 8 lines.

Select the right image (use a sprite) to orientate the rocket.

Yeah, annoying as hell. :-)

_x000D_
_x000D_
function getMouseCoords(e) {
  var e = e || window.event;
  document.getElementById('container').innerHTML = e.clientX + ', ' +
    e.clientY + '<br>' + e.screenX + ', ' + e.screenY;
}


var followCursor = (function() {
  var s = document.createElement('div');
  s.style.position = 'absolute';
  s.style.margin = '0';
  s.style.padding = '5px';
  s.style.border = '1px solid red';
  s.textContent = ""

  return {
    init: function() {
      document.body.appendChild(s);
    },

    run: function(e) {
      var e = e || window.event;
      s.style.left = (e.clientX - 5) + 'px';
      s.style.top = (e.clientY - 5) + 'px';
      getMouseCoords(e);
    }
  };
}());

window.onload = function() {
  followCursor.init();
  document.body.onmousemove = followCursor.run;
}
_x000D_
#container {
  width: 1000px;
  height: 1000px;
  border: 1px solid blue;
}
_x000D_
<div id="container"></div>
_x000D_
_x000D_
_x000D_

What is a Subclass

It is a class that extends another class.

example taken from https://www.java-tips.org/java-se-tips-100019/24-java-lang/784-what-is-a-java-subclass.html, Cat is a sub class of Animal :-)

public class Animal {

    public static void hide() {
        System.out.println("The hide method in Animal.");
    }

    public void override() {
        System.out.println("The override method in Animal.");
    }
}

public class Cat extends Animal {

    public static void hide() {
        System.out.println("The hide method in Cat.");
    }

    public void override() {
        System.out.println("The override method in Cat.");
    }

    public static void main(String[] args) {
        Cat myCat = new Cat();
        Animal myAnimal = (Animal)myCat;
        myAnimal.hide();
        myAnimal.override();
    }
}

Delete specific values from column with where condition?

UPDATE YourTable SET columnName = null WHERE YourCondition

SSL certificate is not trusted - on mobile only

The most likely reason for the error is that the certificate authority that issued your SSL certificate is trusted on your desktop, but not on your mobile.

If you purchased the certificate from a common certification authority, it shouldn't be an issue - but if it is a less common one it is possible that your phone doesn't have it. You may need to accept it as a trusted publisher (although this is not ideal if you are pushing the site to the public as they won't be willing to do this.)

You might find looking at a list of Trusted CAs for Android helps to see if yours is there or not.

How to change context root of a dynamic web project in Eclipse?

I tried out solution suggested by Russ Bateman Here in the post

http://localhost:8080/Myapp to http://localhost:8080/somepath/Myapp

But Didnt worked for me as I needed to have a *.war file that can hold the config and not the individual instance of server on my localmachine.

Reference

In order to do that I need jboss-web.xml placed in WEB-INF

<?xml version="1.0" encoding="UTF-8"?>
 <!--
Copyright (c) 2008 Object Computing, Inc.
All rights reserved.
-->
<!DOCTYPE jboss-web PUBLIC "-//JBoss//DTD Web Application 4.2//EN"
"http://www.jboss.org/j2ee/dtd/jboss-web_4_2.dtd">

  <jboss-web>
  <context-root>somepath/Myapp</context-root>
  </jboss-web>

Python PDF library

I already have used Reportlab in one project.

HTML Agility pack - parsing tables

I know this is a pretty old question but this was my solution that helped with visualizing the table so you can create a class structure. This is also using the HTML Agility Pack

HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(@"<html><body><p><table id=""foo""><tr><th>hello</th></tr><tr><td>world</td></tr></table></body></html>");
var table = doc.DocumentNode.SelectSingleNode("//table");
var tableRows = table.SelectNodes("tr");
var columns = tableRows[0].SelectNodes("th/text()");
for (int i = 1; i < tableRows.Count; i++)
{
    for (int e = 0; e < columns.Count; e++)
    {
        var value = tableRows[i].SelectSingleNode($"td[{e + 1}]");
        Console.Write(columns[e].InnerText + ":" + value.InnerText);
    }
Console.WriteLine();
}

Listing contents of a bucket with boto3

Here is a simple function that returns you the filenames of all files or files with certain types such as 'json', 'jpg'.

def get_file_list_s3(bucket, prefix="", file_extension=None):
            """Return the list of all file paths (prefix + file name) with certain type or all
            Parameters
            ----------
            bucket: str
                The name of the bucket. For example, if your bucket is "s3://my_bucket" then it should be "my_bucket"
            prefix: str
                The full path to the the 'folder' of the files (objects). For example, if your files are in 
                s3://my_bucket/recipes/deserts then it should be "recipes/deserts". Default : ""
            file_extension: str
                The type of the files. If you want all, just leave it None. If you only want "json" files then it
                should be "json". Default: None       
            Return
            ------
            file_names: list
                The list of file names including the prefix
            """
            import boto3
            s3 = boto3.resource('s3')
            my_bucket = s3.Bucket(bucket)
            file_objs =  my_bucket.objects.filter(Prefix=prefix).all()
            file_names = [file_obj.key for file_obj in file_objs if file_extension is not None and file_obj.key.split(".")[-1] == file_extension]
            return file_names

Swift days between two NSDates

Here is the answer for Swift 3 (tested for IOS 10 Beta)

func daysBetweenDates(startDate: Date, endDate: Date) -> Int
{
    let calendar = Calendar.current
    let components = calendar.components([.day], from: startDate, to: endDate, options: [])
    return components.day!
}

Then you can call it like this

let pickedDate: Date = sender.date
let NumOfDays: Int = daysBetweenDates(startDate: pickedDate, endDate: Date())
    print("Num of Days: \(NumOfDays)")

How to change color of SVG image using CSS (jQuery SVG image replacement)?

Alternatively you could use CSS mask, granted browser support isn't good but you could use a fallback

.frame {
    background: blue;
    -webkit-mask: url(image.svg) center / contain no-repeat;
}

Getting Checkbox Value in ASP.NET MVC 4

Use only this

$("input[type=checkbox]").change(function () {
    if ($(this).prop("checked")) {
        $(this).val(true);
    } else {
        $(this).val(false);
    }
});

What does the JSLint error 'body of a for in should be wrapped in an if statement' mean?

Surely it's a little extreme to say

...never use a for in loop to enumerate over an array. Never. Use good old for(var i = 0; i<arr.length; i++)

?

It is worth highlighting the section in the Douglas Crockford extract

...The second form should be used with objects...

If you require an associative array ( aka hashtable / dictionary ) where keys are named instead of numerically indexed, you will have to implement this as an object, e.g. var myAssocArray = {key1: "value1", key2: "value2"...};.

In this case myAssocArray.length will come up null (because this object doesn't have a 'length' property), and your i < myAssocArray.length won't get you very far. In addition to providing greater convenience, I would expect associative arrays to offer performance advantages in many situations, as the array keys can be useful properties (i.e. an array member's ID property or name), meaning you don't have to iterate through a lengthy array repeatedly evaluating if statements to find the array entry you're after.

Anyway, thanks also for the explanation of the JSLint error messages, I will use the 'isOwnProperty' check now when interating through my myriad associative arrays!

Capturing standard out and error with Start-Process

I really had troubles with those examples from Andy Arismendi and from LPG. You should always use:

$stdout = $p.StandardOutput.ReadToEnd()

before calling

$p.WaitForExit()

A full example is:

$pinfo = New-Object System.Diagnostics.ProcessStartInfo
$pinfo.FileName = "ping.exe"
$pinfo.RedirectStandardError = $true
$pinfo.RedirectStandardOutput = $true
$pinfo.UseShellExecute = $false
$pinfo.Arguments = "localhost"
$p = New-Object System.Diagnostics.Process
$p.StartInfo = $pinfo
$p.Start() | Out-Null
$stdout = $p.StandardOutput.ReadToEnd()
$stderr = $p.StandardError.ReadToEnd()
$p.WaitForExit()
Write-Host "stdout: $stdout"
Write-Host "stderr: $stderr"
Write-Host "exit code: " + $p.ExitCode

Having services in React application

I needed some formatting logic to be shared across multiple components and as an Angular developer also naturally leaned towards a service.

I shared the logic by putting it in a separate file

function format(input) {
    //convert input to output
    return output;
}

module.exports = {
    format: format
};

and then imported it as a module

import formatter from '../services/formatter.service';

//then in component

    render() {

        return formatter.format(this.props.data);
    }

How to solve a pair of nonlinear equations using Python?

Short answer: use fsolve

As mentioned in other answers the simplest solution to the particular problem you have posed is to use something like fsolve:

from scipy.optimize import fsolve
from math import exp

def equations(vars):
    x, y = vars
    eq1 = x+y**2-4
    eq2 = exp(x) + x*y - 3
    return [eq1, eq2]

x, y =  fsolve(equations, (1, 1))

print(x, y)

Output:

0.6203445234801195 1.8383839306750887

Analytic solutions?

You say how to "solve" but there are different kinds of solution. Since you mention SymPy I should point out the biggest difference between what this could mean which is between analytic and numeric solutions. The particular example you have given is one that does not have an (easy) analytic solution but other systems of nonlinear equations do. When there are readily available analytic solutions SymPY can often find them for you:

from sympy import *

x, y = symbols('x, y')
eq1 = Eq(x+y**2, 4)
eq2 = Eq(x**2 + y, 4)

sol = solve([eq1, eq2], [x, y])

Output:

?? ?  5   v17? ?3   v17?    v17   1?  ? ?  5   v17? ?3   v17?    1   v17?  ? ?  3   v13? ?v13   5?  1   v13?  ? ?5   v13? ?  v13   3?  1   v13??
??-?- - - ---?·?- - ---?, - --- - -?, ?-?- - + ---?·?- + ---?, - - + ---?, ?-?- - + ---?·?--- + -?, - + ---?, ?-?- - ---?·?- --- - -?, - - ---??
?? ?  2    2 ? ?2    2 ?     2    2?  ? ?  2    2 ? ?2    2 ?    2    2 ?  ? ?  2    2 ? ? 2    2?  2    2 ?  ? ?2    2 ? ?   2    2?  2    2 ??

Note that in this example SymPy finds all solutions and does not need to be given an initial estimate.

You can evaluate these solutions numerically with evalf:

soln = [tuple(v.evalf() for v in s) for s in sol]
[(-2.56155281280883, -2.56155281280883), (1.56155281280883, 1.56155281280883), (-1.30277563773199, 2.30277563773199), (2.30277563773199, -1.30277563773199)]

Precision of numeric solutions

However most systems of nonlinear equations will not have a suitable analytic solution so using SymPy as above is great when it works but not generally applicable. That is why we end up looking for numeric solutions even though with numeric solutions: 1) We have no guarantee that we have found all solutions or the "right" solution when there are many. 2) We have to provide an initial guess which isn't always easy.

Having accepted that we want numeric solutions something like fsolve will normally do all you need. For this kind of problem SymPy will probably be much slower but it can offer something else which is finding the (numeric) solutions more precisely:

from sympy import *

x, y = symbols('x, y')
nsolve([Eq(x+y**2, 4), Eq(exp(x)+x*y, 3)], [x, y], [1, 1])
?0.620344523485226?
?                 ?
?1.83838393066159 ?

With greater precision:

nsolve([Eq(x+y**2, 4), Eq(exp(x)+x*y, 3)], [x, y], [1, 1], prec=50)
?0.62034452348522585617392716579154399314071550594401?
?                                                    ?
? 1.838383930661594459049793153371142549403114879699 ?

PHP - Copy image to my server direct from URL

Two ways, if you're using PHP5 (or higher)

copy('http://www.google.co.in/intl/en_com/images/srpr/logo1w.png', '/tmp/file.png');

If not, use file_get_contents

//Get the file
$content = file_get_contents("http://www.google.co.in/intl/en_com/images/srpr/logo1w.png");
//Store in the filesystem.
$fp = fopen("/location/to/save/image.png", "w");
fwrite($fp, $content);
fclose($fp);

From this SO post

Code line wrapping - how to handle long lines

This is how I do it, and Google does it my way.

  • Break before the symbol for non-assignment operators.
  • Break after the symbol for = and for ,.

In your case, since you're using 120 characters, you can break it after the assignment operator resulting in

private static final Map<Class<? extends Persistent>, PersistentHelper> class2helper =
        new HashMap<Class<? extends Persistent>, PersistentHelper>();

In Java, and for this particular case, I would give two tabs (or eight spaces) after the break, depending on whether tabs or spaces are used for indentation.

This is of course a personal preference and if your project has its own convention for line-wrapping then that is what you should follow whether you like it or not.

Sanitizing user input before adding it to the DOM in Javascript

You could use a simple regular expression to assert that the id only contains allowed characters, like so:

if(id.match(/^[0-9a-zA-Z]{1,16}$/)){
    //The id is fine
}
else{
    //The id is illegal
}

My example allows only alphanumerical characters, and strings of length 1 to 16, you should change it to match the type of ids that you use.

By the way, at line 6, the value property is missing a pair of quotes, an easy mistake to make when you quote on two levels.

I can't see your actual data flow, depending on context this check may not at all be needed, or it may not be enough. In order to make a proper security review we would need more information.

In general, about built in escape or sanitize functions, don't trust them blindly. You need to know exactly what they do, and you need to establish that that is actually what you need. If it is not what you need, the code your own, most of the time a simple whitelisting regex like the one I gave you works just fine.

How to .gitignore all files/folder in a folder, but not the folder itself?

You can't commit empty folders in git. If you want it to show up, you need to put something in it, even just an empty file.

For example, add an empty file called .gitkeep to the folder you want to keep, then in your .gitignore file write:

# exclude everything
somefolder/*

# exception to the rule
!somefolder/.gitkeep 

Commit your .gitignore and .gitkeep files and this should resolve your issue.

How to get numeric position of alphabets in java?

just logic I can suggest take two arrays.

one is Char array

and another is int array.

convert ur input string to char array,get the position of char from char and int array.

dont expect source code here

Is there a foreach in MATLAB? If so, how does it behave if the underlying data changes?

Zach is correct about the direct answer to the question.

An interesting side note is that the following two loops do not execute the same:

for i=1:10000
  % do something
end
for i=[1:10000]
  % do something
end

The first loop creates a variable i that is a scalar and it iterates it like a C for loop. Note that if you modify i in the loop body, the modified value will be ignored, as Zach says. In the second case, Matlab creates a 10k-element array, then it walks all elements of the array.

What this means is that

for i=1:inf
  % do something
end

works, but

for i=[1:inf]
  % do something
end

does not (because this one would require allocating infinite memory). See Loren's blog for details.

Also note that you can iterate over cell arrays.

How to check if a string starts with one of several prefixes?

No one mentioned Stream so far, so here it is:

if (Stream.of("Mon", "Tues", "Wed", "Thurs", "Fri").anyMatch(s -> newStr4.startsWith(s)))

PHP Unset Session Variable

Destroying a PHP Session

A PHP session can be destroyed by session_destroy() function. This function does not need any argument and a single call can destroy all the session variables. If you want to destroy a single session variable then you can use unset() function to unset a session variable.

Here is the example to unset a single variable

<?php    unset($_SESSION['counter']); ?>

Here is the call which will destroy all the session variables

<?php    session_destroy(); ?>

How to change letter spacing in a Textview?

As android doesn't support such a thing, you can do it manually with FontCreator. It has good options for font modifying. I used this tool to build a custom font, even if it takes some times but you can always use it in your projects.

Git Clone - Repository not found

What solved my problem, since I was having a "redirect/sign_in URL" or "repository not found" error

MacOS Users:

  1. Open spotlight (Command Space)
  2. Type keychain (Open keychain access.app)
  3. Search for repo domain (GitHub, GitLab, etc)
  4. Delete all keys related to this domain
  5. Try to clone again (with valid credentials)

Windows users should try similar steps, but Keychain would be Microsoft's Credentials Manager instead or Windows Credentials depending on yours OS version. Make sure to clean both web and windows credentials if that's the case.

How to redirect on another page and pass parameter in url from table?

Here is a general solution that doesn't rely on JQuery. Simply modify the definition of window.location.

<html>
   <head>
      <script>
         function loadNewDoc(){ 
            var loc = window.location;
            window.location = loc.hostname + loc.port + loc.pathname + loc.search; 
         };
      </script>
   </head>
   <body onLoad="loadNewDoc()">
   </body>  
</html>

How do I vertically center text with CSS?

I'm not sure anyone has gone the writing-mode route, but I think it solves the problem cleanly and has broad support:

_x000D_
_x000D_
.vertical {_x000D_
  //border: 1px solid green;_x000D_
  writing-mode: vertical-lr;_x000D_
  text-align: center;_x000D_
  height: 100%;_x000D_
  width: 100%;_x000D_
}_x000D_
.horizontal {_x000D_
  //border: 1px solid blue;_x000D_
  display: inline-block;_x000D_
  writing-mode: horizontal-tb;_x000D_
  width: 100%;_x000D_
  text-align: center;_x000D_
}_x000D_
.content {_x000D_
  text-align: left;_x000D_
  display: inline-block;_x000D_
  border: 1px solid #e0e0e0;_x000D_
  padding: .5em 1em;_x000D_
  border-radius: 1em;_x000D_
}
_x000D_
<div class="vertical">_x000D_
  <div class="horizontal">_x000D_
    <div class="content">_x000D_
      I'm centered in the vertical and horizontal thing_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

This will, of course, work with any dimensions you need (besides 100% of the parent). If you uncomment the border lines, it'll be helpful to familiarize yourself.

JSFiddle demo for you to fiddle.

Caniuse support: 85.22% + 6.26% = 91.48% (even Internet Explorer is in!)

Handler vs AsyncTask vs Thread

In my opinion threads aren't the most efficient way of doing socket connections but they do provide the most functionality in terms of running threads. I say that because from experience, running threads for a long time causes devices to be very hot and resource intensive. Even a simple while(true) will heat a phone in minutes. If you say that UI interaction is not important, perhaps an AsyncTask is good because they are designed for long-term processes. This is just my opinion on it.

UPDATE

Please disregard my above answer! I answered this question back in 2011 when I was far less experienced in Android than I am now. My answer above is misleading and is considered wrong. I'm leaving it there because many people commented on it below correcting me, and I've learned my lesson.

There are far better other answers on this thread, but I will at least give me more proper answer. There is nothing wrong with using a regular Java Thread; however, you should really be careful about how you implement it because doing it wrong can be very processor intensive (most notable symptom can be your device heating up). AsyncTasks are pretty ideal for most tasks that you want to run in the background (common examples are disk I/O, network calls, and database calls). However, AsyncTasks shouldn't be used for particularly long processes that may need to continue after the user has closed your app or put their device to standby. I would say for most cases, anything that doesn't belong in the UI thread, can be taken care of in an AsyncTask.

Excel formula to get week number in month (having Monday)

Finding of week number for each date of a month (considering Monday as beginning of the week)

Keep the first date of month contant $B$13

=WEEKNUM(B18,2)-WEEKNUM($B$13,2)+1

WEEKNUM(B18,2) - returns the week number of the date mentioned in cell B18

WEEKNUM($B$13,2) - returns the week number of the 1st date of month in cell B13

C subscripted value is neither array nor pointer nor vector when assigning an array element value

The problem is that arr is not (declared as) a 2D array, and you are treating it as if it were 2D.

Determine which element the mouse pointer is on top of in JavaScript

Demo :D

Move your mouse in the snippet window :D

_x000D_
_x000D_
<script>
document.addEventListener('mouseover', function (e) {
    console.log ("You are in ", e.target.tagName);
});
</script>
_x000D_
_x000D_
_x000D_

How to enable explicit_defaults_for_timestamp?

In your mysql command line do the following:

mysql> SHOW GLOBAL VARIABLES LIKE '%timestamp%';
+---------------------------------+-------+
| Variable_name                   | Value |
+---------------------------------+-------+
| explicit_defaults_for_timestamp | OFF   |
| log_timestamps                  | UTC   |
+---------------------------------+-------+
2 rows in set (0.01 sec)

mysql> SET GLOBAL explicit_defaults_for_timestamp = 1;
Query OK, 0 rows affected (0.00 sec)

mysql> SHOW GLOBAL VARIABLES LIKE '%timestamp%';
+---------------------------------+-------+
| Variable_name                   | Value |
+---------------------------------+-------+
| explicit_defaults_for_timestamp | ON    |
| log_timestamps                  | UTC   |
+---------------------------------+-------+
2 rows in set (0.00 sec)

javascript check for not null

There are 3 ways to check for "not null". My recommendation is to use the Strict Not Version.

1. Strict Not Version

if (val !== null) { ... }

The Strict Not Version uses the "Strict Equality Comparison Algorithm" http://www.ecma-international.org/ecma-262/5.1/#sec-11.9.6. The !== has faster performance, than the != operator because the Strict Equality Comparison Algorithm doesn't typecast values.

2. Non-strict Not Version

if (val != 'null') { ... }

The Non-strict version uses the "Abstract Equality Comparison Algorithm" http://www.ecma-international.org/ecma-262/5.1/#sec-11.9.3. The != has slower performance, than the !== operator because the Abstract Equality Comparison Algorithm typecasts values.

3. Double Not Version

if (!!val) { ... }

The Double Not Version !! has faster performance, than both the Strict Not Version !== and the Non-Strict Not Version != (https://jsperf.com/tfm-not-null/6). However, it will typecast "Falsey" values like undefined and NaN into False (http://www.ecma-international.org/ecma-262/5.1/#sec-9.2) which may lead to unexpected results, and it has worse readability because null isn't explicitly stated.

Finding the handle to a WPF window

you can use :

Process.GetCurrentProcess().MainWindowHandle

Converting JSON String to Dictionary Not List

Here is a simple snippet that read's in a json text file from a dictionary. Note that your json file must follow the json standard, so it has to have " double quotes rather then ' single quotes.

Your JSON dump.txt File:

{"test":"1", "test2":123}

Python Script:

import json
with open('/your/path/to/a/dict/dump.txt') as handle:
    dictdump = json.loads(handle.read())

MySQL SELECT query string matching

Just turn the LIKE around

SELECT * FROM customers
WHERE 'Robert Bob Smith III, PhD.' LIKE CONCAT('%',name,'%')

Selenium Error - The HTTP request to the remote WebDriver timed out after 60 seconds

I had the same exception when trying to run a headless ChromeDriver with a scheduled task on a windows server (unattended). What solved it for me is to run the task as the user "Administrators" (notice the S at the end). What I also did (I don't know if its relevant) is selected the "Any Connection" from the task "Conditions" tab.

What is the garbage collector in Java?

An object becomes eligible for Garbage collection or GC if it's not reachable from any live threads or by any static references.

In other words, you can say that an object becomes eligible for garbage collection if its all references are null. Cyclic dependencies are not counted as the reference so if object A has a reference to object B and object B has a reference to Object A and they don't have any other live reference then both Objects A and B will be eligible for Garbage collection.


Heap Generations for Garbage Collection -

Java objects are created in Heap and Heap is divided into three parts or generations for the sake of garbage collection in Java, these are called as Young(New) generation, Tenured(Old) Generation and Perm Area of the heap.

Java Heap Space New Generation is further divided into three parts known as Eden space, Survivor 1 and Survivor 2 space. When an object first created in heap its gets created in new generation inside Eden space and after subsequent minor garbage collection if an object survives its gets moved to survivor 1 and then survivor 2 before major garbage collection moved that object to old or tenured generation.

Perm space of Java Heap is where JVM stores Metadata about classes and methods, String pool and Class level details.

Heap Generations for Garbage Collection

Refer here for more : Garbage Collection


You can't force JVM to run Garbage Collection though you can make a request using System.gc() or Runtime.gc() method.

In java.lang.System

public static void gc() {
    Runtime.getRuntime().gc();  
}

In java.lang.Runtime

public native void gc();  // note native  method

Mark and Sweep Algorithm -

This is one of the most popular algorithms used by Garbage collection. Any garbage collection algorithm must perform 2 basic operations. One, it should be able to detect all the unreachable objects and secondly, it must reclaim the heap space used by the garbage objects and make the space available again to the program.

The above operations are performed by Mark and Sweep Algorithm in two phases:

  1. Mark phase
  2. Sweep phase

read here for more details - Mark and Sweep Algorithm

How to run Linux commands in Java?

Java Function to bring Linux Command Result!

public String RunLinuxCommand(String cmd) throws IOException {

    String linuxCommandResult = "";
    Process p = Runtime.getRuntime().exec(cmd);

    BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));

    BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));

    try {
        while ((linuxCommandResult = stdInput.readLine()) != null) {

            return linuxCommandResult;
        }
        while ((linuxCommandResult = stdError.readLine()) != null) {
            return "";
        }
    } catch (Exception e) {
        return "";
    }

    return linuxCommandResult;
}

Text-decoration: none not working

Add this statement on your header tag:

<style>
a:link{
  text-decoration: none!important;
  cursor: pointer;
}
</style>

Windows Batch Files: if else

if not %1 == "" (

must be

if not "%1" == "" (

If an argument isn't given, it's completely empty, not even "" (which represents an empty string in most programming languages). So we use the surrounding quotes to detect an empty argument.

Android Transparent TextView?

Below code for black:-

<color name="black">#000000</color>

Now if i want to use opacity than you can use below code :-

 <color name="black">#99000000</color> 

and below for opacity code:-

Hex Opacity Values

100% — FF
95% — F2
90% — E6
85% — D9
80% — CC
75% — BF
70% — B3
65% — A6
60% — 99
55% — 8C
50% — 80
45% — 73
40% — 66
35% — 59
30% — 4D
25% — 40
20% — 33
15% — 26
10% — 1A
5% — 0D
0% — 00

refer Understanding colors on Android (six characters)

Get a list of all threads currently running in Java

Yes, take a look at getting a list of threads. Lots of examples on that page.

That's to do it programmatically. If you just want a list on Linux at least you can just use this command:

kill -3 processid

and the VM will do a thread dump to stdout.

What's the difference between <b> and <strong>, <i> and <em>?

Use them only if using CSS style classes is for any reason unconvinient or impossible (like blog systems, allow only some tags to use in posts and eventually embedded styles). Another reason is support for very old browsers (some mobile devices?) or primitive search engines (that give points for <b> or <strong> tags, instead of analysing CSS styles).

If you can define CSS styles, use them.

I can't install pyaudio on Windows? How to solve "error: Microsoft Visual C++ 14.0 is required."?

There is no wheel (prebuilt package) for Python 3.7 on Windows (there is one for Python 2.7 and 3.4 up to 3.6) so you need to prepare build environment on your PC to use this package. Easier would be finding the wheel for 3.7 as some packages are quite hard to build on Windows.

Christoph Gohlke (University of California) hosts Windows wheels for most popular packages for nearly all modern Python versions, including latest PyAudio. You can find it here: https://www.lfd.uci.edu/~gohlke/pythonlibs/ (download can be quite slow). After download, just type pip install <downloaded file here>.

There is no difference between python -m pip install, and pip install as long as you're using default installation settings and single python installation. python pip actually tries to run file pip in the current directory.

Edit. See the pipwin comment for automated way of using Mr Goblke's libs . Note that I've not used it myself and I'm not sure about selecting different package flavors like vanilla and mkl versions of numpy.

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

You may need to double-check your SSH identities file. You may be guiding BitBucket to look at a different/incorrect private key to the equivalent public key that you have saved on BitBucket.

Check it with tail ~/.ssh/config - you will see something similar to:

Host bitbucket.org
 HostName bitbucket.org
 IdentityFile ~/.ssh/personal-bitbucket-ssh-key

Remember, that adding additional identities (such as work and home) can be done with the ssh-add command, for example:

ssh-keygen -t rsa -C "companyName" -f "companyName"
ssh-add ~/.ssh/companyName

Once you have confirmed which private key is being looked at locally, you can then take your public equivalent, in this case:

cat ~/.ssh/personal-bitbucket-ssh-key.pub | pbcopy

And paste that cipher onto BitBucket. Your git pushes will now (provided you are using the SSH clone as aforementioned answers have pointed out) be allowed without a password, as your device is a recognised friendly.

Hopefully this helps clear it up for someone.

C++ static virtual members?

It is possible. Make two functions: static and virtual

struct Object{     
  struct TypeInformation;
  static  const TypeInformation &GetTypeInformationStatic() const 
  { 
      return GetTypeInformationMain1();
  }
  virtual const TypeInformation &GetTypeInformation() const
  { 
      return GetTypeInformationMain1();
  }
protected:
  static const TypeInformation &GetTypeInformationMain1(); // Main function
};

struct SomeObject : public Object {     
  static  const TypeInformation &GetTypeInformationStatic() const 
  { 
      return GetTypeInformationMain2();
  }
  virtual const TypeInformation &GetTypeInformation() const
  { 
      return GetTypeInformationMain2();
  }
protected:
  static const TypeInformation &GetTypeInformationMain2(); // Main function
};

How to convert / cast long to String?

String strLong = Long.toString(longNumber);

Simple and works fine :-)

Python initializing a list of lists

The problem is that they're all the same exact list in memory. When you use the [x]*n syntax, what you get is a list of n many x objects, but they're all references to the same object. They're not distinct instances, rather, just n references to the same instance.

To make a list of 3 different lists, do this:

x = [[] for i in range(3)]

This gives you 3 separate instances of [], which is what you want

[[]]*n is similar to

l = []
x = []
for i in range(n):
    x.append(l)

While [[] for i in range(3)] is similar to:

x = []
for i in range(n):
    x.append([])   # appending a new list!

In [20]: x = [[]] * 4

In [21]: [id(i) for i in x]
Out[21]: [164363948, 164363948, 164363948, 164363948] # same id()'s for each list,i.e same object


In [22]: x=[[] for i in range(4)]

In [23]: [id(i) for i in x]
Out[23]: [164382060, 164364140, 164363628, 164381292] #different id(), i.e unique objects this time

How to specify preference of library path?

As an alternative, you can use the environment variables LIBRARY_PATH and CPLUS_INCLUDE_PATH, which respectively indicate where to look for libraries and where to look for headers (CPATH will also do the job), without specifying the -L and -I options.

Edit: CPATH includes header with -I and CPLUS_INCLUDE_PATH with -isystem.

Oracle Error ORA-06512

I also had the same error. In my case reason was I have created a update trigger on a table and under that trigger I am again updating the same table. And when I have removed the update statement from the trigger my problem has been resolved.

Extract regression coefficient values

A summary.lm object stores these values in a matrix called 'coefficients'. So the value you are after can be accessed with:

a2Pval <- summary(mg)$coefficients[2, 4]

Or, more generally/readably, coef(summary(mg))["a2","Pr(>|t|)"]. See here for why this method is preferred.

Output ("echo") a variable to a text file

Your sample code seems to be OK. Thus, the root problem needs to be dug up somehow. Let's eliminate chance for typos in the script. First off, make sure you put Set-Strictmode -Version 2.0 in the beginning of your script. This will help you to catch misspelled variable names. Like so,

# Test.ps1
set-strictmode -version 2.0 # Comment this line and no error will be reported.
$foo = "bar"
set-content -path ./test.txt -value $fo # Error! Should be "$foo"

PS C:\temp> .\test.ps1
The variable '$fo' cannot be retrieved because it has not been set.
At C:\temp\test.ps1:3 char:40
+ set-content -path ./test.txt -value $fo <<<<
    + CategoryInfo          : InvalidOperation: (fo:Token) [], RuntimeException
    + FullyQualifiedErrorId : VariableIsUndefined

The next part about question marks sounds like you have a problem with Unicode. What's the output when you type the file with Powershell like so,

$file = "\\server\share\file.txt"
cat $file

The APR based Apache Tomcat Native library was not found on the java.library.path

Regarding the original question asked in the title ...

  • sudo apt-get install libtcnative-1

  • or if you are on RHEL Linux yum install tomcat-native

The documentation states you need http://tomcat.apache.org/native-doc/

  • sudo apt-get install libapr1.0-dev libssl-dev
  • or RHEL yum install apr-devel openssl-devel

How to remove docker completely from ubuntu 14.04

sudo apt-get remove docker docker-engine docker.io containerd runc
sudo rm -rf /var/lib/docker
sudo apt-get autoclean
sudo apt-get update

Recreate the default website in IIS

Follow these Steps Restore your "Default Website" Website :

  1. create a new website
  2. set "Default Website" as its name
  3. In the Binding section (bottom panel), enter your local IP address in the "IP Address" edit.
  4. Keep the "Host" edit empty

How to get selected value of a html select with asp.net

Java script:

use elementid. selectedIndex() function to get the selected index

Excel "External table is not in the expected format."

I had this same issue(Using the ACE.OLEDB) and what resolved it for me was this link:

http://support.microsoft.com/kb/2459087

The gist of it is that installing multiple office versions and various office sdk's, assemblies, etc. had led to the ACEOleDB.dll reference in the registry pointing to the OFFICE12 folder instead of OFFICE14 in

C:\Program Files\Common Files\Microsoft Shared\OFFICE14\ACEOLEDB.DLL

From the link:

Alternatively, you can modify the registry key changing the dll path to match that of your Access version.

Access 2007 should use OFFICE12, Access 2010 - OFFICE14 and Access 2013 - OFFICE15

(OS: 64bit Office: 64bit) or (OS: 32bit Office: 32bit)

Key: HKCR\CLSID{3BE786A0-0366-4F5C-9434-25CF162E475E}\InprocServer32\

Value Name: (Default)

Value Data: C:\Program Files\Common Files\Microsoft Shared\OFFICE14\ACEOLEDB.DLL

(OS: 64bit Office: 32bit)

Key: HKCR\Wow6432Node\CLSID{3BE786A0-0366-4F5C-9434-25CF162E475E}\InprocServer32\

Value Name: (Default)

Value Data: C:\Program Files (x86)\Common Files\Microsoft Shared\OFFICE14\ACEOLEDB.DLL

Copy Image from Remote Server Over HTTP

Use a GET request to download the image and save it to a web accessible directory on your server.

As you are using PHP, you can use curl to download files from the other server.

How do I diff the same file between two different commits on the same branch?

Check $ git log, copy the SHA-1 ID of the two different commits, and run the git diff command with those IDs. for example:

$ git diff (sha-id-one) (sha-id-two)

Line break in SSRS expression

I've always had luck with the Chr(10) & Chr(13) - I have provided a sample below. This is an expression for an address text box I have in a report.

=Iif(Fields!GUAR_STREET_2.Value <> "",Fields!GUAR_STREET.Value & Chr(10) & Chr(13) & LTrim(Fields!GUAR_STREET_2.Value),Fields!GUAR_STREET.Value)

Also, if you are building a string you need to concatenate stuff together with an & not a + Here is what I think your example should look like

    =IIF(First(Fields!VCHTYPE.Value, "Dataset1")="C","This is a huge paragrpah of text." &
Chr(10) & Chr(13) & "separated by line feeds at each paragraph." &
Chr(10) & Chr(13) & Chr(10) & Chr(13) & "I want to separate the paragraphs." &
Chr(10) & Chr(13) &  Chr(10) & Chr(13) & "Its not working though."
, "This is the second huge paragraph of text." &
Chr(10) & Chr(13) & "separated by line feeds at each paragraph." &
Chr(10) & Chr(13) & Chr(10) & Chr(13) & "I want to separate the paragraphs." &
Chr(10) & Chr(13) & Chr(10) & Chr(13) & "Its not working though." )

Round button with text and icon in flutter

Use Column or Row in a Button child, Row for horizontal button, Column for vertical, and dont forget to contain it with the size you need:

Container(
  width: 120.0,
  height: 30.0,
  child: RaisedButton(
    color: Color(0XFFFF0000),
    child: Row(
      children: <Widget>[
        Text('Play this song', style: TextStyle(color: Colors.white),),
        Icon(Icons.play_arrow, color: Colors.white,),
      ],
    ),
  ),
),

Regex match everything after question mark?

Check out this site: http://rubular.com/ Basically the site allows you to enter some example text (what you would be looking for on your site) and then as you build the regular expression it will highlight what is being matched in real time.

Parsing json and searching through it

You can use jsonpipe if you just need the output (and more comfortable with command line):

cat bookmarks.json | jsonpipe |grep uri

How to extend available properties of User.Identity

Whenever you want to extend the properties of User.Identity with any additional properties like the question above, add these properties to the ApplicationUser class first like so:

public class ApplicationUser : IdentityUser
{
    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
    {
        // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
        var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
        // Add custom user claims here
        return userIdentity;
    }

    // Your Extended Properties
    public long? OrganizationId { get; set; }
}

Then what you need is to create an extension method like so (I create mine in an new Extensions folder):

namespace App.Extensions
{
    public static class IdentityExtensions
    {
        public static string GetOrganizationId(this IIdentity identity)
        {
            var claim = ((ClaimsIdentity)identity).FindFirst("OrganizationId");
            // Test for null to avoid issues during local testing
            return (claim != null) ? claim.Value : string.Empty;
        }
    }
}

When you create the Identity in the ApplicationUser class, just add the Claim -> OrganizationId like so:

    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
    {
        // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
        var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
        // Add custom user claims here => this.OrganizationId is a value stored in database against the user
        userIdentity.AddClaim(new Claim("OrganizationId", this.OrganizationId.ToString()));

        return userIdentity;
    }

Once you added the claim and have your extension method in place, to make it available as a property on your User.Identity, add a using statement on the page/file you want to access it:

in my case: using App.Extensions; within a Controller and @using. App.Extensions withing a .cshtml View file.

EDIT:

What you can also do to avoid adding a using statement in every View is to go to the Views folder, and locate the Web.config file in there. Now look for the <namespaces> tag and add your extension namespace there like so:

<add namespace="App.Extensions" />

Save your file and you're done. Now every View will know of your extensions.

You can access the Extension Method:

var orgId = User.Identity.GetOrganizationId();

Android studio- "SDK tools directory is missing"

This was an issue for me because I already had the SDK installed under a different directory. In order to tell Android Studio to where the SDK is you need to get to the settings, but the "SDK tools directory is missing" dialog always exits the whole program when you click "Finish". Here's how I "solved" it:

  1. Delete your ~/.Android* folders (losing all of your settings :/).
  2. Run Android Studio. It will show you a welcome wizard where it tries to download the SDK again (and fails due to my rubbish internet).
  3. Click the X on the wizard window. That will enable you to get to the normal welcome dialog.
  4. Go to Settings->Project Defaults->Project Structure and change the Android SDK location to the correct one.

Deleting the .Android Studio folders may be unnecessary - I never tried pressing the X on the original error dialog - I only tried "Finish" which exits Android Studio. It is possible if you click the X you can get to settings but unfortunately I can't go back and check now.

ValueError: max() arg is an empty sequence

When the length of v will be zero, it'll give you the value error.

You should check the length or you should check the list first whether it is none or not.

if list:
    k.index(max(list))

or

len(list)== 0

Post an object as data using Jquery Ajax

All arrays passed to php must be object literals. Here's an example from JS/jQuery:

var myarray = {};  //must be declared as an object literal first

myarray[fld1] = val;  // then you can add elements and values
myarray[fld2] = val;
myarray[fld3] = Array();  // array assigned to an element must also be declared as object literal

etc...`

It can now be sent via Ajax in the data: parameter as follows:

data: { new_name: myarray },

php picks this up and reads it as a normal array without any decoding necessary. Here's an example:

$array = $_POST['new_name'];  // myarray became new_name (see above)
$fld1 = array['fld1'];
$fld2 = array['fld2'];
etc...

However, when you return an array to jQuery via Ajax it must first be encoded using json. Here's an example in php:

$return_array = json_encode($return_aray));
print_r($return_array);

And the output from that looks something like this:

{"fname":"James","lname":"Feducia","vip":"true","owner":"false","cell_phone":"(801) 666-0909","email":"[email protected]", "contact_pk":"","travel_agent":""}

{again we see the object literal encoding tags} now this can be read by JS/jQuery as an array without any further action inside JS/JQuery... Here's an example in jquery ajax:

success: function(result) {
console.log(result);
alert( "Return Values: " + result['fname'] + " " + result['lname'] );
}

Normalizing images in OpenCV

When you normalize a matrix using NORM_L1, you are dividing every pixel value by the sum of absolute values of all the pixels in the image. As a result, all pixel values become much less than 1 and you get a black image. Try NORM_MINMAX instead of NORM_L1.

@Cacheable key on multiple method arguments

This will work

@Cacheable(value="bookCache", key="#checkwarehouse.toString().append(#isbn.toString())")

Changing font size and direction of axes text in ggplot2

When making many plots, it makes sense to set it globally (relevant part is the second line, three lines together are a working example):

   library('ggplot2')
   theme_update(text = element_text(size=20))
   ggplot(mpg, aes(displ, hwy, colour = class)) + geom_point()

Making PHP var_dump() values display one line per value

Wrap it in <pre> tags to preserve formatting.

E11000 duplicate key error index in mongodb mongoose

I got this same issue when I had the following configuration in my config/models.js

module.exports.models = {
  connection: 'mongodb',
  migrate: 'alter'
}

Changing migrate from 'alter' to 'safe' fixed it for me.

module.exports.models = {
  connection: 'mongodb',
  migrate: 'safe'
}

Accessing clicked element in angularjs

While AngularJS allows you to get a hand on a click event (and thus a target of it) with the following syntax (note the $event argument to the setMaster function; documentation here: http://docs.angularjs.org/api/ng.directive:ngClick):

function AdminController($scope) {    
  $scope.setMaster = function(obj, $event){
    console.log($event.target);
  }
}

this is not very angular-way of solving this problem. With AngularJS the focus is on the model manipulation. One would mutate a model and let AngularJS figure out rendering.

The AngularJS-way of solving this problem (without using jQuery and without the need to pass the $event argument) would be:

<div ng-controller="AdminController">
    <ul class="list-holder">
        <li ng-repeat="section in sections" ng-class="{active : isSelected(section)}">
            <a ng-click="setMaster(section)">{{section.name}}</a>
        </li>
    </ul>
    <hr>
    {{selected | json}}
</div>

where methods in the controller would look like this:

$scope.setMaster = function(section) {
    $scope.selected = section;
}

$scope.isSelected = function(section) {
    return $scope.selected === section;
}

Here is the complete jsFiddle: http://jsfiddle.net/pkozlowski_opensource/WXJ3p/15/

How to use NULL or empty string in SQL

This is ugly MSSQL:

CASE WHEN LTRIM(RTRIM(ISNULL([Address1], ''))) <> '' THEN [Address2] ELSE '' END

Lists in ConfigParser

There is nothing stopping you from packing the list into a delimited string and then unpacking it once you get the string from the config. If you did it this way your config section would look like:

[Section 3]
barList=item1,item2

It's not pretty but it's functional for most simple lists.

How can I format a String number to have commas and round?

public void convert(int s)
{
    System.out.println(NumberFormat.getNumberInstance(Locale.US).format(s));
}

public static void main(String args[])
{
    LocalEx n=new LocalEx();
    n.convert(10000);
}

Calculating the sum of two variables in a batch script

According to this helpful list of operators [an operator can be thought of as a mathematical expression] found here, you can tell the batch compiler that you are manipulating variables instead of fixed numbers by using the += operator instead of the + operator.

Hope I Helped!

XMLHttpRequest cannot load file. Cross origin requests are only supported for HTTP

This error is happening because you are just opening html documents directly from the browser. To fix this you will need to serve your code from a webserver and access it on localhost. If you have Apache setup, use it to serve your files. Some IDE's have built in web servers, like JetBrains IDE's, Eclipse...

If you have Node.Js setup then you can use http-server. Just run npm install http-server -g and you will be able to use it in terminal like http-server C:\location\to\app. Kirill Fuchs

Python threading. How do I lock a thread?

import threading 

# global variable x 
x = 0

def increment(): 
    """ 
    function to increment global variable x 
    """
    global x 
    x += 1

def thread_task(): 
    """ 
    task for thread 
    calls increment function 100000 times. 
    """
    for _ in range(100000): 
        increment() 

def main_task(): 
    global x 
    # setting global variable x as 0 
    x = 0

    # creating threads 
    t1 = threading.Thread(target=thread_task) 
    t2 = threading.Thread(target=thread_task) 

    # start threads 
    t1.start() 
    t2.start() 

    # wait until threads finish their job 
    t1.join() 
    t2.join() 

if __name__ == "__main__": 
    for i in range(10): 
        main_task() 
        print("Iteration {0}: x = {1}".format(i,x))

Configure cron job to run every 15 minutes on Jenkins

It should be,

*/15 * * * *  your_command_or_whatever

Use the auto keyword in C++ STL

If you want a code that is readable by all programmers (c++, java, and others) use the original old form instead of cryptographic new features

atp::ta::DataDrawArrayInfo* ddai;
for(size_t i = 0; i < m_dataDraw->m_dataDrawArrayInfoList.size(); i++) {
    ddai = m_dataDraw->m_dataDrawArrayInfoList[i];
    //...
}

How do I set a variable to the output of a command in Bash?

If the command that you are trying to execute fails, it would write the output onto the error stream and would then be printed out to the console.

To avoid it, you must redirect the error stream:

result=$(ls -l something_that_does_not_exist 2>&1)

Bootstrap push div content to new line

If your your list is dynamically generated with unknown number and your target is to always have last div in a new line set last div class to "col-xl-12" and remove other classes so it will always take a full row.

This is a copy of your code corrected so that last div always occupy a full row (I although removed unnecessary classes).

_x000D_
_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">_x000D_
<div class="grid">_x000D_
  <div class="row">_x000D_
    <div class="col-sm-3">Under me should be a DIV</div>_x000D_
    <div class="col-md-6 col-sm-5">Under me should be a DIV</div>_x000D_
    <div class="col-xl-12">I am the last DIV and I always take a full row for my self!!</div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Looping through rows in a DataView

The DataView object itself is used to loop through DataView rows.

DataView rows are represented by the DataRowView object. The DataRowView.Row property provides access to the original DataTable row.

C#

foreach (DataRowView rowView in dataView)
{
    DataRow row = rowView.Row;
    // Do something //
}

VB.NET

For Each rowView As DataRowView in dataView
    Dim row As DataRow = rowView.Row
    ' Do something '
Next