Programs & Examples On #Weblogic

WebLogic Server is a Java EE application server from Oracle. WebLogic Server is the centerpiece of Oracle's Fusion Middleware platform.

How to lookup JNDI resources on WebLogic?

java is the root JNDI namespace for resources. What the original snippet of code means is that the container the application was initially deployed in did not apply any additional namespaces to the JNDI context you retrieved (as an example, Tomcat automatically adds all resources to the namespace comp/env, so you would have to do dataSource = (javax.sql.DataSource) context.lookup("java:comp/env/jdbc/myDataSource"); if the resource reference name is jdbc/myDataSource).

To avoid having to change your legacy code I think if you register the datasource with the name myDataSource (remove the jdbc/) you should be fine. Let me know if that works.

SessionTimeout: web.xml vs session.maxInactiveInterval()

Now, i'm being told that this will terminate the session (or is it all sessions?) in the 15th minute of use, regardless their activity.

No, that's not true. The session-timeout configures a per session timeout in case of inactivity.

Are these methods equivalent? Should I favour the web.xml config?

The setting in the web.xml is global, it applies to all sessions of a given context. Programatically, you can change this for a particular session.

Weblogic Transaction Timeout : how to set in admin console in WebLogic AS 8.1

Its possible at application level. Click on the EJB under the deployment(like Home > >Summary of Deployments >). Click on the Configuration tab and there is "Transaction Timeout:"

Indirectly referenced from required .class file

Have you Googled for "weblogic ExpressionMap"? Do you know what it is and what it does?

Looks like you definitely need to be compiling alongside Weblogic and with Weblogic's jars included in your Eclipse classpath, if you're not already.

If you're not already working with Weblogic, then you need to find out what in the world is referencing it. You might need to do some heavy-duty grepping on your jars, classfiles, and/or source files looking for which ones include the string "weblogic".

If I had to include something that was relying on this Weblogic class, but couldn't use Weblogic, I'd be tempted to try to reverse-engineer a compatible class. Create your own weblogic.utils.expressions.ExpressionMap class; see if everything compiles; use any resultant errors or warnings at compile-time or runtime to give you clues as to what methods and other members need to be in this class. Make stub methods that do nothing or return null if possible.

how to change listen port from default 7001 to something different?

The following lines are used to control the listen-port of a server, both are necessary:

    <listen-port>7002</listen-port>
    <listen-port-enabled>true</listen-port-enabled>

How can I compile a Java program in Eclipse without running it?

Right click on Yourproject(in project Explorer)-->Build Project

It will compile all files in your project and updates your build folder, all without running.

Angular 2 - innerHTML styling

The recommended version by Günter Zöchbauer works fine, but I have an addition to make. In my case I had an unstyled html-element and I did not know how to style it. Therefore I designed a pipe to add styling to it.

import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';


@Pipe({
    name: 'StyleClass'
})
export class StyleClassPipe implements PipeTransform {

    constructor(private sanitizer: DomSanitizer) { }
    transform(html: any, styleSelector: any, styleValue: any): SafeHtml {
        const style = ` style = "${styleSelector}: ${styleValue};"`;
        const indexPosition = html.indexOf('>');
        const newHtml = [html.slice(0, indexPosition), style, html.slice(indexPosition)].join('');
        return this.sanitizer.bypassSecurityTrustHtml(newHtml);
    }

}

Then you can add style to any html-element like this:

<span [innerhtml]="Variable | StyleClass: 'margin': '0'"> </span>

With:

Variable = '<p> Test </p>'

What is the "Upgrade-Insecure-Requests" HTTP header?

Short answer: it's closely related to the Content-Security-Policy: upgrade-insecure-requests response header, indicating that the browser supports it (and in fact prefers it).

It took me 30mins of Googling, but I finally found it buried in the W3 spec.

The confusion comes because the header in the spec was HTTPS: 1, and this is how Chromium implemented it, but after this broke lots of websites that were poorly coded (particularly WordPress and WooCommerce) the Chromium team apologized:

"I apologize for the breakage; I apparently underestimated the impact based on the feedback during dev and beta."
— Mike West, in Chrome Issue 501842

Their fix was to rename it to Upgrade-Insecure-Requests: 1, and the spec has since been updated to match.

Anyway, here is the explanation from the W3 spec (as it appeared at the time)...

The HTTPS HTTP request header field sends a signal to the server expressing the client’s preference for an encrypted and authenticated response, and that it can successfully handle the upgrade-insecure-requests directive in order to make that preference as seamless as possible to provide.

...

When a server encounters this preference in an HTTP request’s headers, it SHOULD redirect the user to a potentially secure representation of the resource being requested.

When a server encounters this preference in an HTTPS request’s headers, it SHOULD include a Strict-Transport-Security header in the response if the request’s host is HSTS-safe or conditionally HSTS-safe [RFC6797].

Extract hostname name from string

function hostname(url) {
    var match = url.match(/:\/\/(www[0-9]?\.)?(.[^/:]+)/i);
    if ( match != null && match.length > 2 && typeof match[2] === 'string' && match[2].length > 0 ) return match[2];
}

The above code will successfully parse the hostnames for the following example urls:

http://WWW.first.com/folder/page.html first.com

http://mail.google.com/folder/page.html mail.google.com

https://mail.google.com/folder/page.html mail.google.com

http://www2.somewhere.com/folder/page.html?q=1 somewhere.com

https://www.another.eu/folder/page.html?q=1 another.eu

Original credit goes to: http://www.primaryobjects.com/CMS/Article145

Array versus linked-list

Other than adding and remove from the middle of the list, I like linked lists more because they can grow and shrink dynamically.

What is the default Jenkins password?

With the default Jenkins installation using Homebrew on macOS this will output the initial password for the admin user:

sudo cat /Users/Shared/Jenkins/Home/secrets/initialAdminPassword

How to create new div dynamically, change it, move it, modify it in every way possible, in JavaScript?

This covers the basics of DOM manipulation. Remember, element addition to the body or a body-contained node is required for the newly created node to be visible within the document.

How can I assign the output of a function to a variable using bash?

VAR=$(scan)

Exactly the same way as for programs.

convert date string to mysql datetime field

I assume we are talking about doing this in Bash?

I like to use sed to load the date values into an array so I can break down each field and do whatever I want with it. The following example assumes and input format of mm/dd/yyyy...

DATE=$2
DATE_ARRAY=(`echo $DATE | sed -e 's/\// /g'`)
MONTH=(`echo ${DATE_ARRAY[0]}`)
DAY=(`echo ${DATE_ARRAY[1]}`)
YEAR=(`echo ${DATE_ARRAY[2]}`)
LOAD_DATE=$YEAR$MONTH$DAY

you also may want to read up on the date command in linux. It can be very useful: http://unixhelp.ed.ac.uk/CGI/man-cgi?date

Hope that helps... :)

-Ryan

How to add months to a date in JavaScript?

I would highly recommend taking a look at datejs. With it's api, it becomes drop dead simple to add a month (and lots of other date functionality):

var one_month_from_your_date = your_date_object.add(1).month();

What's nice about datejs is that it handles edge cases, because technically you can do this using the native Date object and it's attached methods. But you end up pulling your hair out over edge cases, which datejs has taken care of for you.

Plus it's open source!

How to put Google Maps V2 on a Fragment using ViewPager

Latest stuff with getMapAsync instead of the deprecated one.

1. check manifest for

<meta-data android:name="com.google.android.geo.API_KEY" android:value="xxxxxxxxxxxxxxxxxxxxxxxxx"/>

You can get the API Key for your app by registering your app at Google Cloud Console. Register your app as Native Android App

2. in your fragment layout .xml add FrameLayout(not fragment):

                  <FrameLayout
                android:layout_width="match_parent"
                android:layout_height="250dp"
                android:layout_weight="2"
                android:name="com.google.android.gms.maps.SupportMapFragment"
                android:id="@+id/mapwhere" />

or whatever height you want

3. In onCreateView in your fragment

    private SupportMapFragment mSupportMapFragment; 

    mSupportMapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.mapwhere);
    if (mSupportMapFragment == null) {
        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        mSupportMapFragment = SupportMapFragment.newInstance();
        fragmentTransaction.replace(R.id.mapwhere, mSupportMapFragment).commit();
    }

    if (mSupportMapFragment != null)
    {
        mSupportMapFragment.getMapAsync(new OnMapReadyCallback() {
            @Override public void onMapReady(GoogleMap googleMap) {
                if (googleMap != null) {

                    googleMap.getUiSettings().setAllGesturesEnabled(true);

                      -> marker_latlng // MAKE THIS WHATEVER YOU WANT

                        CameraPosition cameraPosition = new CameraPosition.Builder().target(marker_latlng).zoom(15.0f).build();
                        CameraUpdate cameraUpdate = CameraUpdateFactory.newCameraPosition(cameraPosition);
                        googleMap.moveCamera(cameraUpdate);

                }

            }
        });

Skip over a value in the range function in python

You can use any of these:

# Create a range that does not contain 50
for i in [x for x in xrange(100) if x != 50]:
    print i

# Create 2 ranges [0,49] and [51, 100] (Python 2)
for i in range(50) + range(51, 100):
    print i

# Create a iterator and skip 50
xr = iter(xrange(100))
for i in xr:
    print i
    if i == 49:
        next(xr)

# Simply continue in the loop if the number is 50
for i in range(100):
    if i == 50:
        continue
    print i

How do you get the file size in C#?

MSDN FileInfo.Length says that it is "the size of the current file in bytes."

My typical Google search for something like this is: msdn FileInfo

Run Bash Command from PHP

Check if have not set a open_basedir in php.ini or .htaccess of domain what you use. That will jail you in directory of your domain and php will get only access to execute inside this directory.

How to stretch div height to fill parent div - CSS

Suppose you have

<body>
  <div id="root" />
</body>

With normal CSS, you can do the following. See a working app https://github.com/onmyway133/Lyrics/blob/master/index.html

#root {
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  width: 100%;
}

With flexbox, you can

html, body {
  height: 100%
}
body {
  display: flex;
  align-items: stretch;
}

#root {
  width: 100%
}

Pandas - 'Series' object has no attribute 'colNames' when using apply()

When you use df.apply(), each row of your DataFrame will be passed to your lambda function as a pandas Series. The frame's columns will then be the index of the series and you can access values using series[label].

So this should work:

df['D'] = (df.apply(lambda x: myfunc(x[colNames[0]], x[colNames[1]]), axis=1)) 

How do I group Windows Form radio buttons?

Radio button without panel

public class RadioButton2 : RadioButton
{
   public string GroupName { get; set; }
}

private void RadioButton2_Clicked(object sender, EventArgs e)
{
    RadioButton2 rb = (sender as RadioButton2);

    if (!rb.Checked)
    {
       foreach (var c in Controls)
       {
           if (c is RadioButton2 && (c as RadioButton2).GroupName == rb.GroupName)
           {
              (c as RadioButton2).Checked = false;
           }
       }

       rb.Checked = true;
    }
}

private void Form1_Load(object sender, EventArgs e)
{
    //a group
    RadioButton2 rb1 = new RadioButton2();
    rb1.Text = "radio1";
    rb1.AutoSize = true;
    rb1.AutoCheck = false;
    rb1.Top = 50;
    rb1.Left = 50;
    rb1.GroupName = "a";
    rb1.Click += RadioButton2_Clicked;
    Controls.Add(rb1);

    RadioButton2 rb2 = new RadioButton2();
    rb2.Text = "radio2";
    rb2.AutoSize = true;
    rb2.AutoCheck = false;
    rb2.Top = 50;
    rb2.Left = 100;
    rb2.GroupName = "a";
    rb2.Click += RadioButton2_Clicked;
    Controls.Add(rb2);

    //b group
    RadioButton2 rb3 = new RadioButton2();
    rb3.Text = "radio3";
    rb3.AutoSize = true;
    rb3.AutoCheck = false;
    rb3.Top = 80;
    rb3.Left = 50;
    rb3.GroupName = "b";
    rb3.Click += RadioButton2_Clicked;
    Controls.Add(rb3);

    RadioButton2 rb4 = new RadioButton2();
    rb4.Text = "radio4";
    rb4.AutoSize = true;
    rb4.AutoCheck = false;
    rb4.Top = 80;
    rb4.Left = 100;
    rb4.GroupName = "b";
    rb4.Click += RadioButton2_Clicked;
    Controls.Add(rb4);
}

Detecting a long press with Android

The idea is creating a Runnable for execute long click in a future, but this execution can be canceled because of a click, or move.

You also need to know, when long click was consumed, and when it is canceled because finger moved too much. We use initialTouchX & initialTouchY for checking if the user exit a square area of 10 pixels, 5 each side.

Here is my complete code for delegating Click & LongClick from Cell in ListView to Activity with OnTouchListener:

    ClickDelegate delegate; 
    boolean goneFlag = false;
    float initialTouchX;
    float initialTouchY;
    final Handler handler = new Handler();
    Runnable mLongPressed = new Runnable() {
        public void run() {
            Log.i("TOUCH_EVENT", "Long press!");
            if (delegate != null) {
                goneFlag = delegate.onItemLongClick(index);
            } else {
                goneFlag = true;
            }
        }
    };

    @OnTouch({R.id.layout})
    public boolean onTouch (View view, MotionEvent motionEvent) {
        switch (motionEvent.getAction()) {
            case MotionEvent.ACTION_DOWN:
                handler.postDelayed(mLongPressed, ViewConfiguration.getLongPressTimeout());
                initialTouchX = motionEvent.getRawX();
                initialTouchY = motionEvent.getRawY();
                return true;
            case MotionEvent.ACTION_MOVE:
            case MotionEvent.ACTION_CANCEL:
                if (Math.abs(motionEvent.getRawX() - initialTouchX) > 5 || Math.abs(motionEvent.getRawY() - initialTouchY) > 5) {
                    handler.removeCallbacks(mLongPressed);
                    return true;
                }
                return false;
            case MotionEvent.ACTION_UP:
                handler.removeCallbacks(mLongPressed);
                if (goneFlag || Math.abs(motionEvent.getRawX() - initialTouchX) > 5 || Math.abs(motionEvent.getRawY() - initialTouchY) > 5) {
                    goneFlag = false;
                    return true;
                }
                break;
        }
        Log.i("TOUCH_EVENT", "Short press!");
        if (delegate != null) {
            if (delegate.onItemClick(index)) {
                return false;
            }
        }
        return false;
    }

ClickDelegateis an interface for sending click events to the handler class like an Activity

    public interface ClickDelegate {
        boolean onItemClick(int position);
        boolean onItemLongClick(int position);
    }

And all what you need is to implement it in your Activity or parent Viewif you need to delegate the behavior:

public class MyActivity extends Activity implements ClickDelegate {

    //code...
    //in some place of you code like onCreate, 
    //you need to set the delegate like this:
    SomeArrayAdapter.delegate = this;
    //or:
    SomeViewHolder.delegate = this;
    //or:
    SomeCustomView.delegate = this;

    @Override
    public boolean onItemClick(int position) {
        Object obj = list.get(position);
        if (obj) {
            return true; //if you handle click
        } else {
            return false; //if not, it could be another event
        }
    }

    @Override
    public boolean onItemLongClick(int position) {
        Object obj = list.get(position);
        if (obj) {
            return true; //if you handle long click
        } else {
            return false; //if not, it's a click
        }
    }
}

Inline for loop

q  = [1, 2, 3, 4, 1, 2, 5, 1, 2, 3, 4, 5]
vm = [-1, -1, -1, -1,1,2,3,1]

p = []
for v in vm:
    if v in q:
        p.append(q.index(v))
    else:
        p.append(99999)

print p
p = [q.index(v) if v in q else 99999 for v in vm]
print p

Output:

[99999, 99999, 99999, 99999, 0, 1, 2, 0]
[99999, 99999, 99999, 99999, 0, 1, 2, 0]

Instead of using append() in the list comprehension you can reference the p as direct output, and use q.index(v) and 99999 in the LC.

Not sure if this is intentional but note that q.index(v) will find just the first occurrence of v, even tho you have several in q. If you want to get the index of all v in q, consider using a enumerator and a list of already visited indexes

Something in those lines(pseudo-code):

visited = []
for i, v in enumerator(vm):
   if i not in visited:
       p.append(q.index(v))
   else:
       p.append(q.index(v,max(visited))) # this line should only check for v in q after the index of max(visited)
   visited.append(i)

sql insert into table with select case values

