Q:

how do I create a file object from an absolute pathname?

I think my problem will take some explaining of the background. My assignment is to create a basic server that will send HTML files on my system that clients request. I was told to test my server by just entering localhost:8080/index.html in my firefox browser as a test client. Entering in that line of input works correctly and prints out the contents of index.html. As a safety, I am suposed to test to make sure that the requested file is within my current working directly, and if its not I should deny the request. I have set up just such a catch and I want to check it. I want to use my file index.html again, but by the entire pathname aka
C:\Users\Gabrielle\Documents\NetBeansProjects\CS2 Assignment 5\src\index.html So I enter in my browser
localhost:8080/C:\Users\Gabrielle\Documents\NetBeansProjects\CS2 Assignment 5\src\index.html
and I am given an error that says the file doesn't exist. I then checked to see what it was trying to make a file out of and its trying to make a file out of and I get
C:%5CUsers%5C%5CGabreille%5C%5CDocuments%5C%5CNetBeansProjects%5C%5CCS2%20Assignment%205%5Cindex.html
which clearly isn't the name of the file. Am i just sending in the file name incorrectly? If it makes any difference, I am running the program from the windows command prompt. Below is the code for my multi-threaded client and the code for my runnable object. If you have any questions or want some clarity, Ill be closely watching this thread.
import java.io.*;
import java.net.*;

public class WebServer {

    public static void main(String[] args)
    {
        try{
            ServerSocket ss = new ServerSocket(8080);
            while(true){
                Thread conn = new Thread(new ClientConnection(ss.accept()));
                conn.start();
            }
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }
    }
}

Here's the actual content
import java.io.*;
import java.net.*;

public class ClientConnection  implements Runnable{

private Socket socket;
File requestedFileName;
String entireInput ="";
String editedInput="";
String fileContent="";
String fileLine="";
PrintWriter out;
File defaultFile = new File("index.html");
File toBeRead;

public ClientConnection(Socket socket)
{
    this.socket=socket;
}

public void run()
{
    try{
        System.out.println("Client Connected");
        String workingDirectory = System.getProperty("user.dir");
        BufferedReader in =
                new BufferedReader(new InputStreamReader(socket.getInputStream()));
         out = new PrintWriter(socket.getOutputStream());
        String line;
            entireInput = in.readLine();

        editedInput= entireInput.substring(entireInput.indexOf("GET")+3,
                entireInput.indexOf("HTTP/1.1"));
        System.out.println("File name:" + editedInput);
        requestedFileName = new File(editedInput);
        System.out.println("What about here?");
        if(editedInput.equals(" / ") || editedInput.equals("  "))
        {
            toBeRead = defaultFile;
            System.out.println("Parent file "+toBeRead.getParent());
            String absolutePath = toBeRead.getAbsolutePath();
            System.out.println("absolute path "+ absolutePath);
            String filePath = absolutePath.substring(0,absolutePath.lastIndexOf(File.separator));
            if(filePath.equals(workingDirectory))
            {
                System.out.println("is in directory");
            }
            else{
                System.out.println("not in directory");
            }
        }
        else
        {

            String hope = editedInput.substring(2);
            toBeRead = new File(hope);
        }

             //toBeRead = new File("index.html");
            if(toBeRead.exists())
            {
                System.out.println("File exists");
            }
            else
            {
                System.out.println("file doesn't exist");
            }
           BufferedReader fileIn = new BufferedReader(new FileReader(toBeRead));

           while((fileLine = fileIn.readLine()) != null)
             {
               //System.out.println("can i get in while loop?");
               fileContent = fileContent + fileLine;
                //System.out.println("File content: \n" + fileContent);
             }

           out.print("HTTP/1.1 200 OK\r\n");
           out.print("content-type: text/html\r\n\r\n");
           out.print(fileContent);
           out.flush();
           out.close();

        }
        catch(FileNotFoundException f)
        {
            System.out.println("File not found");
            out.print("HTTP/1.1 404 Not Found\r\n\r\n");
            out.flush();
            out.close();
        }
        catch(Exception e)
        {
            out.print("HTTP/1.1 500 Internal Server Error\r\n\r\n");
            out.flush();
            out.close();
        }

    }
}

A:

You're giving the file a relative path and expecting it to magically find the file.  Relative paths are resolved relative to where your JVM was started.  If you want an absolute path you'll need to do something like:
new File("C:\\Users\\Gabrielle\\Documents\\NetBeansProjects\\CS2 Assignment 5\\src\\index.html");

You're not getting that from the request to your application because the request is URLEncoded.
Of course, the better solution would be to have the file in a reasonable place relative to your application and reference it relatively.


Q:

How to show unbiased estimator of combination of bernoulli and normal variables?

$X_1, X_2, \ldots, X_n$ is a random sample from $\mathrm{Bernoulli}(\theta)$, $\epsilon_1, \epsilon_2, \ldots, \epsilon_n$ are independent $\mathcal N(0, \sigma^2)$, independent of $X_i$.
Define $Y_i = \theta X_i + \epsilon_i$, for $i = 1, 2, \ldots,n$. Define estimating function
$$
\psi[\theta;(X,Y)] = \sum_{i =1}^n(Y_i - \theta X_i) \>.
$$
a) Show that $\psi[\theta;(X,Y)]$ is unbiased estimator of $\theta$ if $\mathbb E(\psi[\theta;(X,Y)])=0$.
b) Find the estimator $\hat\theta$ such that $\psi[\hat\theta;(X,Y)] = 0$. Is $\hat\theta$ unbiased?

A:

I'm still not quite sure how part (a) is different from part (b) but, from your comment above it appears you are now only asking about part (b), so:
If $\psi[\hat{\theta};(X,Y)] = 0$, then
$$
\sum_{i =1}^n(Y_i - \hat{\theta} X_i) \> = 0
$$
So,
$$ \sum_{i=1}^{n} Y_i = \hat{\theta} \cdot \sum_{i=1}^{n} X_i $$
Therefore $\hat{\theta} = \overline{Y}/\overline{X}$, the ratio of the sample means, satisfies  $\psi[\hat{\theta};(X,Y)] = 0$. Regarding unbiasedness, it is easy to see that
$$ E( \hat{\theta} ) = E\left( \frac{ \sum_{i=1}^{n} \theta X_i + \varepsilon_{i} }{ \sum_{i=1}^{n} X_i }\right) = \theta + E \left( \frac{ \sum_{i=1}^{n} \varepsilon_i }{
\sum_{i=1}^{n} X_i }\right), $$
Edit: Based on the discussion in the comments, I've edited my answer. Let $B=\sum_{i=1}^{n} X_{i}$ and $Z = \sum_{i=1}^{n} \varepsilon_i$. Then, $B \sim {\rm Binomial}(n,\theta)$ and $Z \sim N(0, n \sigma^{2})$.
Since the errors are independent of the $X_{i}$,
$$
E \left( \frac{ \sum_{i=1}^{n} \varepsilon_i }{
\sum_{i=1}^{n} X_i }\right)
= E(Z) \cdot E \left( \frac{1}{B} \right) $$
Clearly $E(Z) = 0$. Assuming $\theta < 1$, $P(B = 0) = (1-\theta)^{n} > 0$. Therefore $E \left( \frac{1}{B} \right) = \infty$, so
$E \left( \frac{ \sum_{i=1}^{n} \varepsilon_i }{
\sum_{i=1}^{n} X_i }\right)$ doesn't exist. Therefore $E(\hat{\theta})$ doesn't exist whenever $\theta < 1$, so $\hat{\theta}$ can't be unbiased (although it is consistent as long as $\theta > 0$).


Q:

Substring with Excel VBA

I have been using this code as a starting point: https://danwagner.co/how-to-transpose-horizontal-data-to-vertical-data-for-easy-pivot-tables/
One one of my cells Ax (x referring to the number), the content is ABCDEFGHI and I want to substring the cells every 2 characters, and the last set is 3 characters. Final result looks like:
AB CD EF GHI
At line 44, using the variable
varDetails = .Range(.Cells(lngIdx, 1), .Cells(lngIdx, 4))

and think that is where I need to modify the code. I am not fluent enough with VBA and need some help.

A:

To split the data from your string you can use the following code
Sub SplitStringEveryTwoCharacters()
    Dim arrayWithValuesByTwo() As String
    Dim myString As String

    'Just replace with your data
    myString = "ABCDEFGHIJKLM"

    'Resize
    ReDim arrayWithValuesByTwo(Len(myString) - 1)

    'For each 2 character in string
    For i = 1 To Len(myString) Step 2
        'Add in array
        If (i <= Len(myString) - 1) Then
            arrayWithValuesByTwo(i - 1) = Mid$(myString, i, 2)
        End If

        If (i = Len(myString)) Then
            arrayWithValuesByTwo(i - 1) = Mid$(myString, i, 1)
        End If
    Next
