Programs & Examples On #Import contacts

How to add an event after close the modal window?

If you're using version 3.x of Bootstrap, the correct way to do this now is:

$('#myModal').on('hidden.bs.modal', function (e) {
  // do something...
})

Scroll down to the events section to learn more.

http://getbootstrap.com/javascript/#modals-usage

This appears to remain unchanged for whenever version 4 releases (http://v4-alpha.getbootstrap.com/components/modal/#events), but if it does I'll be sure to update this post with the relevant information.

Stretch horizontal ul to fit width of div

This is the easiest way to do it: http://jsfiddle.net/thirtydot/jwJBd/

(or with table-layout: fixed for even width distribution: http://jsfiddle.net/thirtydot/jwJBd/59/)

This won't work in IE7.

#horizontal-style {
    display: table;
    width: 100%;
    /*table-layout: fixed;*/
}
#horizontal-style li {
    display: table-cell;
}
#horizontal-style a {
    display: block;
    border: 1px solid red;
    text-align: center;
    margin: 0 5px;
    background: #999;
}

Old answer before your edit: http://jsfiddle.net/thirtydot/DsqWr/

How does HttpContext.Current.User.Identity.Name know which usernames exist?

For windows authentication

select your project.

Press F4

Disable "Anonymous Authentication" and enable "Windows Authentication"

enter image description here

Spring-Boot: How do I set JDBC pool properties like maximum number of connections?

Based on your application type/size/load/no. of users ..etc - u can keep following as your production properties

spring.datasource.tomcat.initial-size=50
spring.datasource.tomcat.max-wait=20000
spring.datasource.tomcat.max-active=300
spring.datasource.tomcat.max-idle=150
spring.datasource.tomcat.min-idle=8
spring.datasource.tomcat.default-auto-commit=true

How can I delete a newline if it is the last character in a file?

POSIX SED:

'${/^$/d}'

$ - match last line


{ COMMANDS } - A group of commands may be enclosed between { and } characters. This is particularly useful when you want a group of commands to be triggered by a single address (or address-range) match.

Oracle date format picture ends before converting entire input string

Perhaps you should check NLS_DATE_FORMAT and use the date string conforming the format. Or you can use to_date function within the INSERT statement, like the following:

insert into visit
values(123456, 
       to_date('19-JUN-13', 'dd-mon-yy'),
       to_date('13-AUG-13 12:56 A.M.', 'dd-mon-yyyy hh:mi A.M.'));

Additionally, Oracle DATE stores date and time information together.

Create PDF from a list of images

If your images are plots you created mith matplotlib, you can use matplotlib.backends.backend_pdf.PdfPages (See documentation).

import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages

# generate a list with dummy plots   
figs = []
for i in [-1, 1]:
    fig = plt.figure()
    plt.plot([1, 2, 3], [i*1, i*2, i*3])
    figs.append(fig)

# gerate a multipage pdf:
with PdfPages('multipage_pdf.pdf') as pdf:
    for fig in figs:
        pdf.savefig(fig)
        plt.close()

Service has zero application (non-infrastructure) endpoints

I had this error in a Windows Service when my WCF Service Library that I created was not connected for hosting, but was connected for connection. I was missing an endpoint. (I wanted both connection and hosting in my Windows Service so that I could serve up the WCF Service to other connections, as well as have the main process of my Windows Service use it as well to do various tasks on a timer/schedule.)

The fix was that I rightlcicked my App.config file and chose Edit WCF Configuration. Then, I did the steps for Create Service so that I could connect to my WCF Service. Now I had two endpoints in my App.config, not just one. One endpoint was for the connection to the WCF Service Library, and another was for the hosting of it.

What does the 'export' command do?

In simple terms, environment variables are set when you open a new shell session. At any time if you change any of the variable values, the shell has no way of picking that change. that means the changes you made become effective in new shell sessions. The export command, on the other hand, provides the ability to update the current shell session about the change you made to the exported variable. You don't have to wait until new shell session to use the value of the variable you changed.

Set TextView text from html-formatted string resource in XML

Android does not have a specification to indicate the type of resource string (e.g. text/plain or text/html). There is a workaround, however, that will allow the developer to specify this within the XML file.

  1. Define a custom attribute to specify that the android:text attribute is html.
  2. Use a subclassed TextView.

Once you define these, you can express yourself with HTML in xml files without ever having to call setText(Html.fromHtml(...)) again. I'm rather surprised that this approach is not part of the API.

This solution works to the degree that the Android studio simulator will display the text as rendered HTML.

enter image description here

res/values/strings.xml (the string resource as HTML)

<resources>
<string name="app_name">TextViewEx</string>
<string name="string_with_html"><![CDATA[
       <em>Hello</em> <strong>World</strong>!
 ]]></string>
</resources>

layout.xml (only the relevant parts)

Declare the custom attribute namespace, and add the android_ex:isHtml attribute. Also use the subclass of TextView.

<RelativeLayout
...
xmlns:android_ex="http://schemas.android.com/apk/res-auto"
...>

<tv.twelvetone.samples.textviewex.TextViewEx
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/string_with_html"
    android_ex:isHtml="true"
    />
 </RelativeLayout>

res/values/attrs.xml (define the custom attributes for the subclass)

 <resources>
<declare-styleable name="TextViewEx">
    <attr name="isHtml" format="boolean"/>
    <attr name="android:text" />
</declare-styleable>
</resources>

TextViewEx.java (the subclass of TextView)

 package tv.twelvetone.samples.textviewex;

 import android.content.Context;
 import android.content.res.TypedArray;
 import android.support.annotation.Nullable;
 import android.text.Html;
 import android.util.AttributeSet;
 import android.widget.TextView;

public TextViewEx(Context context, @Nullable AttributeSet attrs) {
    super(context, attrs);
    TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.TextViewEx, 0, 0);
    try {
        boolean isHtml = a.getBoolean(R.styleable.TextViewEx_isHtml, false);
        if (isHtml) {
            String text = a.getString(R.styleable.TextViewEx_android_text);
            if (text != null) {
                setText(Html.fromHtml(text));
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        a.recycle();
    }
}
}

ESLint not working in VS Code?

For me, i did accidentally disable ESLint when some prompt was shown by it.

Doing below steps fixed it for me

  1. Shift + Command + P and select ESLint: Disabled ESLint
  2. Close vscode
  3. Shift + Command + P and select ESLint: Show Output Channel

Where do I find the line number in the Xcode editor?

If you don't want line numbers shown all the time another way to find the line number of a piece of code is to just click in the left-most margin and create a breakpoint (a small blue arrow appears) then go to the breakpoint navigator (?7) where it will list the breakpoint with its line number. You can delete the breakpoint by right clicking on it.

Display Records From MySQL Database using JTable in Java

this is the easy way to do that you just need to download the jar file "rs2xml.jar" add it to your project and do that : 1- creat a connection 2- statment and resultset 3- creat a jtable 4- give the result set to DbUtils.resultSetToTableModel(rs) as define in this methode you well get your jtable so easy.

public void afficherAll(String tableName){
        String sql="select * from "+tableName;
        try {
            stmt=con.createStatement();
            rs=stmt.executeQuery(sql);
            tbContTable.setModel(DbUtils.resultSetToTableModel(rs));
        } catch (SQLException e) {
            // TODO Auto-generated catch block
             JOptionPane.showMessageDialog(null, e);
        }       
    }

Error while trying to run project: Unable to start program. Cannot find the file specified

I had this issue on VS2008: I removed the .suo; .ncb; and user project file, then restarted the solution and it fixed the problem for me.

How can I render Partial views in asp.net mvc 3?

<%= Html.Partial("PartialName", Model) %>

android fragment- How to save states of views in a fragment when another fragment is pushed on top of it

In the end after trying many of these complicated solutions as I only needed to save/restore a single value in my Fragment (the content of an EditText), and although it might not be the most elegant solution, creating a SharedPreference and storing my state there worked for me

Twitter Bootstrap Button Text Word Wrap

You can simply add this class.

.btn {
    white-space:normal !important;
    word-wrap: break-word; 
}

CSS text-align not working

I try to avoid floating elements unless the design really needs it. Because you have floated the <li> they are out of normal flow.

If you add .navigation { text-align:center; } and change .navigation li { float: left; } to .navigation li { display: inline-block; } then entire navigation will be centred.

One caveat to this approach is that display: inline-block; is not supported in IE6 and needs a workaround to make it work in IE7.

Remove all special characters from a string

Here, check out this function:

function seo_friendly_url($string){
    $string = str_replace(array('[\', \']'), '', $string);
    $string = preg_replace('/\[.*\]/U', '', $string);
    $string = preg_replace('/&(amp;)?#?[a-z0-9]+;/i', '-', $string);
    $string = htmlentities($string, ENT_COMPAT, 'utf-8');
    $string = preg_replace('/&([a-z])(acute|uml|circ|grave|ring|cedil|slash|tilde|caron|lig|quot|rsquo);/i', '\\1', $string );
    $string = preg_replace(array('/[^a-z0-9]/i', '/[-]+/') , '-', $string);
    return strtolower(trim($string, '-'));
}

How to check whether a file is empty or not?

import os    
os.path.getsize(fullpathhere) > 0

Way to read first few lines for pandas dataframe

I think you can use the nrows parameter. From the docs:

nrows : int, default None

    Number of rows of file to read. Useful for reading pieces of large files

which seems to work. Using one of the standard large test files (988504479 bytes, 5344499 lines):

In [1]: import pandas as pd

In [2]: time z = pd.read_csv("P00000001-ALL.csv", nrows=20)
CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
Wall time: 0.00 s

In [3]: len(z)
Out[3]: 20

In [4]: time z = pd.read_csv("P00000001-ALL.csv")
CPU times: user 27.63 s, sys: 1.92 s, total: 29.55 s
Wall time: 30.23 s

Chaining Observables in RxJS

About promise composition vs. Rxjs, as this is a frequently asked question, you can refer to a number of previously asked questions on SO, among which :

Basically, flatMap is the equivalent of Promise.then.

For your second question, do you want to replay values already emitted, or do you want to process new values as they arrive? In the first case, check the publishReplay operator. In the second case, standard subscription is enough. However you might need to be aware of the cold. vs. hot dichotomy depending on your source (cf. Hot and Cold observables : are there 'hot' and 'cold' operators? for an illustrated explanation of the concept)

JQuery, select first row of table

jQuery is not necessary, you can use only javascript.

<table id="table">
  <tr>...</tr>
  <tr>...</tr>
  <tr>...</tr>
   ......
  <tr>...</tr>
</table>

The table object has a collection of all rows.

var myTable = document.getElementById('table');
var rows =  myTable.rows;
var firstRow = rows[0];

Child element click event trigger the parent click event

Without jQuery : DEMO

 <div id="parentDiv" onclick="alert('parentDiv');">
   <div id="childDiv" onclick="alert('childDiv');event.cancelBubble=true;">
     AAA
   </div>   
</div>

How can I change Mac OS's default Java VM returned from /usr/libexec/java_home

I actually looked at this a little in the disassembler, since source isn't available.

/usr/bin/java and /usr/libexec/java_home both make use of JavaLaunching.framework. The JAVA_HOME environment variable is indeed checked first by /usr/bin/java and friends (but not /usr/libexec/java_home.) The framework uses the JAVA_VERSION and JAVA_ARCH envirionment variables to filter the available JVMs. So, by default:

$ /usr/libexec/java_home -V
Matching Java Virtual Machines (2):
    11.0.5, x86_64: "Amazon Corretto 11"    /Library/Java/JavaVirtualMachines/amazon-corretto-11.jdk/Contents/Home
    1.8.0_232, x86_64:  "Amazon Corretto 8" /Library/Java/JavaVirtualMachines/amazon-corretto-8.jdk/Contents/Home

/Library/Java/JavaVirtualMachines/amazon-corretto-11.jdk/Contents/Home

But setting, say, JAVA_VERSION can override the default:

$ JAVA_VERSION=1.8 /usr/libexec/java_home
/Library/Java/JavaVirtualMachines/amazon-corretto-8.jdk/Contents/Home

You can also set JAVA_LAUNCHER_VERBOSE=1 to see some additional debug logging as far as search paths, found JVMs, etc., with both /usr/bin/java and /usr/libexec/java_home.

In the past, JavaLaunching.framework actually used the preferences system (under the com.apple.java.JavaPreferences domain) to set the preferred JVM order, allowing the default JVM to be set with PlistBuddy - but as best as I can tell, that code has been removed in recent versions of macOS. Environment variables seem to be the only way (aside from editing the Info.plist in the JDK bundles themselves.)

Setting default environment variables can of course be done through your .profile or via launchd, if you need them be set at a session level.

change values in array when doing foreach

The callback is passed the element, the index, and the array itself.

arr.forEach(function(part, index, theArray) {
  theArray[index] = "hello world";
});

edit — as noted in a comment, the .forEach() function can take a second argument, which will be used as the value of this in each call to the callback:

arr.forEach(function(part, index) {
  this[index] = "hello world";
}, arr); // use arr as this

That second example shows arr itself being set up as this in the callback.One might think that the array involved in the .forEach() call might be the default value of this, but for whatever reason it's not; this will be undefined if that second argument is not provided.

(Note: the above stuff about this does not apply if the callback is a => function, because this is never bound to anything when such functions are invoked.)

Also it's important to remember that there is a whole family of similar utilities provided on the Array prototype, and many questions pop up on Stackoverflow about one function or another such that the best solution is to simply pick a different tool. You've got:

  • forEach for doing a thing with or to every entry in an array;
  • filter for producing a new array containing only qualifying entries;
  • map for making a one-to-one new array by transforming an existing array;
  • some to check whether at least one element in an array fits some description;
  • every to check whether all entries in an array match a description;
  • find to look for a value in an array

and so on. MDN link

how to remove time from datetime

Personally, I'd return the full, native datetime value and format this in the client code.

That way, you can use the user's locale setting to give the correct meaning to that user.

"11/12" is ambiguous. Is it:

  • 12th November
  • 11th December

Check if a number is a perfect square

My answer is:

def is_square(x):
    return x**.5 % 1 == 0

It basically does a square root, then modulo by 1 to strip the integer part and if the result is 0 return True otherwise return False. In this case x can be any large number, just not as large as the max float number that python can handle: 1.7976931348623157e+308

It is incorrect for a large non-square such as 152415789666209426002111556165263283035677490.

dplyr mutate with conditional values

With dplyr 0.7.2, you can use the very useful case_when function :

