Programs & Examples On #Asp.net dynamic data

ASP.NET Dynamic Data allows users to easily create extensible, data-driven Web applications by using scaffolding, which uses metadata from the data model to create the UI for Web applications. It dynamically generates Web Pages at run time from data model with list, add, edit templates with support for sorting and paging.

Is <img> element block level or inline level?

<img> is a replaced element; it has a display value of inline by default, but its default dimensions are defined by the embedded image's intrinsic values, like it were inline-block. You can set properties like border/border-radius, padding/margin, width, height, etc. on an image.

Replaced elements : They're elements whose contents are not affected by the current document's styles. The position of the replaced element can be affected using CSS, but not the contents of the replaced element itself.

Referenece : https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img

Use virtualenv with Python with Visual Studio Code in Ubuntu

As of September 2016 (according to the GitHub repository documentation of the extension) you can just execute a command from within Visual Studio Code that will let you select the interpreter from an automatically generated list of known interpreters (including the one in your project's virtual environment).

How can I use this feature?

  • Select the command Python: Select Workspace Interpreter(*) from the command palette (F1).
  • Upon selecting the above command a list of discovered interpreters will be displayed in a quick pick list.
  • Selecting an interpreter from this list will update the settings.json file automatically.

(*) This command has been updated to Python: Select Interpreter in the latest release of Visual Studio Code (thanks @nngeek).

Also, notice that your selected interpreter will be shown at the left side of the statusbar, e.g., Python 3.6 64-bit. This is a button you can click to trigger the Select Interpreter feature.

two divs the same line, one dynamic width, one fixed

@Yijie; Check the link maybe that's you want http://jsfiddle.net/sandeep/NCkL4/7/

EDIT:

http://jsfiddle.net/sandeep/NCkL4/8/

OR SEE THE FOLLOWING SNIPPET

_x000D_
_x000D_
#parent{_x000D_
    overflow:hidden;_x000D_
    background:yellow;_x000D_
    position:relative;_x000D_
    display:table;_x000D_
}_x000D_
.left{_x000D_
    display:table-cell;_x000D_
}_x000D_
.right{_x000D_
    background:red;_x000D_
    width:50px;_x000D_
    height:100%;_x000D_
    display:table-cell;_x000D_
}_x000D_
body{_x000D_
    margin:0;_x000D_
    padding:0;_x000D_
}
_x000D_
<div id="parent">_x000D_
  <div class="left">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</div>_x000D_
  <div class="right">fixed</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

MySQL: Insert record if not exists in table

INSERT doesn't allow WHERE in the syntax.

What you can do: create a UNIQUE INDEX on the field which should be unique (name), then use either:

  • normal INSERT (and handle the error if the name already exists)
  • INSERT IGNORE (which will fail silently cause a warning (instead of error) if name already exists)
  • INSERT ... ON DUPLICATE KEY UPDATE (which will execute the UPDATE at the end if name already exists, see documentation)

What is the difference between Collection and List in Java?

First off: a List is a Collection. It is a specialized Collection, however.

A Collection is just that: a collection of items. You can add stuff, remove stuff, iterate over stuff and query how much stuff is in there.

A List adds the information about a defined sequence of stuff to it: You can get the element at position n, you can add an element at position n, you can remove the element at position n.

In a Collection you can't do that: "the 5th element in this collection" isn't defined, because there is no defined order.

There are other specialized Collections as well, for example a Set which adds the feature that it will never contain the same element twice.

Check if a parameter is null or empty in a stored procedure

To check if variable is null or empty use this:

IF LEN(ISNULL(@var, '')) = 0

inline if statement java, why is not working

(inline if) in java won't work if you are using 'if' statement .. the right syntax is in the following example:

int y = (c == 19) ? 7 : 11 ; 

or

String y = (s > 120) ? "Slow Down" : "Safe";
System.out.println(y);

as You can see the type of the variable Y is the same as the return value ...

in your case it is better to use the normal if statement not inline if as it is in the pervious answer without "?"

if (compareChar(curChar, toChar("0"))) getButtons().get(i).setText("§");

How do you clear the console screen in C?

This should work. Then just call cls(); whenever you want to clear the screen.

(using the method suggested before.)

#include <stdio.h>
void cls()
{
    int x;
    for ( x = 0; x < 10; x++ ) 
    {
        printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
    }
}

Meaning of - <?xml version="1.0" encoding="utf-8"?>

The XML declaration in the document map consists of the following:

The version number, ?xml version="1.0"?. 

This is mandatory. Although the number might change for future versions of XML, 1.0 is the current version.

The encoding declaration,

encoding="UTF-8"?

This is optional. If used, the encoding declaration must appear immediately after the version information in the XML declaration, and must contain a value representing an existing character encoding.

How to solve could not create the virtual machine error of Java Virtual Machine Launcher?

  • Tap on Windows-Pause to open the System Control Panel applet. You can alternatively open the control panel manual to go there if you prefer it that way. Click on advanced system settings on the left.
  • Select environmental variables here.
  • Click on new under System Variables.
  • Enter '_JAVA_OPTIONS' as the variable name.
  • Enter '-Xmx1024M' as the variable value.
  • Click ok twice.

Regular expression to limit number of characters to 10

pattern: /[\w\W]{1,10}/g

I used this expression for my case, it includes all the characters available in the text.

Uncaught Invariant Violation: Too many re-renders. React limits the number of renders to prevent an infinite loop

I suspect that the problem lies in the fact that you are calling your state setter immediately inside the function component body, which forces React to re-invoke your function again, with the same props, which ends up calling the state setter again, which triggers React to call your function again.... and so on.

const SingInContainer = ({ message, variant}) => {
    const [open, setSnackBarState] = useState(false);
    const handleClose = (reason) => {
        if (reason === 'clickaway') {
          return;
        }
        setSnackBarState(false)

      };

    if (variant) {
        setSnackBarState(true); // HERE BE DRAGONS
    }
    return (
        <div>
        <SnackBar
            open={open}
            handleClose={handleClose}
            variant={variant}
            message={message}
            />
        <SignInForm/>
        </div>
    )
}

Instead, I recommend you just conditionally set the default value for the state property using a ternary, so you end up with:

const SingInContainer = ({ message, variant}) => {
    const [open, setSnackBarState] = useState(variant ? true : false); 
                                  // or useState(!!variant); 
                                  // or useState(Boolean(variant));
    const handleClose = (reason) => {
        if (reason === 'clickaway') {
          return;
        }
        setSnackBarState(false)

      };

    return (
        <div>
        <SnackBar
            open={open}
            handleClose={handleClose}
            variant={variant}
            message={message}
            />
        <SignInForm/>
        </div>
    )
}

Comprehensive Demo

See this CodeSandbox.io demo for a comprehensive demo of it working, plus the broken component you had, and you can toggle between the two.

Microsoft.WebApplication.targets was not found, on the build server. What's your solution?

I have found this on MS connect:

Yes, you need to install Visual Studio 2010 on your build machine to build database projects. Doing so does not require an additional license of Visual Studio.

So, this is the only option that I have for now.

react-native - Fit Image in containing View, not the whole screen size

the image has a property named Style ( like most of the react-native Compponents) and for Image's Styles, there is a property named resizeMode that takes values like: contain,cover,stretch,center,repeat

most of the time if you use center it will work for you

Using jQuery To Get Size of Viewport

To get the width and height of the viewport:

var viewportWidth = $(window).width();
var viewportHeight = $(window).height();

resize event of the page:

$(window).resize(function() {

});

Why does calling sumr on a stream with 50 tuples not complete

sumr is implemented in terms of foldRight:

 final def sumr(implicit A: Monoid[A]): A = F.foldRight(self, A.zero)(A.append) 

foldRight is not always tail recursive, so you can overflow the stack if the collection is too long. See Why foldRight and reduceRight are NOT tail recursive? for some more discussion of when this is or isn't true.

Create a new TextView programmatically then display it below another TextView

You're not assigning any id to the text view, but you're using tv.getId() to pass it to the addRule method as a parameter. Try to set a unique id via tv.setId(int).

You could also use the LinearLayout with vertical orientation, that might be easier actually. I prefer LinearLayout over RelativeLayouts if not necessary otherwise.

Looking for a short & simple example of getters/setters in C#

My explanation would be following. (It's not so short, but it's quite simple.)


Imagine a class with a variable:

class Something
{
    int weight;
    // and other methods, of course, not shown here
}

Well, there is a small problem with this class: no one can see the weight. We could make weight public, but then everyone would be able to change the weight at any moment (which is perhaps not what we want). So, well, we can do a function:

class Something
{
    int weight;
    public int GetWeight() { return weight; }
    // and other methods
}

This is already better, but now everyone instead of plain something.Weight has to type something.GetWeight(), which is, well, ugly.

With properties, we can do the same, but the code stays clean:

class Something
{
    public int weight { get; private set; }
    // and other methods
}

int w = something.weight // works!
something.weight = x; // doesn't even compile

Nice, so with the properties we have finer control over the variable access.

Another problem: okay, we want the outer code to be able to set weight, but we'd like to control its value, and not allow the weights lower than 100. Moreover, there are is some other inner variable density, which depends on weight, so we'd want to recalculate the density as soon as the weight changes.

This is traditionally achieved in the following way:

class Something
{
    int weight;
    public int SetWeight(int w)
    {
        if (w < 100)
            throw new ArgumentException("weight too small");
        weight = w;
        RecalculateDensity();
    }
    // and other methods
}

something.SetWeight(anotherSomething.GetWeight() + 1);

But again, we don't want expose to our clients that setting the weight is a complicated operation, it's semantically nothing but assigning a new weight. So the code with a setter looks the same way, but nicer:

class Something
{
    private int _w;
    public int Weight
    {
        get { return _w; }
        set
        {
            if (value < 100)
                throw new ArgumentException("weight too small");
            _w = value;
            RecalculateDensity();
        }
    }
    // and other methods
}

something.Weight = otherSomething.Weight + 1; // much cleaner, right?

So, no doubt, properties are "just" a syntactic sugar. But it makes the client's code be better. Interestingly, the need for property-like things arises very often, you can check how often you find the functions like GetXXX() and SetXXX() in the other languages.

YAML mapping values are not allowed in this context

The elements of a sequence need to be indented at the same level. Assuming you want two jobs (A and B) each with an ordered list of key value pairs, you should use:

jobs:
 - - name: A
   - schedule: "0 0/5 * 1/1 * ? *"
   - - type: mongodb.cluster
     - config:
       - host: mongodb://localhost:27017/admin?replicaSet=rs
       - minSecondaries: 2
       - minOplogHours: 100
       - maxSecondaryDelay: 120
 - - name: B
   - schedule: "0 0/5 * 1/1 * ? *"
   - - type: mongodb.cluster
     - config:
       - host: mongodb://localhost:27017/admin?replicaSet=rs
       - minSecondaries: 2
       - minOplogHours: 100
       - maxSecondaryDelay: 120

Converting the sequences of (single entry) mappings to a mapping as @Tsyvarrev does is also possible, but makes you lose the ordering.

warning: incompatible implicit declaration of built-in function ‘xyz’

I met these warnings on mempcpy function. Man page says this function is a GNU extension and synopsis shows:

#define _GNU_SOURCE
#include <string.h>

When #define is added to my source before the #include, declarations for the GNU extensions are made visible and warnings disappear.

How can I reconcile detached HEAD with master/origin?

If you did some commits on top of master and just want to "backwards merge" master there (i.e. you want master to point to HEAD), the one-liner would be:

