Programs & Examples On #Wss 3.0 sp2

How to write a comment in a Razor view?

Note that in general, IDE's like Visual Studio will markup a comment in the context of the current language, by selecting the text you wish to turn into a comment, and then using the Ctrl+K Ctrl+C shortcut, or if you are using Resharper / Intelli-J style shortcuts, then Ctrl+/.

Server side Comments:

Razor .cshtml

Like so:

@* Comment goes here *@

.aspx
For those looking for the older .aspx view (and Asp.Net WebForms) server side comment syntax:

<%-- Comment goes here --%>

Client Side Comments

HTML Comment

<!-- Comment goes here -->

Javascript Comment

// One line Comment goes Here
/* Multiline comment
   goes here */

As OP mentions, although not displayed on the browser, client side comments will still be generated for the page / script file on the server and downloaded by the page over HTTP, which unless removed (e.g. minification), will waste I/O, and, since the comment can be viewed by the user by viewing the page source or intercepting the traffic with the browser's Dev Tools or a tool like Fiddler or Wireshark, can also pose a security risk, hence the preference to use server side comments on server generated code (like MVC views or .aspx pages).

How do I escape a single quote ( ' ) in JavaScript?

You should always consider what the browser will see by the end. In this case, it will see this:

<img src='something' onmouseover='change(' ex1')' />

In other words, the "onmouseover" attribute is just change(, and there's another "attribute" called ex1')' with no value.

The truth is, HTML does not use \ for an escape character. But it does recognise &quot; and &apos; as escaped quote and apostrophe, respectively.

Armed with this knowledge, use this:

document.getElementById("something").innerHTML = "<img src='something' onmouseover='change(&quot;ex1&quot;)' />";

... That being said, you could just use JavaScript quotes:

document.getElementById("something").innerHTML = "<img src='something' onmouseover='change(\"ex1\")' />";

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

this command can download jdk8 tgz package at now (2018-09-06), good luck !

wget --no-cookies --no-check-certificate --header "Cookie: gpw_e24=http%3A%2F%2Fwww.oracle.com%2F; oraclelicense=accept-securebackup-cookie" "http://download.oracle.com/otn-pub/java/jdk/8u141-b15/336fa29ff2bb4ef291e347e091f7f4a7/jdk-8u141-linux-x64.tar.gz"

Enabling the OpenSSL in XAMPP

Yes, you must open php.ini and remove the semicolon to:

;extension=php_openssl.dll

If you don't have that line, check that you have the file (In my PC is on D:\xampp\php\ext) and add this to php.ini in the "Dynamic Extensions" section:

extension=php_openssl.dll

Things have changed for PHP > 7. This is what i had to do for PHP 7.2.

Step: 1: Uncomment extension=openssl

Step: 2: Uncomment extension_dir = "ext"

Step: 3: Restart xampp.

Done.

Explanation: ( From php.ini )

If you wish to have an extension loaded automatically, use the following syntax:

extension=modulename

Note : The syntax used in previous PHP versions (extension=<ext>.so and extension='php_<ext>.dll) is supported for legacy reasons and may be deprecated in a future PHP major version. So, when it is possible, please move to the new (extension=<ext>) syntax.

Special Note: Be sure to appropriately set the extension_dir directive.

How to style the UL list to a single line

In modern browsers you can do the following (CSS3 compliant)

_x000D_
_x000D_
ul_x000D_
{_x000D_
  display:flex;  _x000D_
  list-style:none;_x000D_
}
_x000D_
<ul>_x000D_
  <li><a href="">Item1</a></li>_x000D_
  <li><a href="">Item2</a></li>_x000D_
  <li><a href="">Item3</a></li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

How do I uninstall a Windows service if the files do not exist anymore?

From the command prompt, use the Windows "sc.exe" utility. You will run something like this:

sc delete <service-name>

Difference between Role and GrantedAuthority in Spring Security

AFAIK GrantedAuthority and roles are same in spring security. GrantedAuthority's getAuthority() string is the role (as per default implementation SimpleGrantedAuthority).

For your case may be you can use Hierarchical Roles

<bean id="roleVoter" class="org.springframework.security.access.vote.RoleHierarchyVoter">
    <constructor-arg ref="roleHierarchy" />
</bean>
<bean id="roleHierarchy"
        class="org.springframework.security.access.hierarchicalroles.RoleHierarchyImpl">
    <property name="hierarchy">
        <value>
            ROLE_ADMIN > ROLE_createSubUsers
            ROLE_ADMIN > ROLE_deleteAccounts 
            ROLE_USER > ROLE_viewAccounts
        </value>
    </property>
</bean>

Not the exact sol you looking for, but hope it helps

Edit: Reply to your comment

Role is like a permission in spring-security. using intercept-url with hasRole provides a very fine grained control of what operation is allowed for which role/permission.

The way we handle in our application is, we define permission (i.e. role) for each operation (or rest url) for e.g. view_account, delete_account, add_account etc. Then we create logical profiles for each user like admin, guest_user, normal_user. The profiles are just logical grouping of permissions, independent of spring-security. When a new user is added, a profile is assigned to it (having all permissible permissions). Now when ever user try to perform some action, permission/role for that action is checked against user grantedAuthorities.

Also the defaultn RoleVoter uses prefix ROLE_, so any authority starting with ROLE_ is considered as role, you can change this default behavior by using a custom RolePrefix in role voter and using it in spring security.

How do I make the return type of a method generic?

You need to make it a generic method, like this:

public static T ConfigSetting<T>(string settingName)
{  
    return /* code to convert the setting to T... */
}

But the caller will have to specify the type they expect. You could then potentially use Convert.ChangeType, assuming that all the relevant types are supported:

public static T ConfigSetting<T>(string settingName)
{  
    object value = ConfigurationManager.AppSettings[settingName];
    return (T) Convert.ChangeType(value, typeof(T));
}

I'm not entirely convinced that all this is a good idea, mind you...

Best way to unselect a <select> in jQuery?

A quick google found this post that describes how to do what you want for both single and multiple select lists in IE. The solution seems pretty elegant as well:

$('#clickme').click(function() {
        $('#selectmenu option').attr('selected', false);

}); 

WAITING at sun.misc.Unsafe.park(Native Method)

I had a similar issue, and following previous answers (thanks!), I was able to search and find how to handle correctly the ThreadPoolExecutor terminaison.

In my case, that just fix my progressive increase of similar blocked threads:

  • I've used ExecutorService::awaitTermination(x, TimeUnit) and ExecutorService::shutdownNow() (if necessary) in my finally clause.
  • For information, I've used the following commands to detect thread count & list locked threads:

    ps -u javaAppuser -L|wc -l

    jcmd `ps -C java -o pid=` Thread.print >> threadPrintDayA.log

    jcmd `ps -C java -o pid=` Thread.print >> threadPrintDayAPlusOne.log

    cat threadPrint*.log |grep "pool-"|wc -l

Making a button invisible by clicking another button in HTML

Try this

<input type="button" onclick="demoShow()" value="edit" />
<script type="text/javascript"> 
function demoShow()
{p2.style.visibility="hidden";}
</script>
<input id="p2" type="submit" value="submit" name="submit" />

http://jsbin.com/gurolawu/1/

How to use OrderBy with findAll in Spring Data

public interface StudentDAO extends JpaRepository<StudentEntity, Integer> {
    public List<StudentEntity> findAllByOrderByIdAsc();
}

The code above should work. I'm using something similar:

public List<Pilot> findTop10ByOrderByLevelDesc();

It returns 10 rows with the highest level.

IMPORTANT: Since I've been told that it's easy to miss the key point of this answer, here's a little clarification:

findAllByOrderByIdAsc(); // don't miss "by"
       ^

jquery $(this).id return Undefined

$(this) is a jQuery object that is wrapping the DOM element this and jQuery objects don't have id properties. You probably want just this.id to get the id attribute of the clicked element.

How do I read the first line of a file using cat?

There are many different ways:

sed -n 1p file
head -n 1 file
awk 'NR==1' file

How to set True as default value for BooleanField on Django?

If you're just using a vanilla form (not a ModelForm), you can set a Field initial value ( https://docs.djangoproject.com/en/2.2/ref/forms/fields/#django.forms.Field.initial ) like

class MyForm(forms.Form):
    my_field = forms.BooleanField(initial=True)

If you're using a ModelForm, you can set a default value on the model field ( https://docs.djangoproject.com/en/2.2/ref/models/fields/#default ), which will apply to the resulting ModelForm, like

class MyModel(models.Model):
    my_field = models.BooleanField(default=True)

Finally, if you want to dynamically choose at runtime whether or not your field will be selected by default, you can use the initial parameter to the form when you initialize it:

form = MyForm(initial={'my_field':True})

How do I execute a *.dll file

You can execute a function defined in a DLL file by using the rundll command. You can explore the functions available by using Dependency Walker.

How to create a self-signed certificate with OpenSSL

I would recommend to add the -sha256 parameter, to use the SHA-2 hash algorithm, because major browsers are considering to show "SHA-1 certificates" as not secure.

The same command line from the accepted answer - @diegows with added -sha256

openssl req -x509 -sha256 -newkey rsa:2048 -keyout key.pem -out cert.pem -days XXX

More information in Google Security blog.

Update May 2018. As many noted in the comments that using SHA-2 does not add any security to a self-signed certificate. But I still recommend using it as a good habit of not using outdated / insecure cryptographic hash functions. Full explanation is available in Why is it fine for certificates above the end-entity certificate to be SHA-1 based?.

How to resolve this JNI error when trying to run LWJGL "Hello World"?

A CLASSPATH entry is either a directory at the head of a package hierarchy of .class files, or a .jar file. If you're expecting ./lib to include all the .jar files in that directory, it won't. You have to name them explicitly.

Better/Faster to Loop through set or list?

I the list is vary large looping two time over it will take a lot of time and more in the second time you are looping a set not a list and as we know iterating over a set is slower than list.

i think you need the power of generator and set.

def first_test():

    def loop_one_time(my_list):
        # create a set to keep the items.
        iterated_items = set()
        # as we know iterating over list is faster then list.
        for value in my_list: 
            # as we know checking if element exist in set is very fast not
            # metter the size of the set.
            if value not in iterated_items:  
                iterated_items.add(value) # add this item to list
                yield value


    mylist = [3,1,5,2,4,4,1,4,2,5,1,3]

    for v in loop_one_time(mylist):pass



def second_test():
    mylist = [3,1,5,2,4,4,1,4,2,5,1,3]
    s = set(mylist)
    for v in s:pass


import timeit

print(timeit.timeit('first_test()', setup='from __main__ import first_test', number=10000))
print(timeit.timeit('second_test()', setup='from __main__ import second_test', number=10000))

out put:

   0.024003583388435043
   0.010424674188938422

Note: this technique order is guaranteed

Managing SSH keys within Jenkins for Git

According to this article, you may try following command:

   ssh-add -l

If your key isn't in the list, then

   ssh-add /var/lib/jenkins/.ssh/id_rsa_project

Loading/Downloading image from URL on Swift

The only things there is missing is a !

let url = NSURL.URLWithString("http://live-wallpaper.net/iphone/img/app/i/p/iphone-4s-wallpapers-mobile-backgrounds-dark_2466f886de3472ef1fa968033f1da3e1_raw_1087fae1932cec8837695934b7eb1250_raw.jpg");
var err: NSError?
var imageData :NSData = NSData.dataWithContentsOfURL(url!,options: NSDataReadingOptions.DataReadingMappedIfSafe, error: &err)
var bgImage = UIImage(data:imageData!)

Getting parts of a URL (Regex)

I realize I'm late to the party, but there is a simple way to let the browser parse a url for you without a regex:

var a = document.createElement('a');
a.href = 'http://www.example.com:123/foo/bar.html?fox=trot#foo';

['href','protocol','host','hostname','port','pathname','search','hash'].forEach(function(k) {
    console.log(k+':', a[k]);
});

/*//Output:
href: http://www.example.com:123/foo/bar.html?fox=trot#foo
protocol: http:
host: www.example.com:123
hostname: www.example.com
port: 123
pathname: /foo/bar.html
search: ?fox=trot
hash: #foo
*/

How do I pull from a Git repository through an HTTP proxy?

What finally worked was setting the http_proxy environment variable. I had set HTTP_PROXY correctly, but git apparently likes the lower-case version better.

Repeat each row of data.frame the number of times specified in a column

Use expandRows() from the splitstackshape package:

library(splitstackshape)
expandRows(df, "freq")

Simple syntax, very fast, works on data.frame or data.table.

Result:

    var1 var2
1      a    d
2      b    e
2.1    b    e
3      c    f
3.1    c    f
3.2    c    f

CSS: borders between table columns only

You need to set a border-right on the td's then target the last tds in a row to set the border to none. Ways to target:

  1. Set a class on the last td of each row and use that
  2. If it is a set number of cells and only targeting newer browers then 3 cells wide can use td + td + td
  3. Or better (with new browsers) td:last-child

Angular2 dynamic change CSS property

1) Using inline styles

<div [style.color]="myDynamicColor">

2) Use multiple CSS classes mapping to what you want and switch classes like:

 /* CSS */
 .theme { /* any shared styles */ }
 .theme.blue { color: blue; }
 .theme.red { color: red; }

 /* Template */
 <div class="theme" [ngClass]="{blue: isBlue, red: isRed}">
 <div class="theme" [class.blue]="isBlue">

