text:
Q: weird number appears on output-C I have made a simple list like this:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <conio.h>
 struct node{
    int am;
    struct node *next;
};
typedef struct node node;
int main(){
int n;
    node *head=(node *)malloc(sizeof(node));
    node *cur=head;
    printf("Give me a number:\n");
    scanf(" %d",head->am);
    cur=head;
    while(1){
        printf("Give me a number\n");
        scanf(" %d",&n);
        if(n==0)
            break;
        cur->am=n;
        cur->next=(node *)malloc(sizeof(node));
        cur=cur->next;
        cur->next=null;
    }
    travel(head);
    printf("Total nodes available :%d\n",count(head));
    system("pause");
    return 0;
}

Now travel is supposed to go through each node in the list and display the integer saved in each node.
void travel(node *h){
    if(h==NULL)
        return;
    printf("Received data from node: \t %d\n",h->am);
    travel(h->next);
}

Now the problem is that when travel is called it wont print the integer from the first node.It will also print another "Received data from node:" followed by a strange number.
For example
If i give 1,2,3,4 as inputs these are the results
Received data from node:         2
Received data from node:         3
Received data from node:         4
Received data from node:         4026432

Any ideas?

A:
Now the problem is that when travel is called it wont print the
  integer from the first node

This can be precisely known from this part of the main() function
printf("Give me a number:\n");
scanf(" %d",head->am); //this is wrong use of scanf("%d",&head->am);
cur=head;
while(1){
    printf("Give me a number\n");
    scanf(" %d",&n);
    if(n==0)
        break;
    cur->am=n;

as I've mentioned you're scanning wrongly but that doesn't matter because later in the code in while loop you replace it this way...

*

*you scan number and store it at head->am

*then you assign head to cur so head->am and cur->am are both the same now... so in while loop when you first assign n to cur->am, it gets assigned to head->am. so this explains why you never get to print first node.

Solution:

*

*to overcome it ... in while loop, before assigning cur->am=n try doing:
cur->next=(node *)malloc(sizeof(node));
cur=cur->next;
//then... assign
curr->am=n;

this way you'll not lose first node.

suggestion:
As someone has already said it's much easier to traverse/ travel the list using loops (never mind... if you want to do it recursively)
here's how you do it with the loops:
 void travel(node *h)
 {
    if(h==NULL)
        return; //list is empty,consider printing "list empty" :)
    while(h!=NULL)
    {
        printf("Received data from node: \t %d\n",h->am);
        h=h->next;
    }
}

To put all together your code without changing the travel() function as suggested would be:
#include <stdio.h>
#include <stdlib.h>

struct node
{
    int am;
    struct node *next;
};

typedef struct node node;

void travel(node *h);

int main() //I have a habit of returning values from main() :)
{
    int n;
    node *head=(node *)malloc(sizeof(node));
    node *cur=head;
    printf("Give me a number:\n");
    scanf(" %d",&head->am);
    cur=head;
    while(1)
    {
        printf("Give me a number\n");
        scanf(" %d",&n);
        if(n==0)
            break;
        cur->next=(node *)malloc(sizeof(node));
        cur=cur->next;
        cur->am=n;                     //NOTE:here's the change!
        cur->next=NULL;
    }
    travel(head);
    return 0; //just to signify successful compilation
}

void travel(node *h)
{
    if(h==NULL)
        return;
    printf("Received data from node: \t %d\n",h->am);
    travel(h->next);
}

Sample Input : 5 6 3 1 0
Sample Output :
Give me a number:
5
Give me a number
6
Give me a number
3
Give me a number
1
Give me a number
0
Received data from node:     5
Received data from node:     6
Received data from node:     3
Received data from node:     1

A: There are (at least) those issues:

*

*The line scanf(" %d",head->am) is wrong since scanf() expects an address of the memory location of the expected value meaning &head->am.

*Your loop scans a number and puts it in the current node and only after it creates a new node. Therefore, the first number you enter will be overridden (after fixing the first issue) and the last node created will contain random data because the loop will terminate after entering 0 but before putting anything in the last node.

A: I propose like this:
int main(void){
    int n;
    node anchor = {0, NULL};//dummy head
    node *head, *cur = &anchor;

    while(1){
        printf("Give me a number\n");
        scanf("%d", &n);
        if(n==0)
            break;
        cur->next = malloc(sizeof(node));
        cur = cur->next;
        cur->am = n;
        cur->next = NULL;
    }
    head = anchor.next;

    travel(head);
    printf("Total nodes available :%d\n", count(head));
    return 0;
}

A: You are missing & at the first scanf:
scanf(" %d", &head->am);

But it could be made to do all the scanf inside the while:
int main(){
    node *head=0;
    node *cur=0;
    node *prev=0;
    while(1){
        prev = cur;
        cur=(node *)malloc(sizeof(node));
        cur->next=NULL;
        printf("Give me a number\n");
        scanf("%d",&cur->am);
        if(cur->am==0)
            break;
        if(head == NULL) head = cur;
        if(prev != NULL) prev->next = cur;
    }
    travel(head);
    printf("Total nodes available :%d\n",count(head));
    return 0;
}

I hope I didnt make any mistake as I wrote it in this SO editor..
and as someone said, you should free the linked list .. but thats out of scope here..
HTH


text:
Q: Writing HTML file with special characters I'm having a problem into writing special characters to the HTML
Basically my program is editing an HTML file and through the textbox i will replace stuff in the html file.
However I want it to be able to add characters like "ç" , "á" , "ö" etc.
I know in HTML those characters have some sort of code and I don't want to check every string manually and replace those letters to that special codes.
there must be a way to convert strings and writing them in HTML.
Here's what I tried so far:
string utf8_String = textBox8.Text;
byte[] bytes = Encoding.Default.GetBytes(utf8_String);
utf8_String = Encoding.UTF8.GetString(bytes);
content = content.Replace("{8}", utf8_String);

but it's not working.

A: You should use the System.Web.HttpUtility class, specifically the HtmlEncode and HtmlDecode methods to work with html strings.
The HtmlEncode method converts every special character in your string in the equivalent html entity; HtmlDecode does the exact opposite.
See the MSDN reference for more details.

A: What you need is to read your TextBox.Text with HtmlAgilityPack and after that use HtmlEntity.Entitize method. After that you set the Entitize value to the textbox. Here is little example in console application.
    public static void  Main(string[] args)
    {
        string html = @"<!DOCTYPE html>

My First Heading

My first paragraph.

ç

";

        HtmlDocument doc = new HtmlDocument();
        doc.LoadHtml(html);
        Console.WriteLine(HtmlEntity.Entitize(doc.DocumentNode).InnerHtml);

}

To install Html Agility Pack you can use this in NuGet
PM> Install-Package HtmlAgilityPack

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to write simple geometric shapes into numpy arrays I would like to generate a numpy array of 200x200 elements in size and put into it a circle centered into 100,100 coordinates, radius 80 and stroke width of 3 pixels. How to do this in python 2.7 without involving file operations? Possibly using geometry or imaging libraries to allow generalisation to other shapes.

A: opencv new python bindings  import cv2 create numpy arrays as the default image format
They include drawing functions

A: The usual way is to define a coordinate mesh and apply your shape's equations. To do that the easiest way is to use numpy.mgrid:
http://docs.scipy.org/doc/numpy/reference/generated/numpy.mgrid.html
# xx and yy are 200x200 tables containing the x and y coordinates as values
# mgrid is a mesh creation helper
xx, yy = numpy.mgrid[:200, :200]
# circles contains the squared distance to the (100, 100) point
# we are just using the circle equation learnt at school
circle = (xx - 100) ** 2 + (yy - 100) ** 2
# donuts contains 1's and 0's organized in a donut shape
# you apply 2 thresholds on circle to define the shape
donut = numpy.logical_and(circle < (6400 + 60), circle > (6400 - 60))

A: Cairo is a modern, flexible and fast 2D graphics library.  It has Python bindings and allows creating "surfaces" based on NumPy arrays:
import numpy
import cairo
import math
data = numpy.zeros((200, 200, 4), dtype=numpy.uint8)
surface = cairo.ImageSurface.create_for_data(
    data, cairo.FORMAT_ARGB32, 200, 200)
cr = cairo.Context(surface)

# fill with solid white
cr.set_source_rgb(1.0, 1.0, 1.0)
cr.paint()

# draw red circle
cr.arc(100, 100, 80, 0, 2*math.pi)
cr.set_line_width(3)
cr.set_source_rgb(1.0, 0.0, 0.0)
cr.stroke()

# write output
print data[38:48, 38:48, 0]
surface.write_to_png("circle.png")

This code prints
[[255 255 255 255 255 255 255 255 132   1]
 [255 255 255 255 255 255 252 101   0   0]
 [255 255 255 255 255 251  89   0   0   0]
 [255 255 255 255 249  80   0   0   0  97]
 [255 255 255 246  70   0   0   0 116 254]
 [255 255 249  75   0   0   0 126 255 255]
 [255 252  85   0   0   0 128 255 255 255]
 [255 103   0   0   0 118 255 255 255 255]
 [135   0   0   0 111 255 255 255 255 255]
 [  1   0   0  97 254 255 255 255 255 255]]

showing some random fragment of the circle.  It also creates this PNG:

A: Another possibility is to use scikit-image. You can use circle_perimeter for a hollow or circle for a full circle.
You can draw a single stroke circle like so:
import matplotlib.pyplot as plt
from skimage import draw
arr = np.zeros((200, 200))
rr, cc = draw.circle_perimeter(100, 100, radius=80, shape=arr.shape)
arr[rr, cc] = 1
plt.imshow(arr)
plt.show()

You can also emulate a stroke by using a loop. In this case you should use the anti-aliased version to avoid artifacts:
import matplotlib.pyplot as plt
from skimage import draw
arr = np.zeros((200, 200))
stroke = 3
# Create stroke-many circles centered at radius.
for delta in range(-(stroke // 2) + (stroke % 2), (stroke + 1) // 2):
    rr, cc, _ = draw.circle_perimeter_aa(100, 100, radius=80+delta, shape=arr.shape)
    arr[rr, cc] = 1
plt.imshow(arr)
plt.show()

A probably more efficient way is to generate two full circles and "subtract" the inner from the outer one:
import matplotlib.pyplot as plt
from skimage import draw
arr = np.zeros((200, 200))
stroke = 3
# Create an outer and inner circle. Then subtract the inner from the outer.
radius = 80
inner_radius = radius - (stroke // 2) + (stroke % 2) - 1
outer_radius = radius + ((stroke + 1) // 2)
ri, ci = draw.circle(100, 100, radius=inner_radius, shape=arr.shape)
ro, co = draw.circle(100, 100, radius=outer_radius, shape=arr.shape)
arr[ro, co] = 1
arr[ri, ci] = 0
plt.imshow(arr)
plt.show()

The two methods yield in fact slightly different results.

A: One way to do this using only numpy, (similar to @Simon's answer) is as follows:
import numpy as np

def draw_circle(radius, dim=None):
    if dim == None:
        dim = (radius * 2, radius * 2)
    circle = np.zeros(dim)
    x, y = np.meshgrid(np.arange(dim[0]), np.arange(dim[1]))
    r = np.abs((x - dim[0] / 2)**2 + (y - dim[1] / 2)**2 - radius**2)

    m1 = r.min(axis=1, keepdims=True)
    m2 = r.min(axis=0, keepdims=True)
    rr = np.logical_or(r == m1, r == m2)
    l_x_lim = int(dim[0] / 2 - radius)
    u_x_lim = int(dim[0] / 2 + radius + 1)
    l_y_lim = int(dim[0] / 2 - radius)
    u_y_lim = int(dim[0] / 2 + radius + 1)

    circle[l_x_lim:u_x_lim, l_y_lim:u_y_lim][rr[l_x_lim:u_x_lim, l_y_lim:u_y_lim]] = 1
    return circle

gen_circle(20) # draw a circle of radius 20 pixels


text:
Q: Current Induced In Circuit With Non-Orientable Surface I am very much a physics novice, and am currently taking Physics C in high school, but we've discussed the Maxwell Faraday equation, and I had a question about it.
To be more clear, the maxwell faraday equation we are dealing with is in its integral form:
$$
\oint_C E\cdot dl=-\frac{d\Phi_B}{dt}
$$
And this I have an understanding of. But my question lies in more complicated surfaces. I have an interest in topology, and my, again, novice understanding of topology makes me think that the closed loop wire $C$ that this equation is working on only really works if the wire in question has a Seifert Surface that is orientable. My question is, what happens if the Seifert Surface is non-orientable? Such as a trefoil knot of a wire with a $B$ field "perpendicular" to it? Diagram below.
So if anyone knows what happens in this scenario, whether there is no current in the loop, or whatnot, I would appreciate any clarification. Thank you!


text:
Q: Scala syntactic sugar for mandatory Option-type function parameters Is there a syntatic sugar to call a function with multiple parameters of type Option but without default value of None present in any?
def func1(param1: Option[String],
          param2: Option[String]): String =
  param1.getOrElse(param2.getOrElse("none"))

func1(None, None)                      // "none"
func1(Some("value1"), None)            // "value1"
func1(Some("value1"), Some("value2"))  // "value1"
func1(None, Some("value2"))            // "value2"

I would like to achieve returned value of "value2" by giving only one parameter while calling func1() while not giving None to any other.
func1(param2=Some("value2"))  // not enough arguments for method
                              //  func1: (param1: Option[String], param2: Option[String])String.
                              //  Unspecified value parameter param1.

I'm unable to modify the original function. I could wrap it with another function but looking for already available syntatic sugars first.

A: As long as you cannot change the function, that should not be possible.
But since we're in scala you can just add a method that fits your needs via implicit conversions.
Let's say this class is defined in your library:
class Foo {
  def func1(param1: Option[String], param2: Option[String]): String =
    param1 orElse param2 getOrElse "none"
}

You can create an implicit class that adds your own function with the correct signature.
implicit class FooOps(foo: Foo) {
  def func1(param1: Option[String] = None, param2: Option[String] = None): String =
    foo.func1(param1, param2)
}

The method can now be invoked as you wanted
scala> new Foo().func1()
res1: String = none


text:
Q: Call object of Static Inner Class I'm trying to call an object from a static member class, but I get an exceptionInitializationError. Please could you look at my code and let me know what's wrong?
import java.util.ArrayList;
public class StaticInit {

public static void main(String[] args) throws Exception {

    ArrayList<Olive> olives = OliveJar.olives;

 for( Olive o : olives) {
     System.out.println(o);
 }

    }

public static class OliveJar {
        public static ArrayList<Olive> olives;

         static {
            olives.add(new Olive("Olive 1!", 10));
            olives.add(new Olive("Olive 2!", 30));
            olives.add(new Olive("Olive 3", 10));
            System.out.println("Initialization Successful. Your Jar Contains " + olives.size() + " Olives.");

        }

    }
}

A: ExceptionInitializerError  is becuase you haven't initialized olives
add
olives = new ArrayList<Olive>();

before adding instances to list in static initializer block

A: initialize your array
public static ArrayList<Olive> olives=new ArrayList<Olive>();

A: Change public static ArrayList<Olive> olives; to public static ArrayList<Olive> olives = new ArrayList<>;.

A: Your nested class has a field olives that you never initialize, so you get an exception when calling add. Assign an object to it:
olives = new ArrayList<>();

Additionally, both public and static fields are usually poor design. It's not clear what you're doing here, but this pattern shouldn't be used in real code.


text:
Q: NSNetService delegates not being called I'm trying to resolve a NSNetService (named "My_Mac") to an IP in a background app with this code:
NSNetService *service = [[NSNetService alloc] initWithDomain:@"local." type:@"_daap._tcp" name:@"My_Mac"];
[service setDelegate:self];
[service resolveWithTimeout:5];

And in the same class, I have these delegate methods defined:
- (void)netServiceDidResolveAddress:(NSNetService *)sender
- (void)netService:(NSNetService *)sender didNotResolve:(NSDictionary *)errorDict

Here's the strange part: neither delegate methods get called unless I run a NSAlert after   "[service resolveWithTimeout:5];". Any ideas?

A: If you are using ARC you need to retain the service object somewhere.
In your example, the service object most likely goes out of scope and is not referenced anywhere else in your code, so the compiler will try to release it immediately after the resolve call.
Add a property:
@property (nonatomic, strong) NSMutableArray *services;

In your delegate, or wherever you use NSNetService
- (void)netServiceBrowser:(NSNetServiceBrowser *)browser
           didFindService:(NSNetService *)aNetService
               moreComing:(BOOL)moreComing
{
    if (!self.services) {
        self.services = [[NSMutableArray alloc] init];
    }
    [self.services addObject:aNetService];
    [aNetService setDelegate:self];
    [aNetService resolveWithTimeout:3.0];
}

Don't forget to stop and release those services once you're finished or getting rid of the delegate:
for (NSNetService* service in self.services) {
    [service stop];
}
[self.services removeAllObjects];

A: I'm not sure, but it looks like the request is not actually scheduled in a run loop for some reason.  Maybe try something like this to schedule it?
NSNetService *service = [[[NSNetService alloc] initWithDomain:@"local." type:@"_daap._tcp." name:@"My_Mac"] autorelease];
[service setDelegate:self];
[service scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:@"PrivateMyMacServiceMode"];
[service resolveWithTimeout:8.0];

Stupid question, but are you explicitly implementing NSServiceDelegate protocol or just have the methods?
EDIT: I had another thought that this might be some kind of race condition (a more likely scenario).  Delegates are usually weak references.  If your object is dropping out of scope and being autoreleased, the system would end up with a nil handle and be firing the messages to nil.  In the case where you show an NSAlert (or do other work) your object might be hanging around just long enough for it to get the messages fired back to it.  Could you confirm your object sticks around for the full 8 seconds?

A: I've just run into this problem and I was already retaining the NSNetService object so that wasn't the reason.
Turns it out it was because the access levels of the delegate methods I defined wasn't matching the access level of the class (the class was public while the delegate methods were internal). And because all of the delegate methods are optional, the compiler was just giving a silent warning.


text:
Q: Is it possible to add watermark to an existing pdf with tex, latex? I saved a web page as a pdf.
I would like to add watermark to this existing pdf.
I googled and got some answers either using something like Adobe Acrobat DC or using a programming language like Python.
Is it feasible to add watermark to this existing pdf within tex, latex?


text:
Q: How can use props text between React Components I am trying to appear text from main App.js to component via props. How can take Todos text from App.js to Modal Component in Modal Heading Text. Such as
Are you sure? "and the name of Todo"
App.js
import Todo from "./components/Todo";

function App() {
  return (

My Todos

      <Todo text="Learn React" />
      <Todo text="Master React" />
      <Todo text="Explore the full React course" />

  );
}

export default App;

Modal Component Code
function Modal(props){

    function cancelhandler(){
        props.onCancel();
    }

    function confirmlhandler(){
        props.onConfirm();
    }

    return (

Are you sure?

            <button className="btn btn--alt" onClick={cancelhandler}>Cancel</button>
            <button className="btn"  onClick={confirmlhandler}>Confirm</button>

    );
}
export default Modal;

Todo Component
import Modal from './Modal';
import Backdrop from './Backdrop';

function Todo(props){

    return (

{props.text}

                <button className="btn">Delete</button>

    );
}
export default Todo;

A: You can pass text from Todo to Modal as:
<Modal text={props.text} />

CODESANDBOX LINK
and show it in Modal as:

Are you sure you want to delete {props.text}?

A: There are a few ways to pass this value.

*

*By props:
In Todo Component when declaring Modal Component you can pass variable

components/Todo.jsx

{props.text}

        modalStatus ? <Modal headline={props.text} /> : null; // I have used state here to determine when modal shall be visible

            <button className="btn">Delete</button>

components/Modal.jsx

Are you sure? {props.headline}

        <button className="btn btn--alt" onClick={cancelhandler}>Cancel</button>
        <button className="btn"  onClick={confirmlhandler}>Confirm</button>

*If you have a few components when you want to pass variables you should use useContext instead of props drilling.

components/Todo.jsx
import Modal from "./Modal";
import modalContext from "../contexts/modalContext";
import { useState } from "react";
function Todo(props) {
  const [modalOpen, setModalOpen] = useState(false);
  return (

{props.text}

      <modalContext.Provider value={props.text}>
        {modalOpen ? <Modal /> : null}
      </modalContext.Provider>

        <button className="btn">Delete</button>

  );
}
export default Todo;

contexts/modalContext.jsx
import { createContext } from "react";
const modalContext = createContext(null);

export { modalContext };


text:
Q: Find the volume. Triple integral.
Find volume of common part of sphere and cylinder.

My try in cylndrical coordinates:
  $$\int_{-\frac{\pi}{2}}^{\frac{\pi}{2}}\int_{0}^{Rcos\phi}\int_{-\sqrt{R^2-r^2}}^{\sqrt{R^2-r^2}}1r dzdr d\phi =$$
  $$ =2\int_{-\frac{\pi}{2}}^{\frac{\pi}{2}}\int_{0}^{Rcos\phi} \sqrt{R^2-r^2}rdr d\phi$$

Is it correct? What is the triple integral in spherical coordinates?

A: Looks like you have correct set up for cylindrical coordinates.
When you integrate remember that $\sqrt{R^2 - R^2\cos^2\theta} = R|\sin\theta|$
In spherical:
$x = \rho\cos\theta\cos \phi\\
y = \rho\cos\theta\cos \phi\\
z = \rho\sin \phi$
you will have to break it up into two integrals.
For one integral $\rho$ will have the freedom to move from $0$ to $R$
But we need to find limits for $\phi$
Lets find the contour where the cylinder meets the sphere
$(x,y,z) =  (R\cos^2\theta, R\cos\theta\sin\theta, R\sin\theta)$
$\phi = \theta$
$2\int_{-\frac{\pi}{2}}^\frac{\pi}{2}\int_\theta^\frac{\pi}{2}\int_0^R \rho^2\sin\phi\ d\rho\ d\phi\ d\theta$
Since the region is symmetric across they xy plane, I am integrating half the region and doubling it.
Now we need the integral where $\rho$ is limited by the cylinder wall.
plugging the polar expressions into
$x^2 + y^2 - Rx = 0$ we get
$\rho^2\cos^2\phi - R\rho\cos\theta\cos\phi = 0\\
\rho = R\cos\theta\sec\phi$
$2\int_{-\frac{\pi}{2}}^\frac{\pi}{2}\int_0^\theta\int_0^{R\cos\theta\sec\phi} \rho^2\sin\phi\ d\rho\ d\phi\ d\theta $


text:
Q: When reading in an adjacency list for a graph in Java, how do I avoid duplicate edges? I have a .txt file that represents a graph adjacency list. It has 200 rows, and looks like this: First column represents the vertex ID's, and each corresponding row is the list of other vertices that vertex shares an edge with.
1   37  79  164 155 32  87  39  113 15  18  78  175 140 200 4   160 97  191 100 91  20  69  198 196
2   123 134 10  141 13  12  43  47  3   177 101 179 77  182 117 116 36  103 51  154 162 128 30
3   48  123 134 109 41  17  159 49  136 16  130 141 29  176 2   190 66  153 157 70  114 65  173 104 194 54
4   91  171 118 125 158 76  107 18  73  140 42  193 127 100 84  121 60  81  99  80  150 55  1   35  23  93
5   193 156 102 118 175 39  124 119 19  99  160 75  20  112 37  23  145 135 146 73  35
6   155 56  52  120 131 160 124 119 14  196 144 25  75  76  166 35  87  26  20  32  23
7   156 185 178 79  27  52  144 107 78  22  71  26  31  15  56  76  112 39  8   113 93
8   185 155 171 178 108 64  164 53  140 25  100 133 9   52  191 46  20  150 144 39  62  131 42  119 127 31  7
9   91  155 8   160 107 132 195 26  20  133 39  76  100 78  122 127 38  156 191 196 115
10  190 184 154 49  2   182 173 170 161 47  189 101 153 50  30  109 177 148 179 16  163 116 13  90  185
11  123 134 163 41  12  28  130 13  101 83  77  109 114 21  82  88  74  24  94  48  33
12  161 109 169 21  24  36  65  50  2   101 159 148 54  192 88  47  11  142 43  70  182 177 179 189 194 33
13  161 141 157 44  83  90  181 41  2   176 10  29  116 134 182 170 165 173 190 159 47  82  111 142 72  154 110 21  103 130 11  33  138 152
14  91  156 58  122 62  113 107 73  137 25  19  40  6   139 150 46  37  76  39  127
15  149 58  68  52  39  67  121 191 1   45  100 18  118 174 40  85  196 122 42  193 119 139 26  127 145 135 57  38  7

I'm trying to read this file into some Java classes I made, but I'm not sure how to avoid reading in duplicate edges. For each edge, there are two numbers associated with it in the .txt file. Ex. in row #8, there's a number 9 that represents an edge shared by vertices 8 and 9. Then in row 9 there's a number 8 that represents that same edge shared by 9 and 8.
I'm using this code with a BufferedReader to make each line into an array and then add a new edge for each non-first-column vertex ID.

    private static UndirectedGraph constructGraph(String filename) throws IOException {

     UndirectedGraph graph = new UndirectedGraph();

    //count # of lines in the .txt file and make that many vertices
            int numLines = countLines("/home/paris/Downloads/kargercut.txt");

            for (int i = 0; i<=numLines; i++) {
                graph.addVertex(i);

            }

    //BufferedReader to make each row in .txt file into a split string array, from which I can parse Integers
            BufferedReader br = new BufferedReader(new FileReader("/home/paris/Downloads/kargercut.txt"));
            String s;
            ArrayList<String> vtxIDArray = new ArrayList<>();
            String[] sArray;

            while ((s = br.readLine()) != null ) {
                sArray = s.split(" ");

                for (int i = 1; i <= sArray.length - 1; i++) {
                graph.addEdge(Integer.parseInt(sArray[0]), Integer.parseInt(sArray[i]));  /*addEdge takes two vertex ID's as arguments and creates an edge in memory in all three of the aforementioned locations: one in each Vertex object, and one in the entire graph's "edgeList" ArrayList. */

    }

            }
            System.out.println(Arrays.toString(graph.getVertexIDs()));

            br.close();

            return graph;
        }

My UndirectedEdge class:

public class UndirectedEdge {

    private Vertex end1;
    private Vertex end2;

    UndirectedEdge(Vertex end1, Vertex end2) {
        this.end1 = end1;
        this.end2 = end2;

    }

    public Vertex getEnd1() {
        return end1;
    }

    public Vertex getEnd2() {
        return end2;
    }

    public void setEnd1(Vertex end1) {
        this.end1 = end1;
    }

    public void setEnd2(Vertex end2) {
        this.end2 = end2;
    }
}

The addEdge method:
public void addEdge(Integer end1ID, Integer end2ID) {

        Vertex end1 = findVertex(end1ID);
        Vertex end2 = findVertex(end2ID);

        if ((end1 == null) || (end2 == null)) {
            throw new IllegalArgumentException("1 or 2 of the endpoints don't exist.");
        }
        if (end1 == end2) throw new IllegalArgumentException("No self-loops allowed");

        UndirectedEdge newEdge = new UndirectedEdge(end1, end2);
        edgeList.add(newEdge);
        end1.addEdge(newEdge);
        end2.addEdge(newEdge);

    }

Right now, a single edge in my program is stored in the Vertex class (of each of its endpoints), and in the master edgeList class. With the current way I'm reading this file in, for each edge, I'll have twice as many edges as I should have in each of those three locations in memory.
I have no idea what to do.

A: What you want to do is in the addEdge() method, check whether that edge already exists in your graph. You'll probably want to implement a new function in your UndirectedGraph class called edgeExists(int vertex1, int vertex2) that returns a bool indicating whether the edge you want to add between vertex1 and vertex2 already exist.
Then, call that function every time you want to add a new edge. If the edge doesn't yet exist, add it, otherwise don't.
An easy implementation of edgeExists would probably just check whether the vertex1 object contains vertex2 in its list of adjacencies.


text:
Q: Erro de conversão implícita de tipos
Error  1   Cannot implicitly convert type 'CursoCAvancado.Cliente' to 'string' C:\curso\CursoCAvancado\CursoCAvancado\Form1.cs 47  31  CursoCAvancado

Segue a classe
namespace CursoCAvancado
{
    public partial class Form1 : Form
    {
        Conta conta;

        public Form1()
        {
            InitializeComponent();
        }

        private void textBox3_TextChanged(object sender, EventArgs e)
        {

        }

        private void Sacar_Click(object sender, EventArgs e)
        {

                double valor = Convert.ToDouble(txtValorSaque.Text);
                this.conta.Saca(valor);
                if (valor < 100)
                {
                    MessageBox.Show("Saque efetuado com sucesso" + this.conta.Saldo);
                }
            }

        private void Form1_Load(object sender, EventArgs e)
        {
            this.conta = new Conta();
            this.conta.Titular = new Cliente("everson");
            this.conta.Numero = 1;
            this.conta.Deposita(100);

            txtNumero.Text = Convert.ToString(this.conta.Numero);
            txtSaldo.Text = Convert.ToString(this.conta.Saldo);
            txtTitular.Text = this.conta.Titular;

        }
     }
}
classe conta
 class Conta
    {
        public int Numero { get; set; }
        public double Saldo { get; set; }
        public Cliente Titular { get; set; }

        public void Saca(double valor)
        {
            this.Saldo -= valor;
        }
        public void Deposita(double valor)
        {
            this.Saldo += valor;
        }
        public void Transfere(double valor, Conta destino)
        {

        }
    }
}

Classe cliente
public class Cliente
{
    public string Nome { get; set; }

    public Cliente(string nome)
    {
        this.Nome = nome;
    }
}

A: O erro cita a linha 47 do arquivo. Acredito que seja esta:
txtTitular.Text = this.conta.Titular;

Se this.conta.Titular é um Cliente, você não pode atribuir direto ao valor de um campo de texto, que deve ser uma string. Para preencher com o nome do titular, faltou pegar a propriedade adequada do seu Cliente:
txtTitular.Text = this.conta.Titular.Nome;


text:
Q: Wxpython grid AppendRows The following code is used to generate a table that an row can be added by a button, but only the data of the last row is eliminated after running.
import wx, wx.grid
class GridData(wx.grid.PyGridTableBase):
        _cols = "a b c".split()
        _data = [
        "1 2 3".split(),
        "4 5 6".split(),
        "7 8 9".split()
        ]
        _highlighted = set()

        def GetColLabelValue(self, col):
            return self._cols[col]

        def GetNumberRows(self):
            return len(self._data)

        def GetNumberCols(self):
            return len(self._cols)

        def GetValue(self, row, col):
            return self._data[row][col]

        def SetValue(self, row, col, val):
            self._data[row][col] = val

        def AppendRows(self, *args):
            msg = wx.grid.GridTableMessage(self,
                                       wx.grid.GRIDTABLE_NOTIFY_ROWS_APPENDED,
                                           )
            self.GetView().ProcessTableMessage(msg)
            return True
            # self.GetView().EndBatch()
            # msg = wx.grid.GridTableMessage(self, wx.grid.GRIDTABLE_REQUEST_VIEW_GET_VALUES)
            # self.GetView().ProcessTableMessage(msg)

        def GetAttr(self, row, col, kind):
            attr = wx.grid.GridCellAttr()
            attr.SetBackgroundColour(wx.GREEN if row in self._highlighted else wx.WHITE)
            return attr

        def set_value(self, row, col, val):
            self._highlighted.add(row)
            self.SetValue(row, col, val)

class Test(wx.Frame):#main frame
    def __init__(self):
        wx.Frame.__init__(self, None)

        self.data = GridData()
        self.grid = wx.grid.Grid(self)
        self.grid.SetTable(self.data)

        btn = wx.Button(self, label="set a2 to x")
        btn.Bind(wx.EVT_BUTTON, self.OnTest)

        self.Sizer = wx.BoxSizer(wx.VERTICAL)
        self.Sizer.Add(self.grid, 1, wx.EXPAND)
        self.Sizer.Add(btn, 0, wx.EXPAND)

   def OnTest(self, event):
        self.grid.AppendRows(numRows=3)
        #self.data.set_value(1, 0, "x")
        self.grid.Refresh()

app = wx.PySimpleApp()
app.TopWindow = Test()
app.TopWindow.Show()
app.MainLoop()

There is no error report,and the expectation can't be reached.
The following code is used to generate a table that can be added by a button, but only the data of the last row can be eliminated after running.


text:
Q: Performance issues when using VueJS with HighCharts I'm using a HightCharts in a VueJS project and I'm having the given implementation from below. Due the complexity of the project requirements, I'm not able to use the highcharts-vue so I'm using the plain JS nested in my Vue component.
In the same time, there is a setIntevral method running on each second (for displaying a clock) and many minor setTimeout methods running from time to time.
Since JavaScript is executing in a one-thread (by it's nature), my page is getting slow every time when the chart is loading (the clock is not updating, meaning that setInterval is not even executing).
From HighCharts point of view, I can not use the option for "asynchronous" loading, again due the requirements of my project (this option is strictly related to HighCharts library not to JavaScript in general).
So basically this post can have like two questions:
1) Can this way of adding the plain JavaScript, nested in the components, be a reason for these performance issues?
2) Is there any way to make the JavaScript code from the different components to not be blocked one by another?
The code for component that loads the chart is given below and I'm wondering if this is violating the VueJS principles and if can be the cause for the performance issues which I'm facing.
<template>

</template>


text:
Q: Why is metric space a Hausdorff space but not a topological space? According to this thread: Is this proof that all metric spaces are Hausdorff spaces correct? metric space is indeed a Hausdorff space.
And in this thread: Are all metric spaces topological spaces? It shows that metric spaces are not necessarily topological spaces.
But Hausdorff spaces are actually defined as topological spaces with more properties.Hausdorff_space_definition
So I am confused...
If anyone can help me, thanks!!

A: The short answer is yes, all metrics spaces are Hausdorff topological spaces. The slight technicality that the second link is trying to get at is that, according to the most strict definitions metrics spaces are not topological spaces.
A metric space is a set with a metric. A topological space is a set with a topology. A metric is a function and a topology is a collection of subsets so these are two different things.
However, the fact is that every metric induces a topology on the underlying set by letting the open balls form a basis. Once this is done then we can think of the metric space as coming with a natural underlying topological space structure, and when we do this the topological structure is always Hausdorff.


text:
Q: Error with Compiling Qt 5.0 If I want to Build and run my application in Qt 5.0, nothing happens. I do not get any errors or something. Just nothing.
Some more information:
I have Windows 7 64-bit
Qt Creator 2.8 (Based on Qt 5.0)
I'm using a MSVC compiler
Here are some screenshot:

This is my current kit.

These are my compilers:

A: You downloaded a MSVC2010 (i.e. MSVC 10) package of Qt and are trying to use it with MSVC2013 (i.e. MSVC 12, as detected by Qt).
That's of course not possible, you need a Qt build matching your compiler.
(If "of course" seems like an overstatement to you, ask Microsoft to keep binary compatibility across its compiler versions.)


text:
Q: Accessing a variable's information I am creating a tool to find the temperature of two areas in New Mexico. In the data set, there is a temperature variable inside a dictionary (main) that I can not seem to get the contents of for my program. The output should be 288.142 and yes I know this is in kelvins.
NMNorthzip=[87401,87301]

for x in NMNorthzip:
    r = requests.get("http://api.openweathermap.org/data/2.5/forecast?zip="
                     +str(x) + ",us&appid=id")
    data = r.json()
    forecast = data['list']

    for n in forecast:
        main = n['main']
        for z in main.items():
            print(z)

Output:
('temp_max', 288.142)
('sea_level', 1028.46)
('grnd_level', 797.18)
('temp_min', 288.142)
('temp', 288.142)
('humidity', 26)
('temp_kf', 0)
('pressure', 797.18)

A: You're converting the dictionary to a list and printing the (key, pair) tuples resulting from the .items() function. So remove this:
    for z in main.items():
        print(z)

Instead access dictionary items:
    temperature = main['temp']


text:
Q: Not a valid cell/range reference when using indirect I have 2 sheets and I want to show the value of a cell to the other sheet. The cell I want to show in the other sheet is C26and it has the value €719.39 and the name of that sheet is January. In a cell in another sheet, I write
=INDIRECT('January'!C26)

and I have an error
Error Function INDIRECT parameter 1 value is '€719.39'. It is not a valid cell/range reference.

Why I am getting this error?

A: Try this, though I do not think it is what you want:
=INDIRECT("'January'!" & C26)

I think you want the simple formula:
='January'!C26

The Indirect method is used to combine the value of a cell in a formula.  For example in this instance it would look for the cell reference by the value in Cell C26 on the active page.  So if that cell had the Value A1 it would return the value of A1 on sheet January.
If that is what you want then use the first formula.
But the second formula will return the value of cell C26 on the sheet January.

A: Indirect uses text input so it is either in quotes or refers to a cell where there is text.
=indirect("January!C26")
=indirect("January!"&"C26")

Put "January!" in C1 and "C26" in D1, for example, then:
=indirect($C$1&$D$1)

you could also use "row()" or "column()" with the address function (using r1c1 style):
=INDIRECT(ADDRESS(ROW(),COLUMN(),1,0,"January"),0)


text:
Q: Android: How to use existing graphic elements I would like to create a user interface which would contain network indication icons (3G, WiFi...) and I would like to use existing graphic elements which are displayed in notification bar.
Does anyone know how to get these existing elements and use it in custom layout?
I guess these icons are all ImageView elements and I am wondering whether it is possible to retrieve them with findViewById() method.

A: They are drawables in android.R.drawable. There is a list of avaiable drawables for 1.0 at drawable list

A: You can go to http://source.android.com/download to get instructions on how to download Android sources (images/drawables included), search for *.pngs and then reference the ones you need like this: getResources().getDrawable(android.R.drawable.ic_menu_save).
P.S. At least some of the drawables come with sdk: $SDK_PATH\platforms\android-1.5\data\res\drawable


text:
Q: UILabel sizeToFit break constraints only on ios 7 I have an iOS app almos finished, but i found a bug. I have an UITableView with an prototype cell and an UILabel on the cell. In runtime i put text in the label and use the method sizeToFit() to resize the label. This works fine on iOS8 but on iOS7 a get an error of breaking constrains and the UILabel simply not resize.
I need your help, its the only thing that i have to do to publish the app.
The constrains :
UILabel to top of cell content - 10

UILabel to bottom of cell content - 10

UILabel to left of cell content - 5

UILabel to right of cell content - 5

P.S - I don't have an cell height defined and i don't use the method estimatedCellSize.

A: use label.numberoflines=0;
labe.sizeToFit=YES;

A: You should be changing your constraints or your approach.
Either use the compression and hugging constraint values to make the label size to fit, and remove the constraints to the right and bottom (in this case to pin the label to the top left and resize).
Or, keep the current constraints and change the label to scale its contents to fit.


text:
Q: Почему children для li закрывает Ul, в который он вложен? jQuery Всем привет.
Код здесь: http://jsfiddle.net/4WQGY/
Смысл скрипта в том, чтобы если у нас есть вложенный ul, То мы открываем его и возвращаем false. Иначе, если ничего не вложено, открываем ссылку.
Ссылки работают как надо. Но я никак не пойму. Если в примере нажать "Кухни" и кликнуть - откроется следующий ul, и если в нем кликнуть на ссылку, где нет вложенного ul тот этот ul закроется. Почему так? Как исправить? Я уже голову сломал себе :)
A: $(function(){
    $('.menu ul').hide();
    $('.menu li.current').parent().show();
    $('.menu li').has('ul').children('a').bind('click',function() {
        $(this).parent('li').children('ul').slideToggle(300);
        return false;
    });
});

http://jsfiddle.net/4WQGY/8/


text:
Q: webhdfs two steps upload a file I build a hadoop cluster with 4 machines:

*

*{hostname}: {ip-address}

*master: 192.168.1.60

*slave1: 192.168.1.61

*slave2: 192.168.1.62

*slave3: 192.168.1.63

I use HttpFS upload a file to hdfs with restful way, there contains two steps to finish the task.

*

*Step 1: Submit a HTTP POST request without automatically following redirects and without sending the file data.
curl -i -X POST "http://192.168.1.60:50070/webhdfs/v1/user/haduser/myfile.txt?op=APPEND"
the server return result like:
Location:http://slave1:50075/webhdfs/v1/user/haduser/myfile.txt?op=CREATE&user.name=haduser&namenoderpcaddress=master:8020&overwrite=false

*

*step 2: use the response address to upload the file.

In step 1, How could I get the datanode's ip address(192.168.1.61) rather than the hostname (slave1)?

A: If your hadoop version>=2.5, at every datanode config ${HADOOP_HOME}/etc/hadoop/hdfs-site.xml file.
add:
property dfs.datanode.hostname,
the value is datanodes's ip address.


text:
Q: Facebook Auth Dialog: Developer warning concerning the use of "display" type "popup" starting today we receive developer warnings in the auth dialog with the following message:

You are using a display type of 'popup' in a large browser window or tab. For a better user experience, show this dialog with our JavaScript SDK without specifying an explicit display type. The SDK will choose the best display type for each environment. Alternatively, set height and width on your window.open() call to properly size this dialog if you have special requirements precluding you from using the SDK. This message is only visible to developers of your application.

We have the following situation:

*

*with javascript we open a new popup

*the src of the popup is set with Facebook's PHP-SDK method getLoginUrl

*popup itself has a size of 400px by 580px

The PHP-SDK itself references the proper use of "display=popup" within it's own code:

If you are using the generated URL with a window.open() call in JavaScript, you can pass in display=popup as part of the $params.

The JS-SDK documentation says, that the maximum-size of the opened popup should be 400x580:

For use in a browser popup no bigger than 400px by 580px. Use this display type to maintain context for the user without needing to perform a full-page redirect.

So, to sum up: According to the docs, the implementation above should be ok. Is anyone else having this warning or a solution for this?

A: The JS-SDK documentation says the browser popup should be "no bigger than 400px by 580px". What they don't specify is that they mean 400px tall by 580px wide.
I see the developer warning in my popup auth dialogs that are 275 tall by 875 wide.  I do not see the warning in my popups that are 400 tall by 580 wide.
Your image suggests your popup is 630 high by 446 wide. Too big by any reading of the specification.

A: Maybe you should switch to FB JS SDK and FB.login() method? It always provides the best user experience.

https://developers.facebook.com/docs/reference/javascript/FB.login/


text:
Q: What exactly is the python interpreter implemented with? I am a beginner in programming, and trying to learn Python from "Learning Python by Mark Lutz". In the 'Introducing the Python Interpreter' chapter the author states the following:

Depending on which flavor of Python you run, the interpreter itself may be implemented as a C program, a set of Java classes, or something else.

I am unable to understand how a piece of Python code is distinguished for a division to be made in the interpreter (either C program or Java classes as the author states).

A: A piece of Python code, is just Python code. What the author is saying is that there are different Python interpreters - all of which do run Python code . these different Python interpreters can be programs written in C, in Java, in C#, or in  Python itself. They are the program that is run when you  type python at the command line, or pick python from an application menu. Ordinarily it will be CPython: the reference implementation of the language made by the Python Software foundation, which is written in C.
All in all, this is definitely non-essential for learning Python - just skip ahead, and come back to this issue once you are more familiarized with the Language.

A: The reference interpreter of Python, the one that the others use as a guide, is written in C, and it is nicknamed CPython (not to be confused with Cython, which isn't an interpreter). It compiles Python code to Python bytecode and runs it on its virtual machine, which is also written in C.
There are other interpreters. Here are a few that are most well-known.

*

*Jython, written in Java, which compiles Python to Java bytecode, and runs it on the Java Virtual Machine. It allows Python code to call Java code. Somehow.

*IronPython, written in C# (some of which is apparently written BY Python), which compiles Python to Microsoft's CLI (correct me if I'm wrong) bytecode, and runs it on the corresponding virtual machine.

*PyPy, written in RPython (a stricter branch of Python), which compiles Python to PyPy bytecode (mostly the same as CPython bytecode) and runs it on its virtual machine. More info: http://doc.pypy.org/en/latest/interpreter.html
Theoretically and ideally, all strictly-legal Python code should run the same on any of these. Think of it like different compilers for C: strictly-legal C code will compile to equivalent programs on any of the compilers

*

*Some non-standard things will be allowed by one compiler, but not another (void main() in Visual Studio is non-standard).

*A compiler for Linux won't have access to the windows.h library (like CPython won't have access to the Java libraries).

*They will have different speed/memory performance for different tasks.

A: It sounds like your true question is how a Python interpreter does what it does.  This is the subject of entire college-level courses, but here is the thrust.
The interpreter reads the Python source with a specialized function called a parser. This is an input processor that understands the exact structure of the Python language in the form of a context free grammar.
The parsing procedure checks the input for compliance with Python syntax rules (here is where syntax errors originate) and produces a data structure that has distilled the raw meaning of the Python program in the form of very simple steps represented in a simple array of bytes called byte code.
The complete process of input, parsing, and byte code production is called compilation. Yes, at its heart, Python has a simple kind of compiler.
Byte codes do very basic things like arithmetic, testing and jumping to other byte code locations based on test results, string operations, calling and returning from functions, input, output, and all the hundreds of fundamental operations that Python programs perform that, when combined and executed quickly, make programs seem powerful.
Where the original Python source was reasonably close to human language (well, sort of...), the byte code is reasonably close to machine language: the patterns of 1's and zeros that processors understand as instructions.  Byte code is what's written to .pyc files when a program runs.
It takes only a quite small and simple program (and hopefully a fast one) called the byte code interpreter (yes an interpreter within the Python interpreter) to process the byte code in order to have the processor do the work that the original Python program intended.
Of course if a .pyc file already exists and is newer than the corresponding source code, the compilation can be skipped.
There you have it... A college course in a few sentences. I have skipped enormous amounts of detail, and (a caveat) some of what I've written applies only to some of the many Python implementations out there, but it's a start at understanding.
The author of your book is saying that the implementation language of all above might be C or Java (the Jython implementation of Python). He left out that only a minimal core of Python is implemented in C or Java.  The rest is in Python itself.
If you're interested in knowing more, there are some reasonably good, low-cost and free sources.  See for example this article and also for not too much money try Scheme 9 From Empty Space for how an interpreter of a language other than Python is implemented.


text:
Q: How to display status updates from followed users? (MVC) What would be a good approach to display on a dashboard, status updates from users that are being followed (e.g. twitter) on a MVC framework such as codeigniter.
I have a Table, just for the status update, where I record the ID,user_id & message.
Should I create a DB table where I record who is following who, by recording the Users ID when a user choose to follow someone?
If so how would I make a query to the database to request for status update only for followed users?

A: This is a typical Many-To-Many relationship, so you'll need a table to store this relation. The table would simply contain two user id's one for the follower and one for the one being followed. For example:
Followed_Id (BIGINT) | Follower_Id (BIGINT)

These columns would then both have a foreign key, referencing the ID column of your user table.
There are a few ORM tools for CI, like swatkins notes in his comment.
For the querying of the status updates, you basically have two options:

*

*Polling, where your client would periodically poll the backend for new updates

*Pushing, where your backend will notify your client of new updates

The second option is considered a better approach for problems like these because:

*

*It can be implemented asynchronously

*It avoids unnecessary calls to the backend in case there's no new data


text:
Q: Js executes code that is after a for loop before the loop finish I know that JavaScript executes loops synchronously. So I don't understand why in the code below alert runs before the end of the for loop. I expected js to first complete the loop and then to execute the alert function. Instead, the for loop starts calling the console.log("loop"), and after a couple of seconds the alert gets executed while at the same time the console.log continuous to print the text "loop".

for(let i=0; i<100000; i++){
  console.log("loop");
}

alert("hello world");


text:
Q: SonarQube server new quality profile checkstyle rules While trying to create a new quality profile using our own checkstyle_rules.xml and even using sun issued checkstyle_rules, I get errors like below:
For sun checkstyle rules xml
Rule template can't be activated on a Quality profile:
checkstyle:com.puppycrawl.tools.checkstyle.checks.regexp.RegexpSinglelineCheck

For Google checkstyle rules xml
The definition of the profile 'null' (language 'null') contains multiple occurrences of the
'checkstyle:com.puppycrawl.tools.checkstyle.checks.blocks.RightCurlyCheck' rule.
The plugin which declares this profile should fix this.

I could find documentation regarding xml should give templates, and we need to create actual rules on top of that.
How can I go about creating checkstyle rules for SONAR and how to convert our checkstyle_rules to template

A: you cannot play a template rule, you have first to create your own rule based on the template rule. Then in your quality profile you associate your new rule based on the template, not the template itself.

A: I think this concerns only template rules. Example with rule "Boolean Expression Complexity" (checkstyle:com.puppycrawl.tools.checkstyle.checks.metrics.BooleanExpressionComplexityCheck) See Sonar Checkstyle import: Rule template can't be activated on a Quality profile for more details.
there is no activation button for these rules,you can either create them with default properties or with your custom properties.
In your case RegexpSinglelineCheck template rule have to be created in sonarqube,you cannot activate it by importing an xml file(this is a actually a limitation).And a rule cannot be converted into template,a template can neither be created nor be deleted(there are about 44 rule templates currently in sonarqube checkstyle repository).
I would suggest activating them with the properties used by google(but some of them are not used by google so activate them with according to your needs)
refer this link:https://github.com/checkstyle/checkstyle/blob/master/src/main/resources/google_checks.xml


text:
Q: How to add link in left part of suitebar in Sharepoint 2013 I have to add a link in left part of suitebar of my site in Shareoint 2013.
I have tried using JS. My code is :-

I am not getting the desired result. Can someone suggest some other way or help me with the solution.

A: Try this.


text:
Q: How to display loading image or text while processing in my project i am checking links whether its working or not ,when i click on create link button i want to display please wait for while but when and when if their some text in text box1if textbox1.text == null then it should not be display and when its not null then when i will click create button it should show please wait,my code is working but i want to check if their is some value in text box and user click the create button it should show please wait a while .if their no value in textbox1 then if user click on create button then please wait should not be displayed
here is my code

      <asp:Button ID="Button1" runat="server" Text="Create link" OnClick="btn_createlink_Click" OnClientClick="javascript:ShowProgressBar()" />

         Please wait for while...

    <asp:TextBox ID="TextBox1" runat="server" TextMode="MultiLine" Height="373px"
        Width="410px" ViewStateMode="Enabled"></asp:TextBox>

A: From what I understand, you are only asking how to verify if the checkbox is empty, right? This should do it:

A: Easiest way to do this is probably to use ajax. Simply call a web service and use javascript to show a loading message/icon/whatever for the user. Try to use google for this, it's really straightforward.
It has to be asynchronous, or else it would block your UI and the please wait wouldn't show.


text:
Q: JsPlumb Recreate Canvas Using AJAX I use a function called "initJsPlumb" to create diagram and send it to  my ajax data  which includes route and node informations as parameter.In this function,I generate instance, connections and nodes placement.
The problem is:
A selectbox triggers ajax and gets datas from controller and try to reacreate jsplumb.When i change selectbox ,first using $("#canvas").empty(); and get datas from controller and then recreate diagram with  initJsPlumb(data); .After that, all nodes and connections create correctly.But when i use instance.getConnections() to get all nodes positions its give me old connections list(before call ajax) or i use instance.getAllConnections() its give me correct connections but when write them to console and mouse over on the nodes on console, cannot reach html elements so i cant get their top,left position informations(they are always 0).
Anyone has solutions to solve reset and recreate jsplumb?

A: If you empty out the container jsPlumb is using without telling it jsPlumb will get in a muddle.  You should probably call reset() on the jsPlumb instance, or in fact just create a whole new instance.


text:
Q: Android "speak failed: not bound to tts engine" My android application has text to speak feature and more then one activity uses this feature. So created a static helper class to made this easy.
import java.util.Locale;

import android.content.Context;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.util.Log;

public class TextToSpeechController implements OnInitListener {

    private static final String TAG = "TextToSpeechController";
    private TextToSpeech myTTS;
    private String textToSpeak;
    private Context context;

    private static TextToSpeechController singleton;

    public static TextToSpeechController getInstance(Context ctx) {
        if (singleton == null)
            singleton = new TextToSpeechController(ctx);
        return singleton;
    }

    private TextToSpeechController(Context ctx) {
        context = ctx;
    }

    public void speak(String text) {
        textToSpeak = text;

        if (myTTS == null) {
            // currently can't change Locale until speech ends
            try {
                // Initialize text-to-speech. This is an asynchronous operation.
                // The OnInitListener (second argument) is called after
                // initialization completes.
                myTTS = new TextToSpeech(context, this);

            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        sayText();

    }

    public void onInit(int initStatus) {
        if (initStatus == TextToSpeech.SUCCESS) {
            if (myTTS.isLanguageAvailable(Locale.UK) == TextToSpeech.LANG_AVAILABLE)
                myTTS.setLanguage(Locale.UK);
        }

        // status can be either TextToSpeech.SUCCESS or TextToSpeech.ERROR.
        if (initStatus == TextToSpeech.SUCCESS) {
            int result = myTTS.setLanguage(Locale.UK);
            if (result == TextToSpeech.LANG_MISSING_DATA
                    || result == TextToSpeech.LANG_NOT_SUPPORTED) {
                Log.e(TAG, "TTS missing or not supported (" + result + ")");
                // Language data is missing or the language is not supported.
                // showError(R.string.tts_lang_not_available);

            } else {
                // Initialization failed.
                Log.e(TAG, "Error occured");
            }

        }
    }

    private void sayText() {
        // ask TTs to say the text
        myTTS.speak(this.textToSpeak, TextToSpeech.QUEUE_FLUSH,     null);
    }

    public void stopTTS() {
        if (myTTS != null) {
            myTTS.shutdown();
            myTTS.stop();
            myTTS = null;
        }
    }

}

I am using this helper class like this.
TextToSpeechController.getInstance(this).speak(readableMessage);

But sometimes i see an error like line beloew at LogCat.
"speak:failed not bound to tts engine"

No exception thrown but nothing readed by TTS.
I realized that if i triggered activity from BroadcastReceiver, i got this error. Otherwise if manually open activity from application code works with no problem.
Here is the BroadcastReceiver code
private final BroadcastReceiver mHandleMessageReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        String newMessage = intent.getExtras().getString(EXTRA_MESSAGE);
        String readableMessage = intent.getExtras().getString(READABLE_MESSAGE);

        Bundle b = new Bundle();
        b.putString(EXTRA_MESSAGE, newMessage);
        b.putString(READABLE_MESSAGE, readableMessage);
        Intent newIntent = new Intent("android.intent.action.MAIN");
        newIntent.setClass(context, Speak.class);
        newIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        newIntent.putExtra("MessageReceived", b);
        newIntent.putExtra("CallType", CallType.NOTIFICATION);
        context.startActivity(newIntent);
    }
};

A: Your code is not waiting for the asynch return from the constructor of the TextToSpeech class.  You even have a comment that says it is asynch.  Why it always fails in the Receiver but not the Activity I am not sure - other then maybe the Activity as a foreground task has higher priority and it happen to complete before you call sayText.
You need to wait to call sayText until the init call returns in the case where it has to new up a new TTS object.

A: Here is the code I use for text to speech. For my code simply type speakWords("say something"); in any activity.
public class VoiceRecognition extends Activity implements OnClickListener,
        OnInitListener {

    public static final int VOICE_RECOGNITION_REQUEST_CODE = 1234;

    public Button speakButton;
    // TTS object
    public TextToSpeech myTTS;
    // status check code
    public int MY_DATA_CHECK_CODE = 0;

    // setup TTS
    public void onInit(int initStatus) {

        // check for successful instantiation
        if (initStatus == TextToSpeech.SUCCESS) {
            if (myTTS.isLanguageAvailable(Locale.US) == TextToSpeech.LANG_AVAILABLE)
                myTTS.setLanguage(Locale.US);
        } else if (initStatus == TextToSpeech.ERROR) {
            Toast.makeText(this, "Sorry! Text To Speech failed...",
                    Toast.LENGTH_LONG).show();
        }
    }

    /**
     * Called with the activity is first created.
     */
    @Override
    public void onCreate(Bundle voiceinput) {
        super.onCreate(voiceinput);

        // Inflate our UI from its XML layout description.
        setContentView(R.layout.voice_recognition);

        // check for TTS data
        Intent checkTTSIntent = new Intent();
        checkTTSIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
        startActivityForResult(checkTTSIntent, MY_DATA_CHECK_CODE);

    }

    // speak the user text
    public void speakWords(String speech) {

        // speak straight away
        myTTS.speak(speech, TextToSpeech.QUEUE_FLUSH, null);
    }

    public void onClick(View v) {
        speakWords("hello";
    }

    /**
     * Handle the results from the recognition activity.
     */
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (requestCode == MY_DATA_CHECK_CODE) {
            if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
                // the user has the necessary data - create the TTS
                myTTS = new TextToSpeech(this, this);
            } else {
                // no data - install it now
                Intent installTTSIntent = new Intent();
                installTTSIntent
                        .setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
                startActivity(installTTSIntent);
            }
        }

        super.onActivityResult(requestCode, resultCode, data);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        myTTS.shutdown();
    }


text:
Q: Plone custom template for content type Iam new to Plone. I followed the link http://plone.org/documentation/kb/creating-a-content-type-for-plone-3-for-developers and i added dvd content type. When i extend it by using http://plone.org/documentation/kb/creating-a-custom-template-for-a-plone-content-type, custom template is not showing.Iam getting the error as
Traceback (innermost last):
  Module ZPublisher.Publish, line 126, in publish
  Module ZPublisher.mapply, line 77, in mapply
  Module ZPublisher.Publish, line 46, in call_object
  Module Products.Five.browser.metaconfigure, line 476, in __call__
  Module Products.Five.browser.pagetemplatefile, line 125, in __call__
  Module Products.Five.browser.pagetemplatefile, line 59, in __call__
  Module zope.pagetemplate.pagetemplate, line 107, in pt_render
   - Warning: Compilation failed
   - Warning: zope.tal.taldefs.TALError: bad TAL attribute: u'', at line 27, column 4
PTRuntimeError: ['Compilation failed', "zope.tal.taldefs.TALError: bad TAL attribute: u'', at line 27, column 4"]

I know i made some mistake. I dont know whats that.Anyone help me?!...

A: If you look at the error :
Warning: zope.tal.taldefs.TALError: bad TAL attribute: u'', at line 27, column 4

It says that you have an attributes u'' that have nothing to do in a tal expression. Maybe something like
tal:attributes="u''"

somewhere in your template...


text:
Q: onEdit function not triggering Apps Script in Google Sheets I have been able to successfully create a simple script to take values I enter on a sheet ("Input") set up as a form and populate another sheet ("Current") set up to retain the values in columnar fashion. On my PC it activates with a button on the form.
Now I am trying to execute the script when I access the same form on my android phone where the button doesn't work. I decided to use the onEdit function which I was able to successfully use in a test application, but when I transfer in the code from my PC-based application I get no action.
function onEdit(e) {

      if (e.range.getA1Notation() !== 'F17') {
        return;
      }

var ss = SpreadsheetApp.getActiveSpreadsheet();
var formSS = ss.getSheetByName("Input");
var dataSS = ss.getSheetByName("Current");

//Input Values
var values = [[
formSS.getRange("D4").getValue(),
formSS.getRange("D8").getValue(),
formSS.getRange("E8").getValue(),
formSS.getRange("F8").getValue(),
formSS.getRange("D10").getValue(),
formSS.getRange("F10").getValue(),
formSS.getRange("I10").getValue(),
formSS.getRange("D15").getValue(),
formSS.getRange("E15").getValue(),
formSS.getRange("F15").getValue(),
formSS.getRange("D17").getValue(),
formSS.getRange("F17").getValue()
]];

dataSS.getRange(dataSS.getLastRow()+1, 1, 1, 12).setValues(values);

//Clear Values
formSS.getRange("D4").clearContent()
formSS.getRange("D8").clearContent()
formSS.getRange("E8").clearContent()
formSS.getRange("F8").clearContent()
formSS.getRange("D10").clearContent()
formSS.getRange("F10").clearContent()
formSS.getRange("D15").clearContent()
formSS.getRange("E15").clearContent()
formSS.getRange("F15").clearContent()
formSS.getRange("D17").clearContent()
formSS.getRange("F17").clearContent()

}

The plan is to use the entry of the last value ("F17") as the trigger to execute the script.

A: Main difference between your local file and online file is that when you call
formSS.getRange(CELL_ADDRESS).getValue();

you make a request to the server, so you make many requests to the server during your script execution.
onEdit(e) function has its own limits some details here so maybe (I did not tested it) it would be faster to do all data collecting with one line
var allDataInArray = formSS.getRange("D4:F17").getValues();

... and after that create your values[][] 2D array from allDataInArray ... place it in another sheet with your command
dataSS.getRange(dataSS.getLastRow()+1, 1, 1, 12).setValues(values);

... and set all values to "" in allDataInArray that you have done by clearContent() calls prevoiusly.
After that, you can make another request
formSS.getRange("D4:F17").setValues();

so all deleted content in allDataInArray will be pasted over values you deleted by clearContent() and other values will be replaced by own duplicate.
NOTE: I did not tested this variant...


text:
Q: How can I obtain a reference to the URL that was used to open my app with a link in iOS I have a problem with the situation where my React Native Expo app is running in the background / inactive modus and the app is brought back to the foreground / active mode as a result of the user opening a deep link to my app from the mobile browser.
When this situation occurs, my app needs to get a reference to the deep link in order to show the expected content to the user. The problem is that Linking.getInitialURL() always returns the link that was used to open the app from cold start and not the link that was used to bring the app back to foreground / active modus.
Advice on how to fix this problem would be greatly appreciated.

A: Found it out by myself :-)
    useEffect(() => {
        Linking.addEventListener('url', handleLinkEvent);

        return () => {
            Linking.removeEventListener('url', handleLinkEvent);
        };
    }, []);

For these cases you should use Linking.addEventListener

A: To complete @timboektoe's answer, react-navigation offers a subscribe function to listen to any URL received.
const subscribe = (listener) => {
  const onReceiveURL = ({ url }) => { listener(url); };
  const subscription = Linking.addEventListener('url', onReceiveURL);

  return () => {
    subscription.remove();
  };
};

const linking = {
  prefixes,
  config,
  getInitialURL,
  subscribe,
};


text:
Q: A website won't open, opens on iPhone over the same network I've suddenly lost complete access to a particular website. Every browser on both of my machines (a Windows laptop and an iMac running OS X) display a 'Cannot connect/No server found' error.
Meanwhile, Down For Everyone Or Just Me says that the website is up and that it's just me; on top of this, it opens fine in Mobile Safari on an iPhone that is connected to the same WiFi network.
I've tried rebooting the machines and restarting the router, but nothing has fixed the problem. What could possibly be the reason for this weird behaviour?

A: *

*Check out for transparent proxy servers in your network. These servers automatically redirect traffic through them if your system acquires IP from them.

*Also do the same for the browsers in your system.

*As for yout Iphone, it seems that it gets the IP directly from the router. Additionally also check out if the IP acquired by your Iphone and PC are of the same series.

*MAC configutation in the router generally blocks a few to many clients from access to network. Be sure to check that out too.
Hope this helps.

A: Try changing the DNS on your computer to OpenDNS 208.67.222.222 and 208.67.220.220.
If you were already using OpenDNS, change it back to your ISPs DNS servers (Google the name of your ISP and the keywords "DNS servers").
References:

*

*http://www.opendns.com/


text:
Q: Copy installed ghc and all packages to another machine I am facing a peculiar problem. Here at high school I have got about 10 computers (all are same type, same type cpu, same type memory etc) donated which are now running Debian after reinstall. I was try to teach the pupils some Haskell, I myself learned it little. The kids are interested. A problem is our country is third world and the internet is very slow and costly. The basic ghc and ghci I installed using deb packages (found by using apt-rdepends) on all machines after once downloading all of the deb files only on one machine using some limited time free internet connection. It has taken more than 10 hours to download the all ghc deb files that are missing.
I want know if such trick is possible for cabal? I will download all required tar or other files once, on one computer, using the costly and slow internet, but then I do not want spend all my money to download from internet for all 10 computers.
I want show the kids diagrams and gloss package as it is enjoyable and funny.
I am inspired by this gentleman Smith
How should I do this ? Is there way for other packages in general other than diagrams and gloss?
Thank you and sorry for my bad English.

A: By default, cabal caches each package it downloads to ~/.cabal/packages (and prefers its cache to re-fetching the package unless you explicitly request a re-fetch). So it should be simple enough to just copy that directory between computers.
This would still require you to build all the packages on each machine. If you would prefer to skip even that step, you could consider directly copying GHC's package database around to each of the machines. This is a bit more delicate, but could save quite some time/power.
The global package database (where you should be installing packages that you want to be shared between users) is in /usr/local/lib/ghc-$version by default, and you should be able to copy that directory around to all your computers as well. You can check that you have installed the packages you want into the global database using ghc-pkg list, which will list all the package/version combos installed, separating them by whether they are installed in the global or user package database.

A: In the past I have done this to get GHC and Cabal working on a machine behind a firewall that "cabal install" couldn't see through.
You can use "wget" to download the latest version of every Hackage package. (Or you might try doing something similar with Stack, but I haven't tried that). Also download https://hackage.haskell.org/packages/index.tar.gz, which is the index file.
Install GHC, cabal and cabal-install, and then find the cabal-install configuration file and point it at a local repository containing the index.tar.gz package and the archives for the packages that you downloaded. Then hopefully you should find "cabal install" will work from the local repository.


text:
Q: Rails 5.2 ActiveStorage - How to Determine If An Image Is Newly Uploaded Rails version - 5.2.3
Is there a way to determine whether an image (or any file for that matter) is a new attachment? I want a method in my model to simply return if a certain file is not a new attachment but assign that file's URL/path to an attribute of the model if it's newly attached.
I tried the image.new_record? call but it always returns false. Of course the image.attached? will always return true as long as I have already uploaded files in the db.
models/user.rb (only relevant lines shown)
class User < ApplicationRecord
  include Rails.application.routes.url_helpers

  before_update :assign_profile_pic, :assign_cover_pic

  has_many_attached :profile_images
  has_many_attached :cover_images

  private

  def assign_profile_pic
    return unless profile_images.attached?

    self.profile_pic = rails_blob_path(profile_images.last, only_path: true)
  end

  def assign_cover_pic
    return unless cover_images.attached?

    self.cover_pic = rails_blob_path(cover_images.last, only_path: true)
  end

end

users_controller.rb (only update action and user_params shown):
def update
    user = find_user
    return unless user

    authorize user
    if user.update(user_params)
      render :show, locals: { user: user }, status: :accepted
    else
      process_error(user, 'Cannot update user')
    end
end

private

def user_params
    params.require(:user).permit(
      :email,
      :username,
      :password,
      :password_confirmation,
      :first_name,
      :last_name,
      :middle_name,
      :bio,
      :birthday,
      :gender,
      profile_images: [],
      cover_images: []
    )
  end

What I need to happen is that assign_profile_pic and/or assign_cover_pic will simply return if I am not uploading a new image (in the update action of the controller). For instance I just want to reassign the profile_pic to an already previously uploaded image (which may or may not be profile_images.last). However, so far as I've researched, there's no way to determine if a particular file is a new attachment.
I have a workaround, it's putting the logic in the update action:
def update
    user = find_user
    return unless user

    authorize user
    if user.update(user_params)
      # i can check here whether user_params[:profile_images] is nil or not

      user.assign_profile_pic unless user_params[:profile_images].nil?
      user.assign_cover_pic unless user_params[:cover_images].nil?

      render :show, locals: { user: user }, status: :accepted
    else
      process_error(user, 'Cannot update user')
    end
  end

Which also means assign_profile_pic and assign_cover_pic are going to be public methods in the User model (and include the line save in each of them).
I am a little uncomfortable with this workaround, though. It's because it's adding another call to the database right below user.update and then it adds complexity to the controller (it's not as thin as it should be).
What's the best way to do this?


text:
Q: Sticky footer issue I am new to web styling , so please bear with me .I have a html content and a style sheet as below and it works just fine without the floating footer issue. But a lot of solutions have been created by various developers and I am sure for a good reason (eg. http://ryanfait.com/resources/footer-stick-to-bottom-of-page/). I would like to know if the css defined for the below page layout to keep the footer at the bottom of the page is insufficient and if it will create a problem in future in some scenario.
CSS :
html,body {
    height:100%;
}

#body {
height:75%;
}

HTML

 This is the header

 This is the body

 This is a footer

A: Try making you footer css like this:
position:absolute;
bottom: 0px;


text:
Q: Facebook JS SDK Does Not Set fbs_* Cookie in Safari I've read a few posts about how to fix this, to sum it up:

*

*Manually create the fbs_* cookie during the first POST request to your app

*Add a "Start App" link, when the user clicks it Safari lets you set cookies (http://lightyearsoftware.com/2009/11/on-the-pain-of-developing-for-facebook/)

*Create and submit a form client side (http://anantgarg.com/2010/02/18/cross-domain-cookies-in-safari/)

None of that seems to work, I'm questioning whether or not that information is still valid (I'm on Safari 5.0.5). I need to use the fbs cookie to properly authenticate the user on the server side, and this works on every other browser. I can't set any cookies on the initial POST request, and the client-side form submit doesn't work either. Does Safari not let you set third party cookies even on a POST anymore?

A: The reason cookies are rejected is a default "third party cookies" policy in Safari.
To properly authenticate the user you better stay away from manual usage of fbs_* cookies placed by Facebook's JS (or any other) SDK and use FB.getSession / FB.getAuthResponse and/or FB.getLoginStatus from JS SDK. On the server side you can use signed_request parameter passed to all Canvas and Page Profile Tab applications.


text:
Q: Why obj is not iterable While compiling this code I am getting an error that obj is not iterable. Why? I have to check how many users are online
let users = {
  Alan: {
    age: 27,
    online: false
  },
  Jeff: {
    age: 32,
    online: true
  },
  Sarah: {
    age: 48,
    online: false
  },
  Ryan: {
    age: 19,
    online: true
  }
};

function countOnline(obj) {
  let num =0;
  for(let user of obj){
    if(user['online']==true){
      num++;
    }
  }
  return num;
}

console.log(countOnline(users));

A: Because you are using for...of instead of for...in.
for...of is used for looping over iterable objects while for...in iterates over the enumerable properties of an object. For for...of to work, the object must implement the @@iterator method (Array, string, Set etc)

let users = {
  Alan: {
    age: 27,
    online: false
  },
  Jeff: {
    age: 32,
    online: true
  },
  Sarah: {
    age: 48,
    online: false
  },
  Ryan: {
    age: 19,
    online: true
  }
};

function countOnline(obj) {
  let num = 0;
  for (let user in obj) {
    if (obj[user]['online'] == true) {
      num++;
    }
  }
  return num;
}

console.log(countOnline(users));

In for...in, the user variable will represent key of the object like Alan. So, to get the value of the property, you need to do use obj[user] (eg: obj["Alan"]). So, the condition will be changed to:
if (obj[user]['online'] == true)

A: Objects don't have the @@iterator symbol by default , to use for..of you'll need to add it to the object :

let users = {
  Alan: {
    age: 27,
    online: false
  },
  Jeff: {
    age: 32,
    online: true
  },
  Sarah: {
    age: 48,
    online: false
  },
  Ryan: {
    age: 19,
    online: true
  }
};

users[Symbol.iterator] = function*() {
  for (value of Object.values(this)) {
    yield value;
  }
};

for (let user of users) {
  console.log(user)
}

Or use for..of with Object.entries ( or Object.values )

let users = {
  Alan: {
    age: 27,
    online: false
  },
  Jeff: {
    age: 32,
    online: true
  },
  Sarah: {
    age: 48,
    online: false
  },
  Ryan: {
    age: 19,
    online: true
  }
};

for (let [key, value] of Object.entries(users)) {
  console.log('key :', key, 'value : ', value)
}

console.log('***********');

for (let user of Object.values(users)) {
  console.log({user})
}


text:
Q: I can't connect to my database using java Connection conn = null;
Statement stmt=null;
ResultSet rset=null;
String jdbc_url="jdbc:oracle:thin:hr/hr@bassam-desktop:1521:XE";
String query="";
try
{
    DriverManager.registerDriver(new oracle.jdbc.OracleDriver());
    conn=DriverManager.getConnection(jdbc_url);
    stmt=(Statement) conn.createStatement();
    query="select first_name" +"from employees"+"where employeed_id=100";
    rset=stmt.executeQuery(query);
    System.out.println(rset.getString(1));

}
catch(SQLException | NumberFormatException e)
        {
            System.out.println("result error");
        }
finally{
    try{
        rset.close();
        stmt.close();
        conn.close();

    }
    catch(Exception e)
    {
        System.out.println("Error in closing");
    }
}

I'm getting both errors in the results window, what is the problem? hr password is correct, my host name is correct, isn't it the one you get from "Computer Name" after you right click on "My Computer" in windows xp ?
Edit: After using e.getMessage(), i got this..
result error, ResultSet.next was not called

A: The error message of the exception, that you have put in the comments, tells you what's wrong:

result error, ResultSet.next was not called

You forgot to call ResultSet.next() before accessing the first row of the result set:
if (rset.next()) {
    System.out.println(rset.getString(1));
}

A: Because you're using Netbeans IDE, you can try connecting with their built in tool. That should help you get the jdbc_url right (which is almost certainly the problem). Also, don't forget to download and include in your classpath the ojdbc6.jar (which would definitely be the problem if you're not including it).

A: The e variable represent the exception. try to print the e.getMessage() or print the stack trace with e.printStackTrace() to understand better the problem.

A:  ResultSet rset = stmt.executeQuery();
 while(rset.next()){
     //Code that works with results
 }


text:
Q: Image processing algorithme idea - Opencv I'm trying to isolate little object (black objects) in semolina like the image below. I use OpenCV 3.1 in C++.
I try different method and the best that I found is below. But the result is not good as I want.
I only want to have my black objects at the final.
Original Image :

So I convert my image to grayscale, and apply GaussianBlur and a large Blur in order to have a background.
GaussianBlur(img_gray, img_inter, Size(21, 21), 0, 0);
blur(img_inter, img_blur, Size(51, 51), Point(-1,-1), 0);

Background Image :

After, I subtract my background to my original image:
Subtracted Image :

And the final image after opening operation, threshold and opening again :
Result Image :

The code below :
cvtColor(*img_in, img_gray, CV_BayerGB2GRAY);

GaussianBlur(img_gray, img_inter, Size(21, 21), 0, 0);

blur(img_inter, img_blur, Size(51, 51), Point(-1,-1), 0);

img = (255 - img_gray) - (255 - img_blur); // Background subtraction

morphologyEx(img, img_inter, cv::MORPH_OPEN, cv::getStructuringElement(cv::MORPH_ELLIPSE, cv::Size(3, 3)),Point(-1,-1), 1);
threshold(img_inter, img, 50, 255, CV_THRESH_BINARY);
morphologyEx(img, img_inter, cv::MORPH_OPEN, cv::getStructuringElement(cv::MORPH_ELLIPSE, cv::Size(3, 3)), Point(-1, -1), 1);

If you have any ideas to improve the result, thanks you


text:
Q: Can't Open my Downloaded PDF I have a Code Below in which it Successfully downloading a .pdf file but when i open the file it always shows an error message. This is my Code:
    include("MPDF57/mpdf.php");
$mpdf=new mPDF('c','A4','','',32,25,27,25,16,13);
$mpdf->SetDisplayMode('fullpage');
$mpdf->showImageErrors = true;

$mpdf->list_indent_first_level = 0; // 1 or 0 - whether to indent the first level of a list

$html='Test'; //Assign HTML HERE

$mpdf->WriteHTML($html);
$mpdf->Output('Certificate.pdf','D');

Please do help guys, Thanks in Advance.

A: use header("Content-type:application/pdf");

A:
Try this one..will help you..

http://stackoverflow.com/questions/9248510/working-with-pdf-in-php


text:
Q: How Tasklets works? Does interrupts are disabled while tasklets are being processed since they should run in interrupt context.If they are disbled while a tasklet is being processed then what is the point of calling them bottom halve mechanism since it is same case as top of where the interrupts are disabled.
Or is it like tasklets will be useful only on multi processor system where the interrupts are generated on one processor and the corresponding tasklet is scheduled on another processor with interrupts being disbled on another processor when the tasklet is running.
Please clarify.

A: Linux divides interrupt processing in two parts:

*

*First, you handle the interrupt request (IRQ) in as simple a manner as possible, doing as little as you can, and scheduling a softirq/tasklet to do the heavier part of the processing.

*Then, the softirq/tasklet gets scheduled, and the heavy processing starts.

The contexts in Linux are:

*

*NMI context

*hardirq context: the first part of interrupt processing above.

*softirq context: the second part of interrupt processing above.

*interrupt context: any of the above.

*process/user context: running on behalf of a process, e.g: due to a syscall. The opposite of interrupt context.

*atomic context: interrupt context, or in process context in a section of code that must be atomic (cannot be interrupted), e.g: because we have taken a spinlock.
Interrupts are not disabled while running a tasklet. Further invocations of the same tasklet are.


text:
Q: Regular expression explanation (0+1)*1(0+1)* I'm trying to understand the regular expression:
(0+1)*1(0+1)*
Could you provide examples that matches this pattern?
0+1 means union.
It sounds like logical OR, isn't it? Should we choose between 0 or 1?
01 means concatenation.
It sounds like logical AND, isn't it? Should we use 01 digits together?
(0+1)* means iteration.
Could we iterate 0 or 1 n times? Does 000011110000 match (0+1)* pattern?

A: If this is to be interpreted as a regex, it matches expressions that contain
zero or more sequences of
    (one or more zeros followed by a single one),
followed by a single one,
followed by zero or more sequences of
    (one or more zeros followed by a single one)

As a boolean algebra expression, if you remove the star, it evaluates to
(false OR true) AND true AND (false OR true)

which evaluates to true.

A: (0+1)*1(0+1)*

If this is a regular expression, it will match
zero digit once or more in a row, followed by "1" digit once
above combination zero or more times, followed by "1" digit
followed by zero digit once or more followed by 1 digit once
above line zero or more times.
+

in REGEX means "once or more times" appearance of preceding character
*

in REGEX means "zero or more times" appearance of preceding character
And common brackets "()" are used for grouping an extension.
"0" and "1" in this case are used literally as characters, not as they're numeric values.
to understand how it works, consider the following regex:
(a+b)*c(d+e)*

with letters understood literally, not as variables.

A: Here is the output of YAPE::Regex::Explain:
The regular expression:

(?-imsx:(0+1)*1(0+1)*)

matches as follows:

NODE                     EXPLANATION
----------------------------------------------------------------------
(?-imsx:                 group, but do not capture (case-sensitive)
                         (with ^ and $ matching normally) (with . not
                         matching \n) (matching whitespace and #
                         normally):
----------------------------------------------------------------------
  (                        group and capture to \1 (0 or more times
                           (matching the most amount possible)):
----------------------------------------------------------------------
    0+                       '0' (1 or more times (matching the most
                             amount possible))
----------------------------------------------------------------------
    1                        '1'
----------------------------------------------------------------------
  )*                       end of \1 (NOTE: because you are using a
                           quantifier on this capture, only the LAST
                           repetition of the captured pattern will be
                           stored in \1)
----------------------------------------------------------------------
  1                        '1'
----------------------------------------------------------------------
  (                        group and capture to \2 (0 or more times
                           (matching the most amount possible)):
----------------------------------------------------------------------
    0+                       '0' (1 or more times (matching the most
                             amount possible))
----------------------------------------------------------------------
    1                        '1'
----------------------------------------------------------------------
  )*                       end of \2 (NOTE: because you are using a
                           quantifier on this capture, only the LAST
                           repetition of the captured pattern will be
                           stored in \2)
----------------------------------------------------------------------
)                        end of grouping
----------------------------------------------------------------------

A: Basically (0+1)* mathes any sequence of ones and zeroes. So, in your example (0+1)*1(0+1)* should match any sequence that has 1. It would not match 000, but it would match 010, 1, 111 etc.
(0+1) means 0 OR 1.
1* means any number of ones.
11* or 1+ means one or more occurences of 1.


text:
Q: Variable name "value" is getting error in objective-c and swift combined project Created variable "value" in Objective-C file.
Then import this file in App-Bridging-Header.h file.
Then getting following error.

Before import in App-Bridging-Header.h file it's working.
After import in App-Bridging-Header.h file it's not working.


text:
Q: XSLT Intellisense in Visual Studio 2008 I have an XML file which in addition to it's standard XML schema allows the use of XSLT.
I am including the correct namespace for XSLT (xmlns:xsl="http://www.w3.org/1999/XSL/Transform") however I am not receiving Intellisense for XSLT when I start typing xsl: tags.
Is it possible to turn this on? When I edit XSLT files it works absolutely fine.

A: The Xml editor does support the standard xsl intellisense but it will strictly apply the schema.  Hence you first need to enter a <xsl:stylesheet> and start adding children to it before you will see any xsl options.  This is because all other other xsl elements need be children of either the xsl:stylesheet element or some other xsl element.

A: XSLT Intellisense is a hidden feature of VS 2008. It has to be enabled by setting a Registry key (http://memoryleak.me.uk/2008/11/xslt-intellisense-in-visual-studio-2008.html):

First, make sure you have the xslt.xsd
  file in the C:\Program Files\Microsoft
  Visual Studio 9.0\Xml\Schemas folder.
  If not, copy it from VS2005.
Next, add a new string value to the
  registry named XsltIntellisense
  under
  HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\9.0\XmlEditor
  and set the value to True. This will
  enable some other nice features to the
  standard tag completion stuff.

This hint came originally from http://www.tkachenko.com/blog/archives/000740.html


text:
Q: using countif with named range I am attempting to count the number of occurrences entries in a column that are referenced in a named range.
column J contains a list of locations.  I created a named range "Locations".
I am using =COUNTIF(J6:J217,locations), but the result is only returning results for some of the locations, and only 1 occurrence of the value, instead of each occurrence.
How can I return a count of all the occurrences of the values referenced in my named range "Locations"?

A: Use SUMPRODUCT to iterate the list:
=SUMPRODUCT(COUNTIF(J6:J217,locations))


text:
Q: yii2 resize images maintaining aspect ratio with Imagine I got this code in yii2:
Image::thumbnail($path, 100, 100)->save($thumbnail, ['quality' => 50]);

I thought that it will resize the original image maintaining the aspect ratio.
But it just creates a box...
What can be wrong?

A: You may use like that:
use Imagine\Image\Box;

Image::frame($path)
->thumbnail(new Box(100, 100))
->save($thumbnail, ['quality' => 50]);

A: I am using like this in Yii2 and it works fine.
It also keeps the aspect ratio perfect releted to width.
use yii\imagine\Image;
use Imagine\Image\Box;

 ...

$imagine = Image::getImagine()
->open($resizeImagePath)
->thumbnail(new Box(120, 120))
->save($thumbnailImagePath, ['quality' => 90]);

A: I have made a simple code to maintain the aspect ratio of an image.
use yii\imagine\Image;

.................................................................
public function doResize($imageLocation, $imageDestination, Array $options = null)
{
    $newWidth = $newHeight = 0;
    list($width, $height) = getimagesize($imageLocation);

    if(isset($options['newWidth']) || isset($options['newHeight']))
    {
        if(isset($options['newWidth']) && isset($options['newHeight']))
        {
            $newWidth = $options['newWidth'];
            $newHeight = $options['newHeight'];
        }

        else if(isset($options['newWidth']))
        {
            $deviationPercentage = (($width - $options['newWidth']) / (0.01 * $width)) / 100;

            $newWidth = $options['newWidth'];
            $newHeight = $height - ($height * $deviationPercentage);
        }

        else
        {
            $deviationPercentage = (($height - $options['newHeight']) / (0.01 * $height)) / 100;

            $newWidth = $width - ($width * $deviationPercentage);
            $newHeight = $options['newHeight'];
        }
    }

    else
    {
        // reduce image size up to 20% by default
        $reduceRatio = isset($options['reduceRatio']) ? $options['reduceRatio'] : 20;

        $newWidth = $width * ((100 - $reduceRatio) / 100);
        $newHeight = $height * ((100 - $reduceRatio) / 100);
    }

    return Image::thumbnail(
        $imageLocation,
        (int) $newWidth,
        (int) $newHeight
    )->save(
        $imageDestination,
        ['quality' => isset($options['quality']) ? $options['quality'] : 100]
    );
}

You can use it, like:
(new TheClass)->doResize($imageLocation, $imageDestination, [
    'quality' => 70,
    'reduceRatio' => 50
]);

// or like this
(new TheClass)->doResize($imageLocation, $imageDestination, [
    'quality' => 70,
    'width' => 500,
]);

// or like this
(new TheClass)->doResize($imageLocation, $imageDestination, [
    'quality' => 70,
    'height' => 500,
]);

// and like this (but will break the aspect ratio)
(new TheClass)->doResize($imageLocation, $imageDestination, [
    'quality' => 70,
    'width' => 100
    'height' => 500,
]);


text:
Q: Compare two columns of factors from two data frame, get the entries exist in both data frame in r I have two data frames:
df1
vehicle  speed  time
a         23     234
b         34     421
d         45     290

df2
vehicle  speed  time
a         29     215
b         54     450
c         45     21
f         40     367

Both vehicle columns are factors. I want to find the common vehicles and add the corresponding df2$time to df1, name it as time.2.
The output I want:
df1
vehicle  speed  time    time.2
a         23     234     215
b         34     421     450

I tried:
df1 <- df1[df1$vehicle %in% df2$vehicle, ]
df2 <- df2[df2$vehicle %in% df1$vehicle, ]
df1 <- cbind(df1, time.2 = df2$time)

But after the first two commands, both df1 and df2 have 0 rows inside. I have tried before, when I use another data frame to compare the vehicle with df1, it works. I don't why df2 doesn't work.
Thanks!

A: Try:
library(dplyr)

inner_join(df1,
           df2 %>%
             select(-speed) %>%
             rename(time.2 = time) )

A: Use the merge() function:
df1$vehicle <- as.character(df1$vehicle)
df2$vehicle <- as.character(df2$vehicle)
df <- merge(df1, df2, by="vehicle")
df <- df[, c("vehicle.x", "speed.x", "time.x", "time.y")]