End Sub

What you need to change
Here I have set my string into a variable with myString = "ABCDEFGHIJKLM" but you can easily change this and take it directly from a cell with something like myString = Range("A5").
You can access you data with arrayWithValuesByTwo(1) for example. Just loop through it to get all of the values.


Q:

Can't change FBSDKLoginButton position

I'm have the Facebook login button to my app, but when I can't move it from the top left corner to the center of the screen.
I tried:
 loginButton.center = (self.view?.center)!

and
loginButton.frame = CGRect(origin: CGPoint(x: self.frame.midX,y :self.frame.midY), size: CGSize(width: loginButton.frame.width, height: loginButton.frame.height))

but neither worked, the center variable changes but the button remains in the top left corner
Does anyone knows how to fix this?
I'm adding the button with this code
let loginButton: FBSDKLoginButton = {
        let button = FBSDKLoginButton()
        button.readPermissions = ["email"]
        button.translatesAutoresizingMaskIntoConstraints = false
    return button
    }()
view.addSubview(loginButton)

A:

You should set your code like this:
    let loginButton = FBSDKLoginButton(frame: CGRect(x: 0, y: 0, width: //whatever width you want, height: //whatever height you want))
    loginButton.readPermissions = ["email"]
    loginButton.center = view.center
    view.addSubview(loginButton)

Refer to https://developers.facebook.com/docs/facebook-login/ios#loginkit


Q:

How to get the the source data of all the series of a chart in VBA?

With ActiveWorkbook.Sheets(1)
INSPECT_CHARTS_NUMBER = .ChartObjects.Count
For c= 1 To .ChartObjects.Count
Set INSPECT_CHART = .ChartObjects(c).Duplicate

.ChartObjects(c).Chart.SetSourceData Source:=.Range("e4:h4")

Next lngC
End With

I do the above to change the source data of a chart in VBA this line .Chart.SetSourceData Source:=.Range("e4:h4")does do job, but this will not work if there are multiple series in that chart.
How can I get the sourcedata of all the series and then how can I change them separately?

A:

Here is an example
Let's say the series collection of the active chart is picking the values from A1:A5 and C1:C5. So the below code will change the source to A8:A12 and C8:C12
Dim sc As SeriesCollection
Dim i as Long, j as Long

j = 1

For i = 1 To ActiveChart.SeriesCollection.Count
    ActiveChart.SeriesCollection(i).Values = "=Sheet1!R8C" & j & ":R12C" & j
    j = j + 2 '<~~ Adding 2 for Col C
Next

Screenshot
Before

After

A:

Use .seriescollection
Set ChartSeries = ChartObj.Chart.SeriesCollection.NewSeries

With ChartSeries
    .Name = "Chart Series 1"
    .Values = Array(1, 2, 3, 4, 5)
    .XValues = Array("alpha", "beta", "gamma", "delta", "epsilon")
End With

More on this link.


Q:

Regular expression for name with parentheses

so first time trying to come up with regular expression validation and im a bit confused. User populates the 'name' section of our form like so:
Lastname, firstname (department).

but it could also be
 lastname-hyphenedname, firstname (some department).

or anything along those lines. im having a hard time finding an expression that works around parentheses and various name formats with hyphens. Anyone happen to know a quick expression for this?

A:

^([A-Za-z]+([-']?|\s+))*[A-Za-z]+,\s*([A-Za-z]+([-']?|\s+))*[A-Za-z]+\s*(\([A-Za-z\s]+\))?$
Name which may contain one or more a hyphen parts or parts separated by spaces or ', then comma, maybe some spaces, then an first-name (maybe with hyphens or spaces or '), maybe some spaces, then (name with spaces in brackets). PCRE.


Q:

coreplot pie chart example

I am trying to follow the tutorial at http://www.raywenderlich.com/13269/how-to-draw-graphs-with-core-plot-part-1
I am working on ios 7 and latest core chart library (1.3)
I am trying to draw a pie chart. My example compiles fine, I get the title header but I do not get any pie chart drawn. What I see is shown below:

My main source code that contains the logic is given below. Kindly help
//
//  CPDFirstViewController.m
//  CorePlotDemo
//
//  Created by R Menon on 9/19/13.
//  Copyright (c) 2013 4stepfinance Inc. All rights reserved.
//

#import "CPDPieChartViewController.h"

@interface CPDPieChartViewController ()
@property (weak, nonatomic) IBOutlet UIToolbar *toolbar;
@property (weak, nonatomic) IBOutlet UIBarButtonItem *themeButton;

@property (strong, nonatomic) CPTGraphHostingView *hostView;
@property (strong, nonatomic) CPTTheme *selectedTheme;
- (void)initPlot;
-(void)configureHost;
-(void)configureGraph;
-(void)configureChart;
-(void)configureLegend;
@end

@implementation CPDPieChartViewController
#pragma mark - Chart behavior

- (void)initPlot {
    [self configureHost];
    [self configureChart];
    [self configureGraph];
    [self configureLegend];
}

-(void)configureHost {
    // Set up view frame
    CGRect parentRect = self.view.bounds;
    CGSize toolbarSize = self.toolbar.bounds.size;
    parentRect = CGRectMake(parentRect.origin.x, (parentRect.origin.y + toolbarSize.height), parentRect.size.width, (parentRect.size.height - toolbarSize.height));

    // Create host view
    self.hostView = [(CPTGraphHostingView *) [CPTGraphHostingView alloc] initWithFrame:parentRect];
    self.hostView.allowPinchScaling = NO;
    [self.view addSubview:self.hostView];
}

-(void)configureGraph {
    //Create and initialize graph
    CPTGraph *graph = [[CPTXYGraph alloc] initWithFrame:self.hostView.bounds];
    self.hostView.hostedGraph = graph;
    graph.paddingLeft = 0.0f;
    graph.paddingTop = 0.0f;
    graph.paddingRight = 0.0f;
    graph.paddingBottom = 0.0f;
    graph.axisSet = nil;
    // Set up text stile
    CPTMutableTextStyle *textStyle = [CPTMutableTextStyle textStyle];
    textStyle.color = [CPTColor grayColor];
    textStyle.fontName = @"Helvetica-Bold";
    textStyle.fontSize = 16.0f;

    // Configure title
    NSString *title = @"Portfolio Prices: May 1, 2012";
    graph.title = title;
    graph.titleTextStyle = textStyle;
    graph.titlePlotAreaFrameAnchor = CPTRectAnchorTop;
    graph.titleDisplacement = CGPointMake(0.0f, -12.0f);
    // Set theme
    self.selectedTheme = [CPTTheme themeNamed:kCPTPlainWhiteTheme];
    [graph applyTheme:self.selectedTheme];
}

-(void)configureChart {
    // 1 - Get reference to graph
    CPTGraph *graph = self.hostView.hostedGraph;
    // 2 - Create chart
    CPTPieChart *pieChart = [[CPTPieChart alloc] init];
    pieChart.dataSource = self;
    pieChart.delegate = self;
    pieChart.pieRadius = (self.hostView.bounds.size.height * 0.7) / 2;
    pieChart.identifier = graph.title;
    pieChart.startAngle = M_PI_4;
    pieChart.sliceDirection = CPTPieDirectionClockwise;
    // 3 - Create gradient
    CPTGradient *overlayGradient = [[CPTGradient alloc] init];
    overlayGradient.gradientType = CPTGradientTypeRadial;
    overlayGradient = [overlayGradient addColorStop:[[CPTColor blackColor] colorWithAlphaComponent:0.0] atPosition:0.9];
    overlayGradient = [overlayGradient addColorStop:[[CPTColor blackColor] colorWithAlphaComponent:0.4] atPosition:1.0];
    pieChart.overlayFill = [CPTFill fillWithGradient:overlayGradient];
    // 4 - Add chart to graph
    [graph addPlot:pieChart];
}

-(void)configureLegend {
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:YES];
    [self initPlot];
}