Code samples from: https://angular.io/cheatsheet

More info on ngClass directive : https://angular.io/docs/ts/latest/api/common/index/NgClass-directive.html

Java Byte Array to String to Byte Array

Use the below code API to convert bytecode as string to Byte array.

 byte[] byteArray = DatatypeConverter.parseBase64Binary("JVBERi0xLjQKMyAwIG9iago8P...");

Get source JARs from Maven repository

To download some specific source or javadoc we need to include the GroupIds - Its a comma separated value as shown below

mvn dependency:sources -DincludeGroupIds=com.jcraft,org.testng -Dclassifier=sources

Note that the classifier are not comma separated, to download the javadoc we need to run the above command one more time with the classifier as javadoc

mvn dependency:sources -DincludeGroupIds=com.jcraft,org.testng -Dclassifier=javadoc

Spring MVC + JSON = 406 Not Acceptable

With Spring 4 you only add @EnableWebMvc, for example:

@Controller
@EnableWebMvc
@RequestMapping(value = "/articles/action", headers="Accept=*/*",  produces="application/json")
public class ArticlesController {

}

Windows 7, 64 bit, DLL problems

I solved the problem. When I registered the OCX files, I ran it with the Command Window that had been executed as an administrator.

How to reference static assets within vue javascript

Having a default structure of folders generated by Vue CLI such as src/assets you can place your image there and refer this from HTML as follows <img src="../src/assets/img/logo.png"> as well (works automatically without any changes on deployment too).

How to find length of a string array?

Well, in this case the car variable will be null, so dereferencing it (as you do when you access car.length) will throw a NullPointerException.

In fact, you can't access that variable at all until some value has definitely been assigned to it - otherwise the compiler will complain that "variable car might not have been initialized".

What is it you're trying to do here (it's not clear to me exactly what "solution" you're looking for)?

Java method to swap primitives

I think this is the closest you can get to a simple swap, but it does not have a straightforward usage pattern:

int swap(int a, int b) {  // usage: y = swap(x, x=y);
   return a;
}

y = swap(x, x=y);

It relies on the fact that x will pass into swap before y is assigned to x, then x is returned and assigned to y.

You can make it generic and swap any number of objects of the same type:

<T> T swap(T... args) {   // usage: z = swap(a, a=b, b=c, ... y=z);
    return args[0];
}

c = swap(a, a=b, b=c)

How do I use disk caching in Picasso?

I had the same problem and used Glide library instead. Cache is out of the box there. https://github.com/bumptech/glide

How to implement endless list with RecyclerView?

No repetition calls however you scroll. fetchData will be called only when you are at the end of the list and there is more data to be fetched

Regarding my code:
1.fetchData() fetches 10 items on each call.
2.isScrolling is a class member variable 3.previousTotalCount is also a class member. It stores previously visited last item

recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
                if (newState == AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL) {
                    isScrolling = true
                }
            }

            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)

                val visibleItemCount = layoutManager.childCount
                val totalItemCount = layoutManager.itemCount
                val scrolledOutItems = layoutManager.findFirstVisibleItemPosition()


                if (isScrolling && (visibleItemCount + scrolledOutItems == totalItemCount)
                    && (visibleItemCount + scrolledOutItems != previousTotalCount)) {
                    previousTotalCount = totalItemCount              
                    isScrolling = false
                    fetchData()  //fetches 10 new items from Firestore
                    pagingProgressBar.visibility = View.VISIBLE
                }
            }
        })

grep a file, but show several surrounding lines?

I normally use

grep searchstring file -C n # n for number of lines of context up and down

Many of the tools like grep also have really great man files too. I find myself referring to grep's man page a lot because there is so much you can do with it.

man grep

Many GNU tools also have an info page that may have more useful information in addition to the man page.

info grep

pass parameter by link_to ruby on rails

Try:

<%= link_to "Add to cart", {:controller => "car", :action => "add_to_cart", :car => car.id }%>

and then in your controller

@car = Car.find(params[:car])

which, will find in your 'cars' table (as with rails pluralization) in your DB a car with id == to car.id

hope it helps! happy coding

more than a year later, but if you see it or anyone does, i could use the points ;D

Any free WPF themes?

Not purely themes, but MahApps.Metro provides Windows 8 Look and feel with a few variants like dark and light base themes with green,blue etc for text and others. Its pretty cool and can be used out of the box.

Transfer data from one HTML file to another

Try this code: In testing.html

function testJS() {
    var b = document.getElementById('name').value,
        url = 'http://path_to_your_html_files/next.html?name=' + encodeURIComponent(b);

    document.location.href = url;
}

And in next.html:

window.onload = function () {
    var url = document.location.href,
        params = url.split('?')[1].split('&'),
        data = {}, tmp;
    for (var i = 0, l = params.length; i < l; i++) {
         tmp = params[i].split('=');
         data[tmp[0]] = tmp[1];
    }
    document.getElementById('here').innerHTML = data.name;
}

Description: javascript can't share data between different pages, and we must to use some solutions, e.g. URL get params (in my code i used this way), cookies, localStorage, etc. Store the name parameter in URL (?name=...) and in next.html parse URL and get all params from prev page.

PS. i'm an non-native english speaker, will you please correct my message, if necessary

How do I import an SQL file using the command line in MySQL?

For backup purposes, make a BAT file and run this BAT file using Task Scheduler. It will take a backup of the database; just copy the following line and paste in Notepad and then save the .bat file, and run it on your system.

@echo off
for /f "tokens=1" %%i in ('date /t') do set DATE_DOW=%%i
for /f "tokens=2" %%i in ('date /t') do set DATE_DAY=%%i
for /f %%i in ('echo %date_day:/=-%') do set DATE_DAY=%%i
for /f %%i in ('time /t') do set DATE_TIME=%%i
for /f %%i in ('echo %date_time::=-%') do set DATE_TIME=%%i

"C:\Program Files\MySQL\mysql server 5.5\bin\mysqldump" -u username -ppassword mysql>C:/%DATE_DAY%_%DATE_TIME%_database.sql

How to use shell commands in Makefile

With:

FILES = $(shell ls)

indented underneath all like that, it's a build command. So this expands $(shell ls), then tries to run the command FILES ....

If FILES is supposed to be a make variable, these variables need to be assigned outside the recipe portion, e.g.:

FILES = $(shell ls)
all:
        echo $(FILES)

Of course, that means that FILES will be set to "output from ls" before running any of the commands that create the .tgz files. (Though as Kaz notes the variable is re-expanded each time, so eventually it will include the .tgz files; some make variants have FILES := ... to avoid this, for efficiency and/or correctness.1)

If FILES is supposed to be a shell variable, you can set it but you need to do it in shell-ese, with no spaces, and quoted:

all:
        FILES="$(shell ls)"

However, each line is run by a separate shell, so this variable will not survive to the next line, so you must then use it immediately:

        FILES="$(shell ls)"; echo $$FILES

This is all a bit silly since the shell will expand * (and other shell glob expressions) for you in the first place, so you can just:

        echo *

as your shell command.

Finally, as a general rule (not really applicable to this example): as esperanto notes in comments, using the output from ls is not completely reliable (some details depend on file names and sometimes even the version of ls; some versions of ls attempt to sanitize output in some cases). Thus, as l0b0 and idelic note, if you're using GNU make you can use $(wildcard) and $(subst ...) to accomplish everything inside make itself (avoiding any "weird characters in file name" issues). (In sh scripts, including the recipe portion of makefiles, another method is to use find ... -print0 | xargs -0 to avoid tripping over blanks, newlines, control characters, and so on.)


1The GNU Make documentation notes further that POSIX make added ::= assignment in 2012. I have not found a quick reference link to a POSIX document for this, nor do I know off-hand which make variants support ::= assignment, although GNU make does today, with the same meaning as :=, i.e., do the assignment right now with expansion.

Note that VAR := $(shell command args...) can also be spelled VAR != command args... in several make variants, including all modern GNU and BSD variants as far as I know. These other variants do not have $(shell) so using VAR != command args... is superior in both being shorter and working in more variants.

convert string date to java.sql.Date