git checkout -B master HEAD
  1. That creates a new branch named master, even if it exists already (which is like moving master and that's what we want).
  2. The newly created branch is set to point to HEAD, which is where you are.
  3. The new branch is checked out, so you are on master afterwards.

I found this especially useful in the case of sub-repositories, which also happen to be in a detached state rather often.

How to Detect Browser Back Button event - Cross Browser

The document.mouseover does not work for IE and FireFox. However I have tried this :

$(document).ready(function () {
  setInterval(function () {
    var $sample = $("body");
    if ($sample.is(":hover")) {
      window.innerDocClick = true;
    } else {
      window.innerDocClick = false;
    }
  });

});

window.onhashchange = function () {
  if (window.innerDocClick) {
    //Your own in-page mechanism triggered the hash change
  } else {
    //Browser back or forward button was pressed
  }
};

This works for Chrome and IE and not FireFox. Still working to get FireFox right. Any easy way on detecting Browser back/forward button click are welcome, not particularly in JQuery but also AngularJS or plain Javascript.

Java compiler level does not match the version of the installed Java project facet

I found @bigleftie's comment above very helpful: "Four things must match

  1. Project->Java Build Path->Libraries->JRE version
  2. Project->Java Compiler-> Compiler Compliance Level
  3. Project->Project Facets->Java->Version
  4. (if using Maven) pom.xml - maven-compiler-plugin artefact source and target".

In my case, in the project properties, Java compiler, the JDK compliance was set to use the workspace settings, which were different from the java version for the project. I clicked on 'Configure Workspace Settings', and changed the workspace Compiler compliance level to what I wanted, and the problem was resolved.

String.strip() in Python

In this case, you might get some differences. Consider a line like:

"foo\tbar "

In this case, if you strip, then you'll get {"foo":"bar"} as the dictionary entry. If you don't strip, you'll get {"foo":"bar "} (note the extra space at the end)

Note that if you use line.split() instead of line.split('\t'), you'll split on every whitespace character and the "striping" will be done during splitting automatically. In other words:

line.strip().split()

is always identical to:

line.split()

but:

line.strip().split(delimiter)

Is not necessarily equivalent to:

line.split(delimiter)

OSError: [WinError 193] %1 is not a valid Win32 application

The file hello.py is not an executable file. You need to specify a file like python.exe

try following:

import sys
subprocess.call([sys.executable, 'hello.py', 'htmlfilename.htm'])

Jump to function definition in vim

Another common technique is to place the function name in the first column. This allows the definition to be found with a simple search.

int
main(int argc, char *argv[])
{
    ...
}

The above function could then be found with /^main inside the file or with :grep -r '^main' *.c in a directory. As long as code is properly indented the only time the identifier will occur at the beginning of a line is at the function definition.

Of course, if you aren't using ctags from this point on you should be ashamed of yourself! However, I find this coding standard a helpful addition as well.

Create aar file in Android Studio

just like user hcpl said but if you want to not worry about the version of the library you can do this:

dependencies {
    compile(name:'mylibrary', ext:'aar')
}

as its kind of annoying to have to update the version everytime. Also it makes the not worrying about the name space easier this way.

How to make UIButton's text alignment center? Using IB

For UIButton you should use:-

[btn setContentHorizontalAlignment:UIControlContentHorizontalAlignmentCenter];

How can I write maven build to add resources to classpath?

By default maven does not include any files from "src/main/java".

You have two possible way to that.

  1. put all your resource files (different than java files) to "src/main/resources" - this is highly recommended

  2. Add to your pom (resource plugin):

?

 <resources>
       <resource>
           <directory>src/main/resources</directory>
        </resource>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
  </resources>

Why is pydot unable to find GraphViz's executables in Windows 8?

install Graphviz here and add its bin path solved my problem

https://graphviz.gitlab.io/_pages/Download/Download_windows.html

pip install Graphviz itself seems inadequate

How to Bootstrap navbar static to fixed on scroll?

Here is my implementation using the Affix Bootstrap plugin http://getbootstrap.com/javascript/#affix

It includes some extra affix problems solved (see below).

HTML:

<nav class="navbar navbar-inverse navbar-fixed-top" id="top_navbar">
  <div class="container-fluid">
... (typical Bootstrap top navbar)
  </div>
</div>

...
...
...

<div id="parent-navbar-main" >
  <div id="navbar-main">
... (here is your nav panel to get sticky on scroll)
  </div>
</div>

Javascript:

function set_sticky_panel()  {

  var affixElement = $('#navbar-main');

  var navbarElementHeight = $('#top_navbar').height();

// http://stackoverflow.com/questions/18683303/bootstrap-3-0-affix-with-list-changes-width
  var width = affixElement.parent().width();
  affixElement.width(width);

// http://stackoverflow.com/questions/3410765/get-full-height-of-element
  var affixElementHeight = $('#navbar-main').outerHeight(true);

// https://finiteheap.com/webdev/2014/12/26/bootstrap-affix-flickering.html  
  affixElement.parent().height(affixElementHeight);

// http://stackoverflow.com/questions/23797241/resetting-changing-the-offset-of-bootstrap-affix
  $(window).off('.affix')
  affixElement.removeData('bs.affix').removeClass('affix affix-top affix-bottom')


  affixElement.affix({
    offset: {
    // Distance of between element and top page
      top: function () {
      // how much scrolling is done until sticking the panel
        return (this.top = affixElement.offset().top - parseInt(navbarElementHeight,10))
      }
    }
  });

  // The replacement for the css-file.
  affixElement.on('affix.bs.affix', function (){
  // the absolute position where the sticked panel is to be placed when the fixing event fires (e.g. the panel reached the top of the page).
    affixElement.css('top', navbarElementHeight + 'px');
    affixElement.css('z-index', 10);
  });

}

$(document).on('ready', set_sticky_panel);

$(window).resize(set_sticky_panel);

CSS:

No css is required.

If to compare with the standart implementation my code additionaly solves these problems:

  1. The width of the sticky panel does not break at the fixing event anymore.
  2. The need in the CSS-file usage is eliminated.
  3. Reformatting the sticky panel size on the window change size event (responsiveness) is done now.
  4. No more affix flittering / jumping at the fixing event.

Check whether a string is not null and not empty

To check on if all the string attributes in an object is empty(Instead of using !=null on all the field names following java reflection api approach

private String name1;
private String name2;
private String name3;

public boolean isEmpty()  {

    for (Field field : this.getClass().getDeclaredFields()) {
        try {
            field.setAccessible(true);
            if (field.get(this) != null) {
                return false;
            }
        } catch (Exception e) {
            System.out.println("Exception occurred in processing");
        }
    }
    return true;
}

This method would return true if all the String field values are blank,It would return false if any one values is present in the String attributes

Split String by delimiter position using oracle SQL

You want to use regexp_substr() for this. This should work for your example:

select regexp_substr(val, '[^/]+/[^/]+', 1, 1) as part1,
       regexp_substr(val, '[^/]+$', 1, 1) as part2
from (select 'F/P/O' as val from dual) t

Here, by the way, is the SQL Fiddle.

Oops. I missed the part of the question where it says the last delimiter. For that, we can use regex_replace() for the first part:

select regexp_replace(val, '/[^/]+$', '', 1, 1) as part1,
       regexp_substr(val, '[^/]+$', 1, 1) as part2
from (select 'F/P/O' as val from dual) t

And here is this corresponding SQL Fiddle.

How can we draw a vertical line in the webpage?

There are no vertical lines in html that you can use but you can fake one by absolutely positioning a div outside of your container with a top:0; and bottom:0; style.

Try this:

CSS

.vr {
    width:10px;
    background-color:#000;
    position:absolute;
    top:0;
    bottom:0;
    left:150px;
}

HTML

<div class="vr">&nbsp;</div>

Demo

How do I get the full url of the page I am on in C#

I usually use Request.Url.ToString() to get the full url (including querystring), no concatenation required.

Setting a spinner onClickListener() in Android

Personally, I use that:

    final Spinner spinner = (Spinner) (view.findViewById(R.id.userList));
    spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {                

            userSelectedIndex = position;
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {
        }
    });  

.NET code to send ZPL to Zebra printers

VB Version (using port 9100 - tested on Zebra ZM400)

Sub PrintZPL(ByVal pIP As String, ByVal psZPL As String)
    Dim lAddress As Net.IPEndPoint
    Dim lSocket As System.Net.Sockets.Socket = Nothing
    Dim lNetStream As System.Net.Sockets.NetworkStream = Nothing
    Dim lBytes As Byte()

    Try
        lAddress = New Net.IPEndPoint(Net.IPAddress.Parse(pIP), 9100)
        lSocket = New Socket(AddressFamily.InterNetwork, SocketType.Stream, _                       ProtocolType.Tcp)
        lSocket.Connect(lAddress)
        lNetStream = New NetworkStream(lSocket)

        lBytes = System.Text.Encoding.ASCII.GetBytes(psZPL)
        lNetStream.Write(lBytes, 0, lBytes.Length)
    Catch ex As Exception When Not App.Debugging
        Msgbox ex.message & vbnewline & ex.tostring
    Finally
        If Not lNetStream Is Nothing Then
            lNetStream.Close()
        End If
        If Not lSocket Is Nothing Then
            lSocket.Close()
        End If
    End Try
End Sub

Add common prefix to all cells in Excel

Select the cell you want to be like this, Go To Cell Properties (or CTRL 1) under Number tab in custom enter "X"#

Firebase (FCM) how to get token

This line should get you the firebase FCM token.

String token = FirebaseInstanceId.getInstance().getToken();
Log.d("MYTAG", "This is your Firebase token" + token);

Do Log.d to print it out to the android monitor.

Shortcut to Apply a Formula to an Entire Column in Excel

If the formula already exists in a cell you can fill it down as follows:

  • Select the cell containing the formula and press CTRL+SHIFT+DOWN to select the rest of the column (CTRL+SHIFT+END to select up to the last row where there is data)
  • Fill down by pressing CTRL+D
  • Use CTRL+UP to return up

On Mac, use CMD instead of CTRL.

An alternative if the formula is in the first cell of a column:

  • Select the entire column by clicking the column header or selecting any cell in the column and pressing CTRL+SPACE
  • Fill down by pressing CTRL+D

How to set width to 100% in WPF

It is the container of the Grid that is imposing on its width. In this case, that's a ListBoxItem, which is left-aligned by default. You can set it to stretch as follows:

<ListBox>
    <!-- other XAML omitted, you just need to add the following bit -->
    <ListBox.ItemContainerStyle>
        <Style TargetType="ListBoxItem">
            <Setter Property="HorizontalAlignment" Value="Stretch"/>
        </Style>
    </ListBox.ItemContainerStyle>
</ListBox>

show all tags in git log

Note about tag of tag (tagging a tag), which is at the origin of your issue, as Charles Bailey correctly pointed out in the comment:

Make sure you study this thread, as overriding a signed tag is not as easy:

  • if you already pushed a tag, the git tag man page seriously advised against a simple git tag -f B to replace a tag name "A"
  • don't try to recreate a signed tag with git tag -f (see the thread extract below)

    (it is about a corner case, but quite instructive about tags in general, and it comes from another SO contributor Jakub Narebski):

Please note that the name of tag (heavyweight tag, i.e. tag object) is stored in two places:

  • in the tag object itself as a contents of 'tag' header (you can see it in output of "git show <tag>" and also in output of "git cat-file -p <tag>", where <tag> is heavyweight tag, e.g. v1.6.3 in git.git repository),
  • and also is default name of tag reference (reference in "refs/tags/*" namespace) pointing to a tag object.
    Note that the tag reference (appropriate reference in the "refs/tags/*" namespace) is purely local matter; what one repository has in 'refs/tags/v0.1.3', other can have in 'refs/tags/sub/v0.1.3' for example.

So when you create signed tag 'A', you have the following situation (assuming that it points at some commit)

  35805ce   <--- 5b7b4ead  <=== refs/tags/A
  (commit)       tag A
                 (tag)

Please also note that "git tag -f A A" (notice the absence of options forcing it to be an annotated tag) is a noop - it doesn't change the situation.

If you do "git tag -f -s A A": note that you force owerwriting a tag (so git assumes that you know what you are doing), and that one of -s / -a / -m options is used to force annotated tag (creation of tag object), you will get the following situation

  35805ce   <--- 5b7b4ea  <--- ada8ddc  <=== refs/tags/A
  (commit)       tag A         tag A
                 (tag)         (tag)

Note also that "git show A" would show the whole chain down to the non-tag object...

How to set a ripple effect on textview or imageview on Android?

android:background="?android:selectableItemBackground"
android:focusable="true"
android:clickable="true"

Fatal error: Call to undefined function pg_connect()

Edit. I just noticed you were mentionning MAMP. My advice is for Windows but may be useful if you know what corresponding tools to use.

Things to try:

  • Have you restarted PHP and Apache since your editing of php.ini?

  • Is the php_pgsql.dll found in your php\ext directory?

  • Are you running php as a module? If so, try copying the php_pgsql.dll file in the Apache\bin directory.

  • Are you running PHP from the command line with a flag specifying a different php.ini file?

  • You could try using a tool such as Sysinternals' Filemon to view what files are attempting to be accessed when running PHP.

  • You could try using a tool such as Dependency Walker to look at the dependencies for the postgreSQL DLL, in case you have a missing dependency. Quick search brought up ldd for Unix.

How do I copy an object in Java?

Add Cloneable and below code to your class

public Object clone() throws CloneNotSupportedException {
        return super.clone();
    }

Use this clonedObject = (YourClass) yourClassObject.clone();

org.apache.poi.POIXMLException: org.apache.poi.openxml4j.exceptions.InvalidFormatException:

Try this:

package my_default;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Iterator;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class Test {

    public static void main(String[] args) {
        try {
        // Create Workbook instance holding reference to .xlsx file
        XSSFWorkbook workbook = new XSSFWorkbook();

        // Get first/desired sheet from the workbook
        XSSFSheet sheet = createSheet(workbook, "Sheet 1", false);

        // XSSFSheet sheet = workbook.getSheetAt(1);//Don't use this line
        // because you get Sheet index (1) is out of range (no sheets)

        //Write some information in the cells or do what you want
        XSSFRow row1 = sheet.createRow(0);
        XSSFCell r1c2 = row1.createCell(0);
        r1c2.setCellValue("NAME");
        XSSFCell r1c3 = row1.createCell(1);
        r1c3.setCellValue("AGE");


        //Save excel to HDD Drive
        File pathToFile = new File("D:\\test.xlsx");
        if (!pathToFile.exists()) {
            pathToFile.createNewFile();
        }
        FileOutputStream fos = new FileOutputStream(pathToFile);
        workbook.write(fos);
        fos.close();
        System.out.println("Done");
    } catch (Exception e) {
        e.printStackTrace();
    }
}

private static XSSFSheet createSheet(XSSFWorkbook wb, String prefix, boolean isHidden) {
    XSSFSheet sheet = null;
    int count = 0;

    for (int i = 0; i < wb.getNumberOfSheets(); i++) {
        String sName = wb.getSheetName(i);
        if (sName.startsWith(prefix))
            count++;
    }

    if (count > 0) {
        sheet = wb.createSheet(prefix + count);
    } else
        sheet = wb.createSheet(prefix);

    if (isHidden)
        wb.setSheetHidden(wb.getNumberOfSheets() - 1, XSSFWorkbook.SHEET_STATE_VERY_HIDDEN);

        return sheet;
    }

}

PostgreSQL database service

Your server might not be running. This can have 2 issus IMO:

  1. I had the problem that the permissions were not set on the postgres folders and so the service was not able to start. I have no idea why that happend but giving proper permissions on the root postges folder and subfolders did the trick. If I recall it correctly, postgres is also installed as a service so you should find it in the Service List

  2. To start the server, you have a startcommand in your Startmenu. Somewhere at Start -> PostgreSQL -> Start Service/Server/... (haven't used it on Windows for a long time but it should be there).

Using if-else in JSP

It's almost always advisable to not use scriptlets in your JSP. They're considered bad form. Instead, try using JSTL (JSP Standard Tag Library) combined with EL (Expression Language) to run the conditional logic you're trying to do. As an added benefit, JSTL also includes other important features like looping.

Instead of:

<%String user=request.getParameter("user"); %>
<%if(user == null || user.length() == 0){
    out.print("I see! You don't have a name.. well.. Hello no name");   
}
else {%>
    <%@ include file="response.jsp" %>
<% } %>

Use:

<c:choose>
    <c:when test="${empty user}">
        I see!  You don't have a name.. well.. Hello no name
    </c:when>
    <c:otherwise>
        <%@ include file="response.jsp" %>
    </c:otherwise>
</c:choose>

Also, unless you plan on using response.jsp somewhere else in your code, it might be easier to just include the html in your otherwise statement:

<c:otherwise>
    <h1>Hello</h1>
    ${user}
</c:otherwise>

Also of note. To use the core tag, you must import it as follows:

 <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

You want to make it so the user will receive a message when the user submits a username. The easiest way to do this is to not print a message at all when the "user" param is null. You can do some validation to give an error message when the user submits null. This is a more standard approach to your problem. To accomplish this:

In scriptlet:

<% String user = request.getParameter("user");
   if( user != null && user.length() > 0 ) {
       <%@ include file="response.jsp" %>
   }
%>

In jstl:

<c:if test="${not empty user}">
    <%@ include file="response.jsp" %>
</c:if>

Hiding the scroll bar on an HTML page

If you want scrolling to work, before hiding scrollbars, consider styling them. Modern versions of OS X and mobile OS's have scrollbars that, while impractical for grabbing with a mouse, are quite beautiful and neutral.

To hide scrollbars, a technique by John Kurlak works well except for leaving Firefox users who don't have touchpads with no way to scroll unless they have a mouse with a wheel, which they probably do, but even then they can usually only scroll vertically.

John's technique uses three elements:

  • An outer element to mask the scrollbars.
  • A middle element to have the scrollbars.
  • And a content element to both set the size of the middle element and make it have scrollbars.

It must be possible to set the size of the outer and content elements the same which eliminates using percentages, but I can't think of anything else that won't work with the right tweaking.

My biggest concern is whether all versions of browsers set scrollbars to make visible overflowed content visible. I have tested in current browsers, but not older ones.

Pardon my SASS ;P

%size {
    // set width and height
}

.outer {
    // mask scrollbars of child
    overflow: hidden;
    // set mask size
    @extend %size;
    // has absolutely positioned child
    position: relative;
}

.middle {
    // always have scrollbars.
    // don't use auto, it leaves vertical scrollbar showing
    overflow: scroll;
    // without absolute, the vertical scrollbar shows
    position: absolute;
}
// prevent text selection from revealing scrollbar, which it only does on
// some webkit based browsers.
.middle::-webkit-scrollbar {
    display: none;
}

.content {
    // push scrollbars behind mask
    @extend %size;
}

Testing

OS X is 10.6.8. Windows is Windows 7.

  • Firefox 32.0 Scrollbars hidden. Arrow keys don't scroll, even after clicking to focus, but mouse wheel and two fingers on trackpad do. OS X and Windows.
  • Chrome 37.0 Scrollbars hidden. Arrow keys work after clicking to focus. Mouse wheel and trackpad work. OS X and Windows.
  • Internet Explorer 11 Scrollbars hidden. Arrow keys work after clicking to focus. Mouse wheel works. Windows.
  • Safari 5.1.10 Scrollbars hidden. Arrow keys work after clicking to focus. Mouse wheel and trackpad work. OS X.
  • Android 4.4.4 and 4.1.2. Scrollbars hidden. Touch scrolling works. Tried in Chrome 37.0, Firefox 32.0, and HTMLViewer on 4.4.4 (whatever that is). In HTMLViewer, the page is the size of the masked content and can be scrolled too! Scrolling interacts acceptably with page zooming.

How do I set a checkbox in razor view?

You can do this with @Html.CheckBoxFor():

@Html.CheckBoxFor(m => m.AllowRating, new{@checked=true });

or you can also do this with a simple @Html.CheckBox():

@Html.CheckBox("AllowRating", true) ;

IIS_IUSRS and IUSR permissions in IIS8

IIS_IUSRS group has prominence only if you are using ApplicationPool Identity. Even though you have this group looks empty at run time IIS adds to this group to run a worker process according to microsoft literature.

Register DLL file on Windows Server 2008 R2

You might need to register this DLL using the 32 bit version of regsvr32.exe:

c:\windows\syswow64\regsvr32 c:\tempdl\temp12.dll

How to get current date time in milliseconds in android

I think leverage this functionality using Java

long time= System.currentTimeMillis();

this will return current time in milliseconds mode . this will surely work

long time= System.currentTimeMillis();
android.util.Log.i("Time Class ", " Time value in millisecinds "+time);

Here is my logcat using the above function

05-13 14:38:03.149: INFO/Time Class(301): Time value in millisecinds 1368436083157

If you got any doubt with millisecond value .Check Here

EDIT : Time Zone I used to demo the code IST(+05:30) ,So if you check milliseconds that mentioned in log to match with time in log you might get a different value based your system timezone

EDIT: This is easy approach .but if you need time zone or any other details I think this won't be enough Also See this approach using android api support

Issue with virtualenv - cannot activate

open the folder with any gitbash console. for example using visualCode and Gitbash console program: 1)Install Gitbash for windows

2) using VisualCode IDE, right click over the project open in terminal console option