- (IBAction)themeTapped:(id)sender {
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - CPTPlotDataSource methods
- (NSUInteger)numberOfRecordsForPlot:(CPTPlot *)plot
{
    return [[[CPDStockPriceStore sharedInstance] tickerSymbols] count];
}

- (NSNumber *)numberForPlot:(CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)idx
{
    if (CPTPieChartFieldSliceWidth == fieldEnum)
    {
        return [[[CPDStockPriceStore sharedInstance] dailyPortfolioPrices] objectAtIndex:idx];
    }
    return [NSDecimalNumber zero];
}

- (CPTLayer *)dataLabelForPlot:(CPTPlot *)plot recordIndex:(NSUInteger)idx {
    static CPTMutableTextStyle *labelText = nil;
    if (!labelText) {
        labelText= [[CPTMutableTextStyle alloc] init];
        labelText.color = [CPTColor grayColor];
    }
    // 2 - Calculate portfolio total value
    NSDecimalNumber *portfolioSum = [NSDecimalNumber zero];
    for (NSDecimalNumber *price in [[CPDStockPriceStore sharedInstance] dailyPortfolioPrices]) {
        portfolioSum = [portfolioSum decimalNumberByAdding:price];
    }
    // 3 - Calculate percentage value
    NSDecimalNumber *price = [[[CPDStockPriceStore sharedInstance] dailyPortfolioPrices] objectAtIndex:idx];
    NSDecimalNumber *percent = [price decimalNumberByDividingBy:portfolioSum];
    // 4 - Set up display label
    NSString *labelValue = [NSString stringWithFormat:@"$%0.2f USD (%0.1f %%)", [price floatValue], ([percent floatValue] * 100.0f)];
    // 5 - Create and return layer with label text
    return [[CPTTextLayer alloc] initWithText:labelValue style:labelText];
}

-(NSString *)legendTitleForPieChart:(CPTPieChart *)pieChart recordIndex:(NSUInteger)index {
    return @"";
}

#pragma mark - UIActionSheetDelegate methods
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {

}

@end

A:

Never mind. I had a typo:
Following method definition
- (void)initPlot {
    [self configureHost];
    [self configureChart];
    [self configureGraph];
    [self configureLegend];
}

should change to
- (void)initPlot {
    [self configureHost];
    [self configureGraph];
    [self configureChart];
    [self configureLegend];
}

In other words, I should invoke configureGraph before configureChart method.


Q:

Query to select all dates (when some are missing in a non-related table)

I have three tables:
absen (date, time, id_user)
calendar (datefield)
employee (id_user, name, department, address)

Table absen example:

date        time       user_id
2015/01/02  08:00:00   00600320
2015/01/03  08:25:00   00600320
2015/01/05  08:10:00   00600320
.
.
2015/01/31  09:00:00   00600320

I'm looking for a result like this:
date         time      user_id
2015/01/01   --:--:--  00600320
2015/01/02   08:00:00  00600320
2015/01/03   08:25:00  00600320
2015/01/04   --:--:--  00600320
2015/01/05   08:10:00  00600320
.
.
2015/01/31   09:00:00  00600320

A:

Assuming that the calendar table holds all the dates of the month using the date data type, and that absen uses date and time then this query might be what you want:
select
    c.datefield,
    coalesce(cast(a.time as varchar(8)), '--:--:--') as time,
    e.id_user
from calendar c
cross join employee e
left join absen a on c.datefield = a.date and e.id_user = a.id_user
where c.datefield between '2015/01/01' and '2015/01/31'

The cross join between calendar and employee generates the cross product of the set with dates and the set of employees and the left join pulls in the times from absen and when for the dates where the time is missing the coalesce replaces the missing value with --:--:--.
Since the information about your database setup wasn't all clear I guessed a bit.


Q:

phpmailer Exception while using Pixel & Tonic contact-form plugin

Link to Github repository for plugin: https://github.com/pixelandtonic/ContactForm
Being given an error by the plugin where it is interpreting my Twig variable literally as a string instead of what the variable is representing. I am looking for a way to fix this using the current set-up but having an alternate setup is fine as well. Also for reference, I have followed the guidelines on the README in regards to changing the craft/config/contactform.php file. Much appreciated for the help!
This is my code:
{% macro errorList(errors) %}
{% if errors %}

        {% for error in errors %}

{{ error }}

        {% endfor %}

{% endif %}
{% endmacro %}

{% from _self import errorList %}

<form method="post" action="" accept-charset="UTF-8">
    {{ getCsrfInput() }}
    <input type="hidden" name="action" value="contactForm/sendMessage">

Email to {{default.defaultcontactreason}}

            <input type="hidden" name="toEmail" value="{{ '{{default.defaultContactEmail}}'|hash }}">{{default.defaultContactEmail}}

    {% for category in craft.entries.section('Contacts') %}

Email to {{ category.contactReason }}

            <input type="hidden" name="toEmail" value="{{ '{{category.contactEmail}}'|hash }}">{{category.contactEmail}}

    {% endfor %}

Your Name

    <input id="fromName" type="text" name="fromName" value="{% if message is defined %}{{ message.fromName }}{% endif %}">
    {{ message is defined and message ? errorList(message.getErrors('fromName')) }}

Your Email

    <input id="fromEmail" type="text" name="fromEmail" value="{% if message is defined %}{{ message.fromEmail }}{% endif %}">
    {{ message is defined and message ? errorList(message.getErrors('fromEmail')) }}

Subject

    <input id="subject" type="text" name="subject" value="{% if message is defined %}{{ message.subject }}{% endif %}">
    {{ message is defined and message ? errorList(message.getErrors('subject')) }}

Message

    <textarea rows="10" cols="40" id="message" name="message">{% if message is defined %}{{ message.message }}{% endif %}</textarea>
    {{ message is defined and message ? errorList(message.getErrors('message')) }}

    <input type="submit" value="Send">
    <input type="hidden" name="redirect" value="{{siteUrl}}Contacts">
</form>

A:

Looks like you've got some nested escape tags in Twig, which is a no-no.
value="{{ '{{category.contactEmail}}'|hash }}"

You just need to use:
value="{{ category.contactEmail|hash }}"


Q:

Create Dynamic Objects in PL/SQL

I'm pretty new to PL/SQL and currently I have the need for a specific functionality, which I suspect to not being doable with PL/SQL. I am bound to using PL/SQL, so hints on other programming ('query') languages will unfortunately be of no use to me.
Therefore I'd like to ask, whether it is possible to create instances of user-defined types in PL/SQL during program flow and not only within the DECLARE block, and in case it is possible, I'd like to know how to do it.
Scenario:
I want to create a list of lists like...
TYPE SIMPLE_LIST IS TABLE OF VARCHAR2(30) INDEX BY VARCHAR(30);
TYPE LIST_OF_LISTS IS TABLE OF SIMPLE_LIST INDEX BY VARCHAR2(30);

The creation of the type works without any problems.
In my program, I have a function, which has the need to declare such a LIST_OF_LISTS and fill it dynamically.
Therefore the simplified code sample shall look like...
FUNCTION foo(...) RETURN ...
AS
  ll LIST_OF_LISTS;
  sl SIMPLE_LIST;
  ...
BEGIN
  LOOP  -- iterate over something
  ...
  sl := new SIMPLE_LIST; -- this surely doesn't work
  sl('key1') := ...;
  sl('key2') := ...;
  sl('key3') := ...;
  ...
  ll('iter_key') := sl;
  END LOOP;
  RETURN ll;
END foo;

I want/need to use such a list of lists, because I cannot determine the length of each list (and also not of the list of lists) before runtime.
As one can already tell, I'm looking for an OO-like functionality to create an instance of a type with something like a 'new'-operator, right in the middle of the program flow, to fill the list of lists dynamically. The line with the 'new'-operator is just a hint on what I want to accomplish, as I am aware that this is not the way to encompass the described task.
Can anyone give me a hint on how I might be able to implement the described scenario using PL/SQL?
EDIT
As it might be of interest, here's a little more background information on the actual task I am trying to achieve. In a nutshell, the function 'foo' shall extract a few items from an xml document and return the result packed in a data structure for later processing, which is why I ended up with the approach of using such a list of lists.
The function foo receives an xml document (XMLTYPE), as well as a list of items to be searched for during the parsing of the document. While the document is being parsed, using the DBMS_XMLDOM-package, the list is filled with key and value of each XML tag that matches one of the elements to be searched for. Due to the fact, that the XML tags may not be unique across the whole document but occur multiple times, I came up with the idea to use the defined SIMPLE_LIST to store the values of every single occurrence of XML tags/elements (keys) to be searched for. So the 'key'/'index' of LIST_OF_LISTS shall eventually contain the name of the XML tag/element, while the SIMPLE_LIST shall contain all values of any occurrence of the corresponding XML tag/element, packed together in one list.
The amount of entries within the list to be returned will be rather small (definitely not more than 100 entries), therefore I assume that the use of actual tables or nested tables might be overkill in this case.
Thanks in advance.
Chris
EDIT²
I tested the answers of both Boneist and Mr. Łukasiewicz, and I can confirm that they both worked when applied to my scenario. I accepted the latter, due to the fact that it is the most compact answer.
Thanks again for solving my problem.
Cheers,
Chris

A:

Maybe this helps.
    declare
      TYPE SIMPLE_LIST IS TABLE OF VARCHAR2(30) INDEX BY VARCHAR(30);
      TYPE LIST_OF_LISTS IS TABLE OF SIMPLE_LIST INDEX BY VARCHAR2(30);
        ll LIST_OF_LISTS;
        key_ll VARCHAR2(30);
        key_sl  VARCHAR2(30);
    BEGIN
    --dynamic
     for i in 1 .. 10 loop
        for j in 1..10 loop
          ll('i='||i)('j='||j) := 'value='||j;
        end loop;
     end loop;
-- static
     ll('A')('1'):='A1';
     ll('A')('2'):='A2';
     ll('A')('3'):='A3';
     ll('A')('4'):='A4';
     ll('A')('5'):='A5';
     ll('B')('1'):='B1';
     ll('B')('2'):='B2';
     ll('B')('3'):='B3';
     ll('B')('4'):='B4';
     ll('B')('5'):='B5';

    -- and how to iterate it.
      key_ll := ll.first;
      while (key_ll is not null)
         loop
              key_sl := ll(key_ll).first;
              dbms_output.put_line(key_ll);
              while (key_sl is not null)
                 loop
                    dbms_output.put_line('   key sl: '||key_sl||' value sl: '||ll(key_ll)(key_sl));
                     key_sl :=  ll(key_ll).next(key_sl);
              end loop;

             key_ll := ll.next(key_ll);
      end loop;
    END foo;


Q:

Как в Firefox убрать рамку для элементов таблицы в фокусе?

Firefox разрешает брать элементы таблицы в фокус при зажатой клавише Ctrl. При этом элементы, которые находятся в фокусе, подсвечены синий рамкой. Подскажите, пожалуйста, как её убрать? Вариант с outline: none не работает.

A:

UPD:
Это дейсвительно фича firefox. Так он показывает выделенные узлы (не текстовые). Если вы желаете оставить возможность выделение текстовых узлов, то без js тут не обойтись. Я обновил ваш фидл, добавил простой скрипт для firefox (не тестировал на старых версиях!). Надеюсь, суть ясна и у вас получится адаптировать скрипт под свою реализацию.

OLD:
Лекарство такое:
*::-moz-focus-inner {
  border: 0;
}


Q:

Ipython Magic - Cant get it to install Ubuntu Server 18.04

I have followed the instructions here clearly https://ipython.readthedocs.io/en/stable/install/install.html#dependencies
Ran these commands below.
pip3 install ipython
pip3 show ipython
pip3 install pexpect jedi pygments setuptools decorator prompt-toolkit pickleshare backcall traitlets

I still get this error
>>> %precision 2
  File "<stdin>", line 1
    %precision 2
    ^
SyntaxError: invalid syntax

Thank you for the help in advance

A:

I am assuming that you ran that code inside the same python shell you used to install IPython.
I think you should open the IPython shell by invoking ipython from a terminal and run the code from there.


Q:

Apache spawning enormous number of httpd processes

I am running a CentOS 6.7 machine (16 GB vRAM, 8 vCPUs) with a simple web server setup (Apache/2.2.15, PHP/5.3.3, MySQL/5.1.66), hosting an online shop with a moderate number of page impressions (about 2,000 ~ 4,000 per day).
The server ran smooth over the last 3 years without any necessity to change its configuration. Now, since last week - somehow overnight - Apache/HTTP recurrently becomes inaccessible after a short period of time (about 30 minutes). I checked some parameters and saw that there are a lot of httpd processes running. ps axf | grep httpd | wc shows something like this:
387    2344   18354

Whereas the load is not very exciting. top looks like this:

A very small number of httpd processes is released again from time to time, but the total number keeps almost constantly increasing. If I run a service httpd reload, the number of processes drops back to 0 and begins to increase again over the next couple of minutes to hours. After a while, Apache's log tells me:
[error] server reached MaxClients setting, consider raising the MaxClients setting

I did this and I also adjusted different further config params, but it did not help. No matter what value MaxClients and ServerLimit are set to, Apache will not stop to spawn new httpd processes up to these limits. After this, the website is not accessible anymore.
There was no increase in page hits according to AWStats. Furthermore, there has been not a single change in the PHP application. Apart from the breakdown blocking all requests after 30 minutes, the website performs fast as usual. As a dirty and temporary workaround Cron keeps reloading Apache half-hourly.
Prefork/Worker settings have been as follows over the last 3 years:
<IfModule prefork.c>
StartServers       4
MinSpareServers    5
MaxSpareServers   10
ServerLimit      128
MaxClients       128
MaxRequestsPerChild  600
</IfModule>

<IfModule worker.c>
StartServers         2
MaxClients         150
MinSpareThreads     25
MaxSpareThreads     75
ThreadsPerChild     25
MaxRequestsPerChild  0
</IfModule>

I raised them up to:
<IfModule prefork.c>
StartServers       8
MinSpareServers    5
MaxSpareServers   10
ServerLimit       640
MaxClients       640
MaxRequestsPerChild  1000
</IfModule>

<IfModule worker.c>
StartServers         4
MaxClients         300
MinSpareThreads     25
MaxSpareThreads     75
ThreadsPerChild     25
MaxRequestsPerChild  0
</IfModule>

After this change, Apache/HTTP became unavailable after about 1 hr.
How can this happen all of a sudden and what options do I have to investigate further where this strange behaviour originates from?

A:

Fist, increasing the prefork parameters will only worsen your situation. So restore the previous configuration.
To rule out any prefork problem/misconfiguration, try to disable it. Does the situation change significantly? If so, you find your problem.
If not, the problem is related to external factors: for example, maybe some bot/script is targeting your website, opening many connections (with the relative httpd process). If this is the case, you should be able to see that from Apache log files.
If this is not sufficient, you can enable the mod_status module to show detailed stats. Then, issue apachectl fullstatus to access these statistics. See here and here for more details.


Q:

How do I remove the quote from a symbol in scheme?

I had to create a simple scheme program that outputs the contents of a binary tree.  I managed to complete the program but it outputs all the quotes with it.  How do I get rid of them?
(define bintree
'(interior-node
   'foo
   (interior-node 'bar (leaf 26) (leaf 12))
   (interior-node 'baz (leaf 11)
      (interior-node 'quux (leaf 117) (leaf 14)))))

(print-bintree bintree)  returns ('foo ('bar 26 12) ('baz 11 ('quux 117 14)))

I want it to return (foo (bar 26 12) (baz 11 (quux 117 14))) without the ' mark on it.

A:

It's hard to say without seeing the whole program (in particular, the definition of print-bintree), but it looks like a simple misunderstanding about how the quote works.
In particular, a quote before an open paren means that the contents of the parens are interpreted in a simple "data language", where sequences of characters are interpreted as symbols rather than variables.
To see what I mean, let's try evaluating some simple expressions
(zippy tong)

... produces some error about zippy and tong being undefined.
Now, try this:
'(zippy tong)

The result is going to depend a bit on your printer, but it will produce the same thing as
(list 'zippy 'tong)

That is, the leading quote means that zippy and tong are interpreted as symbols, rather than as variables.
In your code, you write:
'(interior-node 'foo ...)

The problem here is that you're using a quote when you're already inside a quoted expression. This isn't doing what you want. In particular, it will produce something equivalent to
(list 'interior-node (list 'quote 'foo) ...)

So, without getting any further into the magic of quote, it will probably suffice to remove the quotes from the 'foo, 'bar, etc. inside your definition of bintree.


Q:

SEO impact of setting job listing post publish date to always be the current date?

A client wants to keep one of their permanent job listing posts (on a WordPress-based site) in good SEO standing and is afraid that a post date going back to 2015 will negatively impact the SEO of this job listing post. They're curious if they could have the post automatically update the publish date periodically. I haven't come across an easy way to have the site do that periodically, but I did find this post about updating a post's date to the current date/time.
My concern is that Google will flag the post as spam because the post date keeps changing (even if I found a way to automatically update periodically), or that it will otherwise negatively affect SEO. What would the potential impact be on SEO for this case?

A:

If you refer to articles like this: https://www.searchenginejournal.com/seo-changing-article-dates/225789/, you'll clearly see that changing the publish date of a post can be very risky for your site's SEO, potentially resulting in your entire site getting dates removed in search results.
I'd push back on the client and tell them it would hurt their SEO to do something like that.


Q:

MDX - icCube -How can i create the Known mdx entity(An event) between a Pie Chart and a Histogram

My icCube report contains a Pie Chart( 5 top client + "Other") and a histogram, when I select a client on Pie Chart, the histogram change.
Using the following mdx In my Pie Chart
WITH

CATEGORY CALCULATED MEMBER [Client].[Client].[All].[Autre] AS SubCubeComplement( TopCount ( Order ( [Client].[Client].[idclient] ,[Measures].[venteT] , DESC ) ,5) )

SELECT { NONEMPTY([Measures].[venteT]),[Measures].[DateC] }  ON 0 ,
   { NONEMPTY(TopCount ( Order ( [Client].[Client].[idclient]     ,[Measures].[venteT] , DESC ) ,5)),NONEMPTY({[Client].[Client].[All].[Autre]})} ON 1
FROM (SELECT { @{dated![Time].[Time].[Jour]} } ON 0 FROM [CubeVente] )
where{Tail([Statvente].[Statvente].[statVente])}
CELL PROPERTIES VALUE

Using the following mdx In my Histogram
SELECT
{ Order( [Statut].[Statut].[statut].allmembers, [Measures].[DateC], BASC) } * { @{clientv![Client].[Client]} } ON COLUMNS,
{ NonEmpty( Order( [Time].[Time].[Année].allmembers, [Measures].[DateC], BASC), [Measures].[DateC]) } ON ROWS
FROM ( SELECT
{ @{dated![Time].[Time].[Jour]} } ON 0 FROM [CubeVente])

But when I select the cell "Other" in the PieChart, there is an error:

'[Client].[Client].[All-M].[Autre]' n'est pas une entité MDX connue

Is there a way to resolve this error? Txs, Marwen.

A:

You should create the category member on both charts so it's recognized in the histogram charts (don't forget the where clause content).
Note that you can combine the event with an mdx IIF function.
I don't see an easy way to do this properly as the category is created dynamically during the MDX evaluation.


Q:

Understanding const in C++

We were given a semantically and syntactically correct method that looks like this:
const Foo & bar( const Bim & bam ) const;

We are supposed to explain what is meant by each of the three const calls.  I am new to C++ and don't know what they mean.  I understand (roughly) that the const at the end means that the method can only be called upon const variables and promises not to propagate changes.  However, I do not understand the other two.  Please correct me if I was wrong on the last one.

A:

See below for explanation
(1)const Foo & bar( (2)const Bim & bam ) (3)const;

The method is returning a reference of type Foo that is immutable.
The methods parameter of type Bim will not be modified by the method. This means that you can pass into this method objects that are const and non-const. Either way the method will not modified the object or is only able to call methods on that object that are const.
This means that this method does not alter the object in any way.

PS: For 3 there is ways around this if you are a naughty boy


Q:

Find the locus of incenters of $\Delta PBC$

Consider a fixed point $P$ on the plane and a line $m$. Find the locus of the incenters of $\Delta PBC$ where $B, C \in m$ and $\Delta PBC$ is acute-angled $\Delta$.
I don't really know what the locus will be like. But I can understand that if $B$ is fixed then the locus will be a line along $BI$ where $I$ is the Incenter. But for the figure in the question, i.e., $B,C$ not fixed, I can understand that a lot of arms will be formed, but what exactly is the locus k can't really decipher. I have tried it using a Geometry software called $\text {Geogebra}$, which I hope is pretty common among the geometers. I have traced the locus and it was somewhat weird: a set of arms (line-segments) and not some solid locus.

A:

We may assume that the line $m$ is horizontal and $A$ lies above it, at a fixed distance $h$ from it.
Let $H_A$ be the projection of $A$ on $m$, $N$ the midpoint of $AH_A$ and $n$ the parallel to $m$ through $N$.
With a bit of lateral thinking, we may just pick some point $I$ in the upper half plane delimited by $m$ and ask ourself if this point is the incenter of a triangle $ABC$ with $B,C\in m$. This is easily solved: there is a unique circle $\Gamma_I$ centered at $I$ which is tangent to $m$, and the tangents from $A$ to $\Gamma_I$ intersect $m$ at $B,C$.

Clearly $I$ has to lie between $m$ and $n$ ($h>2r$). Now we may deal with the acute-angled constraint. Let $r$ be the radius of $\Gamma_I$ and $I_A$ the projection of $I$ on $m$. Since $\widehat{A}\leq 90^\circ$, $AI\geq \sqrt{2}\,II_A$, hence $I$ has to lie below a hyperbola:

Now it just remains to ensure that also $\widehat{B}$ and $\widehat{C}$ are $\leq 90^\circ$. This is simple to deal with: it just means that $I$ lies above the lines departing from $H_A$ and forming angles equal to $45^\circ$ with $m$.

I leave to you to check that the mentioned conditions are not only necessary but also sufficient to grant that $ABC$ given by $I$ is acute-angled.
Thus the wanted locus is the shaded region above, i.e. a right and isosceles triangle whose hypotenuse has been replaced by an arc of hyperbola. A vertex of such hyperbola is the point $V$ on the segment $AH_A$ such that $\frac{AV}{VH_A}=\sqrt{2}$.


Q:

Why is putting a VPN between the destination and an exit node unsafe?

In a recent Tor blog post the following was mentioned:

The help desk has been asked how to configure a VPN to prevent a
  website from learning that a user is using Tor. We consider
  positioning a VPN between one’s exit node and the destination site to
  be totally unsafe, and not much more anonymous than using a VPN
  without Tor.

Now, having read the FAQ, I understand the reasons why it is preferred to not hide the Exit nodes, but none of those reasons seem to have anything to do with privacy or anonymity.  How does adding a VPN after an exit node break Tor's model so badly that it becomes not much more anonymous than using a VPN without Tor?

A:

If an exit operator routed all traffic through a private VPN, and the exit relay and VPN server were hosted by comparably trustworthy providers, I don't see any issues about anonymity. With no VPN, the provider hosting the Tor exit could sniff all traffic. With the VPN, the provider hosting the VPN exit could sniff all traffic, but the host of the Tor exit would see only encrypted VPN traffic. The Tor network would see the exit relay at the VPN exit IP address. That IP address could be changed, but so can any IP address. If there were too much bandwidth reduction and increased latency, however, the exit would be bad for the network.
I suspect that the help desk was considering a third-party VPN service, rather than a private VPN managed by the exit operator. In that case, the VPN provider could sniff exit traffic. That would introduce an additional unknown.
But even in that case, I think that it's overreaching to claim that it's "not much more anonymous than using a VPN without Tor". Every Tor exit is uniquely identifiable by its IP address. I don't see how another IP address, not listed by the Tor Project, would break anonymity.


Q:

How to find the sum of all entries in the matrix $A^5$

Let $A$ be a $4 × 4$ matrix with non-negative entries such that the sum of the entries in each row of $A$ equals $1$. Find the sum of all entries in the matrix $A^5$.

If $A=I_4$ then $A^5=I_4$ and sum of all entries in the matrix $A^5=4$. But how I show the general result. Please help.

A:

Let $j=\left(\begin{matrix}1\\\vdots\\1\end{matrix}\right)$. Then  the sum of entries of matrix $A^5$ is just $j^TA^5j$. What can you say about $Aj$?


Q:

can i easily write a program to make use of Intel's Quad core or i7 chip if only 1 thread is used?

I wonder if in my program I have only 1 thread, can I write it so that the Quad core or i7 can actually make use of the different cores?  Usually when i write programs on a Quad core computer, the CPU usage will only go to about 25%, and the work seems to be divided among the 4 cores, as the Task Manager shows.  (the programs i wrote usually is Ruby, Python, or PHP, so they may not be so much optimized).
Update: what if i write it in C or C++ instead, and
for (i = 0; i < 100000000; i++) {
  a = i * 2;
  b = i + 1;
  if (a == ...  || b == ...) { ... }
}

and then use the highest level of optimization with the compiler.  can the compiler make the multiplication happen on one core, and the addition happen on a different core, and therefore make 2 cores work at the same time?  isn't that a fairly easy optimization to use 2 cores?

A:

No. You need to use threads to execute multiple paths concurrently on multiple CPU's (be they real or virtual)... execution of one thread is inherently bound to one CPU as this maintains the "happens before" relationship between statements, which is central to how programs work.

A:

First, unless multiple threads are created in the program, then there is only a single thread of execution in that program.
Seeing 25% of CPU  resources being used for the program is an indication that a single core out of four is being utilized at 100%, but all other cores are not being used. If all cores were used, then it would be theoretically possible for the process to hog 100% of the CPU resources.
As a side note, the graphs shown in Task Manager in Windows is the CPU utilization by all processes running at the time, not only for one process.
Secondly, the code you present could be split into code which can execute on two separate threads in order to execute on two cores. I am guessing that you want to show that a and b are independent of each other, and they only depend on i. With that type of situation, separating the inside of the for loop like the following could allow multi-threaded operation which could lead to increased performance:
// Process this in one thread:
for (int i = 0; i < 1000; i++) {
    a = i * 2;
}

// Process this in another thread:
for (int i = 0; i < 1000; i++) {
    b = i + 1;
}

However, what becomes tricky is if there needs to be a time when the results from the two separate threads need to be evaluated, such as seems to be implied by the if statement later on:
for (i = 0; i < 1000; i++) {
  // manipulate "a" and "b"
  if (a == ...  || b == ...) { ... }
}

This would require that the a and b values which reside in separate threads (which are executing on separate processors) to be looked up, which is a serious headache.
There is no real good guarantee that the i values of the two threads are the same at the same time (after all, multiplication and addition probably will take different amount of times to execute), and that means that one thread may need to wait for another for the i values to get in sync before comparing the a and b that corresponds to the dependent value i. Or, do we make a third thread for value comparison and synchronization of the two threads? In either case, the complexity is starting to build up very quickly, so I think we can agree that we're starting to see a serious mess arising -- sharing states between threads can be very tricky.
Therefore, the code example you provide is only partially parallelizable without much effort, however, as soon as there is a need to compare the two variables, separating the two operations becomes very difficult very quickly.
Couple of rules of thumbs when it comes to concurrent programming:
When there are tasks which can be broken down into parts which involve processing of data that is completely independent of other data and its results (states), then parallelizing can be very easy.
For example, two functions which calculates a value from an input (in pseudocode):
f(x) = { return 2x }
g(x) = { return x+1 }

These two functions don't rely on each other, so they can be executed in parallel without any pain. Also, as they are no states to share or handle between calculations, even if there were multiple values of x that needed to be calculated, even those can be split up further:
x = [1, 2, 3, 4]
foreach t in x:
    runInThread(f(t))
foreach t in x:
    runInThread(g(t))

Now, in this example, we can have 8 separate threads performing calculations. Not having side effects can be very good thing for concurrent programming.
However, as soon as there is dependency on data and results from other calculations (which also means there are side effects), parallelization becomes extremely difficult. In many cases, these types of problems will have to be performed in serial as they await results from other calculations to be returned.
Perhaps the question comes down to, why can't compilers figure out parts that can be automatically parallelized and perform those optimizations? I'm not an expert on compilers so I can't say, but there is an article on automatic parallization at Wikipedia which may have some information.


Q:

MSSQL2000: get list of role members

I know a role name and want to find all users in this role.
How do I acheive this in SQL Server 2000 (in the SQL script, not in Management Studio or other tool)?

A:

You can use the following stored procedures:
For fixed server roles, the stored procedure is sp_helpsrvrolemember:
exec sp_helpsrvrolemember 'role'

For general roles, the stored procedure is sp_helprolemember:
exec sp_helprolemember 'role'


Q:

Simple Javascript Math

I am trying to perform the very simple task of doing simple multiplication below. I cannot get the input field to participate in the code below. Please let me know how I might be able to get this to work. Thank you all!
<!DOCTYPE html>

<?php
$count="20";
?>
<input id="spend">
<button onclick="myFunction()">Calculate</button>

A:

Hi try this code it's working
<!DOCTYPE html>

<?php
$count=20;
?>
<input id="spend">
<button onclick="myFunction()">Calculate</button>


Q:

This doesnt work for Plugin get_template_directory_uri()

function Zumper_widget_enqueue_script()
{
    wp_enqueue_script('jquery-repeater-form',get_template_directory_uri().'/admin/js/sample.js');
}
add_action('admin_print_scripts-widgets.php', 'Zumper_widget_enqueue_script');

Suppose a javascript is sitting in my wordpress theme in this path-
admin/js/sample.js
and the theme is using wp_enqueue_script to include this file -
wp_enqueue_script('jquery-repeater-form',get_template_directory_uri().'/admin/js/sample.js');

Now my question is if I am transferring the widget and javascript to plugin-
widget codes will go in plugin.php file and javascript file will go into this path -
js/sample.js
I am enqueing it like this -
wp_enqueue_script('jquery-repeater-form',get_template_directory_uri().'/js/sample.js');

but its not getting included.
Is this function unable to pull the correct path -
get_template_directory_uri() when used in plugin folder?

A:

get_template_directory_uri works in a plugin, in that it returns the active theme directory URI, which is what the template directory is.
If you're trying to get the URI for your plugin assets, then you want plugin_dir_url.
wp_enqueue_script(
    'jquery-repeater-form',
    plugin_dir_url( __FILE__ ) . 'js/sample.js'
);


Q:

Why is the outline larger than its div?

UPDATE
To get the input back to the size I want it to be, I had to get rid of padding and borders. The following accomplished this:
*{padding:0; margin:0; border:0;}

Thanks to CBroe, I discovered this is unique to FF which adds to the input a default border of .75px and a padding of 1.5px. For a total of about 4.5px. Chrome does not.
UPDATE 2
The above fix only gets the child element back to the size I thought it should be. The accepted answer below shows that FF has a bug which explains why the outline didn't behave as it should, which is to outline the parent only and not expand for absolute positioned descendents.

I have two div elements stacked vertically with their outline property set to 1px. The div elements have a height of 117px.
I expect where the two div elements meet to have their outlines contiguous. It does so with no content.
When I place an absolute positioned input with top = 97px and height = 20px into the top div , the outline of that div is pushed down.
Here is a fiddle which shows this. If you remove the input, you will see how the top div outline sits next to the bottom div.
There are two things (at least) that I do not understand:
1) In examining the box using the browser's dev tools (Firefox), I see that the top div is in fact still 117px high. The outline should be drawn around the div, but appears not to be. Why?
2) The input has a top of 97px plus a height of 20px. Why would this affect the position of the outline? It looks like the outline is pushed down 4px.