worked for me too:

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
    Date parsed = null;
    try {
        parsed = sdf.parse("02/01/2014");
    } catch (ParseException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    java.sql.Date data = new java.sql.Date(parsed.getTime());
    contato.setDataNascimento( data);

    // Contato DataNascimento era Calendar
    //contato.setDataNascimento(Calendar.getInstance());         

    // grave nessa conexão!!! 
    ContatoDao dao = new ContatoDao("mysql");           

    // método elegante 
    dao.adiciona(contato); 
    System.out.println("Banco: ["+dao.getNome()+"] Gravado! Data: "+contato.getDataNascimento());

HTML Mobile -forcing the soft keyboard to hide

For further readers/searchers:

As Rene Pot points out on this topic,

By adding the attribute readonly (or readonly="readonly") to the input field you should prevent anyone typing anything in it, but still be able to launch a click event on it.

With this method, you can avoid popping up the "soft" Keyboard and still launch click events / fill the input by any on-screen keyboard.

This solution also works fine with date-time-pickers which generally already implement controls.

Float and double datatype in Java

You should use double instead of float for precise calculations, and float instead of double when using less accurate calculations. Float contains only decimal numbers, but double contains an IEEE754 double-precision floating point number, making it easier to contain and computate numbers more accurately. Hope this helps.

Simulating Slow Internet Connection

Updating this (9 years after it was asked) as the answer I was looking for wasn't mentioned:

Firefox also has presets for throttling connection speeds. Find them in the Network Monitor tab of the developer tools. Default is 'No throttling'.

Slowest is GPRS (Download speed: 50 Kbps, Upload speed: 20 Kbps, Minimum latency (ms): 500), ranging through 'good' and 'regular' 2G, 3G and 4G to DSL and WiFi (Download speed: 30Mbps, Upload speed: 15Mbps, Minimum latency (ms): 2).

More in the Dev Tools docs.

Testing pointers for validity (C/C++)

In general, it's impossible to do. Here's one particularly nasty case:

struct Point2d {
    int x;
    int y;
};

struct Point3d {
    int x;
    int y;
    int z;
};

void dump(Point3 *p)
{
    printf("[%d %d %d]\n", p->x, p->y, p->z);
}

Point2d points[2] = { {0, 1}, {2, 3} };
Point3d *p3 = reinterpret_cast<Point3d *>(&points[0]);
dump(p3);

On many platforms, this will print out:

[0 1 2]

You're forcing the runtime system to incorrectly interpret bits of memory, but in this case it's not going to crash, because the bits all make sense. This is part of the design of the language (look at C-style polymorphism with struct inaddr, inaddr_in, inaddr_in6), so you can't reliably protect against it on any platform.

How to kill a thread instantly in C#?

You should first have some agreed method of ending the thread. For example a running_ valiable that the thread can check and comply with.

Your main thread code should be wrapped in an exception block that catches both ThreadInterruptException and ThreadAbortException that will cleanly tidy up the thread on exit.

In the case of ThreadInterruptException you can check the running_ variable to see if you should continue. In the case of the ThreadAbortException you should tidy up immediately and exit the thread procedure.

The code that tries to stop the thread should do the following:

running_ = false;
threadInstance_.Interrupt();
if(!threadInstance_.Join(2000)) { // or an agreed resonable time
   threadInstance_.Abort();
}

Add 2 hours to current time in MySQL?

SELECT * FROM courses WHERE (NOW() + INTERVAL 2 HOUR) > start_time

Chart.js v2 - hiding grid lines

If you want them gone by default, you can set:

Chart.defaults.scale.gridLines.display = false;

Using "word-wrap: break-word" within a table

You can try this:

td p {word-break:break-all;}

This, however, makes it appear like this when there's enough space, unless you add a <br> tag:

aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb

So, I would then suggest adding <br> tags where there are newlines, if possible.

aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb

http://jsfiddle.net/LLyH3/3/

Also, if this doesn't solve your problem, there's a similar thread here.

Undo git update-index --assume-unchanged <file>

To get undo/show dir's/files that are set to assume-unchanged run this:

git update-index --no-assume-unchanged <file>

To get a list of dir's/files that are assume-unchanged run this:

git ls-files -v|grep '^h'

How can I create a Windows .exe (standalone executable) using Java/Eclipse?

Creating .exe distributions isn't typical for Java. While such wrappers do exist, the normal mode of operation is to create a .jar file.

To create a .jar file from a Java project in Eclipse, use file->export->java->Jar file. This will create an archive with all your classes.

On the command prompt, use invocation like the following:

java -cp myapp.jar foo.bar.MyMainClass

How to get everything after a certain character?

if anyone needs to extract the first part of the string then can try,

Query:

$s = "This_is_a_string_233718";

$text = $s."_".substr($s, 0, strrpos($s, "_"));

Output:

This_is_a_string

HTML entity for the middle dot

This can be done easily using &middot;. You can color or size the dot according to the tags you wrap it with. For example, try and run this

<h2> I &middot; love &middot; Coding </h2>

How to redirect back to form with input - Laravel 5

You can try this:

return redirect()->back()->withInput(Input::all())->with('message', 'Something 
went wrong!');

TypeError: 'float' object is not callable

The problem is with -3.7(prof[x]), which looks like a function call (note the parens). Just use a * like this -3.7*prof[x].

How to programmatically round corners and set random background colors

As the question has already been answered. But I have a little tweak

GradientDrawable drawable = (GradientDrawable) ContextCompat.getDrawable(context, R.drawable.YOUR_DRAWABLE).mutate();

you can change corner radius with:

drawable.setCornerRadius(YOUR_VALUE);

Change color with:

drawable.setColor(Color.YOUR_COLOR);

A mutable drawable is guaranteed to not share its state with any other drawable. So if you change radius without using mutate(), you are likely to change others state too. It is best suitable for specific views.

At last don't forget to set the drawable.

this.setBackground(drawable);

Bitwise operation and usage

One typical usage:

| is used to set a certain bit to 1

& is used to test or clear a certain bit

  • Set a bit (where n is the bit number, and 0 is the least significant bit):

    unsigned char a |= (1 << n);

  • Clear a bit:

    unsigned char b &= ~(1 << n);

  • Toggle a bit:

    unsigned char c ^= (1 << n);

  • Test a bit:

    unsigned char e = d & (1 << n);

Take the case of your list for example:

x | 2 is used to set bit 1 of x to 1

x & 1 is used to test if bit 0 of x is 1 or 0

Loading DLLs at runtime in C#

Members must be resolvable at compile time to be called directly from C#. Otherwise you must use reflection or dynamic objects.

Reflection

namespace ConsoleApplication1
{
    using System;
    using System.Reflection;

    class Program
    {
        static void Main(string[] args)
        {
            var DLL = Assembly.LoadFile(@"C:\visual studio 2012\Projects\ConsoleApplication1\ConsoleApplication1\DLL.dll");

            foreach(Type type in DLL.GetExportedTypes())
            {
                var c = Activator.CreateInstance(type);
                type.InvokeMember("Output", BindingFlags.InvokeMethod, null, c, new object[] {@"Hello"});
            }

            Console.ReadLine();
        }
    }
}

Dynamic (.NET 4.0)

namespace ConsoleApplication1
{
    using System;
    using System.Reflection;

    class Program
    {
        static void Main(string[] args)
        {
            var DLL = Assembly.LoadFile(@"C:\visual studio 2012\Projects\ConsoleApplication1\ConsoleApplication1\DLL.dll");

            foreach(Type type in DLL.GetExportedTypes())
            {
                dynamic c = Activator.CreateInstance(type);
                c.Output(@"Hello");
            }

            Console.ReadLine();
        }
    }
}

SQL Error: ORA-00942 table or view does not exist

I am using Oracle Database and i had same problem. Eventually i found ORACLE DB is converting all the metadata (table/sp/view/trigger) in upper case.

And i was trying how i wrote table name (myTempTable) in sql whereas it expect how it store table name in databsae (MYTEMPTABLE). Also same applicable on column name.

It is quite common problem with developer whoever used sql and now jumped into ORACLE DB.

Listview Scroll to the end of the list after updating the list

I use

setTranscriptMode(ListView.TRANSCRIPT_MODE_NORMAL);

to add entries at the bottom, and older entries scroll off the top, like a chat transcript

Include jQuery in the JavaScript Console

Here is alternative code:

javascript:(function() {var url = '//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js'; var n=document.createElement('script');n.setAttribute('language','JavaScript');n.setAttribute('src',url+'?rand='+new Date().getTime());document.body.appendChild(n);})();

which can be pasted either directly in Console or create a new Bookmark page (in Chrome right-click on the Bookmark Bar, Add Page...) and paste this code as URL.

To test if that worked, see below.

Before:

$()
Uncaught TypeError: $ is not a function(…)

After:

$()
[]

DevTools failed to load SourceMap: Could not load content for chrome-extension

For me, the problem was caused not by the app in development itself but by the Chrome extension: React Developer Tool. I solved partially that by right-clicking the extension icon in the toolbar, clicking "manage extension" (I'm freely translating menu text here since my browser language is in Brazilian Portuguese), then enabling "Allow access to files URLs." But this measure fixed just some of the alerts.

I found issues in the react repo that suggests the cause is a bug in their extension and is planned to be corrected soon - see issues 20091 and 20075.

You can confirm is extension-related by accessing your app in an anonymous tab without any extension enabled.

What is Type-safe?

Type-safe means that programmatically, the type of data for a variable, return value, or argument must fit within a certain criteria.

In practice, this means that 7 (an integer type) is different from "7" (a quoted character of string type).

PHP, Javascript and other dynamic scripting languages are usually weakly-typed, in that they will convert a (string) "7" to an (integer) 7 if you try to add "7" + 3, although sometimes you have to do this explicitly (and Javascript uses the "+" character for concatenation).

C/C++/Java will not understand that, or will concatenate the result into "73" instead. Type-safety prevents these types of bugs in code by making the type requirement explicit.

Type-safety is very useful. The solution to the above "7" + 3 would be to type cast (int) "7" + 3 (equals 10).

How can I have grep not print out 'No such file or directory' errors?

I usually don't let grep do the recursion itself. There are usually a few directories you want to skip (.git, .svn...)

You can do clever aliases with stances like that one:

find . \( -name .svn -o -name .git \) -prune -o -type f -exec grep -Hn pattern {} \;

It may seem overkill at first glance, but when you need to filter out some patterns it is quite handy.

Padding or margin value in pixels as integer using jQuery

You could also extend the jquery framework yourself with something like:

jQuery.fn.margin = function() {
var marginTop = this.outerHeight(true) - this.outerHeight();
var marginLeft = this.outerWidth(true) - this.outerWidth();

return {
    top: marginTop,
    left: marginLeft
}};

Thereby adding a function on your jquery objects called margin(), which returns a collection like the offset function.

fx.

$("#myObject").margin().top

Editing the date formatting of x-axis tick labels in matplotlib

While the answer given by Paul H shows the essential part, it is not a complete example. On the other hand the matplotlib example seems rather complicated and does not show how to use days.

So for everyone in need here is a full working example:

from datetime import datetime
import matplotlib.pyplot as plt
from matplotlib.dates import DateFormatter

myDates = [datetime(2012,1,i+3) for i in range(10)]
myValues = [5,6,4,3,7,8,1,2,5,4]
fig, ax = plt.subplots()
ax.plot(myDates,myValues)

myFmt = DateFormatter("%d")
ax.xaxis.set_major_formatter(myFmt)

## Rotate date labels automatically
fig.autofmt_xdate()
plt.show()

How to Delete node_modules - Deep Nested Folder in Windows

What worked for me was:

  1. closed the node manager console
  2. closed the Atom (visual studio code ) dev environment you are in.
  3. then delete the node_modules

    npm install rimraf -g 
    rimraf node_modules
    

JavaScript: clone a function

Here is an updated answer

var newFunc = oldFunc.bind({}); //clones the function with '{}' acting as it's new 'this' parameter

However .bind is a modern ( >=iE9 ) feature of JavaScript (with a compatibility workaround from MDN)

Notes

  1. It does not clone the function object additional attached properties, including the prototype property. Credit to @jchook

  2. The new function this variable is stuck with the argument given on bind(), even on new function apply() calls. Credit to @Kevin

function oldFunc() {
  console.log(this.msg);
}
var newFunc = oldFunc.bind({ msg: "You shall not pass!" }); // this object is binded
newFunc.apply({ msg: "hello world" }); //logs "You shall not pass!" instead
  1. Bound function object, instanceof treats newFunc/oldFunc as the same. Credit to @Christopher
(new newFunc()) instanceof oldFunc; //gives true
(new oldFunc()) instanceof newFunc; //gives true as well
newFunc == oldFunc; //gives false however

LINQ's Distinct() on a particular property

List<Person>lst=new List<Person>
        var result1 = lst.OrderByDescending(a => a.ID).Select(a =>new Player {ID=a.ID,Name=a.Name} ).Distinct();

Set HTML dropdown selected option using JSTL

In Servlet do:

String selectedRole = "rat"; // Or "cat" or whatever you'd like.
request.setAttribute("selectedRole", selectedRole);

Then in JSP do:

<select name="roleName">
    <c:forEach items="${roleNames}" var="role">
        <option value="${role}" ${role == selectedRole ? 'selected' : ''}>${role}</option>
    </c:forEach>
</select>

It will print the selected attribute of the HTML <option> element so that you end up like:

<select name="roleName">
    <option value="cat">cat</option>
    <option value="rat" selected>rat</option>
    <option value="unicorn">unicorn</option>
</select>

Apart from the problem: this is not a combo box. This is a dropdown. A combo box is an editable dropdown.

How do I force Kubernetes to re-pull an image?

This answer aims to force an image pull in a situation where your node has already downloaded an image with the same name, therefore even though you push a new image to container registry, when you spin up some pods, your pod says "image already present".

For a case in Azure Container Registry (probably AWS and GCP also provides this):

  1. You can look to your Azure Container Registry and by checking the manifest creation date you can identify what image is the most recent one.

  2. Then, copy its digest hash (which has a format of sha256:xxx...xxx).

  3. You can scale down your current replica by running command below. Note that this will obviously stop your container and cause downtime.

kubectl scale --replicas=0 deployment <deployment-name> -n <namespace-name>
  1. Then you can get the copy of the deployment.yaml by running:
kubectl get deployments.apps <deployment-name> -o yaml > deployment.yaml
  1. Then change the line with image field from <image-name>:<tag> to <image-name>@sha256:xxx...xxx, save the file.

  2. Now you can scale up your replicas again. New image will be pulled with its unique digest.

Note: It is assumed that, imagePullPolicy: Always field is present in the container.

How to convert Nonetype to int or string?

In some situations it is helpful to have a function to convert None to int zero:

def nz(value):

    '''
    Convert None to int zero else return value.
    '''

    if value == None:
        return 0
    return value

How to count digits, letters, spaces for a string in Python?

INPUT :

1

26

sadw96aeafae4awdw2 wd100awd

import re

a=int(input())
for i in range(a):
    b=int(input())
    c=input()

    w=re.findall(r'\d',c)
    x=re.findall(r'\d+',c)
    y=re.findall(r'\s+',c)
    z=re.findall(r'.',c)
    print(len(x))
    print(len(y))
    print(len(z)-len(y)-len(w))

OUTPUT :

4

1

19

The four digits are 96, 4, 2, 100 The number of spaces = 1 number of letters = 19

How to track down access violation "at address 00000000"

You start looking near that code that you know ran, and you stop looking when you reach the code you know didn't run.

What you're looking for is probably some place where your program calls a function through a function pointer, but that pointer is null.

It's also possible you have stack corruption. You might have overwritten a function's return address with zero, and the exception occurs at the end of the function. Check for possible buffer overflows, and if you are calling any DLL functions, make sure you used the right calling convention and parameter count.

This isn't an ordinary case of using a null pointer, like an unassigned object reference or PChar. In those cases, you'll have a non-zero "at address x" value. Since the instruction occurred at address zero, you know the CPU's instruction pointer was not pointing at any valid instruction. That's why the debugger can't show you which line of code caused the problem — there is no line of code. You need to find it by finding the code that lead up to the place where the CPU jumped to the invalid address.

The call stack might still be intact, which should at least get you pretty close to your goal. If you have stack corruption, though, you might not be able to trust the call stack.

Auto-center map with multiple markers in Google Maps API v3

There's an easier way, by extending an empty LatLngBounds rather than creating one explicitly from two points. (See this question for more details)

Should look something like this, added to your code:

//create empty LatLngBounds object
var bounds = new google.maps.LatLngBounds();
var infowindow = new google.maps.InfoWindow();    

for (i = 0; i < locations.length; i++) {  
  var marker = new google.maps.Marker({
    position: new google.maps.LatLng(locations[i][1], locations[i][2]),
    map: map
  });

  //extend the bounds to include each marker's position
  bounds.extend(marker.position);

  google.maps.event.addListener(marker, 'click', (function(marker, i) {
    return function() {
      infowindow.setContent(locations[i][0]);
      infowindow.open(map, marker);
    }
  })(marker, i));
}

//now fit the map to the newly inclusive bounds
map.fitBounds(bounds);

//(optional) restore the zoom level after the map is done scaling
var listener = google.maps.event.addListener(map, "idle", function () {
    map.setZoom(3);
    google.maps.event.removeListener(listener);
});

This way, you can use an arbitrary number of points, and don't need to know the order beforehand.

Demo jsFiddle here: http://jsfiddle.net/x5R63/

using wildcards in LDAP search filters/queries

Your best bet would be to anticipate prefixes, so:

"(|(displayName=SEARCHKEY*)(displayName=ITSM - SEARCHKEY*)(displayName=alt prefix - SEARCHKEY*))"

Clunky, but I'm doing a similar thing within my organization.

When should I use git pull --rebase?

git pull --rebase may hide a history rewriting from a collaborator git push --force. I recommend to use git pull --rebase only if you know you forgot to push your commits before someone else does the same.

If you did not commit anything, but your working space is not clean, just git stash before to git pull. This way you won't silently rewrite your history (which could silently drop some of your work).

Use grep --exclude/--include syntax to not grep through certain files

grep 2.5.3 introduced the --exclude-dir parameter which will work the way you want.

grep -rI --exclude-dir=\.svn PATTERN .

You can also set an environment variable: GREP_OPTIONS="--exclude-dir=\.svn"

I'll second Andy's vote for ack though, it's the best.

jQuery click function doesn't work after ajax call?

Since the class is added dynamically, you need to use event delegation to register the event handler like:

$('#LangTable').on('click', '.deletelanguage', function(event) {
    event.preventDefault();
    alert("success");
});

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

FIDDLE DEMO

How to printf "unsigned long" in C?

For int %d

For long int %ld

For long long int %lld

For unsigned long long int %llu

Convert a python 'type' object to a string

print type(someObject).__name__

If that doesn't suit you, use this:

print some_instance.__class__.__name__

Example:

class A:
    pass
print type(A())
# prints <type 'instance'>
print A().__class__.__name__
# prints A

Also, it seems there are differences with type() when using new-style classes vs old-style (that is, inheritance from object). For a new-style class, type(someObject).__name__ returns the name, and for old-style classes it returns instance.

How to convert R Markdown to PDF?

I found using R studio the easiest way, but if wanting to control from the command line, then a simple R script can do the trick using rmarkdown render command (as mentioned above). Full script details here

#!/usr/bin/env R

# Render R markdown to PDF.
# Invoke with:
# > R -q -f make.R --args my_report.Rmd

# load packages
require(rmarkdown)

# require a parameter naming file to render
if (length(args) == 0) {
    stop("Error: missing file operand", call. = TRUE)
} else {
    # read report to render from command line
    for (rmd in commandArgs(trailingOnly = TRUE)) {
        # render Rmd to PDF
        if ( grepl("\\.Rmd$", rmd) && file.exists(rmd)) {
            render(rmd, pdf_document())
        } else {
            print(paste("Ignoring: ", rmd))
        }
    }
}

Which HTTP methods match up to which CRUD methods?

The whole key is whether you're doing an idempotent change or not. That is, if taking action on the message twice will result in “the same” thing being there as if it was only done once, you've got an idempotent change and it should be mapped to PUT. If not, it maps to POST. If you never permit the client to synthesize URLs, PUT is pretty close to Update and POST can handle Create just fine, but that's most certainly not the only way to do it; if the client knows that it wants to create /foo/abc and knows what content to put there, it works just fine as a PUT.

The canonical description of a POST is when you're committing to purchasing something: that's an action which nobody wants to repeat without knowing it. By contrast, setting the dispatch address for the order beforehand can be done with PUT just fine: it doesn't matter if you are told to send to 6 Anywhere Dr, Nowhereville once, twice or a hundred times: it's still the same address. Does that mean that it's an update? Could be… It all depends on how you want to write the back-end. (Note that the results might not be identical: you could report back to the user when they last did a PUT as part of the representation of the resource, which would ensure that repeated PUTs do not cause an identical result, but the result would still be “the same” in a functional sense.)

Splitting strings using a delimiter in python

So, your input is 'dan|warrior|54' and you want "warrior". You do this like so:

>>> dan = 'dan|warrior|54'
>>> dan.split('|')[1]
"warrior"

The type List is not generic; it cannot be parameterized with arguments [HTTPClient]

I got the same error, but when i did as below, it resolved the issue.
Instead of writing like this:

List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);

use the below one:

ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);

How to export a Vagrant virtual machine to transfer it

As stated in

How can I change where Vagrant looks for its virtual hard drive?

the virtual-machine state is stored in a predefined VirtualBox folder. Copying the corresponding machine (folder) besides your vagrant-project to your other host should preserve your virtual machine state.

How to make URL/Phone-clickable UILabel?

Why not just use NSMutableAttributedString?

let attributedString = NSMutableAttributedString(string: "Want to learn iOS? Just visit developer.apple.com!")
        attributedString.addAttribute(.link, value: "https://developer.apple.com", range: NSRange(location: 30, length: 50))

        myView.attributedText = attributedString

You can find more details here

How to hide TabPage from TabControl

No, this doesn't exist. You have to remove the tab and re-add it when you want it. Or use a different (3rd-party) tab control.

Git - Undo pushed commits

Another way to do this without revert (traces of undo):

Don't do it if someone else has pushed other commits

Create a backup of your branch, being in your branch my-branch. So in case something goes wrong, you can restart the process without losing any work done.

git checkout -b my-branch-temp

Go back to your branch.

git checkout my-branch

Reset, to discard your last commit (to undo it):

git reset --hard HEAD^

Remove the branch on remote (ex. origin remote).

git push origin :my-branch

Repush your branch (without the unwanted commit) to the remote.

git push origin my-branch

Done!

I hope that helps! ;)