3) on window console in Visualcode, looking for a Select->default shell and change it for Gitbash

4)now your project is open with bash console and right path, put source ./Scripts/activate

btw : . with blank space = source

enter image description here

MySQL - Select the last inserted row easiest way

In concurrency, the latest record may not be the record you just entered. It may better to get the latest record using the primary key.

If it is a auto increment field, use SELECT LAST_INSERT_ID(); to get the id you just created.

SQL how to make null values come last when sorting ascending

In Oracle, you can use NULLS FIRST or NULLS LAST: specifies that NULL values should be returned before / after non-NULL values:

ORDER BY { column-Name | [ ASC | DESC ] | [ NULLS FIRST | NULLS LAST ] }

For example:

ORDER BY date DESC NULLS LAST

Ref: http://docs.oracle.com/javadb/10.8.3.0/ref/rrefsqlj13658.html

How to get a table cell value using jQuery?

If you can, it might be worth using a class attribute on the TD containing the customer ID so you can write:

$('#mytable tr').each(function() {
    var customerId = $(this).find(".customerIDCell").html();    
 });

Essentially this is the same as the other solutions (possibly because I copy-pasted), but has the advantage that you won't need to change the structure of your code if you move around the columns, or even put the customer ID into a <span>, provided you keep the class attribute with it.

By the way, I think you could do it in one selector:

$('#mytable .customerIDCell').each(function() {
  alert($(this).html());
});

If that makes things easier.

Changing WPF title bar background color

Here's an example on how to achieve this:

    <Grid DockPanel.Dock="Right"
      HorizontalAlignment="Right">

        <StackPanel Orientation="Horizontal"
                HorizontalAlignment="Right"
                VerticalAlignment="Center">

            <Button x:Name="MinimizeButton"
                KeyboardNavigation.IsTabStop="False"
                Click="MinimizeWindow"
                Style="{StaticResource MinimizeButton}" 
                Template="{StaticResource MinimizeButtonControlTemplate}" />

            <Button x:Name="MaximizeButton"
                KeyboardNavigation.IsTabStop="False"
                Click="MaximizeClick"
                Style="{DynamicResource MaximizeButton}" 
                Template="{DynamicResource MaximizeButtonControlTemplate}" />

            <Button x:Name="CloseButton"
                KeyboardNavigation.IsTabStop="False"
                Command="{Binding ApplicationCommands.Close}"
                Style="{DynamicResource CloseButton}" 
                Template="{DynamicResource CloseButtonControlTemplate}"/>

        </StackPanel>
    </Grid>
</DockPanel>

Handle Click Events in the code-behind.

For MouseDown -

App.Current.MainWindow.DragMove();

For Minimize Button -

App.Current.MainWindow.WindowState = WindowState.Minimized;

For DoubleClick and MaximizeClick

if (App.Current.MainWindow.WindowState == WindowState.Maximized)
{
    App.Current.MainWindow.WindowState = WindowState.Normal;
}
else if (App.Current.MainWindow.WindowState == WindowState.Normal)
{
    App.Current.MainWindow.WindowState = WindowState.Maximized;
}

Can (a== 1 && a ==2 && a==3) ever evaluate to true?

Rule number one of interviews; never say impossible.

No need for hidden character trickery.

_x000D_
_x000D_
window.__defineGetter__( 'a', function(){_x000D_
    if( typeof i !== 'number' ){_x000D_
        // define i in the global namespace so that it's not lost after this function runs_x000D_
        i = 0;_x000D_
    }_x000D_
    return ++i;_x000D_
});_x000D_
_x000D_
if( a == 1 && a == 2 && a == 3 ){_x000D_
    alert( 'Oh dear, what have we done?' );_x000D_
}
_x000D_
_x000D_
_x000D_

How do I programmatically change file permissions?

Full control over file attributes is available in Java 7, as part of the "new" New IO facility (NIO.2). For example, POSIX permissions can be set on an existing file with setPosixFilePermissions(), or atomically at file creation with methods like createFile() or newByteChannel().

You can create a set of permissions using EnumSet.of(), but the helper method PosixFilePermissions.fromString() will uses a conventional format that will be more readable to many developers. For APIs that accept a FileAttribute, you can wrap the set of permissions with with PosixFilePermissions.asFileAttribute().

Set<PosixFilePermission> ownerWritable = PosixFilePermissions.fromString("rw-r--r--");
FileAttribute<?> permissions = PosixFilePermissions.asFileAttribute(ownerWritable);
Files.createFile(path, permissions);

In earlier versions of Java, using native code of your own, or exec-ing command-line utilities are common approaches.

ORA-06550: line 1, column 7 (PL/SQL: Statement ignored) Error

If the value stored in PropertyLoader.RET_SECONDARY_V_ARRAY is not "V_ARRAY", then you are using different types; even if they are declared identically (e.g. both are table of number) this will not work.

You're hitting this data type compatibility restriction:

You can assign a collection to a collection variable only if they have the same data type. Having the same element type is not enough.

You're trying to call the procedure with a parameter that is a different type to the one it's expecting, which is what the error message is telling you.

Converting from IEnumerable to List

I use an extension method for this. My extension method first checks to see if the enumeration is null and if so creates an empty list. This allows you to do a foreach on it without explicitly having to check for null.

Here is a very contrived example:

IEnumerable<string> stringEnumerable = null;
StringBuilder csv = new StringBuilder();
stringEnumerable.ToNonNullList().ForEach(str=> csv.Append(str).Append(","));

Here is the extension method:

public static List<T> ToNonNullList<T>(this IEnumerable<T> obj)
{
    return obj == null ? new List<T>() : obj.ToList();
}

What's the name for hyphen-separated case?

It's referred to as kebab-case. See lodash docs.

The R %in% operator

You can use all

> all(1:6 %in% 0:36)
[1] TRUE
> all(1:60 %in% 0:36)
[1] FALSE

On a similar note, if you want to check whether any of the elements is TRUE you can use any

> any(1:6 %in% 0:36)
[1] TRUE
> any(1:60 %in% 0:36)
[1] TRUE
> any(50:60 %in% 0:36)
[1] FALSE

ERROR in ./node_modules/css-loader?

try using

npm rebuild node-sass

How to make picturebox transparent?

I've had a similar problem like this. You can not make Transparent picturebox easily such as picture that shown at top of this page, because .NET Framework and VS .NET objects are created by INHERITANCE! (Use Parent Property).

I solved this problem by RectangleShape and with the below code I removed background, if difference between PictureBox and RectangleShape is not important and doesn't matter, you can use RectangleShape easily.

private void CreateBox(int X, int Y, int ObjectType)
{
    ShapeContainer canvas = new ShapeContainer();
    RectangleShape box = new RectangleShape();
    box.Parent = canvas;
    box.Size = new System.Drawing.Size(100, 90);
    box.Location = new System.Drawing.Point(X, Y);
    box.Name = "Box" + ObjectType.ToString();
    box.BackColor = Color.Transparent;
    box.BorderColor = Color.Transparent;
    box.BackgroundImage = img.Images[ObjectType];// Load from imageBox Or any resource
    box.BackgroundImageLayout = ImageLayout.Stretch;
    box.BorderWidth = 0;
    canvas.Controls.Add(box);   // For feature use 
}

URL Encoding using C#

Edit: Note that this answer is now out of date. See Siarhei Kuchuk's answer below for a better fix

UrlEncoding will do what you are suggesting here. With C#, you simply use HttpUtility, as mentioned.

You can also Regex the illegal characters and then replace, but this gets far more complex, as you will have to have some form of state machine (switch ... case, for example) to replace with the correct characters. Since UrlEncode does this up front, it is rather easy.

As for Linux versus windows, there are some characters that are acceptable in Linux that are not in Windows, but I would not worry about that, as the folder name can be returned by decoding the Url string, using UrlDecode, so you can round trip the changes.

Adding background image to div using CSS

Specify a height and a width:

.header-shadow{
    background-image: url('../images/header-shade.jpg');
    height: 10px;
    width: 10px;
}

How do you declare string constants in C?

There's one more (at least) road to Rome:

static const char HELLO3[] = "Howdy";

(static — optional — is to prevent it from conflicting with other files). I'd prefer this one over const char*, because then you'll be able to use sizeof(HELLO3) and therefore you don't have to postpone till runtime what you can do at compile time.

The define has an advantage of compile-time concatenation, though (think HELLO ", World!") and you can sizeof(HELLO) as well.

But then you can also prefer const char* and use it across multiple files, which would save you a morsel of memory.

In short — it depends.

HTML5 Dynamically create Canvas

It happens because you call it before DOM has loaded. Firstly, create the element and add atrributes to it, then after DOM has loaded call it. In your case it should look like that:

var canvas = document.createElement('canvas');
canvas.id     = "CursorLayer";
canvas.width  = 1224;
canvas.height = 768;
canvas.style.zIndex   = 8;
canvas.style.position = "absolute";
canvas.style.border   = "1px solid";
window.onload = function() {
    document.getElementById("CursorLayer");
}

Use of for_each on map elements

It's unfortunate that you don't have Boost however if your STL implementation has the extensions then you can compose mem_fun_ref and select2nd to create a single functor suitable for use with for_each. The code would look something like this:

#include <algorithm>
#include <map>
#include <ext/functional>   // GNU-specific extension for functor classes missing from standard STL

using namespace __gnu_cxx;  // for compose1 and select2nd

class MyClass
{
public:
    void Method() const;
};

std::map<int, MyClass> Map;

int main(void)
{
    std::for_each(Map.begin(), Map.end(), compose1(std::mem_fun_ref(&MyClass::Method), select2nd<std::map<int, MyClass>::value_type>()));
}

Note that if you don't have access to compose1 (or the unary_compose template) and select2nd, they are fairly easy to write.

Pandas - replacing column values

Yes, you are using it incorrectly, Series.replace() is not inplace operation by default, it returns the replaced dataframe/series, you need to assign it back to your dataFrame/Series for its effect to occur. Or if you need to do it inplace, you need to specify the inplace keyword argument as True Example -

data['sex'].replace(0, 'Female',inplace=True)
data['sex'].replace(1, 'Male',inplace=True)

Also, you can combine the above into a single replace function call by using list for both to_replace argument as well as value argument , Example -

data['sex'].replace([0,1],['Female','Male'],inplace=True)

Example/Demo -

In [10]: data = pd.DataFrame([[1,0],[0,1],[1,0],[0,1]], columns=["sex", "split"])

In [11]: data['sex'].replace([0,1],['Female','Male'],inplace=True)

In [12]: data
Out[12]:
      sex  split
0    Male      0
1  Female      1
2    Male      0
3  Female      1

You can also use a dictionary, Example -

In [15]: data = pd.DataFrame([[1,0],[0,1],[1,0],[0,1]], columns=["sex", "split"])

In [16]: data['sex'].replace({0:'Female',1:'Male'},inplace=True)

