Programs & Examples On #Voicexml

VoiceXML is designed for creating audio dialogs that feature synthesized speech, digitized audio, recognition of spoken and DTMF key input, recording of spoken input, telephony, and mixed initiative conversations.

Get width height of remote image from url

Get image size with jQuery

function getMeta(url){
    $("<img/>",{
        load : function(){
            alert(this.width+' '+this.height);
        },
        src  : url
    });
}

Get image size with JavaScript

function getMeta(url){   
    var img = new Image();
    img.onload = function(){
        alert( this.width+' '+ this.height );
    };
    img.src = url;
}

Get image size with JavaScript (modern browsers, IE9+ )

function getMeta(url){   
    var img = new Image();
    img.addEventListener("load", function(){
        alert( this.naturalWidth +' '+ this.naturalHeight );
    });
    img.src = url;
}

Use the above simply as: getMeta( "http://example.com/img.jpg" );

https://developer.mozilla.org/en/docs/Web/API/HTMLImageElement

SQL DELETE with INNER JOIN

Add .* to s in your first line.

Try:

DELETE s.* FROM spawnlist s
INNER JOIN npc n ON s.npc_templateid = n.idTemplate
WHERE (n.type = "monster");

SSL certificate rejected trying to access GitHub over HTTPS behind firewall

To clone on windows while setting SSL verify to false:

    git -c http.sslVerify=false clone http://example.com/e.git

If you want to clone without borfing your global settings.

java.lang.NoSuchMethodError: javax.servlet.ServletContext.getContextPath()Ljava/lang/String;

java.lang.NoSuchMethodError: javax.servlet.ServletContext.getContextPath()Ljava/lang/String;

That method was added in Servlet 2.5.

So this problem can have at least 3 causes:

  1. The servlet container does not support Servlet 2.5.
  2. The web.xml is not declared conform Servlet 2.5 or newer.
  3. The webapp's runtime classpath is littered with servlet container specific JAR files of a different servlet container make/version which does not support Servlet 2.5.

To solve it,

  1. Make sure that your servlet container supports at least Servlet 2.5. That are at least Tomcat 6, Glassfish 2, JBoss AS 4.1, etcetera. Tomcat 5.5 for example supports at highest Servlet 2.4. If you can't upgrade Tomcat, then you'd need to downgrade Spring to a Servlet 2.4 compatible version.
  2. Make sure that the root declaration of web.xml complies Servlet 2.5 (or newer, at least the highest whatever your target runtime supports). For an example, see also somewhere halfway our servlets wiki page.
  3. Make sure that you don't have any servlet container specific libraries like servlet-api.jar or j2ee.jar in /WEB-INF/lib or even worse, the JRE/lib or JRE/lib/ext. They do not belong there. This is a pretty common beginner's mistake in an attempt to circumvent compilation errors in an IDE, see also How do I import the javax.servlet API in my Eclipse project?.

What is the difference between a static and a non-static initialization code block

The static block is a "static initializer".

It's automatically invoked when the class is loaded, and there's no other way to invoke it (not even via Reflection).

I've personally only ever used it when writing JNI code:

class JNIGlue {
    static {
        System.loadLibrary("foo");
    }
}

Changing CSS Values with Javascript

I don't have rep enough to comment so I'll format an answer, yet it is only a demonstration of the issue in question.

It seems, when element styles are defined in stylesheets they are not visible to getElementById("someElement").style

This code illustrates the issue... Code from below on jsFiddle.

In Test 2, on the first call, the items left value is undefined, and so, what should be a simple toggle gets messed up. For my use I will define my important style values inline, but it does seem to partially defeat the purpose of the stylesheet.

Here's the page code...

<html>
  <head>
    <style type="text/css">
      #test2a{
        position: absolute;
        left: 0px;
        width: 50px;
        height: 50px;
        background-color: green;
        border: 4px solid black;
      }
      #test2b{
        position: absolute;
        left: 55px;
        width: 50px;
        height: 50px;
        background-color: yellow;
        margin: 4px;
      }
    </style>
  </head>
  <body>

  <!-- test1 -->
    Swap left positions function with styles defined inline.
    <a href="javascript:test1();">Test 1</a><br>
    <div class="container">
      <div id="test1a" style="position: absolute;left: 0px;width: 50px; height: 50px;background-color: green;border: 4px solid black;"></div>
      <div id="test1b" style="position: absolute;left: 55px;width: 50px; height: 50px;background-color: yellow;margin: 4px;"></div>
    </div>
    <script type="text/javascript">
     function test1(){
       var a = document.getElementById("test1a");
       var b = document.getElementById("test1b");
       alert(a.style.left + " - " + b.style.left);
       a.style.left = (a.style.left == "0px")? "55px" : "0px";
       b.style.left = (b.style.left == "0px")? "55px" : "0px";
     }
    </script>
  <!-- end test 1 -->

  <!-- test2 -->
    <div id="moveDownThePage" style="position: relative;top: 70px;">
    Identical function with styles defined in stylesheet.
    <a href="javascript:test2();">Test 2</a><br>
    <div class="container">
      <div id="test2a"></div>
      <div id="test2b"></div>
    </div>
    </div>
    <script type="text/javascript">
     function test2(){
       var a = document.getElementById("test2a");
       var b = document.getElementById("test2b");
       alert(a.style.left + " - " + b.style.left);
       a.style.left = (a.style.left == "0px")? "55px" : "0px";
       b.style.left = (b.style.left == "0px")? "55px" : "0px";
     }
    </script>
  <!-- end test 2 -->

  </body>
</html>

I hope this helps to illuminate the issue.

Skip

What does .pack() do?

The pack() method is defined in Window class in Java and it sizes the frame so that all its contents are at or above their preferred sizes.

How to implement HorizontalScrollView like Gallery?

Here is a good tutorial with code. Let me know if it works for you! This is also a good tutorial.

EDIT

In This example, all you need to do is add this line:

gallery.setSelection(1);

after setting the adapter to gallery object, that is this line:

gallery.setAdapter(new ImageAdapter(this));

UPDATE1

Alright, I got your problem. This open source library is your solution. I also have used it for one of my projects. Hope this will solve your problem finally.

UPDATE2:

I would suggest you to go through this tutorial. You might get idea. I think I got your problem, you want the horizontal scrollview with snap. Try to search with that keyword on google or out here, you might get your solution.

HTML -- two tables side by side

You can place your tables in a div and add style to your table "float: left"

<div>
  <table style="float: left">
    <tr>
      <td>..</td>
    </tr>
  </table>
  <table style="float: left">
    <tr>
      <td>..</td>
    </tr>
  </table>
</div>

or simply use css:

div>table {
  float: left
}

Initialize array of strings

This example program illustrates initialization of an array of C strings.

#include <stdio.h>

const char * array[] = {
    "First entry",
    "Second entry",
    "Third entry",
};

#define n_array (sizeof (array) / sizeof (const char *))

int main ()
{
    int i;

    for (i = 0; i < n_array; i++) {
        printf ("%d: %s\n", i, array[i]);
    }
    return 0;
}

It prints out the following:

0: First entry
1: Second entry
2: Third entry

pull access denied repository does not exist or may require docker login

I had the same issue when working with docker-composer. In my case it was an Amazon AWS ECR private registry. It seems to be a bug in docker-compose

https://github.com/docker/compose/issues/1622#issuecomment-162988389

After adding the full path "myrepo/myimage" to docker compose yaml

image: xxxxxxxxx.dkr.ecr.us-east-1.amazonaws.com/myrepo:myimage

it was all fine.

Fastest way to flatten / un-flatten nested JSON objects

You can try out the package jpflat.

It flattens, inflates, resolves promises, flattens arrays, has customizable path creation and customizable value serialization.

The reducers and serializers receive the whole path as an array of it's parts, so more complex operations can be done to the path instead of modifying a single key or changing the delimiter.

Json path is the default, hence "jp"flat.

https://www.npmjs.com/package/jpflat

let flatFoo = await require('jpflat').flatten(foo)

"Adaptive Server is unavailable or does not exist" error connecting to SQL Server from PHP

Bud, disable selinux or add the following to your RedHat/CentOS Server:

setsebool -P httpd_can_network_connect_db 1
setsebool -P httpd_can_network_connect 1

Best always!

How to get MAC address of client using PHP?

To get client's device ip and mac address

{
    if (isset($_SERVER['HTTP_CLIENT_IP']))
        $ipaddress = $_SERVER['HTTP_CLIENT_IP'];
    else if(isset($_SERVER['HTTP_X_FORWARDED_FOR']))
        $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
    else if(isset($_SERVER['HTTP_X_FORWARDED']))
        $ipaddress = $_SERVER['HTTP_X_FORWARDED'];
    else if(isset($_SERVER['HTTP_FORWARDED_FOR']))
        $ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
    else if(isset($_SERVER['HTTP_FORWARDED']))
        $ipaddress = $_SERVER['HTTP_FORWARDED'];
    else if(isset($_SERVER['REMOTE_ADDR']))
        $ipaddress = $_SERVER['REMOTE_ADDR'];
    else
        $ipaddress = 'UNKNOWN';

    $macCommandString   =   "arp " . $ipaddress . " | awk 'BEGIN{ i=1; } { i++; if(i==3) print $3 }'";

    $mac = exec($macCommandString);

    return ['ip' => $ipaddress, 'mac' => $mac];
}

Build a basic Python iterator

Include the following code in your class code.

 def __iter__(self):
        for x in self.iterable:
            yield x

Make sure that you replace self.iterablewith the iterable which you iterate through.

Here's an example code

class someClass:
    def __init__(self,list):
        self.list = list
    def __iter__(self):
        for x in self.list:
            yield x


var = someClass([1,2,3,4,5])
for num in var: 
    print(num) 

Output

1
2
3
4
5

Note: Since strings are also iterable, they can also be used as an argument for the class

foo = someClass("Python")
for x in foo:
    print(x)

Output

P
y
t
h
o
n

how to check for datatype in node js- specifically for integer

I just made some tests in node.js v4.2.4 (but this is true in any javascript implementation):

> typeof NaN
'number'
> isNaN(NaN)
true
> isNaN("hello")
true

the surprise is the first one as type of NaN is "number", but that is how it is defined in javascript.

So the next test brings up unexpected result

> typeof Number("hello")
"number"

because Number("hello") is NaN

The following function makes results as expected:

function isNumeric(n){
  return (typeof n == "number" && !isNaN(n));
}

Bootstrap 3 Carousel fading to new slide instead of sliding to new slide

This can be accomplished using only CSS. To change the carousel to a fade transition instead of slide, use one of the following snippets (LESS or standard CSS).

LESS

// Fade transition for carousel items
.carousel {
  .item {
    left: 0 !important;
    .transition(opacity .4s); //adjust timing here
  }
  .carousel-control {
    background-image: none; // remove background gradients on controls
  }
  // Fade controls with items
  .next.left,
  .prev.right {
    opacity: 1;
    z-index: 1;
  }
  .active.left,
  .active.right {
    opacity: 0;
    z-index: 2;
  }
}

Plain CSS:

/* Fade transition for carousel items */
.carousel .item {
    left: 0 !important;
      -webkit-transition: opacity .4s; /*adjust timing here */
         -moz-transition: opacity .4s;
           -o-transition: opacity .4s;
              transition: opacity .4s;
}
.carousel-control {
    background-image: none !important; /* remove background gradients on controls */
}
/* Fade controls with items */
.next.left,
.prev.right {
    opacity: 1;
    z-index: 1;
}
.active.left,
.active.right {
    opacity: 0;
    z-index: 2;
}

In C++, what is a virtual base class?

I'd like to add to OJ's kind clarifications.

Virtual inheritance doesn't come without a price. Like with all things virtual, you get a performance hit. There is a way around this performance hit that is possibly less elegant.

Instead of breaking the diamond by deriving virtually, you can add another layer to the diamond, to get something like this:

   B
  / \
D11 D12
 |   |
D21 D22
 \   /
  DD

None of the classes inherit virtually, all inherit publicly. Classes D21 and D22 will then hide virtual function f() which is ambiguous for DD, perhaps by declaring the function private. They'd each define a wrapper function, f1() and f2() respectively, each calling class-local (private) f(), thus resolving conflicts. Class DD calls f1() if it wants D11::f() and f2() if it wants D12::f(). If you define the wrappers inline you'll probably get about zero overhead.

Of course, if you can change D11 and D12 then you can do the same trick inside these classes, but often that is not the case.

Write a file in UTF-8 using FileWriter (Java)?

In my opinion