How do I view cookies in Internet Explorer 11 using Developer Tools

How about typing document.cookie into the console? It just shows the values, but it's something.

enter image description here

Docker: unable to prepare context: unable to evaluate symlinks in Dockerfile path: GetFileAttributesEx

In case if we have multiple docker files in our environment just Dockerfile wont suffice our requirement.

docker build -t ihub -f Dockerfile.ihub .

So use the file (-f argument) command to specify your docker file(Dockerfile.ihub)

mvn clean install vs. deploy vs. release

  • mvn install will put your packaged maven project into the local repository, for local application using your project as a dependency.
  • mvn release will basically put your current code in a tag on your SCM, change your version in your projects.
  • mvn deploy will put your packaged maven project into a remote repository for sharing with other developers.

Resources :

Python dict how to create key or append an element to key?

You can use a defaultdict for this.

from collections import defaultdict
d = defaultdict(list)
d['key'].append('mykey')

This is slightly more efficient than setdefault since you don't end up creating new lists that you don't end up using. Every call to setdefault is going to create a new list, even if the item already exists in the dictionary.

How to set xlim and ylim for a subplot in matplotlib

You should use the OO interface to matplotlib, rather than the state machine interface. Almost all of the plt.* function are thin wrappers that basically do gca().*.

plt.subplot returns an axes object. Once you have a reference to the axes object you can plot directly to it, change its limits, etc.

import matplotlib.pyplot as plt

ax1 = plt.subplot(131)
ax1.scatter([1, 2], [3, 4])
ax1.set_xlim([0, 5])
ax1.set_ylim([0, 5])


ax2 = plt.subplot(132)
ax2.scatter([1, 2],[3, 4])
ax2.set_xlim([0, 5])
ax2.set_ylim([0, 5])

and so on for as many axes as you want.

or better, wrap it all up in a loop:

import matplotlib.pyplot as plt

DATA_x = ([1, 2],
          [2, 3],
          [3, 4])

DATA_y = DATA_x[::-1]

XLIMS = [[0, 10]] * 3
YLIMS = [[0, 10]] * 3

for j, (x, y, xlim, ylim) in enumerate(zip(DATA_x, DATA_y, XLIMS, YLIMS)):
    ax = plt.subplot(1, 3, j + 1)
    ax.scatter(x, y)
    ax.set_xlim(xlim)
    ax.set_ylim(ylim)

Unresolved external symbol on static class members

Static data members declarations in the class declaration are not definition of them. To define them you should do this in the .CPP file to avoid duplicated symbols.

The only data you can declare and define is integral static constants. (Values of enums can be used as constant values as well)

You might want to rewrite your code as:

class test {
public:
  const static unsigned char X = 1;
  const static unsigned char Y = 2;
  ...
  test();
};

test::test() {
}

If you want to have ability to modify you static variables (in other words when it is inappropriate to declare them as const), you can separate you code between .H and .CPP in the following way:

.H :

class test {
public:

  static unsigned char X;
  static unsigned char Y;

  ...

  test();
};

.CPP :

unsigned char test::X = 1;
unsigned char test::Y = 2;

test::test()
{
  // constructor is empty.
  // We don't initialize static data member here, 
  // because static data initialization will happen on every constructor call.
}

How to run only one unit test class using Gradle

In case you have a multi-module project :

let us say your module structure is

root-module
 -> a-module
 -> b-module

and the test(testToRun) you are looking to run is in b-module, with full path : com.xyz.b.module.TestClass.testToRun

As here you are interested to run the test in b-module, so you should see the tasks available for b-module.

./gradlew :b-module:tasks

The above command will list all tasks in b-module with description. And in ideal case, you will have a task named test to run the unit tests in that module.

./gradlew :b-module:test

Now, you have reached the point for running all the tests in b-module, finally you can pass a parameter to the above task to run tests which matches the certain path pattern

./gradlew :b-module:test --tests "com.xyz.b.module.TestClass.testToRun"

Now, instead of this if you run

./gradlew test --tests "com.xyz.b.module.TestClass.testToRun"

It will run the test task for both module a and b, which might result in failure as there is nothing matching the above pattern in a-module.

Sublime Text 2: How do I change the color that the row number is highlighted?

On windows 7, find

C:\Users\Simion\AppData\Roaming\Sublime Text 2\Packages\Color Scheme - Default

Find your color scheme file, open it, and find lineHighlight.
Ex:

<key>lineHighlight</key>
<string>#ccc</string>

replace #ccc with your preferred background color.

Change tab bar tint color on iOS 7

In app delegate didFinishLaunchingWithOptions:

window.tintColor = [UIColor purpleColor];

sets the tint color globally for the app.

How do you subtract Dates in Java?

Well you can remove the third calendar instance.

GregorianCalendar c1 = new GregorianCalendar();
GregorianCalendar c2 = new GregorianCalendar();
c1.set(2000, 1, 1);
c2.set(2010,1, 1);
c2.add(GregorianCalendar.MILLISECOND, -1 * c1.getTimeInMillis());

Refused to execute script, strict MIME type checking is enabled?

I solved my problem by adding just ${pageContext.request.contextPath} to my jsp path . in stead of :

 <script    src="static/js/jquery-3.2.1.min.js"></script>

I set :

 <script    src="${pageContext.request.contextPath}/static/js/jquery-3.2.1.min.js"></script>

SQL Server - inner join when updating

This should do it:

UPDATE ProductReviews
SET    ProductReviews.status = '0'
FROM   ProductReviews
       INNER JOIN products
         ON ProductReviews.pid = products.id
WHERE  ProductReviews.id = '17190'
       AND products.shopkeeper = '89137'

VBA Check if variable is empty

I had a similar issue with an integer that could be legitimately assigned 0 in Access VBA. None of the above solutions worked for me.

At first I just used a boolean var and IF statement:

Dim i as integer, bol as boolean
   If bol = false then
      i = ValueIWantToAssign
      bol = True
   End If

In my case, my integer variable assignment was within a for loop and another IF statement, so I ended up using "Exit For" instead as it was more concise.

Like so:

Dim i as integer
ForLoopStart
   If ConditionIsMet Then
      i = ValueIWantToAssign
   Exit For
   End If
ForLoopEnd

How to resolve 'unrecognized selector sent to instance'?

For me, what caused this error was that I accidentally had the same message being sent twice to the same class member. When I right clicked on the button in the gui, I could see the method name twice, and I just deleted one. Newbie mistake in my case for sure, but wanted to get it out there for other newbies to consider.

Understanding MongoDB BSON Document size limit

To post a clarification answer here for those who get directed here by Google.

The document size includes everything in the document including the subdocuments, nested objects etc.

So a document of:

{
  "_id": {},
  "na": [1, 2, 3],
  "naa": [
    { "w": 1, "v": 2, "b": [1, 2, 3] },
    { "w": 5, "b": 2, "h": [{ "d": 5, "g": 7 }, {}] }
  ]
}

Has a maximum size of 16 MB.

Subdocuments and nested objects are all counted towards the size of the document.

How to check if a date is in a given range?

Convert both dates to timestamps then do

pseudocode:

if date_from_user > start_date && date_from_user < end_date
    return true

php search array key and get value

<?php

// Checks if key exists (doesn't care about it's value).
// @link http://php.net/manual/en/function.array-key-exists.php
if (array_key_exists(20120504, $search_array)) {
  echo $search_array[20120504];
}

// Checks against NULL
// @link http://php.net/manual/en/function.isset.php
if (isset($search_array[20120504])) {
  echo $search_array[20120504];
}

// No warning or error if key doesn't exist plus checks for emptiness.
// @link http://php.net/manual/en/function.empty.php
if (!empty($search_array[20120504])) {
  echo $search_array[20120504];
}

?>

Token Authentication vs. Cookies

Http is stateless. In order to authorize you, you have to "sign" every single request you're sending to server.

Token authentication

  • A request to the server is signed by a "token" - usually it means setting specific http headers, however, they can be sent in any part of the http request (POST body, etc.)

  • Pros:

    • You can authorize only the requests you wish to authorize. (Cookies - even the authorization cookie are sent for every single request.)
    • Immune to XSRF (Short example of XSRF - I'll send you a link in email that will look like <img src="http://bank.com?withdraw=1000&to=myself" />, and if you're logged in via cookie authentication to bank.com, and bank.com doesn't have any means of XSRF protection, I'll withdraw money from your account simply by the fact that your browser will trigger an authorized GET request to that url.) Note there are anti forgery measure you can do with cookie-based authentication - but you have to implement those.
    • Cookies are bound to a single domain. A cookie created on the domain foo.com can't be read by the domain bar.com, while you can send tokens to any domain you like. This is especially useful for single page applications that are consuming multiple services that are requiring authorization - so I can have a web app on the domain myapp.com that can make authorized client-side requests to myservice1.com and to myservice2.com.
  • Cons:
    • You have to store the token somewhere; while cookies are stored "out of the box". The locations that comes to mind are localStorage (con: the token is persisted even after you close browser window), sessionStorage (pro: the token is discarded after you close browser window, con: opening a link in a new tab will render that tab anonymous) and cookies (Pro: the token is discarded after you close the browser window. If you use a session cookie you will be authenticated when opening a link in a new tab, and you're immune to XSRF since you're ignoring the cookie for authentication, you're just using it as token storage. Con: cookies are sent out for every single request. If this cookie is not marked as https only, you're open to man in the middle attacks.)
    • It is slightly easier to do XSS attack against token based authentication (i.e. if I'm able to run an injected script on your site, I can steal your token; however, cookie based authentication is not a silver bullet either - while cookies marked as http-only can't be read by the client, the client can still make requests on your behalf that will automatically include the authorization cookie.)
    • Requests to download a file, which is supposed to work only for authorized users, requires you to use File API. The same request works out of the box for cookie-based authentication.