In [17]: data
Out[17]:
      sex  split
0    Male      0
1  Female      1
2    Male      0
3  Female      1

Is it possible to access an SQLite database from JavaScript?

Up to date answer

My fork of sql.js has now be merged into the original version, on kriken's repo.

The good documentation is also available on the original repo.

Original answer (outdated)

You should use the newer version of sql.js. It is a port of sqlite 3.8, has a good documentation and is actively maintained (by me). It supports prepared statements, and BLOB data type.

Share cookie between subdomain and domain

Simple solution

setcookie("NAME", "VALUE", time()+3600, '/', EXAMPLE.COM);

Setcookie's 5th parameter determines the (sub)domains that the cookie is available to. Setting it to (EXAMPLE.COM) makes it available to any subdomain (eg: SUBDOMAIN.EXAMPLE.COM )

Reference: http://php.net/manual/en/function.setcookie.php

How to read a text file?

It depends on what you are trying to do.

file, err := os.Open("file.txt")
fmt.print(file)

The reason it outputs &{0xc082016240}, is because you are printing the pointer value of a file-descriptor (*os.File), not file-content. To obtain file-content, you may READ from a file-descriptor.


To read all file content(in bytes) to memory, ioutil.ReadAll

package main

import (
    "fmt"
    "io/ioutil"
    "os"
    "log"
)

func main() {
    file, err := os.Open("file.txt")
    if err != nil {
        log.Fatal(err)
    }
    defer func() {
        if err = f.Close(); err != nil {
            log.Fatal(err)
        }
    }()


  b, err := ioutil.ReadAll(file)
  fmt.Print(b)
}

But sometimes, if the file size is big, it might be more memory-efficient to just read in chunks: buffer-size, hence you could use the implementation of io.Reader.Read from *os.File

func main() {
    file, err := os.Open("file.txt")
    if err != nil {
        log.Fatal(err)
    }
    defer func() {
        if err = f.Close(); err != nil {
            log.Fatal(err)
        }
    }()


    buf := make([]byte, 32*1024) // define your buffer size here.

    for {
        n, err := file.Read(buf)

        if n > 0 {
            fmt.Print(buf[:n]) // your read buffer.
        }

        if err == io.EOF {
            break
        }
        if err != nil {
            log.Printf("read %d bytes: %v", n, err)
            break
        }
    }

}

Otherwise, you could also use the standard util package: bufio, try Scanner. A Scanner reads your file in tokens: separator.

By default, scanner advances the token by newline (of course you can customise how scanner should tokenise your file, learn from here the bufio test).

package main

import (
    "fmt"
    "os"
    "log"
    "bufio"
)

func main() {
    file, err := os.Open("file.txt")
    if err != nil {
        log.Fatal(err)
    }
    defer func() {
        if err = f.Close(); err != nil {
            log.Fatal(err)
        }
    }()

    scanner := bufio.NewScanner(file)

    for scanner.Scan() {             // internally, it advances token based on sperator
        fmt.Println(scanner.Text())  // token in unicode-char
        fmt.Println(scanner.Bytes()) // token in bytes

    }
}

Lastly, I would also like to reference you to this awesome site: go-lang file cheatsheet. It encompassed pretty much everything related to working with files in go-lang, hope you'll find it useful.

TypeError: can't use a string pattern on a bytes-like object in re.findall()

The problem is that your regex is a string, but html is bytes:

>>> type(html)
<class 'bytes'>

Since python doesn't know how those bytes are encoded, it throws an exception when you try to use a string regex on them.

You can either decode the bytes to a string:

html = html.decode('ISO-8859-1')  # encoding may vary!
title = re.findall(pattern, html)  # no more error

Or use a bytes regex:

regex = rb'<title>(,+?)</title>'
#        ^

In this particular context, you can get the encoding from the response headers:

with urllib.request.urlopen(url) as response:
    encoding = response.info().get_param('charset', 'utf8')
    html = response.read().decode(encoding)

See the urlopen documentation for more details.

How to create threads in nodejs

There is also now https://github.com/xk/node-threads-a-gogo, though I'm not sure about project status.

Curl command without using cache

I know this is an older question, but I wanted to post an answer for users with the same question:

curl -H 'Cache-Control: no-cache' http://www.example.com

This curl command servers in its header request to return non-cached data from the web server.

How to create a Restful web service with input parameters?

Be careful. For this you need @GET (not @PUT).

On linux SUSE or RedHat, how do I load Python 2.7

Execute the below commands to make yum work as well as python2.7

yum groupinstall -y development
yum groupinstall -y 'development tools'
yum install -y zlib-dev openssl-devel wget sqlite-devel bzip2-devel
yum -y install gcc gcc-c++ numpy python-devel scipy git boost*
yum install -y *lapack*
yum install -y gcc gcc-c++ make bison flex autoconf libtool memcached libevent libevent-devel uuidd libuuid-devel  boost boost-devel libcurl-dev libcurl curl gperf mysql-devel

cd
mkdir srk
cd srk 
wget http://www.python.org/ftp/python/2.7.6/Python-2.7.6.tar.xz
yum install xz-libs
xz -d Python-2.7.6.tar.xz
tar -xvf Python-2.7.6.tar
cd Python-2.7.6
./configure --prefix=/usr/local
make
make altinstall



echo "export PATH="/usr/local/bin:$PATH"" >> /etc/profile
source /etc/profile
mv /usr/bin/python /usr/bin/python.bak
update-alternatives --install /usr/bin/python python /usr/bin/python2.6 1
update-alternatives --install /usr/bin/python python /usr/local/bin/python2.7 2
update-alternatives --config python
sed -i "s/python/python2.6/g" /usr/bin/yum

"Correct" way to specifiy optional arguments in R functions

how about this?

fun <- function(x, ...){
  y=NULL
  parms=list(...)
  for (name in names(parms) ) {
    assign(name, parms[[name]])
  }
  print(is.null(y))
}

Then try:

> fun(1,y=4)
[1] FALSE
> fun(1)
[1] TRUE

Change the icon of the exe file generated from Visual Studio 2010

To specify an application icon

  1. In Solution Explorer, choose a project node (not the Solution node).
  2. On the menu bar, choose Project, Properties.
  3. When the Project Designer appears, choose the Application tab.
  4. In the Icon list, choose an icon (.ico) file.

To specify an application icon and add it to your project

  1. In Solution Explorer, choose a project node (not the Solution node).
  2. On the menu bar, choose Project, Properties.
  3. When the Project Designer appears, choose the Application tab.
  4. Near the Icon list, choose the button, and then browse to the location of the icon file that you want.

The icon file is added to your project as a content file.

reference : for details see here

How do I iterate through each element in an n-dimensional matrix in MATLAB?

If you look deeper into the other uses of size you can see that you can actually get a vector of the size of each dimension. This link shows you the documentation:

www.mathworks.com/access/helpdesk/help/techdoc/ref/size.html

After getting the size vector, iterate over that vector. Something like this (pardon my syntax since I have not used Matlab since college):

d = size(m);
dims = ndims(m);
for dimNumber = 1:dims
   for i = 1:d[dimNumber]
      ...

Make this into actual Matlab-legal syntax, and I think it would do what you want.

Also, you should be able to do Linear Indexing as described here.

SQL Server stored procedure parameters

Why would you pass a parameter to a stored procedure that doesn't use it?

It sounds to me like you might be better of building dynamic SQL statements and then executing them. What you are trying to do with the SP won't work, and even if you could change what you are doing in such a way to accommodate varying numbers of parameters, you would then essentially be using dynamically generated SQL you are defeating the purpose of having/using a SP in the first place. SP's have a role, but there are not the solution in all cases.

SQL Server Linked Server Example Query

For what it's worth, I found the following syntax to work the best:

SELECT * FROM [LINKED_SERVER]...[TABLE]

I couldn't get the recommendations of others to work, using the database name. Additionally, this data source has no schema.

Generic type conversion FROM string

For many types (integer, double, DateTime etc), there is a static Parse method. You can invoke it using reflection:

MethodInfo m = typeof(T).GetMethod("Parse", new Type[] { typeof(string) } );

if (m != null)
{
    return m.Invoke(null, new object[] { base.Value });
}

Prevent onmouseout when hovering child element of the parent absolute div WITHOUT jQuery

I make it work like a charm with this:

function HideLayer(theEvent){
 var MyDiv=document.getElementById('MyDiv');
 if(MyDiv==(!theEvent?window.event:theEvent.target)){
  MyDiv.style.display='none';
 }
}

Ah, and MyDiv tag is like this:

<div id="MyDiv" onmouseout="JavaScript: HideLayer(event);">
 <!-- Here whatever divs, inputs, links, images, anything you want... -->
<div>

This way, when onmouseout goes to a child, grand-child, etc... the style.display='none' is not executed; but when onmouseout goes out of MyDiv it runs.

So no need to stop propagation, use timers, etc...

Thanks for examples, i could make this code from them.

Hope this helps someone.

Also can be improved like this:

function HideLayer(theLayer,theEvent){
 if(theLayer==(!theEvent?window.event:theEvent.target)){
  theLayer.style.display='none';
 }
}

And then the DIVs tags like this:

<div onmouseout="JavaScript: HideLayer(this,event);">
 <!-- Here whatever divs, inputs, links, images, anything you want... -->
<div>

So more general, not only for one div and no need to add id="..." on each layer.

Could not install Gradle distribution from 'https://services.gradle.org/distributions/gradle-2.1-all.zip'

If you are on Windows, you can go to:

C:\Users\{your_name}\.gradle

And delete all the references of the gradle package you can find in those folders:

  1. caches
  2. daemon
  3. wrapper

Then re-open your project and sync gradle

How to get the file name from a full path using JavaScript?

function getFileName(path, isExtension){

  var fullFileName, fileNameWithoutExtension;

  // replace \ to /
  while( path.indexOf("\\") !== -1 ){
    path = path.replace("\\", "/");
  }

  fullFileName = path.split("/").pop();
  return (isExtension) ? fullFileName : fullFileName.slice( 0, fullFileName.lastIndexOf(".") );
}

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

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

Example on github

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

Store text file content line by line into array

Try this:

String[] arr = new String[3];// if size is fixed otherwise use ArrayList.
int i=0;
while((str = in.readLine()) != null)          
    arr[i++] = str;

System.out.println(Arrays.toString(arr));

Getting one value from a tuple

For anyone in the future looking for an answer, I would like to give a much clearer answer to the question.

# for making a tuple
my_tuple = (89, 32)
my_tuple_with_more_values = (1, 2, 3, 4, 5, 6)

# to concatenate tuples
another_tuple = my_tuple + my_tuple_with_more_values
print(another_tuple)
# (89, 32, 1, 2, 3, 4, 5, 6)

# getting a value from a tuple is similar to a list
first_val = my_tuple[0]
second_val = my_tuple[1]

# if you have a function called my_tuple_fun that returns a tuple,
# you might want to do this
my_tuple_fun()[0]
my_tuple_fun()[1]

# or this
v1, v2 = my_tuple_fun()

Hope this clears things up further for those that need it.

How to add an event after close the modal window?

$('.close').click(function() {
  //Code to be executed when close is clicked
  $('#result').html('yes,result');
});

Adding a tooltip to an input box

It seems to be a bug, it work for all input type that aren't textbox (checkboxes, radio,...)

There is a quick workaround that will work.

<div data-tip="This is the text of the tooltip2">
    <input type="text" name="test" value="44"/>
</div>

JsFiddle

How can strip whitespaces in PHP's variable?

This is an old post but the shortest answer is not listed here so I am adding it now

strtr($str,[' '=>'']);

Another common way to "skin this cat" would be to use explode and implode like this

implode('',explode(' ', $str));

Count number of days between two dates

I kept getting results in seconds, so this worked for me:

(Time.now - self.created_at) / 86400

Spring JPA and persistence.xml

I'm confused. You're injecting a PU into the service layer and not the persistence layer? I don't get that.

I inject the persistence layer into the service layer. The service layer contains business logic and demarcates transaction boundaries. It can include more than one DAO in a transaction.

I don't get the magic in your save() method either. How is the data saved?

In production I configure spring like this:

<jee:jndi-lookup id="entityManagerFactory" jndi-name="persistence/ThePUname" />

along with the reference in web.xml

For unit testing I do this:

<bean id="entityManagerFactory"
    class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
    p:dataSource-ref="dataSource" p:persistence-xml-location="classpath*:META-INF/test-persistence.xml"
    p:persistence-unit-name="RealPUName" p:jpaDialect-ref="jpaDialect"
    p:jpaVendorAdapter-ref="jpaVendorAdapter" p:loadTimeWeaver-ref="weaver">
</bean>

How to implement band-pass Butterworth filter with Scipy.signal.butter

You could skip the use of buttord, and instead just pick an order for the filter and see if it meets your filtering criterion. To generate the filter coefficients for a bandpass filter, give butter() the filter order, the cutoff frequencies Wn=[low, high] (expressed as the fraction of the Nyquist frequency, which is half the sampling frequency) and the band type btype="band".

Here's a script that defines a couple convenience functions for working with a Butterworth bandpass filter. When run as a script, it makes two plots. One shows the frequency response at several filter orders for the same sampling rate and cutoff frequencies. The other plot demonstrates the effect of the filter (with order=6) on a sample time series.

from scipy.signal import butter, lfilter


def butter_bandpass(lowcut, highcut, fs, order=5):
    nyq = 0.5 * fs
    low = lowcut / nyq
    high = highcut / nyq
    b, a = butter(order, [low, high], btype='band')
    return b, a


def butter_bandpass_filter(data, lowcut, highcut, fs, order=5):
    b, a = butter_bandpass(lowcut, highcut, fs, order=order)
    y = lfilter(b, a, data)
    return y