If you wanna write follow kind UTF-8.You should create a byte array.Then,you can do such as the following: byte[] by=("<?xml version=\"1.0\" encoding=\"utf-8\"?>"+"Your string".getBytes();

Then, you can write each byte into file you created. Example:

OutputStream f=new FileOutputStream(xmlfile);
    byte[] by=("<?xml version=\"1.0\" encoding=\"utf-8\"?>"+"Your string".getBytes();
    for (int i=0;i<by.length;i++){
    byte b=by[i];
    f.write(b);

    }
    f.close();

How do I update/upsert a document in Mongoose?

app.put('url', function(req, res) {

        // use our bear model to find the bear we want
        Bear.findById(req.params.bear_id, function(err, bear) {

            if (err)
                res.send(err);

            bear.name = req.body.name;  // update the bears info

            // save the bear
            bear.save(function(err) {
                if (err)
                    res.send(err);

                res.json({ message: 'Bear updated!' });
            });

        });
    });

Here is a better approach to solving the update method in mongoose, you can check Scotch.io for more details. This definitely worked for me!!!

JTable How to refresh table model after insert delete or update the data.

The faster way for your case is:

    jTable.repaint(); // Repaint all the component (all Cells).

The optimized way when one or few cell change:

    ((AbstractTableModel) jTable.getModel()).fireTableCellUpdated(x, 0); // Repaint one cell.

How can I get a count of the total number of digits in a number?

Try This:

myint.ToString().Length

Does that work ?

How to resize Image in Android?

BitmapFactory.Options options=new BitmapFactory.Options();
            options.inSampleSize = 10;
            FixBitmap = BitmapFactory.decodeFile(ImagePath, options);
            //FixBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.gv);

           byteArrayOutputStream = new ByteArrayOutputStream();
           FixBitmap.compress(Bitmap.CompressFormat.JPEG, 80, byteArrayOutputStream); //compress to 50% of original image quality
           byteArray = byteArrayOutputStream.toByteArray();

           ConvertImage = Base64.encodeToString(byteArray, Base64.DEFAULT);

How to delete an SMS from the inbox in Android programmatically?

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
    SMSData sms = (SMSData) getListAdapter().getItem(position);
    Toast.makeText(getApplicationContext(), sms.getBody(),
            Toast.LENGTH_LONG).show();
    Toast.makeText(getApplicationContext(), sms.getNumber(),
            Toast.LENGTH_LONG).show();

    deleteSms(sms.getId());

}

public boolean deleteSms(String smsId) {
    boolean isSmsDeleted = false;
    try {
        MainActivity.this.getContentResolver().delete(
                Uri.parse("content://sms/" + smsId), null, null);
        isSmsDeleted = true;

    } catch (Exception ex) {
        isSmsDeleted = false;
    }
    return isSmsDeleted;
}

How to select a single column with Entity Framework?

Using LINQ your query should look something like this:

public User GetUser(int userID){

return
(
 from p in "MyTable" //(Your Entity Model)
 where p.UserID == userID
 select p.Name
).SingleOrDefault();

}

Of course to do this you need to have an ADO.Net Entity Model in your solution.

How to check whether a Button is clicked by using JavaScript

Just hook up the onclick event:

<input id="button" type="submit" name="button" value="enter" onclick="myFunction();"/>

Specifying maxlength for multiline textbox

Use HTML textarea with runat="server" to access it in server side. This solution has less pain than using javascript or regex.

<textarea runat="server" id="txt1" maxlength="100" />

Note: To access Text Property in server side, you should use txt1.Value instead of txt1.Text

What is the Java ?: operator called and what does it do?

This construct is called Ternary Operator in Computer Science and Programing techniques.
And Wikipedia suggest the following explanation:

In computer science, a ternary operator (sometimes incorrectly called a tertiary operator) is an operator that takes three arguments. The arguments and result can be of different types. Many programming languages that use C-like syntax feature a ternary operator, ?: , which defines a conditional expression.

Not only in Java, this syntax is available within PHP, Objective-C too.

In the following link it gives the following explanation, which is quiet good to understand it:

A ternary operator is some operation operating on 3 inputs. It's a shortcut for an if-else statement, and is also known as a conditional operator.

In Perl/PHP it works as:
boolean_condition ? true_value : false_value

In C/C++ it works as:
logical expression ? action for true : action for false

This might be readable for some logical conditions which are not too complex otherwise it is better to use If-Else block with intended combination of conditional logic.

We can simplify the If-Else blocks with this Ternary operator for one code statement line.
For Example:

if ( car.isStarted() ) {
     car.goForward();
} else {
     car.startTheEngine();
}

Might be equal to the following:

( car.isStarted() ) ? car.goForward() : car.startTheEngine();

So if we refer to your statement:

int count = isHere ? getHereCount(index) : getAwayCount(index);

It is actually the 100% equivalent of the following If-Else block:

int count;
if (isHere) {
    count = getHereCount(index);
} else {
    count = getAwayCount(index);
}

That's it!
Hope this was helpful to somebody!
Cheers!

CXF: No message body writer found for class - automatically mapping non-simple resources

You can try with mentioning "Accept: application/json" in your rest client header as well, if you are expecting your object as JSON in response.

regex to remove all text before a character

Variant of Tim's one, good only on some implementations of Regex: ^.*?_

var subjectString = "3.04_somename.jpg";
var resultString = Regex.Replace(subjectString,
    @"^   # Match start of string
    .*?   # Lazily match any character, trying to stop when the next condition becomes true
    _     # Match the underscore", "", RegexOptions.IgnorePatternWhitespace);

How do I escape ampersands in batch files?

& is used to separate commands. Therefore you can use ^ to escape the &.

Check whether a table contains rows or not sql server 2005

Also, you can use exists

select case when exists (select 1 from table) 
          then 'contains rows' 
          else 'doesnt contain rows' 
       end

or to check if there are child rows for a particular record :

select * from Table t1
where exists(
select 1 from ChildTable t2
where t1.id = t2.parentid)

or in a procedure

if exists(select 1 from table)
begin
 -- do stuff
end

org.hibernate.PersistentObjectException: detached entity passed to persist

Two solutions 1. use merge if you want to update the object 2. use save if you want to just save new object (make sure identity is null to let hibernate or database generate it) 3. if you are using mapping like
@OneToOne(fetch = FetchType.EAGER,cascade=CascadeType.ALL) @JoinColumn(name = "stock_id")

Then use CascadeType.ALL to CascadeType.MERGE

thanks Shahid Abbasi

Using Gulp to Concatenate and Uglify files

It turns out that I needed to use gulp-rename and also output the concatenated file first before 'uglification'. Here's the code:

var gulp = require('gulp'),
    gp_concat = require('gulp-concat'),
    gp_rename = require('gulp-rename'),
    gp_uglify = require('gulp-uglify');

gulp.task('js-fef', function(){
    return gulp.src(['file1.js', 'file2.js', 'file3.js'])
        .pipe(gp_concat('concat.js'))
        .pipe(gulp.dest('dist'))
        .pipe(gp_rename('uglify.js'))
        .pipe(gp_uglify())
        .pipe(gulp.dest('dist'));
});

gulp.task('default', ['js-fef'], function(){});

Coming from grunt it was a little confusing at first but it makes sense now. I hope it helps the gulp noobs.

And, if you need sourcemaps, here's the updated code:

var gulp = require('gulp'),
    gp_concat = require('gulp-concat'),
    gp_rename = require('gulp-rename'),
    gp_uglify = require('gulp-uglify'),
    gp_sourcemaps = require('gulp-sourcemaps');

gulp.task('js-fef', function(){
    return gulp.src(['file1.js', 'file2.js', 'file3.js'])
        .pipe(gp_sourcemaps.init())
        .pipe(gp_concat('concat.js'))
        .pipe(gulp.dest('dist'))
        .pipe(gp_rename('uglify.js'))
        .pipe(gp_uglify())
        .pipe(gp_sourcemaps.write('./'))
        .pipe(gulp.dest('dist'));
});

gulp.task('default', ['js-fef'], function(){});

See gulp-sourcemaps for more on options and configuration.

How to Use -confirm in PowerShell

For when you want a 1-liner

while( -not ( ($choice= (Read-Host "May I continue?")) -match "y|n")){ "Y or N ?"}

How to use OKHTTP to make a post request?

   protected Void doInBackground(String... movieIds) {
                for (; count <= 1; count++) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

                Resources res = getResources();
                String web_link = res.getString(R.string.website);

                OkHttpClient client = new OkHttpClient();

                RequestBody formBody = new FormBody.Builder()
                        .add("name", name)
                        .add("bsname", bsname)
                        .add("email", email)
                        .add("phone", phone)
                        .add("whatsapp", wapp)
                        .add("location", location)
                        .add("country", country)
                        .add("state", state)
                        .add("city", city)
                        .add("zip", zip)
                        .add("fb", fb)
                        .add("tw", tw)
                        .add("in", in)
                        .add("age", age)
                        .add("gender", gender)
                        .add("image", encodeimg)
                        .add("uid", user_id)
                        .build();
                Request request = new Request.Builder()
                        .url(web_link+"edit_profile.php")
                        .post(formBody)
                        .build();

                try {
                    Response response = client.newCall(request).execute();

                    JSONArray array = new JSONArray(response.body().string());
                    JSONObject object = array.getJSONObject(0);

                    hashMap.put("msg",object.getString("msgtype"));
                    hashMap.put("msg",object.getString("msg"));
                    // Do something with the response.
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    e.printStackTrace();
                }



                return null;
            }

SQL Logic Operator Precedence: And and Or

And has precedence over Or, so, even if a <=> a1 Or a2

Where a And b 

is not the same as

Where a1 Or a2 And b,

because that would be Executed as

Where a1 Or (a2 And b)

and what you want, to make them the same, is the following (using parentheses to override rules of precedence):

 Where (a1 Or a2) And b

Here's an example to illustrate:

Declare @x tinyInt = 1
Declare @y tinyInt = 0
Declare @z tinyInt = 0

Select Case When @x=1 OR @y=1 And @z=1 Then 'T' Else 'F' End -- outputs T
Select Case When (@x=1 OR @y=1) And @z=1 Then 'T' Else 'F' End -- outputs F

For those who like to consult references (in alphabetic order):

Python's time.clock() vs. time.time() accuracy?

Short answer: use time.clock() for timing in Python.

On *nix systems, clock() returns the processor time as a floating point number, expressed in seconds. On Windows, it returns the seconds elapsed since the first call to this function, as a floating point number.

time() returns the the seconds since the epoch, in UTC, as a floating point number. There is no guarantee that you will get a better precision that 1 second (even though time() returns a floating point number). Also note that if the system clock has been set back between two calls to this function, the second function call will return a lower value.

Spring Boot java.lang.NoClassDefFoundError: javax/servlet/Filter

The configuration here is working for me:

configurations {
    customProvidedRuntime
}

dependencies {
    compile(
        // Spring Boot dependencies
    )

    customProvidedRuntime('org.springframework.boot:spring-boot-starter-tomcat')
}

war {
    classpath = files(configurations.runtime.minus(configurations.customProvidedRuntime))
}

springBoot {
    providedConfiguration = "customProvidedRuntime"
}

Import/Index a JSON file into Elasticsearch

I just made sure that I am in the same directory as the json file and then simply ran this

curl -s -H "Content-Type: application/json" -XPOST localhost:9200/product/default/_bulk?pretty --data-binary @product.json

So if you too make sure you are at the same directory and run it this way. Note: product/default/ in the command is something specific to my environment. you can omit it or replace it with whatever is relevant to you.

Store a cmdlet's result value in a variable in Powershell

Use the -ExpandProperty flag of Select-Object

$var=Get-WSManInstance -enumerate wmicimv2/win32_process | select -expand Priority

Update to answer the other question:

Note that you can as well just access the property:

$var=(Get-WSManInstance -enumerate wmicimv2/win32_process).Priority

So to get multiple of these into variables:

$var=Get-WSManInstance -enumerate wmicimv2/win32_process
   $prio = $var.Priority
   $pid = $var.ProcessID

How to remove the first Item from a list?

>>> x = [0, 1, 2, 3, 4]
>>> x.pop(0)
0

More on this here.

JFrame.dispose() vs System.exit()

  • If you have multiple windows open and only want to close the one that was closed use JFrame.dispose().

  • If you want to close all windows and terminate the application use System.exit()

Execution sequence of Group By, Having and Where clause in SQL Server?

In Oracle 12c, you can run code both in either sequence below:

Where
Group By
Having

Or

Where 
Having
Group by

Create a HTML table where each TR is a FORM

I had a problem similar to the one posed in the original question. I was intrigued by the divs styled as table elements (didn't know you could do that!) and gave it a run. However, my solution was to keep my tables wrapped in tags, but rename each input and select option to become the keys of array, which I'm now parsing to get each element in the selected row.

Here's a single row from the table. Note that key [4] is the rendered ID of the row in the database from which this table row was retrieved:

<table>
  <tr>
    <td>DisabilityCategory</td>
    <td><input type="text" name="FormElem[4][ElemLabel]" value="Disabilities"></td>
    <td><select name="FormElem[4][Category]">
        <option value="1">General</option>
        <option value="3">Disability</option>
        <option value="4">Injury</option>
        <option value="2"selected>School</option>
        <option value="5">Veteran</option>
        <option value="10">Medical</option>
        <option value="9">Supports</option>
        <option value="7">Residential</option>
        <option value="8">Guardian</option>
        <option value="6">Criminal</option>
        <option value="11">Contacts</option>
      </select></td>
    <td>4</td>
    <td style="text-align:center;"><input type="text" name="FormElem[4][ElemSeq]" value="0" style="width:2.5em; text-align:center;"></td>
    <td>'ccpPartic'</td>
    <td><input type="text" name="FormElem[4][ElemType]" value="checkbox"></td>
    <td><input type="checkbox" name="FormElem[4][ElemRequired]"></td>
    <td><input type="text" name="FormElem[4][ElemLabelPrefix]" value=""></td>
    <td><input type="text" name="FormElem[4][ElemLabelPostfix]" value=""></td>
    <td><input type="text" name="FormElem[4][ElemLabelPosition]" value="before"></td>
    <td><input type="submit" name="submit[4]" value="Commit Changes"></td>
  </tr>
</table>

Then, in PHP, I'm using the following method to store in an array ($SelectedElem) each of the elements in the row corresponding to the submit button. I'm using print_r() just to illustrate:

$SelectedElem = implode(",", array_keys($_POST['submit']));
print_r ($_POST['FormElem'][$SelectedElem]);

Perhaps this sounds convoluted, but it turned out to be quite simple, and it preserved the organizational structure of the table.

How does the @property decorator work in Python?

This point is been cleared by many people up there but here is a direct point which I was searching. This is what I feel is important to start with the @property decorator. eg:-

class UtilityMixin():
    @property
    def get_config(self):
        return "This is property"

The calling of function "get_config()" will work like this.

util = UtilityMixin()
print(util.get_config)

If you notice I have not used "()" brackets for calling the function. This is the basic thing which I was searching for the @property decorator. So that you can use your function just like a variable.

what's the correct way to send a file from REST web service to client?

Since youre using JSON, I would Base64 Encode it before sending it across the wire.

If the files are large, try to look at BSON, or some other format that is better with binary transfers.

You could also zip the files, if they compress well, before base64 encoding them.

Get input type="file" value when it has multiple files selected

The files selected are stored in an array: [input].files

For example, you can access the items

// assuming there is a file input with the ID `my-input`...
var files = document.getElementById("my-input").files;

for (var i = 0; i < files.length; i++)
{
 alert(files[i].name);
}

For jQuery-comfortable people, it's similarly easy

// assuming there is a file input with the ID `my-input`...
var files = $("#my-input")[0].files;

for (var i = 0; i < files.length; i++)
{
 alert(files[i].name);
}

How do I format axis number format to thousands with a comma in matplotlib?

You can use matplotlib.ticker.funcformatter

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as tkr


def func(x, pos):  # formatter function takes tick label and tick position
    s = '%d' % x
    groups = []
    while s and s[-1].isdigit():
        groups.append(s[-3:])
        s = s[:-3]
    return s + ','.join(reversed(groups))

y_format = tkr.FuncFormatter(func)  # make formatter

x = np.linspace(0,10,501)
y = 1000000*np.sin(x)
ax = plt.subplot(111)
ax.plot(x,y)
ax.yaxis.set_major_formatter(y_format)  # set formatter to needed axis

plt.show()

enter image description here

Error Code: 1062. Duplicate entry '1' for key 'PRIMARY'

I just encountered the same issue but here it seemed to come from the fact that I declared the ID-column to be UNsigned and that in combination with an ID-value of '0' (zero) caused the import to fail...

So by changing the value of every ID (PK-column) that I'd declared '0' and every corresponding FK to the new value, my issue was solved.

jQuery getJSON save result into variable

You can't get value when calling getJSON, only after response.

var myjson;
$.getJSON("http://127.0.0.1:8080/horizon-update", function(json){
    myjson = json;
});

Reset the Value of a Select Box

What worked for me was:

$('select option').each(function(){$(this).removeAttr('selected');});   

Create or update mapping in elasticsearch

Please note that there is a mistake in the url provided in this answer:

For a PUT mapping request: the url should be as follows:

http://localhost:9200/name_of_index/_mappings/document_type

and NOT

http://localhost:9200/name_of_index/document_type/_mappings

Entity Framework 6 GUID as primary key: Cannot insert the value NULL into column 'Id', table 'FileStore'; column does not allow nulls

If you do Code-First and already have a Database:

public override void Up()
{
    AlterColumn("dbo.MyTable","Id", c =>  c.Guid(nullable: false, identity: true, defaultValueSql: "newsequentialid()"));
}

SmtpException: Unable to read data from the transport connection: net_io_connectionclosed

In my case, the customer forgot to add new IP address in their SMTP settings. Open IIS 6.0 in the server which sets up the smtp, right click Smtp virtual server, choose Properties, Access tab, click Connections, add IP address of the new server. Then click Relay, also add IP address of the new server. This solved my issue.

How can I plot a confusion matrix?

enter image description here

you can use plt.matshow() instead of plt.imshow() or you can use seaborn module's heatmap (see documentation) to plot the confusion matrix

import seaborn as sn
import pandas as pd
import matplotlib.pyplot as plt
array = [[33,2,0,0,0,0,0,0,0,1,3], 
        [3,31,0,0,0,0,0,0,0,0,0], 
        [0,4,41,0,0,0,0,0,0,0,1], 
        [0,1,0,30,0,6,0,0,0,0,1], 
        [0,0,0,0,38,10,0,0,0,0,0], 
        [0,0,0,3,1,39,0,0,0,0,4], 
        [0,2,2,0,4,1,31,0,0,0,2],
        [0,1,0,0,0,0,0,36,0,2,0], 
        [0,0,0,0,0,0,1,5,37,5,1], 
        [3,0,0,0,0,0,0,0,0,39,0], 
        [0,0,0,0,0,0,0,0,0,0,38]]
df_cm = pd.DataFrame(array, index = [i for i in "ABCDEFGHIJK"],
                  columns = [i for i in "ABCDEFGHIJK"])
plt.figure(figsize = (10,7))
sn.heatmap(df_cm, annot=True)

Is it possible to run JavaFX applications on iOS, Android or Windows Phone 8?

Possible. You can get commercial sport also.

JavaFXPorts is the name of the open source project maintained by Gluon that develops the code necessary for Java and JavaFX to run well on mobile and embedded hardware. The goal of this project is to contribute as much back to the OpenJFX project wherever possible, and when not possible, to maintain the minimal number of changes necessary to enable the goals of JavaFXPorts. Gluon takes the JavaFXPorts source code and compiles it into binaries ready for deployment onto iOS, Android, and embedded hardware. The JavaFXPorts builds are freely available on this website for all developers.

http://gluonhq.com/labs/javafxports/

"Javac" doesn't work correctly on Windows 10

I had the same issue on Windows 10 - the java -version command was working but javac -version was not. There are three things I did:

(1) I downloaded the latest jdk (not the jre) and installed it. Then, I added the jdk/bin path tan o environment variable. In my case, it was C:\Program Files\Java\jdk-10\bin. I did not need to add the ; for Windows 10.

(2) Move this path to the top of all the other paths.

(3) Delete any other Java paths that might exist.

Test the java -version and javac -version commands again. Voila!

what is the use of $this->uri->segment(3) in codeigniter pagination

In your code $this->uri->segment(3) refers to the pagination offset which you use in your query. According to your $config['base_url'] = base_url().'index.php/papplicant/viewdeletedrecords/' ;, $this->uri->segment(3) i.e segment 3 refers to the offset. The first segment is the controller, second is the method, there after comes the parameters sent to the controllers as segments.

What is the regex for "Any positive integer, excluding 0"

Try this one, this one works best to suffice the requiremnt.

[1-9][0-9]*

Here is the sample output

String 0 matches regex: false
String 1 matches regex: true
String 2 matches regex: true
String 3 matches regex: true
String 4 matches regex: true
String 5 matches regex: true
String 6 matches regex: true
String 7 matches regex: true
String 8 matches regex: true
String 9 matches regex: true
String 10 matches regex: true
String 11 matches regex: true
String 12 matches regex: true
String 13 matches regex: true
String 14 matches regex: true
String 15 matches regex: true
String 16 matches regex: true
String 999 matches regex: true
String 2654 matches regex: true
String 25633 matches regex: true
String 254444 matches regex: true
String 0.1 matches regex: false
String 0.2 matches regex: false
String 0.3 matches regex: false
String -1 matches regex: false
String -2 matches regex: false
String -5 matches regex: false
String -6 matches regex: false
String -6.8 matches regex: false
String -9 matches regex: false
String -54 matches regex: false
String -29 matches regex: false
String 1000 matches regex: true
String 100000 matches regex: true

find difference between two text files with one item per line

an awk answer:

awk 'NR == FNR {file1[$0]++; next} !($0 in file1)' file1 file2

Save and load weights in keras

Here is a YouTube video that explains exactly what you're wanting to do: Save and load a Keras model

There are three different saving methods that Keras makes available. These are described in the video link above (with examples), as well as below.

First, the reason you're receiving the error is because you're calling load_model incorrectly.

To save and load the weights of the model, you would first use

model.save_weights('my_model_weights.h5')

to save the weights, as you've displayed. To load the weights, you would first need to build your model, and then call load_weights on the model, as in

model.load_weights('my_model_weights.h5')

Another saving technique is model.save(filepath). This save function saves:

  • The architecture of the model, allowing to re-create the model.
  • The weights of the model.
  • The training configuration (loss, optimizer).
  • The state of the optimizer, allowing to resume training exactly where you left off.

To load this saved model, you would use the following:

from keras.models import load_model
new_model = load_model(filepath)'

Lastly, model.to_json(), saves only the architecture of the model. To load the architecture, you would use

from keras.models import model_from_json
model = model_from_json(json_string)

How to use JavaScript regex over multiple lines?

[\\w\\s]*

This one was beyond helpful for me, especially for matching multiple things that include new lines, every single other answer ended up just grouping all of the matches together.

Storing files in SQL Server

There's a really good paper by Microsoft Research called To Blob or Not To Blob.

Their conclusion after a large number of performance tests and analysis is this:

  • if your pictures or document are typically below 256K in size, storing them in a database VARBINARY column is more efficient

  • if your pictures or document are typically over 1 MB in size, storing them in the filesystem is more efficient (and with SQL Server 2008's FILESTREAM attribute, they're still under transactional control and part of the database)

  • in between those two, it's a bit of a toss-up depending on your use

If you decide to put your pictures into a SQL Server table, I would strongly recommend using a separate table for storing those pictures - do not store the employee photo in the employee table - keep them in a separate table. That way, the Employee table can stay lean and mean and very efficient, assuming you don't always need to select the employee photo, too, as part of your queries.

For filegroups, check out Files and Filegroup Architecture for an intro. Basically, you would either create your database with a separate filegroup for large data structures right from the beginning, or add an additional filegroup later. Let's call it "LARGE_DATA".

Now, whenever you have a new table to create which needs to store VARCHAR(MAX) or VARBINARY(MAX) columns, you can specify this file group for the large data:

 CREATE TABLE dbo.YourTable
     (....... define the fields here ......)
     ON Data                   -- the basic "Data" filegroup for the regular data
     TEXTIMAGE_ON LARGE_DATA   -- the filegroup for large chunks of data

Check out the MSDN intro on filegroups, and play around with it!

git ignore all files of a certain type, except those in a specific subfolder

An optional prefix ! which negates the pattern; any matching file excluded by a previous pattern will become included again. If a negated pattern matches, this will override lower precedence patterns sources.

http://schacon.github.com/git/gitignore.html

*.json
!spec/*.json

error C2220: warning treated as error - no 'object' file generated

This error message is very confusing. I just fixed the other 'warnings' in my project and I really had only one (simple one):

warning C4101: 'i': unreferenced local variable

After I commented this unused i, and compiled it, the other error went away.

Laravel Fluent Query Builder Join with subquery

I can't comment because my reputation is not high enough. @Franklin Rivero if you are using Laravel 5.2 you can set the bindings on the main query instead of the join using the setBindings method.

So the main query in @ph4r05's answer would look something like this:

$q = DnsResult::query()
    ->from($dnsTable . ' AS s')
    ->join(
        DB::raw('(' . $qqSql. ') AS ss'),
        function(JoinClause $join) {
            $join->on('s.watch_id', '=', 'ss.watch_id')
                 ->on('s.last_scan_at', '=', 'ss.last_scan');
        })
    ->setBindings($subq->getBindings());

Associating existing Eclipse project with existing SVN repository

Team->Share project is exactly what you need to do. Select SVN from the list, then click "Next". Subclipse will notice the presence of .svn directories that will ask you to confirm that the information is correct, and associate the project with subclipse.

Rounding SQL DateTime to midnight

This might look cheap but it's working for me

SELECT CONVERT(DATETIME,LEFT(CONVERT(VARCHAR,@dateFieldOrVariable,101),10)+' 00:00:00.000')

Resetting MySQL Root Password with XAMPP on Localhost

You want to edit this file: "\xampp\phpMyAdmin\config.inc.php"

change this line:

$cfg['Servers'][$i]['password'] = 'WhateverPassword';

to whatever your password is. If you don't remember your password, then run this command within the Shell:

mysqladmin.exe -u root password WhateverPassword

where WhateverPassword is your new password.

How to use hex() without 0x in Python?

You can simply write

hex(x)[2:]

to get the first two characters removed.

Parse JSON object with string and value only

You need to get a list of all the keys, loop over them and add them to your map as shown in the example below:

    String s = "{menu:{\"1\":\"sql\", \"2\":\"android\", \"3\":\"mvc\"}}";
    JSONObject jObject  = new JSONObject(s);
    JSONObject  menu = jObject.getJSONObject("menu");

    Map<String,String> map = new HashMap<String,String>();
    Iterator iter = menu.keys();
    while(iter.hasNext()){
        String key = (String)iter.next();
        String value = menu.getString(key);
        map.put(key,value);
    }

Developing C# on Linux

MonoDevelop, the IDE associated with Mono Project should be enough for C# development on Linux. Now I don't know any good profilers and other tools for C# development on Linux. But then again mind you, that C# is a language more native to windows. You are better developing C# apps for windows than for linux.

EDIT: When you download MonoDevelop from the Ubuntu Software Center, it will contain pretty much everything you need to get started right away (Compiler, Runtime Environment, IDE). If you would like more information, see the following links:

Print specific part of webpage

Just use CSS to hide the content you do not want printed. When the user selects print - the page will look to the " media="print" CSS for instructions about the layout of the page.

The media="print" CSS has instructions to hide the content that we do not want printed.

<!-- CSS for the things we want to print (print view) -->
<style type="text/css" media="print">

#SCREEN_VIEW_CONTAINER{
        display: none;
    }
.other_print_layout{
        background-color:#FFF;
    }
</style>

<!-- CSS for the things we DO NOT want to print (web view) -->
<style type="text/css" media="screen">

   #PRINT_VIEW{
      display: none;
   }
.other_web_layout{
        background-color:#E0E0E0;
    }
</style>

<div id="SCREEN_VIEW_CONTAINER">
     the stuff I DO NOT want printed is here and will be hidden - 
     and not printed when the user selects print.
</div>

<div id="PRINT_VIEW">
     the stuff I DO want printed is here.
</div>

How to detect idle time in JavaScript elegantly?

Based on the inputs provided by @equiman

class _Scheduler {
    timeoutIDs;

    constructor() {
        this.timeoutIDs = new Map();
    }

    addCallback = (callback, timeLapseMS, autoRemove) => {
        if (!this.timeoutIDs.has(timeLapseMS + callback)) {
            let timeoutID = setTimeout(callback, timeLapseMS);
            this.timeoutIDs.set(timeLapseMS + callback, timeoutID);
        }

        if (autoRemove !== false) {
            setTimeout(
                this.removeIdleTimeCallback, // Remove
                10000 + timeLapseMS, // 10 secs after
                callback, // the callback
                timeLapseMS, // is invoked.
            );
        }
    };

    removeCallback = (callback, timeLapseMS) => {
        let timeoutID = this.timeoutIDs.get(timeLapseMS + callback);
        if (timeoutID) {
            clearTimeout(timeoutID);
            this.timeoutIDs.delete(timeLapseMS + callback);
        }
    };
}

class _IdleTimeScheduler extends _Scheduler {
    events = [
        'load',
        'mousedown',
        'mousemove',
        'keydown',
        'keyup',
        'input',
        'scroll',
        'touchstart',
        'touchend',
        'touchcancel',
        'touchmove',
    ];
    callbacks;

    constructor() {
        super();
        this.events.forEach(name => {
            document.addEventListener(name, this.resetTimer, true);
        });

        this.callbacks = new Map();
    }

    addIdleTimeCallback = (callback, timeLapseMS) => {
        this.addCallback(callback, timeLapseMS, false);

        let callbacksArr = this.callbacks.get(timeLapseMS);
        if (!callbacksArr) {
            this.callbacks.set(timeLapseMS, [callback]);
        } else {
            if (!callbacksArr.includes(callback)) {
                callbacksArr.push(callback);
            }
        }
    };

    removeIdleTimeCallback = (callback, timeLapseMS) => {
        this.removeCallback(callback, timeLapseMS);

        let callbacksArr = this.callbacks.get(timeLapseMS);
        if (callbacksArr) {
            let index = callbacksArr.indexOf(callback);
            if (index !== -1) {
                callbacksArr.splice(index, 1);
            }
        }
    };

    resetTimer = () => {
        for (let [timeLapseMS, callbacksArr] of this.callbacks) {
            callbacksArr.forEach(callback => {
                // Clear the previous IDs
                let timeoutID = this.timeoutIDs.get(timeLapseMS + callback);
                clearTimeout(timeoutID);

                // Create new timeout IDs.
                timeoutID = setTimeout(callback, timeLapseMS);
                this.timeoutIDs.set(timeLapseMS + callback, timeoutID);
            });
        }
    };
}
export const Scheduler = new _Scheduler();
export const IdleTimeScheduler = new _IdleTimeScheduler();

All shards failed

If you encounter this apparent index corruption in a running system, you can work around it by deleting all files called segments.gen. It is advisory only, and Lucene can recover correctly without it.

From ElasticSearch Blog

Script for rebuilding and reindexing the fragmented index?

Here is the modified script which i took from http://www.foliotek.com/devblog/sql-server-optimization-with-index-rebuilding which i found useful to post here. Although it uses a cursor and i know what is the main problem with cursors it can be easily converted to a cursor-less version.

It is well-documented and you can easily read through it and modify to your needs.

  IF OBJECT_ID('tempdb..#work_to_do') IS NOT NULL 
        DROP TABLE tempdb..#work_to_do

BEGIN TRY
--BEGIN TRAN

use yourdbname

-- Ensure a USE  statement has been executed first.

    SET NOCOUNT ON;

    DECLARE @objectid INT;
    DECLARE @indexid INT;
    DECLARE @partitioncount BIGINT;
    DECLARE @schemaname NVARCHAR(130);
    DECLARE @objectname NVARCHAR(130);
    DECLARE @indexname NVARCHAR(130);
    DECLARE @partitionnum BIGINT;
    DECLARE @partitions BIGINT;
    DECLARE @frag FLOAT;
    DECLARE @pagecount INT;
    DECLARE @command NVARCHAR(4000);

    DECLARE @page_count_minimum SMALLINT
    SET @page_count_minimum = 50

    DECLARE @fragmentation_minimum FLOAT
    SET @fragmentation_minimum = 30.0

-- Conditionally select tables and indexes from the sys.dm_db_index_physical_stats function
-- and convert object and index IDs to names.

    SELECT  object_id AS objectid ,
            index_id AS indexid ,
            partition_number AS partitionnum ,
            avg_fragmentation_in_percent AS frag ,
            page_count AS page_count
    INTO    #work_to_do
    FROM    sys.dm_db_index_physical_stats(DB_ID(), NULL, NULL, NULL,
                                           'LIMITED')
    WHERE   avg_fragmentation_in_percent > @fragmentation_minimum
            AND index_id > 0
            AND page_count > @page_count_minimum;

IF CURSOR_STATUS('global', 'partitions') >= -1
BEGIN
 PRINT 'partitions CURSOR DELETED' ;
    CLOSE partitions
    DEALLOCATE partitions
END
-- Declare the cursor for the list of partitions to be processed.
    DECLARE partitions CURSOR LOCAL
    FOR
        SELECT  *
        FROM    #work_to_do;

-- Open the cursor.
    OPEN partitions;

-- Loop through the partitions.
    WHILE ( 1 = 1 )
        BEGIN;
            FETCH NEXT
FROM partitions
INTO @objectid, @indexid, @partitionnum, @frag, @pagecount;

            IF @@FETCH_STATUS < 0
                BREAK;

            SELECT  @objectname = QUOTENAME(o.name) ,
                    @schemaname = QUOTENAME(s.name)
            FROM    sys.objects AS o
                    JOIN sys.schemas AS s ON s.schema_id = o.schema_id
            WHERE   o.object_id = @objectid;

            SELECT  @indexname = QUOTENAME(name)
            FROM    sys.indexes
            WHERE   object_id = @objectid
                    AND index_id = @indexid;

            SELECT  @partitioncount = COUNT(*)
            FROM    sys.partitions
            WHERE   object_id = @objectid
                    AND index_id = @indexid;

            SET @command = N'ALTER INDEX ' + @indexname + N' ON '
                + @schemaname + N'.' + @objectname + N' REBUILD';

            IF @partitioncount > 1
                SET @command = @command + N' PARTITION='
                    + CAST(@partitionnum AS NVARCHAR(10));

            EXEC (@command);
            --print (@command); //uncomment for testing

            PRINT N'Rebuilding index ' + @indexname + ' on table '
                + @objectname;
            PRINT N'  Fragmentation: ' + CAST(@frag AS VARCHAR(15));
            PRINT N'  Page Count:    ' + CAST(@pagecount AS VARCHAR(15));
            PRINT N' ';
        END;

-- Close and deallocate the cursor.
    CLOSE partitions;
    DEALLOCATE partitions;

-- Drop the temporary table.
    DROP TABLE #work_to_do;
--COMMIT TRAN

END TRY
BEGIN CATCH
--ROLLBACK TRAN
    PRINT 'ERROR ENCOUNTERED:' + ERROR_MESSAGE()
END CATCH

HTML page disable copy/paste

You cannot prevent people from copying text from your page. If you are trying to satisfy a "requirement" this may work for you:

<body oncopy="return false" oncut="return false" onpaste="return false">

How to disable Ctrl C/V using javascript for both internet explorer and firefox browsers

A more advanced aproach:

How to detect Ctrl+V, Ctrl+C using JavaScript?

Edit: I just want to emphasise that disabling copy/paste is annoying, won't prevent copying and is 99% likely a bad idea.

How to print a string in C++

You need #include<string> to use string AND #include<iostream> to use cin and cout. (I didn't get it when I read the answers). Here's some code which works:

#include<string>
#include<iostream>
using namespace std;

int main()
{
    string name;
    cin >> name;
    string message("hi");
    cout << name << message;
    return 0;
}

How can I use querySelector on to pick an input element by name?

So ... you need to change some things in your code

<form method="POST" id="form-pass">
Password: <input type="text" name="pwd" id="input-pwd">
<input type="submit" value="Submit">
</form>

<script>
var form = document.querySelector('#form-pass');
var pwd = document.querySelector('#input-pwd');
pwd.focus();
form.onsubmit = checkForm;

function checkForm() {
  alert(pwd.value);
}
</script>

Try this way.

Intellij Cannot resolve symbol on import

you can try invalidating the cache and restarting intellij, in many cases it will help.

File -> Invalidate Caches/Restart

Sorting HTML table with JavaScript

Nick Grealy's accepted answer is great but acts a bit quirky if your rows are inside a <tbody> tag (the first row isn't ever sorted and after sorting rows end up outside of the tbody tag, possibly losing formatting).

This is a simple fix, however:

Just change:

document.querySelectorAll('th').forEach(th => th.addEventListener('click', (() => {
  const table = th.closest('table');
  Array.from(table.querySelectorAll('tr:nth-child(n+2)'))
    .sort(comparer(Array.from(th.parentNode.children).indexOf(th), this.asc = !this.asc))
    .forEach(tr => table.appendChild(tr) );

to:

document.querySelectorAll('th').forEach(th => th.addEventListener('click', (() => {
  const table = th.closest('table');
  const tbody = table.querySelector('tbody');
  Array.from(tbody.querySelectorAll('tr'))
    .sort(comparer(Array.from(th.parentNode.children).indexOf(th), this.asc = !this.asc))
    .forEach(tr => tbody.appendChild(tr) );

Oracle: SQL query to find all the triggers belonging to the tables?

Use the Oracle documentation and search for keyword "trigger" in your browser.

This approach should work with other metadata type questions.

Finding non-numeric rows in dataframe in pandas?

You could use np.isreal to check the type of each element (applymap applies a function to each element in the DataFrame):

In [11]: df.applymap(np.isreal)
Out[11]:
          a     b
item
a      True  True
b      True  True
c      True  True
d     False  True
e      True  True

If all in the row are True then they are all numeric:

In [12]: df.applymap(np.isreal).all(1)
Out[12]:
item
a        True
b        True
c        True
d       False
e        True
dtype: bool

So to get the subDataFrame of rouges, (Note: the negation, ~, of the above finds the ones which have at least one rogue non-numeric):

In [13]: df[~df.applymap(np.isreal).all(1)]
Out[13]:
        a    b
item
d     bad  0.4

You could also find the location of the first offender you could use argmin:

In [14]: np.argmin(df.applymap(np.isreal).all(1))
Out[14]: 'd'

As @CTZhu points out, it may be slightly faster to check whether it's an instance of either int or float (there is some additional overhead with np.isreal):

df.applymap(lambda x: isinstance(x, (int, float)))

Error: Generic Array Creation

You can't create arrays with a generic component type.

Create an array of an explicit type, like Object[], instead. You can then cast this to PCB[] if you want, but I don't recommend it in most cases.

PCB[] res = (PCB[]) new Object[list.size()]; /* Not type-safe. */

If you want type safety, use a collection like java.util.List<PCB> instead of an array.

By the way, if list is already a java.util.List, you should use one of its toArray() methods, instead of duplicating them in your code. This doesn't get your around the type-safety problem though.

Calculating powers of integers

I managed to modify(boundaries, even check, negative nums check) Qx__ answer. Use at your own risk. 0^-1, 0^-2 etc.. returns 0.

private static int pow(int x, int n) {
        if (n == 0)
            return 1;
        if (n == 1)
            return x;
        if (n < 0) { // always 1^xx = 1 && 2^-1 (=0.5 --> ~ 1 )
            if (x == 1 || (x == 2 && n == -1))
                return 1;
            else
                return 0;
        }
        if ((n & 1) == 0) { //is even 
            long num = pow(x * x, n / 2);
            if (num > Integer.MAX_VALUE) //check bounds
                return Integer.MAX_VALUE; 
            return (int) num;
        } else {
            long num = x * pow(x * x, n / 2);
            if (num > Integer.MAX_VALUE) //check bounds
                return Integer.MAX_VALUE;
            return (int) num;
        }
    }

How to export datagridview to excel using vb.net?

In design mode: Set DataGridView1 ClipboardCopyMode properties to EnableAlwaysIncludeHeaderText

or on the program code

DataGridView1.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableAlwaysIncludeHeaderText

In the run time select all cells content (Ctrl+A) and copy (Ctrl+C) and paste to the Excel Program. Let the Excel do the rest

Sorry for the inconvenient, I have been searching the method to print data directly from the datagridvew (create report from vb.net VB2012) and have not found the satisfaction result. Above code just my though, wondering if my applications user can rely on above simple step it will be nice and I could go ahead to next step on my program progress.

Reset IntelliJ UI to Default

check, if this works for you.

File -> Settings -> (type appe in search box) and select Appearance -> Select Intellij from dropdown option of Theme on the right (under UI Options).

Hope this helps someone.

What's the difference between ClusterIP, NodePort and LoadBalancer service types in Kubernetes?

ClusterIP: Services are reachable by pods/services in the Cluster
If I make a service called myservice in the default namespace of type: ClusterIP then the following predictable static DNS address for the service will be created:

myservice.default.svc.cluster.local (or just myservice.default, or by pods in the default namespace just "myservice" will work)

And that DNS name can only be resolved by pods and services inside the cluster.

NodePort: Services are reachable by clients on the same LAN/clients who can ping the K8s Host Nodes (and pods/services in the cluster) (Note for security your k8s host nodes should be on a private subnet, thus clients on the internet won't be able to reach this service)
If I make a service called mynodeportservice in the mynamespace namespace of type: NodePort on a 3 Node Kubernetes Cluster. Then a Service of type: ClusterIP will be created and it'll be reachable by clients inside the cluster at the following predictable static DNS address:

mynodeportservice.mynamespace.svc.cluster.local (or just mynodeportservice.mynamespace)

For each port that mynodeportservice listens on a nodeport in the range of 30000 - 32767 will be randomly chosen. So that External clients that are outside the cluster can hit that ClusterIP service that exists inside the cluster. Lets say that our 3 K8s host nodes have IPs 10.10.10.1, 10.10.10.2, 10.10.10.3, the Kubernetes service is listening on port 80, and the Nodeport picked at random was 31852.

A client that exists outside of the cluster could visit 10.10.10.1:31852, 10.10.10.2:31852, or 10.10.10.3:31852 (as NodePort is listened for by every Kubernetes Host Node) Kubeproxy will forward the request to mynodeportservice's port 80.

LoadBalancer: Services are reachable by everyone connected to the internet* (Common architecture is L4 LB is publicly accessible on the internet by putting it in a DMZ or giving it both a private and public IP and k8s host nodes are on a private subnet)
(Note: This is the only service type that doesn't work in 100% of Kubernetes implementations, like bare metal Kubernetes, it works when Kubernetes has cloud provider integrations.)

If you make mylbservice, then a L4 LB VM will be spawned (a cluster IP service, and a NodePort Service will be implicitly spawned as well). This time our NodePort is 30222. the idea is that the L4 LB will have a public IP of 1.2.3.4 and it will load balance and forward traffic to the 3 K8s host nodes that have private IP addresses. (10.10.10.1:30222, 10.10.10.2:30222, 10.10.10.3:30222) and then Kube Proxy will forward it to the service of type ClusterIP that exists inside the cluster.


You also asked: Does the NodePort service type still use the ClusterIP? Yes*
Or is the NodeIP actually the IP found when you run kubectl get nodes? Also Yes*

Lets draw a parrallel between Fundamentals:
A container is inside a pod. a pod is inside a replicaset. a replicaset is inside a deployment.
Well similarly:
A ClusterIP Service is part of a NodePort Service. A NodePort Service is Part of a Load Balancer Service.


In that diagram you showed, the Client would be a pod inside the cluster.

How to convert base64 string to image?

You can try using open-cv to save the file since it helps with image type conversions internally. The sample code:

import cv2
import numpy as np

def save(encoded_data, filename):
    nparr = np.fromstring(encoded_data.decode('base64'), np.uint8)
    img = cv2.imdecode(nparr, cv2.IMREAD_ANYCOLOR)
    return cv2.imwrite(filename, img)

Then somewhere in your code you can use it like this:

save(base_64_string, 'testfile.png');
save(base_64_string, 'testfile.jpg');
save(base_64_string, 'testfile.bmp');

Could not load type from assembly error

Adding your DLL to GAC(global assembly cache)

Visual Studio Command Prompt => Run as Adminstrator

gacutil /i "dll file path"

You can see added assembly C:\Windows\system32\

It Will also solve dll missing or "Could not load file or assembly" in SSIS Script task

Deleting objects from an ArrayList in Java

I have found an alternative faster solution:

  int j = 0;
  for (Iterator i = list.listIterator(); i.hasNext(); ) {
    j++;

    if (campo.getNome().equals(key)) {
       i.remove();
       i = list.listIterator(j);
    }
  }

Display / print all rows of a tibble (tbl_df)

You could also use

print(tbl_df(df), n=40)

or with the help of the pipe operator

df %>% tbl_df %>% print(n=40)

To print all rows specify tbl_df %>% print(n = Inf)

Eclipse - Failed to create the java virtual machine

You can also try closing other programs. :)

It's pretty simple, but worked for me. In my case the VM just don't had enough memory to run, and i got the same message. So i had to clean up the ram, by closing unnecessary programs.

jQuery - how to write 'if not equal to' (opposite of ==)

== => !=

=== => !==

Equal and its opposite

Where are SQL Server connection attempts logged?

If you'd like to track only failed logins, you can use the SQL Server Audit feature (available in SQL Server 2008 and above). You will need to add the SQL server instance you want to audit, and check the failed login operation to audit.

Note: tracking failed logins via SQL Server Audit has its disadvantages. For example - it doesn't provide the names of client applications used.

If you want to audit a client application name along with each failed login, you can use an Extended Events session.

To get you started, I recommend reading this article: http://www.sqlshack.com/using-extended-events-review-sql-server-failed-logins/

Calling JMX MBean method from a shell script

The Syabru Nagios JMX plugin is meant to be used from Nagios, but doesn't require Nagios and is very convenient for command-line use:

~$ ./check_jmx -U service:jmx:rmi:///jndi/rmi://localhost:1099/JMXConnector --username myuser --password mypass -O java.lang:type=Memory -A HeapMemoryUsage -K used 
JMX OK - HeapMemoryUsage.used = 445012360 | 'HeapMemoryUsage used'=445012360;;;;

Python - List of unique dictionaries

Heres an implementation with little memory overhead at the cost of not being as compact as the rest.

values = [ {'id':2,'name':'hanna', 'age':30},
           {'id':1,'name':'john', 'age':34},
           {'id':1,'name':'john', 'age':34},
           {'id':2,'name':'hanna', 'age':30},
           {'id':1,'name':'john', 'age':34},]
count = {}
index = 0
while index < len(values):
    if values[index]['id'] in count:
        del values[index]
    else:
        count[values[index]['id']] = 1
        index += 1

output:

[{'age': 30, 'id': 2, 'name': 'hanna'}, {'age': 34, 'id': 1, 'name': 'john'}]

Python constructor and default value

Let's illustrate what's happening here:

Python 3.1.2 (r312:79147, Sep 27 2010, 09:45:41) 
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> class Foo:
...     def __init__(self, x=[]):
...         x.append(1)
... 
>>> Foo.__init__.__defaults__
([],)
>>> f = Foo()
>>> Foo.__init__.__defaults__
([1],)
>>> f2 = Foo()
>>> Foo.__init__.__defaults__
([1, 1],)

You can see that the default arguments are stored in a tuple which is an attribute of the function in question. This actually has nothing to do with the class in question and goes for any function. In python 2, the attribute will be func.func_defaults.

As other posters have pointed out, you probably want to use None as a sentinel value and give each instance it's own list.

How to concatenate a std::string and an int?

It seems to me that the simplest answer is to use the sprintf function:

sprintf(outString,"%s%d",name,age);

Calculating how many minutes there are between two times

You just need to query the TotalMinutes property like this varTime.TotalMinutes

Netbeans - Error: Could not find or load main class

You can solve it in these steps

  1. Right-click on the project in the left toolbar.
  2. Click on properties.
  3. Click on Run
  4. Click the browse button on the right side.(select your main class)
  5. Click ok

Using gdb to single-step assembly code outside specified executable causes error "cannot find bounds of current function"

You can use stepi or nexti (which can be abbreviated to si or ni) to step through your machine code.

jQuery: how to get which button was clicked upon form submission?

I write this function that helps me

var PupulateFormData= function (elem) {
var arr = {};
$(elem).find("input[name],select[name],button[name]:focus,input[type='submit']:focus").each(function () {
    arr[$(this).attr("name")] = $(this).val();
});
return arr;
};

and then Use

var data= PupulateFormData($("form"));

Formula px to dp, dp to px android

Just call getResources().getDimensionPixelSize(R.dimen.your_dimension) to convert from dp units to pixels

How to enable assembly bind failure logging (Fusion) in .NET

In my case helped type disk name in lower case

Wrong - C:\someFolder

Correct - c:\someFolder

SQL Server SELECT INTO @variable?

"SELECT *
  INTO 
    @TempCustomer 
FROM 
    Customer
WHERE 
    CustomerId = @CustomerId"

Which means creating a new @tempCustomer tablevariable and inserting data FROM Customer. You had already declared it above so no need of again declaring. Better to go with

INSERT INTO @tempCustomer SELECT * FROM Customer

How to show progress dialog in Android?

ProgressDialog dialog = 
   ProgressDialog.show(yourActivity.this, "", "Please Wait...");

Making an iframe responsive

iframes cannot be responsive. You can make the iframe container responsive but not the content it is displaying since it is a webpage that has its own set height and width.

The example fiddle link works because it's displaying an embedded youtube video link that does not have a size declared.

convert a list of objects from one type to another using lambda expression

If you know you want to convert from List<T1> to List<T2> then List<T>.ConvertAll will be slightly more efficient than Select/ToList because it knows the exact size to start with:

target = orig.ConvertAll(x => new TargetType { SomeValue = x.SomeValue });

In the more general case when you only know about the source as an IEnumerable<T>, using Select/ToList is the way to go. You could also argue that in a world with LINQ, it's more idiomatic to start with... but it's worth at least being aware of the ConvertAll option.

Laravel - Route::resource vs Route::controller

For route controller method we have to define only one route. In get or post method we have to define the route separately.

And the resources method is used to creates multiple routes to handle a variety of Restful actions.

Here the Laravel documentation about this.

How do I get specific properties with Get-AdUser

using select-object for example:

Get-ADUser -Filter * -SearchBase 'OU=Users & Computers, DC=aaaaaaa, DC=com' -Properties DisplayName | select -expand displayname | Export-CSV "ADUsers.csv" 

How to combine multiple inline style objects?

If you're using React Native, you can use the array notation:

<View style={[styles.base, styles.background]} />

Check out my detailed blog post about this.

Validate that a string is a positive integer

ES6:

Number.isInteger(Number(theNumberString)) > 0

What causes a SIGSEGV

Here is an example of SIGSEGV.

root@pierr-desktop:/opt/playGround# cat test.c
int main()
{
     int * p ;
     * p = 0x1234;
     return 0 ;
}
root@pierr-desktop:/opt/playGround# g++ -o test test.c  
root@pierr-desktop:/opt/playGround# ./test 
Segmentation fault

And here is the detail.

How to handle it?

  1. Avoid it as much as possible in the first place.

    Program defensively: use assert(), check for NULL pointer , check for buffer overflow.

    Use static analysis tools to examine your code.

    compile your code with -Werror -Wall.

    Has somebody review your code.

  2. When that actually happened.

    Examine you code carefully.

    Check what you have changed since the last time you code run successfully without crash.

    Hopefully, gdb will give you a call stack so that you know where the crash happened.


EDIT : sorry for a rush. It should be *p = 0x1234; instead of p = 0x1234;

How do I get SUM function in MySQL to return '0' if no values are found?

Use COALESCE to avoid that outcome.

SELECT COALESCE(SUM(column),0)
FROM   table
WHERE  ...

To see it in action, please see this sql fiddle: http://www.sqlfiddle.com/#!2/d1542/3/0


More Information:

Given three tables (one with all numbers, one with all nulls, and one with a mixture):

SQL Fiddle

MySQL 5.5.32 Schema Setup:

CREATE TABLE foo
(
  id    INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
  val   INT
);

INSERT INTO foo (val) VALUES
(null),(1),(null),(2),(null),(3),(null),(4),(null),(5),(null),(6),(null);

CREATE TABLE bar
(
  id    INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
  val   INT
);

INSERT INTO bar (val) VALUES
(1),(2),(3),(4),(5),(6);

CREATE TABLE baz
(
  id    INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
  val   INT
);

INSERT INTO baz (val) VALUES
(null),(null),(null),(null),(null),(null);

Query 1:

SELECT  'foo'                   as table_name,
        'mixed null/non-null'   as description,
        21                      as expected_sum,
        COALESCE(SUM(val), 0)   as actual_sum
FROM    foo
UNION ALL

SELECT  'bar'                   as table_name,
        'all non-null'          as description,
        21                      as expected_sum,
        COALESCE(SUM(val), 0)   as actual_sum
FROM    bar
UNION ALL

SELECT  'baz'                   as table_name,
        'all null'              as description,
        0                       as expected_sum,
        COALESCE(SUM(val), 0)   as actual_sum
FROM    baz

Results:

| TABLE_NAME |         DESCRIPTION | EXPECTED_SUM | ACTUAL_SUM |
|------------|---------------------|--------------|------------|
|        foo | mixed null/non-null |           21 |         21 |
|        bar |        all non-null |           21 |         21 |
|        baz |            all null |            0 |          0 |

How to click on hidden element in Selenium WebDriver?

I did it with jQuery:

page.execute_script %Q{ $('#some_id').prop('checked', true) }

app.config for a class library

You generally should not add an app.config file to a class library project; it won't be used without some painful bending and twisting on your part. It doesn't hurt the library project at all - it just won't do anything at all.

Instead, you configure the application which is using your library; so the configuration information required would go there. Each application that might use your library likely will have different requirements, so this actually makes logical sense, too.

INNER JOIN in UPDATE sql for DB2

Try this and then tell me the results:

UPDATE File1 AS B                          
SET    b.campo1 = (SELECT DISTINCT A.campo1
                   FROM  File2 A           
                   INNER JOIN File1      
                   ON A.campo2 = File1.campo2 
                   AND A.campo2 = B.campo2) 

How to list containers in Docker

Use docker container ls to list all running containers.

Use the flag -a to show all containers (not just running). i.e. docker container ls -a

Use the flag -q to show containers and their numeric IDs. i.e. docker container ls -q

Visit the documentation to learn all available options for this command.

Show a div as a modal pop up

A simple modal pop up div or dialog box can be done by CSS properties and little bit of jQuery.The basic idea is simple:

  • 1. Create a div with semi transparent background & show it on top of your content page on click.
  • 2. Show your pop up div or alert div on top of the semi transparent dimming/hiding div.
  • So we need three divs:

  • content(main content of the site).
  • hider(To dim the content).
  • popup_box(the modal div to display).

    First let us define the CSS:

        #hider
        {
            position:absolute;
            top: 0%;
            left: 0%;
            width:1600px;
            height:2000px;
            margin-top: -800px; /*set to a negative number 1/2 of your height*/
            margin-left: -500px; /*set to a negative number 1/2 of your width*/
            /*
            z- index must be lower than pop up box
           */
            z-index: 99;
           background-color:Black;
           //for transparency
           opacity:0.6;
        }
    
        #popup_box  
        {
    
        position:absolute;
            top: 50%;
            left: 50%;
            width:10em;
            height:10em;
            margin-top: -5em; /*set to a negative number 1/2 of your height*/
            margin-left: -5em; /*set to a negative number 1/2 of your width*/
            border: 1px solid #ccc;
            border:  2px solid black;
            z-index:100; 
    
        }
    

    It is important that we set our hider div's z-index lower than pop_up box as we want to show popup_box on top.
    Here comes the java Script:

            $(document).ready(function () {
            //hide hider and popup_box
            $("#hider").hide();
            $("#popup_box").hide();
    
            //on click show the hider div and the message
            $("#showpopup").click(function () {
                $("#hider").fadeIn("slow");
                $('#popup_box').fadeIn("slow");
            });
            //on click hide the message and the
            $("#buttonClose").click(function () {
    
                $("#hider").fadeOut("slow");
                $('#popup_box').fadeOut("slow");
            });
    
            });
    

    And finally the HTML:

    <div id="hider"></div>
    <div id="popup_box">
        Message<br />
        <a id="buttonClose">Close</a>
    </div>    
    <div id="content">
        Page's main content.<br />
        <a id="showpopup">ClickMe</a>
    </div>
    

    I have used jquery-1.4.1.min.js www.jquery.com/download and tested the code in Firefox. Hope this helps.

  • Loading context in Spring using web.xml

    You can also load the context while defining the servlet itself (WebApplicationContext)

      <servlet>
        <servlet-name>admin</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
          <param-name>contextConfigLocation</param-name>
          <param-value>
                    /WEB-INF/spring/*.xml
                </param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
      </servlet>
      <servlet-mapping>
        <servlet-name>admin</servlet-name>
        <url-pattern>/</url-pattern>
      </servlet-mapping>
    

    rather than (ApplicationContext)

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/applicationContext*.xml</param-value>
    </context-param>
    
    <listener>
       <listener-class>
            org.springframework.web.context.ContextLoaderListener
       </listener-class>
    </listener> 
    

    or can do both together.

    Drawback of just using WebApplicationContext is that it will load context only for this particular Spring entry point (DispatcherServlet) where as with above mentioned methods context will be loaded for multiple entry points (Eg. Webservice Servlet, REST servlet etc)

    Context loaded by ContextLoaderListener will infact be a parent context to that loaded specifically for DisplacherServlet . So basically you can load all your business service, data access or repository beans in application context and separate out your controller, view resolver beans to WebApplicationContext.

    number several equations with only one number

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

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

    The documentation of the amsmath package explains this and more.

    Unsupported method: BaseConfig.getApplicationIdSuffix()

    I also faced the same issue and got a solution very similar:

    1. Changing the classpath to classpath 'com.android.tools.build:gradle:2.3.2'

      Image after adding the classpath

    2. A new message indicating to Update Build Tool version, so just click that message to update. Update

    Unity Scripts edited in Visual studio don't provide autocomplete

    If you have done all of the above and still isn't working , just try this: Note: you should have updated VS. Screenshot from visual studio

    Goto Unity > edit> preference >External tools> external script editor. Unity screenshot Somehow for me I had not selected "visual studio" for external script editor and it was not working. As soon as i selected this and doubled clicked on c# file from unity it started working.

    I hope it helps you too.

    How to use font-awesome icons from node-modules

    SASS modules version

    Soon, using @import in sass will be depreciated. SASS modules configuration works using @use instead.

    @use "../node_modules/font-awesome/scss/font-awesome"  with (
      $fa-font-path: "../icons"
    );
    
    .icon-user {
      @extend .fa;
      @extend .fa-user;
    }
    

    Java replace all square brackets in a string

    _x000D_
    _x000D_
       Use this line:) String result = strCurBal.replaceAll("[(" what ever u need to remove ")]", "");_x000D_
    _x000D_
        String strCurBal = "(+)3428";_x000D_
        Log.e("Agilanbu before omit ", strCurBal);_x000D_
        String result = strCurBal.replaceAll("[()]", ""); // () removing special characters from string_x000D_
        Log.e("Agilanbu after omit ", result);_x000D_
       _x000D_
        o/p :_x000D_
        Agilanbu before omit : (+)3428_x000D_
        Agilanbu after omit :  +3428_x000D_
    _x000D_
        String finalVal = result.replaceAll("[+]", ""); // + removing special characters from string_x000D_
        Log.e("Agilanbu finalVal  ", finalVal);_x000D_
        o/p_x000D_
        Agilanbu finalVal : 3428_x000D_
                _x000D_
        String finalVal1 = result.replaceAll("[+]", "-"); // insert | append | replace the special characters from string_x000D_
        Log.e("Agilanbu finalVal  ", finalVal1);_x000D_
        o/p_x000D_
        Agilanbu finalVal : -3428  // replacing the + symbol to -
    _x000D_
    _x000D_
    _x000D_

    Dynamically change bootstrap progress bar value when checkboxes checked

    Try this maybe :

    Bootply : http://www.bootply.com/106527

    Js :

    $('input').on('click', function(){
      var valeur = 0;
      $('input:checked').each(function(){
           if ( $(this).attr('value') > valeur )
           {
               valeur =  $(this).attr('value');
           }
      });
      $('.progress-bar').css('width', valeur+'%').attr('aria-valuenow', valeur);    
    });
    

    HTML :

     <div class="progress progress-striped active">
            <div class="progress-bar" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100">
            </div>
        </div>
    <div class="row tasks">
            <div class="col-md-6">
              <p><span>Identify your campaign audience.</span>Who are we talking to here? Understand your buyer persona before launching into a campaign, so you can target them correctly.</p>
            </div>
            <div class="col-md-2">
              <label>2014-01-29</label>
            </div>
            <div class="col-md-2">
              <input name="progress" class="progress" type="checkbox" value="10">
            </div>
            <div class="col-md-2">
              <input name="done" class="done" type="checkbox" value="20">
            </div>
          </div><!-- tasks -->
    
    <div class="row tasks">
            <div class="col-md-6">
              <p><span>Set your goals + benchmarks</span>Having SMART goals can help you be
    sure that you’ll have tangible results to share with the world (or your
    boss) at the end of your campaign.</p>
            </div>
            <div class="col-md-2">
              <label>2014-01-25</label>
            </div>
            <div class="col-md-2">
              <input name="progress" class="progress" type="checkbox" value="30">
            </div>
            <div class="col-md-2">
              <input name="done" class="done" type="checkbox" value="40">
            </div>
          </div><!-- tasks -->
    

    Css

    .tasks{
        background-color: #F6F8F8;
        padding: 10px;
        border-radius: 5px;
        margin-top: 10px;
    }
    .tasks span{
        font-weight: bold;
    }
    .tasks input{
        display: block;
        margin: 0 auto;
        margin-top: 10px;
    }
    .tasks a{
        color: #000;
        text-decoration: none;
        border:none;
    }
    .tasks a:hover{
        border-bottom: dashed 1px #0088cc;
    }
    .tasks label{
        display: block;
        text-align: center;
    }
    

    _x000D_
    _x000D_
    $(function(){_x000D_
    $('input').on('click', function(){_x000D_
      var valeur = 0;_x000D_
      $('input:checked').each(function(){_x000D_
           if ( $(this).attr('value') > valeur )_x000D_
           {_x000D_
               valeur =  $(this).attr('value');_x000D_
           }_x000D_
      });_x000D_
      $('.progress-bar').css('width', valeur+'%').attr('aria-valuenow', valeur);    _x000D_
    });_x000D_
    _x000D_
    });
    _x000D_
    .tasks{_x000D_
     background-color: #F6F8F8;_x000D_
     padding: 10px;_x000D_
     border-radius: 5px;_x000D_
     margin-top: 10px;_x000D_
    }_x000D_
    .tasks span{_x000D_
     font-weight: bold;_x000D_
    }_x000D_
    .tasks input{_x000D_
     display: block;_x000D_
     margin: 0 auto;_x000D_
     margin-top: 10px;_x000D_
    }_x000D_
    .tasks a{_x000D_
     color: #000;_x000D_
     text-decoration: none;_x000D_
     border:none;_x000D_
    }_x000D_
    .tasks a:hover{_x000D_
     border-bottom: dashed 1px #0088cc;_x000D_
    }_x000D_
    .tasks label{_x000D_
     display: block;_x000D_
     text-align: center;_x000D_
    }
    _x000D_
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>_x000D_
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
    _x000D_
     <div class="progress progress-striped active">_x000D_
            <div class="progress-bar" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100">_x000D_
            </div>_x000D_
        </div>_x000D_
    <div class="row tasks">_x000D_
            <div class="col-md-6">_x000D_
              <p><span>Identify your campaign audience.</span>Who are we talking to here? Understand your buyer persona before launching into a campaign, so you can target them correctly.</p>_x000D_
            </div>_x000D_
            <div class="col-md-2">_x000D_
              <label>2014-01-29</label>_x000D_
            </div>_x000D_
            <div class="col-md-2">_x000D_
              <input name="progress" class="progress" type="checkbox" value="10">_x000D_
            </div>_x000D_
            <div class="col-md-2">_x000D_
              <input name="done" class="done" type="checkbox" value="20">_x000D_
            </div>_x000D_
          </div><!-- tasks -->_x000D_
    _x000D_
    <div class="row tasks">_x000D_
            <div class="col-md-6">_x000D_
              <p><span>Set your goals + benchmarks</span>Having SMART goals can help you be_x000D_
    sure that you’ll have tangible results to share with the world (or your_x000D_
    boss) at the end of your campaign.</p>_x000D_
            </div>_x000D_
            <div class="col-md-2">_x000D_
              <label>2014-01-25</label>_x000D_
            </div>_x000D_
            <div class="col-md-2">_x000D_
              <input name="progress" class="progress" type="checkbox" value="30">_x000D_
            </div>_x000D_
            <div class="col-md-2">_x000D_
              <input name="done" class="done" type="checkbox" value="40">_x000D_
            </div>_x000D_
          </div><!-- tasks -->
    _x000D_
    _x000D_
    _x000D_

    Frontend tool to manage H2 database

    I like SQuirreL SQL Client, and NetBeans is very useful; but more often, I just fire up the built-in org.h2.tools.Server and browse port 8082:

    $ java -cp /opt/h2/bin/h2.jar org.h2.tools.Server -help
    Starts the H2 Console (web-) server, TCP, and PG server.
    Usage: java org.h2.tools.Server 
    When running without options, -tcp, -web, -browser and -pg are started.
    Options are case sensitive. Supported options are:
    [-help] or [-?]         Print the list of options
    [-web]                  Start the web server with the H2 Console
    [-webAllowOthers]       Allow other computers to connect - see below
    [-webPort ]       The port (default: 8082)
    [-webSSL]               Use encrypted (HTTPS) connections
    [-browser]              Start a browser and open a page to connect to the web server
    [-tcp]                  Start the TCP server
    [-tcpAllowOthers]       Allow other computers to connect - see below
    [-tcpPort ]       The port (default: 9092)
    [-tcpSSL]               Use encrypted (SSL) connections
    [-tcpPassword ]    The password for shutting down a TCP server
    [-tcpShutdown ""]  Stop the TCP server; example: tcp://localhost:9094
    [-tcpShutdownForce]     Do not wait until all connections are closed
    [-pg]                   Start the PG server
    [-pgAllowOthers]        Allow other computers to connect - see below
    [-pgPort ]        The port (default: 5435)
    [-baseDir ]        The base directory for H2 databases; for all servers
    [-ifExists]             Only existing databases may be opened; for all servers
    [-trace]                Print additional trace information; for all servers
    

    Split a vector into chunks

    split(x,matrix(1:n,n,length(x))[1:length(x)])

    perhaps this is more clear, but the same idea:
    split(x,rep(1:n, ceiling(length(x)/n),length.out = length(x)))

    if you want it ordered,throw a sort around it

    2 ways for "ClearContents" on VBA Excel, but 1 work fine. Why?

    It is because you haven't qualified Cells(1, 1) with a worksheet object, and the same holds true for Cells(10, 2). For the code to work, it should look something like this:

    Dim ws As Worksheet
    
    Set ws = Sheets("SheetName")
    Range(ws.Cells(1, 1), ws.Cells(10, 2)).ClearContents
    

    Alternately:

    With Sheets("SheetName")
        Range(.Cells(1, 1), .Cells(10, 2)).ClearContents
    End With
    

    EDIT: The Range object will inherit the worksheet from the Cells objects when the code is run from a standard module or userform. If you are running the code from a worksheet code module, you will need to qualify Range also, like so:

    ws.Range(ws.Cells(1, 1), ws.Cells(10, 2)).ClearContents
    

    or

    With Sheets("SheetName")
        .Range(.Cells(1, 1), .Cells(10, 2)).ClearContents
    End With
    

    ajax jquery simple get request

    You can make AJAX requests to applications loaded from the SAME domain and SAME port.

    Besides that, you should add dataType JSON if you want the result to be deserialized automatically.

    $.ajax({
            url: "https://app.asana.com/-/api/0.1/workspaces/",
            type: 'GET',
            dataType: 'json', // added data type
            success: function(res) {
                console.log(res);
                alert(res);
            }
        });
    

    http://api.jquery.com/jQuery.ajax/

    How to change symbol for decimal point in double.ToString()?

    Some shortcut is to create a NumberFormatInfo class, set its NumberDecimalSeparator property to "." and use the class as parameter to ToString() method whenever u need it.

    using System.Globalization;
    
    NumberFormatInfo nfi = new NumberFormatInfo();
    nfi.NumberDecimalSeparator = ".";
    
    value.ToString(nfi);
    

    'ssh-keygen' is not recognized as an internal or external command

    if you run from cmd on windows check the path System Variable value must have inside C:\Program Files\Git\bin or the path of you git installation on cmd type set to see the variables

    Get latitude and longitude automatically using php, API

    I think allow_url_fopen on your apache server is disabled. you need to trun it on.

    kindly change allow_url_fopen = 0 to allow_url_fopen = 1

    Don't forget to restart your Apache server after changing it.

    Two divs side by side - Fluid display

    You can also use the Grid View its also Responsive its something like this:

    #wrapper {
       width: auto;
        height: auto;
        box-sizing: border-box;
        display: grid;
        grid-auto-flow: row;
        grid-template-columns: repeat(6, 1fr);
    }
    
    #left{
        text-align: left;
        grid-column: 1/4;
    }
    
    #right {
        text-align: right;
        grid-column: 4/6;
    }
    

    and the HTML should look like this :

    <div id="wrapper">
    <div id="left" > ...some awesome stuff </div>
    <div id="right" > ...some awesome stuff </div>
    </div>
    

    here is a link for more information:

    https://www.w3schools.com/css/css_rwd_grid.asp

    im quite new but i thougt i could share my little experience

    How to declare an ArrayList with values?

    In Java 9+ you can do:

    var x = List.of("xyz", "abc");
    // 'var' works only for local variables
    

    Java 8 using Stream:

    Stream.of("xyz", "abc").collect(Collectors.toList());
    

    And of course, you can create a new object using the constructor that accepts a Collection:

    List<String> x = new ArrayList<>(Arrays.asList("xyz", "abc"));
    

    Tip: The docs contains very useful information that usually contains the answer you're looking for. For example, here are the constructors of the ArrayList class:

    How to access the first property of a Javascript object?

    if someone prefers array destructuring

    const [firstKey] = Object.keys(object);
    

    What is the difference between children and childNodes in JavaScript?

    Pick one depends on the method you are looking for!?

    I will go with ParentNode.children:

    As it provides namedItem method that allows me directly to get one of the children elements without looping through all children or avoiding to use getElementById etc.

    e.g.

    ParentNode.children.namedItem('ChildElement-ID'); // JS
    ref.current.children.namedItem('ChildElement-ID'); // React
    this.$refs.ref.children.namedItem('ChildElement-ID'); // Vue
    

    I will go with Node.childNodes:

    As it provides forEach method when I work with window.IntersectionObserver e.g.

    nodeList.forEach((node) => { observer.observe(node) })
    // IE11 does not support forEach on nodeList, but easy to be polyfilled.
    

    On Chrome 83

    Node.childNodes provides entries, forEach, item, keys, length and values

    ParentNode.children provides item, length and namedItem

    TypeError: 'int' object is not subscriptable

    Just to be clear, all the answers so far are correct, but the reasoning behind them is not explained very well.

    The sumall variable is not yet a string. Parentheticals will not convert to a string (e.g. summ = (int(birthday[0])+int(birthday[1])) still returns an integer. It looks like you most likely intended to type str((int(sumall[0])+int(sumall[1]))), but forgot to. The reason the str() function fixes everything is because it converts anything in it compatible to a string.

    add class with JavaScript

    document.getElementsByClassName returns a node list. So you'll have to iterate over the list and bind the event to individual elements. Like this...

    var buttons = document.getElementsByClassName("navButton");
    
    for(var i = 0; i < buttons.length; ++i){
        buttons[i].onmouseover = function() {
            this.setAttribute("class", "active");
            this.setAttribute("src", "images/arrows/top_o.png");
        }
    }
    

    How can I increase the cursor speed in terminal?

    If by "cursor speed", you mean the repeat rate when holding down a key - then have a look here: http://hints.macworld.com/article.php?story=20090823193018149

    To summarize, open up a Terminal window and type the following command:

    defaults write NSGlobalDomain KeyRepeat -int 0
    

    More detail from the article:

    Everybody knows that you can get a pretty fast keyboard repeat rate by changing a slider on the Keyboard tab of the Keyboard & Mouse System Preferences panel. But you can make it even faster! In Terminal, run this command:

    defaults write NSGlobalDomain KeyRepeat -int 0

    Then log out and log in again. The fastest setting obtainable via System Preferences is 2 (lower numbers are faster), so you may also want to try a value of 1 if 0 seems too fast. You can always visit the Keyboard & Mouse System Preferences panel to undo your changes.

    You may find that a few applications don't handle extremely fast keyboard input very well, but most will do just fine with it.

    Get local href value from anchor (a) tag

    In my case I had a href with a # and target.href was returning me the complete url. Target.hash did the work for me.

    $(".test a").on('click', function(e) {
        console.log(e.target.href); // logs https://www.test.com/#test
        console.log(e.target.hash); // logs #test
      });
    

    How do I rotate a picture in WinForms

    I have modified the function of Mr.net_prog which gets only the picture box and rotate the image in it.

        public static void RotateImage(PictureBox picBox)
        {
    
            Image img = picBox.Image;
            var bmp = new Bitmap(img);
    
            using (Graphics gfx = Graphics.FromImage(bmp))
            {
                gfx.Clear(Color.White);
                gfx.DrawImage(img, 0, 0, img.Width, img.Height);
            }
    
            bmp.RotateFlip(RotateFlipType.Rotate270FlipNone);
            picBox.Image = bmp;
        }
    

    Updating PartialView mvc 4

    You can also try this.

     $(document).ready(function () {
                var url = "@(Html.Raw(Url.Action("ActionName", "ControllerName")))";
                $("#PartialViewDivId").load(url);
            setInterval(function () {
                var url = "@(Html.Raw(Url.Action("ActionName", "ControllerName")))";
                $("#PartialViewDivId").load(url);
            }, 30000); //Refreshes every 30 seconds
    
            $.ajaxSetup({ cache: false });  //Turn off caching
        });
    

    It makes an initial call to load the div, and then subsequent calls are on a 30 second interval.

    In the controller section you can update the object and pass the object to the partial view.

    public class ControllerName: Controller
    {
        public ActionResult ActionName()
        {
            .
            .   // code for update object
            .
            return PartialView("PartialViewName", updatedObject);
        }
    }
    

    Make content horizontally scroll inside a div

    The problem is that your imgs will always bump down to the next line because of the containing div.

    In order to get around this, you need to place the imgs in their own div with a width wide enough to hold all of them. Then you can use your styles as is.

    So, when I set the imgs to 120px each and place them inside a

    div#insideDiv{
        width:800px;
    }
    

    it all works.

    Adjust width as necessary.

    See http://jsfiddle.net/jasongennaro/8YfRe/

    Mongoose: Find, modify, save

    Why not use Model.update? After all you're not using the found user for anything else than to update it's properties:

    User.update({username: oldUsername}, {
        username: newUser.username, 
        password: newUser.password, 
        rights: newUser.rights
    }, function(err, numberAffected, rawResponse) {
       //handle it
    })
    

    replace special characters in a string python

    replace operates on a specific string, so you need to call it like this

    removeSpecialChars = z.replace("!@#$%^&*()[]{};:,./<>?\|`~-=_+", " ")
    

    but this is probably not what you need, since this will look for a single string containing all that characters in the same order. you can do it with a regexp, as Danny Michaud pointed out.

    as a side note, you might want to look for BeautifulSoup, which is a library for parsing messy HTML formatted text like what you usually get from scaping websites.

    MySQL Query - Records between Today and Last 30 Days

    Here's a solution without using curdate() function, this is a solution for those who use TSQL I guess

    SELECT myDate
    FROM myTable
    WHERE myDate BETWEEN DATEADD(DAY, -30, GETDATE()) AND GETDATE()
    

    How do I clear the previous text field value after submitting the form with out refreshing the entire page?

    <form>
    <input type="text" placeholder="user-name" /><br>
    <input type=submit value="submit" id="submit" /> <br>
    </form>
    
    <script>
    $(window).load(function() {
    $('form').children('input:not(#submit)').val('')
    }
    
    </script>
    

    You can use this script where every you want.

    How to ignore parent css style

    You could turn it off by overriding it like this:

    height:auto !important;

    How can I find out which server hosts LDAP on my windows domain?

    If you're using AD you can use serverless binding to locate a domain controller for the default domain, then use LDAP://rootDSE to get information about the directory server, as described in the linked article.

    AngularJS ui-router login authentication

    I have another solution: that solution works perfectly when you have only content you want to show when you are logged in. Define a rule where you checking if you are logged in and its not path of whitelist routes.

    $urlRouterProvider.rule(function ($injector, $location) {
       var UserService = $injector.get('UserService');
       var path = $location.path(), normalized = path.toLowerCase();
    
       if (!UserService.isLoggedIn() && path.indexOf('login') === -1) {
         $location.path('/login/signin');
       }
    });
    

    In my example i ask if i am not logged in and the current route i want to route is not part of `/login', because my whitelist routes are the following

    /login/signup // registering new user
    /login/signin // login to app
    

    so i have instant access to this two routes and every other route will be checked if you are online.

    Here is my whole routing file for the login module

    export default (
      $stateProvider,
      $locationProvider,
      $urlRouterProvider
    ) => {
    
      $stateProvider.state('login', {
        parent: 'app',
        url: '/login',
        abstract: true,
        template: '<ui-view></ui-view>'
      })
    
      $stateProvider.state('signin', {
        parent: 'login',
        url: '/signin',
        template: '<login-signin-directive></login-signin-directive>'
      });
    
      $stateProvider.state('lock', {
        parent: 'login',
        url: '/lock',
        template: '<login-lock-directive></login-lock-directive>'
      });
    
      $stateProvider.state('signup', {
        parent: 'login',
        url: '/signup',
        template: '<login-signup-directive></login-signup-directive>'
      });
    
      $urlRouterProvider.rule(function ($injector, $location) {
        var UserService = $injector.get('UserService');
        var path = $location.path();
    
        if (!UserService.isLoggedIn() && path.indexOf('login') === -1) {
             $location.path('/login/signin');
        }
      });
    
      $urlRouterProvider.otherwise('/error/not-found');
    }
    

    () => { /* code */ } is ES6 syntax, use instead function() { /* code */ }

    Search File And Find Exact Match And Print Line?

    Build lists of matched lines - several flavors:

    def lines_that_equal(line_to_match, fp):
        return [line for line in fp if line == line_to_match]
    
    def lines_that_contain(string, fp):
        return [line for line in fp if string in line]
    
    def lines_that_start_with(string, fp):
        return [line for line in fp if line.startswith(string)]
    
    def lines_that_end_with(string, fp):
        return [line for line in fp if line.endswith(string)]
    

    Build generator of matched lines (memory efficient):

    def generate_lines_that_equal(string, fp):
        for line in fp:
            if line == string:
                yield line
    

    Print all matching lines (find all matches first, then print them):

    with open("file.txt", "r") as fp:
        for line in lines_that_equal("my_string", fp):
            print line
    

    Print all matching lines (print them lazily, as we find them)

    with open("file.txt", "r") as fp:
        for line in generate_lines_that_equal("my_string", fp):
            print line
    

    Generators (produced by yield) are your friends, especially with large files that don't fit into memory.

    How do I convert dmesg timestamp to custom date format?

    you will need to reference the "btime" in /proc/stat, which is the Unix epoch time when the system was latest booted. Then you could base on that system boot time and then add on the elapsed seconds given in dmesg to calculate timestamp for each events.

    CREATE FILE encountered operating system error 5(failed to retrieve text for this error. Reason: 15105)

    I was getting similar error.

    CREATE FILE encountered operating system error **32**(failed to retrieve text for this error. Reason: 15105) while attempting to open or create the physical file
    

    I used the following command to attach the database:

    EXEC sp_attach_single_file_db @dbname = 'SPDB',
    @physname = 'D:\SPDB.mdf'
    

    Understanding Matlab FFT example

    The reason why your X-axis plots frequencies only till 500 Hz is your command statement 'f = Fs/2*linspace(0,1,NFFT/2+1);'. Your Fs is 1000. So when you divide it by 2 & then multiply by values ranging from 0 to 1, it returns a vector of length NFFT/2+1. This vector consists of equally spaced frequency values, ranging from 0 to Fs/2 (i.e. 500 Hz). Since you plot using 'plot(f,2*abs(Y(1:NFFT/2+1)))' command, your X-axis limit is 500 Hz.

    What does if __name__ == "__main__": do?

    The simplest explanation for the __name__ variable (imho) is the following:

    Create the following files.

    # a.py
    import b
    

    and

    # b.py
    print "Hello World from %s!" % __name__
    
    if __name__ == '__main__':
        print "Hello World again from %s!" % __name__
    

    Running them will get you this output:

    $ python a.py
    Hello World from b!
    

    As you can see, when a module is imported, Python sets globals()['__name__'] in this module to the module's name. Also, upon import all the code in the module is being run. As the if statement evaluates to False this part is not executed.

    $ python b.py
    Hello World from __main__!
    Hello World again from __main__!
    

    As you can see, when a file is executed, Python sets globals()['__name__'] in this file to "__main__". This time, the if statement evaluates to True and is being run.

    What is the best way to get the first letter from a string in Java, returned as a string of length 1?

    Long story short, it probably doesn't matter. Use whichever you think looks nicest.

    Longer answer, using Oracle's Java 7 JDK specifically, since this isn't defined at the JLS:

    String.valueOf or Character.toString work the same way, so use whichever you feel looks nicer. In fact, Character.toString simply calls String.valueOf (source).

    So the question is, should you use one of those or String.substring. Here again it doesn't matter much. String.substring uses the original string's char[] and so allocates one object fewer than String.valueOf. This also prevents the original string from being GC'ed until the one-character string is available for GC (which can be a memory leak), but in your example, they'll both be available for GC after each iteration, so that doesn't matter. The allocation you save also doesn't matter -- a char[1] is cheap to allocate, and short-lived objects (as the one-char string will be) are cheap to GC, too.

    If you have a large enough data set that the three are even measurable, substring will probably give a slight edge. Like, really slight. But that "if... measurable" contains the real key to this answer: why don't you just try all three and measure which one is fastest?

    Replace an element into a specific position of a vector

    See an example here: http://www.cplusplus.com/reference/stl/vector/insert/ eg.:

    
    
    ...
    vector::iterator iterator1;
    
      iterator1= vec1.begin();
      vec1.insert ( iterator1+i , vec2[i] );
    
    // This means that at position "i" from the beginning it will insert the value from vec2 from position i
    
    

    Your first approach was replacing the values from vec1[i] with the values from vec2[i]

    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

    Calculating the area under a curve given a set of coordinates, without knowing the function

    The numpy and scipy libraries include the composite trapezoidal (numpy.trapz) and Simpson's (scipy.integrate.simps) rules.

    Here's a simple example. In both trapz and simps, the argument dx=5 indicates that the spacing of the data along the x axis is 5 units.

    from __future__ import print_function
    
    import numpy as np
    from scipy.integrate import simps
    from numpy import trapz
    
    
    # The y values.  A numpy array is used here,
    # but a python list could also be used.
    y = np.array([5, 20, 4, 18, 19, 18, 7, 4])
    
    # Compute the area using the composite trapezoidal rule.
    area = trapz(y, dx=5)
    print("area =", area)
    
    # Compute the area using the composite Simpson's rule.
    area = simps(y, dx=5)
    print("area =", area)
    

    Output:

    area = 452.5
    area = 460.0
    

    How do you rebase the current branch's changes on top of changes being merged in?

    Another way to look at it is to consider git rebase master as:

    Rebase the current branch on top of master

    Here , 'master' is the upstream branch, and that explain why, during a rebase, ours and theirs are reversed.

    How to remove element from an array in JavaScript?

    Array.splice() has the interesting property that one cannot use it to remove the first element. So, we need to resort to

    function removeAnElement( array, index ) {
        index--;
    
        if ( index === -1 ) {
            return array.shift();
        } else {
            return array.splice( index, 1 );
        }
    }
    

    ALTER TABLE ADD COLUMN IF NOT EXISTS in SQLite

    In case you're having this problem in flex/adobe air and find yourself here first, i've found a solution, and have posted it on a related question: ADD COLUMN to sqlite db IF NOT EXISTS - flex/air sqlite?

    My comment here: https://stackoverflow.com/a/24928437/2678219

    How to source virtualenv activate in a Bash script

    You can also do this using a subshell to better contain your usage - here's a practical example:

    #!/bin/bash
    
    commandA --args
    
    # Run commandB in a subshell and collect its output in $VAR
    # NOTE
    #  - PATH is only modified as an example
    #  - output beyond a single value may not be captured without quoting
    #  - it is important to discard (or separate) virtualenv activation stdout
    #    if the stdout of commandB is to be captured
    #
    VAR=$(
        PATH="/opt/bin/foo:$PATH"
        . /path/to/activate > /dev/null  # activate virtualenv
        commandB  # tool from /opt/bin/ which requires virtualenv
    )
    
    # Use the output from commandB later
    commandC "$VAR"
    

    This style is especially helpful when

    • a different version of commandA or commandC exists under /opt/bin
    • commandB exists in the system PATH or is very common
    • these commands fail under the virtualenv
    • one needs a variety of different virtualenvs

    Reading numbers from a text file into an array in C

    5623125698541159 is treated as a single number (out of range of int on most architecture). You need to write numbers in your file as

    5 6 2 3 1 2 5  6 9 8 5 4 1 1 5 9  
    

    for 16 numbers.

    If your file has input

    5,6,2,3,1,2,5,6,9,8,5,4,1,1,5,9 
    

    then change %d specifier in your fscanf to %d,.

      fscanf(myFile, "%d,", &numberArray[i] );  
    

    Here is your full code after few modifications:

    #include <stdio.h>
    #include <stdlib.h>
    
    int main(){
    
        FILE *myFile;
        myFile = fopen("somenumbers.txt", "r");
    
        //read file into array
        int numberArray[16];
        int i;
    
        if (myFile == NULL){
            printf("Error Reading File\n");
            exit (0);
        }
    
        for (i = 0; i < 16; i++){
            fscanf(myFile, "%d,", &numberArray[i] );
        }
    
        for (i = 0; i < 16; i++){
            printf("Number is: %d\n\n", numberArray[i]);
        }
    
        fclose(myFile);
    
        return 0;
    }
    

    how to add json library

    AFAIK the json module was added in version 2.6, see here. I'm guessing you can update your python installation to the latest stable 2.6 from this page.

    Set Content-Type to application/json in jsp file

    @Petr Mensik & kensen john

    Thanks, I could not used the page directive because I have to set a different content type according to some URL parameter. I will paste my code here since it's something quite common with JSON:

        <%
            String callback = request.getParameter("callback");
            response.setCharacterEncoding("UTF-8");
            if (callback != null) {
                // Equivalent to: <@page contentType="text/javascript" pageEncoding="UTF-8">
                response.setContentType("text/javascript");
            } else {
                // Equivalent to: <@page contentType="application/json" pageEncoding="UTF-8">
                response.setContentType("application/json");
            }
    
            [...]
    
            String output = "";
    
            if (callback != null) {
                output += callback + "(";
            }
    
            output += jsonObj.toString();
    
            if (callback != null) {
                output += ");";
            }
        %>
        <%=output %>
    

    When callback is supplied, returns:

        callback({...JSON stuff...});
    

    with content-type "text/javascript"

    When callback is NOT supplied, returns:

        {...JSON stuff...}
    

    with content-type "application/json"

    SQL grouping by all the columns

    No because this fundamentally means that you will not be grouping anything. If you group by all columns (and have a properly defined table w/ a unique index) then SELECT * FROM table is essentially the same thing as SELECT * FROM table GROUP BY *.

    How to prevent column break within an element?

    The accepted answer is now two years old and things appear to have changed.

    This article explains the use of the column-break-inside property. I can't say how or why this differs from break-inside, because only the latter appears to be documented in the W3 spec. However, the Chrome and Firefox support the following:

    li {
        -webkit-column-break-inside:avoid;
           -moz-column-break-inside:avoid;
                column-break-inside:avoid;
    }
    

    Processing Symbol Files in Xcode

    I know that this is not a technical solution but I had my iphone connected with the computer by cable and disconnecting the device from the computer and connecting it again (by cable again) worked for me as I could not solved it with the solutions that are provided before.

    How to set app icon for Electron / Atom Shell App

    If you want to update the app icon in the taskbar, then Update following in main.js (if using typescript then main.ts)

    win.setIcon(path.join(__dirname, '/src/assets/logo-small.png'));
    

    __dirname points to the root directory (same directory as package.json) of your application.

    MySQL Error 1215: Cannot add foreign key constraint

    I had the same problem.
    I solved it doing this:

    I created the following line in the
    primary key: (id int(11) unsigned NOT NULL AUTO_INCREMENT)

    I found out this solution after trying to import a table in my schema builder. If it works for you, let me know!

    Good luck!

    Felipe Tércio

    Convert XML String to Object

    Just in case anyone might find this useful:

    public static class XmlConvert
    {
        public static string SerializeObject<T>(T dataObject)
        {
            if (dataObject == null)
            {
                return string.Empty;
            }
            try
            {
                using (StringWriter stringWriter = new System.IO.StringWriter())
                {
                    var serializer = new XmlSerializer(typeof(T));
                    serializer.Serialize(stringWriter, dataObject);
                    return stringWriter.ToString();
                }
            }
            catch (Exception ex)
            {
                return string.Empty;
            }
        }
    
        public static T DeserializeObject<T>(string xml)
             where T : new()
        {
            if (string.IsNullOrEmpty(xml))
            {
                return new T();
            }
            try
            {
                using (var stringReader = new StringReader(xml))
                {
                    var serializer = new XmlSerializer(typeof(T));
                    return (T)serializer.Deserialize(stringReader);
                }
            }
            catch (Exception ex)
            {
                return new T();
            }
        }
    }
    

    You can call it using:

    MyCustomObject myObject = new MyCustomObject();
    string xmlString = XmlConvert.SerializeObject(myObject)
    myObject = XmlConvert.DeserializeObject<MyCustomObject>(xmlString);
    

    Convert a string to datetime in PowerShell

    Chris Dents' answer has already covered the OPs' question but seeing as this was the top search on google for PowerShell format string as date I thought I'd give a different string example.


    If like me, you get the time string like this 20190720170000.000000+000

    An important thing to note is you need to use ToUniversalTime() when using [System.Management.ManagementDateTimeConverter] otherwise you get offset times against your input.

    PS Code

    cls
    Write-Host "This example is for the 24hr clock with HH"
    Write-Host "ToUniversalTime() must be used when using [System.Management.ManagementDateTimeConverter]"
    $my_date_24hr_time   = "20190720170000.000000+000"
    $date_format         = "yyyy-MM-dd HH:mm"
    [System.Management.ManagementDateTimeConverter]::ToDateTime($my_date_24hr_time).ToUniversalTime();
    [System.Management.ManagementDateTimeConverter]::ToDateTime($my_date_24hr_time).ToUniversalTime().ToSTring($date_format)
    [datetime]::ParseExact($my_date_24hr_time,"yyyyMMddHHmmss.000000+000",$null).ToSTring($date_format)
    Write-Host
    Write-Host "-----------------------------"
    Write-Host
    Write-Host "This example is for the am pm clock with hh"
    Write-Host "Again, ToUniversalTime() must be used when using [System.Management.ManagementDateTimeConverter]"
    Write-Host
    $my_date_ampm_time   = "20190720110000.000000+000"
    [System.Management.ManagementDateTimeConverter]::ToDateTime($my_date_ampm_time).ToUniversalTime();
    [System.Management.ManagementDateTimeConverter]::ToDateTime($my_date_ampm_time).ToUniversalTime().ToSTring($date_format)
    [datetime]::ParseExact($my_date_ampm_time,"yyyyMMddhhmmss.000000+000",$null).ToSTring($date_format)
    

    Output

    This example is for the 24hr clock with HH
    ToUniversalTime() must be used when using [System.Management.ManagementDateTimeConverter]
    
    20 July 2019 17:00:00
    2019-07-20 17:00
    2019-07-20 17:00
    
    -----------------------------
    
    This example is for the am pm clock with hh
    Again, ToUniversalTime() must be used when using [System.Management.ManagementDateTimeConverter]
    
    20 July 2019 11:00:00
    2019-07-20 11:00
    2019-07-20 11:00
    

    MS doc on [Management.ManagementDateTimeConverter]:

    https://docs.microsoft.com/en-us/dotnet/api/system.management.managementdatetimeconverter?view=dotnet-plat-ext-3.1

    Error in if/while (condition) {: missing Value where TRUE/FALSE needed

    this works with "NA" not for NA

    comments = c("no","yes","NA")
      for (l in 1:length(comments)) {
        #if (!is.na(comments[l])) print(comments[l])
        if (comments[l] != "NA") print(comments[l])
      }
    

    Angular JS update input field after change

    I'm guessing that when you enter a value into the totals field that value expression somehow gets overwritten.

    However, you can take an alternative approach: Create a field for the total value and when either one or two changes update that field.

    <li>Total <input type="text" ng-model="total">{{total}}</li>
    

    And change the javascript:

    function TodoCtrl($scope) {
        $scope.$watch('one * two', function (value) {
            $scope.total = value;
        });
    }
    

    Example fiddle here.

    Can't change table design in SQL Server 2008

    Prevent saving changes that require table re-creation

    Five swift clicks

    Prevent saving changes that require table re-creation in five clicks

    1. Tools
    2. Options
    3. Designers
    4. Prevent saving changes that require table re-creation
    5. OK.

    After saving, repeat the proceudure to re-tick the box. This safe-guards against accidental data loss.

    Further explanation

    • By default SQL Server Management Studio prevents the dropping of tables, because when a table is dropped its data contents are lost.*

    • When altering a column's datatype in the table Design view, when saving the changes the database drops the table internally and then re-creates a new one.

    *Your specific circumstances will not pose a consequence since your table is empty. I provide this explanation entirely to improve your understanding of the procedure.

    "The semaphore timeout period has expired" error for USB connection

    I had a similar problem which I solved by changing the Port Settings in the port driver (located in Ports in device manager) to fit the device I was using.

    For me it was that wrong Bits per second value was set.

    How to Identify port number of SQL server

    Visually you can open "SQL Server Configuration Manager" and check properties of "Network Configuration":

    SQL Server Configuration

    What does LINQ return when the results are empty

    In Linq-to-SQL if you try to get the first element on a query with no results you will get sequence contains no elements error. I can assure you that the mentioned error is not equal to object reference not set to an instance of an object. in conclusion no, it won't return null since null can't say sequence contains no elements it will always say object reference not set to an instance of an object ;)

    How to change the commit author for one specific commit?

    If what you need to change is the AUTHOR OF THE LAST commit and no other is using your repository, you may undo your last commit with:

    git push -f origin last_commit_hash:branch_name 
    

    change the author name of your commit with:

    git commit --amend --author "type new author here"
    

    Exit the editor that opens and push again your code:

    git push
    

    Load local javascript file in chrome for testing?

    If you still need to do this, I ran across the same problem. Somehow, EDGE renders all the scripts even if they are not via HTTP, HTTPS etc... Open the html/js file directly from the filesystem with Edge, and it will work.

    How to print colored text to the terminal?

    Here is a simple function I use to print a text message in color without having to remember ANSI codes but rather using standard RGB tuples to define the foreground and background colors.

    def print_in_color(txt_msg, fore_tuple, back_tuple, ):
        # Prints the text_msg in the foreground color specified by fore_tuple with the background specified by back_tuple
        # text_msg is the text, fore_tuple is foreground color tuple (r,g,b), back_tuple is background tuple (r,g,b)
        rf,bf,gf = fore_tuple
        rb,gb,bb = back_tuple
        msg = '{0}' + txt_msg
        mat = '\33[38;2;' + str(rf) + ';' + str(gf) + ';' + str(bf) + ';48;2;' + str(rb) + ';' +str(gb) + ';' + str(bb) + 'm'
        print(msg .format(mat))
        print('\33[0m') # Returns default print color to back to black
    
    # Example of use using a message with variables
    fore_color = 'cyan'
    back_color = 'dark green'
    msg = 'foreground color is {0} and the background color is {1}'.format(fore_color, back_color)
    print_in_color(msg, (0,255,255), (0,127,127))
    

    How can I reverse a NSArray in Objective-C?

    DasBoot has the right approach, but there are a few mistakes in his code. Here's a completely generic code snippet that will reverse any NSMutableArray in place:

    /* Algorithm: swap the object N elements from the top with the object N 
     * elements from the bottom. Integer division will wrap down, leaving 
     * the middle element untouched if count is odd.
     */
    for(int i = 0; i < [array count] / 2; i++) {
        int j = [array count] - i - 1;
    
        [array exchangeObjectAtIndex:i withObjectAtIndex:j];
    }
    

    You can wrap that in a C function, or for bonus points, use categories to add it to NSMutableArray. (In that case, 'array' would become 'self'.) You can also optimize it by assigning [array count] to a variable before the loop and using that variable, if you desire.

    If you only have a regular NSArray, there's no way to reverse it in place, because NSArrays cannot be modified. But you can make a reversed copy:

    NSMutableArray * copy = [NSMutableArray arrayWithCapacity:[array count]];
    
    for(int i = 0; i < [array count]; i++) {
        [copy addObject:[array objectAtIndex:[array count] - i - 1]];
    }
    

    Or use this little trick to do it in one line:

    NSArray * copy = [[array reverseObjectEnumerator] allObjects];
    

    If you just want to loop over an array backwards, you can use a for/in loop with [array reverseObjectEnumerator], but it's likely a bit more efficient to use -enumerateObjectsWithOptions:usingBlock::

    [array enumerateObjectsWithOptions:NSEnumerationReverse
                            usingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        // This is your loop body. Use the object in obj here. 
        // If you need the index, it's in idx.
        // (This is the best feature of this method, IMHO.)
        // Instead of using 'continue', use 'return'.
        // Instead of using 'break', set '*stop = YES' and then 'return'.
        // Making the surrounding method/block return is tricky and probably
        // requires a '__block' variable.
        // (This is the worst feature of this method, IMHO.)
    }];
    

    (Note: Substantially updated in 2014 with five more years of Foundation experience, a new Objective-C feature or two, and a couple tips from the comments.)

    How do I add a library path in cmake?

    The simplest way of doing this would be to add

    include_directories(${CMAKE_SOURCE_DIR}/inc)
    link_directories(${CMAKE_SOURCE_DIR}/lib)
    
    add_executable(foo ${FOO_SRCS})
    target_link_libraries(foo bar) # libbar.so is found in ${CMAKE_SOURCE_DIR}/lib
    

    The modern CMake version that doesn't add the -I and -L flags to every compiler invocation would be to use imported libraries:

    add_library(bar SHARED IMPORTED) # or STATIC instead of SHARED
    set_target_properties(bar PROPERTIES
      IMPORTED_LOCATION "${CMAKE_SOURCE_DIR}/lib/libbar.so"
      INTERFACE_INCLUDE_DIRECTORIES "${CMAKE_SOURCE_DIR}/include/libbar"
    )
    
    set(FOO_SRCS "foo.cpp")
    add_executable(foo ${FOO_SRCS})
    target_link_libraries(foo bar) # also adds the required include path
    

    If setting the INTERFACE_INCLUDE_DIRECTORIES doesn't add the path, older versions of CMake also allow you to use target_include_directories(bar PUBLIC /path/to/include). However, this no longer works with CMake 3.6 or newer.

    SyntaxError: cannot assign to operator

    In case it helps someone, if your variables have hyphens in them, you may see this error since hyphens are not allowed in variable names in Python and are used as subtraction operators.

    Example:

    my-variable = 5   # would result in 'SyntaxError: can't assign to operator'
    

    Blurring an image via CSS?

    Yes there is using the following code will allow you to apply a blurring effect to the specified image and also it will allow you to choose the amount of blurring.

    img {
      -webkit-filter: blur(10px);
        filter: blur(10px);
    }
    

    Android - how to make a scrollable constraintlayout?

    For completing the previous answers I am adding the following example, which also takes into account the use of the AppBar. With this code, the Android Studio design editor seems to work fine with the ConstraintLayout.

    <?xml version="1.0" encoding="utf-8"?> 
    <LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="true"
        android:background="@drawable/bg"
        android:orientation="vertical">
    
    <android.support.design.widget.AppBarLayout
        android:id="@+id/app_bar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.ActionBar.AppOverlayTheme">
        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            app:popupTheme="@style/AppTheme.PopupOverlay"/>
    </android.support.design.widget.AppBarLayout>
    
    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
    
        <android.support.constraint.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
    
            <ImageView
                android:id="@+id/image_id"
                android:layout_width="match_parent"
                android:layout_height="@dimen/app_bar_height"
                android:fitsSystemWindows="true"
                android:scaleType="centerCrop"
                android:src="@drawable/intro"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toBottomOf="parent" />
    
            <TextView
                android:id="@+id/desc_id"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="@dimen/text_margin"
                android:text="@string/intro_desc"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/image_id" />
    
            <Button
                android:id="@+id/button_scan"
                style="?android:textAppearanceSmall"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="8dp"
                android:backgroundTint="@color/colorAccent"
                android:padding="8dp"
                android:text="@string/intro_button_scan"
                android:textStyle="bold"
                app:layout_constraintTop_toBottomOf="@+id/desc_id" />
    
            <Button
                android:id="@+id/button_return"
                style="?android:textAppearanceSmall"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="8dp"
                android:layout_marginTop="8dp"
                android:backgroundTint="@color/colorAccent"
                android:padding="8dp"
                android:text="@string/intro_button_return"
                android:textStyle="bold"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/button_recycle" />
    
            <Button
                android:id="@+id/button_recycle"
                style="?android:textAppearanceSmall"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="8dp"
                android:backgroundTint="@color/colorAccent"
                android:padding="8dp"
                android:text="@string/intro_button_recycle"
                android:textStyle="bold"
                app:layout_constraintTop_toBottomOf="@+id/button_scan" />
        </android.support.constraint.ConstraintLayout>
    </ScrollView>
    </LinearLayout>
    

    Creating .pem file for APNS?

    There is a easiest way to create .Pem file if you have already apns p12 file in your key chain access.

    Open terminal and enter the below command:

    For Devlopment openssl pkcs12 -in apns-div-cert.p12 -out apns-div-cert.pem -nodes -clcerts

    For Production openssl pkcs12 -in apns-dist-cert.p12 -out apns-dist-cert.pem -nodes -clcerts

    Rename your P12 file with this name : apns-div-cert.p12 otherwise instead of this you need to enter your filename. Thanks!!

    What does auto do in margin:0 auto?

    When you have specified a width on the object that you have applied margin: 0 auto to, the object will sit centrally within it's parent container.

    Specifying auto as the second parameter basically tells the browser to automatically determine the left and right margins itself, which it does by setting them equally. It guarantees that the left and right margins will be set to the same size. The first parameter 0 indicates that the top and bottom margins will both be set to 0.

    margin-top:0;
    margin-bottom:0;
    margin-left:auto;
    margin-right:auto;
    

    Therefore, to give you an example, if the parent is 100px and the child is 50px, then the auto property will determine that there's 50px of free space to share between margin-left and margin-right:

    var freeSpace = 100 - 50;
    var equalShare = freeSpace / 2;
    

    Which would give:

    margin-left:25;
    margin-right:25;
    

    Have a look at this jsFiddle. You do not have to specify the parent width, only the width of the child object.

    ComboBox: Adding Text and Value to an Item (no Binding Source)

    You must create your own class type and override the ToString() method to return the text you want. Here is a simple example of a class you can use:

    public class ComboboxItem
    {
        public string Text { get; set; }
        public object Value { get; set; }
    
        public override string ToString()
        {
            return Text;
        }
    }
    

    The following is a simple example of its usage:

    private void Test()
    {
        ComboboxItem item = new ComboboxItem();
        item.Text = "Item text1";
        item.Value = 12;
    
        comboBox1.Items.Add(item);
    
        comboBox1.SelectedIndex = 0;
    
        MessageBox.Show((comboBox1.SelectedItem as ComboboxItem).Value.ToString());
    }
    

    How to query DATETIME field using only date in Microsoft SQL Server?

    Simple answer;

    select * from test where cast ([date] as date) = '03/19/2014';
    

    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)