Cookie authentication

  • A request to the server is always signed in by authorization cookie.
  • Pros:
    • Cookies can be marked as "http-only" which makes them impossible to be read on the client side. This is better for XSS-attack protection.
    • Comes out of the box - you don't have to implement any code on the client side.
  • Cons:
    • Bound to a single domain. (So if you have a single page application that makes requests to multiple services, you can end up doing crazy stuff like a reverse proxy.)
    • Vulnerable to XSRF. You have to implement extra measures to make your site protected against cross site request forgery.
    • Are sent out for every single request, (even for requests that don't require authentication).

Overall, I'd say tokens give you better flexibility, (since you're not bound to single domain). The downside is you have to do quite some coding by yourself.

Filling a List with all enum values in Java

This is a bit more readable:

Object[] allValues = all.getDeclaringClass().getEnumConstants();

How to perform Unwind segue programmatically?

Here's a complete answer with Objective C and Swift:

1) Create an IBAction unwind segue in your destination view controller (where you want to segue to). Anywhere in the implementation file.

// Objective C

    - (IBAction)unwindToContainerVC:(UIStoryboardSegue *)segue {

    }

// Swift

 @IBAction func unwindToContainerVC(segue: UIStoryboardSegue) {

    }

2) On the source view controller (the controller you're segueing from), ^ + drag from "Name of activity" to exit. You should see the unwind segue created in step 1 in the popup. (If you don't see it, review step one). Pick unwindToContainerVC: from the popup, or whatever you named your method to connect your source controller to the unwind IBAction.

enter image description here

3) Select the segue in the source view controller's document outline of the storyboard (it will be listed near the bottom), and give it an identifier.

enter image description here

4) Call the unwind segue using this method from source view controller, substituting your unwind segue name.

// Objective C

[self performSegueWithIdentifier:@"unwindToContainerVC" sender:self];

// Swift

self.performSegueWithIdentifier("unwindToContainerVC", sender: self)

NB. Use the sourceViewController property of the segue parameter on the unwind method to access any exposed properties on the source controller. Also, notice that the framework handles dismissing the source controller. If you'd like to confirm this add a dealloc method to the source controller with a log message that should fire once it has been killed. If dealloc doesn't fire you may have a retain cycle.

Check if table exists in SQL Server

IF EXISTS 
(
    SELECT   * 
    FROM     sys.objects 
    WHERE    object_id = OBJECT_ID(N'[dbo].[Mapping_APCToFANavigator]') 
             AND 
             type in (N'U')
)
BEGIN

    -- Do whatever you need to here.

END

Here in the above code, the table name is Mapping_APCToFANavigator.

UML diagram shapes missing on Visio 2013

If you don't find Stencils you can locate them in your install location. C:\Program Files\Microsoft Office\Office15\Visio Content\1033 for UML Sequcen Stencies you can open

NVIDIA-SMI has failed because it couldn't communicate with the NVIDIA driver

I just want to thank @Heapify for providing a practical answer and update his answer because the attached links are not up-to-date.

Step 1: Check the existing kernel of your Ubuntu Linux:

uname -a

Step 2:

Ubuntu maintains a website for all the versions of kernel that have been released. At the time of this writing, the latest stable release of Ubuntu kernel is 4.15. If you go to this link: http://kernel.ubuntu.com/~kernel-ppa/mainline/v4.15/, you will see several links for download.

Step 3:

Download the appropriate files based on the type of OS you have. For 64 bit, I would download the following deb files:

// UP-TO-DATE 2019-03-18
wget https://kernel.ubuntu.com/~kernel-ppa/mainline/v4.15/linux-headers-4.15.0-041500_4.15.0-041500.201802011154_all.deb
wget https://kernel.ubuntu.com/~kernel-ppa/mainline/v4.15/linux-headers-4.15.0-041500-generic_4.15.0-041500.201802011154_amd64.deb
wget https://kernel.ubuntu.com/~kernel-ppa/mainline/v4.15/linux-image-4.15.0-041500-generic_4.15.0-041500.201802011154_amd64.deb

Step 4:

Install all the downloaded deb files:

sudo dpkg -i *.deb

Step 5:

Reboot your machine and check if the kernel has been updated by:

uname -aenter code here

Display only 10 characters of a long string?

And here's a jQuery example:

HTML text field:

<input type="text" id="myTextfield" />

jQuery code to limit its size:

var elem = $("#myTextfield");
if(elem) elem.val(elem.val().substr(0,10));

As an example, you could use the jQuery code above to restrict the user from entering more than 10 characters while he's typing; the following code snippet does exactly this:

$(document).ready(function() {
    var elem = $("#myTextfield");
    if (elem) {
        elem.keydown(function() {
            if (elem.val().length > 10)
                elem.val(elem.val().substr(0, 10));
        });
    }            
});

Update: The above code snippet was only used to show an example usage.

The following code snippet will handle you issue with the DIV element:

$(document).ready(function() {
    var elem = $(".tasks-overflow");
    if(elem){
        if (elem.text().length > 10)
                elem.text(elem.text().substr(0,10))
    }
});

Please note that I'm using text instead of val in this case, since the val method doesn't seem to work with the DIV element.

button image as form input submit button?

Late to the conversation...

But, why not use css? That way you can keep the button as a submit type.

html:

<input type="submit" value="go" />

css:

button, input[type="submit"] {
    background:url(/images/submit.png) no-repeat;"
}

Works like a charm.

EDIT: If you want to remove the default button styles, you can use the following css:

button, input[type="submit"]{
    color: inherit;
    border: none;
    padding: 0;
    font: inherit;
    cursor: pointer;
    outline: inherit;
}

from this SO question

How to use the unsigned Integer in Java 8 and Java 9?

If using a third party library is an option, there is jOOU (a spin off library from jOOQ), which offers wrapper types for unsigned integer numbers in Java. That's not exactly the same thing as having primitive type (and thus byte code) support for unsigned types, but perhaps it's still good enough for your use-case.

import static org.joou.Unsigned.*;

// and then...
UByte    b = ubyte(1);
UShort   s = ushort(1);
UInteger i = uint(1);
ULong    l = ulong(1);

All of these types extend java.lang.Number and can be converted into higher-order primitive types and BigInteger.

(Disclaimer: I work for the company behind these libraries)

insert a NOT NULL column to an existing table

ALTER TABLE `MY_TABLE` ADD COLUMN `STAGE` INTEGER UNSIGNED NOT NULL AFTER `PREV_COLUMN`;

Map and filter an array at the same time

Use Array.prototy.filter itself

function renderOptions(options) {
    return options.filter(function(option){
        return !option.assigned;
    }).map(function (option) {
        return (someNewObject);
    });   
}

How to convert Java String to JSON Object

Your json -

{
    "title":"Free Music Archive - Genres",
    "message":"",
    "errors":[
    ],
    "total":"163",
    "total_pages":82,
    "page":1,
    "limit":"2",
    "dataset":[
    {
    "genre_id":"1",
    "genre_parent_id":"38",
    "genre_title":"Avant-Garde",
    "genre_handle":"Avant-Garde",
    "genre_color":"#006666"
    },
    {
    "genre_id":"2",
    "genre_parent_id":null,
    "genre_title":"International",
    "genre_handle":"International",
    "genre_color":"#CC3300"
    }
    ]
    }

Using the JSON library from json.org -

JSONObject o = new JSONObject(jsonString);

NOTE:

The following information will be helpful to you - json.org.

UPDATE:

import org.json.JSONObject;
 //Other lines of code
URL seatURL = new URL("http://freemusicarchive.org/
 api/get/genres.json?api_key=60BLHNQCAOUFPIBZ&limit=2");
 //Return the JSON Response from the API
 BufferedReader br = new BufferedReader(new         
 InputStreamReader(seatURL.openStream(),
 Charset.forName("UTF-8")));
 String readAPIResponse = " ";
 StringBuilder jsonString = new StringBuilder();
 while((readAPIResponse = br.readLine()) != null){
   jsonString.append(readAPIResponse);
 }
 JSONObject jsonObj = new JSONObject(jsonString.toString());
 System.out.println(jsonString);
 System.out.println("---------------------------");
 System.out.println(jsonObj);

Javascript: open new page in same window

<script type="text/javascript">
window.open ('YourNewPage.htm','_self',false)
</script>

see reference: http://www.w3schools.com/jsref/met_win_open.asp

How to generate and manually insert a uniqueidentifier in sql server?

Kindly check Column ApplicationId datatype in Table aspnet_Users , ApplicationId column datatype should be uniqueidentifier .

*Your parameter order is passed wrongly , Parameter @id should be passed as first argument, but in your script it is placed in second argument..*

So error is raised..

Please refere sample script:

DECLARE @id uniqueidentifier
SET @id = NEWID()
Create Table #temp1(AppId uniqueidentifier)

insert into #temp1 values(@id)

Select * from #temp1

Drop Table #temp1

Make $JAVA_HOME easily changable in Ubuntu

I know this is a long cold question, but it comes up every time there is a new or recent major Java release. Now this would easily apply to 6 and 7 swapping.

I have done this in the past with update-java-alternatives: http://manpages.ubuntu.com/manpages/hardy/man8/update-java-alternatives.8.html

How to catch a unique constraint error in a PL/SQL block?

I'm sure you have your reasons, but just in case... you should also consider using a "merge" query instead:

begin
    merge into some_table st
    using (select 'some' name, 'values' value from dual) v
    on (st.name=v.name)
    when matched then update set st.value=v.value
    when not matched then insert (name, value) values (v.name, v.value);
end;

(modified the above to be in the begin/end block; obviously you can run it independantly of the procedure too).

Find records with a date field in the last 24 hours

There are so many ways to do this. The listed ones work great, but here's another way if you have a datetime field:

SELECT [fields] 
FROM [table] 
WHERE timediff(now(), my_datetime_field) < '24:00:00'

timediff() returns a time object, so don't make the mistake of comparing it to 86400 (number of seconds in a day), or your output will be all kinds of wrong.

Convert string to a variable name

Maybe I didn't understand your problem right, because of the simplicity of your example. To my understanding, you have a series of instructions stored in character vectors, and those instructions are very close to being properly formatted, except that you'd like to cast the right member to numeric.

If my understanding is right, I would like to propose a slightly different approach, that does not rely on splitting your original string, but directly evaluates your instruction (with a little improvement).

original_string <- "variable_name=\"10\"" # Your original instruction, but with an actual numeric on the right, stored as character.
library(magrittr) # Or library(tidyverse), but it seems a bit overkilled if the point is just to import pipe-stream operator
eval(parse(text=paste(eval(original_string), "%>% as.numeric")))
print(variable_name)
#[1] 10

Basically, what we are doing is that we 'improve' your instruction variable_name="10" so that it becomes variable_name="10" %>% as.numeric, which is an equivalent of variable_name=as.numeric("10") with magrittr pipe-stream syntax. Then we evaluate this expression within current environment.

Hope that helps someone who'd wander around here 8 years later ;-)

pip broke. how to fix DistributionNotFound error?

I had this problem because I installed python/pip with a weird ~/.pydistutils.cfg that I didn't remember writing. Deleted it, reinstalled (with pybrew), and everything was fine.

All com.android.support libraries must use the exact same version specification

include the following line:

implementation 'com.android.support:support-v4:27.1.1'

Make sure you are using android studio plugin 3+

enter image description here

Addressing localhost from a VirtualBox virtual machine

macOS

I'm running Virtual Box on macOS (previously OS X), using Virtual Box to test IE on Windows, etc.

Go to IE in Virtual Box and access localhost via http://10.0.2.2 for localhost, or http://10.0.2.2:3000 for localhost:3000.

I kept Network settings as NAT, no need for bridge as suggested above in my case. There is no need to edit any config files.

How do I get the path to the current script with Node.js?

var settings = 
    JSON.parse(
        require('fs').readFileSync(
            require('path').resolve(
                __dirname, 
                'settings.json'),
            'utf8'));

How to iterate a table rows with JQuery and access some cell values?

try this

var value = iterate('tr.item span.value');
var quantity = iterate('tr.item span.quantity');

function iterate(selector)
{
  var result = '';
  if ($(selector))
  {
    $(selector).each(function ()
    {
      if (result == '')
      {
        result = $(this).html();
      }
      else
      {
        result = result + "," + $(this).html();
      }
    });
  }
}

How do I give text or an image a transparent background using CSS?

You can use pure CSS 3: rgba(red, green, blue, alpha), where alpha is the level of transparency you want. There is no need for JavaScript or jQuery.

Here is an example:

#item-you-want-to-style{
    background:rgba(192.233, 33, 0.5)
}