if __name__ == "__main__":
    import numpy as np
    import matplotlib.pyplot as plt
    from scipy.signal import freqz

    # Sample rate and desired cutoff frequencies (in Hz).
    fs = 5000.0
    lowcut = 500.0
    highcut = 1250.0

    # Plot the frequency response for a few different orders.
    plt.figure(1)
    plt.clf()
    for order in [3, 6, 9]:
        b, a = butter_bandpass(lowcut, highcut, fs, order=order)
        w, h = freqz(b, a, worN=2000)
        plt.plot((fs * 0.5 / np.pi) * w, abs(h), label="order = %d" % order)

    plt.plot([0, 0.5 * fs], [np.sqrt(0.5), np.sqrt(0.5)],
             '--', label='sqrt(0.5)')
    plt.xlabel('Frequency (Hz)')
    plt.ylabel('Gain')
    plt.grid(True)
    plt.legend(loc='best')

    # Filter a noisy signal.
    T = 0.05
    nsamples = T * fs
    t = np.linspace(0, T, nsamples, endpoint=False)
    a = 0.02
    f0 = 600.0
    x = 0.1 * np.sin(2 * np.pi * 1.2 * np.sqrt(t))
    x += 0.01 * np.cos(2 * np.pi * 312 * t + 0.1)
    x += a * np.cos(2 * np.pi * f0 * t + .11)
    x += 0.03 * np.cos(2 * np.pi * 2000 * t)
    plt.figure(2)
    plt.clf()
    plt.plot(t, x, label='Noisy signal')

    y = butter_bandpass_filter(x, lowcut, highcut, fs, order=6)
    plt.plot(t, y, label='Filtered signal (%g Hz)' % f0)
    plt.xlabel('time (seconds)')
    plt.hlines([-a, a], 0, T, linestyles='--')
    plt.grid(True)
    plt.axis('tight')
    plt.legend(loc='upper left')

    plt.show()

Here are the plots that are generated by this script:

Frequency response for several filter orders

enter image description here

Blue and Purple Default links, how to remove?

By default link color is blue and the visited color is purple. Also, the text-decoration is underlined and the color is blue. If you want to keep the same color for visited, hover and focus then follow below code-

For example color is: #000

a:visited, a:hover, a:focus {
    text-decoration: none;
    color: #000;
}

If you want to use a different color for hover, visited and focus. For example Hover color: red visited color: green and focus color: yellow then follow below code

   a:hover {
        color: red;
    }
    a:visited {
        color: green;
    }
    a:focus {
        color: yellow;
    }

NB: good practice is to use color code.

What, why or when it is better to choose cshtml vs aspx?

As other people have answered, .cshtml (or .vbhtml if that's your flavor) provides a handler-mapping to load the MVC engine. The .aspx extension simply loads the aspnet_isapi.dll that performs the compile and serves up web forms. The difference in the handler mapping is simply a method of allowing the two to co-exist on the same server allowing both MVC applications and WebForms applications to live under a common root.

This allows http://www.mydomain.com/MyMVCApplication to be valid and served with MVC rules along with http://www.mydomain.com/MyWebFormsApplication to be valid as a standard web form.

Edit:
As for the difference in the technologies, the MVC (Razor) templating framework is intended to return .Net pages to a more RESTful "web-based" platform of templated views separating the code logic between the model (business/data objects), the view (what the user sees) and the controllers (the connection between the two). The WebForms model (aspx) was an attempt by Microsoft to use complex javascript embedding to simulate a more stateful application similar to a WinForms application complete with events and a page lifecycle that would be capable of retaining its own state from page to page.

The choice to use one or the other is always going to be a contentious one because there are arguments for and against both systems. I for one like the simplicity in the MVC architecture (though routing is anything but simple) and the ease of the Razor syntax. I feel the WebForms architecture is just too heavy to be an effective web platform. That being said, there are a lot of instances where the WebForms framework provides a very succinct and usable model with a rich event structure that is well defined. It all boils down to the needs of the application and the preferences of those building it.

How to SHA1 hash a string in Android?

If you can get away with using Guava it is by far the simplest way to do it, and you don't have to reinvent the wheel:

final HashCode hashCode = Hashing.sha1().hashString(yourValue, Charset.defaultCharset());

You can then take the hashed value and get it as a byte[], as an int, or as a long.

No wrapping in a try catch, no shenanigans. And if you decide you want to use something other than SHA-1, Guava also supports sha256, sha 512, and a few I had never even heard about like adler32 and murmur3.

No internet on Android emulator - why and how to fix?

Try launching the Emulator from the command line as follows:

emulator -verbose -avd <AVD name>

This will give you detailed output and may show the error that's preventing the emulator from connecting to the Internet.

Stacking DIVs on top of each other?

style="position:absolute"

Import text file as single character string

It seems your solution is not much ugly. You can use functions and make it proffesional like these ways

  • first way
new.function <- function(filename){
  readChar(filename, file.info(filename)$size)
}

new.function('foo.txt')
  • second way
new.function <- function(){
  filename <- 'foo.txt'
  return (readChar(filename, file.info(filename)$size))
}

new.function()

Python UTC datetime object's ISO format doesn't include Z (Zulu or Zero offset)

Python datetime objects don't have time zone info by default, and without it, Python actually violates the ISO 8601 specification (if no time zone info is given, assumed to be local time). You can use the pytz package to get some default time zones, or directly subclass tzinfo yourself:

from datetime import datetime, tzinfo, timedelta
class simple_utc(tzinfo):
    def tzname(self,**kwargs):
        return "UTC"
    def utcoffset(self, dt):
        return timedelta(0)

Then you can manually add the time zone info to utcnow():

>>> datetime.utcnow().replace(tzinfo=simple_utc()).isoformat()
'2014-05-16T22:51:53.015001+00:00'

Note that this DOES conform to the ISO 8601 format, which allows for either Z or +00:00 as the suffix for UTC. Note that the latter actually conforms to the standard better, with how time zones are represented in general (UTC is a special case.)

Convert and format a Date in JSP

You can do that using the SimpleDateFormat class.

SimpleDateFormat formatter=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

String dates=formatter.format(mydate);
//mydate is your date object

How to get the first word in the string

Don't need a regex. string[: string.find(' ')]

PIL image to array (numpy array to array) - Python

I use numpy.fromiter to invert a 8-greyscale bitmap, yet no signs of side-effects

import Image
import numpy as np

im = Image.load('foo.jpg')
im = im.convert('L')

arr = np.fromiter(iter(im.getdata()), np.uint8)
arr.resize(im.height, im.width)

arr ^= 0xFF  # invert
inverted_im = Image.fromarray(arr, mode='L')
inverted_im.show()

How do I Convert DateTime.now to UTC in Ruby?

In irb:

>>d = DateTime.now
=> #<DateTime: 11783702280454271/4800000000,5/12,2299161>
>> "#{d.hour.to_i - d.zone.to_i}:#{d.min}:#{d.sec}"
=> "11:16:41"

will convert the time to the utc. But as posted if it is just Time you can use:

Time.now.utc

and get it straight away.

MySQL - Selecting data from multiple tables all with same structure but different data

It sounds like you'd be happer with a single table. The five having the same schema, and sometimes needing to be presented as if they came from one table point to putting it all in one table.

Add a new column which can be used to distinguish among the five languages (I'm assuming it's language that is different among the tables since you said it was for localization). Don't worry about having 4.5 million records. Any real database can handle that size no problem. Add the correct indexes, and you'll have no trouble dealing with them as a single table.

How to handle :java.util.concurrent.TimeoutException: android.os.BinderProxy.finalize() timed out after 10 seconds errors?

One thing which is invariably true is that at this time, the device would be suffocating for some memory (which is usually the reason for GC to most likely get triggered).

As mentioned by almost all authors earlier, this issue surfaces when Android tries to run GC while the app is in background. In most of the cases where we observed it, user paused the app by locking their screen. This might also indicate memory leak somewhere in the application, or the device being too loaded already. So the only legitimate way to minimize it is:

  • to ensure there are no memory leaks, and
  • to reduce the memory footprint of the app in general.

Remove all special characters, punctuation and spaces from string

Differently than everyone else did using regex, I would try to exclude every character that is not what I want, instead of enumerating explicitly what I don't want.

For example, if I want only characters from 'a to z' (upper and lower case) and numbers, I would exclude everything else:

import re
s = re.sub(r"[^a-zA-Z0-9]","",s)

This means "substitute every character that is not a number, or a character in the range 'a to z' or 'A to Z' with an empty string".

In fact, if you insert the special character ^ at the first place of your regex, you will get the negation.

Extra tip: if you also need to lowercase the result, you can make the regex even faster and easier, as long as you won't find any uppercase now.

import re
s = re.sub(r"[^a-z0-9]","",s.lower())

How can I create basic timestamps or dates? (Python 3.4)

>>> import time
>>> print(time.strftime('%a %H:%M:%S'))
Mon 06:23:14

What does the Excel range.Rows property really do?

I'm not sure, but I think the second parameter is a red herring.

Both .Rows and .Columns take two optional parameters: RowIndex and ColumnIndex. Try to use ColumnIndex, e.g. Rows(ColumnIndex:=2), generates an error for both .Rows and .Columns.

My feeling it's inherited in some sense from the Cells(RowIndex,ColumnIndex) Property but only the first parameter is appropriate.

Python 3 - ValueError: not enough values to unpack (expected 3, got 2)

Since unpaidMembers is a dictionary it always returns two values when called with .items() - (key, value). You may want to keep your data as a list of tuples [(name, email, lastname), (name, email, lastname)..].

Datetime format Issue: String was not recognized as a valid DateTime

You can use DateTime.ParseExact() method.

Converts the specified string representation of a date and time to its DateTime equivalent using the specified format and culture-specific format information. The format of the string representation must match the specified format exactly.

DateTime date = DateTime.ParseExact("04/30/2013 23:00", 
                                    "MM/dd/yyyy HH:mm", 
                                    CultureInfo.InvariantCulture);

Here is a DEMO.

hh is for 12-hour clock from 01 to 12, HH is for 24-hour clock from 00 to 23.

For more information, check Custom Date and Time Format Strings

Disable Rails SQL logging in console

To turn it off:

old_logger = ActiveRecord::Base.logger
ActiveRecord::Base.logger = nil

To turn it back on:

ActiveRecord::Base.logger = old_logger

How to compile and run C/C++ in a Unix console/Mac terminal?

For running c++ files run below command, Assuming file name is "main.cpp"

1.Compile to make object file from c++ file.

g++ -c main.cpp -o main.o

2.Since #include <conio.h> does not support in MacOS so we should use its alternative which supports in Mac that is #include <curses.h>. Now object file needs to be converted to executable file. To use curses.h we have to use library -lcurses.

g++ -o main main.o -lcurses

3.Now run the executable.

./main

Mockito How to mock only the call of a method of the superclass

Consider refactoring the code from ChildService.save() method to different method and test that new method instead of testing ChildService.save(), this way you will avoid unnecessary call to super method.

Example:

class BaseService {  
    public void save() {...}  
}

public Childservice extends BaseService {  
    public void save(){  
        newMethod();    
        super.save();
    }
    public void newMethod(){
       //some codes
    }
} 

Simple JavaScript problem: onClick confirm not preventing default action

Using a simple link for an action such as removing a record looks dangerous to me : what if a crawler is trying to index your pages ? It will ignore any javascript and follow every link, probably not a good thing.

You'd better use a form with method="POST".

And then you will have an event "OnSubmit" to do exactly what you want...

Javascript onclick hide div

HTML

<div id='hideme'><strong>Warning:</strong>These are new products<a href='#' class='close_notification' title='Click to Close'><img src="images/close_icon.gif" width="6" height="6" alt="Close" onClick="hide('hideme')" /></a

Javascript:

function hide(obj) {

    var el = document.getElementById(obj);

        el.style.display = 'none';

}

Angular2 Exception: Can't bind to 'routerLink' since it isn't a known native property

Word of caution when coding with Visual Studio (2013)

I have wasted 4 to 5 hours trying to debug this error. I tried all the solutions that I found on StackOverflow by the letter and I still got this error: Can't bind to 'routerlink' since it isn't a known native property

Be aware, Visual Studio has the nasty habit of autoformatting text when you copy/paste code. I always got a small instantaneous adjustment from VS13 (camel case disappears).

This:

<div>
    <a [routerLink]="['/catalog']">Catalog</a>
    <a [routerLink]="['/summary']">Summary</a>
</div>

Becomes:

<div>
    <a [routerlink]="['/catalog']">Catalog</a>
    <a [routerlink]="['/summary']">Summary</a>
</div>

It's a small difference, but enough to trigger the error. The ugliest part is that this small difference just kept avoiding my attention every time I copied and pasted. By sheer chance, I saw this small difference and solved it.

Android ListView Text Color

You can do this in your code:

final ListView lv = (ListView) convertView.findViewById(R.id.list_view);

for (int i = 0; i < lv.getChildCount(); i++) {
    ((TextView)lv.getChildAt(i)).setTextColor(getResources().getColor(R.color.black));
}

How to convert std::chrono::time_point to calendar datetime string with fractional seconds?

This worked for me for a format like YYYY.MM.DD-HH.MM.SS.fff. Attempting to make this code capable of accepting any string format will be like reinventing the wheel (i.e. there are functions for all this in Boost.

std::chrono::system_clock::time_point string_to_time_point(const std::string &str)
{
    using namespace std;
    using namespace std::chrono;

    int yyyy, mm, dd, HH, MM, SS, fff;

    char scanf_format[] = "%4d.%2d.%2d-%2d.%2d.%2d.%3d";

    sscanf(str.c_str(), scanf_format, &yyyy, &mm, &dd, &HH, &MM, &SS, &fff);

    tm ttm = tm();
    ttm.tm_year = yyyy - 1900; // Year since 1900
    ttm.tm_mon = mm - 1; // Month since January 
    ttm.tm_mday = dd; // Day of the month [1-31]
    ttm.tm_hour = HH; // Hour of the day [00-23]
    ttm.tm_min = MM;
    ttm.tm_sec = SS;

    time_t ttime_t = mktime(&ttm);

    system_clock::time_point time_point_result = std::chrono::system_clock::from_time_t(ttime_t);

    time_point_result += std::chrono::milliseconds(fff);
    return time_point_result;
}

std::string time_point_to_string(std::chrono::system_clock::time_point &tp)
{
    using namespace std;
    using namespace std::chrono;

    auto ttime_t = system_clock::to_time_t(tp);
    auto tp_sec = system_clock::from_time_t(ttime_t);
    milliseconds ms = duration_cast<milliseconds>(tp - tp_sec);

    std::tm * ttm = localtime(&ttime_t);

    char date_time_format[] = "%Y.%m.%d-%H.%M.%S";

    char time_str[] = "yyyy.mm.dd.HH-MM.SS.fff";

    strftime(time_str, strlen(time_str), date_time_format, ttm);

    string result(time_str);
    result.append(".");
    result.append(to_string(ms.count()));

    return result;
}

Keep-alive header clarification

Where is this info kept ("this connection is between computer A and server F")?

A TCP connection is recognized by source IP and port and destination IP and port. Your OS, all intermediate session-aware devices and the server's OS will recognize the connection by this.

HTTP works with request-response: client connects to server, performs a request and gets a response. Without keep-alive, the connection to an HTTP server is closed after each response. With HTTP keep-alive you keep the underlying TCP connection open until certain criteria are met.

This allows for multiple request-response pairs over a single TCP connection, eliminating some of TCP's relatively slow connection startup.

When The IIS (F) sends keep alive header (or user sends keep-alive) , does it mean that (E,C,B) save a connection

No. Routers don't need to remember sessions. In fact, multiple TCP packets belonging to same TCP session need not all go through same routers - that is for TCP to manage. Routers just choose the best IP path and forward packets. Keep-alive is only for client, server and any other intermediate session-aware devices.

which is only for my session ?

Does it mean that no one else can use that connection

That is the intention of TCP connections: it is an end-to-end connection intended for only those two parties.

If so - does it mean that keep alive-header - reduce the number of overlapped connection users ?

Define "overlapped connections". See HTTP persistent connection for some advantages and disadvantages, such as:

  • Lower CPU and memory usage (because fewer connections are open simultaneously).
  • Enables HTTP pipelining of requests and responses.
  • Reduced network congestion (fewer TCP connections).
  • Reduced latency in subsequent requests (no handshaking).

if so , for how long does the connection is saved to me ? (in other words , if I set keep alive- "keep" till when?)

An typical keep-alive response looks like this:

Keep-Alive: timeout=15, max=100

See Hypertext Transfer Protocol (HTTP) Keep-Alive Header for example (a draft for HTTP/2 where the keep-alive header is explained in greater detail than both 2616 and 2086):

  • A host sets the value of the timeout parameter to the time that the host will allows an idle connection to remain open before it is closed. A connection is idle if no data is sent or received by a host.

  • The max parameter indicates the maximum number of requests that a client will make, or that a server will allow to be made on the persistent connection. Once the specified number of requests and responses have been sent, the host that included the parameter could close the connection.

However, the server is free to close the connection after an arbitrary time or number of requests (just as long as it returns the response to the current request). How this is implemented depends on your HTTP server.

Looping through a DataTable

If you want to change the contents of each and every cell in a datatable then we need to Create another Datatable and bind it as follows using "Import Row". If we don't create another table it will throw an Exception saying "Collection was Modified".

Consider the following code.

//New Datatable created which will have updated cells
DataTable dtUpdated = new DataTable();

//This gives similar schema to the new datatable
dtUpdated = dtReports.Clone();
foreach (DataRow row in dtReports.Rows)
{
    for (int i = 0; i < dtReports.Columns.Count; i++)
    {
        string oldVal = row[i].ToString();
        string newVal = "{"+oldVal;
        row[i] = newVal;
    }
    dtUpdated.ImportRow(row); 
}

This will have all the cells preceding with Paranthesis({)

Subtract two dates in Java

Assuming that you're constrained to using Date, you can do the following:

Date diff = new Date(d2.getTime() - d1.getTime());

Here you're computing the differences in milliseconds since the "epoch", and creating a new Date object at an offset from the epoch. Like others have said: the answers in the duplicate question are probably better alternatives (if you aren't tied down to Date).

Difference between Select Unique and Select Distinct

SELECT UNIQUE is old syntax supported by Oracle's flavor of SQL. It is synonymous with SELECT DISTINCT.

Use SELECT DISTINCT because this is standard SQL, and SELECT UNIQUE is non-standard, and in database brands other than Oracle, SELECT UNIQUE may not be recognized at all.

Anaconda Navigator won't launch (windows 10)

So none of the above answers worked for me.

I performed the following steps in order to make it work for me : OS : Windows 10 Home 64 Bit

Open Anaconda Prompt

conda remove anaconda-navigator
conda install anaconda-navigator

conda install -c anaconda pywin32 // Had to install since I got a module not found error // with just the above two commands

And it worked for me!!

What does 'super' do in Python?

Consider the following code:

class X():
    def __init__(self):
        print("X")

class Y(X):
    def __init__(self):
        # X.__init__(self)
        super(Y, self).__init__()
        print("Y")

class P(X):
    def __init__(self):
        super(P, self).__init__()
        print("P")

class Q(Y, P):
    def __init__(self):
        super(Q, self).__init__()
        print("Q")

Q()

If change constructor of Y to X.__init__, you will get:

X
Y
Q

But using super(Y, self).__init__(), you will get:

X
P
Y
Q

And P or Q may even be involved from another file which you don't know when you writing X and Y. So, basically, you won't know what super(Child, self) will reference to when you are writing class Y(X), even the signature of Y is as simple as Y(X). That's why super could be a better choice.

Questions every good PHP Developer should be able to answer

Why you should never output user input directly!

Printing things like data from GET directly can lead to Cross-site scripting (XSS) vulnerabilities. Thats why you should always send input from the client through htmlspecialchars() first.

Updating property value in properties file without deleting other values

Properties prop = new Properties();
prop.load(...); // FileInputStream 
prop.setProperty("key", "value");
prop.store(...); // FileOutputStream 

.NET String.Format() to add commas in thousands place for a number

This is the best format. Works in all of those cases:

String.Format( "{0:#,##0.##}", 0 ); // 0
String.Format( "{0:#,##0.##}", 0.5 ); // 0.5 - some of the formats above fail here. 
String.Format( "{0:#,##0.##}", 12314 ); // 12,314
String.Format( "{0:#,##0.##}", 12314.23123 ); // 12,314.23
String.Format( "{0:#,##0.##}", 12314.2 ); // 12,314.2
String.Format( "{0:#,##0.##}", 1231412314.2 ); // 1,231,412,314.2

Chart.js v2 - hiding grid lines

OK, nevermind.. I found the trick:

    scales: {
      yAxes: [
        {
          gridLines: {
                lineWidth: 0
            }
        }
      ]
    }

How to find index of all occurrences of element in array?

You can write a simple readable solution to this by using both map and filter:

const nanoIndexes = Cars
  .map((car, i) => car === 'Nano' ? i : -1)
  .filter(index => index !== -1);

EDIT: If you don't need to support IE/Edge (or are transpiling your code), ES2019 gave us flatMap, which lets you do this in a simple one-liner:

const nanoIndexes = Cars.flatMap((car, i) => car === 'Nano' ? i : []);

If strings starts with in PowerShell

$Group is an object, but you will actually need to check if $Group.samaccountname.StartsWith("string").

Change $Group.StartsWith("S_G_") to $Group.samaccountname.StartsWith("S_G_").

How to animate GIFs in HTML document?

Agreed with Yuri Tkachenko's answer.

I wanna point this out.

It's a pretty specific scenario. BUT it happens.

When you copy a gif before its loaded fully in some site like google images. it just gives the preview image address of that gif. Which is clearly not a gif.

So, make sure it ends with .gif extension

getting a checkbox array value from POST

// if you do the input like this
<input id="'.$userid.'" value="'.$userid.'"  name="invite['.$userid.']" type="checkbox">

// you can access the value directly like this:
$invite = $_POST['invite'][$userid];

Fork() function in C

I think every process you make start executing the line you create so something like this...

pid=fork() at line 6. fork function returns 2 values 
you have 2 pids, first pid=0 for child and pid>0 for parent 
so you can use if to separate

.

/*
    sleep(int time) to see clearly
    <0 fail 
    =0 child
    >0 parent
*/
int main(int argc, char** argv) {
    pid_t childpid1, childpid2;
    printf("pid = process identification\n");
    printf("ppid = parent process identification\n");
    childpid1 = fork();
    if (childpid1 == -1) {
        printf("Fork error !\n");
    }
    if (childpid1 == 0) {
        sleep(1);
        printf("child[1] --> pid = %d and  ppid = %d\n",
                getpid(), getppid());
    } else {
        childpid2 = fork();
        if (childpid2 == 0) {
            sleep(2);
            printf("child[2] --> pid = %d and ppid = %d\n",
                    getpid(), getppid());
        } else {
            sleep(3);
            printf("parent --> pid = %d\n", getpid());
        }
    }
    return 0;
}

//pid = process identification
//ppid = parent process identification
//child[1] --> pid = 2399 and  ppid = 2398
//child[2] --> pid = 2400 and ppid = 2398
//parent --> pid = 2398

linux.die.net

some uni stuff

How to make a phone call programmatically?

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main); 
   final Button button = (Button) findViewById(R.id.btn_call);
    button.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            String mobileNo = "123456789";
            String uri = "tel:" + mobileNo.trim();
            Intent intent = new Intent(Intent.ACTION_CALL);
            intent.setData(Uri.parse(uri));
            startActivity(intent);
        }
    });*
 }