A:

That's because outlines are implementation dependent. It's not only the size:

Outlines may be non-rectangular.

From CSS3 UI,

This specification does not define the exact position or shape of the
  outline, but it is typically drawn immediately outside the border box.

Firefox has historically had a tendency of making outlines bigger in various situations, e.g.

outlines are drawn outside (i.e., expanded by) box-shadow and other visual overflow
outlines are drawn outside (expanded by) outlines on descendant elements

The former was fixed, the latter seems the same as your problem.


Q:

java.util.MissingResourceException: Can't find bundle for base name 'property_file name', locale en_US

I am trying to create a utility class ReadPropertyUtil.java for reading data from property file. While my class is located under a util directory , my skyscrapper.properties file is placed in some other directory.
But , when i try to access the properties using [ResourceBundle][1], i get exceptions, that bundle can't be loaded.
Below is the code on how I am reading the properties and also an image which shows my directory structure.
ReadPropertiesUtil.java
/**
 * Properties file name.
 */
private static final String FILENAME = "skyscrapper";

/**
 * Resource bundle.
 */
private static ResourceBundle resourceBundle = ResourceBundle.getBundle(FILENAME);

/**
 * Method to read the property value.
 *
 * @param key
 * @return
 */
public static String getProperty(final String key) {
    String str = null;
    if (resourceBundle != null) {
        str = resourceBundle.getString(key);
            LOGGER.debug("Value found: " + str + " for key: " + key);
    } else {
            LOGGER.debug("Properties file was not loaded correctly!!");
    }
    return str;
}