SELECT using 'CASE' in SQL

Change to:

SELECT 
  CASE 
    WHEN FRUIT = 'A' THEN 'APPLE' 
    WHEN FRUIT = 'B' THEN 'BANANA'     
  END
FROM FRUIT_TABLE;

Is Java's assertEquals method reliable?

assertEquals uses the equals method for comparison. There is a different assert, assertSame, which uses the == operator.

To understand why == shouldn't be used with strings you need to understand what == does: it does an identity check. That is, a == b checks to see if a and b refer to the same object. It is built into the language, and its behavior cannot be changed by different classes. The equals method, on the other hand, can be overridden by classes. While its default behavior (in the Object class) is to do an identity check using the == operator, many classes, including String, override it to instead do an "equivalence" check. In the case of String, instead of checking if a and b refer to the same object, a.equals(b) checks to see if the objects they refer to are both strings that contain exactly the same characters.

Analogy time: imagine that each String object is a piece of paper with something written on it. Let's say I have two pieces of paper with "Foo" written on them, and another with "Bar" written on it. If I take the first two pieces of paper and use == to compare them it will return false because it's essentially asking "are these the same piece of paper?". It doesn't need to even look at what's written on the paper. The fact that I'm giving it two pieces of paper (rather than the same one twice) means it will return false. If I use equals, however, the equals method will read the two pieces of paper and see that they say the same thing ("Foo"), and so it'll return true.

The bit that gets confusing with Strings is that the Java has a concept of "interning" Strings, and this is (effectively) automatically performed on any string literals in your code. This means that if you have two equivalent string literals in your code (even if they're in different classes) they'll actually both refer to the same String object. This makes the == operator return true more often than one might expect.

How to delete row based on cell value

if you want to delete rows based on some specific cell value. let suppose we have a file containing 10000 rows, and a fields having value of NULL. and based on that null value want to delete all those rows and records.

here are some simple tip. First open up Find Replace dialog, and on Replace tab, make all those cell containing NULL values with Blank. then press F5 and select the Blank option, now right click on the active sheet, and select delete, then option for Entire row.

it will delete all those rows based on cell value of containing word NULL.

What is the default stack size, can it grow, how does it work with garbage collection?

How much a stack can grow?

You can use a VM option named ss to adjust the maximum stack size. A VM option is usually passed using -X{option}. So you can use java -Xss1M to set the maximum of stack size to 1M.

Each thread has at least one stack. Some Java Virtual Machines(JVM) put Java stack(Java method calls) and native stack(Native method calls in VM) into one stack, and perform stack unwinding using a Managed to Native Frame, known as M2NFrame. Some JVMs keep two stacks separately. The Xss set the size of the Java Stack in most cases.

For many JVMs, they put different default values for stack size on different platforms.

Can we limit this growth?

When a method call occurs, a new stack frame will be created on the stack of that thread. The stack will contain local variables, parameters, return address, etc. In java, you can never put an object on stack, only object reference can be stored on stack. Since array is also an object in java, arrays are also not stored on stack. So, if you reduce the amount of your local primitive variables, parameters by grouping them into objects, you can reduce the space on stack. Actually, the fact that we cannot explicitly put objects on java stack affects the performance some time(cache miss).

Does stack has some default minimum value or default maximum value?

As I said before, different VMs are different, and may change over versions. See here.

how does garbage collection work on stack?

Garbage collections in Java is a hot topic. Garbage collection aims to collect unreachable objects in the heap. So that needs a definition of 'reachable.' Everything on the stack constitutes part of the root set references in GC. Everything that is reachable from every stack of every thread should be considered as live. There are some other root set references, like Thread objects and some class objects.

This is only a very vague use of stack on GC. Currently most JVMs are using a generational GC. This article gives brief introduction about Java GC. And recently I read a very good article talking about the GC on .net. The GC on oracle jvm is quite similar so I think that might also help you.

Display open transactions in MySQL

Although there won't be any remaining transaction in the case, as @Johan said, you can see the current transaction list in InnoDB with the query below if you want.

SELECT * FROM information_schema.innodb_trx\G

From the document:

The INNODB_TRX table contains information about every transaction (excluding read-only transactions) currently executing inside InnoDB, including whether the transaction is waiting for a lock, when the transaction started, and the SQL statement the transaction is executing, if any.

blur() vs. onblur()

Contrary to what pointy says, the blur() method does exist and is a part of the w3c standard. The following exaple will work in every modern browser (including IE):

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
    <head>
        <title>Javascript test</title>
        <script type="text/javascript" language="javascript">
            window.onload = function()
            {
                var field = document.getElementById("field");
                var link = document.getElementById("link");
                var output = document.getElementById("output");

                field.onfocus = function() { output.innerHTML += "<br/>field.onfocus()"; };
                field.onblur = function() { output.innerHTML += "<br/>field.onblur()"; };
                link.onmouseover = function() { field.blur(); };
            };
        </script>
    </head>
    <body>
        <form name="MyForm">
            <input type="text" name="field" id="field" />
            <a href="javascript:void(0);" id="link">Blur field on hover</a>
            <div id="output"></div>
        </form>
    </body>
</html>

Note that I used link.onmouseover instead of link.onclick, because otherwise the click itself would have removed the focus.

What is a Python egg?

Python eggs are a way of bundling additional information with a Python project, that allows the project's dependencies to be checked and satisfied at runtime, as well as allowing projects to provide plugins for other projects. There are several binary formats that embody eggs, but the most common is '.egg' zipfile format, because it's a convenient one for distributing projects. All of the formats support including package-specific data, project-wide metadata, C extensions, and Python code.

The easiest way to install and use Python eggs is to use the "Easy Install" Python package manager, which will find, download, build, and install eggs for you; all you do is tell it the name (and optionally, version) of the Python project(s) you want to use.

Python eggs can be used with Python 2.3 and up, and can be built using the setuptools package (see the Python Subversion sandbox for source code, or the EasyInstall page for current installation instructions).

The primary benefits of Python Eggs are:

  • They enable tools like the "Easy Install" Python package manager

  • .egg files are a "zero installation" format for a Python package; no build or install step is required, just put them on PYTHONPATH or sys.path and use them (may require the runtime installed if C extensions or data files are used)

  • They can include package metadata, such as the other eggs they depend on

  • They allow "namespace packages" (packages that just contain other packages) to be split into separate distributions (e.g. zope., twisted., peak.* packages can be distributed as separate eggs, unlike normal packages which must always be placed under the same parent directory. This allows what are now huge monolithic packages to be distributed as separate components.)

  • They allow applications or libraries to specify the needed version of a library, so that you can e.g. require("Twisted-Internet>=2.0") before doing an import twisted.internet.

  • They're a great format for distributing extensions or plugins to extensible applications and frameworks (such as Trac, which uses eggs for plugins as of 0.9b1), because the egg runtime provides simple APIs to locate eggs and find their advertised entry points (similar to Eclipse's "extension point" concept).

There are also other benefits that may come from having a standardized format, similar to the benefits of Java's "jar" format.

How to find Google's IP address?

If all you are trying to do is find the IP address that corresponds to a domain name, like google.com, this is very easy on every machine connected to the Internet.

Simply run the ping command from any command prompt. Typing something like

ping google.com

will give you (among other things) that information.

Python error: TypeError: 'module' object is not callable for HeadFirst Python code

Your module and your class AthleteList have the same name. The line

import AthleteList

imports the module and creates a name AthleteList in your current scope that points to the module object. If you want to access the actual class, use

AthleteList.AthleteList

In particular, in the line

return(AthleteList(templ.pop(0), templ.pop(0), templ))

you are actually accessing the module object and not the class. Try

return(AthleteList.AthleteList(templ.pop(0), templ.pop(0), templ))

Retrofit and GET using parameters

I also wanted to clarify that if you have complex url parameters to build, you will need to build them manually. ie if your query is example.com/?latlng=-37,147, instead of providing the lat and lng values individually, you will need to build the latlng string externally, then provide it as a parameter, ie:

public interface LocationService {    
    @GET("/example/")
    void getLocation(@Query(value="latlng", encoded=true) String latlng);
}

Note the encoded=true is necessary, otherwise retrofit will encode the comma in the string parameter. Usage:

String latlng = location.getLatitude() + "," + location.getLongitude();
service.getLocation(latlng);

Empty set literal?

Adding to the crazy ideas: with Python 3 accepting unicode identifiers, you could declare a variable ? = frozenset() (? is U+03D5) and use it instead.

Grant execute permission for a user on all stored procedures in database?

Create a role add this role to users, and then you can grant execute to all the routines in one shot to this role.

CREATE ROLE <abc>
GRANT EXECUTE TO <abc>

EDIT
This works in SQL Server 2005, I'm not sure about backward compatibility of this feature, I'm sure anything later than 2005 should be fine.

Full width image with fixed height

<div id="container">
    <img style="width: 100%; height: 40%;" id="image" src="...">
</div>

I hope this will serve your purpose.

CSS Select box arrow style

Please follow the way like below:

_x000D_
_x000D_
.selectParent {_x000D_
 width:120px;_x000D_
 overflow:hidden;   _x000D_
}_x000D_
.selectParent select { _x000D_
 display: block;_x000D_
 width: 100%;_x000D_
 padding: 2px 25px 2px 2px; _x000D_
 border: none; _x000D_
 background: url("http://cdn1.iconfinder.com/data/icons/cc_mono_icon_set/blacks/16x16/br_down.png") right center no-repeat; _x000D_
 appearance: none; _x000D_
 -webkit-appearance: none;_x000D_
 -moz-appearance: none; _x000D_
}_x000D_
.selectParent.left select {_x000D_
 direction: rtl;_x000D_
 padding: 2px 2px 2px 25px;_x000D_
 background-position: left center;_x000D_
}_x000D_
/* for IE and Edge */ _x000D_
select::-ms-expand { _x000D_
 display: none; _x000D_
}
_x000D_
<div class="selectParent">_x000D_
  <select>_x000D_
    <option value="1">Option 1</option>_x000D_
    <option value="2">Option 2</option>           _x000D_
   </select>_x000D_
</div>_x000D_
<br />_x000D_
<div class="selectParent left">_x000D_
  <select>_x000D_
    <option value="1">Option 1</option>_x000D_
    <option value="2">Option 2</option>           _x000D_
   </select>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Convert numpy array to tuple

Another option

tuple([tuple(row) for row in myarray])

If you are passing NumPy arrays to C++ functions, you may also wish to look at using Cython or SWIG.

CSS: Hover one element, effect for multiple elements?

You don't need JavaScript for this.

Some CSS would do it. Here is an example:

_x000D_
_x000D_
<html>_x000D_
  <style type="text/css">_x000D_
    .section { background:#ccc; }_x000D_
    .layer { background:#ddd; }_x000D_
    .section:hover img { border:2px solid #333; }_x000D_
    .section:hover .layer { border:2px solid #F90; }_x000D_
  </style>_x000D_
</head>_x000D_
<body>_x000D_
  <div class="section">_x000D_
    <img src="myImage.jpg" />_x000D_
    <div class="layer">Lorem Ipsum</div>_x000D_
  </div>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

tell pip to install the dependencies of packages listed in a requirement file

Any way to do this without manually re-installing the packages in a new virtualenv to get their dependencies ? This would be error-prone and I'd like to automate the process of cleaning the virtualenv from no-longer-needed old dependencies.

That's what pip-tools package is for (from https://github.com/jazzband/pip-tools):

Installation

$ pip install --upgrade pip  # pip-tools needs pip==6.1 or higher (!)
$ pip install pip-tools

Example usage for pip-compile

Suppose you have a Flask project, and want to pin it for production. Write the following line to a file:

# requirements.in
Flask

Now, run pip-compile requirements.in:

$ pip-compile requirements.in
#
# This file is autogenerated by pip-compile
# Make changes in requirements.in, then run this to update:
#
#    pip-compile requirements.in
#
flask==0.10.1
itsdangerous==0.24        # via flask
jinja2==2.7.3             # via flask
markupsafe==0.23          # via jinja2
werkzeug==0.10.4          # via flask

And it will produce your requirements.txt, with all the Flask dependencies (and all underlying dependencies) pinned. Put this file under version control as well and periodically re-run pip-compile to update the packages.

Example usage for pip-sync

Now that you have a requirements.txt, you can use pip-sync to update your virtual env to reflect exactly what's in there. Note: this will install/upgrade/uninstall everything necessary to match the requirements.txt contents.

$ pip-sync
Uninstalling flake8-2.4.1:
  Successfully uninstalled flake8-2.4.1
Collecting click==4.1
  Downloading click-4.1-py2.py3-none-any.whl (62kB)
    100% |¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦| 65kB 1.8MB/s
  Found existing installation: click 4.0
    Uninstalling click-4.0:
      Successfully uninstalled click-4.0
Successfully installed click-4.1

How to create a POJO?

there are mainly three options are possible for mapping purpose

  1. serialize
  2. XML mapping
  3. POJO mapping.(Plain Old Java Objects)

While using the pojo classes,it is easy for a developer to map with the database. POJO classes are created for database and at the same time value-objects classes are created with getter and setter methods that will easily hold the content.

So,for the purpose of mapping in between java with database, value-objects and POJO classes are implemented.

What's the PowerShell syntax for multiple values in a switch statement?

A slight modification to derekerdmann's post to meet the original request using regex's alternation operator "|"(pipe).

It's also slightly easier for regex newbies to understand and read.

Note that while using regex, if you don't put the start of string character "^"(caret/circumflex) and/or end of string character "$"(dollar) then you may get unexpected/unintuitive behavior (like matching "yesterday" or "why").

Putting grouping characters "()"(parentheses) around the options reduces the need to put start and end of string characters for each option. Without them, you'll get possibly unexpected behavior if you're not savvy with regex. Of course, if you're not processing user input, but rather some set of known strings, it will be more readable without grouping and start and end of string characters.

switch -regex ($someString) #many have noted ToLower() here is redundant
{
        #processing user input
    "^(y|yes|indubitably)$" { "You entered Yes." }

        # not processing user input
    "y|yes|indubitably" { "Yes was the selected string" } 
    default { "You entered No." } 
}

Run PowerShell command from command prompt (no ps1 script)

This works from my Windows 10's cmd.exe prompt

powershell -ExecutionPolicy Bypass -Command "Import-Module C:\Users\william\ps1\TravelBook; Get-TravelBook Hawaii"

This example shows

  1. how to chain multiple commands
  2. how to import module with module path
  3. how to run a function defined in the module
  4. No need for those fancy "&".

How to VueJS router-link active style

Just add to @Bert's solution to make it more clear:

    const routes = [
  { path: '/foo', component: Foo },
  { path: '/bar', component: Bar }
]

const router = new VueRouter({
  routes,
  linkExactActiveClass: "active" // active class for *exact* links.
})

As one can see, this line should be removed:

linkActiveClass: "active", // active class for non-exact links.

this way, ONLY the current link is hi-lighted. This should apply to most of the cases.

David

How to set Internet options for Android emulator?

You can do it using AVD Manager, choose Tools -> Options. Set HTTP Proxy Server to 8.8.8.8,8.8.4.4

The emulator will be connected.

Detect change to ngModel on a select tag (Angular 2)

I have stumbled across this question and I will submit my answer that I used and worked pretty well. I had a search box that filtered and array of objects and on my search box I used the (ngModelChange)="onChange($event)"

in my .html

<input type="text" [(ngModel)]="searchText" (ngModelChange)="reSearch(newValue)" placeholder="Search">

then in my component.ts

reSearch(newValue: string) {
    //this.searchText would equal the new value
    //handle my filtering with the new value
}

Reload content in modal (twitter bootstrap)

I was also stuck on this problem then I saw that the ids of the modal are the same. You need different ids of modals if you want multiple modals. I used dynamic id. Here is my code in haml:

.modal.hide.fade{"id"=> discount.id,"aria-hidden" => "true", "aria-labelledby" => "myModalLabel", :role => "dialog", :tabindex => "-1"}

you can do this

<div id="<%= some.id %>" class="modal hide fade in">
  <div class="modal-header">
    <a class="close" data-dismiss="modal">×</a>
    <h3>Header</h3>
  </div>
  <div class="modal-body"></div>
  <div class="modal-footer">
    <input type="submit" class="btn btn-success" value="Save" />
  </div>
</div>

and your links to modal will be

<a data-toggle="modal" data-target="#" href='"#"+<%= some.id %>' >Open modal</a>
<a data-toggle="modal" data-target="#myModal" href='"#"+<%= some.id %>' >Open modal</a>
<a data-toggle="modal" data-target="#myModal" href='"#"+<%= some.id %>' >Open modal</a>

I hope this will work for you.

Input from the keyboard in command line application

When readLine() function is run on Xcode, the debug console waits for input. The rest of the code will be resumed after input is done.

    let inputStr = readLine()
    if let inputStr = inputStr {
        print(inputStr)
    }

Using RegEX To Prefix And Append In Notepad++

Use a Macro.

Macro>Start Recording

Use the keyboard to make your changes in a repeatable manner e.g.

home>type "able">end>down arrow>home

Then go back to the menu and click stop recording then run a macro multiple times.

That should do it and no regex based complications!

Check whether variable is number or string in JavaScript

Type checking

You can check the type of variable by using typeof operator:

typeof variable

Value checking

The code below returns true for numbers and false for anything else:

!isNaN(+variable);

Image, saved to sdcard, doesn't appear in Android's Gallery app

Try this one, it will broadcast about a new image created, so your image visible. inside a gallery. photoFile replace with actual file path of the newly created image

private void galleryAddPicBroadCast() {
        Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        Uri contentUri = Uri.fromFile(photoFile);
        mediaScanIntent.setData(contentUri);
        this.sendBroadcast(mediaScanIntent);
    }

How do I mount a host directory as a volume in docker compose

Checkout their documentation

From the looks of it you could do the following on your docker-compose.yml

volumes:
    - ./:/app

Where ./ is the host directory, and /app is the target directory for the containers.


EDIT:
Previous documentation source now leads to version history, you'll have to select the version of compose you're using and look for the reference.

For the lazy – v3 / v2 / v1

Side note: Syntax remains the same for all versions as of this edit

How can I check if an array contains a specific value in php?

Using dynamic variable for search in array

 /* https://ideone.com/Pfb0Ou */

$array = array('kitchen', 'bedroom', 'living_room', 'dining_room');

/* variable search */
$search = 'living_room';

if (in_array($search, $array)) {
    echo "this array contains $search";
} else
    echo "this array NOT contains $search";

You don't have write permissions for the /var/lib/gems/2.3.0 directory

Building on derek's answer above, it is generally not recommended to use the system provided Ruby instance for your own development work, as system tools might depend on the particular version or location of the Ruby install. Similar to this answer for Mac OSX, you will want to follow derek's instructions on using something like rbenv (RVM is a similar alternative) to install your own Ruby instance.

However, there is no need to uninstall the system version of Ruby, the rbenv installation instructions provide a mechanism to make sure that the instance of Ruby available in your shell is the rbenv instance, not the system instance. This is the

echo 'eval "$(rbenv init -)"' >> ~/.bashrc

line in derek's answer.

Importing a CSV file into a sqlite3 database table using Python

My 2 cents (more generic):

import csv, sqlite3
import logging

def _get_col_datatypes(fin):
    dr = csv.DictReader(fin) # comma is default delimiter
    fieldTypes = {}
    for entry in dr:
        feildslLeft = [f for f in dr.fieldnames if f not in fieldTypes.keys()]
        if not feildslLeft: break # We're done
        for field in feildslLeft:
            data = entry[field]

            # Need data to decide
            if len(data) == 0:
                continue

            if data.isdigit():
                fieldTypes[field] = "INTEGER"
            else:
                fieldTypes[field] = "TEXT"
        # TODO: Currently there's no support for DATE in sqllite

    if len(feildslLeft) > 0:
        raise Exception("Failed to find all the columns data types - Maybe some are empty?")

    return fieldTypes


def escapingGenerator(f):
    for line in f:
        yield line.encode("ascii", "xmlcharrefreplace").decode("ascii")


def csvToDb(csvFile, outputToFile = False):
    # TODO: implement output to file

    with open(csvFile,mode='r', encoding="ISO-8859-1") as fin:
        dt = _get_col_datatypes(fin)

        fin.seek(0)

        reader = csv.DictReader(fin)

        # Keep the order of the columns name just as in the CSV
        fields = reader.fieldnames
        cols = []

        # Set field and type
        for f in fields:
            cols.append("%s %s" % (f, dt[f]))

        # Generate create table statement:
        stmt = "CREATE TABLE ads (%s)" % ",".join(cols)

        con = sqlite3.connect(":memory:")
        cur = con.cursor()
        cur.execute(stmt)

        fin.seek(0)


        reader = csv.reader(escapingGenerator(fin))

        # Generate insert statement:
        stmt = "INSERT INTO ads VALUES(%s);" % ','.join('?' * len(cols))

        cur.executemany(stmt, reader)
        con.commit()

    return con

How to limit text width

use css property word-wrap: break-word;

see example here: http://jsfiddle.net/emgRF/

What process is listening on a certain port on Solaris?

I found this script somewhere. I don't remember where, but it works for me:

#!/bin/ksh

line='---------------------------------------------'
pids=$(/usr/bin/ps -ef | sed 1d | awk '{print $2}')

if [ $# -eq 0 ]; then
   read ans?"Enter port you would like to know pid for: "
else
   ans=$1
fi

for f in $pids
do
   /usr/proc/bin/pfiles $f 2>/dev/null | /usr/xpg4/bin/grep -q "port: $ans"
   if [ $? -eq 0 ]; then
      echo $line
      echo "Port: $ans is being used by PID:\c"
      /usr/bin/ps -ef -o pid -o args | egrep -v "grep|pfiles" | grep $f
   fi
done
exit 0

Edit: Here is the original source: [Solaris] Which process is bound to a given port ?

MIME types missing in IIS 7 for ASP.NET - 404.17

Fix:

I chose the "ISAPI & CGI Restrictions" after clicking the server name (not the site name) in IIS Manager, and right clicked the "ASP.NET v4.0.30319" lines and chose "Allow".

After turning on ASP.NET from "Programs and Features > Turn Windows features on or off", you must install ASP.NET from the Windows command prompt. The MIME types don't ever show up, but after doing this command, I noticed these extensions showed up under the IIS web site "Handler Mappings" section of IIS Manager.

C:\>cd C:\Windows\Microsoft.NET\Framework64\v4.0.30319

C:\Windows\Microsoft.NET\Framework64\v4.0.30319>dir aspnet_reg*
 Volume in drive C is Windows
 Volume Serial Number is 8EE6-5DD0

 Directory of C:\Windows\Microsoft.NET\Framework64\v4.0.30319

03/18/2010  08:23 PM            19,296 aspnet_regbrowsers.exe
03/18/2010  08:23 PM            36,696 aspnet_regiis.exe
03/18/2010  08:23 PM           102,232 aspnet_regsql.exe
               3 File(s)        158,224 bytes
               0 Dir(s)  34,836,508,672 bytes free

C:\Windows\Microsoft.NET\Framework64\v4.0.30319>aspnet_regiis.exe -i
Start installing ASP.NET (4.0.30319).
.....
Finished installing ASP.NET (4.0.30319).

C:\Windows\Microsoft.NET\Framework64\v4.0.30319>

However, I still got this error. But if you do what I mentioned for the "Fix", this will go away.

HTTP Error 404.2 - Not Found
The page you are requesting cannot be served because of the ISAPI and CGI Restriction list settings on the Web server.

What does -> mean in Python function definitions?

def f(x) -> str:
return x+4

print(f(45))

# will give the result : 
49

# or with other words '-> str' has NO effect to return type:

print(f(45).__class__)

<class 'int'>

what does "dead beef" mean?

It is also used for debugging purposes.

Here is a handy list of some of these values:

http://en.wikipedia.org/wiki/Magic_number_%28programming%29#Magic_debug_values

test if event handler is bound to an element in jQuery

This works for me: $('#profile1').attr('onclick')

Is a Java hashmap search really O(1)?

It is O(1) only if your hashing function is very good. The Java hash table implementation does not protect against bad hash functions.

Whether you need to grow the table when you add items or not is not relevant to the question because it is about lookup time.

Subtracting time.Duration from time in Go

In response to Thomas Browne's comment, because lnmx's answer only works for subtracting a date, here is a modification of his code that works for subtracting time from a time.Time type.

package main

import (
    "fmt"
    "time"
)

func main() {
    now := time.Now()

    fmt.Println("now:", now)

    count := 10
    then := now.Add(time.Duration(-count) * time.Minute)
    // if we had fix number of units to subtract, we can use following line instead fo above 2 lines. It does type convertion automatically.
    // then := now.Add(-10 * time.Minute)
    fmt.Println("10 minutes ago:", then)
}

Produces:

now: 2009-11-10 23:00:00 +0000 UTC
10 minutes ago: 2009-11-10 22:50:00 +0000 UTC

Not to mention, you can also use time.Hour or time.Second instead of time.Minute as per your needs.

Playground: https://play.golang.org/p/DzzH4SA3izp

laravel foreach loop in controller

Hi, this will throw an error:

foreach ($product->sku as $sku){ 
// Code Here
}

because you cannot loop a model with a specific column ($product->sku) from the table.
So you must loop on the whole model:

foreach ($product as $p) {
// code
}

Inside the loop you can retrieve whatever column you want just adding "->[column_name]"

foreach ($product as $p) {
echo $p->sku;
}

Have a great day

Send a ping to each IP on a subnet

for i in $(seq 1 254); do ping -c1 192.168.11.$i; done

Why do I need to configure the SQL dialect of a data source?

Databases implement subtle differences in the SQL they use. Things such as data types for example vary across databases (e.g. in Oracle You might put an integer value in a number field and in SQL Server use an int field). Or database specific functionality - selecting the top n rows is different depending on the database. The dialect abstracts this so you don't have to worry about it.

How to Detect Browser Back Button event - Cross Browser

if (window.performance && window.performance.navigation.type == window.performance.navigation.TYPE_BACK_FORWARD) {
  alert('hello world');
}

This is the only one solution that worked for me (it's not a onepage website). It's working with Chrome, Firefox and Safari.

How can I reduce the waiting (ttfb) time

I have met the same problem. My project is running on the local server. I checked my php code.

$db = mysqli_connect('localhost', 'root', 'root', 'smart');

I use localhost to connect to my local database. That maybe the cause of the problem which you're describing. You can modify your HOSTS file. Add the line

127.0.0.1 localhost.

Setting onClickListener for the Drawable right of an EditText

This has been already answered but I tried a different way to make it simpler.

The idea is using putting an ImageButton on the right of EditText and having negative margin to it so that the EditText flows into the ImageButton making it look like the Button is in the EditText.

enter image description here

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <EditText
            android:id="@+id/editText"
            android:layout_weight="1"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:hint="Enter Pin"
            android:singleLine="true"
            android:textSize="25sp"
            android:paddingRight="60dp"
            />
        <ImageButton
            android:id="@+id/pastePin"
            android:layout_marginLeft="-60dp"
            style="?android:buttonBarButtonStyle"
            android:paddingBottom="5dp"
            android:src="@drawable/ic_action_paste"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </LinearLayout>

Also, as shown above, you can use a paddingRight of similar width in the EditText if you don't want the text in it to be flown over the ImageButton.

I guessed margin size with the help of android-studio's layout designer and it looks similar across all screen sizes. Or else you can calculate the width of the ImageButton and set the margin programatically.

cURL POST command line on WINDOWS RESTful service

One more alternative cross-platform solution on powershell 6.2.3:

$headers = @{
    'Authorization' = 'Token 12d119ad48f9b70ed53846f9e3d051dc31afab27'
}

$body = @"
{
    "value":"3.92.0", 
    "product":"847"
}
"@


$params = @{
    Uri         = 'http://local.vcs:9999/api/v1/version/'
    Headers     = $headers
    Method      = 'POST'
    Body        = $body
    ContentType = 'application/json'

}

Invoke-RestMethod @params

MySQL - Replace Character in Columns

Replace below characters

~ ! @ # $ % ^ & * ( ) _ +
` - = 
{ } |
[ ] \
: " 
; '

< > ?
, . 

with this SQL

SELECT note as note_original, 

    REPLACE(
        REPLACE(
            REPLACE(
                REPLACE(
                    REPLACE(
                        REPLACE(
                            REPLACE(
                                REPLACE(
                                    REPLACE(
                                        REPLACE(
                                            REPLACE(
                                                REPLACE(
                                                    REPLACE(
                                                        REPLACE(
                                                            REPLACE(
                                                                REPLACE(
                                                                    REPLACE(
                                                                        REPLACE(
                                                                            REPLACE(
                                                                                REPLACE(
                                                                                    REPLACE(
                                                                                        REPLACE(
                                                                                            REPLACE(
                                                                                                REPLACE(
                                                                                                    REPLACE(
                                                                                                        REPLACE(
                                                                    REPLACE(
                                                                        REPLACE(
                                                                            REPLACE(
                                                                                REPLACE(
                                                                                    REPLACE(
                                                                                        REPLACE(
                                                                                            REPLACE(note, '\"', ''),
                                                                                        '.', ''),
                                                                                    '?', ''),
                                                                                '`', ''),
                                                                            '<', ''),
                                                                        '=', ''),
                                                                    '{', ''),
                                                                                                        '}', ''),
                                                                                                    '[', ''),
                                                                                                ']', ''),
                                                                                            '|', ''),
                                                                                        '\'', ''),
                                                                                    ':', ''),
                                                                                ';', ''),
                                                                            '~', ''),
                                                                        '!', ''),
                                                                    '@', ''),
                                                                '#', ''),
                                                            '$', ''),
                                                        '%', ''),
                                                    '^', ''),
                                                '&', ''),
                                            '*', ''),
                                        '_', ''),
                                    '+', ''),
                                ',', ''),
                            '/', ''),
                        '(', ''),
                    ')', ''),
                '-', ''),
            '>', ''),
        ' ', '-'),
    '--', '-') as note_changed FROM invheader