ajax jquery simple get request

It seems to me, this is a cross-domain issue since you're not allowed to make a request to a different domain.

You have to find solutions to this problem: - Use a proxy script, running on your server that will forward your request and will handle the response sending it to the browser Or - The service you're making the request should have JSONP support. This is a cross-domain technique. You might want to read this http://en.wikipedia.org/wiki/JSONP

Zsh: Conda/Pip installs command not found

You should do the following:
1. /home/$USER/anaconda/bin/conda init zsh (or /home/$USER/miniconda3/bin/conda init zsh if you use miniconda)
2. source ~/.zshrc (or just reopen terminal)

Why this answer is better than others?

  • You shouldn't reinvent the wheel: there is already command in conda to activate, all you need to do is to call conda with full path
  • Maybe ~/.bash_profile doesn't exist (my case, only ~/.bashrc)
  • You can have bash-specific config inside ~/.bash_profile
  • You don't need manually paste and export any pathes

How do I count columns of a table

this query may help you

SELECT COUNT(COLUMN_NAME) FROM INFORMATION_SCHEMA.COLUMNS WHERE 
TABLE_CATALOG = 'database' AND TABLE_SCHEMA = 'dbo'
AND TABLE_NAME = 'tbl_ifo'

How do I use typedef and typedef enum in C?

typedef defines a new data type. So you can have:

typedef char* my_string;
typedef struct{
  int member1;
  int member2;
} my_struct;

So now you can declare variables with these new data types

my_string s;
my_struct x;

s = "welcome";
x.member1 = 10;

For enum, things are a bit different - consider the following examples:

enum Ranks {FIRST, SECOND};
int main()
{
   int data = 20;
   if (data == FIRST)
   {
      //do something
   }
}

using typedef enum creates an alias for a type:

typedef enum Ranks {FIRST, SECOND} Order;
int main()
{
   Order data = (Order)20;  // Must cast to defined type to prevent error

   if (data == FIRST)
   {
      //do something
   }
}

Is there a way to add/remove several classes in one single instruction with classList?

To add class to a element

document.querySelector(elem).className+=' first second third';

UPDATE:

Remove a class

document.querySelector(elem).className=document.querySelector(elem).className.split(class_to_be_removed).join(" ");

How to check if image exists with given url?

Use Case

$('#myImg').safeUrl({wanted:"http://example/nature.png",rm:"/myproject/images/anonym.png"});

API :

$.fn.safeUrl=function(args){
  var that=this;
  if($(that).attr('data-safeurl') && $(that).attr('data-safeurl') === 'found'){
        return that;
  }else{
       $.ajax({
    url:args.wanted,
    type:'HEAD',
    error:
        function(){
            $(that).attr('src',args.rm)
        },
    success:
        function(){
             $(that).attr('src',args.wanted)
             $(that).attr('data-safeurl','found');
        }
      });
   }


 return that;
};

Note : rm means here risk managment .


Another Use Case :

$('#myImg').safeUrl({wanted:"http://example/1.png",rm:"http://example/2.png"})
.safeUrl({wanted:"http://example/2.png",rm:"http://example/3.png"});
  • 'http://example/1.png' : if not exist 'http://example/2.png'

  • 'http://example/2.png' : if not exist 'http://example/3.png'

SyntaxError of Non-ASCII character

You should define source code encoding, add this to the top of your script:

# -*- coding: utf-8 -*-

The reason why it works differently in console and in the IDE is, likely, because of different default encodings set. You can check it by running:

import sys
print sys.getdefaultencoding()

Also see:

Exception in thread "main" java.lang.UnsupportedClassVersionError: a (Unsupported major.minor version 51.0)

Copy the contents of the PATH settings to a notepad and check if the location for the 1.4.2 comes before that of the 7. If so, remove the path to 1.4.2 in the PATH setting and save it.

After saving and applying "Environment Variables" close and reopen the cmd line. In XP the path does no get reflected in already running programs.

How to filter WooCommerce products by custom attribute

You can use WooCommerce AJAX Product Filter. You can also watch how the plugin is used for product filtering.

Here is a screenshot:

enter image description here

Tree view of a directory/folder in Windows?

If it is just viewing in tree view,One workaround is to use the Explorer in Notepad++ or any other tools.

Submit form after calling e.preventDefault()

$('form').submit(function(e){

    var submitAllow = true;

    // Cycle through each Attendee Name
    $('[name="atendeename[]"]', this).each(function(index, el){

        // If there is a value
        if ($(el).val()) {

            // Find adjacent entree input
            var entree = $(el).next('input');

            // If entree is empty, don't submit form
            if ( ! entree.val()) {
                alert('Please select an entree');
                entree.focus();
                submitAllow = false;
                return false;
            }
        }
    });

    return submitAllow;

});

Virtual Serial Port for Linux

Using the links posted in the previous answers, I coded a little example in C++ using a Virtual Serial Port. I pushed the code into GitHub: https://github.com/cymait/virtual-serial-port-example .

The code is pretty self explanatory. First, you create the master process by running ./main master and it will print to stderr the device is using. After that, you invoke ./main slave device, where device is the device printed in the first command.

And that's it. You have a bidirectional link between the two process.

Using this example you can test you the application by sending all kind of data, and see if it works correctly.

Also, you can always symlink the device, so you don't need to re-compile the application you are testing.

How can I convert a series of images to a PDF from the command line on linux?

Use convert from http://www.imagemagick.org. (Readily supplied as a package in most Linux distributions.)

Getting return value from stored procedure in C#

When you use

cmd.Parameters.Add("@RETURN_VALUE", SqlDbType.Int).Direction = ParameterDirection.ReturnValue;

you must then ensure your stored procedure has

return @RETURN_VALUE;

at the end of the stored procedure.

How to get the caller's method name in the called method?

I found a way if you're going across classes and want the class the method belongs to AND the method. It takes a bit of extraction work but it makes its point. This works in Python 2.7.13.

import inspect, os

class ClassOne:
    def method1(self):
        classtwoObj.method2()

class ClassTwo:
    def method2(self):
        curframe = inspect.currentframe()
        calframe = inspect.getouterframes(curframe, 4)
        print '\nI was called from', calframe[1][3], \
        'in', calframe[1][4][0][6: -2]

# create objects to access class methods
classoneObj = ClassOne()
classtwoObj = ClassTwo()