You need commas after end finishing the case statement. And, the "as" goes after the case statement, not inside it:

Insert into TblStuff(FullName, Address, City, Zip)
    Select (Case When Middle is Null Then Fname + LName
                 Else Fname +' ' + Middle + ' '+ Lname
            End)  as FullName,
           (Case When Address2 is Null Then Address1
                 else Address1 +', ' + Address2
            End)  as  Address,
           City as City,
           Zip as Zip
    from tblImport

How to convert string to datetime format in pandas python?

Use to_datetime, there is no need for a format string the parser is man/woman enough to handle it:

In [51]:
pd.to_datetime(df['I_DATE'])

Out[51]:
0   2012-03-28 14:15:00
1   2012-03-28 14:17:28
2   2012-03-28 14:50:50
Name: I_DATE, dtype: datetime64[ns]

To access the date/day/time component use the dt accessor:

In [54]:
df['I_DATE'].dt.date

Out[54]:
0    2012-03-28
1    2012-03-28
2    2012-03-28
dtype: object

In [56]:    
df['I_DATE'].dt.time

Out[56]:
0    14:15:00
1    14:17:28
2    14:50:50
dtype: object

You can use strings to filter as an example:

In [59]:
df = pd.DataFrame({'date':pd.date_range(start = dt.datetime(2015,1,1), end = dt.datetime.now())})
df[(df['date'] > '2015-02-04') & (df['date'] < '2015-02-10')]

Out[59]:
         date
35 2015-02-05
36 2015-02-06
37 2015-02-07
38 2015-02-08
39 2015-02-09

Where is the Postgresql config file: 'postgresql.conf' on Windows?

On my machine:

C:\Program Files (x86)\OpenERP 6.1-20121026-233219\PostgreSQL\data

Preventing multiple clicks on button

One way you do this is set a counter and if number exceeds the certain number return false. easy as this.

var mybutton_counter=0;
$("#mybutton").on('click', function(e){
    if (mybutton_counter>0){return false;} //you can set the number to any
    //your call
     mybutton_counter++; //incremental
});

make sure, if statement is on top of your call.

Center image using text-align center?

That will not work as the text-align property applies to block containers, not inline elements, and img is an inline element. See the W3C specification.

Use this instead:

_x000D_
_x000D_
img.center {_x000D_
    display: block;_x000D_
    margin: 0 auto;_x000D_
}
_x000D_
<div style="border: 1px solid black;">_x000D_
<img class="center" src ="https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-icon.png?v=c78bd457575a">_x000D_
_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to Change color of Button in Android when Clicked?

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- default -->
    <item
        android:state_pressed="false"
        android:state_focused="false">
        <shape
            android:innerRadiusRatio="1"
            android:shape="rectangle" >
            <solid android:color="#00a3e2" />

            <padding
                android:bottom="10dp"
                android:left="10dp"
                android:right="10dp"
                android:top="10dp" />

        </shape>
    </item>

    <!-- button focused -->
    <item
        android:state_pressed="false"
        android:state_focused="true">
        <shape
            android:innerRadiusRatio="1"
            android:shape="rectangle" >
            <solid android:color="#5a97f5" />

            <padding
                android:bottom="5dp"
                android:left="10dp"
                android:right="10dp"
                android:top="5dp" />
        </shape></item>

    <!-- button pressed -->
    <item
        android:state_pressed="true"
        android:state_focused="false">
        <shape
            android:innerRadiusRatio="1"
            android:shape="rectangle" >
            <solid android:color="#478df9"/>
            <padding
                android:bottom="10dp"
                android:left="10dp"
                android:right="10dp"
                android:top="10dp" />
        </shape></item>
</selector>

No default constructor found; nested exception is java.lang.NoSuchMethodException with Spring MVC?

If your environment is using both Guice and Spring and using the constructor @Inject, for example, with Play Framework, you will also run into this issue if you have mistakenly auto-completed the import with an incorrect choice of:

import com.google.inject.Inject;

Then you get the same missing default constructor error even though the rest of your source with @Inject looks exactly the same way as other working components in your project and compile without an error.

Correct that with:

import javax.inject.Inject;

Do not write a default constructor with construction time injection.

Compilation error: stray ‘\302’ in program etc

You have invalid chars in your source. If you don't have any valid non ascii chars in your source, maybe in a double quoted string literal, you can simply convert your file back to ascii with:

tr -cd '\11\12\15\40-\176' < old.c > new.c

Edit: method with iconv will stop at wrong chars which makes no sense. The above command line is working with the example file. Good luck :-)

java.sql.SQLException: Incorrect string value: '\xF0\x9F\x91\xBD\xF0\x9F...'

Besides,data type can use blob install of varchar or text.

How to check if a double is null?

A double primitive in Java can never be null. It will be initialized to 0.0 if no value has been given for it (except when declaring a local double variable and not assigning a value, but this will produce a compile-time error).

More info on default primitive values here.

How to get the absolute path to the public_html folder?

<?php

    // Get absolute path
    $path = getcwd(); // /home/user/public_html/test/test.php.   

    $path = substr($path, 0, strpos($path, "public_html"));

    $root = $path . "public_html/";

    echo $root; // This will output /home/user/public_html/

Use Font Awesome Icon in Placeholder

Where supported, you can use the ::input-placeholder pseudoselector combined with ::before.

See an example at:

http://codepen.io/JonFabritius/pen/nHeJg

I was just working on this and came across this article, from which I modified this stuff:

http://davidwalsh.name/html5-placeholder-css

Given URL is not permitted by the application configuration

Update to Anvesh Saxena's answer(correct but outdated as FB App interface has changed):