x=read.table(
 text="V1 V2 V3 V4
 1  1  2  3  5
 2  2  4  4  1
 3  1  4  1  1
 4  4  5  1  3
 5  5  5  5  4")
x$V5 = case_when(x$V1==1 & x$V2!=4 ~ 1,
                 x$V2==4 & x$V3!=1 ~ 2,
                 TRUE ~ 0)

Expressed with dplyr::mutate, it gives:

x = x %>% mutate(
     V5 = case_when(
         V1==1 & V2!=4 ~ 1,
         V2==4 & V3!=1 ~ 2,
         TRUE ~ 0
     )
)

Please note that NA are not treated specially, as it can be misleading. The function will return NA only when no condition is matched. If you put a line with TRUE ~ ..., like I did in my example, the return value will then never be NA.

Therefore, you have to expressively tell case_when to put NA where it belongs by adding a statement like is.na(x$V1) | is.na(x$V3) ~ NA_integer_. Hint: the dplyr::coalesce() function can be really useful here sometimes!

Moreover, please note that NA alone will usually not work, you have to put special NA values : NA_integer_, NA_character_ or NA_real_.

Closing Twitter Bootstrap Modal From Angular Controller

You can do it like this:

angular.element('#modal').modal('hide');

Cycles in family tree software

Instead of removing all assertions, you should still check for things like a person being his/her own parent or other impossible situations and present an error. Maybe issue a warning if it is unlikely so the user can still detect common input errors, but it will work if everything is correct.

I would store the data in a vector with a permanent integer for each person and store the parents and children in person objects where the said int is the index of the vector. This would be pretty fast to go between generations (but slow for things like name searches). The objects would be in order of when they were created.

When to use NSInteger vs. int

You usually want to use NSInteger when you don't know what kind of processor architecture your code might run on, so you may for some reason want the largest possible integer type, which on 32 bit systems is just an int, while on a 64-bit system it's a long.

I'd stick with using NSInteger instead of int/long unless you specifically require them.

NSInteger/NSUInteger are defined as *dynamic typedef*s to one of these types, and they are defined like this:

#if __LP64__ || TARGET_OS_EMBEDDED || TARGET_OS_IPHONE || TARGET_OS_WIN32 || NS_BUILD_32_LIKE_64
typedef long NSInteger;
typedef unsigned long NSUInteger;
#else
typedef int NSInteger;
typedef unsigned int NSUInteger;
#endif

With regard to the correct format specifier you should use for each of these types, see the String Programming Guide's section on Platform Dependencies

How to read an external local JSON file in JavaScript?

I took Stano's excellent answer and wrapped it in a promise. This might be useful if you don't have an option like node or webpack to fall back on to load a json file from the file system:

// wrapped XMLHttpRequest in a promise
const readFileP = (file, options = {method:'get'}) => 
  new Promise((resolve, reject) => {
    let request = new XMLHttpRequest();
    request.onload = resolve;
    request.onerror = reject;
    request.overrideMimeType("application/json");
    request.open(options.method, file, true);
    request.onreadystatechange = () => {
        if (request.readyState === 4 && request.status === "200") {
            resolve(request.responseText);
        }
    };
    request.send(null);
});

You can call it like this:

readFileP('<path to file>')
    .then(d => {
      '<do something with the response data in d.srcElement.response>'
    });

TSQL DATETIME ISO 8601

Gosh, NO!!! You're asking for a world of hurt if you store formatted dates in SQL Server. Always store your dates and times and one of the SQL Server "date/time" datatypes (DATETIME, DATE, TIME, DATETIME2, whatever). Let the front end code resolve the method of display and only store formatted dates when you're building a staging table to build a file from. If you absolutely must display ISO date/time formats from SQL Server, only do it at display time. I can't emphasize enough... do NOT store formatted dates/times in SQL Server.

{Edit}. The reasons for this are many but the most obvious are that, even with a nice ISO format (which is sortable), all future date calculations and searches (search for all rows in a given month, for example) will require at least an implicit conversion (which takes extra time) and if the stored formatted date isn't the format that you currently need, you'll need to first convert it to a date and then to the format you want.

The same holds true for front end code. If you store a formatted date (which is text), it requires the same gyrations to display the local date format defined either by windows or the app.

My recommendation is to always store the date/time as a DATETIME or other temporal datatype and only format the date at display time.

Good font for code presentations?

I do a lot of such presentation and use Monaco for code and Chalkboard for text (within a template that, overall, has only small changes from the Blackboard one supplied with Keynote). Look at any of my presentations' PDFs (e.g. this one) and you can decide whether you like the effect.

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

Add /Q for quiet mode and it should remove the prompt.

HTML - how can I show tooltip ONLY when ellipsis is activated

Here's a pure CSS solution. No need for jQuery. It won't show a tooltip, instead it'll just expand the content to its full length on mouseover.

Works great if you have content that gets replaced. Then you don't have to run a jQuery function every time.

.might-overflow {
    text-overflow: ellipsis;
    overflow : hidden;
    white-space: nowrap;
}

.might-overflow:hover {
    text-overflow: clip;
    white-space: normal;
    word-break: break-all;
}

How to cancel a pull request on github?

GitHub now supports closing a pull request

Basically, you need to do the following steps:

  1. Visit the pull request page
  2. Click on the pull request
  3. Click the "close pull request" button

Example (button on the very bottom):

github close pull request

This way the pull request gets closed (and ignored), without merging it.

onActivityResult is not being called in Fragment

For those who use Android Navigation Component should use in Activity's onActivityResult(...) the primaryNavigationFragment to get it's fragment reference and call fragment's fragment.onActivityResult(...).

Here's Activity's onActivityResult(...)

@Override
public void onActivityResult(int requestCode, int resultCode, Intent imageData)
{
    super.onActivityResult(requestCode, resultCode, imageData);

    for (Fragment fragment : getSupportFragmentManager().getPrimaryNavigationFragment().getChildFragmentManager().getFragments())
    {
            fragment.onActivityResult(requestCode, resultCode, imageData);
    }
}

Is there a difference between x++ and ++x in java?

If it's like many other languages you may want to have a simple try:

i = 0;
if (0 == i++) // if true, increment happened after equality check
if (2 == ++i) // if true, increment happened before equality check

If the above doesn't happen like that, they may be equivalent

cannot call member function without object

You need to instantiate an object in order to call its member functions. The member functions need an object to operate on; they can't just be used on their own. The main() function could, for example, look like this:

int main()
{
   Name_pairs np;
   cout << "Enter names and ages. Use 0 to cancel.\n";
   while(np.test())
   {
      np.read_names();
      np.read_ages();
   }
   np.print();
   keep_window_open();
}

Simple DatePicker-like Calendar

I'm particularly fond of this date picker built for Mootools: http://electricprism.com/aeron/calendar/

It's lovely right out of the box.

Unable to copy ~/.ssh/id_rsa.pub

Try this and it will work like a charm. I was having the same error but this approach did the trick for me:

ssh USER@REMOTE "cat file"|xclip -i

Uploading Images to Server android

use below code it helps you....

        BitmapFactory.Options options = new BitmapFactory.Options();

        options.inSampleSize = 4;
        options.inPurgeable = true;
        Bitmap bm = BitmapFactory.decodeFile("your path of image",options);

        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        bm.compress(Bitmap.CompressFormat.JPEG,40,baos); 


        // bitmap object

        byteImage_photo = baos.toByteArray();

                    //generate base64 string of image

                   String encodedImage =Base64.encodeToString(byteImage_photo,Base64.DEFAULT);

  //send this encoded string to server

Load vs. Stress testing

Wikipedia on load testing (bold is mine):

[...]A load test is usually conducted to understand the behaviour of the system under a specific expected load. This load can be the expected concurrent number of users on the application performing a specific number of transactions within the set duration. This test will give out the response times of all the important business critical transactions.[...]

and on stress testing:

understand the upper limits of capacity within the system. This kind of test is done to determine the system's robustness in terms of extreme load and helps application administrators to determine if the system will perform sufficiently if the current load goes well above the expected maximum.

So the bottom line is: if you are testing normal, expected load (you know the system will be used by up to 100 users at a time), this is load testing. But when you want to determine how the system behaves under extreme load (DoS, Slashdot effect) and when it breaks, this is stress testing.

Comparing two files in linux terminal

Use comm -13 (requires sorted files):

$ cat file1
one
two
three

$ cat file2
one
two
three
four

$ comm -13 <(sort file1) <(sort file2)
four

What does "pending" mean for request in Chrome Developer Window?

I came across this issue when I was debugging a local web application. The issue turned out to be AVG Antivirus and Firewall restrictions. I had to allow an exception through the firewall to get rid of the "Pending" status.

What is the best way to get all the divisors of a number?

I like Greg solution, but I wish it was more python like. I feel it would be faster and more readable; so after some time of coding I came out with this.

The first two functions are needed to make the cartesian product of lists. And can be reused whnever this problem arises. By the way, I had to program this myself, if anyone knows of a standard solution for this problem, please feel free to contact me.

"Factorgenerator" now returns a dictionary. And then the dictionary is fed into "divisors", who uses it to generate first a list of lists, where each list is the list of the factors of the form p^n with p prime. Then we make the cartesian product of those lists, and we finally use Greg' solution to generate the divisor. We sort them, and return them.

I tested it and it seem to be a bit faster than the previous version. I tested it as part of a bigger program, so I can't really say how much is it faster though.

Pietro Speroni (pietrosperoni dot it)

from math import sqrt


##############################################################
### cartesian product of lists ##################################
##############################################################

def appendEs2Sequences(sequences,es):
    result=[]
    if not sequences:
        for e in es:
            result.append([e])
    else:
        for e in es:
            result+=[seq+[e] for seq in sequences]
    return result


def cartesianproduct(lists):
    """
    given a list of lists,
    returns all the possible combinations taking one element from each list
    The list does not have to be of equal length
    """
    return reduce(appendEs2Sequences,lists,[])

##############################################################
### prime factors of a natural ##################################
##############################################################

def primefactors(n):
    '''lists prime factors, from greatest to smallest'''  
    i = 2
    while i<=sqrt(n):
        if n%i==0:
            l = primefactors(n/i)
            l.append(i)
            return l
        i+=1
    return [n]      # n is prime


##############################################################
### factorization of a natural ##################################
##############################################################

def factorGenerator(n):
    p = primefactors(n)
    factors={}
    for p1 in p:
        try:
            factors[p1]+=1
        except KeyError:
            factors[p1]=1
    return factors

def divisors(n):
    factors = factorGenerator(n)
    divisors=[]
    listexponents=[map(lambda x:k**x,range(0,factors[k]+1)) for k in factors.keys()]
    listfactors=cartesianproduct(listexponents)
    for f in listfactors:
        divisors.append(reduce(lambda x, y: x*y, f, 1))
    divisors.sort()
    return divisors



print divisors(60668796879)

P.S. it is the first time I am posting to stackoverflow. I am looking forward for any feedback.

PHP: trying to create a new line with "\n"

$a = 'John' ; <br/>
$b = 'Doe' ; <br/>
$c = $a.$b"&lt;br/>";

Using Ansible set_fact to create a dictionary from register results

Thank you Phil for your solution; in case someone ever gets in the same situation as me, here is a (more complex) variant:

---
# this is just to avoid a call to |default on each iteration
- set_fact:
    postconf_d: {}

- name: 'get postfix default configuration'
  command: 'postconf -d'
  register: command

# the answer of the command give a list of lines such as:
# "key = value" or "key =" when the value is null
- name: 'set postfix default configuration as fact'
  set_fact:
    postconf_d: >
      {{
        postconf_d |
        combine(
          dict([ item.partition('=')[::2]|map('trim') ])
        )
  with_items: command.stdout_lines

This will give the following output (stripped for the example):

"postconf_d": {
    "alias_database": "hash:/etc/aliases", 
    "alias_maps": "hash:/etc/aliases, nis:mail.aliases",
    "allow_min_user": "no", 
    "allow_percent_hack": "yes"
}

Going even further, parse the lists in the 'value':

- name: 'set postfix default configuration as fact'
  set_fact:
    postconf_d: >-
      {% set key, val = item.partition('=')[::2]|map('trim') -%}
      {% if ',' in val -%}
        {% set val = val.split(',')|map('trim')|list -%}
      {% endif -%}
      {{ postfix_default_main_cf | combine({key: val}) }}
  with_items: command.stdout_lines
...
"postconf_d": {
    "alias_database": "hash:/etc/aliases", 
    "alias_maps": [
        "hash:/etc/aliases", 
        "nis:mail.aliases"
    ], 
    "allow_min_user": "no", 
    "allow_percent_hack": "yes"
}

A few things to notice:

  • in this case it's needed to "trim" everything (using the >- in YAML and -%} in Jinja), otherwise you'll get an error like:

    FAILED! => {"failed": true, "msg": "|combine expects dictionaries, got u\"  {u'...
    
  • obviously the {% if .. is far from bullet-proof

  • in the postfix case, val.split(',')|map('trim')|list could have been simplified to val.split(', '), but I wanted to point out the fact you will need to |list otherwise you'll get an error like:

    "|combine expects dictionaries, got u\"{u'...': <generator object do_map at ...
    

Hope this can help.

Recursively looping through an object to build a property list

I'll provide a solution too, using recursion. Commented lines to clarify things.

It works well for its purpose right now.

_x000D_
_x000D_
// works only if the value is a dictionary or something specified below, and adds all keys in nested objects and outputs them

const example = {
  city: "foo",
  year: 2020,
  person: {
    name: "foo",
    age: 20,
    deeper: {
      even_deeper: {
        key: "value", 
        arr: [1, 2, {
          a: 1,
          b: 2
        }]
      }
    }
  },
};

var flat  =  [];    // store keys
var depth =  0;     // depth, used later
var path  =  "obj"; // base path to be added onto, specified using the second parameter of flatKeys 

let flatKeys = (t, name) => {
  path = name ? name : path;  // if specified, set the path 
  for (const k in t) {
    const v = t[k];
    let type = typeof v;      // store the type value's type
    switch (type) {  
      case "string":          // these are the specified cases for which a key will be added,
      case "number":          // specify more if you want
      case "array" :
        flat.push(path + "." + k);  // add the complete path to the array
        break;
      case "object":
        flat.push(path + "." + k)
        path += "." + k;
        flatKeys(v);
        break;
    }
  }
  return flat;
};

let flattened = flatKeys(example, "example"); // the second argument is what the root path should be (for convenience)
console.log(flattened, "keys: " + flattened.length);
_x000D_
_x000D_
_x000D_

ORDER BY using Criteria API

For Hibernate 5.2 and above, use CriteriaBuilder as follows

CriteriaBuilder builder = sessionFactory.getCriteriaBuilder();
CriteriaQuery<Cat> query = builder.createQuery(Cat.class);
Root<Cat> rootCat = query.from(Cat.class);
Join<Cat,Mother> joinMother = rootCat.join("mother");  // <-attribute name
Join<Mother,Kind> joinMotherKind = joinMother.join("kind");
query.select(rootCat).orderBy(builder.asc(joinMotherKind.get("value")));
Query<Cat> q = sessionFactory.getCurrentSession().createQuery(query);
List<Cat> cats = q.getResultList();

How do you create a static class in C++?

Can I write something like static class?

No, according to the C++11 N3337 standard draft Annex C 7.1.1:

Change: In C ++, the static or extern specifiers can only be applied to names of objects or functions. Using these specifiers with type declarations is illegal in C ++. In C, these specifiers are ignored when used on type declarations. Example:

static struct S {    // valid C, invalid in C++
  int i;
};

Rationale: Storage class specifiers don’t have any meaning when associated with a type. In C ++, class members can be declared with the static storage class specifier. Allowing storage class specifiers on type declarations could render the code confusing for users.

And like struct, class is also a type declaration.

The same can be deduced by walking the syntax tree in Annex A.

It is interesting to note that static struct was legal in C, but had no effect: Why and when to use static structures in C programming?

Get a resource using getResource()

One thing to keep in mind is that the relevant path here is the path relative to the file system location of your class... in your case TestGameTable.class. It is not related to the location of the TestGameTable.java file.
I left a more detailed answer here... where is resource actually located

How can I exclude one word with grep?

grep provides '-v' or '--invert-match' option to select non-matching lines.

e.g.

grep -v 'unwanted_pattern' file_name

This will output all the lines from file file_name, which does not have 'unwanted_pattern'.

If you are searching the pattern in multiple files inside a folder, you can use the recursive search option as follows

grep -r 'wanted_pattern' * | grep -v 'unwanted_pattern'

Here grep will try to list all the occurrences of 'wanted_pattern' in all the files from within currently directory and pass it to second grep to filter out the 'unwanted_pattern'. '|' - pipe will tell shell to connect the standard output of left program (grep -r 'wanted_pattern' *) to standard input of right program (grep -v 'unwanted_pattern').

Create an array of integers property in Objective-C

This works

@interface RGBComponents : NSObject {

    float components[8];

}

@property(readonly) float * components;

- (float *) components {
    return components;
}

How to redirect a URL path in IIS?

If you have loads of re-directs to create, having loads of virtual directories over the places is a nightmare to maintain. You could try using ISAPI redirect an IIS extension. Then all you re-directs are managed in one place.

http://www.isapirewrite.com/docs/

It allows also you to match patterns based on reg ex expressions etc. I've used where I've had to re-direct 100's of pages and its saved a lot of time.

Remove table row after clicking table row delete button

As @gaurang171 mentioned, we can use .closest() which will return the first ancestor, or the closest to our delete button, and use .remove() to remove it.

This is how we can implement it using jQuery click event instead of using JavaScript onclick.

HTML:

<table id="myTable">
<tr>
  <th width="30%" style="color:red;">ID</th>
  <th width="25%" style="color:red;">Name</th>
  <th width="25%" style="color:red;">Age</th>
  <th width="1%"></th>
</tr>

<tr>
  <td width="30%" style="color:red;">SSS-001</td>
  <td width="25%" style="color:red;">Ben</td>
  <td width="25%" style="color:red;">25</td>
  <td><button type='button' class='btnDelete'>x</button></td>
</tr>

<tr>
  <td width="30%" style="color:red;">SSS-002</td>
  <td width="25%" style="color:red;">Anderson</td>
  <td width="25%" style="color:red;">47</td>
  <td><button type='button' class='btnDelete'>x</button></td>
</tr>

<tr>
  <td width="30%" style="color:red;">SSS-003</td>
  <td width="25%" style="color:red;">Rocky</td>
  <td width="25%" style="color:red;">32</td>
  <td><button type='button' class='btnDelete'>x</button></td>
</tr>

<tr>
  <td width="30%" style="color:red;">SSS-004</td>
  <td width="25%" style="color:red;">Lee</td>
  <td width="25%" style="color:red;">15</td>
  <td><button type='button' class='btnDelete'>x</button></td>
</tr>
                            

jQuery

 $(document).ready(function(){
     $("#myTable").on('click','.btnDelete',function(){
         $(this).closest('tr').remove();
      });
  });

Try in JSFiddle: click here.

for-in statement

edit 2018: This is outdated, js and typescript now have for..of loops.
http://www.typescriptlang.org/docs/handbook/iterators-and-generators.html


The book "TypeScript Revealed" says

"You can iterate through the items in an array by using either for or for..in loops as demonstrated here:

// standard for loop
for (var i = 0; i < actors.length; i++)
{
  console.log(actors[i]);
}

// for..in loop
for (var actor in actors)
{
  console.log(actor);
}

"

Turns out, the second loop does not pass the actors in the loop. So would say this is plain wrong. Sadly it is as above, loops are untouched by typescript.

map and forEach often help me and are due to typescripts enhancements on function definitions more approachable, lke at the very moment:

this.notes = arr.map(state => new Note(state));

My wish list to TypeScript;

  1. Generic collections
  2. Iterators (IEnumerable, IEnumerator interfaces would be best)

How to define optional methods in Swift protocol?

Here's a very simple example for swift Classes ONLY, and not for structures or enumerations. Note that the protocol method being optional, has two levels of optional chaining at play. Also the class adopting the protocol needs the @objc attribute in its declaration.

@objc protocol CollectionOfDataDelegate{
   optional func indexDidChange(index: Int)
}


@objc class RootView: CollectionOfDataDelegate{

    var data = CollectionOfData()

   init(){
      data.delegate = self
      data.indexIsNow()
   }

  func indexDidChange(index: Int) {
      println("The index is currently: \(index)")
  }

}

class CollectionOfData{
    var index : Int?
    weak var delegate : CollectionOfDataDelegate?

   func indexIsNow(){
      index = 23
      delegate?.indexDidChange?(index!)
    }

 }

Clicking at coordinates without identifying element

If you can see the source code of page, its always the best option to refer to the button by its id or NAME attribute. For example you have button "Login" looking like this:

 <input type="submit" name="login" id="login" />

In that case is best way to do

selenium.click(id="login");

Just out of the curiosity - isnt that HTTP basic authentification? In that case maybe look at this: http://code.google.com/p/selenium/issues/detail?id=34

"insufficient memory for the Java Runtime Environment " message in eclipse

Your application (Eclipse) needs more memory and JVM is not allocating enough.You can increase the amount of memory JVM allocates by following the answers given here

Difference between CR LF, LF and CR line break types?

This is a good summary I found:

The Carriage Return (CR) character (0x0D, \r) moves the cursor to the beginning of the line without advancing to the next line. This character is used as a new line character in Commodore and Early Macintosh operating systems (OS-9 and earlier).

The Line Feed (LF) character (0x0A, \n) moves the cursor down to the next line without returning to the beginning of the line. This character is used as a new line character in UNIX based systems (Linux, Mac OSX, etc)

The End of Line (EOL) sequence (0x0D 0x0A, \r\n) is actually two ASCII characters, a combination of the CR and LF characters. It moves the cursor both down to the next line and to the beginning of that line. This character is used as a new line character in most other non-Unix operating systems including Microsoft Windows, Symbian OS and others.

Source

How to resolve the error "Unable to access jarfile ApacheJMeter.jar errorlevel=1" while initiating Jmeter?

I faced with the same error, when i downloaded the Jmeter Source, and it got fixed once i downloaded Jmeter Binary. Please watch this video.

Manually Triggering Form Validation using jQuery

When there is a very complex (especially asynchronous) validation process, there is a simple workaround:

<form id="form1">
<input type="button" onclick="javascript:submitIfVeryComplexValidationIsOk()" />
<input type="submit" id="form1_submit_hidden" style="display:none" />
</form>
...
<script>
function submitIfVeryComplexValidationIsOk() {
    var form1 = document.forms['form1']
    if (!form1.checkValidity()) {
        $("#form1_submit_hidden").click()
        return
    }

    if (checkForVeryComplexValidation() === 'Ok') {
         form1.submit()
    } else {
         alert('form is invalid')
    }
}
</script>

Transfer data from one HTML file to another

Assuming you are talking about this js in browser environment (unlike others like nodejs), Unfortunately I think what you are trying to do isn't possible simply because this is not the way it is supposed to work.

Html pages are delivered to the browser via HTTP Protocol, which is a 'stateless' protocol. If you still needed to pass values in between pages, there could be 3 approaches:

  1. Session Cookies
  2. HTML5 LocalStorage
  3. POST the variable in the url and retrieve them in next.html via window object

Array of PHP Objects

Arrays can hold pointers so when I want an array of objects I do that.

$a = array();
$o = new Whatever_Class();
$a[] = &$o;
print_r($a);

This will show that the object is referenced and accessible through the array.

Declare and initialize a Dictionary in Typescript

If you want to ignore a property, mark it as optional by adding a question mark:

interface IPerson {
    firstName: string;
    lastName?: string;
}

Using ffmpeg to encode a high quality video

Make sure the PNGs are fully opaque before creating the video

e.g. with imagemagick, give them a black background:

convert 0.png -background black -flatten +matte 0_opaque.png

From my tests, no bitrate or codec is sufficient to make the video look good if you feed ffmpeg PNGs with transparency

Use of Application.DoEvents()

The DoEvents does allow the user to click around or type and trigger other events, and background threads are a better approach.

However, there are still cases where you may run into issues that require flushing event messages. I ran into a problem where the RichTextBox control was ignoring the ScrollToCaret() method when the control had messages in queue to process.

The following code blocks all user input while executing DoEvents:

using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace Integrative.Desktop.Common
{
    static class NativeMethods
    {
        #region Block input

        [DllImport("user32.dll", EntryPoint = "BlockInput")]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool BlockInput([MarshalAs(UnmanagedType.Bool)] bool fBlockIt);

        public static void HoldUser()
        {
            BlockInput(true);
        }

        public static void ReleaseUser()
        {
            BlockInput(false);
        }

        public static void DoEventsBlockingInput()
        {
            HoldUser();
            Application.DoEvents();
            ReleaseUser();
        }

        #endregion
    }
}

Horizontal scroll css?

Just set your width to auto:

#myWorkContent{
    width: auto;
    height:210px;
    border: 13px solid #bed5cd;
    overflow-x: scroll;
    overflow-y: hidden;
    white-space: nowrap;
}

This way your div can be as wide as possible, so you can add as many kitty images as possible ;3

Your div's width will expand based on the child elements it contains.

jsFiddle

iOS Swift - Get the Current Local Time and Date Timestamp

The simple way to create Current TimeStamp. like below,

func generateCurrentTimeStamp () -> String {
    let formatter = DateFormatter()
    formatter.dateFormat = "yyyy_MM_dd_hh_mm_ss"
    return (formatter.string(from: Date()) as NSString) as String
}

Set width to match constraints in ConstraintLayout

If you want TextView in the center of parent..
Your main layout is Constraint Layout

<androidx.appcompat.widget.AppCompatTextView
     android:layout_width="0dp"
     android:layout_height="wrap_content"
     android:text="@string/logout"
     app:layout_constraintLeft_toLeftOf="parent"
     app:layout_constraintRight_toRightOf="parent"
     android:gravity="center">
</androidx.appcompat.widget.AppCompatTextView>

How can you determine a point is between two other points on a line segment?

how about just ensuring that the slope is the same and the point is between the others?

given points (x1, y1) and (x2, y2) ( with x2 > x1) and candidate point (a,b)

if (b-y1) / (a-x1) = (y2-y2) / (x2-x1) And x1 < a < x2

Then (a,b) must be on line between (x1,y1) and (x2, y2)

How to remove ASP.Net MVC Default HTTP Headers?

In Asp.Net Core you can edit the web.config files like so:

<httpProtocol>
  <customHeaders>
    <remove name="X-Powered-By" />
  </customHeaders>
</httpProtocol>

You can remove the server header in the Kestrel options:

            .UseKestrel(c =>
            {
                // removes the server header
                c.AddServerHeader = false;
            }) 

CMake output/build directory

It sounds like you want an out of source build. There are a couple of ways you can create an out of source build.

  1. Do what you were doing, run

    cd /path/to/my/build/folder
    cmake /path/to/my/source/folder
    

    which will cause cmake to generate a build tree in /path/to/my/build/folder for the source tree in /path/to/my/source/folder.

    Once you've created it, cmake remembers where the source folder is - so you can rerun cmake on the build tree with

    cmake /path/to/my/build/folder
    

    or even

    cmake .
    

    if your current directory is already the build folder.

  2. For CMake 3.13 or later, use these options to set the source and build folders

    cmake -B/path/to/my/build/folder -S/path/to/my/source/folder
    
  3. For older CMake, use some undocumented options to set the source and build folders:

    cmake -B/path/to/my/build/folder -H/path/to/my/source/folder
    

    which will do exactly the same thing as (1), but without the reliance on the current working directory.

CMake puts all of its outputs in the build tree by default, so unless you are liberally using ${CMAKE_SOURCE_DIR} or ${CMAKE_CURRENT_SOURCE_DIR} in your cmake files, it shouldn't touch your source tree.

The biggest thing that can go wrong is if you have previously generated a build tree in your source tree (i.e. you have an in source build). Once you've done this the second part of (1) above kicks in, and cmake doesn't make any changes to the source or build locations. Thus, you cannot create an out-of-source build for a source directory with an in-source build. You can fix this fairly easily by removing (at a minimum) CMakeCache.txt from the source directory. There are a few other files (mostly in the CMakeFiles directory) that CMake generates that you should remove as well, but these won't cause cmake to treat the source tree as a build tree.

Since out-of-source builds are often more desirable than in-source builds, you might want to modify your cmake to require out of source builds:

# Ensures that we do an out of source build

MACRO(MACRO_ENSURE_OUT_OF_SOURCE_BUILD MSG)
     STRING(COMPARE EQUAL "${CMAKE_SOURCE_DIR}"
     "${CMAKE_BINARY_DIR}" insource)
     GET_FILENAME_COMPONENT(PARENTDIR ${CMAKE_SOURCE_DIR} PATH)
     STRING(COMPARE EQUAL "${CMAKE_SOURCE_DIR}"
     "${PARENTDIR}" insourcesubdir)
    IF(insource OR insourcesubdir)
        MESSAGE(FATAL_ERROR "${MSG}")
    ENDIF(insource OR insourcesubdir)
ENDMACRO(MACRO_ENSURE_OUT_OF_SOURCE_BUILD)

MACRO_ENSURE_OUT_OF_SOURCE_BUILD(
    "${CMAKE_PROJECT_NAME} requires an out of source build."
)

The above macro comes from a commonly used module called MacroOutOfSourceBuild. There are numerous sources for MacroOutOfSourceBuild.cmake on google but I can't seem to find the original and it's short enough to include here in full.

Unfortunately cmake has usually written a few files by the time the macro is invoked, so although it will stop you from actually performing the build you will still need to delete CMakeCache.txt and CMakeFiles.

You may find it useful to set the paths that binaries, shared and static libraries are written to - in which case see how do I make cmake output into a 'bin' dir? (disclaimer, I have the top voted answer on that question...but that's how I know about it).

jquery to change style attribute of a div class

Try with

$('.handle').css({'left': '300px'});

Instead of

$('.handle').css({'style':'left: 300px'})

Why I can't change directories using "cd"?

While sourcing the script you want to run is one solution, you should be aware that this script then can directly modify the environment of your current shell. Also it is not possible to pass arguments anymore.

Another way to do, is to implement your script as a function in bash.

function cdbm() {
  cd whereever_you_want_to_go
  echo "Arguments to the functions were $1, $2, ..."
}

This technique is used by autojump: http://github.com/joelthelion/autojump/wiki to provide you with learning shell directory bookmarks.

Django Cookies, how can I set them?

Using Django's session framework should cover most scenarios, but Django also now provide direct cookie manipulation methods on the request and response objects (so you don't need a helper function).

Setting a cookie:

def view(request):
  response = HttpResponse('blah')
  response.set_cookie('cookie_name', 'cookie_value')

Retrieving a cookie:

def view(request):
  value = request.COOKIES.get('cookie_name')
  if value is None:
    # Cookie is not set

  # OR

  try:
    value = request.COOKIES['cookie_name']
  except KeyError:
    # Cookie is not set

Merge 2 arrays of objects

If you want to merge the 2 arrays, but remove duplicate objects use this. Duplicates are identified on .uniqueId of each object

function mergeObjectArraysRemovingDuplicates(firstObjectArray, secondObjectArray) {
  return firstObjectArray.concat(
    secondObjectArray.filter((object) => !firstObjectArray.map((x) => x.uniqueId).includes(object.uniqueId)),
  );
}

oracle diff: how to compare two tables?

I used Oracle SQL developer to export the table/s into CSV format and then did the comparison using WinMerge.

How to select all instances of a variable and edit variable name in Sublime

As user1767754 said, the key here is to not make any selection initially.

Just place the cursor inside the variable name, don't double click to select it. For single character variables, place the cursor at the front or end of the variable to not make any selection initially.

Now keep hitting Cmd+D for next variable selection or Ctrl+Cmd+G for selecting all variables at once. It will magically select only the variables.

There has been an error processing your request, Error log record number

I encountered a problem like this and it turns out that I accidentally changed the permission of the var/cache folder. Just delete the cache folder so magento could automatically create the folder with the right permissions.

rm -rf root/var/cache

Cross-thread operation not valid: Control accessed from a thread other than the thread it was created on

Threading Model in UI

Please read the Threading Model in UI applications (old VB link is here) in order to understand basic concepts. The link navigates to page that describes the WPF threading model. However, Windows Forms utilizes the same idea.

The UI Thread

  • There is only one thread (UI thread), that is allowed to access System.Windows.Forms.Control and its subclasses members.
  • Attempt to access member of System.Windows.Forms.Control from different thread than UI thread will cause cross-thread exception.
  • Since there is only one thread, all UI operations are queued as work items into that thread:

enter image description here

enter image description here

BeginInvoke and Invoke methods

enter image description here

Invoke

enter image description here

BeginInvoke

enter image description here

Code solution

Read answers on question How to update the GUI from another thread in C#?. For C# 5.0 and .NET 4.5 the recommended solution is here.

Reading and writing binary file

Here is a short example, the C++ way using rdbuf. I got this from the web. I can't find my original source on this:

#include <fstream>
#include <iostream>

int main () 
{
  std::ifstream f1 ("C:\\me.txt",std::fstream::binary);

  std::ofstream f2 ("C:\\me2.doc",std::fstream::trunc|std::fstream::binary);

  f2<<f1.rdbuf();

  return 0;
}

How to specify the download location with wget?

Make sure you have the URL correct for whatever you are downloading. First of all, URLs with characters like ? and such cannot be parsed and resolved. This will confuse the cmd line and accept any characters that aren't resolved into the source URL name as the file name you are downloading into.

For example:

wget "sourceforge.net/projects/ebosse/files/latest/download?source=typ_redirect"

will download into a file named, ?source=typ_redirect.

As you can see, knowing a thing or two about URLs helps to understand wget.

I am booting from a hirens disk and only had Linux 2.6.1 as a resource (import os is unavailable). The correct syntax that solved my problem downloading an ISO onto the physical hard drive was:

wget "(source url)" -O (directory where HD was mounted)/isofile.iso" 

One could figure the correct URL by finding at what point wget downloads into a file named index.html (the default file), and has the correct size/other attributes of the file you need shown by the following command:

wget "(source url)"

Once that URL and source file is correct and it is downloading into index.html, you can stop the download (ctrl + z) and change the output file by using:

-O "<specified download directory>/filename.extension"

after the source url.

In my case this results in downloading an ISO and storing it as a binary file under isofile.iso, which hopefully mounts.

How do I increase memory on Tomcat 7 when running as a Windows Service?

The answer to my own question is, I think, to use tomcat7.exe:

cd $CATALINA_HOME
.\bin\service.bat install tomcat
.\bin\tomcat7.exe //US//tomcat7 --JvmMs=512 --JvmMx=1024 --JvmSs=1024

Also, you can launch the UI tool mentioned by BalusC without the system tray or using the installer with tomcat7w.exe

.\bin\tomcat7w.exe //ES//tomcat

An additional note to this:

Setting the --JvmXX parameters (through the UI tool or the command line) may not be enough. You may also need to specify the JVM memory values explicitly. From the command line it may look like this:

bin\tomcat7w.exe //US//tomcat7 --JavaOptions=-Xmx=1024;-Xms=512;..

Be careful not to override the other JavaOption values. You can try updating bin\service.bat or use the UI tool and append the java options (separate each value with a new line).

How do I capture response of form.submit

You can accomplish this using jQuery and the ajax() method:

_x000D_
_x000D_
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>_x000D_
<script language="javascript" type="text/javascript">_x000D_
function submitform() {_x000D_
      $.ajax({_x000D_
        headers: { _x000D_
          'Accept': 'application/json',_x000D_
          'Content-Type': 'application/json' _x000D_
        },_x000D_
        type: "POST",_x000D_
        url : "/hello.hello",_x000D_
        dataType : "json",_x000D_
        data : JSON.stringify({"hello_name": "hello"}),_x000D_
        error: function () {_x000D_
          alert('loading Ajax failure');_x000D_
        },_x000D_
     onFailure: function () {_x000D_
          alert('Ajax Failure');_x000D_
     },_x000D_
     statusCode: {_x000D_
          404: function() {_x000D_
          alert("missing info");_x000D_
          }   _x000D_
     },_x000D_
        success : function (response) {_x000D_
          alert("The server says: " + JSON.stringify(response));_x000D_
        }_x000D_
      })_x000D_
      .done(function( data ) {_x000D_
        $("#result").text(data['hello']);_x000D_
      });_x000D_
};</script>
_x000D_
_x000D_
_x000D_

How to redirect to logon page when session State time out is completed in asp.net mvc

I discover very simple way to redirect Login Page When session end in MVC. I have already tested it and this works without problems.

In short, I catch session end in _Layout 1 minute before and make redirection.

I try to explain everything step by step.

If we want to session end 30 minute after and redirect to loginPage see this steps:

  1. Change the web config like this (set 31 minute):

     <system.web>
        <sessionState timeout="31"></sessionState>
     </system.web>
    
  2. Add this JavaScript in _Layout (when session end 1 minute before this code makes redirect, it makes count time after user last action, not first visit on site)

    <script>
        //session end 
        var sessionTimeoutWarning = @Session.Timeout- 1;
    
        var sTimeout = parseInt(sessionTimeoutWarning) * 60 * 1000;
        setTimeout('SessionEnd()', sTimeout);
    
        function SessionEnd() {
            window.location = "/Account/LogOff";
        }
    </script>
    
  3. Here is my LogOff Action, which makes only LogOff and redirect LoginIn Page

    public ActionResult LogOff()
    {
        Session["User"] = null; //it's my session variable
        Session.Clear();
        Session.Abandon();
        FormsAuthentication.SignOut(); //you write this when you use FormsAuthentication
        return RedirectToAction("Login", "Account");
    } 
    

I hope this is a very useful code for you.

How to copy a selection to the OS X clipboard

Depending on which version of Vim I use, I'm able to use the + register to access the clipboard.

"Mac OS X clipboard sharing" may have some ideas that work for you as well.

How do I test if a recordSet is empty? isNull?

RecordCount is what you want to use.

If Not temp_rst1.RecordCount > 0 ...

Programmatically saving image to Django ImageField

Super easy if model hasn't been created yet:

First, copy your image file to the upload path (assumed = 'path/' in following snippet).

Second, use something like:

class Layout(models.Model):
    image = models.ImageField('img', upload_to='path/')

layout = Layout()
layout.image = "path/image.png"
layout.save()

tested and working in django 1.4, it might work also for an existing model.

How can I add a Google search box to my website?

Sorry for replying on an older question, but I would like to clarify the last question.

You use a "get" method for your form. When the name of your input-field is "g", it will make a URL like this:

https://www.google.com/search?g=[value from input-field]

But when you search with google, you notice the following URL:

https://www.google.nl/search?q=google+search+bar

Google uses the "q" Querystring variable as it's search-query. Therefor, renaming your field from "g" to "q" solved the problem.

How to convert String into Hashmap in java

You can do it in single line, for any object type not just Map.

(Since I use Gson quite liberally, I am sharing a Gson based approach)

Gson gson = new Gson();    
Map<Object,Object> attributes = gson.fromJson(gson.toJson(value),Map.class);

What it does is:

  1. gson.toJson(value) will serialize your object into its equivalent Json representation.
  2. gson.fromJson will convert the Json string to specified object. (in this example - Map)

There are 2 advantages with this approach:

  1. The flexibility to pass an Object instead of String to toJson method.
  2. You can use this single line to convert to any object even your own declared objects.

How do I align a number like this in C?

Why is printf("%8d\n", intval); not working for you? It should...

You did not show the format strings for any of your "not working" examples, so I'm not sure what else to tell you.

#include <stdio.h>

int
main(void)
{
        int i;
        for (i = 1; i <= 10000; i*=10) {
                printf("[%8d]\n", i);
        }
        return (0);
}

$ ./printftest
[       1]
[      10]
[     100]
[    1000]
[   10000]

EDIT: response to clarification of question:

#include <math.h>
int maxval = 1000;
int width = round(1+log(maxval)/log(10));
...
printf("%*d\n", width, intval);

The width calculation computes log base 10 + 1, which gives the number of digits. The fancy * allows you to use the variable for a value in the format string.

You still have to know the maximum for any given run, but there's no way around that in any language or pencil & paper.

Setting background images in JFrame

import javax.swing.*;

import java.awt.*;

import java.awt.event.*;

class BackgroundImageJFrame extends JFrame
{

    JButton b1;
    JLabel l1;

    public BackgroundImageJFrame() {

        setSize(400,400);
        setVisible(true);

        setLayout(new BorderLayout());

        JLabel background=new JLabel(new ImageIcon("C:\\Users\\Computer\\Downloads\\colorful_design.png"));

        add(background);

        background.setLayout(new FlowLayout());

        l1=new JLabel("Here is a button");
        b1=new JButton("I am a button");

        background.add(l1);
        background.add(b1);
    }

    public static void main(String args[]) 
    {
        new BackgroundImageJFrame();
    }
}

check out the below link

http://java-demos.blogspot.in/2012/09/setting-background-image-in-jframe.html

Get the week start date and week end date from week number

Here is a DATEFIRST agnostic solution:

SET DATEFIRST 4     /* or use any other weird value to test it */
DECLARE @d DATETIME

SET @d = GETDATE()

SELECT
  @d ThatDate,
  DATEADD(dd, 0 - (@@DATEFIRST + 5 + DATEPART(dw, @d)) % 7, @d) Monday,
  DATEADD(dd, 6 - (@@DATEFIRST + 5 + DATEPART(dw, @d)) % 7, @d) Sunday

Excel VBA date formats

Format converts the values to strings. IsDate still returns true because it can parse that string and get a valid date.

If you don't want to change the cells to string, don't use Format. (IOW, don't convert them to strings in the first place.) Use the Cell.NumberFormat, and set it to the date format you want displayed.

ActiveCell.NumberFormat = "mm/dd/yy"   ' Outputs 10/28/13
ActiveCell.NumberFormat = "dd/mm/yyyy" ' Outputs 28/10/2013

How to generate Entity Relationship (ER) Diagram of a database using Microsoft SQL Server Management Studio?

  1. Go to Sql Server Management Studio >
  2. Object Explorer >
  3. Databases >
  4. Choose and expand your Database.
  5. Under your database right click on "Database Diagrams" and select "New Database Diagram".
  6. It will a open a new window. Choose tables to include in ER-Diagram (to select multiple tables press "ctrl" or "shift" button and select tables).
  7. Click add.
  8. Wait for it to complete. Done!

You can save generated diagram for future use.

screenshot

Get value of a string after last slash in JavaScript

When I know the string is going to be reasonably short then I use the following one liner... (remember to escape backslashes)

// if str is C:\windows\file system\path\picture name.jpg
alert( str.split('\\').pop() );

alert pops up with picture name.jpg

How do I increase the contrast of an image in Python OpenCV

I would like to suggest a method using the LAB color channel. Wikipedia has enough information regarding what the LAB color channel is about.

I have done the following using OpenCV 3.0.0 and python:

import cv2

#-----Reading the image-----------------------------------------------------
img = cv2.imread('Dog.jpg', 1)
cv2.imshow("img",img) 

#-----Converting image to LAB Color model----------------------------------- 
lab= cv2.cvtColor(img, cv2.COLOR_BGR2LAB)
cv2.imshow("lab",lab)

#-----Splitting the LAB image to different channels-------------------------
l, a, b = cv2.split(lab)
cv2.imshow('l_channel', l)
cv2.imshow('a_channel', a)
cv2.imshow('b_channel', b)

#-----Applying CLAHE to L-channel-------------------------------------------
clahe = cv2.createCLAHE(clipLimit=3.0, tileGridSize=(8,8))
cl = clahe.apply(l)
cv2.imshow('CLAHE output', cl)

#-----Merge the CLAHE enhanced L-channel with the a and b channel-----------
limg = cv2.merge((cl,a,b))
cv2.imshow('limg', limg)

#-----Converting image from LAB Color model to RGB model--------------------
final = cv2.cvtColor(limg, cv2.COLOR_LAB2BGR)
cv2.imshow('final', final)

#_____END_____#

You can run the code as it is. To know what CLAHE (Contrast Limited Adaptive Histogram Equalization)is about, you can again check Wikipedia.

What does the ^ (XOR) operator do?

Another application for XOR is in circuits. It is used to sum bits.

When you look at a truth table:

 x | y | x^y
---|---|-----
 0 | 0 |  0     // 0 plus 0 = 0 
 0 | 1 |  1     // 0 plus 1 = 1
 1 | 0 |  1     // 1 plus 0 = 1
 1 | 1 |  0     // 1 plus 1 = 0 ; binary math with 1 bit

You can notice that the result of XOR is x added with y, without keeping track of the carry bit, the carry bit is obtained from the AND between x and y.

x^y // is actually ~xy + ~yx
    // Which is the (negated x ANDed with y) OR ( negated y ANDed with x ).

How to check if file already exists in the folder

Dim SourcePath As String = "c:\SomeFolder\SomeFileYouWantToCopy.txt" 'This is just an example string and could be anything, it maps to fileToCopy in your code.
Dim SaveDirectory As string = "c:\DestinationFolder"

Dim Filename As String = System.IO.Path.GetFileName(SourcePath) 'get the filename of the original file without the directory on it
Dim SavePath As String = System.IO.Path.Combine(SaveDirectory, Filename) 'combines the saveDirectory and the filename to get a fully qualified path.

If System.IO.File.Exists(SavePath) Then
   'The file exists
Else
    'the file doesn't exist
End If

Show constraints on tables command

The main problem with the validated answer is you'll have to parse the output to get the informations. Here is a query allowing you to get them in a more usable manner :

SELECT cols.TABLE_NAME, cols.COLUMN_NAME, cols.ORDINAL_POSITION,
cols.COLUMN_DEFAULT, cols.IS_NULLABLE, cols.DATA_TYPE,
    cols.CHARACTER_MAXIMUM_LENGTH, cols.CHARACTER_OCTET_LENGTH,
    cols.NUMERIC_PRECISION, cols.NUMERIC_SCALE,
    cols.COLUMN_TYPE, cols.COLUMN_KEY, cols.EXTRA,
    cols.COLUMN_COMMENT, refs.REFERENCED_TABLE_NAME, refs.REFERENCED_COLUMN_NAME,
    cRefs.UPDATE_RULE, cRefs.DELETE_RULE,
    links.TABLE_NAME, links.COLUMN_NAME,
    cLinks.UPDATE_RULE, cLinks.DELETE_RULE
FROM INFORMATION_SCHEMA.`COLUMNS` as cols
LEFT JOIN INFORMATION_SCHEMA.`KEY_COLUMN_USAGE` AS refs
ON refs.TABLE_SCHEMA=cols.TABLE_SCHEMA
    AND refs.REFERENCED_TABLE_SCHEMA=cols.TABLE_SCHEMA
    AND refs.TABLE_NAME=cols.TABLE_NAME
    AND refs.COLUMN_NAME=cols.COLUMN_NAME
LEFT JOIN INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS AS cRefs
ON cRefs.CONSTRAINT_SCHEMA=cols.TABLE_SCHEMA
    AND cRefs.CONSTRAINT_NAME=refs.CONSTRAINT_NAME
LEFT JOIN INFORMATION_SCHEMA.`KEY_COLUMN_USAGE` AS links
ON links.TABLE_SCHEMA=cols.TABLE_SCHEMA
    AND links.REFERENCED_TABLE_SCHEMA=cols.TABLE_SCHEMA
    AND links.REFERENCED_TABLE_NAME=cols.TABLE_NAME
    AND links.REFERENCED_COLUMN_NAME=cols.COLUMN_NAME
LEFT JOIN INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS AS cLinks
ON cLinks.CONSTRAINT_SCHEMA=cols.TABLE_SCHEMA
    AND cLinks.CONSTRAINT_NAME=links.CONSTRAINT_NAME
WHERE cols.TABLE_SCHEMA=DATABASE()
    AND cols.TABLE_NAME="table"

How to check if a table exists in a given schema

For PostgreSQL 9.3 or less...Or who likes all normalized to text

Three flavors of my old SwissKnife library: relname_exists(anyThing), relname_normalized(anyThing) and relnamechecked_to_array(anyThing). All checks from pg_catalog.pg_class table, and returns standard universal datatypes (boolean, text or text[]).

/**
 * From my old SwissKnife Lib to your SwissKnife. License CC0.
 * Check and normalize to array the free-parameter relation-name.
 * Options: (name); (name,schema), ("schema.name"). Ignores schema2 in ("schema.name",schema2).
 */
CREATE FUNCTION relname_to_array(text,text default NULL) RETURNS text[] AS $f$
     SELECT array[n.nspname::text, c.relname::text]
     FROM   pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace,
            regexp_split_to_array($1,'\.') t(x) -- not work with quoted names
     WHERE  CASE
              WHEN COALESCE(x[2],'')>'' THEN n.nspname = x[1]      AND c.relname = x[2]
              WHEN $2 IS NULL THEN           n.nspname = 'public'  AND c.relname = $1
              ELSE                           n.nspname = $2        AND c.relname = $1
            END
$f$ language SQL IMMUTABLE;

CREATE FUNCTION relname_exists(text,text default NULL) RETURNS boolean AS $wrap$
  SELECT EXISTS (SELECT relname_to_array($1,$2))
$wrap$ language SQL IMMUTABLE;

CREATE FUNCTION relname_normalized(text,text default NULL,boolean DEFAULT true) RETURNS text AS $wrap$
  SELECT COALESCE(array_to_string(relname_to_array($1,$2), '.'), CASE WHEN $3 THEN '' ELSE NULL END)
$wrap$ language SQL IMMUTABLE;

How to get the current time in Python

import datetime
date_time = str(datetime.datetime.now()).split()
date,time = date_time

date will print date and time will print time.

cordova run with ios error .. Error code 65 for command: xcodebuild with args:

In my case it was the app icon PNG file... I mean, it took 1 day to go from the provided error

Error code 65 for command: xcodebuild with args:

to the human-readable one:

"the PNG file icon is no good for the picky Apple Xcode"

Pretty Printing a pandas dataframe

A simple approach is to output as html, which pandas does out of the box:

df.to_html('temp.html')

How to make an ng-click event conditional?

We can add ng-click event conditionally without using disabled class.

HTML:

<div ng-repeat="object in objects">
<span ng-click="!object.status && disableIt(object)">{{object.value}}</span>
</div>

submit a form in a new tab

It is also possible to use the new button attribute called formtarget that was introduced with HTML5.

<form>
  <input type="submit" formtarget="_blank"/>
</form>

CSS fixed width in a span

Unfortunately inline elements (or elements having display:inline) ignore the width property. You should use floating divs instead:

<style type="text/css">
div.f1 { float: left; width: 20px; }
div.f2 { float: left; }
div.f3 { clear: both; }
</style>

<div class="f1"></div><div class="f2">The Lazy dog</div><div class="f3"></div>
<div class="f1">AND</div><div class="f2">The Lazy cat</div><div class="f3"></div>
<div class="f1">OR</div><div class="f2">The active goldfish</div><div class="f3"></div>

Now I see you need to use spans and lists, so we need to rewrite this a little bit:

<html><head>
<style type="text/css">
        span.f1 { display: block; float: left; clear: left; width: 60px; }
    li { list-style-type: none; }
    </style>

</head><body>
<ul>
<li><span class="f1">&nbsp;</span>The lazy dog.</li>
<li><span class="f1">AND</span> The lazy cat.</li>
<li><span class="f1">OR</span> The active goldfish.</li>
</ul>
</body>
</html>

Doctrine and LIKE query

you can also do it like that :

$ver = $em->getRepository('GedDocumentBundle:version')->search($val);

$tail = sizeof($ver);

Dead simple example of using Multiprocessing Queue, Pool and Locking

The best solution for your problem is to utilize a Pool. Using Queues and having a separate "queue feeding" functionality is probably overkill.

Here's a slightly rearranged version of your program, this time with only 2 processes coralled in a Pool. I believe it's the easiest way to go, with minimal changes to original code:

import multiprocessing
import time

data = (
    ['a', '2'], ['b', '4'], ['c', '6'], ['d', '8'],
    ['e', '1'], ['f', '3'], ['g', '5'], ['h', '7']
)

def mp_worker((inputs, the_time)):
    print " Processs %s\tWaiting %s seconds" % (inputs, the_time)
    time.sleep(int(the_time))
    print " Process %s\tDONE" % inputs

def mp_handler():
    p = multiprocessing.Pool(2)
    p.map(mp_worker, data)

if __name__ == '__main__':
    mp_handler()

Note that mp_worker() function now accepts a single argument (a tuple of the two previous arguments) because the map() function chunks up your input data into sublists, each sublist given as a single argument to your worker function.

Output:

Processs a  Waiting 2 seconds
Processs b  Waiting 4 seconds
Process a   DONE
Processs c  Waiting 6 seconds
Process b   DONE
Processs d  Waiting 8 seconds
Process c   DONE
Processs e  Waiting 1 seconds
Process e   DONE
Processs f  Waiting 3 seconds
Process d   DONE
Processs g  Waiting 5 seconds
Process f   DONE
Processs h  Waiting 7 seconds
Process g   DONE
Process h   DONE

Edit as per @Thales comment below:

If you want "a lock for each pool limit" so that your processes run in tandem pairs, ala:

A waiting B waiting | A done , B done | C waiting , D waiting | C done, D done | ...

then change the handler function to launch pools (of 2 processes) for each pair of data:

def mp_handler():
    subdata = zip(data[0::2], data[1::2])
    for task1, task2 in subdata:
        p = multiprocessing.Pool(2)
        p.map(mp_worker, (task1, task2))

Now your output is:

 Processs a Waiting 2 seconds
 Processs b Waiting 4 seconds
 Process a  DONE
 Process b  DONE
 Processs c Waiting 6 seconds
 Processs d Waiting 8 seconds
 Process c  DONE
 Process d  DONE
 Processs e Waiting 1 seconds
 Processs f Waiting 3 seconds
 Process e  DONE
 Process f  DONE
 Processs g Waiting 5 seconds
 Processs h Waiting 7 seconds
 Process g  DONE
 Process h  DONE

number several equations with only one number

First of all, you probably don't want the align environment if you have only one column of equations. In fact, your example is probably best with the cases environment. But to answer your question directly, used the aligned environment within equation - this way the outside environment gives the number:

\begin{equation}
  \begin{aligned}
  w^T x_i + b &\geq 1-\xi_i &\text{ if }& y_i=1,  \\
  w^T x_i + b &\leq -1+\xi_i & \text{ if } &y_i=-1,
  \end{aligned}
\end{equation}

The documentation of the amsmath package explains this and more.

How to add icon to mat-icon-button

the above CSS can be written in SASS as follows (and it actually includes all button types, instead of just button.mat-button)

button,
a {
    &.mat-button,
    &.mat-raised-button,
    &.mat-flat-button,
    &.mat-stroked-button {
        .mat-icon {
            vertical-align: top;
            font-size: 1.25em;
        }
    }
}

List<Object> and List<?>

List<Object> object = new List<Object>();

You cannot do this because List is an interface and you cannot create object of any interface or in other word you cannot instantiate any interface. Moreover, you can assign any object of class which implements List to its reference variable. For example you can do this:

list<Object> object = new ArrayList<Object>();

Here ArrayList is a class which implements List, you can use any class which implements List.

How to get the title of HTML page with JavaScript?

Can use getElementsByTagName

var x = document.getElementsByTagName("title")[0];

alert(x.innerHTML)

// or

alert(x.textContent)

// or

document.querySelector('title')

Edits as suggested by Paul

Max retries exceeded with URL in requests

What happened here is that itunes server refuses your connection (you're sending too many requests from same ip address in short period of time)

Max retries exceeded with url: /in/app/adobe-reader/id469337564?mt=8

error trace is misleading it should be something like "No connection could be made because the target machine actively refused it".

There is an issue at about python.requests lib at Github, check it out here

To overcome this issue (not so much an issue as it is misleading debug trace) you should catch connection related exceptions like so:

try:
    page1 = requests.get(ap)
except requests.exceptions.ConnectionError:
    r.status_code = "Connection refused"

Another way to overcome this problem is if you use enough time gap to send requests to server this can be achieved by sleep(timeinsec) function in python (don't forget to import sleep)

from time import sleep

All in all requests is awesome python lib, hope that solves your problem.

How to resolve TypeError: Cannot convert undefined or null to object

Replace

if (typeof obj === 'undefined') { return undefined;} // return undefined for undefined
if (obj === 'null') { return null;} // null unchanged

with

if (obj === undefined) { return undefined;} // return undefined for undefined 
if (obj === null) { return null;} // null unchanged

spark submit add multiple jars in classpath

if you are using properties file you can add following line there:

spark.jars=jars/your_jar1.jar,...

assuming that

<your root from where you run spark-submit>
  |
  |-jars
      |-your_jar1.jar

String length in bytes in JavaScript

Years passed and nowadays you can do it natively

(new TextEncoder().encode('foo')).length

Note that it's not supported by IE (you may use a polyfill for that).

MDN documentation

Standard specifications

Count number of cells with any value (string or number) in a column in Google Docs Spreadsheet

Shorter and dealing with a column (entire, not just a section of a column):

=COUNTA(A:A)

COUNTA

Beware, a cell containing just a space would be included in the count.

Writing numerical values on the plot with Matplotlib

Use pyplot.text() (import matplotlib.pyplot as plt)

import matplotlib.pyplot as plt

x=[1,2,3]
y=[9,8,7]

plt.plot(x,y)
for a,b in zip(x, y): 
    plt.text(a, b, str(b))
plt.show()

Easy way to make a confirmation dialog in Angular?

In order to reuse a single confirmation dialog implementation in a multi-module application, the dialog must be implemented in a separate module. Here's one way of doing this with Material Design and FxFlex, though both of those can be trimmed back or replaced.

First the shared module (./app.module.ts):

import {NgModule} from '@angular/core';
import {CommonModule} from '@angular/common';
import {MatDialogModule, MatSelectModule} from '@angular/material';
import {ConfirmationDlgComponent} from './confirmation-dlg.component';
import {FlexLayoutModule} from '@angular/flex-layout';

@NgModule({
   imports: [
      CommonModule,
      FlexLayoutModule,
      MatDialogModule
   ],
   declarations: [
      ConfirmationDlgComponent
   ],
   exports: [
      ConfirmationDlgComponent
   ],
   entryComponents: [ConfirmationDlgComponent]
})

export class SharedModule {
}

And the dialog component (./confirmation-dlg.component.ts):

import {Component, Inject} from '@angular/core';
import {MAT_DIALOG_DATA} from '@angular/material';

@Component({
   selector: 'app-confirmation-dlg',
   template: `
      <div fxLayoutAlign="space-around" class="title colors" mat-dialog-title>{{data.title}}</div>
      <div class="msg" mat-dialog-content>
         {{data.msg}}
      </div>
      <a href="#"></a>
      <mat-dialog-actions fxLayoutAlign="space-around">
         <button mat-button [mat-dialog-close]="false" class="colors">No</button>
         <button mat-button [mat-dialog-close]="true" class="colors">Yes</button>
      </mat-dialog-actions>`,
   styles: [`
      .title {font-size: large;}
      .msg {font-size: medium;}
      .colors {color: white; background-color: #3f51b5;}
      button {flex-basis: 60px;}
   `]
})
export class ConfirmationDlgComponent {
   constructor(@Inject(MAT_DIALOG_DATA) public data: any) {}
}

Then we can use it in another module:

import {FlexLayoutModule} from '@angular/flex-layout';
import {NgModule} from '@angular/core';
import {GeneralComponent} from './general/general.component';
import {NgbModule} from '@ng-bootstrap/ng-bootstrap';
import {CommonModule} from '@angular/common';
import {MaterialModule} from '../../material.module';

@NgModule({
   declarations: [
      GeneralComponent
   ],
   imports: [
      FlexLayoutModule,
      MaterialModule,
      CommonModule,
      NgbModule.forRoot()
   ],
   providers: []
})
export class SystemAdminModule {}

The component's click handler uses the dialog:

import {Component} from '@angular/core';
import {ConfirmationDlgComponent} from '../../../shared/confirmation-dlg.component';
import {MatDialog} from '@angular/material';

@Component({
   selector: 'app-general',
   templateUrl: './general.component.html',
   styleUrls: ['./general.component.css']
})
export class GeneralComponent {

   constructor(private dialog: MatDialog) {}

   onWhateverClick() {
      const dlg = this.dialog.open(ConfirmationDlgComponent, {
         data: {title: 'Confirm Whatever', msg: 'Are you sure you want to whatever?'}
      });

      dlg.afterClosed().subscribe((whatever: boolean) => {
         if (whatever) {
            this.whatever();
         }
      });
   }

   whatever() {
      console.log('Do whatever');
   }
}

Just using the this.modal.open(MyComponent); as you did won't return you an object whose events you can subscribe to which is why you can't get it to do something. This code creates and opens a dialog whose events we can subscribe to.

If you trim back the css and html this is really a simple component, but writing it yourself gives you control over its design and layout whereas a pre-written component will need to be much more heavyweight to give you that control.

Convert JSONObject to Map

The best way to convert it to HashMap<String, Object> is this:

HashMap<String, Object> result = new ObjectMapper().readValue(jsonString, new TypeReference<Map<String, Object>>(){}));

Automatically size JPanel inside JFrame

If the BorderLayout option provided by our friends doesnot work, try adding ComponentListerner to the JFrame and implement the componentResized(event) method. When the JFrame object will be resized, this method will be called. So if you write the the code to set the size of the JPanel in this method, you will achieve the intended result.

Ya, I know this 'solution' is not good but use it as a safety net. ;)

Can we instantiate an abstract class?

Just observations you could make:

  1. Why poly extends my? This is useless...
  2. What is the result of the compilation? Three files: my.class, poly.class and poly$1.class
  3. If we can instantiate an abstract class like that, we can instantiate an interface too... weird...


Can we instantiate an abstract class?

No, we can't. What we can do is, create an anonymous class (that's the third file) and instantiate it.


What about a super class instantiation?

The abstract super class is not instantiated by us but by java.

EDIT: Ask him to test this

public static final void main(final String[] args) {
    final my m1 = new my() {
    };
    final my m2 = new my() {
    };
    System.out.println(m1 == m2);

    System.out.println(m1.getClass().toString());
    System.out.println(m2.getClass().toString());

}

output is:

false
class my$1
class my$2

How do I change the database name using MySQL?

Follow bellow steps:

shell> mysqldump -hlocalhost -uroot -p  database1  > dump.sql

mysql> CREATE DATABASE database2;

shell> mysql -hlocalhost -uroot -p database2 < dump.sql

If you want to drop database1 otherwise leave it.

mysql> DROP DATABASE database1;

Note : shell> denote command prompt and mysql> denote mysql prompt.

How do you add an SDK to Android Studio?

I followed almost the same instructions by @Mason G. Zhwiti , but had to instead navigate to this folder to find the SDK:

/Users/{my-username}/Library/Android/sdk

I'm using Android Studio v1.2.2 on Mac OS

JSTL if tag for equal strings

I think the other answers miss one important detail regarding the property name to use in the EL expression. The rules for converting from the method names to property names are specified in 'Introspector.decpitalize` which is part of the java bean standard:

This normally means converting the first character from upper case to lower case, but in the (unusual) special case when there is more than one character and both the first and second characters are upper case, we leave it alone.

Thus "FooBah" becomes "fooBah" and "X" becomes "x", but "URL" stays as "URL".

So in your case the JSTL code should look like the following, note the capital 'P':

<c:if test = "${ansokanInfo.PSystem == 'NAT'}">

MySQL Workbench not displaying query results

I had the same problem after upgrading to Ubuntu 14.10. I found this link which describes the steps to be followed in order to apply the patch. It takes a while since you have to start all over again: downloading, building, installing... but it worked for me! Sorry I'm not an expert and I can't provide further details.

Here are the steps described in the link above:

If you want to patch and build mysql-workbench yourself, get the source from for 6.2.3. From the directory you downloaded it to, do:

wget 'http://dev.mysql.com/get/Downloads/MySQLGUITools/mysql-workbench-community-6.2.3-src.tar.gz'

tar xvf mysql-workbench-community-6.2.3-src.tar.gz && cd mysql-workbench-community-6.2.3-src

wget -O patch-glib.diff 'http://bugs.mysql.com/file.php?id=21874&bug_id=74147'

patch -p0 < patch-glib.diff

sudo apt-get build-dep mysql-workbench

sudo apt-get install libgdal-dev

cd build

cmake .. -DBUILD_CONFIG=mysql_release

make

sudo make install

Hope this can be helpful.

Remove Trailing Spaces and Update in Columns in SQL Server

I had the same problem after extracting data from excel file using ETL and finaly i found solution there :

https://www.codeproject.com/Tips/330787/LTRIM-RTRIM-doesn-t-always-work

hope it helps ;)

Accessing an SQLite Database in Swift

I've created an elegant SQLite library written completely in Swift called SwiftData.

Some of its feature are:

  • Bind objects conveniently to the string of SQL
  • Support for transactions and savepoints
  • Inline error handling
  • Completely thread safe by default

It provides an easy way to execute 'changes' (e.g. INSERT, UPDATE, DELETE, etc.):

if let err = SD.executeChange("INSERT INTO Cities (Name, Population, IsWarm, FoundedIn) VALUES ('Toronto', 2615060, 0, '1793-08-27')") {
    //there was an error during the insert, handle it here
} else {
    //no error, the row was inserted successfully
}

and 'queries' (e.g. SELECT):

let (resultSet, err) = SD.executeQuery("SELECT * FROM Cities")
if err != nil {
    //there was an error during the query, handle it here
} else {
    for row in resultSet {
        if let name = row["Name"].asString() {
            println("The City name is: \(name)")
        }
        if let population = row["Population"].asInt() {
            println("The population is: \(population)")
        }
        if let isWarm = row["IsWarm"].asBool() {
            if isWarm {
                println("The city is warm")
            } else {
                println("The city is cold")
            }
        }
        if let foundedIn = row["FoundedIn"].asDate() {
            println("The city was founded in: \(foundedIn)")
        }
    }
}

Along with many more features!

You can check it out here

Copy existing project with a new name in Android Studio

This is a combination nt.bas's answer and step 9 of Civic's answer with visual examples because it took me a while to find out what was intended since I am new to Android Studio. It has been tested in Android Studio 3.2.1.

  1. Open the project you want to clone in Android Studio. (In this example, the old project name was test5 and the new project name was test6)

  2. In the left file-overview pane, click: Project (where it might currently say android).

fig0

  1. Right mouse button click on the project within the file explorer pane and click refactor>clone.

fig1

  1. Change the "New name" to your new project name and click ok.

fig2

  1. File>open>New window>Select your new project>Open in new project window. In the new window, wait until the bottom line of Android studio is finished/says:"Gradle Sync Finished".

16

17

14

  1. In the file overview pane and right mouse button click (RMB) on: app.java/< your old project name (not the test one, not the androidTest one, just the blank one)>

fig8

  1. Enter the new name of your package and select both checkmarks, click refactor.

fig9 fig10

  1. In the bottom left bar click "Do refactor".

fig12

  1. Open app/res/values/strings.xml and change name of the old project (e.g. test5) to the new name of the project in line:

    <string name="app_name">test5</string>
    

fig3

  1. Open Gradle scripts/build.gradle (Module:app) and change the line to the same line with your new project name:%fig4

    applicationId "com.example.a.test5"    
    

fig4

  1. A yellow line will appear at the top of your code pane, requesting gradle sync. Press "sync now".

fig5

  1. in top bar, press build>Clean project.

fig13

  1. If it says "Gradle build finished" in the bottom left, you click "Build>Rebuild project".

fig14

fig15

  1. Now you should be able to compile and run your project again (if it worked in the first place).

Get Image Height and Width as integer values?

Like this :

imageCreateFromPNG($var);
//I don't know where from you get your image, here it's in the png case
// and then :
list($width, $height) = getimagesize($image);
echo $width;
echo $height;

Is it possible to have multiple statements in a python lambda expression?

There actually is a way you can use multiple statements in lambda. Here's my solution:

lst = [[567,345,234],[253,465,756, 2345],[333,777,111, 555]]

x = lambda l: exec("l.sort(); return l[1]")

map(x, lst)

gradient descent using python and numpy

Below you can find my implementation of gradient descent for linear regression problem.

At first, you calculate gradient like X.T * (X * w - y) / N and update your current theta with this gradient simultaneously.

  • X: feature matrix
  • y: target values
  • w: weights/values
  • N: size of training set

Here is the python code:

import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
import random

def generateSample(N, variance=100):
    X = np.matrix(range(N)).T + 1
    Y = np.matrix([random.random() * variance + i * 10 + 900 for i in range(len(X))]).T
    return X, Y

def fitModel_gradient(x, y):
    N = len(x)
    w = np.zeros((x.shape[1], 1))
    eta = 0.0001

    maxIteration = 100000
    for i in range(maxIteration):
        error = x * w - y
        gradient = x.T * error / N
        w = w - eta * gradient
    return w

def plotModel(x, y, w):
    plt.plot(x[:,1], y, "x")
    plt.plot(x[:,1], x * w, "r-")
    plt.show()

def test(N, variance, modelFunction):
    X, Y = generateSample(N, variance)
    X = np.hstack([np.matrix(np.ones(len(X))).T, X])
    w = modelFunction(X, Y)
    plotModel(X, Y, w)


test(50, 600, fitModel_gradient)
test(50, 1000, fitModel_gradient)
test(100, 200, fitModel_gradient)

test1 test2 test2

Append values to query string

Note you can add the Microsoft.AspNetCore.WebUtilities nuget package from Microsoft and then use this to append values to query string:

QueryHelpers.AddQueryString(longurl, "action", "login1")
QueryHelpers.AddQueryString(longurl, new Dictionary<string, string> { { "action", "login1" }, { "attempts", "11" } });

Elegant solution for line-breaks (PHP)

Because you are outputting to the browser, you have to use <br/>. Otherwise there is \n and \r or both combined.

Disabled form fields not submitting data

We can also use the readonly only with below attributes -

readonly onclick='return false;'

This is because if we will only use the readonly then radio buttons will be editable. To avoid this situation we can use readonly with above combination. It will restrict the editing and element's values will also passed during form submission.

Removing index column in pandas when reading a csv

df.reset_index(drop=True, inplace=True)

MySql Error: 1364 Field 'display_name' doesn't have default value

MySQL is most likely in STRICT mode, which isn't necessarily a bad thing, as you'll identify bugs/issues early and not just blindly think everything is working as you intended.

Change the column to allow null:

ALTER TABLE `x` CHANGE `display_name` `display_name` TEXT NULL

or, give it a default value as empty string:

ALTER TABLE `x` CHANGE `display_name` `display_name` TEXT NOT NULL DEFAULT ''

How to log Apache CXF Soap Request and Soap Response using Log4j?

cxf.xml

<cxf:bus>
    <cxf:ininterceptors>
        <ref bean="loggingInInterceptor" />
    </cxf:ininterceptors>
    <cxf:outinterceptors>
        <ref bean="logOutInterceptor" />
    </cxf:outinterceptors>
</cxf:bus>

org.apache.cxf.Logger

org.apache.cxf.common.logging.Log4jLogger

Please check screenshot here

Downloading Java JDK on Linux via wget is shown license page instead

Here's how to get the command yourself. This works for any version:

  1. Access packages page here: https://www.oracle.com/java/technologies/javase-jdk11-downloads.html
  2. Click the download link for your desired package
  3. Check the box indicating that you have "reviewed and accept..."
  4. Right-click & Copy the link address from the button
  5. Paste into a text editor and then copy everything AFTER 'nexturl=', beginning with 'https://'
  6. Update the download URL in this command and you should be good to go:

    wget --no-check-certificate -c --header "Cookie: oraclelicense=accept-securebackup-cookie" https://download.oracle.com/otn/java/jdk/11.0.6+8/90eb79fb590d45c8971362673c5ab495/jdk-11.0.6_linux-x64_bin.tar.gz

To further explain the wget, the --no-check-certificate should be clear enough, but the header content (for any call) is discoverable by using the Developer Tools Network Tab in your browser. The developer tools are powerful and are well worth the time to learn. Enjoy.

PHP Unset Array value effect on other indexes

The keys are maintained with the removed key missing but they can be rearranged by doing this:

$array = array(1,2,3,4,5);
unset($array[2]);
$arranged = array_values($array);
print_r($arranged);

Outputs:

Array
(
    [0] => 1
    [1] => 2
    [2] => 4
    [3] => 5
)

Notice that if we do the following without rearranging:

unset($array[2]);
$array[]=3;

The index of the value 3 will be 5 because it will be pushed to the end of the array and will not try to check or replace missing index. This is important to remember when using FOR LOOP with index access.

How can I compare strings in C using a `switch` statement?

Assuming little endianness and sizeof(char) == 1, you could do that (something like this was suggested by MikeBrom).

char* txt = "B1";
int tst = *(int*)txt;
if ((tst & 0x00FFFFFF) == '1B')
    printf("B1!\n");

It could be generalized for BE case.

How to Store Historical Data

Just wanted to add an option that I started using because I use Azure SQL and the multiple table thing was way too cumbersome for me. I added an insert/update/delete trigger on my table and then converted the before/after change to json using the "FOR JSON AUTO" feature.

 SET @beforeJson = (SELECT * FROM DELETED FOR JSON AUTO)
SET @afterJson = (SELECT * FROM INSERTED FOR JSON AUTO)

That returns a JSON representation fo the record before/after the change. I then store those values in a history table with a timestamp of when the change occurred (I also store the ID for current record of concern). Using the serialization process, I can control how data is backfilled in the case of changes to schema.

I learned about this from this link here

How to cherry pick a range of commits and merge into another branch?

Are you sure you don't want to actually merge the branches? If the working branch has some recent commits you don't want, you can just create a new branch with a HEAD at the point you want.

Now, if you really do want to cherry-pick a range of commits, for whatever reason, an elegant way to do this is to just pull of a patchset and apply it to your new integration branch:

git format-patch A..B
git checkout integration
git am *.patch

This is essentially what git-rebase is doing anyway, but without the need to play games. You can add --3way to git-am if you need to merge. Make sure there are no other *.patch files already in the directory where you do this, if you follow the instructions verbatim...

How to deal with "data of class uneval" error from ggplot2?

when you add a new data set to a geom you need to use the data= argument. Or put the arguments in the proper order mapping=..., data=.... Take a look at the arguments for ?geom_line.

Thus:

p + geom_line(data=df.last, aes(HrEnd, MWh, group=factor(Date)), color="red") 

Or:

p + geom_line(aes(HrEnd, MWh, group=factor(Date)), df.last, color="red") 

java collections - keyset() vs entrySet() in map

Traversal over the large map entrySet() is much better than the keySet(). Check this tutorial how they optimise the traversal over the large object with the help of entrySet() and how it helps for performance tuning.

How can I delay a :hover effect in CSS?

For a more aesthetic appearance :) can be:

left:-9999em; 
top:-9999em; 

position for .sNv2 .nav UL can be replaced by z-index:-1 and z-index:1 for .sNv2 .nav LI:Hover UL

Docker Error bind: address already in use

Before it was running on :docker run -d --name oracle -p 1521:1521 -p 5500:5500 qa/oracle I just changed the port to docker run -d --name oracle -p 1522:1522 -p 5500:5500 qa/oracle

it worked fine for me !

Choose folders to be ignored during search in VS Code

Forget aboves for vscode exclude search pattern, try to below pattern it is working for any folder in vscode last version!

!../../../locales/*

for example i have searched like below vscode example clude settings

files to include: *.js

files to exclude: **/node_modules,!../../../locales/,!../../../theme/,!../../admin/client/*

Split array into two parts without for loop in java

You can use System.arraycopy().

int[] source = new int[1000];

int[] part1 = new int[500];
int[] part2 = new int[500];

//              (src   , src-offset  , dest , offset, count)
System.arraycopy(source, 0           , part1, 0     , part1.length);
System.arraycopy(source, part1.length, part2, 0     , part2.length);

java.math.BigInteger cannot be cast to java.lang.Long

It's a very old post, but if it benefits anyone, we can do something like this:

Long max=((BigInteger) Collections.max(dynamics)).longValue(); 

Bridged networking not working in Virtualbox under Windows 10

Go to your net card. Go to properties and then "Add service", which? This: VirtualBox NDIS6 Bridged Networking Driver

Reopen Virtual Box

using if else with eval in aspx page

You can try c#

public string ProcessMyDataItem(object myValue)
 {
  if (myValue == null)
   {
   return "0 %"";
  }
   else
  {
     if(Convert.ToInt32(myValue) < 50)
       return "0";
     else
      return myValue.ToString() + "%";
  }

 }

asp

 <div class="tooltip" style="display: none">                                                                  
      <div style="text-align: center; font-weight: normal">
   Value =<%# ProcessMyDataItem(Eval("Percentage")) %> </div>
 </div>

How do I loop through a date range?

I have a Range class in MiscUtil which you could find useful. Combined with the various extension methods, you could do:

foreach (DateTime date in StartDate.To(EndDate).ExcludeEnd()
                                   .Step(DayInterval.Days())
{
    // Do something with the date
}

(You may or may not want to exclude the end - I just thought I'd provide it as an example.)

This is basically a ready-rolled (and more general-purpose) form of mquander's solution.

What does the Java assert keyword do, and when should it be used?

Assertions are used to check post-conditions and "should never fail" pre-conditions. Correct code should never fail an assertion; when they trigger, they should indicate a bug (hopefully at a place that is close to where the actual locus of the problem is).

An example of an assertion might be to check that a particular group of methods is called in the right order (e.g., that hasNext() is called before next() in an Iterator).

Always pass weak reference of self into block in ARC?

I totally agree with @jemmons:

But this should not be the default pattern you follow when dealing with blocks that call self! This should only be used to break what would otherwise be a retain cycle between self and the block. If you were to adopt this pattern everywhere, you'd run the risk of passing a block to something that got executed after self was deallocated.

//SUSPICIOUS EXAMPLE:
__weak MyObject *weakSelf = self;
[[SomeOtherObject alloc] initWithCompletion:^{
  //By the time this gets called, "weakSelf" might be nil because it's not  retained!
  [weakSelf doSomething];
}];

To overcome this problem one can define a strong reference over the weakSelf inside the block:

__weak MyObject *weakSelf = self;
[[SomeOtherObject alloc] initWithCompletion:^{
  MyObject *strongSelf = weakSelf;
  [strongSelf doSomething];
}];

Call a url from javascript

var req ;

// Browser compatibility check          
if (window.XMLHttpRequest) {
   req = new XMLHttpRequest();
    } else if (window.ActiveXObject) {

 try {
   req = new ActiveXObject("Msxml2.XMLHTTP");
 } catch (e) {

   try {
     req = new ActiveXObject("Microsoft.XMLHTTP");
   } catch (e) {}
 }

}


var req = new XMLHttpRequest();
req.open("GET", "test.html",true);
req.onreadystatechange = function () {
    //document.getElementById('divTxt').innerHTML = "Contents : " + req.responseText;
}

req.send(null);

Migration: Cannot add foreign key constraint

You can directly pass boolean parameter in integer column saying that it should be unsigned or not. In laravel 5.4 following code solved my problem.

        $table->integer('user_id', false, true);

Here second parameter false represents that it should not be auto-incrementing and third parameter true represents that it should be unsigned. You can keep foreign key constraint in same migration or separate it. It works on both.

Xampp MySQL not starting - "Attempting to start MySQL service..."

In Windows, you should go: Start > Run > services.msc > Apache 2.4 > Properties > Start Mode > Automatic > Apply > Start > OK > [Same as MySQL]

How do I check if an integer is even or odd?

int isOdd(int i){
  return(i % 2);
}

done.

Can we add div inside table above every <tr>?

You can not use tag to make group of more than one tag. If you want to make group of tag for any purpose like in ajax to change particular group or in CSS to change style of particular tag etc. then use

Ex.

<table>
  <tbody id="foods">
    <tr>
      <td>Group 1</td>
    </tr>
    <tr>
      <td>Group 1</td>
    </tr>
  </tbody>

  <tbody id="drinks">
    <tr>
      <td>Group 2</td>
    </tr>
    <tr>
      <td>Group 2</td>
    </tr>
  </tbody>
</table>

A message body writer for Java type, class myPackage.B, and MIME media type, application/octet-stream, was not found

This can also happen if you've recently upgraded Ant. I was using Ant 1.8.4 on a project, and upgraded Ant to 1.9.4, and started to get this error when building a fat jar using Ant.

The solution for me was to downgrade back to Ant 1.8.4 for the command line and Eclipse using the process detailed here

How to remove unused imports from Eclipse

You can direct use the shortcut by pressing Ctrl+Shift+O

Mongodb find() query : return only unique values (no duplicates)

I think you can use db.collection.distinct(fields,query)

You will be able to get the distinct values in your case for NetworkID.

It should be something like this :

Db.collection.distinct('NetworkID')

How to make html table vertically scrollable

I fought with this one for a while. My goal was to have a table with headers where the widths of the each header column was the the same as the corresponding body column and was the minimum size necessary to fit the data. also the body data was scrollable underneath header.

I solved this by using divs and not tables. Each "table" was a div with the header being a div of divs and the body being a div of divs. I used the style as indicated by @sushil above. I added a bit of javascript/jQuery to balance the columns. Maybe 20-30 lines.

Unfortunately I lost the code and have to rebuild it. I know this is a bit old, but maybe it will help someone else.

How to get full file path from file name?

Directory.GetCurrentDirectory

string dirpath = Directory.GetCurrentDirectory();

Prepend this dirpath to the filename to get the complete path.

As @Dan Puzey indicated in the comments, it would be better to use Path.Combine

Path.Combine(Directory.GetCurrentDirectory(), filename)

Could not find module "@angular-devkit/build-angular"

From the ionic forum this worked for me.

npm i @ionic/angular-toolkit@latest

How to use a class from one C# project with another C# project

If you have two projects in one solution folder.Just add the Reference of the Project into another.using the Namespace you can get the classes. While Creating the object for that the requried class. Call the Method which you want.

FirstProject:

class FirstClass()
{
   public string Name()
   {
      return "James";
   }
}

Here add reference to the Second Project

SecondProject:

class SeccondClass
{
    FirstProject.FirstClass obj=new FirstProject.FirstClass();
    obj.Name();
}

Difference between Constructor and ngOnInit

I think the best example would be using services. Let's say that I want to grab data from my server when my component gets 'Activated'. Let's say that I also want to do some additional things to the data after I get it from the server, maybe I get an error and want to log it differently.

It is really easy with ngOnInit over a constructor, it also limits how many callback layers I need to add to my application.

For Example:

export class Users implements OnInit{

    user_list: Array<any>;

    constructor(private _userService: UserService){
    };

    ngOnInit(){
        this.getUsers();
    };

    getUsers(){
        this._userService.getUsersFromService().subscribe(users =>  this.user_list = users);
    };


}

with my constructor I could just call my _userService and populate my user_list, but maybe I want to do some extra things with it. Like make sure everything is upper_case, I am not entirely sure how my data is coming through.

So it makes it much easier to use ngOnInit.

export class Users implements OnInit{

    user_list: Array<any>;

    constructor(private _userService: UserService){
    };

    ngOnInit(){
        this.getUsers();
    };

    getUsers(){
        this._userService.getUsersFromService().subscribe(users =>  this.user_list = users);
        this.user_list.toUpperCase();
    };


}

It makes it much easier to see, and so I just call my function within my component when I initialize instead of having to dig for it somewhere else. Really it's just another tool you can use to make it easier to read and use in the future. Also I find it really bad practice to put function calls within a constructor!

PuTTY scripting to log onto host

For me it works this way:

putty -ssh [email protected] 22 -pw password

putty, protocol, user name @ ip address port and password. To connect in less than a second.

Determine which MySQL configuration file is being used

I installed mysql use brew install mysql

mysqld --verbose --help | less

And it shows:

enter image description here

Forms authentication timeout vs sessionState timeout

      <sessionState timeout="2" />
      <authentication mode="Forms">
          <forms name="userLogin" path="/" timeout="60" loginUrl="Login.aspx" slidingExpiration="true"/>
      </authentication>

This configuration sends me to the login page every two minutes, which seems to controvert the earlier answers

How to write inside a DIV box with javascript

You can use one of the following methods:

document.getElementById('log').innerHTML = "text";

document.getElementById('log').innerText = "text";

document.getElementById('log').textContent = "text";

For Jquery:

$("#log").text("text");

$("#log").html("text");

Get the Year/Month/Day from a datetime in php?

Check out the manual: http://www.php.net/manual/en/datetime.format.php

<?php
$date = new DateTime('2000-01-01');
echo $date->format('Y-m-d H:i:s');
?>

Will output: 2000-01-01 00:00:00

paint() and repaint() in Java

Difference between Paint() and Repaint() method

Paint():

This method holds instructions to paint this component. Actually, in Swing, you should change paintComponent() instead of paint(), as paint calls paintBorder(), paintComponent() and paintChildren(). You shouldn't call this method directly, you should call repaint() instead.

Repaint():

This method can't be overridden. It controls the update() -> paint() cycle. You should call this method to get a component to repaint itself. If you have done anything to change the look of the component, but not its size ( like changing color, animating, etc. ) then call this method.

Is it possible to have a default parameter for a mysql stored procedure?

Unfortunately, MySQL doesn't support DEFAULT parameter values, so:

CREATE PROCEDURE `blah`
(
  myDefaultParam int DEFAULT 0
)
BEGIN
  -- Do something here
END

returns the error:

ERROR 1064 (42000): You have an error in your SQL syntax; check the manual
that corresponds to your MySQL server version for the right syntax to use 
near 'DEFAULT 0) BEGIN END' at line 3

To work around this limitation, simply create additional procedures that assign default values to the original procedure:

DELIMITER //

DROP PROCEDURE IF EXISTS blah//
DROP PROCEDURE IF EXISTS blah2//
DROP PROCEDURE IF EXISTS blah1//
DROP PROCEDURE IF EXISTS blah0//

CREATE PROCEDURE blah(param1 INT UNSIGNED, param2 INT UNSIGNED)
BEGIN
    SELECT param1, param2;
END;
//

CREATE PROCEDURE blah2(param1 INT UNSIGNED, param2 INT UNSIGNED)
BEGIN
    CALL blah(param1, param2);
END;
//

CREATE PROCEDURE blah1(param1 INT UNSIGNED)
BEGIN
    CALL blah2(param1, 3);
END;
//

CREATE PROCEDURE blah0()
BEGIN
    CALL blah1(4);
END;
//

Then, running this:

CALL blah(1, 1);
CALL blah2(2, 2);
CALL blah1(3);
CALL blah0();

will return:

+--------+--------+
| param1 | param2 |
+--------+--------+
|      1 |      1 |
+--------+--------+
1 row in set (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

+--------+--------+
| param1 | param2 |
+--------+--------+
|      2 |      2 |
+--------+--------+
1 row in set (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

+--------+--------+
| param1 | param2 |
+--------+--------+
|      3 |      3 |
+--------+--------+
1 row in set (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

+--------+--------+
| param1 | param2 |
+--------+--------+
|      4 |      3 |
+--------+--------+
1 row in set (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

Then, if you make sure to only use the blah2(), blah1() and blah0() procedures, your code will not need to be immediately updated, when you add a third parameter to the blah() procedure.

Converting user input string to regular expression

Thanks to earlier answers, this blocks serves well as a general purpose solution for applying a configurable string into a RegEx .. for filtering text:

var permittedChars = '^a-z0-9 _,.?!@+<>';
permittedChars = '[' + permittedChars + ']';

var flags = 'gi';
var strFilterRegEx = new RegExp(permittedChars, flags);

log.debug ('strFilterRegEx: ' + strFilterRegEx);

strVal = strVal.replace(strFilterRegEx, '');
// this replaces hard code solt:
// strVal = strVal.replace(/[^a-z0-9 _,.?!@+]/ig, '');

How to write to an existing excel file without overwriting data (using pandas)?

There is a better solution in pandas 0.24:

with pd.ExcelWriter(path, mode='a') as writer:
    s.to_excel(writer, sheet_name='another sheet', index=False)

before:

enter image description here

after:

enter image description here

so upgrade your pandas now:

pip install --upgrade pandas

Error 80040154 (Class not registered exception) when initializing VCProjectEngineObject (Microsoft.VisualStudio.VCProjectEngine.dll)

There are not many good reasons this would fail, especially the regsvr32 step. Run dumpbin /exports on that dll. If you don't see DllRegisterServer then you've got a corrupt install. It should have more side-effects, you wouldn't be able to build C/C++ projects anymore.

One standard failure mode is running this on a 64-bit operating system. This is 32-bit unmanaged code, you would indeed get the 'class not registered' exception. Project + Properties, Build tab, change Platform Target to x86.

What's the difference between Invoke() and BeginInvoke()

Do you mean Delegate.Invoke/BeginInvoke or Control.Invoke/BeginInvoke?

  • Delegate.Invoke: Executes synchronously, on the same thread.
  • Delegate.BeginInvoke: Executes asynchronously, on a threadpool thread.
  • Control.Invoke: Executes on the UI thread, but calling thread waits for completion before continuing.
  • Control.BeginInvoke: Executes on the UI thread, and calling thread doesn't wait for completion.

Tim's answer mentions when you might want to use BeginInvoke - although it was mostly geared towards Delegate.BeginInvoke, I suspect.

For Windows Forms apps, I would suggest that you should usually use BeginInvoke. That way you don't need to worry about deadlock, for example - but you need to understand that the UI may not have been updated by the time you next look at it! In particular, you shouldn't modify data which the UI thread might be about to use for display purposes. For example, if you have a Person with FirstName and LastName properties, and you did:

person.FirstName = "Kevin"; // person is a shared reference
person.LastName = "Spacey";
control.BeginInvoke(UpdateName);
person.FirstName = "Keyser";
person.LastName = "Soze";

Then the UI may well end up displaying "Keyser Spacey". (There's an outside chance it could display "Kevin Soze" but only through the weirdness of the memory model.)

Unless you have this sort of issue, however, Control.BeginInvoke is easier to get right, and will avoid your background thread from having to wait for no good reason. Note that the Windows Forms team has guaranteed that you can use Control.BeginInvoke in a "fire and forget" manner - i.e. without ever calling EndInvoke. This is not true of async calls in general: normally every BeginXXX should have a corresponding EndXXX call, usually in the callback.

java comparator, how to sort by integer?

One simple way is

Comparator<Dog> ageAscendingComp = ...;
Comparator<Dog> ageDescendingComp = Collections.reverseOrder(ageAscendingComp);
// then call the sort method

On a side note, Dog should really not implement Comparator. It means you have to do strange things like

Collections.sort(myList, new Dog("Rex", 4));
// ^-- why is a new dog being made? What are we even sorting by?!
Collections.sort(myList, myList.get(0));
// ^-- or perhaps more confusingly

Rather you should make Compartors as separate classes.

eg.

public class DogAgeComparator implments Comparator<Dog> {
    public int compareTo(Dog d1, Dog d2) {
        return d1.getAge() - d2.getAge();
    }
}

This has the added benefit that you can use the name of the class to say how the Comparator will sort the list. eg.

Collections.sort(someDogs, new DogNameComparator());
// now in name ascending order

Collections.sort(someDogs, Collections.reverseOrder(new DogAgeComparator()));
// now in age descending order

You should also not not have Dog implement Comparable. The Comparable interface is used to denote that there is some inherent and natural way to order these objects (such as for numbers and strings). Now this is not the case for Dog objects as sometimes you may wish to sort by age and sometimes you may wish to sort by name.

Play an audio file using jQuery when a button is clicked

JSFiddle Demonstration

This is what I use with JQuery:

$('.button').on('click', function () { 
    var obj = document.createElement("audio");
        obj.src = "linktoyourfile.wav"; 
        obj.play(); 
});

Oracle comparing timestamp with date

You can truncate the date part:

select * from table1 where trunc(field1) = to_date('2012-01-01', 'YYYY-MM-DD')

The trouble with this approach is that any index on field1 wouldn't be used due to the function call.

Alternatively (and more index friendly)

select * from table1 
 where field1 >= to_timestamp('2012-01-01', 'YYYY-MM-DD') 
   and field1 < to_timestamp('2012-01-02', 'YYYY-MM-DD')

how to load CSS file into jsp

You can write like that. This is for whenever you change context path you don't need to modify your jsp file.

<link rel="stylesheet" href="${pageContext.request.contextPath}/css/styles.css" />

Accessing localhost:port from Android emulator

After running your local host you get http://localhost:[port number]/ here you found your port number.

Then get your IP address from Command, Open your windows command and type ipconfig enter image description here

In my case, IP was 192.168.10.33 so my URL will be http://192.168.10.33:[port number]/. In Android, the studio uses this URL as your URL. And after that set your URL and your port number in manual proxy for the emulator.

enter image description here

Add one day to date in javascript

The Date constructor that takes a single number is expecting the number of milliseconds since December 31st, 1969.

Date.getDate() returns the day index for the current date object. In your example, the day is 30. The final expression is 31, therefore it's returning 31 milliseconds after December 31st, 1969.

A simple solution using your existing approach is to use Date.getTime() instead. Then, add a days worth of milliseconds instead of 1.

For example,

var dateString = 'Mon Jun 30 2014 00:00:00';

var startDate = new Date(dateString);

// seconds * minutes * hours * milliseconds = 1 day 
var day = 60 * 60 * 24 * 1000;

var endDate = new Date(startDate.getTime() + day);

JSFiddle

Please note that this solution doesn't handle edge cases related to daylight savings, leap years, etc. It is always a more cost effective approach to instead, use a mature open source library like moment.js to handle everything.

Create or write/append in text file

Try this code:

function logErr($data){
  $logPath = __DIR__. "/../logs/logs.txt";
  $mode = (!file_exists($logPath)) ? 'w':'a';
  $logfile = fopen($logPath, $mode);
  fwrite($logfile, "\r\n". $data);
  fclose($logfile);
}

I always use it like this, and it works...

How to change the Text color of Menu item in Android?

The short answer is YES. lucky you!
To do so, you need to override some styles of the Android default styles :

First, look at the definition of the themes in Android :

<style name="Theme.IconMenu">
<!-- Menu/item attributes -->
<item name="android:itemTextAppearance">@android:style/TextAppearance.Widget.IconMenu.Item</item>
<item name="android:itemBackground">@android:drawable/menu_selector</item>
<item name="android:itemIconDisabledAlpha">?android:attr/disabledAlpha</item>
<item name="android:horizontalDivider">@android:drawable/divider_horizontal_bright</item>
<item name="android:verticalDivider">@android:drawable/divider_vertical_bright</item>
<item name="android:windowAnimationStyle">@android:style/Animation.OptionsPanel</item>
<item name="android:moreIcon">@android:drawable/ic_menu_more</item>
<item name="android:background">@null</item>
</style>

So, the appearance of the text in the menu is in @android:style/TextAppearance.Widget.IconMenu.Item
Now, in the definition of the styles :

<style name="TextAppearance.Widget.IconMenu.Item" parent="TextAppearance.Small">
<item name="android:textColor">?textColorPrimaryInverse</item>
</style>

So now we have the name of the color in question, if you look in the color folder of the resources of the system :

<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_enabled="false" android:color="@android:color/bright_foreground_light_disabled" /> 
<item android:state_window_focused="false" android:color="@android:color/bright_foreground_light" /> 
<item android:state_pressed="true" android:color="@android:color/bright_foreground_light" /> 
<item android:state_selected="true" android:color="@android:color/bright_foreground_light" /> 
<item android:color="@android:color/bright_foreground_light" /> 
<!--  not selected --> 
</selector>

Finally, here is what you need to do :

Override "TextAppearance.Widget.IconMenu.Item" and create your own style. Then link it to your own selector to make it the way you want. Hope this helps you. Good luck!

String to Dictionary in Python

This data is JSON! You can deserialize it using the built-in json module if you're on Python 2.6+, otherwise you can use the excellent third-party simplejson module.

import json    # or `import simplejson as json` if on Python < 2.6

json_string = u'{ "id":"123456789", ... }'
obj = json.loads(json_string)    # obj now contains a dict of the data

error: Libtool library used but 'LIBTOOL' is undefined

For folks who ended up here and are using CYGWIN, install following packages in cygwin and re-run:

  • cygwin32-libtool
  • libtool
  • libtool-debuginfo

Regex how to match an optional character

You also could use simpler regex designed for your case like (.*)\/(([^\?\n\r])*) where $2 match what you want.

OpenCV in Android Studio

Anybody facing problemn while creating jniLibs cpp is shown ..just add ndk ..

Unable to load config info from /usr/local/ssl/openssl.cnf on Windows

The only thing that worked for me in this situation was the self-created openssl.cnf file.

Here are the basics needed for this exercise (edit as needed):

#
# OpenSSL configuration file.
#

# Establish working directory.

dir                         = .

[ ca ]
default_ca                  = CA_default

[ CA_default ]
serial                      = $dir/serial
database                    = $dir/certindex.txt
new_certs_dir               = $dir/certs
certificate                 = $dir/cacert.pem
private_key                 = $dir/private/cakey.pem
default_days                = 365
default_md                  = md5
preserve                    = no
email_in_dn                 = no
nameopt                     = default_ca
certopt                     = default_ca
policy                      = policy_match

[ policy_match ]
countryName                 = match
stateOrProvinceName         = match
organizationName            = match
organizationalUnitName      = optional
commonName                  = supplied
emailAddress                = optional

[ req ]
default_bits                = 1024          # Size of keys
default_keyfile             = key.pem       # name of generated keys
default_md                  = md5               # message digest algorithm
string_mask                 = nombstr       # permitted characters
distinguished_name          = req_distinguished_name
req_extensions              = v3_req

[ req_distinguished_name ]
# Variable name             Prompt string
#-------------------------    ----------------------------------
0.organizationName          = Organization Name (company)
organizationalUnitName      = Organizational Unit Name (department, division)
emailAddress                = Email Address
emailAddress_max            = 40
localityName                = Locality Name (city, district)
stateOrProvinceName         = State or Province Name (full name)
countryName                 = Country Name (2 letter code)
countryName_min             = 2
countryName_max             = 2
commonName                  = Common Name (hostname, IP, or your name)
commonName_max              = 64

# Default values for the above, for consistency and less typing.
# Variable name             Value
#------------------------     ------------------------------
0.organizationName_default  = My Company
localityName_default        = My Town
stateOrProvinceName_default = State or Providence
countryName_default         = US

[ v3_ca ]
basicConstraints            = CA:TRUE
subjectKeyIdentifier        = hash
authorityKeyIdentifier      = keyid:always,issuer:always

[ v3_req ]
basicConstraints            = CA:FALSE
subjectKeyIdentifier        = hash

I hope that helps.

How do MySQL indexes work?

The first thing you must know is that indexes are a way to avoid scanning the full table to obtain the result that you're looking for.

There are different kinds of indexes and they're implemented in the storage layer, so there's no standard between them and they also depend on the storage engine that you're using.

InnoDB and the B+Tree index

For InnoDB, the most common index type is the B+Tree based index, that stores the elements in a sorted order. Also, you don't have to access the real table to get the indexed values, which makes your query return way faster.

The "problem" about this index type is that you have to query for the leftmost value to use the index. So, if your index has two columns, say last_name and first_name, the order that you query these fields matters a lot.

So, given the following table:

CREATE TABLE person (
    last_name VARCHAR(50) NOT NULL,
    first_name VARCHAR(50) NOT NULL,
    INDEX (last_name, first_name)
);

This query would take advantage of the index:

SELECT last_name, first_name FROM person
WHERE last_name = "John" AND first_name LIKE "J%"

But the following one would not

SELECT last_name, first_name FROM person WHERE first_name = "Constantine"

Because you're querying the first_name column first and it's not the leftmost column in the index.

This last example is even worse:

SELECT last_name, first_name FROM person WHERE first_name LIKE "%Constantine"

Because now, you're comparing the rightmost part of the rightmost field in the index.

The hash index

This is a different index type that unfortunately, only the memory backend supports. It's lightning fast but only useful for full lookups, which means that you can't use it for operations like >, < or LIKE.

Since it only works for the memory backend, you probably won't use it very often. The main case I can think of right now is the one that you create a temporary table in the memory with a set of results from another select and perform a lot of other selects in this temporary table using hash indexes.

If you have a big VARCHAR field, you can "emulate" the use of a hash index when using a B-Tree, by creating another column and saving a hash of the big value on it. Let's say you're storing a url in a field and the values are quite big. You could also create an integer field called url_hash and use a hash function like CRC32 or any other hash function to hash the url when inserting it. And then, when you need to query for this value, you can do something like this:

SELECT url FROM url_table WHERE url_hash=CRC32("http://gnu.org");

The problem with the above example is that since the CRC32 function generates a quite small hash, you'll end up with a lot of collisions in the hashed values. If you need exact values, you can fix this problem by doing the following:

SELECT url FROM url_table 
WHERE url_hash=CRC32("http://gnu.org") AND url="http://gnu.org";

It's still worth to hash things even if the collision number is high cause you'll only perform the second comparison (the string one) against the repeated hashes.

Unfortunately, using this technique, you still need to hit the table to compare the url field.

Wrap up

Some facts that you may consider every time you want to talk about optimization:

  1. Integer comparison is way faster than string comparison. It can be illustrated with the example about the emulation of the hash index in InnoDB.

  2. Maybe, adding additional steps in a process makes it faster, not slower. It can be illustrated by the fact that you can optimize a SELECT by splitting it into two steps, making the first one store values in a newly created in-memory table, and then execute the heavier queries on this second table.

MySQL has other indexes too, but I think the B+Tree one is the most used ever and the hash one is a good thing to know, but you can find the other ones in the MySQL documentation.

I highly recommend you to read the "High Performance MySQL" book, the answer above was definitely based on its chapter about indexes.

How to read all rows from huge table?

I think your question is similar to this thread: JDBC Pagination which contains solutions for your need.

In particular, for PostgreSQL, you can use the LIMIT and OFFSET keywords in your request: http://www.petefreitag.com/item/451.cfm

PS: In Java code, I suggest you to use PreparedStatement instead of simple Statements: http://download.oracle.com/javase/tutorial/jdbc/basics/prepared.html