# start the program
os.system('cls')
classoneObj.method1()

Which variable size to use (db, dw, dd) with x86 assembly?

Quick review,

  • DB - Define Byte. 8 bits
  • DW - Define Word. Generally 2 bytes on a typical x86 32-bit system
  • DD - Define double word. Generally 4 bytes on a typical x86 32-bit system

From x86 assembly tutorial,

The pop instruction removes the 4-byte data element from the top of the hardware-supported stack into the specified operand (i.e. register or memory location). It first moves the 4 bytes located at memory location [SP] into the specified register or memory location, and then increments SP by 4.

Your num is 1 byte. Try declaring it with DD so that it becomes 4 bytes and matches with pop semantics.

Which keycode for escape key with jQuery

Just posting an updated answer than e.keyCode is considered DEPRECATED on MDN.

Rather you should opt for e.key instead which supports clean names for everything. Here is the relevant copy pasta

window.addEventListener("keydown", function (event) {
  if (event.defaultPrevented) {
    return; // Do nothing if the event was already processed
  }

  switch (event.key) {
    case "ArrowDown":
      // Do something for "down arrow" key press.
      break;
    case "ArrowUp":
      // Do something for "up arrow" key press.
      break;
    case "ArrowLeft":
      // Do something for "left arrow" key press.
      break;
    case "ArrowRight":
      // Do something for "right arrow" key press.
      break;
    case "Enter":
      // Do something for "enter" or "return" key press.
      break;
    case "Escape":
      // Do something for "esc" key press.
      break;
    default:
      return; // Quit when this doesn't handle the key event.
  }

  // Cancel the default action to avoid it being handled twice
  event.preventDefault();
}, true);

django: TypeError: 'tuple' object is not callable

You're missing comma (,) inbetween:

>>> ((1,2) (2,3))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object is not callable

Put comma:

>>> ((1,2), (2,3))
((1, 2), (2, 3))

Getting the inputstream from a classpath resource (XML file)

ClassLoader.class.getResourceAsStream("/path/to/your/xml") and make sure that your compile script is copying the xml file to where in your CLASSPATH.

Bash foreach loop

You'll probably want to handle spaces in your file names, abhorrent though they are :-)

So I would opt initially for something like:

pax> cat qq.in
normalfile.txt
file with spaces.doc

pax> sed 's/ /\\ /g' qq.in | xargs -n 1 cat
<<contents of 'normalfile.txt'>>
<<contents of 'file with spaces.doc'>>

pax> _

JavaScript inside an <img title="<a href='#' onClick='alert('Hello World!')>The Link</a>" /> possible?

When you click on the image you'll get the alert:

<img src="logo1.jpg" onClick='alert("Hello World!")'/>

if this is what you want.

Make code in LaTeX look *nice*

For simple document, I sometimes use verbatim, but listing is nice for big chunk of code.

How to trigger a click on a link using jQuery

You should call the element's native .click() method or use the createEvent API.

For more info, please visit: https://learn.jquery.com/events/triggering-event-handlers/

MVC web api: No 'Access-Control-Allow-Origin' header is present on the requested resource

That problem happens when you try to access from a different domain or different port.

If you're using Visual Studio, then go to Tools > NuGet Package Manager > Package Manager Console. There you have to install the NuGet Package Microsoft.AspNet.WebApi.Cors

Install-Package Microsoft.AspNet.WebApi.Cors

Then, in PROJECT > App_Start > WebApiConfig, enable CORS

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        
        //Enable CORS. Note that the domain doesn't have / in the end.
        config.EnableCors(new EnableCorsAttribute("https://tiagoperes.eu",headers:"*",methods:"*"));

        ....

    }
}

Once installed successfully, build the solution and that should suffice

Convert base64 string to ArrayBuffer

Pure JS - no string middlestep (no atob)

I write following function which convert base64 in direct way (without conversion to string at the middlestep). IDEA

  • get 4 base64 characters chunk
  • find index of each character in base64 alphabet
  • convert index to 6-bit number (binary string)
  • join four 6 bit numbers which gives 24-bit numer (stored as binary string)
  • split 24-bit string to three 8-bit and covert each to number and store them in output array
  • corner case: if input base64 string ends with one/two = char, remove one/two numbers from output array

Below solution allows to process large input base64 strings. Similar function for convert bytes to base64 without btoa is HERE

_x000D_
_x000D_
function base64ToBytesArr(str) {
  const abc = [..."ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"]; // base64 alphabet
  let result = [];

  for(let i=0; i<str.length/4; i++) {
    let chunk = [...str.slice(4*i,4*i+4)]
    let bin = chunk.map(x=> abc.indexOf(x).toString(2).padStart(6,0)).join(''); 
    let bytes = bin.match(/.{1,8}/g).map(x=> +('0b'+x));
    result.push(...bytes.slice(0,3 - (str[4*i+2]=="=") - (str[4*i+3]=="=")));
  }
  return result;
}


// --------
// TEST
// --------


let test = "Alice's Adventure in Wonderland.";  

console.log('test string:', test.length, test);
let b64_btoa = btoa(test);
console.log('encoded string:', b64_btoa);

let decodedBytes = base64ToBytesArr(b64_btoa); // decode base64 to array of bytes
console.log('decoded bytes:', JSON.stringify(decodedBytes));
let decodedTest = decodedBytes.map(b => String.fromCharCode(b) ).join``;
console.log('Uint8Array', JSON.stringify(new Uint8Array(decodedBytes)));
console.log('decoded string:', decodedTest.length, decodedTest);
_x000D_
_x000D_
_x000D_

The localhost page isn’t working localhost is currently unable to handle this request. HTTP ERROR 500

Such kind of error normally happens when you try using functions like php_info() wrongly.

<?php 
     php_info(); // 500 error
     phpinfo(); // Works correctly
?>

A close look at your code will be better.

How can I find the maximum value and its index in array in MATLAB?

You can use max() to get the max value. The max function can also return the index of the maximum value in the vector. To get this, assign the result of the call to max to a two element vector instead of just a single variable.

e.g. z is your array,

>> [x, y] = max(z)

x =

7

y =

4

Here, 7 is the largest number at the 4th position(index).

How to detect Adblock on my website?

http://thepcspy.com/read/how_to_block_adblock/

With jQuery:

function blockAdblockUser() {
    if ($('.myTestAd').height() == 0) {
        window.location = 'http://example.com/AdblockNotice.html';
    }
}

$(document).ready(function(){
    blockAdblockUser();
});

Of course, you would need to have a landing page for AdblockNotice.html, and the .myTestAd class needs to reflect your actual ad containers. But this should work.

EDIT

As TD_Nijboer recommends, a better way is to use the :hidden (or :visible, as I use below) selector so that display: none is also checked:

function blockAdblockUser() {
    if ($('.myTestAd').filter(':visible').length == 0) {
        // All are hidden, or "not visible", so:
        // Redirect, show dialog, do something...
    } else if ($('.myTestAd').filter(':hidden').length > 0) {
        // Maybe a different error if only some are hidden?
        // Redirect, show dialog, do something...
    }
}

Of course, both of these could be combined into one if block if desired.

Note that visibility: hidden will not be captured by either as well (where the layout space stays, but the ad is not visible). To check that, another filter can be used:

$('.myTestAd').filter(function fi(){
    return $(this).css('visibility') == 'hidden';
})

Which will give you an array of ad elements which are "invisible" (with any being greater than 0 being a problem, in theory).

Difference between View and Request scope in managed beans

A @ViewScoped bean lives exactly as long as a JSF view. It usually starts with a fresh new GET request, or with a navigation action, and will then live as long as the enduser submits any POST form in the view to an action method which returns null or void (and thus navigates back to the same view). Once you refresh the page, or return a non-null string (even an empty string!) navigation outcome, then the view scope will end.

A @RequestScoped bean lives exactly as long a HTTP request. It will thus be garbaged by end of every request and recreated on every new request, hereby losing all changed properties.

A @ViewScoped bean is thus particularly more useful in rich Ajax-enabled views which needs to remember the (changed) view state across Ajax requests. A @RequestScoped one would be recreated on every Ajax request and thus fail to remember all changed view state. Note that a @ViewScoped bean does not share any data among different browser tabs/windows in the same session like as a @SessionScoped bean. Every view has its own unique @ViewScoped bean.

See also:

How to connect with Java into Active Directory

Here is a simple code that authenticate and make an LDAP search usin JNDI on a W2K3 :

class TestAD
{
  static DirContext ldapContext;
  public static void main (String[] args) throws NamingException
  {
    try
    {
      System.out.println("Début du test Active Directory");

      Hashtable<String, String> ldapEnv = new Hashtable<String, String>(11);
      ldapEnv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
      //ldapEnv.put(Context.PROVIDER_URL,  "ldap://societe.fr:389");
      ldapEnv.put(Context.PROVIDER_URL,  "ldap://dom.fr:389");
      ldapEnv.put(Context.SECURITY_AUTHENTICATION, "simple");
      //ldapEnv.put(Context.SECURITY_PRINCIPAL, "cn=administrateur,cn=users,dc=societe,dc=fr");
      ldapEnv.put(Context.SECURITY_PRINCIPAL, "cn=jean paul blanc,ou=MonOu,dc=dom,dc=fr");
      ldapEnv.put(Context.SECURITY_CREDENTIALS, "pwd");
      //ldapEnv.put(Context.SECURITY_PROTOCOL, "ssl");
      //ldapEnv.put(Context.SECURITY_PROTOCOL, "simple");
      ldapContext = new InitialDirContext(ldapEnv);

      // Create the search controls         
      SearchControls searchCtls = new SearchControls();

      //Specify the attributes to return
      String returnedAtts[]={"sn","givenName", "samAccountName"};
      searchCtls.setReturningAttributes(returnedAtts);

      //Specify the search scope
      searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);

      //specify the LDAP search filter
      String searchFilter = "(&(objectClass=user))";

      //Specify the Base for the search
      String searchBase = "dc=dom,dc=fr";
      //initialize counter to total the results
      int totalResults = 0;

      // Search for objects using the filter
      NamingEnumeration<SearchResult> answer = ldapContext.search(searchBase, searchFilter, searchCtls);

      //Loop through the search results
      while (answer.hasMoreElements())
      {
        SearchResult sr = (SearchResult)answer.next();

        totalResults++;

        System.out.println(">>>" + sr.getName());
        Attributes attrs = sr.getAttributes();
        System.out.println(">>>>>>" + attrs.get("samAccountName"));
      }

      System.out.println("Total results: " + totalResults);
      ldapContext.close();
    }
    catch (Exception e)
    {
      System.out.println(" Search error: " + e);
      e.printStackTrace();
      System.exit(-1);
    }
  }
}

How can I see the specific value of the sql_mode?

It's only blank for you because you have not set the sql_mode. If you set it, then that query will show you the details:

mysql> SELECT @@sql_mode;
+------------+
| @@sql_mode |
+------------+
|            |
+------------+
1 row in set (0.00 sec)

mysql> set sql_mode=ORACLE;
Query OK, 0 rows affected (0.00 sec)

mysql> SELECT @@sql_mode;
+----------------------------------------------------------------------------------------------------------------------+
| @@sql_mode                                                                                                           |
+----------------------------------------------------------------------------------------------------------------------+
| PIPES_AS_CONCAT,ANSI_QUOTES,IGNORE_SPACE,ORACLE,NO_KEY_OPTIONS,NO_TABLE_OPTIONS,NO_FIELD_OPTIONS,NO_AUTO_CREATE_USER |
+----------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

Select top 10 records for each category

If you know what the sections are, you can do:

select top 10 * from table where section=1
union
select top 10 * from table where section=2
union
select top 10 * from table where section=3

SQL Query To Obtain Value that Occurs more than once

I think this answer can also work (it may require a little bit of modification though) :

SELECT * FROM Students AS S1 WHERE EXISTS(SELECT Lastname, count(*) FROM Students AS S2 GROUP BY Lastname HAVING COUNT(*) > 3 WHERE S2.Lastname = S1.Lastname)

How to set up subdomains on IIS 7

As DotNetMensch said but you DO NOT need to add another site in IIS as this can also cause further problems and make things more complicated because you then have a website within a website so the file paths, masterpage paths and web.config paths may need changing. You just need to edit teh bindings of the existing site and add the new subdomain there.

So:

  1. Add sub-domain to DNS records. My host (RackSpace) uses a web portal to do this so you just log in and go to Network->Domains(DNS)->Actions->Create Zone, and enter your subdomain as mysubdomain.domain.com etc, leave the other settings as default

  2. Go to your domain in IIS, right-click->Edit Bindings->Add, and add your new subdomain leaving everything else the same e.g. mysubdomain.domain.com

You may need to wait 5-10 mins for the DNS records to update but that's all you need.

Floating point inaccuracy examples

In python:

>>> 1.0 / 10
0.10000000000000001

Explain how some fractions cannot be represented precisely in binary. Just like some fractions (like 1/3) cannot be represented precisely in base 10.

How can I set focus on an element in an HTML form using JavaScript?

As mentioned earlier, document.forms works too.

function setFocusToTextBox( _element ) {
  document.forms[ 'myFormName' ].elements[ _element ].focus();
}

setFocusToTextBox( 0 );
// sets focus on first element of the form

Objective-C declared @property attributes (nonatomic, copy, strong, weak)

nonatomic property means @synthesized methods are not going to be generated threadsafe -- but this is much faster than the atomic property since extra checks are eliminated.

strong is used with ARC and it basically helps you , by not having to worry about the retain count of an object. ARC automatically releases it for you when you are done with it.Using the keyword strong means that you own the object.

weak ownership means that you don't own it and it just keeps track of the object till the object it was assigned to stays , as soon as the second object is released it loses is value. For eg. obj.a=objectB; is used and a has weak property , than its value will only be valid till objectB remains in memory.

copy property is very well explained here

strong,weak,retain,copy,assign are mutually exclusive so you can't use them on one single object... read the "Declared Properties " section

hoping this helps you out a bit...

How do you sort a dictionary by value?

Actually in C#, dictionaries don't have sort() methods. As you are more interested in sort by values, you can't get values until you provide them key. In short, you need to iterate through them using LINQ's OrderBy(),

var items = new Dictionary<string, int>();
items.Add("cat", 0);
items.Add("dog", 20);
items.Add("bear", 100);
items.Add("lion", 50);

// Call OrderBy() method here on each item and provide them the IDs.
foreach (var item in items.OrderBy(k => k.Key))
{
    Console.WriteLine(item);// items are in sorted order
}

You can do one trick:

var sortedDictByOrder = items.OrderBy(v => v.Value);

or:

var sortedKeys = from pair in dictName
            orderby pair.Value ascending
            select pair;

It also depends on what kind of values you are storing: single (like string, int) or multiple (like List, Array, user defined class). If it's single you can make list of it and then apply sort.
If it's user defined class, then that class must implement IComparable, ClassName: IComparable<ClassName> and override compareTo(ClassName c) as they are more faster and more object oriented than LINQ.

How do I test if a string is empty in Objective-C?

if (string.length == 0) stringIsEmpty;

java.security.AccessControlException: Access denied (java.io.FilePermission

Just document it here on Windows you need to escape the \ character:

"e:\\directory\\-"

PostgreSQL delete with inner join

Just use a subquery with INNER JOIN, LEFT JOIN or smth else:

DELETE FROM m_productprice
WHERE m_product_id IN
(
  SELECT B.m_product_id
  FROM   m_productprice  B
    INNER JOIN m_product C 
    ON   B.m_product_id = C.m_product_id
  WHERE  C.upc = '7094' 
  AND    B.m_pricelist_version_id = '1000020'
)

to optimize the query,

Windows- Pyinstaller Error "failed to execute script " When App Clicked

That error is due to missing of modules in pyinstaller. You can find the missing modules by running script in executable command line, i.e., by removing '-w' from the command. Once you created the command line executable file then in command line it will show the missing modules. By finding those missing modules you can add this to your command : " --hidden-import = missingmodule "

I solved my problem through this.

Mysql - delete from multiple tables with one query

The documentation for DELETE tells you the multi-table syntax.

DELETE [LOW_PRIORITY] [QUICK] [IGNORE]
    tbl_name[.*] [, tbl_name[.*]] ...
    FROM table_references
    [WHERE where_condition]

Or:

DELETE [LOW_PRIORITY] [QUICK] [IGNORE]
    FROM tbl_name[.*] [, tbl_name[.*]] ...
    USING table_references
    [WHERE where_condition]

How does the communication between a browser and a web server take place?

Hyper Text Transfer Protocol (HTTP) is a protocol used for transferring web pages (like the one you're reading right now). A protocol is really nothing but a standard way of doing things. If you were to meet the President of the United States, or the king of a country, there would be specific procedures that you'd have to follow. You couldn't just walk up and say "hey dude". There would be a specific way to walk, to talk, a standard greeting, and a standard way to end the conversation. Protocols in the TCP/IP stack serve the same purpose.

The TCP/IP stack has four layers: Application, Transport, Internet, and Network. At each layer there are different protocols that are used to standardize the flow of information, and each one is a computer program (running on your computer) that's used to format the information into a packet as it's moving down the TCP/IP stack. A packet is a combination of the Application Layer data, the Transport Layer header (TCP or UDP), and the IP layer header (the Network Layer takes the packet and turns it into a frame).

The Application Layer

...consists of all applications that use the network to transfer data. It does not care about how the data gets between two points and it knows very little about the status of the network. Applications pass data to the next layer in the TCP/IP stack and then continue to perform other functions until a reply is received. The Application Layer uses host names (like www.dalantech.com) for addressing. Examples of application layer protocols: Hyper Text Transfer Protocol (HTTP -web browsing), Simple Mail Transfer Protocol (SMTP -electronic mail), Domain Name Services (DNS -resolving a host name to an IP address), to name just a few.

The main purpose of the Application Layer is to provide a common command language and syntax between applications that are running on different operating systems -kind of like an interpreter. The data that is sent by an application that uses the network is formatted to conform to one of several set standards. The receiving computer can understand the data that is being sent even if it is running a different operating system than the sender due to the standards that all network applications conform to.

The Transport Layer

...is responsible for assigning source and destination port numbers to applications. Port numbers are used by the Transport Layer for addressing and they range from 1 to 65,535. Port numbers from 0 to 1023 are called "well known ports". The numbers below 256 are reserved for public (standard) services that run at the Application Layer. Here are a few: 25 for SMTP, 53 for DNS (udp for domain resolution and tcp for zone transfers) , and 80 for HTTP. The port numbers from 256 to 1023 are assigned by the IANA to companies for the applications that they sell.

Port numbers from 1024 to 65,535 are used for client side applications -the web browser you are using to read this page, for example. Windows will only assign port numbers up to 5000 -more than enough port numbers for a Windows based PC. Each application has a unique port number assigned to it by the transport layer so that as data is received by the Transport Layer it knows which application to give the data to. An example is when you have more than one browser window running. Each window is a separate instance of the program that you use to surf the web, and each one has a different port number assigned to it so you can go to www.dalantech.com in one browser window and this site does not load into another browser window. Applications like FireFox that use tabbed windows simply have a unique port number assigned to each tab

The Internet Layer

...is the "glue" that holds networking together. It permits the sending, receiving, and routing of data.

The Network Layer

...consists of your Network Interface Card (NIC) and the cable connected to it. It is the physical medium that is used to transmit and receive data. The Network Layer uses Media Access Control (MAC) addresses, discussed earlier, for addressing. The MAC address is fixed at the time an interface was manufactured and cannot be changed. There are a few exceptions, like DSL routers that allow you to clone the MAC address of the NIC in your PC.

For more info:

Where is virtualenvwrapper.sh after pip install?

or, like I did..just uninstall virtualenvwrapper

sudo pip uninstall virtualenvwrapper

and then install it with easy_install

sudo easy_install virtualenvwrapper

this time I found the file "/usr/local/bin/virtualenvwrapper.sh" installed... Before that I weren't finding that file anywhere even by this command

find / -name virtualenvwrapper.sh

Secure random token in Node.js

Look at real_ates ES2016 way, it's more correct.

ECMAScript 2016 (ES7) way

import crypto from 'crypto';

function spawnTokenBuf() {
    return function(callback) {
        crypto.randomBytes(48, callback);
    };
}

async function() {
    console.log((await spawnTokenBuf()).toString('base64'));
};

Generator/Yield Way

var crypto = require('crypto');
var co = require('co');

function spawnTokenBuf() {
    return function(callback) {
        crypto.randomBytes(48, callback);
    };
}

co(function* () {
    console.log((yield spawnTokenBuf()).toString('base64'));
});

Determine a string's encoding in C#

I found new library on GitHub: CharsetDetector/UTF-unknown

Charset detector build in C# - .NET Core 2-3, .NET standard 1-2 & .NET 4+

it's also a port of the Mozilla Universal Charset Detector based on other repositories.

CharsetDetector/UTF-unknown have a class named CharsetDetector.

CharsetDetector contains some static encoding detect methods:

  • CharsetDetector.DetectFromFile()
  • CharsetDetector.DetectFromStream()
  • CharsetDetector.DetectFromBytes()

detected result is in class DetectionResult has attribute Detected which is instance of class DetectionDetail with below attributes:

  • EncodingName
  • Encoding
  • Confidence

below is an example to show usage:

// Program.cs
using System;
using System.Text;
using UtfUnknown;

namespace ConsoleExample
{
    public class Program
    {
        public static void Main(string[] args)
        {
            string filename = @"E:\new-file.txt";
            DetectDemo(filename);
        }

        /// <summary>
        /// Command line example: detect the encoding of the given file.
        /// </summary>
        /// <param name="filename">a filename</param>
        public static void DetectDemo(string filename)
        {
            // Detect from File
            DetectionResult result = CharsetDetector.DetectFromFile(filename);
            // Get the best Detection
            DetectionDetail resultDetected = result.Detected;

            // detected result may be null.
            if (resultDetected != null)
            {
                // Get the alias of the found encoding
                string encodingName = resultDetected.EncodingName;
                // Get the System.Text.Encoding of the found encoding (can be null if not available)
                Encoding encoding = resultDetected.Encoding;
                // Get the confidence of the found encoding (between 0 and 1)
                float confidence = resultDetected.Confidence;

                if (encoding != null)
                {
                    Console.WriteLine($"Detection completed: {filename}");
                    Console.WriteLine($"EncodingWebName: {encoding.WebName}{Environment.NewLine}Confidence: {confidence}");
                }
                else
                {
                    Console.WriteLine($"Detection completed: {filename}");
                    Console.WriteLine($"(Encoding is null){Environment.NewLine}EncodingName: {encodingName}{Environment.NewLine}Confidence: {confidence}");
                }
            }
            else
            {
                Console.WriteLine($"Detection failed: {filename}");
            }
        }
    }
}

example result screenshot: enter image description here

How to check a string starts with numeric number?

System.out.println(Character.isDigit(mystring.charAt(0));

EDIT: I searched for java docs, looked at methods on string class which can get me 1st character & looked at methods on Character class to see if it has any method to check such a thing.

I think, you could do the same before asking it.

EDI2: What I mean is, try to do things, read/find & if you can't find anything - ask.
I made a mistake when posting it for the first time. isDigit is a static method on Character class.

Android: Storing username and password?

Take a look at this this post from android-developers, that might help increasing the security on the stored data in your Android app.

Using Cryptography to Store Credentials Safely

Swift: print() vs println() vs NSLog()

A few differences:

  1. print vs println:

    The print function prints messages in the Xcode console when debugging apps.

    The println is a variation of this that was removed in Swift 2 and is not used any more. If you see old code that is using println, you can now safely replace it with print.

    Back in Swift 1.x, print did not add newline characters at the end of the printed string, whereas println did. But nowadays, print always adds the newline character at the end of the string, and if you don't want it to do that, supply a terminator parameter of "".

  2. NSLog:

    • NSLog adds a timestamp and identifier to the output, whereas print will not;

    • NSLog statements appear in both the device’s console and debugger’s console whereas print only appears in the debugger console.

    • NSLog in iOS 10-13/macOS 10.12-10.x uses printf-style format strings, e.g.

        NSLog("%0.4f", CGFloat.pi)
      

      that will produce:

      2017-06-09 11:57:55.642328-0700 MyApp[28937:1751492] 3.1416

    • NSLog from iOS 14/macOS 11 can use string interpolation. (Then, again, in iOS 14 and macOS 11, we would generally favor Logger over NSLog. See next point.)

    Nowadays, while NSLog still works, we would generally use “unified logging” (see below) rather than NSLog.

  3. Effective iOS 14/macOS 11, we have Logger interface to the “unified logging” system. For an introduction to Logger, see WWDC 2020 Explore logging in Swift.

    • To use Logger, you must import os:

      import os
      
    • Like NSLog, unified logging will output messages to both the Xcode debugging console and the device console, too

    • Create a Logger and log a message to it:

      let logger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "network")
      logger.log("url = \(url)")
      

      When you observe the app via the external Console app, you can filter on the basis of the subsystem and category. It is very useful to differentiate your debugging messages from (a) those generated by other subsystems on behalf of your app, or (b) messages from other categories or types.

    • You can specify different types of logging messages, either .info, .debug, .error, .fault, .critical, .notice, .trace, etc.:

      logger.error("web service did not respond \(error.localizedDescription)")
      

      So, if using the external Console app, you can choose to only see messages of certain categories (e.g. only show debugging messages if you choose “Include Debug Messages” on the Console “Action” menu). These settings also dictate many subtle issues details about whether things are logged to disk or not. See WWDC video for more details.

    • By default, non-numeric data is redacted in the logs. In the example where you logged the URL, if the app were invoked from the device itself and you were watching from your macOS Console app, you would see the following in the macOS Console:

      url = <private>

      If you are confident that this message will not include user confidential data and you wanted to see the strings in your macOS console, you would have to do:

      os_log("url = \(url, privacy: .public)")
      
  4. Prior to iOS 14/macOS 11, iOS 10/macOS 10.12 introduced os_log for “unified logging”. For an introduction to unified logging in general, see WWDC 2016 video Unified Logging and Activity Tracing.

    • Import os.log:

      import os.log
      
    • You should define the subsystem and category:

      let log = OSLog(subsystem: Bundle.main.bundleIdentifier!, category: "network")
      

      When using os_log, you would use a printf-style pattern rather than string interpolation:

      os_log("url = %@", log: log, url.absoluteString)
      
    • You can specify different types of logging messages, either .info, .debug, .error, .fault (or .default):

      os_log("web service did not respond", type: .error)
      
    • You cannot use string interpolation when using os_log. For example with print and Logger you do:

      logger.log("url = \(url)")
      

      But with os_log, you would have to do:

      os_log("url = %@", url.absoluteString)
      
    • The os_log enforces the same data privacy, but you specify the public visibility in the printf formatter (e.g. %{public}@ rather than %@). E.g., if you wanted to see it from an external device, you'd have to do:

      os_log("url = %{public}@", url.absoluteString)
      
    • You can also use the “Points of Interest” log if you want to watch ranges of activities from Instruments:

      let pointsOfInterest = OSLog(subsystem: Bundle.main.bundleIdentifier!, category: .pointsOfInterest)
      

      And start a range with:

      os_signpost(.begin, log: pointsOfInterest, name: "Network request")
      

      And end it with:

      os_signpost(.end, log: pointsOfInterest, name: "Network request")
      

      For more information, see https://stackoverflow.com/a/39416673/1271826.

Bottom line, print is sufficient for simple logging with Xcode, but unified logging (whether Logger or os_log) achieves the same thing but offers far greater capabilities.

The power of unified logging comes into stark relief when debugging iOS apps that have to be tested outside of Xcode. For example, when testing background iOS app processes like background fetch, being connected to the Xcode debugger changes the app lifecycle. So, you frequently will want to test on a physical device, running the app from the device itself, not starting the app from Xcode’s debugger. Unified logging lets you still watch your iOS device log statements from the macOS Console app.

Vue.js unknown custom element

I had the same error

[Vue warn]: Unknown custom element: - did you register the component correctly? For recursive components, make sure to provide the "name" option.

however, I totally forgot to run npm install && npm run dev to compiling the js files.

maybe this helps newbies like me.

Using a remote repository with non-standard port

Try this

git clone ssh://[email protected]:11111/home/git/repo.git

Multiple select in Visual Studio?

Update: MixEdit extension now provides this ability.

MultiEdit extension for VS allows for something similar (doesn't support multiple selections as of this writing, just multiple carets)

Head over to Hanselman's for a quick animated gif of this in action: Simultaneous Editing for Visual Studio with the free MultiEdit extension

How to extract a string between two delimiters

  String s = "ABC[This is to extract]";

    System.out.println(s);
    int startIndex = s.indexOf('[');
    System.out.println("indexOf([) = " + startIndex);
    int endIndex = s.indexOf(']');
    System.out.println("indexOf(]) = " + endIndex);
    System.out.println(s.substring(startIndex + 1, endIndex));