In your FB App configuration you need to add a Website platform with your website's URL set. Then you can add App Domains which I set to our website's base domain (e.g. for a URL like http://www.mycoolwebsite.com, just use mycoolwebsite.com).

New FB Settings Screenshot

IMPORTANT: In order for this to work you'll need to be using a subdomain of your app's URL for your local development. You can do this easily by modifying your hosts file on your development computer to use a non-existent subdomain of your website such as local.mycoolwebsite.com. Just google 'edit hosts file' for your platform (e.g. mac / windows) if you're not familiar with how to do this.

Django DB Settings 'Improperly Configured' Error

On Django 1.9, I tried django-admin runserver and got the same error, but when I used python manage.py runserver I got the intended result. This may solve this error for a lot of people!

How to handle an IF STATEMENT in a Mustache template?

Just took a look over the mustache docs and they support "inverted sections" in which they state

they (inverted sections) will be rendered if the key doesn't exist, is false, or is an empty list

http://mustache.github.io/mustache.5.html#Inverted-Sections

{{#value}}
  value is true
{{/value}}
{{^value}}
  value is false
{{/value}}

Pythonic way to check if a file exists?

If (when the file doesn't exist) you want to create it as empty, the simplest approach is

with open(thepath, 'a'): pass

(in Python 2.6 or better; in 2.5, this requires an "import from the future" at the top of your module).

If, on the other hand, you want to leave the file alone if it exists, but put specific non-empty contents there otherwise, then more complicated approaches based on if os.path.isfile(thepath):/else statement blocks are probably more suitable.

Locate current file in IntelliJ

  1. Open the project explorer ( default left side )
  2. Click on the tiny wheel setting button
  3. Mark Auto scroll from source option.

Boom! You are done.

How to order citations by appearance using BibTeX?

Change

\bibliographystyle{plain}

to

\bibliographystyle{ieeetr}

Then rebuild it a few times to replace the .aux and .bbl files that were made when you used the plain style.

Or simply delete the .aux and .bbl files and rebuild.

If you use MiKTeX you shouldn't need to download anything extra.

Does "\d" in regex mean a digit?

[0-9] is not always equivalent to \d. In python3, [0-9] matches only 0123456789 characters, while \d matches [0-9] and other digit characters, for example Eastern Arabic numerals ??????????.

Sound effects in JavaScript / HTML5

howler.js

For game authoring, one of the best solutions is to use a library which solves the many problems we face when writing code for the web, such as howler.js. howler.js abstracts the great (but low-level) Web Audio API into an easy to use framework. It will attempt to fall back to HTML5 Audio Element if Web Audio API is unavailable.

var sound = new Howl({
  urls: ['sound.mp3', 'sound.ogg']
}).play();
// it also provides calls for spatial/3d audio effects (most browsers)
sound.pos3d(0.1,0.3,0.5);

wad.js

Another great library is wad.js, which is especially useful for producing synth audio, such as music and effects. For example:

var saw = new Wad({source : 'sawtooth'})
saw.play({
    volume  : 0.8,
    wait    : 0,     // Time in seconds between calling play() and actually triggering the note.
    loop    : false, // This overrides the value for loop on the constructor, if it was set. 
    pitch   : 'A4',  // A4 is 440 hertz.
    label   : 'A',   // A label that identifies this note.
    env     : {hold : 9001},
    panning : [1, -1, 10],
    filter  : {frequency : 900},
    delay   : {delayTime : .8}
})

Sound for Games

Another library similar to Wad.js is "Sound for Games", it has more focus on effects production, while providing a similar set of functionality through a relatively distinct (and perhaps more concise feeling) API:

function shootSound() {
  soundEffect(
    1046.5,           //frequency
    0,                //attack
    0.3,              //decay
    "sawtooth",       //waveform
    1,                //Volume
    -0.8,             //pan
    0,                //wait before playing
    1200,             //pitch bend amount
    false,            //reverse bend
    0,                //random pitch range
    25,               //dissonance
    [0.2, 0.2, 2000], //echo array: [delay, feedback, filter]
    undefined         //reverb array: [duration, decay, reverse?]
  );
}

Summary

Each of these libraries are worth a look, whether you need to play back a single sound file, or perhaps create your own html-based music editor, effects generator, or video game.

Pandas: rolling mean by time interval

This example seems to call for a weighted mean as suggested in @andyhayden's comment. For example, there are two polls on 10/25 and one each on 10/26 and 10/27. If you just resample and then take the mean, this effectively gives twice as much weighting to the polls on 10/26 and 10/27 compared to the ones on 10/25.

To give equal weight to each poll rather than equal weight to each day, you could do something like the following.

>>> wt = df.resample('D',limit=5).count()

            favorable  unfavorable  other
enddate                                  
2012-10-25          2            2      2
2012-10-26          1            1      1
2012-10-27          1            1      1

>>> df2 = df.resample('D').mean()

            favorable  unfavorable  other
enddate                                  
2012-10-25      0.495        0.485  0.025
2012-10-26      0.560        0.400  0.040
2012-10-27      0.510        0.470  0.020

That gives you the raw ingredients for doing a poll-based mean instead of a day-based mean. As before, the polls are averaged on 10/25, but the weight for 10/25 is also stored and is double the weight on 10/26 or 10/27 to reflect that two polls were taken on 10/25.

>>> df3 = df2 * wt
>>> df3 = df3.rolling(3,min_periods=1).sum()
>>> wt3 = wt.rolling(3,min_periods=1).sum()

>>> df3 = df3 / wt3  

            favorable  unfavorable     other
enddate                                     
2012-10-25   0.495000     0.485000  0.025000
2012-10-26   0.516667     0.456667  0.030000
2012-10-27   0.515000     0.460000  0.027500
2012-10-28   0.496667     0.465000  0.041667
2012-10-29   0.484000     0.478000  0.042000
2012-10-30   0.488000     0.474000  0.042000
2012-10-31   0.530000     0.450000  0.020000
2012-11-01   0.500000     0.465000  0.035000
2012-11-02   0.490000     0.470000  0.040000
2012-11-03   0.490000     0.465000  0.045000
2012-11-04   0.500000     0.448333  0.035000
2012-11-05   0.501429     0.450000  0.032857
2012-11-06   0.503333     0.450000  0.028333
2012-11-07   0.510000     0.435000  0.010000

Note that the rolling mean for 10/27 is now 0.51500 (poll-weighted) rather than 52.1667 (day-weighted).

Also note that there have been changes to the APIs for resample and rolling as of version 0.18.0.

rolling (what's new in pandas 0.18.0)

resample (what's new in pandas 0.18.0)

pythonw.exe or python.exe?

See here: http://docs.python.org/using/windows.html

pythonw.exe "This suppresses the terminal window on startup."

How to fill a datatable with List<T>

Just in case you have a nullable property in your class object:

private static DataTable ConvertToDatatable<T>(List<T> data)
{
    PropertyDescriptorCollection props = TypeDescriptor.GetProperties(typeof(T));
    DataTable table = new DataTable();
    for (int i = 0; i < props.Count; i++)
    {
        PropertyDescriptor prop = props[i];
        if (prop.PropertyType.IsGenericType && prop.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
            table.Columns.Add(prop.Name, prop.PropertyType.GetGenericArguments()[0]); 
        else
            table.Columns.Add(prop.Name, prop.PropertyType);
    }

    object[] values = new object[props.Count];
    foreach (T item in data)
    {
        for (int i = 0; i < values.Length; i++)
        {
            values[i] = props[i].GetValue(item);
        }
        table.Rows.Add(values);
    }
    return table;
 }

C++ JSON Serialization

Does anything, easy like that, exists?? THANKS :))

C++ does not store class member names in compiled code, and there's no way to discover (at runtime) which members (variables/methods) class contains. In other words, you cannot iterate through members of a struct. Because there's no such mechanism, you won't be able to automatically create "JSONserialize" for every object.

You can, however, use any json library to serialize objects, BUT you'll have to write serialization/deserialization code yourself for every class. Either that, or you'll have to create serializeable class similar to QVariantMap that'll be used instead of structs for all serializeable objects.

In other words, if you're okay with using specific type for all serializeable objects (or writing serialization routines yourself for every class), it can be done. However, if you want to automatically serialize every possible class, you should forget about it. If this feature is important to you, try another language.

Changing a specific column name in pandas DataFrame

Since inplace argument is available, you don't need to copy and assign the original data frame back to itself, but do as follows:

df.rename(columns={'two':'new_name'}, inplace=True)

from unix timestamp to datetime

I would like to add that Using the library momentjs in javascript you can have the whole data information in an object with:

const today = moment(1557697070824.94).toObject();

You should obtain an object with this properties:

today: {
  date: 15,
  hours: 2,
  milliseconds: 207,
  minutes: 31,
  months: 4
  seconds: 22,
  years: 2019
}

It is very useful when you have to calculate dates.

How to convert a boolean array to an int array

Using numpy, you can do:

y = x.astype(int)

If you were using a non-numpy array, you could use a list comprehension:

y = [int(val) for val in x]

Parse String to Date with Different Format in Java

Take a look at SimpleDateFormat. The code goes something like this:

SimpleDateFormat fromUser = new SimpleDateFormat("dd/MM/yyyy");
SimpleDateFormat myFormat = new SimpleDateFormat("yyyy-MM-dd");

try {

    String reformattedStr = myFormat.format(fromUser.parse(inputString));
} catch (ParseException e) {
    e.printStackTrace();
}

Constructors in JavaScript objects

Using Nick's sample above, you can create a constructor for objects without parameters using a return statement as the last statement in your object definition. Return your constructor function as below and it will run the code in __construct each time you create the object:

function Box()
{
   var __construct = function() {
       alert("Object Created.");
       this.color = 'green';
   }

  this.color = '';

   this.getColor = function() {
       return this.color;
   }

   __construct();
}

var b = new Box();

Get a specific bit from byte

While it's good to read and understand Josh's answer, you'll probably be happier using the class Microsoft provided for this purpose: System.Collections.BitArray It's available in all versions of .NET Framework.

What's the difference between a mock & stub?

Stub

I believe the biggest distinction is that a stub you have already written with predetermined behavior. So you would have a class that implements the dependency (abstract class or interface most likely) you are faking for testing purposes and the methods would just be stubbed out with set responses. They would not do anything fancy and you would have already written the stubbed code for it outside of your test.

Mock

A mock is something that as part of your test you have to setup with your expectations. A mock is not setup in a predetermined way so you have code that does it in your test. Mocks in a way are determined at runtime since the code that sets the expectations has to run before they do anything.

Difference between Mocks and Stubs

Tests written with mocks usually follow an initialize -> set expectations -> exercise -> verify pattern to testing. While the pre-written stub would follow an initialize -> exercise -> verify.

Similarity between Mocks and Stubs

The purpose of both is to eliminate testing all the dependencies of a class or function so your tests are more focused and simpler in what they are trying to prove.

Get the selected value in a dropdown using jQuery.

Hello guys i am using this technique to get the values from the selected dropdown list and it is working like charm.

var methodvalue = $("#method option:selected").val(); 

Why do we need to install gulp globally and locally?

Technically you don't need to install it globally if the node_modules folder in your local installation is in your PATH. Generally this isn't a good idea.

Alternatively if npm test references gulp then you can just type npm test and it'll run the local gulp.

I've never installed gulp globally -- I think it's bad form.

Make a simple fade in animation in Swift?

import UIKit

/*
 Here is simple subclass for CAAnimation which create a fadeIn animation
 */

class FadeInAdnimation: CABasicAnimation {
    override init() {
        super.init()
        keyPath = "opacity"
        duration = 2.0
        fromValue = 0
        toValue = 1
        fillMode = CAMediaTimingFillMode.forwards
        isRemovedOnCompletion = false
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
}

/*
 Example of usage
 */

class ViewController: UIViewController {

    weak var label: UILabel!

    override func loadView() {
        let view = UIView()
        view.backgroundColor = .white

        let label = UILabel()
        label.alpha = 0
        label.frame = CGRect(x: 150, y: 200, width: 200, height: 20)
        label.text = "Hello World!"
        label.textColor = .black
        view.addSubview(label)
        self.label = label

        let button = UIButton(type: .custom)
        button.frame = CGRect(x: 0, y: 250, width: 300, height: 100)
        button.setTitle("Press to Start FadeIn", for: UIControl.State())
        button.backgroundColor = .red
        button.addTarget(self, action: #selector(startFadeIn), for: .touchUpInside)
        view.addSubview(button)

        self.view = view
    }

    /*
     Animation in action
     */
    @objc private func startFadeIn() {
        label.layer.add(FadeInAdnimation(), forKey: "fadeIn")
    }

}

Change the size of a JTextField inside a JBorderLayout

With a BorderLayout you need to use setPreferredSize instead of setSize

Why is this program erroneously rejected by three C++ compilers?

I can't see a new-line after that last brace.

As you know: "If a source file that is not empty does not end in a new-line character, ... the behavior is undefined".

Ansible: Store command's stdout in new variable?

I'm a newbie in Ansible, but I would suggest next solution:

playbook.yml

...
vars:
  command_output_full:
    stdout: will be overriden below
  command_output: {{ command_output_full.stdout }}
...
...
...
tasks:
  - name: Create variable from command
    command: "echo Hello"
    register: command_output_full
  - debug: msg="{{ command_output }}"

It should work (and works for me) because Ansible uses lazy evaluation. But it seems it checks validity before the launch, so I have to define command_output_full.stdout in vars.

And, of course, if it is too many such vars in vars section, it will look ugly.

HttpClient does not exist in .net 4.0: what can I do?

Agreeing with TrueWill's comment on a separate answer, the best way I've seen to use system.web.http on a .NET 4 targeted project under current Visual Studio is Install-Package Microsoft.AspNet.WebApi.Client -Version 4.0.30506

jQuery, get ID of each element in a class using .each?

Try this, replacing .myClassName with the actual name of the class (but keep the period at the beginning).

$('.myClassName').each(function() {
    alert( this.id );
});

So if the class is "test", you'd do $('.test').each(func....

This is the specific form of .each() that iterates over a jQuery object.

The form you were using iterates over any type of collection. So you were essentially iterating over an array of characters t,e,s,t.

Using that form of $.each(), you would need to do it like this:

$.each($('.myClassName'), function() {
    alert( this.id );
});

...which will have the same result as the example above.

How to get hex color value rather than RGB value?

Convert RGB to Hex

I am using Jasmine protractor and I was getting errors like - Expected [ 'rgba(255, 255, 255, 1)' ] to contain '#fff'. Below function worked fine for me.

function RGBAToHexA(test:string) {
let sep = test.toString().indexOf(",") > -1 ? "," : " ";
const rgba = test.toString().substring(5).split(")")[0].split(sep);
console.log(rgba)
let r = (+rgba[0]).toString(16),
  g = (+rgba[1]).toString(16),
  b = (+rgba[2]).toString(16),
  a = Math.round(+rgba[3] * 255).toString(16);

    if (r.length == 1)
        r = "0" + r;
    if (g.length == 1)
        g = "0" + g;
    if (b.length == 1)
        b = "0" + b;
    if (a.length == 1)
        a = "0" + a;

return "#" + r + g + b + a;

}

describe('Check CSS', function() {
 
it('should check css of login page', async function(){
        browser.waitForAngularEnabled(true);
        browser.actions().mouseMove(element(by.css('.btn-auth, .btn-auth:hover'))).perform(); // mouse hover on button
        csspage.Loc_auth_btn.getCssValue('color').then(function(color){
            console.log(RGBAToHexA(color))
            expect( RGBAToHexA(color)).toContain(cssData.hoverauth.color);

        })

       

TypeScript add Object to array with push

If your example represents your real code, the problem is not in the push, it's that your constructor doesn't do anything.

You need to declare and initialize the x and y members.

Explicitly:

export class Pixel {
    public x: number;
    public y: number;   
    constructor(x: number, y: number) {
        this.x = x;
        this.y = y;
    }
}

Or implicitly:

export class Pixel {
    constructor(public x: number, public y: number) {}
}

no pg_hba.conf entry for host

Your postgres server configuration seems correct

host    all         all         127.0.0.1/32          md5
host    all         all         192.168.0.1/32        trust
That should grant access from the client to the postgres server. So that leads me to believe the username / password is whats failing.

Test this by creating a specific user for that database

createuser -a -d -W -U postgres chaosuser

Then adjust your perl script to use the newly created user

my $dbh = DBI->connect("DBI:PgPP:database=chaosLRdb;host=192.168.0.1;port=5433", "chaosuser", "chaos123");

How to make <input type="date"> supported on all browsers? Any alternatives?

Just use <script src="modernizr.js"></script> in the <head> section, and the script will add classes which help you to separate the two cases: if it's supported by the current browser, or if it's not.

Plus follow the links posted in this thread. It will help you: HTML5 input type date, color, range support in Firefox and Internet Explorer

How to get single value of List<object>

You can access the fields by indexing the object array:

foreach (object[] item in selectedValues)
{
  idTextBox.Text = item[0];
  titleTextBox.Text = item[1];
  contentTextBox.Text = item[2];
}

That said, you'd be better off storing the fields in a small class of your own if the number of items is not dynamic:

public class MyObject
{
    public int Id { get; set; }
    public string Title { get; set; }
    public string Content { get; set; }
}

Then you can do:

foreach (MyObject item in selectedValues)
{
  idTextBox.Text = item.Id;
  titleTextBox.Text = item.Title;
  contentTextBox.Text = item.Content;
}

Test if remote TCP port is open from a shell script

I'm guessing that it's too late for an answer, and this might not be a good one, but here you go...

What about putting it inside of a while loop with a timer on it of some sort. I'm more of a Perl guy than Solaris, but depending on the shell you're using, you should be able to do something like:

TIME = 'date +%s' + 15
while TIME != `date +%s'
do whatever

And then just add a flag in the while loop, so that if it times out before completing, you can cite the timeout as reason for failure.

I suspect that the telnet has a timeout switch as well, but just off the top of my head, I think the above will work.

How do I check for null values in JavaScript?

Javascript is very flexible with regards to checking for "null" values. I'm guessing you're actually looking for empty strings, in which case this simpler code will work:

if(!pass || !cpass || !email || !cemail || !user){

Which will check for empty strings (""), null, undefined, false and the numbers 0 and NaN

Please note that if you are specifically checking for numbers it is a common mistake to miss 0 with this method, and num !== 0 is preferred (or num !== -1 or ~num (hacky code that also checks against -1)) for functions that return -1, e.g. indexOf)

SQL to Entity Framework Count Group-By

with EF 6.2 it worked for me

  var query = context.People
               .GroupBy(p => new {p.name})
               .Select(g => new { name = g.Key.name, count = g.Count() });

Query to list number of records in each table in a database

        SELECT ( Schema_name(A.schema_id) + '.' + A.NAME ) AS TableName,
 Sum(B.rows)AS RecordCount 
    FROM   sys.objects A INNER JOIN sys.partitions B 
    ON A.object_id = B.object_id WHERE  A.type = 'U' 
        GROUP  BY A.schema_id,A.NAME ;

QUERY_PHOTO

QUERY_RESULT_PHOTO

Pressing Ctrl + A in Selenium WebDriver

The simplest answer in C# (if you are C# inclined).

Actions action = new Actions(); 
action.KeyDown(OpenQA.Selenium.Keys.Control).SendKeys("a").KeyUp(OpenQA.Selenium.Keys.Control).perform();

This answer is almost given by Hari Reddy, but I have fixed the case which he'd got wrong on some keywords, added the KeyUp or you get in a mess leaving the control key down.

I've also added the clarification on OpenQA.Selenium.Keys, because you may also be using Windows.Forms on the same class as I was an require this clarity.

Lastly, I type "a" because I found that to be the simplest way and I can see no suggestion from the OP that they don't want the simplest answer.

Many thanks to Hari Reddy though as I was a novice in Actions class usage and I was writing many different commands. Chaining them together the way he showed is quicker :-)

jQuery .get error response function?

$.get does not give you the opportunity to set an error handler. You will need to use the low-level $.ajax function instead:

$.ajax({
    url: 'http://example.com/page/2/',
    type: 'GET',
    success: function(data){ 
        $(data).find('#reviews .card').appendTo('#reviews');
    },
    error: function(data) {
        alert('woops!'); //or whatever
    }
});

Edit March '10

Note that with the new jqXHR object in jQuery 1.5, you can set an error handler after calling $.get:

$.get('http://example.com/page/2/', function(data){ 
    $(data).find('#reviews .card').appendTo('#reviews');
}).fail(function() {
    alert('woops'); // or whatever
});

Pygame Drawing a Rectangle

import pygame, sys
from pygame.locals import *

def main():
    pygame.init()

    DISPLAY=pygame.display.set_mode((500,400),0,32)

    WHITE=(255,255,255)
    BLUE=(0,0,255)

    DISPLAY.fill(WHITE)

    pygame.draw.rect(DISPLAY,BLUE,(200,150,100,50))

    while True:
        for event in pygame.event.get():
            if event.type==QUIT:
                pygame.quit()
                sys.exit()
        pygame.display.update()

main()

This creates a simple window 500 pixels by 400 pixels that is white. Within the window will be a blue rectangle. You need to use the pygame.draw.rect to go about this, and you add the DISPLAY constant to add it to the screen, the variable blue to make it blue (blue is a tuple that values which equate to blue in the RGB values and it's coordinates.

Look up pygame.org for more info

Java reflection: how to get field value from an object, not knowing its class

public abstract class Refl {
    /** Use: Refl.<TargetClass>get(myObject,"x.y[0].z"); */
    public static<T> T get(Object obj, String fieldPath) {
        return (T) getValue(obj, fieldPath);
    }
    public static Object getValue(Object obj, String fieldPath) {
        String[] fieldNames = fieldPath.split("[\\.\\[\\]]");
        String success = "";
        Object res = obj;
        for (String fieldName : fieldNames) {
            if (fieldName.isEmpty()) continue;
            int index = toIndex(fieldName);
            if (index >= 0) {
                try {
                    res = ((Object[])res)[index];
                } catch (ClassCastException cce) {
                    throw new RuntimeException("cannot cast "+res.getClass()+" object "+res+" to array, path:"+success, cce);
                } catch (IndexOutOfBoundsException iobe) {
                    throw new RuntimeException("bad index "+index+", array size "+((Object[])res).length +" object "+res +", path:"+success, iobe);
                }
            } else {
                Field field = getField(res.getClass(), fieldName);
                field.setAccessible(true);
                try {
                    res = field.get(res);
                } catch (Exception ee) {
                    throw new RuntimeException("cannot get value of ["+fieldName+"] from "+res.getClass()+" object "+res +", path:"+success, ee);
                }
            }
            success += fieldName + ".";
        }
        return res;
    }

    public static Field getField(Class<?> clazz, String fieldName) {
        Class<?> tmpClass = clazz;
        do {
            try {
                Field f = tmpClass.getDeclaredField(fieldName);
                return f;
            } catch (NoSuchFieldException e) {
                tmpClass = tmpClass.getSuperclass();
            }
        } while (tmpClass != null);

        throw new RuntimeException("Field '" + fieldName + "' not found in class " + clazz);
    }

    private static int toIndex(String s) {
        int res = -1;
        if (s != null && s.length() > 0 && Character.isDigit(s.charAt(0))) {
            try {
                res = Integer.parseInt(s);
                if (res < 0) {
                    res = -1;
                }
            } catch (Throwable t) {
                res = -1;
            }
        }
        return res;
    }
}

It supports fetching fields and array items, e.g.:

System.out.println(""+Refl.getValue(b,"x.q[0].z.y"));

there is no difference between dots and braces, they are just delimiters, and empty field names are ignored:

System.out.println(""+Refl.getValue(b,"x.q[0].z.y[value]"));
System.out.println(""+Refl.getValue(b,"x.q.1.y.z.value"));
System.out.println(""+Refl.getValue(b,"x[q.1]y]z[value"));

C programming: Dereferencing pointer to incomplete type error

You haven't defined struct stasher_file by your first definition. What you have defined is an nameless struct type and a variable stasher_file of that type. Since there's no definition for such type as struct stasher_file in your code, the compiler complains about incomplete type.

In order to define struct stasher_file, you should have done it as follows

struct stasher_file {
 char name[32];
 int  size;
 int  start;
 int  popularity;
};

Note where the stasher_file name is placed in the definition.

how to create a cookie and add to http response from inside my service layer?

A cookie is a object with key value pair to store information related to the customer. Main objective is to personalize the customer's experience.

An utility method can be created like

private Cookie createCookie(String cookieName, String cookieValue) {
    Cookie cookie = new Cookie(cookieName, cookieValue);
    cookie.setPath("/");
    cookie.setMaxAge(MAX_AGE_SECONDS);
    cookie.setHttpOnly(true);
    cookie.setSecure(true);
    return cookie;
}

If storing important information then we should alsways put setHttpOnly so that the cookie cannot be accessed/modified via javascript. setSecure is applicable if you are want cookies to be accessed only over https protocol.

using above utility method you can add cookies to response as

Cookie cookie = createCookie("name","value");
response.addCookie(cookie);

How many characters can a Java String have?

You should be able to get a String of length

  1. Integer.MAX_VALUE always 2,147,483,647 (231 - 1)
    (Defined by the Java specification, the maximum size of an array, which the String class uses for internal storage)
    OR

  2. Half your maximum heap size (since each character is two bytes) whichever is smaller.

How to create a simple checkbox in iOS?

Yeah, no checkbox for you in iOS (-:

Here, this is what I did to create a checkbox:

UIButton *checkbox;
BOOL checkBoxSelected;
checkbox = [[UIButton alloc] initWithFrame:CGRectMake(x,y,20,20)];
// 20x20 is the size of the checkbox that you want
// create 2 images sizes 20x20 , one empty square and
// another of the same square with the checkmark in it
// Create 2 UIImages with these new images, then:

[checkbox setBackgroundImage:[UIImage imageNamed:@"notselectedcheckbox.png"]
                    forState:UIControlStateNormal];
[checkbox setBackgroundImage:[UIImage imageNamed:@"selectedcheckbox.png"]
                    forState:UIControlStateSelected];
[checkbox setBackgroundImage:[UIImage imageNamed:@"selectedcheckbox.png"]
                    forState:UIControlStateHighlighted];
checkbox.adjustsImageWhenHighlighted=YES;
[checkbox addTarget:(nullable id) action:(nonnull SEL) forControlEvents:(UIControlEvents)];
[self.view addSubview:checkbox];

Now in the target method do the following:

-(void)checkboxSelected:(id)sender
{
    checkBoxSelected = !checkBoxSelected; /* Toggle */
    [checkbox setSelected:checkBoxSelected];
}

That's it!

How to extract request http headers from a request using NodeJS connect

To see a list of HTTP request headers, you can use :

console.log(JSON.stringify(req.headers));

to return a list in JSON format.

{
"host":"localhost:8081",
"connection":"keep-alive",
"cache-control":"max-age=0",
"accept":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
"upgrade-insecure-requests":"1",
"user-agent":"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.107 Safari/537.36",
"accept-encoding":"gzip, deflate, sdch",
"accept-language":"en-US,en;q=0.8,et;q=0.6"
}

How to check if a std::string is set or not?

The default constructor for std::string always returns an object that is set to a null string.

CSS Input field text color of inputted text

I always do input prompts, like this:

    <input style="color: #C0C0C0;" value="[email protected]" 
    onfocus="this.value=''; this.style.color='#000000'">

Of course, if your user fills in the field, changes focus and comes back to the field, the field will once again be cleared. If you do it like that, be sure that's what you want. You can make it a one time thing by setting a semaphore, like this:

    <script language = "text/Javascript"> 
    cleared[0] = cleared[1] = cleared[2] = 0; //set a cleared flag for each field
    function clearField(t){                   //declaring the array outside of the
    if(! cleared[t.id]){                      // function makes it static and global
        cleared[t.id] = 1;  // you could use true and false, but that's more typing
        t.value='';         // with more chance of typos
        t.style.color='#000000';
        }
    }
    </script>

Your <input> field then looks like this:

    <input id = 0; style="color: #C0C0C0;" value="[email protected]" 
    onfocus=clearField(this)>

Need to combine lots of files in a directory

In windows I use a simple command in a batch file and I use a Scheduled Task to keep all the info in only one file. Be sure to choose another path to the result file, or You will have duplicate data.

type PathToOriginalFiles\*.Extension > AnotherPathToResultFile\NameOfTheResultFile.Extension

If you need to join lots of csv files, a good thing to do is to have the header in only one file with a name like 0header.csv, or other name, so that it will allways be the first file in list, and be sure to program all the other csv files to not contain an header.

Difference between scaling horizontally and vertically for databases

SQL databases like Oracle, db2 also support Horizontal scaling through Shared disk cluster. For example Oracle RAC, IBM DB2 purescale or Sybase ASE Cluster edition. New node can be added to Oracle RAC system or DB2 purescale system to achieve horizontal scaling.

But the approach is different from noSQL databases (like mongodb, CouchDB or IBM Cloudant) is that the data sharding is not part of Horizontal scaling. In noSQL databases data is shraded during horizontal scaling.

How to check if a process id (PID) exists

ps command with -p $PID can do this:

$ ps -p 3531
  PID TTY          TIME CMD
 3531 ?        00:03:07 emacs

NSURLSession/NSURLConnection HTTP load failed on iOS 9

I have solved it with adding some key in info.plist. The steps I followed are:

I Opened my project's info.plist file

Added a Key called NSAppTransportSecurity as a Dictionary.

Added a Subkey called NSAllowsArbitraryLoads as Boolean and set its value to YES as like following image. enter image description here

Clean the Project and Now Everything is Running fine as like before.

Ref Link: https://stackoverflow.com/a/32609970

scrollable div inside container

If you put overflow: scroll on a fixed height div, the div will scroll if the contents take up too much space.

Convert floating point number to a certain precision, and then copy to string

Using round:

>>> numvar = 135.12345678910
>>> str(round(numvar, 9))
'135.123456789'

How to check if a Docker image with a specific tag exist locally?

In case you are trying to search for a docker image from a docker registry, I guess the easiest way to check if a docker image is present is by using the Docker V2 REST API Tags list service

Example:-

curl $CURLOPTS -H "Authorization: Bearer $token" "https://hub.docker.com:4443/v2/your-repo-name/tags/list"

if the above result returns 200Ok with a list of image tags, then we know that image exists

{"name":"your-repo-name","tags":["1.0.0.1533677221","1.0.0.1533740305","1.0.0.1535659921","1.0.0.1535665433","latest"]}

else if you see something like

{"errors":[{"code":"NAME_UNKNOWN","message":"repository name not known to registry","detail":{"name":"your-repo-name"}}]} 

then you know for sure that image doesn't exist.

Pass data to layout that are common to all pages

You don't have to mess with actions or change the model, just use a base controller and cast the existing controller from the layout viewcontext.

Create a base controller with the desired common data (title/page/location etc) and action initialization...

public abstract class _BaseController:Controller {
    public Int32 MyCommonValue { get; private set; }

    protected override void OnActionExecuting(ActionExecutingContext filterContext) {

        MyCommonValue = 12345;

        base.OnActionExecuting(filterContext);
    }
}

Make sure every controller uses the base controller...

public class UserController:_BaseController {...

Cast the existing base controller from the view context in your _Layout.cshml page...

@{
    var myController = (_BaseController)ViewContext.Controller;
}

Now you can refer to values in your base controller from your layout page.

@myController.MyCommonValue

UPDATE

You could also create a page extension that would allow you to use this.

//Allows typed "this.Controller()." in cshtml files
public static class MyPageExtensions {
    public static _BaseController Controller(this WebViewPage page) => Controller<_BaseController>(page);
    public static T Controller<T>(this WebViewPage page) where T : _BaseController => (T)page.ViewContext.Controller;
}

Then you only have to remember to use this.Controller() when you want the controller.

@{
    var myController = this.Controller(); //_BaseController
}

or specific controller that inherits from _BaseController...

@{
    var myController = this.Controller<MyControllerType>();
}

Hibernate JPA Sequence (non-Id)

"I don't want to use a trigger or any other thing other than Hibernate itself to generate the value for my property"

In that case, how about creating an implementation of UserType which generates the required value, and configuring the metadata to use that UserType for persistence of the mySequenceVal property?

Reset par to the default values at startup

dev.off() is the best function, but it clears also all plots. If you want to keep plots in your window, at the beginning save default par settings:

def.par = par()

Then when you use your par functions you still have a backup of default par settings. Later on, after generating plots, finish with:

par(def.par) #go back to default par settings

With this, you keep generated plots and reset par settings.

Making macOS Installer Packages which are Developer ID ready

FYI for those that are trying to create a package installer for a bundle or plugin, it's easy:

pkgbuild --component "Color Lists.colorPicker" --install-location ~/Library/ColorPickers ColorLists.pkg

How do I remove accents from characters in a PHP string?

$unwanted_array = array(    '&amp;' => 'and', '&' => 'and', '@' => 'at', '©' => 'c', '®' => 'r', 
'°'=>'','¸'=>'','?'=>'','¯'=>'','_'=>'',
'Á'=>'a','á'=>'a','À'=>'a','à'=>'a','A'=>'a','a'=>'a','?'=>'a','?'=>'A','?'=>'A',
'?'=>'a','?'=>'a','?'=>'A','?'=>'a','?'=>'A','Â'=>'a','â'=>'a','?'=>'a','?'=>'A',
'?'=>'a','?'=>'a','?'=>'a','?'=>'A','A'=>'a','a'=>'a','Å'=>'a','å'=>'a','?'=>'a',
'?'=>'a','Ä'=>'a','ä'=>'a','ã'=>'a','Ã'=>'A','A'=>'a','a'=>'a','A'=>'a','a'=>'a',
'?'=>'a','?'=>'a','?'=>'A','?'=>'a','?'=>'a','?'=>'A','?'=>'a','?'=>'A','Æ'=>'ae',
'æ'=>'ae','?'=>'ae','?'=>'ae','?'=>'a','?'=>'A',
'C'=>'c','c'=>'c','C'=>'c','c'=>'c','C'=>'c','c'=>'c','C'=>'c','c'=>'c','Ç'=>'c','ç'=>'c',
'D'=>'d','d'=>'d','?'=>'D','?'=>'d','Ð'=>'d','d'=>'d','?'=>'D','?'=>'d','?'=>'D','?'=>'d','ð'=>'d','Ð'=>'D',
'É'=>'e','é'=>'e','È'=>'e','è'=>'e','E'=>'e','e'=>'e','ê'=>'e','?'=>'e','?'=>'E','?'=>'e',
'?'=>'E','E'=>'e','e'=>'e','Ë'=>'e','ë'=>'e','E'=>'e','e'=>'e','E'=>'e','e'=>'e','E'=>'e',
'e'=>'e','?'=>'e','?'=>'E','?'=>'e','?'=>'e','?'=>'e','?'=>'E','?'=>'e',
'?'=>'E','?'=>'e','?'=>'E','?'=>'e','?'=>'E','?'=>'e','?'=>'E',
'ƒ'=>'f',
'G'=>'g','g'=>'g','G'=>'g','g'=>'g','G'=>'G','g'=>'g','G'=>'g','g'=>'g','G'=>'g','g'=>'g',
'H_'=>'H','h_'=>'h','H'=>'h','h'=>'h','?'=>'H','?'=>'h','?'=>'H','?'=>'h','H'=>'h','h'=>'h','?'=>'H','?'=>'h',
'?'=>'I','Í'=>'i','í'=>'i','Ì'=>'i','ì'=>'i','I'=>'i','i'=>'i','Î'=>'i','î'=>'i','I'=>'i','i'=>'i',
'Ï'=>'i','ï'=>'i','?'=>'I','?'=>'i','I'=>'i','i'=>'i','I'=>'i','I'=>'i','i'=>'i','I'=>'i','i'=>'i',
'?'=>'I','?'=>'I','?'=>'i','?'=>'ij','?'=>'ij','i'=>'i',
'J'=>'j','j'=>'j',
'K'=>'k','k'=>'k','?'=>'K','?'=>'k',
'L'=>'l','l'=>'l','L'=>'l','l'=>'l','L'=>'l','l'=>'l','L'=>'l','l'=>'l','?'=>'l','?'=>'l',
'N'=>'n','n'=>'n','N'=>'n','n'=>'n','Ñ'=>'N','ñ'=>'n','N'=>'n','n'=>'n','?'=>'N','?'=>'n','?'=>'n','?'=>'n',
'Ó'=>'o','ó'=>'o','Ò'=>'o','ò'=>'o','O'=>'o','o'=>'o','Ô'=>'o','ô'=>'o','?'=>'o','?'=>'O','?'=>'o',
'?'=>'O','?'=>'o','?'=>'O','O'=>'o','o'=>'o','Ö'=>'o','ö'=>'o','O'=>'o','o'=>'o','Õ'=>'o','õ'=>'o',
'Ø'=>'o','ø'=>'o','?'=>'o','?'=>'o','O'=>'O','o'=>'o','O'=>'O','o'=>'o','O'=>'o','o'=>'o','?'=>'o',
'?'=>'O','O'=>'o','o'=>'o','?'=>'o','?'=>'O','?'=>'o','?'=>'O','?'=>'o','?'=>'O','?'=>'o','?'=>'O',
'?'=>'o','?'=>'O','?'=>'o','?'=>'O','?'=>'o','?'=>'O','?'=>'o','?'=>'O','?'=>'o','?'=>'O',
'Œ'=>'oe','œ'=>'oe',
'?'=>'k',
'R'=>'r','r'=>'r','R'=>'r','r'=>'r','?'=>'r','R'=>'r','r'=>'r','?'=>'R','?'=>'r','?'=>'R','?'=>'r',
'S_'=>'S','s_'=>'s','S'=>'s','s'=>'s','S'=>'s','s'=>'s','Š'=>'s','š'=>'s','S'=>'s','s'=>'s',
'?'=>'S','?'=>'s','?'=>'S','?'=>'s',
'?'=>'z','ß'=>'ss','T'=>'t','t'=>'t','T'=>'t','t'=>'t','?'=>'T','?'=>'t','?'=>'T',
'?'=>'t','?'=>'T','?'=>'t','™'=>'tm','T'=>'t','t'=>'t',
'Ú'=>'u','ú'=>'u','Ù'=>'u','ù'=>'u','U'=>'u','u'=>'u','Û'=>'u','û'=>'u','U'=>'u','u'=>'u','U'=>'u','u'=>'u',
'Ü'=>'u','ü'=>'u','U'=>'u','u'=>'u','U'=>'u','u'=>'u','U'=>'u','u'=>'u','U'=>'u','u'=>'u','U'=>'u','u'=>'u',
'U'=>'u','u'=>'u','U'=>'u','u'=>'u','U'=>'u','u'=>'u','U'=>'u','u'=>'u','?'=>'u','?'=>'U','?'=>'u','?'=>'U',
'?'=>'u','?'=>'U','?'=>'u','?'=>'U','?'=>'u','?'=>'U','?'=>'u','?'=>'U','?'=>'u','?'=>'U',
'W'=>'w','w'=>'w',
'Ý'=>'y','ý'=>'y','?'=>'y','?'=>'Y','Y'=>'y','y'=>'y','ÿ'=>'y','Ÿ'=>'y','?'=>'y','?'=>'Y','?'=>'y','?'=>'Y',
'Z_'=>'Z','z_'=>'z','Z'=>'z','z'=>'z','Ž'=>'z','ž'=>'z','Z'=>'z','z'=>'z','?'=>'Z','?'=>'z',
'þ'=>'p','?'=>'n','?'=>'a','?'=>'a','?'=>'b','?'=>'b','?'=>'v','?'=>'v','?'=>'g','?'=>'g','?'=>'g','?'=>'g',
'?'=>'d','?'=>'d','?'=>'e','?'=>'e','?'=>'jo','?'=>'jo','?'=>'e','?'=>'e','?'=>'zh','?'=>'zh','?'=>'z','?'=>'z',
'?'=>'i','?'=>'i','?'=>'i','?'=>'i','?'=>'i','?'=>'i','?'=>'j','?'=>'j','?'=>'k','?'=>'k','?'=>'l','?'=>'l',
'?'=>'m','?'=>'m','?'=>'n','?'=>'n','?'=>'o','?'=>'o','?'=>'p','?'=>'p','?'=>'r','?'=>'r','?'=>'s','?'=>'s',
'?'=>'t','?'=>'t','?'=>'u','?'=>'u','?'=>'f','?'=>'f','?'=>'h','?'=>'h','?'=>'c','?'=>'c','?'=>'ch','?'=>'ch',
'?'=>'sh','?'=>'sh','?'=>'sch','?'=>'sch','?'=>'-',
'?'=>'-','?'=>'y','?'=>'y','?'=>'-','?'=>'-',
'?'=>'je','?'=>'je','?'=>'ju','?'=>'ju','?'=>'ja','?'=>'ja','?'=>'a','?'=>'b','?'=>'g','?'=>'d','?'=>'h','?'=>'v',
'?'=>'z','?'=>'h','?'=>'t','?'=>'i','?'=>'k','?'=>'k','?'=>'l','?'=>'m','?'=>'m','?'=>'n','?'=>'n','?'=>'s','?'=>'e',
'?'=>'p','?'=>'p','?'=>'C','?'=>'c','?'=>'q','?'=>'r','?'=>'w','?'=>'t'
);

$accentsRemoved = strtr( $stringToRemoveAccents , $unwanted_array );

CSS hover vs. JavaScript mouseover

Use CSS, it makes for much easier management of the style itself.

Sass Nesting for :hover does not work

For concatenating selectors together when nesting, you need to use the parent selector (&):

.class {
    margin:20px;
    &:hover {
        color:yellow;
    }
}

Syntax behind sorted(key=lambda: ...)

lambda is a Python keyword that is used to generate anonymous functions.

>>> (lambda x: x+2)(3)
5

Change date format in a Java string

SimpleDateFormat dt1 = new SimpleDateFormat("yyyy-mm-dd");

Dynamic function name in javascript?

I might be missing the obvious here, but what's wrong with just adding the name? functions are invoked regardless of their name. names are just used for scoping reasons. if you assign it to a variable, and it's in scope, it can be called. hat happens is your are executing a variable which happens to be a function. if you must have a name for identification reasons when debugging, insert it between the keyword function and the opening brace.

_x000D_
_x000D_
var namedFunction = function namedFunction (a,b) {return a+b};_x000D_
_x000D_
alert(namedFunction(1,2));_x000D_
alert(namedFunction.name);_x000D_
alert(namedFunction.toString());
_x000D_
_x000D_
_x000D_

an alternative approach is to wrap the function in an outer renamed shim, which you can also pass into an outer wrapper, if you don't want to dirty the surrounding namespace. if you are wanting to actually dynamically create the function from strings (which most of these examples do), it's trivial to rename the source to do what you want. if however you want to rename existing functions without affecting their functionality when called elsewhere, a shim is the only way to achieve it.

_x000D_
_x000D_
(function(renamedFunction) {_x000D_
_x000D_
  alert(renamedFunction(1,2));_x000D_
  alert(renamedFunction.name);_x000D_
  alert(renamedFunction.toString());_x000D_
  alert(renamedFunction.apply(this,[1,2]));_x000D_
_x000D_
_x000D_
})(function renamedFunction(){return namedFunction.apply(this,arguments);});_x000D_
_x000D_
function namedFunction(a,b){return a+b};
_x000D_
_x000D_
_x000D_

What are the differences between the different saving methods in Hibernate?

None of the answers above are complete. Although Leo Theobald answer looks nearest answer.

The basic point is how hibernate is dealing with states of entities and how it handles them when there is a state change. Everything must be seen with respect to flushes and commits as well, which everyone seems to have ignored completely.

NEVER USE THE SAVE METHOD of HIBERNATE. FORGET THAT IT EVEN EXISTS IN HIBERNATE!

Persist

As everyone explained, Persist basically transitions an entity from "Transient" state to "Managed" State. At this point, a slush or a commit can create an insert statement. But the entity will still remains in "Managed" state. That doesn't change with flush.

At this point, if you "Persist" again there will be no change. And there wont be any more saves if we try to persist a persisted entity.

The fun begins when we try to evict the entity.

An evict is a special function of Hibernate which will transition the entity from "Managed" to "Detached". We cannot call a persist on a detached entity. If we do that, then Hibernate raises an exception and entire transaction gets rolled back on commit.

Merge vs Update

These are 2 interesting functions doing different stuff when dealt in different ways. Both of them are trying to transition the entity from "Detached" state to "Managed" state. But doing it differently.

Understand a fact that Detached means kind of an "offline" state. and managed means "Online" state.

Observe the code below:

Session ses1 = sessionFactory.openSession();

    Transaction tx1 = ses1.beginTransaction();

    HibEntity entity = getHibEntity();

    ses1.persist(entity);
    ses1.evict(entity);

    ses1.merge(entity);

    ses1.delete(entity);

    tx1.commit();

When you do this? What do you think will happen? If you said this will raise exception, then you are correct. This will raise exception because, merge has worked on entity object, which is detached state. But it doesn't alter the state of object.

Behind the scene, merge will raise a select query and basically returns a copy of entity which is in attached state. Observe the code below:

Session ses1 = sessionFactory.openSession();

    Transaction tx1 = ses1.beginTransaction();
    HibEntity entity = getHibEntity();

    ses1.persist(entity);
    ses1.evict(entity);

    HibEntity copied = (HibEntity)ses1.merge(entity);
    ses1.delete(copied);

    tx1.commit();

The above sample works because merge has brought a new entity into the context which is in persisted state.

When applied with Update the same works fine because update doesn't actually bring a copy of entity like merge.

Session ses1 = sessionFactory.openSession();

    Transaction tx1 = ses1.beginTransaction();

    HibEntity entity = getHibEntity();

    ses1.persist(entity);
    ses1.evict(entity);

    ses1.update(entity);

    ses1.delete(entity);

    tx1.commit();

At the same time in debug trace we can see that Update hasn't raised SQL query of select like merge.

delete

In the above example I used delete without talking about delete. Delete will basically transition the entity from managed state to "removed" state. And when flushed or commited will issue a delete command to store.

However it is possible to bring the entity back to "managed" state from "removed" state using the persist method.

Hope the above explanation clarified any doubts.

Difference between Spring MVC and Struts MVC

The major difference between Spring MVC and Struts is: Spring MVC is loosely coupled framework whereas Struts is tightly coupled. For enterprise Application you need to build your application as loosely coupled as it would make your application more reusable and robust as well as distributed.

How to redirect and append both stdout and stderr to a file with Bash?

In Bash 4 (as well as ZSH 4.3.11):

cmd &>>outfile

just out of box

How to iterate over each string in a list of strings and operate on it's elements

for i,j in enumerate(words): # i---index of word----j
     #now you got index of your words (present in i)
     print(i) 

Windows Scipy Install: No Lapack/Blas Resources Found

For python27 1?Install numpy + mkl(download link:http://www.lfd.uci.edu/~gohlke/pythonlibs/) 2?install scipy (the same site) OK!

Add borders to cells in POI generated Excel File

Setting up borders in the style used in the cells will accomplish this. Example:

style.setBorderBottom(HSSFCellStyle.BORDER_MEDIUM);
style.setBorderTop(HSSFCellStyle.BORDER_MEDIUM);
style.setBorderRight(HSSFCellStyle.BORDER_MEDIUM);
style.setBorderLeft(HSSFCellStyle.BORDER_MEDIUM);

The type 'string' must be a non-nullable type in order to use it as parameter T in the generic type or method 'System.Nullable<T>'

Use string instead of string? in all places in your code.

The Nullable<T> type requires that T is a non-nullable value type, for example int or DateTime. Reference types like string can already be null. There would be no point in allowing things like Nullable<string> so it is disallowed.

Also if you are using C# 3.0 or later you can simplify your code by using auto-implemented properties:

public class WordAndMeaning
{
    public string Word { get; set; }
    public string Meaning { get; set; }
}

How to calculate the IP range when the IP address and the netmask is given?

Invert mask (XOR with ones), AND it with IP. Add 1. This will be the starting range. OR IP with mask. This will be the ending range.

read subprocess stdout line by line

A function that allows iterating over both stdout and stderr concurrently, in realtime, line by line

In case you need to get the output stream for both stdout and stderr at the same time, you can use the following function.

The function uses Queues to merge both Popen pipes into a single iterator.

Here we create the function read_popen_pipes():

from queue import Queue, Empty
from concurrent.futures import ThreadPoolExecutor


def enqueue_output(file, queue):
    for line in iter(file.readline, ''):
        queue.put(line)
    file.close()


def read_popen_pipes(p):

    with ThreadPoolExecutor(2) as pool:
        q_stdout, q_stderr = Queue(), Queue()

        pool.submit(enqueue_output, p.stdout, q_stdout)
        pool.submit(enqueue_output, p.stderr, q_stderr)

        while True:

            if p.poll() is not None and q_stdout.empty() and q_stderr.empty():
                break

            out_line = err_line = ''

            try:
                out_line = q_stdout.get_nowait()
            except Empty:
                pass
            try:
                err_line = q_stderr.get_nowait()
            except Empty:
                pass

            yield (out_line, err_line)

read_popen_pipes() in use:

import subprocess as sp


with sp.Popen(my_cmd, stdout=sp.PIPE, stderr=sp.PIPE, text=True) as p:

    for out_line, err_line in read_popen_pipes(p):

        # Do stuff with each line, e.g.:
        print(out_line, end='')
        print(err_line, end='')

    return p.poll() # return status-code

git pull from master into the development branch

Situation: Working in my local branch, but I love to keep-up updates in the development branch named dev.

Solution: Usually, I prefer to do :

git fetch
git rebase origin/dev

Find and replace specific text characters across a document with JS

Similar to @max-malik's answer, but without using jQuery, you can also do this using document.createTreeWalker:

_x000D_
_x000D_
button.addEventListener('click', e => {_x000D_
  const treeWalker = document.createTreeWalker(document.body);_x000D_
  while (treeWalker.nextNode()) {_x000D_
    const node = treeWalker.currentNode;_x000D_
    node.textContent = node.textContent.replace(/@/g, '$');_x000D_
  }_x000D_
})
_x000D_
<div>This is an @ that we are @ replacing.</div>_x000D_
<div>This is another @ that we are replacing.</div>_x000D_
<div>_x000D_
  <span>This is an @ in a span in @ div.</span>_x000D_
</div>_x000D_
<br>_x000D_
<input id="button" type="button" value="Replace @ with $" />
_x000D_
_x000D_
_x000D_

More elegant "ps aux | grep -v grep"

You could use preg_split instead of explode and split on [ ]+ (one or more spaces). But I think in this case you could go with preg_match_all and capturing:

preg_match_all('/[ ]php[ ]+\S+[ ]+(\S+)/', $input, $matches);
$result = $matches[1];

The pattern matches a space, php, more spaces, a string of non-spaces (the path), more spaces, and then captures the next string of non-spaces. The first space is mostly to ensure that you don't match php as part of a user name but really only as a command.

An alternative to capturing is the "keep" feature of PCRE. If you use \K in the pattern, everything before it is discarded in the match:

preg_match_all('/[ ]php[ ]+\S+[ ]+\K\S+/', $input, $matches);
$result = $matches[0];

I would use preg_match(). I do something similar for many of my system management scripts. Here is an example:

$test = "user     12052  0.2  0.1 137184 13056 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust1 cron
user     12054  0.2  0.1 137184 13064 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust3 cron
user     12055  0.6  0.1 137844 14220 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust4 cron
user     12057  0.2  0.1 137184 13052 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust89 cron
user     12058  0.2  0.1 137184 13052 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust435 cron
user     12059  0.3  0.1 135112 13000 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust16 cron
root     12068  0.0  0.0 106088  1164 pts/1    S+   10:00   0:00 sh -c ps aux | grep utilities > /home/user/public_html/logs/dashboard/currentlyPosting.txt
root     12070  0.0  0.0 103240   828 pts/1    R+   10:00   0:00 grep utilities";

$lines = explode("\n", $test);

foreach($lines as $line){
        if(preg_match("/.php[\s+](cust[\d]+)[\s+]cron/i", $line, $matches)){
                print_r($matches);
        }

}

The above prints:

Array
(
    [0] => .php cust1 cron
    [1] => cust1
)
Array
(
    [0] => .php cust3 cron
    [1] => cust3
)
Array
(
    [0] => .php cust4 cron
    [1] => cust4
)
Array
(
    [0] => .php cust89 cron
    [1] => cust89
)
Array
(
    [0] => .php cust435 cron
    [1] => cust435
)
Array
(
    [0] => .php cust16 cron
    [1] => cust16
)

You can set $test to equal the output from exec. the values you are looking for would be in the if statement under the foreach. $matches[1] will have the custx value.

How to get the first non-null value in Java?

Following on from LES2's answer, you can eliminate some repetition in the efficient version, by calling the overloaded function:

public static <T> T coalesce(T a, T b) {
    return a != null ? a : b;
}
public static <T> T coalesce(T a, T b, T c) {
    return a != null ? a : coalesce(b,c);
}
public static <T> T coalesce(T a, T b, T c, T d) {
    return a != null ? a : coalesce(b,c,d);
}
public static <T> T coalesce(T a, T b, T c, T d, T e) {
    return a != null ? a : coalesce(b,c,d,e);
}

How to delete a cookie?

would this work?

function eraseCookie(name) {
    document.cookie = name + '=; Max-Age=0'
}

I know Max-Age causes the cookie to be a session cookie in IE when creating the cookie. Not sure how it works when deleting cookies.

Unable to load Private Key. (PEM routines:PEM_read_bio:no start line:pem_lib.c:648:Expecting: ANY PRIVATE KEY)

Create CA certificate

openssl genrsa -out privateKey.pem 4096
openssl req -new -x509 -nodes -days 3600 -key privateKey.pem -out caKey.pem

Contains method for a slice

Currently there's Contains function in slice package. You can read the docs here.

Sample usage :

if !slice.Contains(sliceVar, valueToFind) {
    //code here
}

c# Image resizing to different size while preserving aspect ratio

I created a extension method that is much simpiler than the answers that are posted. and the aspect ratio is applied without cropping the image.

public static Image Resize(this Image image, int width, int height) {
     var scale = Math.Min(height / (float)image.Height, width / (float)image.Width);
     return image.GetThumbnailImage((int)(image.Width * scale), (int)(image.Height * scale), () => false, IntPtr.Zero);
}

Example usage:

using (var img = Image.FromFile(pathToOriginalImage)) {
    using (var thumbnail = img.Resize(60, 60)){
        // Here you can do whatever you need to do with thumnail
    }
}

Adb install failure: INSTALL_CANCELED_BY_USER

1 Settings

2 Additional Settings

3 Developer Options

4 Developer options: Check the Install via USB option.

enter image description here

How can I open multiple files using "with open" in Python?

As of Python 2.7 (or 3.1 respectively) you can write

with open('a', 'w') as a, open('b', 'w') as b:
    do_something()

In earlier versions of Python, you can sometimes use contextlib.nested() to nest context managers. This won't work as expected for opening multiples files, though -- see the linked documentation for details.


In the rare case that you want to open a variable number of files all at the same time, you can use contextlib.ExitStack, starting from Python version 3.3:

with ExitStack() as stack:
    files = [stack.enter_context(open(fname)) for fname in filenames]
    # Do something with "files"

Most of the time you have a variable set of files, you likely want to open them one after the other, though.

How can I start InternetExplorerDriver using Selenium WebDriver

package Browser;

import org.openqa.selenium.WebDriver; import org.openqa.selenium.ie.InternetExplorerDriver;

public class Hello {

public static void main(String[] args) {


    // setting IEdriver property
    System.setProperty("webdriver.ie.driver",
            "paste the path of the IEDriverserver.exe");

    WebDriver driver = new InternetExplorerDriver();

    // launching the google home screen
    driver.get("https://www.google.com/?gws_rd=ssl");

}

} //Hope this will work

Batch file to move files to another directory

Try:

move "C:\files\*.txt" "C:\txt"

Empty set literal?

It depends on if you want the literal for a comparison, or for assignment.

If you want to make an existing set empty, you can use the .clear() metod, especially if you want to avoid creating a new object. If you want to do a comparison, use set() or check if the length is 0.

example:

#create a new set    
a=set([1,2,3,'foo','bar'])
#or, using a literal:
a={1,2,3,'foo','bar'}

#create an empty set
a=set()
#or, use the clear method
a.clear()

#comparison to a new blank set
if a==set():
    #do something

#length-checking comparison
if len(a)==0:
    #do something

How do I do multiple CASE WHEN conditions using SQL Server 2008?

Something Like this, Two Conditions Two Columns

SELECT ITEMSREQ.ITEM AS ITEM,
       ITEMSREQ.CANTIDAD AS CANTIDAD,
       (CASE  WHEN ITEMSREQ.ITEMAPROBADO=1 THEN 'APROBADO'
              WHEN ITEMSREQ.ITEMAPROBADO=0 THEN 'NO APROBADO'
        END) AS ITEMS,
        (CASE 
              WHEN ITEMSREQ.ITEMAPROBADO = 0 
              THEN CASE WHEN REQUISICIONES.RECIBIDA IS NULL  THEN 'ITEM NO APROBADO PARA ENTREGA' END
              WHEN ITEMSREQ.ITEMAPROBADO = 1 
              THEN CASE WHEN REQUISICIONES.RECIBIDA IS NULL THEN 'ITEM AUN NO RECIBIDO' 
                        WHEN REQUISICIONES.RECIBIDA=1 THEN 'RECIBIDO' 
                        WHEN REQUISICIONES.RECIBIDA=0 THEN 'NO RECIBIDO' 
                       END
              END)
              AS RECIBIDA
 FROM ITEMSREQ
      INNER JOIN REQUISICIONES ON
      ITEMSREQ.CNSREQ = REQUISICIONES.CNSREQ

Reading from stdin

You can do something like this to read 10 bytes:

char buffer[10];
read(STDIN_FILENO, buffer, 10);

remember read() doesn't add '\0' to terminate to make it string (just gives raw buffer).

To read 1 byte at a time:

char ch;
while(read(STDIN_FILENO, &ch, 1) > 0)
{
 //do stuff
}

and don't forget to #include <unistd.h>, STDIN_FILENO defined as macro in this file.

There are three standard POSIX file descriptors, corresponding to the three standard streams, which presumably every process should expect to have:

Integer value   Name
       0        Standard input (stdin)
       1        Standard output (stdout)
       2        Standard error (stderr)

So instead STDIN_FILENO you can use 0.

Edit:
In Linux System you can find this using following command:

$ sudo grep 'STDIN_FILENO' /usr/include/* -R | grep 'define'
/usr/include/unistd.h:#define   STDIN_FILENO    0   /* Standard input.  */

Notice the comment /* Standard input. */

Install a Nuget package in Visual Studio Code

If you're working with .net core, you can use the dotnet CLI, for instance

dotnet add package <package name>

Exclude all transitive dependencies of a single dependency

One thing I have found useful:

If you put the dependency with the exclusions in the dependencyManagement section of either the parent POM for your project, or in an importable dependency management POM, then you don't need to repeat the exclusion (or the version).

For example, if your parent POM has:

<dependencyManagement>
    <dependencies>
    ...         
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.2.1</version>
            <exclusions>
                <exclusion>
                    <groupId>junit</groupId>
                    <artifactId>junit</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
     ....
  </dependencies>
</dependencyManagement>

Then the modules in your project can simply declare the dependency as:

        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
        </dependency>

The in the parent POM will specify both the version and the exclusions. I use this technique for nearly all of our projects and it eliminates a lot of repetition.

Load content of a div on another page

Yes, see "Loading Page Fragments" on http://api.jquery.com/load/.

In short, you add the selector after the URL. For example:

$('#result').load('ajax/test.html #container');

Get names of all keys in the collection

With Kristina's answer as inspiration, I created an open source tool called Variety which does exactly this: https://github.com/variety/variety

How do I get the number of days between two dates in JavaScript?

What about using formatDate from DatePicker widget? You could use it to convert the dates in timestamp format (milliseconds since 01/01/1970) and then do a simple subtraction.

Set background colour of cell to RGB value of data in cell

Cells cannot be changed from within a VBA function used as a worksheet formula. Except via this workaround...

Put this function into a new module:

Function SetRGB(x As Range, R As Byte, G As Byte, B As Byte)
  On Error Resume Next
  x.Interior.Color = RGB(R, G, B)
  x.Font.Color = IIf(0.299 * R + 0.587 * G + 0.114 * B < 128, vbWhite, vbBlack)
End Function

Then use this formula in your sheet, for example in cell D2:

=HYPERLINK(SetRGB(D2;A2;B2;C2);"HOVER!")

Once you hover the mouse over the cell (try it!), the background color updates to the RGB taken from cells A2 to C2. The font color is a contrasting white or black.

Conda command not found

Execute the following command after installing and adding to the path

source ~/.bashrc

where source is a bash shell built-in command that executes the content of the file passed as argument, in the current shell.

It runs during boot up automatically.

How does paintComponent work?

Two things you can do here:

  1. Read Painting in AWT and Swing
  2. Use a debugger and put a breakpoint in the paintComponent method. Then travel up the stacktrace and see how provides the Graphics parameter.

Just for info, here is the stacktrace that I got from the example of code I posted at the end:

Thread [AWT-EventQueue-0] (Suspended (breakpoint at line 15 in TestPaint))  
    TestPaint.paintComponent(Graphics) line: 15 
    TestPaint(JComponent).paint(Graphics) line: 1054    
    JPanel(JComponent).paintChildren(Graphics) line: 887    
    JPanel(JComponent).paint(Graphics) line: 1063   
    JLayeredPane(JComponent).paintChildren(Graphics) line: 887  
    JLayeredPane(JComponent).paint(Graphics) line: 1063 
    JLayeredPane.paint(Graphics) line: 585  
    JRootPane(JComponent).paintChildren(Graphics) line: 887 
    JRootPane(JComponent).paintToOffscreen(Graphics, int, int, int, int, int, int) line: 5228   
    RepaintManager$PaintManager.paintDoubleBuffered(JComponent, Image, Graphics, int, int, int, int) line: 1482 
    RepaintManager$PaintManager.paint(JComponent, JComponent, Graphics, int, int, int, int) line: 1413  
    RepaintManager.paint(JComponent, JComponent, Graphics, int, int, int, int) line: 1206   
    JRootPane(JComponent).paint(Graphics) line: 1040    
    GraphicsCallback$PaintCallback.run(Component, Graphics) line: 39    
    GraphicsCallback$PaintCallback(SunGraphicsCallback).runOneComponent(Component, Rectangle, Graphics, Shape, int) line: 78    
    GraphicsCallback$PaintCallback(SunGraphicsCallback).runComponents(Component[], Graphics, int) line: 115 
    JFrame(Container).paint(Graphics) line: 1967    
    JFrame(Window).paint(Graphics) line: 3867   
    RepaintManager.paintDirtyRegions(Map<Component,Rectangle>) line: 781    
    RepaintManager.paintDirtyRegions() line: 728    
    RepaintManager.prePaintDirtyRegions() line: 677 
    RepaintManager.access$700(RepaintManager) line: 59  
    RepaintManager$ProcessingRunnable.run() line: 1621  
    InvocationEvent.dispatch() line: 251    
    EventQueue.dispatchEventImpl(AWTEvent, Object) line: 705    
    EventQueue.access$000(EventQueue, AWTEvent, Object) line: 101   
    EventQueue$3.run() line: 666    
    EventQueue$3.run() line: 664    
    AccessController.doPrivileged(PrivilegedAction<T>, AccessControlContext) line: not available [native method]    
    ProtectionDomain$1.doIntersectionPrivilege(PrivilegedAction<T>, AccessControlContext, AccessControlContext) line: 76    
    EventQueue.dispatchEvent(AWTEvent) line: 675    
    EventDispatchThread.pumpOneEventForFilters(int) line: 211   
    EventDispatchThread.pumpEventsForFilter(int, Conditional, EventFilter) line: 128    
    EventDispatchThread.pumpEventsForHierarchy(int, Conditional, Component) line: 117   
    EventDispatchThread.pumpEvents(int, Conditional) line: 113  
    EventDispatchThread.pumpEvents(Conditional) line: 105   
    EventDispatchThread.run() line: 90  

The Graphics parameter comes from here:

RepaintManager.paintDirtyRegions(Map) line: 781 

The snippet involved is the following:

Graphics g = JComponent.safelyGetGraphics(
                        dirtyComponent, dirtyComponent);
                // If the Graphics goes away, it means someone disposed of
                // the window, don't do anything.
                if (g != null) {
                    g.setClip(rect.x, rect.y, rect.width, rect.height);
                    try {
                        dirtyComponent.paint(g); // This will eventually call paintComponent()
                    } finally {
                        g.dispose();
                    }
                }

If you take a look at it, you will see that it retrieve the graphics from the JComponent itself (indirectly with javax.swing.JComponent.safelyGetGraphics(Component, Component)) which itself takes it eventually from its first "Heavyweight parent" (clipped to the component bounds) which it self takes it from its corresponding native resource.

Regarding the fact that you have to cast the Graphics to a Graphics2D, it just happens that when working with the Window Toolkit, the Graphics actually extends Graphics2D, yet you could use other Graphics which do "not have to" extends Graphics2D (it does not happen very often but AWT/Swing allows you to do that).

import java.awt.Color;
import java.awt.Graphics;

import javax.swing.JFrame;
import javax.swing.JPanel;

class TestPaint extends JPanel {

    public TestPaint() {
        setBackground(Color.WHITE);
    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawOval(0, 0, getWidth(), getHeight());
    }

    public static void main(String[] args) {
        JFrame jFrame = new JFrame();
        jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jFrame.setSize(300, 300);
        jFrame.add(new TestPaint());
        jFrame.setVisible(true);
    }
}

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

.show() and .hide() modify the css display rule. I think you want:

$(selector).css('visibility', 'hidden'); // Hide element
$(selector).css('visibility', 'visible'); // Show element

Bootstrap Responsive Text Size

Simplest way is to use dimensions in % or em. Just change the base font size everything will change.

Less

@media (max-width: @screen-xs) {
    body{font-size: 10px;}
}

@media (max-width: @screen-sm) {
    body{font-size: 14px;}
}


h5{
    font-size: 1.4rem;
}       

Look at all the ways at https://stackoverflow.com/a/21981859/406659

You could use viewport units (vh,vw...) but they dont work on Android < 4.4

Generate Java class from JSON?

I had the same problem so i decided to start writing a small tool to help me with this. Im gonna share andopen source it.

https://github.com/BrunoAlexandreMendesMartins/CleverModels

It supports, JAVA, C# & Objective-c from JSON .

Feel free to contribute!

Return an empty Observable

Yes, there is am Empty operator

Rx.Observable.empty();

For typescript, you can use from:

Rx.Observable<Response>.from([])

Twitter Bootstrap - full width navbar

Not sure if the navbar-static-top class was available prior to version 2.2.2 but I think you can accomplish your goal with the following:

<div class="navbar navbar-static-top">
    <div class="navbar-inner">
        <ul class="nav">
            <li class="active"><a href="#">Test1</a></li>
            <li><a href="#">Test2</a></li>
            <li><a href="#">Test3</a></li>
            <li><a href="#">Test4</a></li>
            <li><a href="#">Test5</a></li>
        </ul>
    </div>
</div>
<div class="container">
    ...
</div>

I put together a jsFiddle as an example.

How to check if a String is numeric in Java

I think the only way to reliably tell if a string is a number, is to parse it. So I would just parse it, and if it's a number, you get the number in an int for free!

sorting dictionary python 3

Dictionaries are unordered by definition, What would be the main reason for ordering by key? A list of tuples created by the sort method can be used for whatever the need may have been, but changing the list of tuples back into a dictionary will return a random order

>>> myDic
{10: 'b', 3: 'a', 5: 'c'}
>>> sorted(myDic.items())
[(3, 'a'), (5, 'c'), (10, 'b')]
>>> print(dict(myDic.items()))
{10: 'b', 3: 'a', 5: 'c'}

Creating and playing a sound in swift

For Swift 3:

extension SystemSoundID {
    static func playFileNamed(_ fileName: String, withExtenstion fileExtension: String) {
        var sound: SystemSoundID = 0
        if let soundURL = Bundle.main.url(forResource: fileName, withExtension: fileExtension) {
            AudioServicesCreateSystemSoundID(soundURL as CFURL, &sound)
            AudioServicesPlaySystemSound(sound)
        }
    }
}

SQL select only rows with max value on a column

here is another solution hope it will help someone

Select a.id , a.rev, a.content from Table1 a
inner join 
(SELECT id, max(rev) rev FROM Table1 GROUP BY id) x on x.id =a.id and x.rev =a.rev

Shell script to capture Process ID and kill it if exist

Actually the easiest way to do that would be to pass kill arguments like below:

ps -ef | grep your_process_name | grep -v grep | awk '{print $2}' | xargs kill

Hope it helps.

How do I change TextView Value inside Java Code?

First, add a textView in the XML file

<TextView  
    android:id="@+id/rate_id"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/what_U_want_to_display_in_first_time"
    />

then add a button in xml file with id btn_change_textView and write this two line of code in onCreate() method of activity

Button btn= (Button) findViewById(R.id. btn_change_textView);
TextView textView=(TextView)findViewById(R.id.rate_id);

then use clickListener() on button object like this

btn.setOnClickListener(new View.OnClickListener {
    public void onClick(View v) {
      
        textView.setText("write here what u want to display after button click in string");
    }
});

Using HTML data-attribute to set CSS background-image url

You will need a little JavaScript for that:

var list = document.getElementsByClassName('thumb');

for (var i = 0; i < list.length; i++) {
  var src = list[i].getAttribute('data-image-src');
  list[i].style.backgroundImage="url('" + src + "')";
}

Wrap that in <script> tags at the bottom just before the </body> tag or wrap in a function that you call once the page loaded.

How do I turn off the mysql password validation?

For mysql 8.0 the command to disable password validation component is:

UNINSTALL COMPONENT 'file://component_validate_password';

To install it back again, the command is:

INSTALL COMPONENT 'file://component_validate_password';

If you just want to change the policy of password validation plugin:

SET GLOBAL validate_password.policy = 0;   // For LOW
SET GLOBAL validate_password.policy = 1;   // For MEDIUM
SET GLOBAL validate_password.policy = 2;   // For HIGH

@POST in RESTful web service

REST webservice: (http://localhost:8080/your-app/rest/data/post)

package com.yourorg.rest;

import javax.ws.rs.Consumes;
import javax.ws.rs.POST; 
import javax.ws.rs.Path; 
import javax.ws.rs.Produces; 
import javax.ws.rs.core.MediaType; 
import javax.ws.rs.core.Response;

    @Path("/data")
public class JSONService {

    @POST
    @Path("/post")
    @Consumes(MediaType.APPLICATION_JSON)
    public Response createDataInJSON(String data) { 

        String result = "Data post: "+data;

        return Response.status(201).entity(result).build(); 
    }

Client send a post:

package com.yourorg.client;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;

public class JerseyClientPost {

  public static void main(String[] args) {

    try {

        Client client = Client.create();

        WebResource webResource = client.resource("http://localhost:8080/your-app/rest/data/post");

        String input = "{\"message\":\"Hello\"}";

        ClientResponse response = webResource.type("application/json")
           .post(ClientResponse.class, input);

        if (response.getStatus() != 201) {
            throw new RuntimeException("Failed : HTTP error code : "
                 + response.getStatus());
        }

        System.out.println("Output from Server .... \n");
        String output = response.getEntity(String.class);
        System.out.println(output);

      } catch (Exception e) {

        e.printStackTrace();

      }

    }
}

ssh : Permission denied (publickey,gssapi-with-mic)

And I think this will clearify the cause of posted problem, actualy this is bug of pssh itself (contains inside "askpass-client.py"). It is pssh's lib file. And there is documented issue for -A case: https://code.google.com/archive/p/parallel-ssh/issues/80 There are two possible resolutions to use version of pssh containing this bug in case you forced to use passphrase for private key access:

  1. Correct your "askpass-client.py" as described in link listed before in my post.
  2. Using your favorite pass keeper.

Thnks for attention, hope it helps!

Doctrine 2 ArrayCollection filter method

The Collection#filter method really does eager load all members. Filtering at the SQL level will be added in doctrine 2.3.

How to open the Chrome Developer Tools in a new window?

If you need to open the DevTools press ctrl-shift-i.

If the DevTools window is already opened you can use the ctrl-shift-d shortcut; it switches the window into a detached mode.

For example in my case the electron application window (Chrome) is really small.

enter image description here

It's not possible to use any other suggestions except the ctrl-shift-d shortcut

How do I toggle an ng-show in AngularJS based on a boolean?

You just need to toggle the value of "isReplyFormOpen" on ng-click event

<a ng-click="isReplyFormOpen = !isReplyFormOpen">Reply</a>
 <div ng-show="isReplyFormOpen" id="replyForm">
   </div>

Is it possible to use vh minus pixels in a CSS calc()?

It does work indeed. Issue was with my less compiler. It was compiled in to:

.container {
  min-height: calc(-51vh);
}

Fixed with the following code in less file:

.container {
  min-height: calc(~"100vh - 150px");
}

Thanks to this link: Less Aggressive Compilation with CSS3 calc

Generate your own Error code in swift 3

I still think that Harry's answer is the simplest and completed but if you need something even simpler, then use:

struct AppError {
    let message: String

    init(message: String) {
        self.message = message
    }
}

extension AppError: LocalizedError {
    var errorDescription: String? { return message }
//    var failureReason: String? { get }
//    var recoverySuggestion: String? { get }
//    var helpAnchor: String? { get }
}

And use or test it like this:

printError(error: AppError(message: "My App Error!!!"))

func print(error: Error) {
    print("We have an ERROR: ", error.localizedDescription)
}

How do I change the figure size for a seaborn plot?

You can also set figure size by passing dictionary to rc parameter with key 'figure.figsize' in seaborn set method:

import seaborn as sns

sns.set(rc={'figure.figsize':(11.7,8.27)})

Other alternative may be to use figure.figsize of rcParams to set figure size as below:

from matplotlib import rcParams

# figure size in inches
rcParams['figure.figsize'] = 11.7,8.27

More details can be found in matplotlib documentation

How do I set the maximum line length in PyCharm?

For PyCharm 2017

We can follow below: File >> Settings >> Editor >> Code Style.

Then provide values for Hard Wrap & Visual Guides for wrapping while typing, tick the checkbox.

NB: look at other tabs as well, viz. Python, HTML, JSON etc.

OpenCV error: the function is not implemented

I hope this answer is still useful, despite problem seems to be quite old.

If you have Anaconda installed, and your OpenCV does not support GTK+ (as in this case), you can simply type

conda install -c menpo opencv=2.4.11

It will install suitable OpenCV version that does not produce a mentioned error. Besides, it will reinstall previously installed OpenCV if there was one as a part of Anaconda.

A JOIN With Additional Conditions Using Query Builder or Eloquent

The sql query sample like this

LEFT JOIN bookings  
    ON rooms.id = bookings.room_type_id
    AND (bookings.arrival = ?
        OR bookings.departure = ?)

Laravel join with multiple conditions

->leftJoin('bookings', function($join) use ($param1, $param2) {
    $join->on('rooms.id', '=', 'bookings.room_type_id');
    $join->on(function($query) use ($param1, $param2) {
        $query->on('bookings.arrival', '=', $param1);
        $query->orOn('departure', '=',$param2);
    });
})

Calculating time difference in Milliseconds

From Java 8 onward you can try the following:

import java.time.*;
import java.time.temporal.ChronoUnit;

Instant start_time = Instant.now();
// Your code
Instant stop_time = Instant.now();

System.out.println(Duration.between(start_time, stop_time).toMillis());

//or

System.out.println(ChronoUnit.MILLIS.between(start_time, stop_time));

Cross-browser custom styling for file upload button

The best example is this one, No hiding, No jQuery, It's completely pure CSS

http://css-tricks.com/snippets/css/custom-file-input-styling-webkitblink/

_x000D_
_x000D_
.custom-file-input::-webkit-file-upload-button {_x000D_
    visibility: hidden;_x000D_
}_x000D_
_x000D_
.custom-file-input::before {_x000D_
    content: 'Select some files';_x000D_
    display: inline-block;_x000D_
    background: -webkit-linear-gradient(top, #f9f9f9, #e3e3e3);_x000D_
    border: 1px solid #999;_x000D_
    border-radius: 3px;_x000D_
    padding: 5px 8px;_x000D_
    outline: none;_x000D_
    white-space: nowrap;_x000D_
    -webkit-user-select: none;_x000D_
    cursor: pointer;_x000D_
    text-shadow: 1px 1px #fff;_x000D_
    font-weight: 700;_x000D_
    font-size: 10pt;_x000D_
}_x000D_
_x000D_
.custom-file-input:hover::before {_x000D_
    border-color: black;_x000D_
}_x000D_
_x000D_
.custom-file-input:active::before {_x000D_
    background: -webkit-linear-gradient(top, #e3e3e3, #f9f9f9);_x000D_
}
_x000D_
<input type="file" class="custom-file-input">
_x000D_
_x000D_
_x000D_

Why doesn't Java support unsigned ints?

I can think of one unfortunate side-effect. In java embedded databases, the number of ids you can have with a 32bit id field is 2^31, not 2^32 (~2billion, not ~4billion).

Return background color of selected cell

You can use Cell.Interior.Color, I've used it to count the number of cells in a range that have a given background color (ie. matching my legend).

is there any IE8 only css hack?

So a recent question prompted me to notice a selector set hack for excluding IE 8 only.

.selector, #excludeIE8::before {} will cause IE 8 to throw out the entire selector set, while 5-7 and 9-11 will read it just fine. Any of the :: selectors (::first-line, ::before, ::first-letter, ::selection) will work, I've merely chosen ::before so the line reads accurately. Note that the goal of the fake ::before selector is to be fake, so be sure to change it to something else if you actually have an element with the ID excludeIE8

Interestingly enough, in modern browsers (FF 45-52, GC 49-57, Edge 25/13) a bad :: selector eats the entire selector set (dabblet demo). It seems that the last Windows version of Safari (and LTE IE 7, lol) doesn't have this behavior while still understanding ::before. Additionally, I can't find anything in the spec to indicate that this is intended behavior, and since it would cause breakage on any selector set containing: ::future-legitimate-pseudoelement... I'm inclined to say this is a bug- and one that'll nibble our rears in the future.


However, if you only want something at the property level (rather than the rule level), Ziga above had the best solution via appending  \9 (the space is key; do NOT copypaste that inline as it uses an nbsp):

/*property-level hacks:*/
/*Standards, Edge*/
prop:val;
/*lte ie 11*/
prop:val\9;
/*lte ie 8*/
prop:val \9;
/*lte ie 7*/
*prop:val;
/*lte ie 6*/
_prop:val;

/*other direction...*/
/*gte ie 8, NOT Edge*/
prop:val\0;

Side note, I feel like a dirty necromancer- but I wanted somewhere to document the exclude-IE8-only selector set hack I found today, and this seemed to be the most fitting place.

Visual Studio Code Tab Key does not insert a tab

Click "Tab Moves Focus" at the bottom right in the status bar.

I believe I had clicked on ctrl+M. When doing this, the "Tab Moves Focus" tab/button showed up at the bottom right. Clicking on that makes it go away and starts working again.

enter image description here

How to map to multiple elements with Java 8 streams?

It's an interesting question, because it shows that there are a lot of different approaches to achieve the same result. Below I show three different implementations.


Default methods in Collection Framework: Java 8 added some methods to the collections classes, that are not directly related to the Stream API. Using these methods, you can significantly simplify the implementation of the non-stream implementation:

Collection<DataSet> convert(List<MultiDataPoint> multiDataPoints) {
    Map<String, DataSet> result = new HashMap<>();
    multiDataPoints.forEach(pt ->
        pt.keyToData.forEach((key, value) ->
            result.computeIfAbsent(
                key, k -> new DataSet(k, new ArrayList<>()))
            .dataPoints.add(new DataPoint(pt.timestamp, value))));
    return result.values();
}

Stream API with flatten and intermediate data structure: The following implementation is almost identical to the solution provided by Stuart Marks. In contrast to his solution, the following implementation uses an anonymous inner class as intermediate data structure.

Collection<DataSet> convert(List<MultiDataPoint> multiDataPoints) {
    return multiDataPoints.stream()
        .flatMap(mdp -> mdp.keyToData.entrySet().stream().map(e ->
            new Object() {
                String key = e.getKey();
                DataPoint dataPoint = new DataPoint(mdp.timestamp, e.getValue());
            }))
        .collect(
            collectingAndThen(
                groupingBy(t -> t.key, mapping(t -> t.dataPoint, toList())),
                m -> m.entrySet().stream().map(e -> new DataSet(e.getKey(), e.getValue())).collect(toList())));
}

Stream API with map merging: Instead of flattening the original data structures, you can also create a Map for each MultiDataPoint, and then merge all maps into a single map with a reduce operation. The code is a bit simpler than the above solution:

Collection<DataSet> convert(List<MultiDataPoint> multiDataPoints) {
    return multiDataPoints.stream()
        .map(mdp -> mdp.keyToData.entrySet().stream()
            .collect(toMap(e -> e.getKey(), e -> asList(new DataPoint(mdp.timestamp, e.getValue())))))
        .reduce(new HashMap<>(), mapMerger())
        .entrySet().stream()
        .map(e -> new DataSet(e.getKey(), e.getValue()))
        .collect(toList());
}

You can find an implementation of the map merger within the Collectors class. Unfortunately, it is a bit tricky to access it from the outside. Following is an alternative implementation of the map merger:

<K, V> BinaryOperator<Map<K, List<V>>> mapMerger() {
    return (lhs, rhs) -> {
        Map<K, List<V>> result = new HashMap<>();
        lhs.forEach((key, value) -> result.computeIfAbsent(key, k -> new ArrayList<>()).addAll(value));
        rhs.forEach((key, value) -> result.computeIfAbsent(key, k -> new ArrayList<>()).addAll(value));
        return result;
    };
}

Is recursion ever faster than looping?

Most of the answers here are wrong. The right answer is it depends. For example, here are two C functions which walks through a tree. First the recursive one:

static
void mm_scan_black(mm_rc *m, ptr p) {
    SET_COL(p, COL_BLACK);
    P_FOR_EACH_CHILD(p, {
        INC_RC(p_child);
        if (GET_COL(p_child) != COL_BLACK) {
            mm_scan_black(m, p_child);
        }
    });
}

And here is the same function implemented using iteration:

static
void mm_scan_black(mm_rc *m, ptr p) {
    stack *st = m->black_stack;
    SET_COL(p, COL_BLACK);
    st_push(st, p);
    while (st->used != 0) {
        p = st_pop(st);
        P_FOR_EACH_CHILD(p, {
            INC_RC(p_child);
            if (GET_COL(p_child) != COL_BLACK) {
                SET_COL(p_child, COL_BLACK);
                st_push(st, p_child);
            }
        });
    }
}

It's not important to understand the details of the code. Just that p are nodes and that P_FOR_EACH_CHILD does the walking. In the iterative version we need an explicit stack st onto which nodes are pushed and then popped and manipulated.

The recursive function runs much faster than the iterative one. The reason is because in the latter, for each item, a CALL to the function st_push is needed and then another to st_pop.

In the former, you only have the recursive CALL for each node.

Plus, accessing variables on the callstack is incredibly fast. It means you are reading from memory which is likely to always be in the innermost cache. An explicit stack, on the other hand, has to be backed by malloc:ed memory from the heap which is much slower to access.

With careful optimization, such as inlining st_push and st_pop, I can reach roughly parity with the recursive approach. But at least on my computer, the cost of accessing heap memory is bigger than the cost of the recursive call.

But this discussion is mostly moot because recursive tree walking is incorrect. If you have a large enough tree, you will run out of callstack space which is why an iterative algorithm must be used.

Div not expanding even with content inside

You didn't typed the closingtag from the div with id="infohold.

How to make PyCharm always show line numbers

Version 2.6 and above:
PyCharm (far left menu) -> Preferences... -> Editor (bottom left section) -> General -> Appearance -> Show line numbers checkbox

enter image description here

Version 2.5 and below:
Settings -> Editor -> General -> Appearance -> Show line numbers checkbox

ASP.NET MVC ActionLink and post method

This is my solution for the problem. This is controller with 2 action methods

public class FeedbackController : Controller
{
public ActionResult Index()
{
   var feedbacks =dataFromSomeSource.getData;
   return View(feedbacks);
}

[System.Web.Mvc.HttpDelete]
[System.Web.Mvc.Authorize(Roles = "admin")]
public ActionResult Delete([FromBody]int id)
{
   return RedirectToAction("Index");
}
}

In View I render construct following structure.

<html>
..
<script src="~/Scripts/bootbox.min.js"></script>
<script>
function confirmDelete(id) {
  bootbox.confirm('@Resources.Resource.AreYouSure', function(result) {
    if (result) {
      document.getElementById('idField').value = id;
      document.getElementById('myForm').submit();
    }
  }.bind(this));
}
</script>

@using (Html.BeginForm("Delete", "Feedback", FormMethod.Post, new { id = "myForm" }))
{
  @Html.HttpMethodOverride(HttpVerbs.Delete)
  @Html.Hidden("id",null,new{id="idField"})
  foreach (var feedback in @Model)
  {
   if (User.Identity.IsAuthenticated && User.IsInRole("admin"))
   {
    @Html.ActionLink("Delete Item", "", new { id = @feedback.Id }, new { onClick = "confirmDelete("+feedback.Id+");return false;" })
   }
  }
...
</html>

Point of interest in Razor View:

  1. JavaScript function confirmDelete(id) which is called when the link generated with @Html.ActionLink is clicked;

  2. confirmDelete() function required id of item being clicked. This item is passed from onClick handler confirmDelete("+feedback.Id+");return false; Pay attention handler returns false to prevent default action - which is get request to target. OnClick event for buttons could be attached with jQuery for all buttons in the list as alternative (probably it will be even better, as it will be less text in the HTML page and data could be passed via data- attribute).

  3. Form has id=myForm, in order to find it in confirmDelete().

  4. Form includes @Html.HttpMethodOverride(HttpVerbs.Delete) in order to use the HttpDelete verb, as action marked with the HttpDeleteAttribute.

  5. In the JS function I do use action confirmation (with help of external plugin, but standard confirm works fine too. Don't forget to use bind() in call back or var that=this (whatever you prefer).

  6. Form has a hidden element with id='idField' and name='id'. So before the form is submitted after confirmation (result==true), the value of the hidden element is set to value passed argument and browser will submit data to controller like this:

Request URL:http://localhost:38874/Feedback/Delete

Request Method:POST Status Code:302 Found

Response Headers

Location:/Feedback Host:localhost:38874 Form Data X-HTTP-Method-Override:DELETE id:5

As you see it is POST request with X-HTTP-Method-Override:DELETE and data in body set to "id:5". Response has 302 code which redirect to Index action, by this you refresh your screen after delete.

MVC4 HTTP Error 403.14 - Forbidden

Before applying

runAllManagedModulesForAllRequests="true"/>

consider the link below that suggests a less drastic alternative. In the post the author offers the following alteration to the local web.config:

  <system.webServer>
    <modules>
    <remove name="UrlRoutingModule-4.0" />
    <add name="UrlRoutingModule-4.0" type="System.Web.Routing.UrlRoutingModule" preCondition="" />
    </modules>

http://www.britishdeveloper.co.uk/2010/06/dont-use-modules-runallmanagedmodulesfo.html

How to create a listbox in HTML without allowing multiple selection?

Remove the multiple="multiple" attribute and add SIZE=6 with the number of elements you want

you may want to check this site

http://www.htmlcodetutorial.com/forms/_SELECT.html

The project was not built since its build path is incomplete

Here is what made the error disappear for me:

Close eclipse, open up a terminal window and run:

$ mvn clean eclipse:clean eclipse:eclipse

Are you using Maven? If so,

  1. Right-click on the project, Build Path and go to Configure Build Path
  2. Click the libraries tab. If Maven dependencies are not in the list, you need to add it.
  3. Close the dialog.

To add it: Right-click on the project, Maven → Disable Maven Nature Right-click on the project, Configure → Convert to Maven Project.

And then clean

Edit 1:

If that doesn't resolve the issue try right-clicking on your project and select properties. Select Java Build Path → Library tab. Look for a JVM. If it's not there, click to add Library and add the default JVM. If VM is there, click edit and select the default JVM. Hopefully, that works.

Edit 2:

You can also try going into the folder where you have all your projects and delete the .metadata for eclipse (be aware that you'll have to re-import all the projects afterwards! Also all the environment settings you've set would also have to be redone). After it was deleted just import the project again, and hopefully, it works.

Recommendations of Python REST (web services) framework?

In 2010, the Pylons and repoze.bfg communities "joined forces" to create Pyramid, a web framework based most heavily on repoze.bfg. It retains the philosophies of its parent frameworks, and can be used for RESTful services. It's worth a look.

JavaScript or jQuery browser back button click detector

You can use this awesome plugin

https://github.com/ianrogren/jquery-backDetect

All you need to do is to write this code

  $(window).load(function(){
    $('body').backDetect(function(){
      // Callback function
      alert("Look forward to the future, not the past!");
    });
  });

Best

Read file data without saving it in Flask

If you want to use standard Flask stuff - there's no way to avoid saving a temporary file if the uploaded file size is > 500kb. If it's smaller than 500kb - it will use "BytesIO", which stores the file content in memory, and if it's more than 500kb - it stores the contents in TemporaryFile() (as stated in the werkzeug documentation). In both cases your script will block until the entirety of uploaded file is received.

The easiest way to work around this that I have found is:

1) Create your own file-like IO class where you do all the processing of the incoming data

2) In your script, override Request class with your own:

class MyRequest( Request ):
  def _get_file_stream( self, total_content_length, content_type, filename=None, content_length=None ):
    return MyAwesomeIO( filename, 'w' )

3) Replace Flask's request_class with your own:

app.request_class = MyRequest

4) Go have some beer :)

How do I send an HTML email?

You can find a complete and very simple java class for sending emails using Google(gmail) account here, Send email message using java application

It uses following properties

Properties props = new Properties();
  props.put("mail.smtp.auth", "true");
  props.put("mail.smtp.starttls.enable", "true");
  props.put("mail.smtp.host", "smtp.gmail.com");
  props.put("mail.smtp.port", "587");

Does Android keep the .apk files? if so where?

Preinstalled Apps are typically in /system/app and user installed apps are in /data/app.

You can use "adb pull", but you need to know the full path of the APK file. On the emulator, you can get a directory listing using "adb shell" + "ls". But on an android device, you will not be able to do that in "/data" folder due to security reasons. So how do you figure out the full path of the APK file?

You can get a full list of all apps installed by writing a program that queries the PackageManager. Short code snippet below:

PackageManager  pm = getPackageManager();
List<PackageInfo> pkginfo_list = pm.getInstalledPackages(PackageManager.GET_ACTIVITIES);
List<ApplicationInfo> appinfo_list = pm.getInstalledApplications(0);
for (int x=0; x < pkginfo_list.size(); x++){             
  PackageInfo pkginfo = pkginfo_list.get(x);
  pkg_path[x] = appinfo_list.get(x).publicSourceDir;  //store package path in array
}

You can also find apps that will give such info. There are lots of them. Try this one (AppSender).

GitHub - List commits by author

If the author has a GitHub account, just click the author's username from anywhere in the commit history, and the commits you can see will be filtered down to those by that author:

Screenshot showing where to click to filter down commits

You can also click the 'n commits' link below their name on the repo's "contributors" page:

Another screenshot

Alternatively, you can directly append ?author=<theusername> or ?author=<emailaddress> to the URL. For example, https://github.com/jquery/jquery/commits/master?author=dmethvin or https://github.com/jquery/jquery/commits/[email protected] both give me:

Screenshot with only Dave Methvin's commits

For authors without a GitHub account, only filtering by email address will work, and you will need to manually add ?author=<emailaddress> to the URL - the author's name will not be clickable from the commits list.


You can also get the list of commits by a particular author from the command line using

git log --author=[your git name]

Example:

git log --author=Prem

How to make full screen background in a web page

Make a div 100% wide and 100% high. Then set a background image.

Border Height on CSS

Building on top of @ReBa's answer above, this custom-border class is what worked for me.

Mods:

  • working with border instead of backaground-color since background-color is not consistent.
  • Setting height & top of the properties of :after in such a way that the total comes up to 100% where bottom's value is implicit.

_x000D_
_x000D_
ul {_x000D_
  list-style-type: none;_x000D_
  display: flex;_x000D_
  flex-direction: row;_x000D_
}_x000D_
_x000D_
li {_x000D_
  padding: 10px;_x000D_
}_x000D_
_x000D_
.custom-border {_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
.custom-border:after {_x000D_
  content: " ";_x000D_
  position: absolute;_x000D_
  border-left: 1px #6c757d solid;_x000D_
  top: 35%;_x000D_
  right: 0;_x000D_
  height: 30%;_x000D_
  margin-top: auto;_x000D_
  margin-bottom: auto;_x000D_
}
_x000D_
<ul>_x000D_
  <li class="custom-border">_x000D_
    Hello_x000D_
  </li>_x000D_
  <li class="custom-border">_x000D_
    World_x000D_
  </li>_x000D_
  <li class="custom-border">_x000D_
    Foo_x000D_
  </li>_x000D_
  <li class="custom-border">Bar</li>_x000D_
  <li class="custom-border">Baz</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

Good Luck...

How to add values in a variable in Unix shell scripting?

You can do this as well. Can be faster for quick calculations:

echo $[2+2]

Help needed with Median If in Excel

Expanding on Brian Camire's Answer:

Using =MEDIAN(IF($A$1:$A$6="Airline",$B$1:$B$6,"")) with CTRL+SHIFT+ENTER will include blank cells in the calculation. Blank cells will be evaluated as 0 which results in a lower median value. The same is true if using the average funtion. If you don't want to include blank cells in the calculation, use a nested if statement like so:

=MEDIAN(IF($A$1:$A$6="Airline",IF($B$1:$B$6<>"",$B$1:$B$6)))

Don't forget to press CTRL+SHIFT+ENTER to treat the formula as an "array formula".

Textfield with only bottom border

See this JSFiddle

_x000D_
_x000D_
 input[type="text"]_x000D_
    {_x000D_
        border: 0;_x000D_
        border-bottom: 1px solid red;_x000D_
        outline: 0;_x000D_
    }
_x000D_
<form>_x000D_
        <input type="text" value="See! ONLY BOTTOM BORDER!" />_x000D_
    </form>
_x000D_
_x000D_
_x000D_

How to use multiple conditions (With AND) in IIF expressions in ssrs

Here is an example that should give you some idea..

=IIF(First(Fields!Gender.Value,"vw_BrgyClearanceNew")="Female" and 
(First(Fields!CivilStatus.Value,"vw_BrgyClearanceNew")="Married"),false,true)

I think you have to identify the datasource name or the table name where your data is coming from.

How to capture and save an image using custom camera in Android?

Following Snippet will help you

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="de.vogella.cameara.api"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="15" />
    <uses-permission android:name="android.permission.CAMERA"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name="de.vogella.camera.api.MakePhotoActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <Button
        android:id="@+id/captureFront"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:onClick="onClick"
        android:text="Make Photo" />

</RelativeLayout>

PhotoHandler.java

package org.sample;

import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.content.Context;
import android.hardware.Camera;
import android.hardware.Camera.PictureCallback;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;

public class PhotoHandler implements PictureCallback {

    private final Context context;

    public PhotoHandler(Context context) {
        this.context = context;
    }

    @Override
    public void onPictureTaken(byte[] data, Camera camera) {

        File pictureFileDir = getDir();

        if (!pictureFileDir.exists() && !pictureFileDir.mkdirs()) {

            Log.d(Constants.DEBUG_TAG, "Can't create directory to save image.");
            Toast.makeText(context, "Can't create directory to save image.",
                    Toast.LENGTH_LONG).show();
            return;

        }

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyymmddhhmmss");
        String date = dateFormat.format(new Date());
        String photoFile = "Picture_" + date + ".jpg";

        String filename = pictureFileDir.getPath() + File.separator + photoFile;

        File pictureFile = new File(filename);

        try {
            FileOutputStream fos = new FileOutputStream(pictureFile);
            fos.write(data);
            fos.close();
            Toast.makeText(context, "New Image saved:" + photoFile,
                    Toast.LENGTH_LONG).show();
        } catch (Exception error) {
            Log.d(Constants.DEBUG_TAG, "File" + filename + "not saved: "
                    + error.getMessage());
            Toast.makeText(context, "Image could not be saved.",
                    Toast.LENGTH_LONG).show();
        }
    }

    private File getDir() {
        File sdDir = Environment
          .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
        return new File(sdDir, "CameraAPIDemo");
    }
}

MakePhotoActivity.java

package org.sample;

import android.app.Activity;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.hardware.Camera.CameraInfo;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import de.vogella.cameara.api.R;

public class MakePhotoActivity extends Activity {
    private final static String DEBUG_TAG = "MakePhotoActivity";
    private Camera camera;
    private int cameraId = 0;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        // do we have a camera?
        if (!getPackageManager()
                .hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
            Toast.makeText(this, "No camera on this device", Toast.LENGTH_LONG)
                    .show();
        } else {
            cameraId = findFrontFacingCamera();
            camera = Camera.open(cameraId);
            if (cameraId < 0) {
                Toast.makeText(this, "No front facing camera found.",
                        Toast.LENGTH_LONG).show();
            }
        }
    }

    public void onClick(View view) {
        camera.takePicture(null, null,
                new PhotoHandler(getApplicationContext()));
    }

    private int findFrontFacingCamera() {
        int cameraId = -1;
        // Search for the front facing camera
        int numberOfCameras = Camera.getNumberOfCameras();
        for (int i = 0; i < numberOfCameras; i++) {
            CameraInfo info = new CameraInfo();
            Camera.getCameraInfo(i, info);
            if (info.facing == CameraInfo.CAMERA_FACING_FRONT) {
                Log.d(DEBUG_TAG, "Camera found");
                cameraId = i;
                break;
            }
        }
        return cameraId;
    }

    @Override
    protected void onPause() {
        if (camera != null) {
            camera.release();
            camera = null;
        }
        super.onPause();
    }

}

Indentation shortcuts in Visual Studio

If you would like nicely auto-formatted code. Try CTRL + A + K + F. While holding down CTRL hit a, then k, then f.

The HTTP request is unauthorized with client authentication scheme 'Ntlm'

My problem was; None admin users were getting "the http request is unauthorized with client authentication scheme 'negotiate' asmx" on my asmx services.

I gived read/execute folder permissions for the none admin users and my problem was solved.

Android Spinner: Get the selected item change event

Some of the previous answers are not correct. They work for other widgets and views, but the documentation for the Spinner widget clearly states:

A spinner does not support item click events. Calling this method will raise an exception.

Better use OnItemSelectedListener() instead:

spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
    @Override
    public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
        // your code here
    }

    @Override
    public void onNothingSelected(AdapterView<?> parentView) {
        // your code here
    }

});

This works for me.

Note that onItemSelected method is also invoked when the view is being build, so you can consider putting it inside onCreate() method call.

How to find the date of a day of the week from a date using PHP?

I had to use a similar solution for Portuguese (Brazil):

<?php
$scheduled_day = '2018-07-28';
$days = ['Dom','Seg','Ter','Qua','Qui','Sex','Sáb'];
$day = date('w',strtotime($scheduled_day));
$scheduled_day = date('d-m-Y', strtotime($scheduled_day))." ($days[$day])";
// provides 28-07-2018 (Sáb)

Get startup type of Windows service using PowerShell

With PowerShell version 4:

You can run a command as given below:

   Get-Service | select -property name,starttype

Get keys from HashMap in Java

Try this simple program:

public class HashMapGetKey {

public static void main(String args[]) {

      // create hash map

       HashMap map = new HashMap();

      // populate hash map

      map.put(1, "one");
      map.put(2, "two");
      map.put(3, "three");
      map.put(4, "four");

      // get keyset value from map

Set keyset=map.keySet();

      // check key set values

      System.out.println("Key set values are: " + keyset);
   }    
}

How do I install a plugin for vim?

Update (as 2019):

cd ~/.vim
git clone git://github.com/tpope/vim-haml.git pack/bundle/start/haml

Explanation (from :h pack ad :h packages):

  1. All the directories found are added to runtimepath. They must be in ~/.vim/pack/whatever/start [you can only change whatever].
  2. the plugins found in the plugins dir in runtimepath are sourced.

So this load the plugin on start (hence the name start).

You can also get optional plugin (loaded with :packadd) if you put them in ~/.vim/pack/bundle/opt

How can I solve Exception in thread "main" java.lang.NullPointerException error

This is the problem

double a[] = null;

Since a is null, NullPointerException will arise every time you use it until you initialize it. So this:

a[i] = var;

will fail.

A possible solution would be initialize it when declaring it:

double a[] = new double[PUT_A_LENGTH_HERE]; //seems like this constant should be 7

IMO more important than solving this exception, is the fact that you should learn to read the stacktrace and understand what it says, so you could detect the problems and solve it.

java.lang.NullPointerException

This exception means there's a variable with null value being used. How to solve? Just make sure the variable is not null before being used.

at twoten.TwoTenB.(TwoTenB.java:29)

This line has two parts:

  • First, shows the class and method where the error was thrown. In this case, it was at <init> method in class TwoTenB declared in package twoten. When you encounter an error message with SomeClassName.<init>, means the error was thrown while creating a new instance of the class e.g. executing the constructor (in this case that seems to be the problem).
  • Secondly, shows the file and line number location where the error is thrown, which is between parenthesis. This way is easier to spot where the error arose. So you have to look into file TwoTenB.java, line number 29. This seems to be a[i] = var;.

From this line, other lines will be similar to tell you where the error arose. So when reading this:

at javapractice.JavaPractice.main(JavaPractice.java:32)

It means that you were trying to instantiate a TwoTenB object reference inside the main method of your class JavaPractice declared in javapractice package.

How to save a new sheet in an existing excel file, using Pandas?

I would strongly recommend you work directly with openpyxl since it now supports Pandas DataFrames.

This allows you to concentrate on the relevant Excel and Pandas code.

How to Count Duplicates in List with LINQ

Slightly shorter version using methods chain:

var list = new List<string> {"a", "b", "a", "c", "a", "b"};
var q = list.GroupBy(x => x)
            .Select(g => new {Value = g.Key, Count = g.Count()})
            .OrderByDescending(x=>x.Count);

foreach (var x in q)
{
    Console.WriteLine("Value: " + x.Value + " Count: " + x.Count);
}

MongoDB or CouchDB - fit for production?

We are currently using mongodb as an file storage service for our collaboration over LAN. Also, projects like trello are using mongodb as their backend datastore. I have used couchdb earlier, but not in production capacity.

How can I trigger another job from a jenkins pipeline (jenkinsfile) with GitHub Org Plugin?

The command build in pipeline is there to trigger other jobs in jenkins.

Example on github

The job must exist in Jenkins and can be parametrized. As for the branch, I guess you can read it from git

How to count duplicate rows in pandas dataframe?

If you like to count duplicates on particular column(s):

len(df['one'])-len(df['one'].drop_duplicates())

If you want to count duplicates on entire dataframe:

len(df)-len(df.drop_duplicates())

Or simply you can use DataFrame.duplicated(subset=None, keep='first'):

df.duplicated(subset='one', keep='first').sum()

where

subset : column label or sequence of labels(by default use all of the columns)

keep : {‘first’, ‘last’, False}, default ‘first’

  • first : Mark duplicates as True except for the first occurrence.
  • last : Mark duplicates as True except for the last occurrence.
  • False : Mark all duplicates as True.

handling dbnull data in vb.net

I think this should be much easier to use:

select ISNULL(sum(field),0) from tablename

Copied from: http://www.codeproject.com/Questions/736515/How-do-I-avoide-Conversion-from-type-DBNull-to-typ

List of tuples to dictionary

With dict comprehension:

h = {k:v for k,v in l}

Which programming language for cloud computing?

Depends on which "cloud" you would want to use. If it is Google App Engine, you can use Java or Python. Groovy too is supported on Google App Engine which runs on jvm. If you are going with Amazon, you can pretty much install any OS (Amazon Machine Images) you would like with any application server and use any language depending on the application servers support for the language. But doing something like that would mean a lot of technical understanding of scalability concepts. Some of the services might be provided off the shelf like DB services, storage etc. I heard about ruby and Heroku (another cloud application platform). But dont have experience with it.

Personally I prefer Java/Groovy for such things because of the vast libraries and tools available.

Database Structure for Tree Data Structure

Have a look at Managing Hierarchical Data in MySQL. It discusses two approaches for storing and managing hierarchical (tree-like) data in a relational database.

The first approach is the adjacency list model, which is what you essentially describe: having a foreign key that refers to the table itself. While this approach is simple, it can be very inefficient for certain queries, like building the whole tree.

The second approach discussed in the article is the nested set model. This approach is far more efficient and flexible. Refer to the article for detailed explanation and example queries.

Tar error: Unexpected EOF in archive

May be you have ftped the file in ascii mode instead of binary mode ? If not, this might help.

$ gunzip myarchive.tar.gz

And then untar the resulting tar file using

$ tar xvf myarchive.tar

Hope this helps.

C multi-line macro: do/while(0) vs scope block

Andrey Tarasevich provides the following explanation:

  1. On Google Groups
  2. On bytes.com

[Minor changes to formatting made. Parenthetical annotations added in square brackets []].

The whole idea of using 'do/while' version is to make a macro which will expand into a regular statement, not into a compound statement. This is done in order to make the use of function-style macros uniform with the use of ordinary functions in all contexts.

Consider the following code sketch:

if (<condition>)
  foo(a);
else
  bar(a);

where foo and bar are ordinary functions. Now imagine that you'd like to replace function foo with a macro of the above nature [named CALL_FUNCS]:

if (<condition>)
  CALL_FUNCS(a);
else
  bar(a);

Now, if your macro is defined in accordance with the second approach (just { and }) the code will no longer compile, because the 'true' branch of if is now represented by a compound statement. And when you put a ; after this compound statement, you finished the whole if statement, thus orphaning the else branch (hence the compilation error).

One way to correct this problem is to remember not to put ; after macro "invocations":

if (<condition>)
  CALL_FUNCS(a)
else
  bar(a);

This will compile and work as expected, but this is not uniform. The more elegant solution is to make sure that macro expand into a regular statement, not into a compound one. One way to achieve that is to define the macro as follows:

#define CALL_FUNCS(x) \
do { \
  func1(x); \
  func2(x); \
  func3(x); \
} while (0)

Now this code:

if (<condition>)
  CALL_FUNCS(a);
else
  bar(a);

will compile without any problems.

However, note the small but important difference between my definition of CALL_FUNCS and the first version in your message. I didn't put a ; after } while (0). Putting a ; at the end of that definition would immediately defeat the entire point of using 'do/while' and make that macro pretty much equivalent to the compound-statement version.

I don't know why the author of the code you quoted in your original message put this ; after while (0). In this form both variants are equivalent. The whole idea behind using 'do/while' version is not to include this final ; into the macro (for the reasons that I explained above).

How to insert a picture into Excel at a specified cell position with VBA

If it's simply about inserting and resizing a picture, try the code below.

For the specific question you asked, the property TopLeftCell returns the range object related to the cell where the top left corner is parked. To place a new image at a specific place, I recommend creating an image at the "right" place and registering its top and left properties values of the dummy onto double variables.

Insert your Pic assigned to a variable to easily change its name. The Shape Object will have that same name as the Picture Object.

Sub Insert_Pic_From_File(PicPath as string, wsDestination as worksheet)
    Dim Pic As Picture, Shp as Shape
    Set Pic = wsDestination.Pictures.Insert(FilePath)
    Pic.Name = "myPicture"
    'Strongly recommend using a FileSystemObject.FileExists method to check if the path is good before executing the previous command
    Set Shp = wsDestination.Shapes("myPicture")
    With Shp
        .Height = 100
        .Width = 75
        .LockAspectRatio = msoTrue  'Put this later so that changing height doesn't change width and vice-versa)
        .Placement = 1
        .Top = 100
        .Left = 100
    End with
End Sub

Good luck!