Directory Structure

This line is giving the error private static ResourceBundle resourceBundle = ResourceBundle.getBundle(FILENAME);
I am unable to understand why isn't this working and what is the solution. The src folder is already added in build path completely.

A:

Try with the fully qualified name for the resource:
private static final String FILENAME = "resources/skyscrapper";

A:

ResourceBundle doesn't load files?  You need to get the files into a resource first.  How about just loading into a FileInputStream then a PropertyResourceBundle
   FileInputStream fis = new FileInputStream("skyscrapper.properties");
   resourceBundle = new PropertyResourceBundle(fis);

Or if you need the locale specific code, something like this should work
File file = new File("skyscrapper.properties");
URL[] urls = {file.toURI().toURL()};
ClassLoader loader = new URLClassLoader(urls);
ResourceBundle rb = ResourceBundle.getBundle("skyscrapper", Locale.getDefault(), loader);

A:

Use the Resource like
ResourceBundle rb = ResourceBundle.getBundle("com//sudeep//internationalization//MyApp",locale);
or
ResourceBundle rb = ResourceBundle.getBundle("com.sudeep.internationalization.MyApp",locale);

Just give the qualified path .. Its working for me!!!


Q:

Inserting date into database when we insert data to database every time display inserting date in asp.net

when i inserting data into database i need to insert date also but i pass a insert query in this query i inserted data but it took date column by default SQL database date format but i want to display when the user enter data to insert data base that date i want to display my tried query is:
string s = "insert into BatchPermissons(BatchId,SubjectId,AuditoName,AudioID,CreatedBy,CreatedDate) values(" + batchno + ", " + subjectid + " , '" + AudiotoName + "', " + AudioId + ",'" + CBY + "'," + DateTime.Now.ToString() + ")";
SqlCommand cmd = new SqlCommand(s, con);
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();