Using logging in multiple modules

A simple way of using one instance of logging library in multiple modules for me was following solution:

base_logger.py

import logging

logger = logging
logger.basicConfig(format='%(asctime)s - %(message)s', level=logging.INFO)

Other files

from base_logger import logger

if __name__ == '__main__':
    logger.info("This is an info message")

In WPF, what are the differences between the x:Name and Name attributes?

The specified x:Name becomes the name of a field that is created in the underlying code when XAML is processed, and that field holds a reference to the object. In Silverlight, using the managed API, the process of creating this field is performed by the MSBuild target steps, which also are responsible for joining the partial classes for a XAML file and its code-behind. This behavior is not necessarily XAML-language specified; it is the particular implementation that Silverlight applies to use x:Name in its programming and application models.

Read More on MSDN...

How to call one shell script from another shell script?

pathToShell="/home/praveen/"   
chmod a+x $pathToShell"myShell.sh"
sh $pathToShell"myShell.sh"

How do I read an image file using Python?

The word "read" is vague, but here is an example which reads a jpeg file using the Image class, and prints information about it.

from PIL import Image
jpgfile = Image.open("picture.jpg")

print(jpgfile.bits, jpgfile.size, jpgfile.format)

Passing Variable through JavaScript from one html page to another page

There are two pages: Pageone.html :

<script>
var hello = "hi"
location.replace("http://example.com/PageTwo.html?" + hi + "");
</script>

PageTwo.html :

<script>
var link = window.location.href;
link = link.replace("http://example.com/PageTwo.html?","");
document.write("The variable contained this content:" + link + "");
</script>

Hope it helps!

How do you log content of a JSON object in Node.js?

Try this one:

console.log("Session: %j", session);

If the object could be converted into JSON, that will work.

Model summary in pytorch

Yes, you can get exact Keras representation, using pytorch-summary package.

Example for VGG16

from torchvision import models
from torchsummary import summary

vgg = models.vgg16()
summary(vgg, (3, 224, 224))

----------------------------------------------------------------
        Layer (type)               Output Shape         Param #
================================================================
            Conv2d-1         [-1, 64, 224, 224]           1,792
              ReLU-2         [-1, 64, 224, 224]               0
            Conv2d-3         [-1, 64, 224, 224]          36,928
              ReLU-4         [-1, 64, 224, 224]               0
         MaxPool2d-5         [-1, 64, 112, 112]               0
            Conv2d-6        [-1, 128, 112, 112]          73,856
              ReLU-7        [-1, 128, 112, 112]               0
            Conv2d-8        [-1, 128, 112, 112]         147,584
              ReLU-9        [-1, 128, 112, 112]               0
        MaxPool2d-10          [-1, 128, 56, 56]               0
           Conv2d-11          [-1, 256, 56, 56]         295,168
             ReLU-12          [-1, 256, 56, 56]               0
           Conv2d-13          [-1, 256, 56, 56]         590,080
             ReLU-14          [-1, 256, 56, 56]               0
           Conv2d-15          [-1, 256, 56, 56]         590,080
             ReLU-16          [-1, 256, 56, 56]               0
        MaxPool2d-17          [-1, 256, 28, 28]               0
           Conv2d-18          [-1, 512, 28, 28]       1,180,160
             ReLU-19          [-1, 512, 28, 28]               0
           Conv2d-20          [-1, 512, 28, 28]       2,359,808
             ReLU-21          [-1, 512, 28, 28]               0
           Conv2d-22          [-1, 512, 28, 28]       2,359,808
             ReLU-23          [-1, 512, 28, 28]               0
        MaxPool2d-24          [-1, 512, 14, 14]               0
           Conv2d-25          [-1, 512, 14, 14]       2,359,808
             ReLU-26          [-1, 512, 14, 14]               0
           Conv2d-27          [-1, 512, 14, 14]       2,359,808
             ReLU-28          [-1, 512, 14, 14]               0
           Conv2d-29          [-1, 512, 14, 14]       2,359,808
             ReLU-30          [-1, 512, 14, 14]               0
        MaxPool2d-31            [-1, 512, 7, 7]               0
           Linear-32                 [-1, 4096]     102,764,544
             ReLU-33                 [-1, 4096]               0
          Dropout-34                 [-1, 4096]               0
           Linear-35                 [-1, 4096]      16,781,312
             ReLU-36                 [-1, 4096]               0
          Dropout-37                 [-1, 4096]               0
           Linear-38                 [-1, 1000]       4,097,000
================================================================
Total params: 138,357,544
Trainable params: 138,357,544
Non-trainable params: 0
----------------------------------------------------------------
Input size (MB): 0.57
Forward/backward pass size (MB): 218.59
Params size (MB): 527.79
Estimated Total Size (MB): 746.96
----------------------------------------------------------------

Pointers in Python?

It's not a bug, it's a feature :-)

When you look at the '=' operator in Python, don't think in terms of assignment. You don't assign things, you bind them. = is a binding operator.

So in your code, you are giving the value 1 a name: a. Then, you are giving the value in 'a' a name: b. Then you are binding the value 2 to the name 'a'. The value bound to b doesn't change in this operation.

Coming from C-like languages, this can be confusing, but once you become accustomed to it, you find that it helps you to read and reason about your code more clearly: the value which has the name 'b' will not change unless you explicitly change it. And if you do an 'import this', you'll find that the Zen of Python states that Explicit is better than implicit.

Note as well that functional languages such as Haskell also use this paradigm, with great value in terms of robustness.

How to iterate through a table rows and get the cell values using jQuery

Hello every one thanks for the help below is the working code for my question

$("#TableView tr.item").each(function() { 
    var quantity1=$(this).find("input.name").val(); 
    var quantity2=$(this).find("input.id").val(); 
});

Android - Best and safe way to stop thread

My requirement was slightly different than the question, still this is also a useful way of stopping the thread to be executing its tasks. All I wanted to do is to stop the thread on exiting the screen and resumes while returning to the screen.

As per the Android docs, this would be the proposed replacement for stop method which has been deprecated from API 15

Many uses of stop should be replaced by code that simply modifies some variable to indicate that the target thread should stop running. The target thread should check this variable regularly, and return from its run method in an orderly fashion if the variable indicates that it is to stop running.

My Thread class

   class ThreadClass implements Runnable {
            ...
                  @Override
                        public void run() {
                            while (count < name.length()) {

                                if (!exited) // checks boolean  
                                  {
                                   // perform your task
                                                     }
            ...

OnStop and OnResume would look like this

  @Override
    protected void onStop() {
        super.onStop();
        exited = true;
    }

    @Override
    protected void onResume() {
        super.onResume();
        exited = false;
    }

Changing website favicon dynamically

According to WikiPedia, you can specify which favicon file to load using the link tag in the head section, with a parameter of rel="icon".

For example:

 <link rel="icon" type="image/png" href="/path/image.png">

I imagine if you wanted to write some dynamic content for that call, you would have access to cookies so you could retrieve your session information that way and present appropriate content.

You may fall foul of file formats (IE reportedly only supports it's .ICO format, whilst most everyone else supports PNG and GIF images) and possibly caching issues, both on the browser and through proxies. This would be because of the original itention of favicon, specifically, for marking a bookmark with a site's mini-logo.

Smooth scroll without the use of jQuery

Here's the code that worked for me.

`$('a[href*="#"]')

    .not('[href="#"]')
    .not('[href="#0"]')
    .click(function(event) {
     if (
       location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '')
       &&
       location.hostname == this.hostname
        ) {

  var target = $(this.hash);
  target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
  if (target.length) {

    event.preventDefault();
    $('html, body').animate({
      scrollTop: target.offset().top
    }, 1000, function() {

      var $target = $(target);
      $target.focus();
      if ($target.is(":focus")) { 
        return false;
      } else {
        $target.attr('tabindex','-1'); 
        $target.focus(); 
      };
    });
    }
   }
  });

`

Auto expand a textarea using jQuery

_x000D_
_x000D_
function autoResizeTextarea() {_x000D_
  for (let index = 0; index < $('textarea').length; index++) {_x000D_
    let element = $('textarea')[index];_x000D_
    let offset = element.offsetHeight - element.clientHeight;_x000D_
    $(element).css('resize', 'none');_x000D_
    $(element).on('input', function() {_x000D_
      $(this).height(0).height(this.scrollHeight - offset - parseInt($(this).css('padding-top')));_x000D_
    });_x000D_
  }_x000D_
}
_x000D_
_x000D_
_x000D_

https://codepen.io/nanachi1/pen/rNNKrzQ

this should work.

C++ inheritance - inaccessible base?

By default, inheritance is private. You have to explicitly use public:

class Bar : public Foo

rotating axis labels in R

Not sure if this is what you mean, but try setting las=1. Here's an example:

require(grDevices)
tN <- table(Ni <- stats::rpois(100, lambda=5))
r <- barplot(tN, col=rainbow(20), las=1)

output

That represents the style of axis labels. (0=parallel, 1=all horizontal, 2=all perpendicular to axis, 3=all vertical)

What does 'git blame' do?

From GitHub:

The blame command is a Git feature, designed to help you determine who made changes to a file.

Despite its negative-sounding name, git blame is actually pretty innocuous; its primary function is to point out who changed which lines in a file, and why. It can be a useful tool to identify changes in your code.

Basically, git-blame is used to show what revision and author last modified each line of a file. It's like checking the history of the development of a file.

UNION with WHERE clause

i think it will depend on many things - run EXPLAIN PLAN on each one to see what your optimizer selects. Otherwise - as @rayman suggests - run them both and time them.

How to query a CLOB column in Oracle

For big CLOB selects also can be used:

SELECT dbms_lob.substr( column_name, dbms_lob.getlength(column_name), 1) FROM foo