but the above query inserting default date in database.i need to insert when i insert data that particular date will be store can any one help me out.

A:

You can replace the DateTime.Now.ToString() with "getdate()". This will take the date from SQL server. Or add format to the ToString
DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");


Q:

How to parse HTML output

I am getting a HTML output after sending parameters to an API.
Are there any good user-friendly examples on how to parse the HTML inside mule?
Which Elements would be the best to use? Are there any common best practices?
I've been searching this for a while, but I couldn't find any answer.
All I could find was either incomplete or related to json, and other output types. Any help is appreciated!

A:

What does html response looks like? Surprised to see an API returning HTML!! How can it be API then :). Check with API provider if there is any machine-friendly response format they provide.
Anyways, I don't think there is anything built-in mule to parse HTML.
That said, you can write a java class and use that in Java Component element. I have used https://jsoup.org/ outside of mule to parse HTML and it is really good. You can try that.


Q:

I need to take screenshots and upload to a webserver, what technology should I use?

I am building a peice of software that needs to allow a user to take a screenshot of his/her computer which will then be uploaded to a web server.
What technology should I use? I don't think js has access to the appropriate resources, but would like to keep it browser based. Help?

A:

nope ... javascript won't work ...
you need some lib which takes a screenshot and another one which does the upload.
in .net there are builtin libs for both (taking screenshots, upload via ftp)
edit:
choose a technology which is able to create a screenshot and post it to an external resource via POST (or upload it via FTP). therefore you will need some access to local file-system ... well ... what would you think if you, as a novice, get prompted to allow access to local-filesystem (or network-resources)?
edit2:
as far as i know, silverlights support taking screenshots ... and there would be some ftp/post action included as well ..


Q:

Read informations from application preferences instead from AndroidManifest.xml

I'm new in Android dev and I'm developing an Android App using Eclipse. I provided a functionality to Synchronize database on Dropbox. To do it, Dropbox give me a key value to use for authentication. This key have to be inserted in AndroidManifest.xml
<activity
android:name="com.dropbox.client2.android.AuthActivity"
android:configChanges="orientation|keyboard"
android:launchMode="singleTask" >
<intent-filter>
    <!-- Change this to be db- followed by your app key -->
    <data android:scheme="db-xxxxxxxxxx" />

    <action android:name="android.intent.action.VIEW" />

    <category android:name="android.intent.category.BROWSABLE" />
    <category android:name="android.intent.category.DEFAULT" />
</intent-filter>

But using this logic, the end user will not be able to change this value to synchronize database on his dropbox account, and not on my. I've made a preference screen to store the key in Application Preferences, but I' don't find code where the value is read from Android Manifest. I think it's about here but I'm new and I don't understand how to edit my code:
 public void startAuthentication(Context context) {
    AppKeyPair appKeyPair = getAppKeyPair();

    // Check if the app has set up its manifest properly.
    Intent testIntent = new Intent(Intent.ACTION_VIEW);
    String scheme = "db-" + appKeyPair.key;
    String uri = scheme + "://" + AuthActivity.AUTH_VERSION + "/test";
    testIntent.setData(Uri.parse(uri));
    PackageManager pm = context.getPackageManager();
    List<ResolveInfo> activities = pm.queryIntentActivities(testIntent, 0);

    if (0 == activities.size()) {
        throw new IllegalStateException("URI scheme in your app's " +
                "manifest is not set up correctly. You should have a " +
                "com.dropbox.client2.android.AuthActivity with the " +
                "scheme: " + scheme);
    } else if (activities.size() > 1) {
        // Check to make sure there's no other app with this scheme.
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle("Security alert");
        builder.setMessage("Another app on your phone may be trying to " +
                "pose as the app you are currently using. The malicious " +
                "app cannot access your account, but linking to Dropbox " +
                "has been disabled as a precaution. Please contact " +
                "support@dropbox.com.");
        builder.setPositiveButton("OK", new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.show();
        return;
    } else {
        // Just one activity registered for the URI scheme. Now make sure
        // it's within the same package so when we return from web auth
        // we're going back to this app and not some other app.
        String authPackage = activities.get(0).activityInfo.packageName;
        if (!context.getPackageName().equals(authPackage)) {
            throw new IllegalStateException("There must be an " +
                    "AuthActivity within your app's package registered " +
                    "for your URI scheme (" + scheme + "). However, it " +
                    "appears that an activity in a different package is " +
                    "registered for that scheme instead. If you have " +
                    "multiple apps that all want to use the same access" +
                    "token pair, designate one of them to do " +
                    "authentication and have the other apps launch it " +
                    "and then retrieve the token pair from it.");
        }
    }

    // Start Dropbox auth activity.
    Intent intent = new Intent(context, AuthActivity.class);
    intent.putExtra(AuthActivity.EXTRA_INTERNAL_CONSUMER_KEY,
            appKeyPair.key);
    intent.putExtra(AuthActivity.EXTRA_INTERNAL_CONSUMER_SECRET,
            appKeyPair.secret);
    if (!(context instanceof Activity)) {
        // If starting the intent outside of an Activity, must include
        // this. See startActivity(). Otherwise, we prefer to stay in
        // the same task.
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    }
    context.startActivity(intent);

Can you help me?
Thank you in advance

A:

I think that you may be misunderstanding what that key is used for. It is not used for choosing which account to sync files with.
The key you want to change is an APP API key. Each user does not need a unique key unless you are targeting at developers who would have their own API keys already. This is used to identify your app and shut it down, among other things, if it's causing trouble for Dropbox.
The specific instance of this key you are trying to edit is what gets control back to your app after a user authenticates with their personal account. This needs to be kept in sync with the key you use for authentication when calling AppKeyPair appKeys = new AppKeyPair(APP_KEY, APP_SECRET);
You will not be able to modify the the data tag in that intent filter at runtime.


Q:

Non maximum suppression from google cloud vision response nodejs

So I'd like to see if it's possible to implement non max suppression in nodejs from google clouds vision API responses, for example a response looks like this:
[
  {
    "mid": "/m/09728",
    "languageCode": "",
    "name": "Bread",
    "score": 0.8558391332626343,
    "boundingPoly": {
      "vertices": [],
      "normalizedVertices": [
        {
          "x": 0.010737711563706398,
          "y": 0.26679491996765137
        },
        {
          "x": 0.9930269718170166,
          "y": 0.26679491996765137
        },
        {
          "x": 0.9930269718170166,
          "y": 0.7275580167770386
        },
        {
          "x": 0.010737711563706398,
          "y": 0.7275580167770386
        }
      ]
    }
  },
  {
    "mid": "/m/052lwg6",
    "languageCode": "",
    "name": "Baked goods",
    "score": 0.6180902123451233,
    "boundingPoly": {
      "vertices": [],
      "normalizedVertices": [
        {
          "x": 0.010737711563706398,
          "y": 0.26679491996765137
        },
        {
          "x": 0.9930269718170166,
          "y": 0.26679491996765137
        },
        {
          "x": 0.9930269718170166,
          "y": 0.7275580167770386
        },
        {
          "x": 0.010737711563706398,
          "y": 0.7275580167770386
        }
      ]
    }
  },
  {
    "mid": "/m/02wbm",
    "languageCode": "",
    "name": "Food",
    "score": 0.5861617922782898,
    "boundingPoly": {
      "vertices": [],
      "normalizedVertices": [
        {
          "x": 0.321802020072937,
          "y": 0.2874892055988312
        },
        {
          "x": 0.999139130115509,
          "y": 0.2874892055988312
        },
        {
          "x": 0.999139130115509,
          "y": 0.6866284608840942
        },
        {
          "x": 0.321802020072937,
          "y": 0.6866284608840942
        }
      ]
    }
  }
]

So actually the bounding box that should be on the outside is food like so:

I've found examples in Python to do this, but that means I need to use subprocesses in Node to execute the python script and then pull back the response, which kinda feels a bit dirty.
Obviously those box values from google need multiplying by the image height and width, so if we assume it's 288 X 512 for example:
      const left = Math.round(vertices[0].x * 288);
      const top = Math.round(vertices[0].y * 512);
      const width = Math.round((vertices[2].x * 288)) - left;
      const height = Math.round((vertices[2].y * 512)) - top;

My adapted script is like so(just hard codes the threshold and takes the array of boxes from the command line):
# import the necessary packages
import numpy as np
import sys
import json

# Malisiewicz et al.
def non_max_suppression_fast():
    overlapThresh = 0.3
    boxes = json.loads(sys.argv[1])
    # if there are no boxes, return an empty list
    if len(boxes) == 0:
        return []

    # if the bounding boxes integers, convert them to floats --
    # this is important since we'll be doing a bunch of divisions
    if boxes.dtype.kind == "i":
        boxes = boxes.astype("float")

    # initialize the list of picked indexes
    pick = []

    # grab the coordinates of the bounding boxes
    x1 = boxes[:,0]
    y1 = boxes[:,1]
    x2 = boxes[:,2]
    y2 = boxes[:,3]

    # compute the area of the bounding boxes and sort the bounding
    # boxes by the bottom-right y-coordinate of the bounding box
    area = (x2 - x1 + 1) * (y2 - y1 + 1)
    idxs = np.argsort(y2)

    # keep looping while some indexes still remain in the indexes
    # list
    while len(idxs) > 0:
        # grab the last index in the indexes list and add the
        # index value to the list of picked indexes
        last = len(idxs) - 1
        i = idxs[last]
        pick.append(i)

        # find the largest (x, y) coordinates for the start of
        # the bounding box and the smallest (x, y) coordinates
        # for the end of the bounding box
        xx1 = np.maximum(x1[i], x1[idxs[:last]])
        yy1 = np.maximum(y1[i], y1[idxs[:last]])
        xx2 = np.minimum(x2[i], x2[idxs[:last]])
        yy2 = np.minimum(y2[i], y2[idxs[:last]])

        # compute the width and height of the bounding box
        w = np.maximum(0, xx2 - xx1 + 1)
        h = np.maximum(0, yy2 - yy1 + 1)

        # compute the ratio of overlap
        overlap = (w * h) / area[idxs[:last]]

        # delete all indexes from the index list that have
        idxs = np.delete(idxs, np.concatenate(([last],
            np.where(overlap > overlapThresh)[0])))

    # return only the bounding boxes that were picked using the
    # integer data type
    return boxes[pick].astype("int")

Is anyone able to give me any pointers here please? I'm pretty sure it's just about calculating the total area of the each box, but I can't quite get my brain around it.

A:

Ok so actually this is pretty simple if you use Tensorflow.js - use the following function to take the response from google vision:
Note 288 and 512 are my image width and height you'll need to setup your own.
function nonMaxSuppression(objects){

    return new Promise((resolve) => {
      // Loop through the objects and convert the vertices into the right format.
      for (let index = 0; index < objects.length; index++) {
        const verts = objects[index].boundingPoly.normalizedVertices;

        // As above note 288 and 512 are image width and image height for me.
        const left = Math.round(verts[0].x * 288);
        const top = Math.round(verts[0].y * 512);
        const width = Math.round((verts[2].x * 288)) - left;
        const height = Math.round((verts[2].y * 512)) - top;
        // we need an array of boxes AND an array of scores
        this.boxes.push([left, top, width, height]);
        this.scores.push(objects[index].score);
      }
      // Params are boxes, scores, max number of boxes to select.
      const theBox = tf.image.nonMaxSuppression(this.boxes, this.scores, 2);
      // the function returns the box number that matched from this.boxes, seems like it's not zero based at least in my tests so we need to - 1 to get the index from the original array.
      resolve(theBox.id -1 );
    });
}

Ta-dah banana!


Q:

JEditorPane.scrollToReference() with dynamically-generated HTML

I can't figure out how JEditorPane.scrollToReference() is meant to be used with a dynamically-generated HTML page. I'd like to open a dialog box with a JEditorPane that is  scrolled to an anchor of my choosing. No matter how I approach the problem, the view is always scrolled at the bottom of the page.
As an ugly workaround, I currently parse the entire HTML document for anchor tags, save their offsets in a Map<String, Integer>, and then I call:
editorPane.setCaretPosition(anchorMap.get("anchor-name"));

...which doesn't even produce an attractive result, because the caret position within the visible rectangle is seemingly unpredictable, and is rarely at the top of the window. I'm looking for a more browser-like behavior where the anchored text appears at the top of the visible area.
Below is a screenshot of what happens with my awkward workaround (there is an anchor on "header 6"), without having touched the scroll bar:

I think I'm missing something but I can't figure out what exactly.
Source of my current workaround:
import javax.swing.*;
import javax.swing.text.MutableAttributeSet;
import javax.swing.text.html.*;
import javax.swing.text.html.HTMLEditorKit.*;
import javax.swing.text.html.parser.*;
import java.io.*;
import java.awt.*;
import java.util.HashMap;

public class AnchorTest
{
    public static void main(String[] args)
    {
        final String html = generateLongPage();
        final HashMap<String, Integer> anchors = anchorPositions(html);

        SwingUtilities.invokeLater(new Runnable()
        {
            public void run()
            {
                JEditorPane editor  = new JEditorPane("text/html", html);
                JScrollPane scroller= new JScrollPane(editor);

                scroller.setPreferredSize(new Dimension(400, 250));

                //editor.scrollToReference("anchor6");  // doesn't work...
                editor.setCaretPosition(anchors.get("anchor6")); //sorta works

                JOptionPane.showMessageDialog(new JPanel(), scroller, "",
                        JOptionPane.PLAIN_MESSAGE);
            }});
    }

    public static HashMap<String, Integer> anchorPositions(String html)
    {
        final HashMap<String, Integer> map = new HashMap<String, Integer>();

        Reader reader = new StringReader(html);
        HTMLEditorKit.Parser parser = new ParserDelegator();

        try
        {
            ParserCallback cb = new ParserCallback()
            {
                public void handleStartTag(HTML.Tag t,
                                           MutableAttributeSet a,
                                           int pos)
                {
                    if (t == HTML.Tag.A) {
                        String name =
                            (String)a.getAttribute(HTML.Attribute.NAME);
                        map.put(name, pos);
                    }
                }
            };

            parser.parse(reader, cb, true);
        }
        catch (IOException ignore) {}

        return map;
    }

    public static String generateLongPage()
    {
        StringBuilder sb = new StringBuilder(
                "<title>hello</title>\n");

        for (int i = 0; i < 10; i++) {
            sb.append(String.format(
                    "
header %d
\n
", i, i));

            for (int j = 0; j < 100; j++) {
                sb.append("blah ");
            }
            sb.append("
\n\n");
        }

        return sb.append("").toString();
    }
}

A:

The problem is probably because the pane is not visible yet or not laid out yet when scrollToReference is executed, so its size cannot be determined.
The implementation of scrollToReference has the following block:
Rectangle r = modelToView(iter.getStartOffset());
if (r != null) {
   ...
   scrollRectToVisible(r);
}

In the posted example the rectangle is null for anchor6, since the view is not yet visible or its size is not positive.
Try this dirty fix to delay scrolling:
SwingUtilities.invokeLater(new Runnable() {
    public void run() {
        editor.scrollToReference("anchor6");
    }
});
JOptionPane.showMessageDialog(new JPanel(), scroller, "",
        JOptionPane.PLAIN_MESSAGE);


Q:

How to convert string to int in python?

Hey guys todays my first day with python and im trying to do what seems like a simple thing to  me but it keeps giving me errors. I am reading a number from a text file and trying to convert it into an int. This is my code:
f=open('commentcount.txt','r')
counts = f.readline()
int(counts)
counts = counts + 1
print(counts)

i am getting this error: counts = counts + 1
TypeError: Can't convert 'int' object to str implicitly
Can somone please tell me what I am doing wrong?  thanks!

A:

You must assign the value of int(counts) to counts in order to keep changes. Note that int(...) doesn't modify the variable you pass in.
counts = int(counts)

Be sure that f.readline() return an string that "represents" a int.


Q:

android editview as textview and many lines in one textview

Is there any way to make EditView to work sometimes as itself and sometimes as TextView (readonly, but not grayed (when I set setEnabled(false) it becomes gray which I dont like). Simply I would like to use the same form for displaying information and for editing and as for now the only solution which comes to my mind is to have two components and to play with visibility parameter of them (sometimes EditView is visible and TextView not and vice versa).
And is there any possibility to have few lines in one TextView? When I wrote
android:text="bla bla \n bla bla"
in xml code it doesn't work. :(

A:

You can set text color to black or any other you want in disabled mode using android:textColor="#000000" in you xml. But if you also want EditText to hide its style and totally look like TextView, you will need to apply custom styling on your text view for this...which will unnecessarily increase you efforts.
Proffered and most robust way is to have two views i.e. TextView and EditText togather and play with their visibility.
And in your second part of question, text should go to next line ideally, if its not, then there might be some other property which is restricting it to do so...


Q:

Using boot-clj dependency from local

I'm experimenting with boot-new. I'm making some changes to the code and need to test with boot -d. How can I test any boot dependency without having it available in clojars.

A:

To test the changes for the boot dependency libs (the one that we supply in -d), we can make changes to those lib and run boot build. This add the updated jar to our local maven repo and it will be used when we refer it via boot -d.