Q:

Printing a rectangle of asterisks in Java

The following is the source code to print a rectangle entirely composed of asterisks (*), with a test class included as well.
import javax.swing.JOptionPane ;

/**
 * A class to print block rectangles.
 */
class RectanglePrinter
{
    // instance var's
    int height ;            // height of rectangle (i.e. number of segments)
    int width ;             // width of each segment(i.e. number of "*"s printed)

    /**
     * Create a RectanglePrinter object.
     * @param height height of rectangle (i.e., number of lines to print)
     * @param width width of rectangle (i.e., number of '*'s per line
     */
    public RectanglePrinter(int height, int width)  // constructor
    {
        this.height = height ;
        this.width = width ;
    }

    /**
     * Prints one line of a rectangle, by printing exactly "width" asterisks
     */
    public void printSegment()
    {
        // write the body of this method here

    }

    /**
     * Prints a rectangle exactly "height" lines in height.  Each line is
     * printed via a call to method printSegment
     */
    public void printRectangle()
    {
        System.out.println("Printing a " + height + " x " + width + " rectangle:") ;
        // write the body of this method here

    }

}  // end of class rectanglePrinter definition

public class RectanglePrinterTest
{
    public static void main (String [] args)
    {
        String input = JOptionPane.showInputDialog
                                   ("What is the height of the rectangle?") ;
        int height = Integer.parseInt(input) ;

        input = JOptionPane.showInputDialog
                            ("What is the width of the rectangle?") ;

        int width = Integer.parseInt(input) ;

        RectanglePrinter r = new RectanglePrinter(height, width) ;

        System.out.println() ;
        r.printRectangle() ;
        System.out.println() ;
    }
}

In the segments where it says to fill out the method body, I was instructed to use for loops to print out the asterisks. I think I have a basic idea of how to do the printSegment() method:
for (int w = 1; w <= width; w++)
            {
                System.out.println("*");
            }

But from there, I am unsure of what to do within the printRectangle method. Judging from the comments in the code, I think I'm supposed to write a for loop in the printRectangle method that calls the printSegment method, except I don't think you can call a void method within the body of another method. Any help on this would be greatly appreciated.
Update:
I attempted to use the following code within the body of printRectangle()
for (int h = 1; h <= height; h++)
                {
                    printSegment();
                }

After running the code and inputting the height and width, I received the following output:
Printing a 6 x 7 rectangle:
*

*

*

*

*

*

*

*

*

*

*

*

*

*

*

*

*

*

*

*

*

*

*

*

*

*

*

*

*

*

*

*

*

*

*

*

*

*

*

*

*

Now I can print out the asterisks at least, so I just need to know how to modify the code so the output is a rectangular block of asterisks.
Update #2.
I figured out the solution. Here's the code that got me the result I was looking for.
import javax.swing.JOptionPane ;

/**
 * A class to print block rectangles.
 */
class RectanglePrinter
{
    // instance var's
    int height ;            // height of rectangle (i.e. number of segments)
    int width ;             // width of each segment(i.e. number of "*"s printed)

    /**
     * Create a RectanglePrinter object.
     * @param height height of rectangle (i.e., number of lines to print)
     * @param width width of rectangle (i.e., number of '*'s per line
     */
    public RectanglePrinter(int height, int width)  // constructor
    {
        this.height = height ;
        this.width = width ;
    }

    /**
     * Prints one line of a rectangle, by printing exactly "width" asterisks
     */
    public void printSegment()
    {
        // write the body of this method here
                for (int w = 1; w <= width; w++)
                {
                    for (int h = 1; h <= height; h++)
                    {
                        System.out.print("*");
                    }
                    System.out.println();
                }

    }

    /**
     * Prints a rectangle exactly "height" lines in height.  Each line is
     * printed via a call to method printSegment
     */
    public void printRectangle()
    {
        System.out.println("Printing a " + height + " x " + width + " rectangle:") ;
        // write the body of this method here
                printSegment();

    }

}  // end of class rectanglePrinter definition

public class RectanglePrinterTest
{
    public static void main (String [] args)
    {
        String input = JOptionPane.showInputDialog
                                   ("What is the height of the rectangle?") ;
        int height = Integer.parseInt(input) ;

        input = JOptionPane.showInputDialog
                            ("What is the width of the rectangle?") ;

        int width = Integer.parseInt(input) ;

        RectanglePrinter r = new RectanglePrinter(height, width) ;

        System.out.println() ;
        r.printRectangle() ;
        System.out.println() ;
    }
}

The differences made: I added a nested for loop in the body of the printSegment() method, and instead of using
System.out.println("*"); , used System.out.print("*") in the innermost loop, and System.out.println() in the outer loop, which resulted in the following output for the input of 5 x 7:
Printing a 5 x 7 rectangle:
*****
*****
*****
*****
*****
*****
*****

A:

It does indeed sound like you are supposed to make a loop in printRectangle where you call printSegment for height amount times.
To call your printSegment method inside printRectangle simply write printSegment(); to call it.
Since its in the same class this is all you have to do to call it. If it were called from another class you can check how RectanglePrinterTest main method calls printRectangle using r.printRectangle(); where r is an instance of the RectanglePrinter class.
As its a void method it wont return anything so you don't need to do anything else. :)
So to sum it up you are on the right track! Keep going and just try what you think feels right and you will surely figure it out.


Q:

Prove that $H$ is a finite set.

Let $H$ be compact in $\Bbb R^n$
Also assume that for every $x\in H$ there is an $r=r(x)$ such that $B_r(x)\cap H=\{x\} $
Prove that $H$ is a finite set.

Solution:
Since $H$ is compact, $\exists$ a finite $$x_1, x_2, \dots , x_N\in H \subseteq \bigcup B_{r(x_i)}$$
for $N\in\Bbb N$
Let's set $r:=$ min $\{r(x_1),\dots , r(x_N)\}$
Then, $$H \subseteq \bigcup _{i=1}^{N} B_r(x_i)$$
Then, $$( \bigcup _{i=1}^{N} B_r(x_i))\cap H= \{x_1, \dots ,x_N\}$$
So, $H=\{x_1,\dots , x_N\}$ is finite.

Does the proof of details true? Does there exist any drawbacks, missing in detail?
To learn this is important for me. I exhibited all my performance. Please help me. Thank you.

A:

The collection $\{ B_{r(x)} (x) \}$ (open balls of radius $r(x)$ and centered at $x$) forms an open cover of $H$. Since $H$ is compact, this collection has a finite subcover $\{ B_{r(x_i)} (x_i) \}_{i=1}^N$. Then you can proceed as you did after your first "Then."

A:

Suppose that $H$ is not finite.  Then, there exists a sequence $(x_i) \in H$.  Since $H$ is compact by assumption, by Bolzano-Weierstrass, there is a convergent subsequence. Say, the subsequence is also called $(x_{i})$ which converges to a point $x$.  By definition of convergence, for every $\epsilon >0,$ there is an $N$ such that if $i > N$, then $|x - x_i| < \epsilon$.  But this is a contradiction to the hypothesis that $B_r(x) \cap H = x$ for $r$ small enough.  Thus, $H$ must be finite.


Q:

Why do you need to redefine serialVersionUID if you extends a class which implements Serializable "down the line"?

For one of my projects, I need to define a new exception which extends ProviderMismatchException.
From the javadoc link, you can see that this exception:

extends IllegalArgumentException, which
extends RuntimeException, which
extends Exception, which
extends Throwable.

All of them define their own static final serialVersionUID except for Throwable which adds the private modifier.
Now, if you implement an interface Foo, then all inherited classse also implement that interface, and this stands for Serializable as well; however, why do subclasses in the JDK redefine it for each subclass? What is the danger of not defining it again for inherited classes?

A:

The serialVersioUID is a static long value, thus it won't be inherited through the class hierarchy.
You need this to indicate if a prior serialized instance of a class has the same version as the current implementation or not.

If a serializable class does not explicitly declare a serialVersionUID, then the serialization runtime will calculate a default serialVersionUID value for that class based on various aspects of the class, as described in the Java(TM) Object Serialization Specification. However, it is strongly recommended that all serializable classes explicitly declare serialVersionUID values, since the default serialVersionUID computation is highly sensitive to class details that may vary depending on compiler implementations, and can thus result in unexpected InvalidClassExceptions during deserialization.

For Details see here:
What is a serialVersionUID and why should I use it?


Q:

Loop through each element under "Data"

I'm using Kucoin's API to get a list of coins.
Here is the endpoint: https://api.kucoin.com/v1/market/open/coins
And here's my code:
$kucoin_coins = file_get_contents('https://api.kucoin.com/v1/market/open/coins');
$kucoin_coins = json_decode($kucoin_coins, true);

print_r($kucoin_coins);

I can see how to target one coin like so:
echo "name: " . $kucoin_coins['data'][0]['name'];

But I can't see how to loop through them.
How can I loop through each of the "coins" returned here? They are under the "data" part that is returned. I'm sorry, I'm just not seeing how to do it right now. Thank you!

A:

You can loop through the decoded elements using the foreach command:
foreach ($kucoin_coins['data'] as $coin) {
    //do your magic here.
}

But I usually prefer using json_decode($kucoin_coins) rather than the one for arrays. I believe this:
$item->attribute;

Is easier to write than this one:
$item['attribute'];


Q:

jQuery selector element with no class

So i have let's say three divs

     .
     .

Is there a way to select the div that doesnt have any class?
I dont know the order of the elements in DOM, so using something like .next() wouldnt work.

A:

Try it with the :not() pseudo-class selector:
$('div:not([class])')


Q:

How do I apply the Settings.settings values at design time?

I have a panel in my Form like this:

and a Panel_BackColor in project's Settings.setting file:

I can change panel back color in the Form constructor:
public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
            panel1.BackColor = UI_Settings.Default.Panel_BackColor;
        }
    }

All things work at runtime:

But nothing change at Design Time. How can I apply these settings at Design mode too?

A:

I asked "not edited version" of this question on MSDN forum and got an answer within an hour.
Questions like Convert int to string? is a good questions but mine is not!
I think stackoverflow should keep a watch on it's editors and policy.
The answer:
Select your control in Form Designer (for example a button), go to Properties, (ApplicationSettings),(PropertyBinding), then bind BackColor or other property to Button_BackColor or other settings. Afterward by changing settings in Settings.settings file, all binded controls would be affected.


Q:

Escaping characters for use with Oracle's Xmltable

I'm using Xmltable to convert a field of comma-delimited email addresses to a table of values.
WITH

data AS
  (
    select  1 ID, 'foo&bar@domain.tld,bar@domain.tld' recipients from dual
  )

select  ID, trim(COLUMN_VALUE) recipient
from    data,xmltable(('"'|| REPLACE( recipients , ',', '","') || '"'))

produces an error:

[72000][19112] ORA-19112: error raised during evaluation: XVM-01003:
  [XPST0003] Syntax error at '"foo' 1
  "foo&bar@domain.tld","bar@domain.tld" - ^

However, when I replace the & with its entity value (&):
WITH

DATA AS
  (
    select  1 ID, 'foo&bar@domain.tld,bar@domain.tld' recipients from dual
  )

select  ID
        -- & --> &
        , replace( trim(COLUMN_VALUE), '&', '&') recipient
from    data
        -- & --> &
        ,xmltable(('"'|| REPLACE( replace( recipients, '&','&')  , ',', '","') || '"'))

the query works:
ID,RECIPIENT
1,foo&bar@domain.tld
1,bar@domain.tld

I'm imaging that there might be other characters that are valid in an email address, but will be problematic for Xmltable.
Is there a better way to do this?

A:

You could use the built-in dbms_xmlgen.convert() function:
with data (id, recipients) as
(
  select 1, 'foo&bar@domain.tld,bar@domain.tld' from dual
)
select d.id, dbms_xmlgen.convert(x.column_value.getstringval(), 1) as recipient
from data d
cross join
xmltable(('"' || replace(dbms_xmlgen.convert(d.recipients, 0), ',', '","') || '"')) x

        ID RECIPIENT
---------- ------------------------------
         1 foo&bar@domain.tld
         1 bar@domain.tld

The inner call dbms_xmlgen.convert(d.recipients, 0) gives you
foo&bar@domain.tld,bar@domain.tld

After that has been modified to have double quotes around each comma-separated value and been split into multiple rows, you end up with column_value as:
foo&bar@domain.tld
bar@domain.tld

so the outer dbms_xmlgen.convert(x.column_value.getstringval(), 1) converts any encoded entities back to their plain versions.
If you do this in a PL/SQL context then you can use dbms_xmlgen.entity_encode and dbms_xmlgen.entity_decode instead of the fixed 0 and 1, but those aren't available in plain SQL.
(There are only five entities to worry about anyway, but you still might as well allow for them all - whether they are valid in email addresses or not - and using a function call like this is maybe going to be less confusing to future maintainers...)


Q:

Oracle: How do I add users to the HTTP ACL in Oracle 11?

How do I add a user to the network ACL (access control list)?
When running this code
declare
    req utl_http.req;
begin
    req := utl_http.begin_request('http://example.com');
end;

I receive this error.
ORA-24247: network access denied by access control list (ACL)

A:

First, see if you have an ACL for port 80, the HTTP port.  If you do, it should look something like  this.
select * from dba_network_acls;

HOST     LOWER_PORT UPPER_PORT ACL                     ACLID
---      ---------- ---------- ---                     -----
*        80         80         /sys/acls/www.xml       1FBEC09C32D78F5AE05335D6488A7883

If you need to recreate it, you can drop it with this command:
dbms_network_acl_admin.drop_acl('www.xml');

Create the ACL:
 dbms_network_acl_admin.create_acl(
     acl => 'www.xml',
     description => 'WWW ACL',
     principal => 'SCOTT',
     is_grant => true,
     privilege => 'connect'
 );

Assign hosts and ports to the ACL:
 dbms_network_acl_admin.assign_acl(
     acl => 'www.xml',
     host => '*',
     lower_port => 80
 );

Add users to the ACL:
 dbms_network_acl_admin.add_privilege(
     acl => 'www.xml',
     principal => 'OE',
     is_grant => true,
     privilege => 'connect'
 );

version note: kevinsky points out that this is applicable for Oracle 11 but that it has changed in Oracle 12.


Q:

using TryGetValue for nested Dictionary

I have this dictionary:
 private Dictionary<int, Dictionary<string, string>> MyDictionary = new Dictionary<int, Dictionary<string, string>>();

how can i use TryGetValue in this?
I have tried this but it doesn't work.
 MyDictionary.TryGetValue(key, out value);

key is an integer and value is an empty string.

A:

You will use in the following way.
I am getting the right value back. Please execute the same.
   using System;
using System.Collections.Generic;

namespace ConsoleApplication3
{
    public class Program
    {
        public static void Main()
        {
            var dictionary = new Dictionary<int, Dictionary<string, string>>();
            var value = new Dictionary<string, string> { { "Key1", "Value1" }, { "Key2", "Value2" } };
            dictionary.Add(1, value);

            Dictionary<string, string> result;

            if (dictionary.TryGetValue(1, out result))
            {
                foreach (var key in result.Keys)
                {
                    Console.WriteLine("Key: {0} Value: b{1}", key, result[key]);
                }
            }
        }
    }
}


Q:

Typescript problem when creating a recursive style object

I need to make a recursive style object, that can support style properties and in a nested format.
I have a super hard time wrapping my head around this, and I've tried pretty much all solutions I could find here on SO and google.
interface Properties {
  border?: string;
  width?: string;
}

//# 1 Type attempt
type TRecursiveProperties = Properties & {
  [index: string]: TRecursiveProperties;
};

//# 2 Interface attempt
interface IRecursiveProperties extends Properties {
  [index: string]: IRecursiveProperties;
}

const test: TRecursiveProperties = {
  border: '1px solid green',
  isActive: {
    border: '2px solid red',
    '&:hover': {
      border: '3px solid blue'
    }
  }
};

I'd expect the Recursive properties to be a fallback/catch all or some way to exclude keys from Properties object.
The 2 errors I get are either

Type alias 'TRecursiveProperties' circularly references itself.
Property 'width' of type 'string' is not assignable to string index type 'IRecursiveProperties'

Any ideas how I can achieve that?

A:

I would go for this:
interface Properties {
  width?: string;
  border?: string;
  [selector: string]: string | Properties | undefined;
}

const myStyles: Properties = {
  'width': '100px',
  ' .child': {
    'width': '200px',
    'border': '1px color blue',
    '&:hover': {
      border: '1px solid aquamarine',
    },
  },
};

In this typescript resource:https://basarat.gitbooks.io/typescript/docs/types/index-signatures.html, search for 'Design Pattern: Nested index signature' to see a pretty similar example.


Q:

Can clang-format align a block of #defines for me?

I have a source file containing some lines like this;
#define ARC_V2_LP_START         0x002
#define ARC_V2_LP_END           0x003
#define ARC_V2_STATUS32         0x00a

With all the values nicely aligned. Unfortunately clang-format does this;
#define ARC_V2_LP_START 0x002
#define ARC_V2_LP_END 0x003
#define ARC_V2_STATUS32 0x00a

I have found the AlignConsecutiveDeclarations and AlignConsecutiveAssignments options, but nothing that will align consecutive #defines. Is it possible to do this?

A:

[UPDATE]
The op's pull request finally went through and as of clang version 9.0.0 is live. The functionality is enabled by the AlignConsecutiveMacros: true option.
[ORIGINAL]
Weirdly enough this feature is yet to be implemented in clang; the formatting option for consecutive macros is currently missing.
Many developers are interested and there is a working pull request that has been waiting for approval for years: https://reviews.llvm.org/D28462?id=93341
You can integrate it or just wait whether they add it on the official branch, but at this point I doubt they will.


Q:

Pressing "Enter" to print value to Console Log

When I input a value in to a text box on the page the console log calls the else condition in my if statement even if I type "yes" in to the text box. What am I doing wrong?
<!DOCTYPE html>
<html>
    <head>
        <title> Choose your own adventure </title>
        <meta charset= "utf-8">
        <script src= "choose1.js"></script>
        <link type= "text/css" rel= "stylesheet" href= "choose1.css"/>
    </head>
    <body>
        <p> What do you do? </p>
            <input type= "text" id= "decision" name= "decision" onkeydown=  "if(event.keyCode === 13) confirm()" />
        </p>
    </body>
</html>

//choose1.js//
function confirm(){
    var begin= document.getElementById("decision");
    if(begin === "yes") {
        console.log("Success!");
    }
    else {
        console.log("Failure");
    }
}

A:

Because begin is pointing at the <input> element itself, not its contents.  You need to get hold of the value:
var begin= document.getElementById("decision").value;

Also, note that there is already a top-level function called confirm, you may want to consider renaming yours so you don't clash.


Q:

Eclipse 4.x - Solarized CSS theme

With Eclipse 4 new support of CSS themes, I wanted to ask if anyone was able to port Solarized (http://ethanschoonover.com/solarized) to it. I'm not looking for a simple Color Switch in the editor, but rather the whole window.
If no one is able or willing, would you please point me to a reference for the Theme styling?
Thank you.

A:

Your best shot would be to start from this plugin : https://github.com/eclipse-color-theme/eclipse-ui-themes
And then modify the CSS.
Here are some resources:

http://wiki.eclipse.org/E4/CSS
http://wiki.eclipse.org/E4/CSS/SWT_Mapping
http://www.vogella.com/articles/Eclipse4CSS/article.html

Regards


Q:

Transparent PNG in a div tag, not using alpha?

I have an odd issue while beginning to learn CSS. This is a test page. It has a large transparent PNG covering the background color of solid blue.
Typically the black image (which has transparent holes in it) completely blacks out my background color.
In this example page I made the image's div transparent just to see if the background was still working.
Any ideas why my alpha is getting completely ignored?
Thanks all.

A:

It's because on .backgrounddiv you have background-color set to #000. Instead use transparent to fix:
.backgrounddiv {
    position:absolute;
    background-color: transparent;
    background-image:url(POCTransparentBG.png);
...


Q:

Django form: select field after the submit of the form

I have a report form report.html:
<select id="select" class="form-control" name="organization">
        <option value="">-- Select Organization --</option>
        {% for organization in organization_list %}
        <option value="{{ organization.name }}">{{ organization.name }}</option>
        {% endfor %}
</select>

After the submitting this form the selected organization is not saved. But it would be better if the organization will be displayed. It can be helpful for the user: she/he can see, what filter displays these results.
How to save and show after form submitting the selected value for the select field?
views.py:
def report(request):

    user = request.user
    admin = None
    try:
        admin = user.administrator
    except ObjectDoesNotExist:
        pass
    if not admin:
        return render(request, 'vms/no_admin_rights.html')

    organization_list = get_organizations_ordered_by_name()

    if request.method == 'POST':
        form = ReportForm(request.POST)
        if form.is_valid():
            first_name = form.cleaned_data['first_name']
            last_name = form.cleaned_data['last_name']
            organization = form.cleaned_data['organization']
            event_name = form.cleaned_data['event_name']
            job_name = form.cleaned_data['job_name']
            start_date = form.cleaned_data['start_date']
            end_date = form.cleaned_data['end_date']
            report_list = get_administrator_report(
                first_name,
                last_name,
                organization,
                event_name,
                job_name,
                start_date,
                end_date
                )
            total_hours = calculate_total_report_hours(report_list)
            return render(request, 'administrator/report.html', {'form': form, 'report_list': report_list, 'total_hours': total_hours, 'notification': True, 'organization_list': organization_list})
        else:
            return render(request, 'administrator/report.html', {'form': form, 'notification': False, 'organization_list': organization_list})
    else:
        form = ReportForm()
        return render(request, 'administrator/report.html', {'form': form, 'notification': False, 'organization_list': organization_list})

forms.py:
class ReportForm(forms.Form):
    first_name = forms.RegexField(regex=r'^[(A-Z)|(a-z)|(\s)]+$', max_length=30, required=False)
    last_name = forms.RegexField(regex=r'^[(A-Z)|(a-z)|(\s)]+$', max_length=30, required=False)
    organization = forms.RegexField(regex=r'^[(A-Z)|(a-z)|(\s)]+$', max_length=75, required=False)
    event_name = forms.RegexField(regex=r'^[(A-Z)|(a-z)|(0-9)|(\s)|(\.)|(,)|(\-)|(!)]+$', max_length=75, required=False)
    job_name = forms.RegexField(regex=r'^[(A-Z)|(a-z)|(\s)]+$', max_length=75, required=False)
    start_date = forms.DateField(required=False)
    end_date = forms.DateField(required=False)

A:

Change this line:
return render(request, 'administrator/report.html', {'form': form, 'report_list': report_list, 'total_hours': total_hours, 'notification': True, 'organization_list': organization_list})

add to the context 'selected_organization': organization:
return render(request, 'administrator/report.html', {'form': form, 'report_list': report_list, 'total_hours': total_hours, 'notification': True, 'organization_list': organization_list, 'selected_organization': organization})

And report form should look like this:
<select id="select" class="form-control" name="organization">
    <option value="">-- Select Organization --</option>
    {% for organization in organization_list %}
    <option value="{{ organization.name }}" {% if selected_organization == organization %}selected{% endif %}>{{ organization.name }}</option>
    {% endfor %}
</select>


Q:

Adding/deleting data into local browser storage using a button, and displaying it in a UI table (React)

I would like to have a react app that uses local storage to store data, and display that data in a table in the user interface (UI).
I want to be able to submit an entry into local storage by clicking a button (SUBMIT), and then be able to delete an entry in local storage by clicking another button (DELETE).
And whatever data is in local storage I would like it to be displayed in a small table in the UI even after the browser is refreshed.
I have used this tutorial (https://www.robinwieruch.de/local-storage-react#local-storage-in-react) as a basis for the local storage and provided the code I am using from that tutorial below. But in the tutorial, the data is submitted by typing into a box and having it displayed in a paragraph. And from the developer tools I can see this is only for one key value pair.
CODE:
import React from 'react';

const useStateWithLocalStorage = localStorageKey => {
  const [value, setValue] = React.useState(
    localStorage.getItem(localStorageKey) || ''
  );

  React.useEffect(() => {
    localStorage.setItem(localStorageKey, value);
  }, [value]);

  return [value, setValue];
};

const App = () => {
  const [value, setValue] = useStateWithLocalStorage(
    'myValueInLocalStorage'
  );

  const onChange = event => setValue(event.target.value);

  return (

Hello React with Local Storage!

      <input value={value} type="text" onChange={onChange} />

{value}

  );
};

export default App;

From the tutorial, I believe data will be:
Submitted into local storage using localStorage.setItem('myData', data)
Displayed in the table using localStorage.getItem('myData')
Deleted from local storage/table using localStorage.removeItem('myData')or, localStorage.clear()
My guess is each one of the previous pieces of code will be in a a separate function that gets called in return().
I have attached below, what I am trying to create, specifically, what the UI will look like:

Submitting data to local storage is done with the SUBMIT button, while data is deleted from local storage using the DELETE button in the table, while everything that is displayed in the table is from local storage.
Let me know if more information is needed. There are so many ways to do this, and I honestly do not know what to do. For example, if I need to create a class with multiple functions in the class that do what I described above (e.g a function for submitting, another for deleting, and one for retrieving data from the table).

A:

To store arrays in localstorage use JSON.stringify otherwise you will end up storing a comma separated string
So the code for the custom hook will need to be changed to use JSON.stringify and JSON.parse
const useStateWithLocalStorageArray = localStorageKey => {
  const [value, setValue] = React.useState(
    JSON.parse(localStorage.getItem(localStorageKey) || '[]' )
  );
  React.useEffect(() => {
    localStorage.setItem(localStorageKey, JSON.stringify(value))
  }, [value]);
  return [value, setValue];
};

Here is the full source in Plunker - https://plnkr.co/edit/NuSBnLpPpoOmmEE6


Q:

How can i display my other query rows when i got null = 0 values of other returned rows

I have a three tables that i used to left outer join to view all my clinic names including the sum and count for the data that i need, i have here the tables screenshot below:

now, i made my query like this:
SELECT
tbl_clinics.clinic_name,
COALESCE(COUNT(tbl_check_up.check_up_id),0) AS totalpatient,
COALESCE(SUM(tbl_bill.bill_amt),0) AS totalearn
FROM
tbl_clinics
LEFT OUTER JOIN tbl_check_up ON tbl_clinics.clinic_id = tbl_check_up.clinic_id
LEFT OUTER JOIN tbl_bill ON tbl_bill.bill_id = tbl_check_up.bill_id
WHERE tbl_clinics.user_id = 102

The output of my query is this:

Problem:
Now, my problem is i want to show my other clinics by showing null to zero values. In my data, i have 3 clinics which has user_id = 102, but why only Clinic 1 shows? . I want something output like this below, where it shows there are no values in tbl_check_up that has a Clinic Id of 2 and 3 same as the bill.
+---------------+---------------+------------+
|  Clinic Name  | Total Patient | Total Earn |
+---------------+---------------+------------+
| Clinic 1      |       4       |   800.00   |
+---------------+---------------+------------+
| Clinic 2      |       0       |   0        |
+---------------+---------------+------------+
| Clinic 3      |       0       |   0        |
+---------------+---------------+------------+

A:

This is your query (the COALESCE() is not necessary for the COUNT()):
SELECT c.clinic_name,
       COUNT(cu.check_up_id) AS totalpatient,
       COALESCE(SUM(b.bill_amt), 0) AS totalearn
FROM tbl_clinics c LEFT OUTER JOIN
     tbl_check_up cu
     ON c.clinic_id = cu.clinic_id LEFT OUTER JOIN
     tbl_bill b
     ON b.bill_id = cu.bill_id
WHERE c.user_id = 102
GROUP BY c.clinic_name;

I think you just need the GROUP BY.


Q:

sql statment in email messge utl_mail.send

I am sending emails true oracle apex which works fine. what i need however is to have an sql count statement in the message of the email.
what i have is
begin
   utl_mail.send(sender     => 'a@test.com',
                  recipients =>'a@test.com',
                  subject    => 'FileRequest',
                  message    =>  'select count(filenumber) where status is assigned' files from registry '||:p5_filenumber ||''||'  ' ||:p5_filename || ' has now been assigned to the ' || :p5_department || '');

end;

which obviously is not working
what i will like to see is
begin
   utl_mail.send(sender     => 'a@test.com',
                  recipients =>'a@test.com',
                  subject    => 'FileRequest',
                  message    =>  5 files from registry '||:p5_filenumber ||''||'  ' ||:p5_filename || ' has now been assigned to the ' || :p5_department || '');

end;

A:

Compute the value BEFORE sending the mail. Something like this:
declare
  l_cnt number;
  l_msg varchar2(200);
begin
  -- select number you're interested in
  select count(*)
    into l_cnt
    from some_table
    where some_conditions;

  -- compose the message
  l_msg := l_cnt ||' files from registry ...';

  -- send mail
  utl_mail.send(sender     => 'a@test.com',
                recipients => 'a@test.com',
                subject    => 'FileRequest',
                message    =>  l_msg);
end;


Q:

Smooth finish on large parts

I would like to print a vase that has a width/length/height footprint of 100x100x200 mm, and the surface finish is of particular interest to me. Ideally, I would like to do a minimum of sanding/XTC-3D coating after printing, if any.
What would be the best material to work with?

A:

From the printer...
Non-post-processed surface smoothness of a print is mainly a function of the Layer height during print: it is smoother if one reduces the height of the steps taken between the layers. A very good FDM machine can achieve down to 0.05 mm layer height, but 0.1 mm is what most hobbyist machines can achieve if well dialed in. SLA printers cure resin in layers down to 25 micron reliably and some can get down to 12.5 micron - a quarter of the best achievable FDM.
Reducing the layer height in FDM comes at the cost of mainly three factors:

Print time increases roughly antiproportional to the layer height. 0.1 mm is about double the print time of 0.2 mm and so on.
The prints tensile strength gets reduced by increasing the number of layers increases, creating additional possible weakpoints.
The thinner the layer, the more susceptible the print is to errors like clogged nozzles or variations of the filament thickness.

SLA printers are not affected by the print strength loss and the errors from clogged nozzles and can print entirely clear material without air inclusions. They are affected by the print time increase though. Usually, SLA prints come out of the vat covered in residual resin and curing them in the proper post-processing method results in this resin smoothing over the surface perfectly.
Simple Postprocessing...
Many prints can easily be post-processed.
Sanding
PLA and ABS can be easily sanded down to somewhat smooth, but you'll need to spend time and muscle grease or go electric. A sander with 300+ grit can help a lot. If you have a rotational body, you could sand the vase on a lathe.
Putty
A plastic putty could be smeared over the stepped surface to smooth it and then sanded smooth. I personally like Valejo plastic putty, as it doesn't shrink, but Tamya putty also is a good alternative, bonding strong.
Primer-Filler
Independent of the base material, using a spray coating can easily fill in the notches and crannies left behind during printing. Printing in 0.15 mm and giving it a short spray coat of primer-filler twice, sanding over rough spots between did a good job of smoothing prints for me.
Vapor Smoothing
If you chose ABS, you could use Acetone vapor to smooth over the surface of a print in almost an instant. This can achieve Super smooth results with tall layer heights, as you practically melt the plastic over, but it comes at the loss of small surface details.
Exposure time is the limiting factor here: the longer the exposure to the acetone vapor, the more the surface is smoothed and the less details remain. Think of exposure time like running the smooth filter in blender once or twice each second.

Similarly, ethylacetate or propylene carbonate could be used for PLA prints, though timing might differ from the well established "a couple of seconds" for acetone vapor. Note that these two chemicals are much more expensive.
Costs
Checking prices, I was quoted about 90 €/l for (chemical grade) Ethyl Acetate and 130 €/l for (chemical grade) Propylene Carbonate via a laboratory supply. Useable Acetone (not chemical grade) comes about 3.70 €/l in home depot. For comparison: chemical-grade Acetone comes with a price tag of about 50 €/l.
Considering that ABS filaments and PLA filaments typically price similarily,  ABS+Acetone Vapor is the least costly chemical Vapor smoothing.


Q:

Roxygenize error when documenting package ("$ operator is invalid for atomic vectors")

I was previously able to successfully build this package and it passed all checks when I called devtools::check() with no warnings/notes. I've just added some new functions and updated the documentation, and now when I try to run devtools::document(roclets=c('rd', 'collate', 'namespace')) I get the following error: 'Error: $ operator is invalid for atomic vectors'.
I've attempted to use roxygen2::roxygenize and locate any stray "$"s in my code but have had no luck. I'm unsure where I could be using the $ operator that could be causing this problem.
I have found that the error comes from the "rd" generation stage of the roxygenize command, as when I run devtools::document(roclets=c('collate', 'namespace')) I get a different set of errors. In this case I get a long series of warnings for each tag in each of my R files along the lines of "Warning: @tag [row#x]: unknown tag".
When I run traceback() after running devtools::document(roclets=c('rd', 'collate', 'namespace')) I get the following:
16: paste0("@", x$tag, if (x$file != "") paste0(" [", x$file, "#",
        x$line, "]"), ": ", message)
15: make_tag_message(x, paste0(...))
14: warning(make_tag_message(x, paste0(...)), call. = FALSE, immediate. = TRUE)
13: roxy_tag_warning("should have only a single argument")
12: registry[[x$tag]](x)
11: FUN(X[[i]], ...)
10: lapply(tokens, parse_tag, registry = registry)
9: vapply(x, is.null, logical(1))
8: compact(lapply(tokens, parse_tag, registry = registry))
7: parse_tags(tokens, registry = registry, global_options = global_options)
6: .f(call = .l[[1L]][[1L]], srcref = .l[[2L]][[1L]], tokens = .l[[3L]][[1L]],
       ...)
5: purrr::pmap(list(call = as.list(parsed)[has_tokens], srcref = refs[has_tokens],
       tokens = tokens[has_tokens]), block_create, registry = registry,
       global_options = global_options)
4: FUN(X[[i]], ...)
3: lapply(files, tokenize_file, registry = registry, global_options = global_options)
2: parse_package(base_path, env = NULL, registry = registry, global_options = options)
1: roxygen2::roxygenize("D:\\Transposon_Work\\packFinder")

I'm unsure how including further documentation and adding functions have introduced this error, since I've searched through the whole document for each "$" operator I've used. I thought the issue might be something to do with my .Rbuildignore file which is automatically generated each time I run roxygenize to be as follows:
    ^.*.Rproj$
    ^.Rproj.user$
My github can be found here: https://github.com/jackgisby/Transposon_Search
Additionally, my local copy has the following:
- .git folder
- .gitignore folder
- .Rproj.user
- .Rhistory
These are not in .Rbuildignore.

A:

After lots of trial and error I discovered that deleting the R files that documented my data in data/ allowed me to call devtools::document(roclets=c('collate', 'namespace')) without the error. After investigating further I realised that deleting the tag @docType data from each of these files also fixed the error. I am, however, unsure why this is causing a problem as previously I was able to document these functions with this tag - although I've added to the documentation since then.
The files with these tags removed are as follows:

https://github.com/jackgisby/Transposon_Search/blob/development/R/packMatches.R
https://github.com/jackgisby/Transposon_Search/blob/development/R/arabidopsisThalianaRefseqSubset.R

To conclude, the issue was fixed by deleting the roxygen @docType data tags for my documentation of my Rdata, but I'm unsure why this is the case.


Q:

How to install new git hook to all existing (cloned) repositories?

I have ~50 repositories on my machine. I would like to install newly created git hook to all of them.
I've already created .git-templates folder and put hooks there, then git config --global init.templatedir ~/.git-templates - it works for new repositories but what about existing ones?

A:

I you use a recent version of git (>= 2.9), then I would recommend using the core.hooksPath variable.
Then you can create a separate directory where you put all your hooks, eg /var/myhooks, then
git config --global core.hooksPath /var/myhooks

would make this directory the default hooks directory for all your repositories at once. As a side effect, all hooks under .git/hooks in each repository will be ignored. But inside a specific repository, you could then override this again with its own hooks directory:
git config core.hooksPath .git/hooks


Q:

unable to force JS library to HEAD

I've read the main docs about this but find it lacking context. This did better job of explaining and it seems it should work. How to force a JavaScript library to load in the <head> of a Drupal 8 page
EVERY attempt I try returns
A colon cannot be used in an unquoted mapping value

Searching for this, I've attempted to enclose the include line in single quotes, without, but all within context of attempting
js-header
Since this YML, I'm making sure we're using two spaces for indentation and nothing else. What am I overlooking here? This is a snippet of mytheme.libraries.yml
  flexslider:
  version: 1.x
  css:
    theme:
      includes/flexslider/css/flexslider.css: {}
  js:
    includes/flexslider/js/jquery.flexslider-min.js: {}
  dependencies:
    - core/jquery

fontawesome:
  version: 1.x
  css:
    theme:
      includes/fontawesome/css/font-awesome.css: {}

global-styling:
  version: 1.3.2
  css:
    theme:
      includes/mapquest/css/mapquest.css: {}
  js-header:
    header: true
      js:
        includes/mapquest/js/mapquest.js: {}

This is portion of mytheme.info.yml that applies:
  #Libraries
  libraries:
  - mytheme/bootstrap
  - mytheme/flexslider
  - mytheme/fontawesome
  - mytheme/global-components
  - mytheme/global-styling

A:

I think you've indented too far. The line following header: true is directly beneath it in the example you linked to.
global-styling:
  version: 1.3.2
  css:
    theme:
      includes/mapquest/css/mapquest.css: {}
js-header:
  header: true
  js:
    includes/mapquest/js/mapquest.js: {}


Q:

Sending GSON string from client to server Design issue in java

I am building an application which allows restaurant guests to order food and send to server.
What i have considered is to
1) create a class Order.java class
public class Order
{

private Intger  tableId;
private Integer restaurantId;
private Integer foodId;
private Integer foodQuantity;

getter and setters
}

2) This class object will be populated with guests order and an ArrayList of objects of the class will be sent to server as Gson String.
Now  if an order consist of some 7 items, Then the arraylist will have 7 objects, but tableId and restaurantId will be same 7 times.
can you suggest a better design where in I can associate restaurantId and tableId with the entire arraylist.
Thanks.

A:

There is no right solution, it would depend on your needs, one possible solution would be something like:
public class Order {

    private int tableId;
    private int restaurant;
    private List<OrderItem> items;

    // setters and getters

}

public class OrderItem {

    private int itemId; // foodId
    private int quatity; // foodQuantity

    // setters and getters

}

But if you were in a situation that the information comes not normalized, like you suggested (in which tableId is repeated for every single food ordered), I would consider to implement a normalization process that will return a structure with the classes I draft above. But if you are implementing it, please consider to make it as normalized as possible.


Q:

When I save a user account as an admin, I get logged in as that user

I'm experiencing a strange issue that I'm having a really hard time debugging.
When I save a user account (of an authenticated user) as an admin, the account is saved, but when the page reloads I get an access denied and I am suddenly logged in as the user I saved, not the admin.  This happens whether I save the account in the UI (via the People page) or save the account using a rules action.
Recently, I added a custom function and modified a few of my rules, so these changes are likely to be the cause of the problem.  The site is version-controlled using git, so I can roll back to a working version, but I would like to attempt to determine what I did wrong.
I have Netbeans working with Xdebug.  I just don't know where to set breakpoints or how otherwise to start looking for the source of this problem.

A:

Can you re-produce the problem from CLI?
Using drush scr, bootstrap, login as user 1, save a new user, check if your ID changed.
If you can do this from CLI, git bisect can be very helpful in finding the commit that caused it.


Q:

MySQL to group a column's values to a single cell value

I have a query that return data with 10 columns and in which only one column value is unique for every row and all the other column values will be repeated for few rows each.
Eg:
Column 1 | Column 2 | column 3 | column 4 | column 5 | Column 6
          Sony     |    Xperia   |   stack      |   ask        | question   |    XYZ
          Sony     |    Xperia   |   stack      |   ask        | question   |    ABC
          Sony     |    Xperia   |   stack      |   ask        | question   |    123
          Nexus   |   Android  |   stack      |   ask        | question   |    POI
          Nexus   |   Android  |   stack      |   ask        | question   |    KILL
I want the result to be as -
Eg: Column 1 | Column 2 | column 3 | column 4 | column 5 | Column 6
          Sony     |    Xperia   |   stack      |   ask        | question   |    XYZ, ABC, 123
          Nexus   |   Android  |   stack      |   ask        | question   |    POI, KILL
Can you guys please help me in achieving this through mysql query ?? Just a hint of the possibilities would do.
I got the values in sorted order so that the "to be grouped" rows will always come consecutively.
Thanks in advance. :)

A:

You do this using aggregation and group_concat():
select column1, column2, column3, column4, column5, group_concat(column6) as column6
from query q
group by column1, column2, column3, column4, column5;


Q:

How to do this SQL query in Rails?

How to do this SQL query in Rails?
I have three tables I'm trying to join. I'm pretty sure I've connected them properly in the model.
I have a few joined tables, in this case, there is an "ownership" table which has the user id and the game id. It is inner-joined with the "games" table and the "users" table. The game table has game information and has a console column which is joined with the console table. The console table are all the consoles in the database. In this way, when I display a game, I can display the console it belongs to.
I have created a web interface to keep up with my video game collection. I have it working in PHP, but I'm converting everything to Ruby on Rails. What I'm trying to do now is, on the inventory page, I want to display the consoles that the user has games for so the user can select a console and filter the games displayed to only show the games for that console.
For instance, the main inventory page shows every game the user owns. On the right side there's a sidebar with the consoles the user has games for. If the user only wants to see the games he has for the N64, he clicks on N64 and the display is filtered to only show N64 games.
I don't want to display a console on the sidebar unless the user owns a game for that console.
Here's the SQL query that I want to work:
select distinct console_general.eng_name from ownership inner join games on games.id=ownership.games_id inner join console_general on console_general.console_id=games.console_general_id;

Here are my tables:
mysql> describe games;
+--------------------+------------+------+-----+---------+----------------+
| Field              | Type       | Null | Key | Default | Extra          |
+--------------------+------------+------+-----+---------+----------------+
| id                 | int(11)    | NO   | PRI | NULL    | auto_increment |
| ean                | mediumtext | YES  |     | NULL    |                |
| eng_title          | mediumtext | YES  |     | NULL    |                |
| jap_title          | mediumtext | YES  |     | NULL    |                |
| console_general_id | int(11)    | YES  | MUL | NULL    |                |
| region_id          | int(11)    | YES  | MUL | NULL    |                |
| image              | int(11)    | YES  | MUL | NULL    |                |
+--------------------+------------+------+-----+---------+----------------+

mysql> describe ownership;
+----------------------+------------+------+-----+---------+-------+
| Field                | Type       | Null | Key | Default | Extra |
+----------------------+------------+------+-----+---------+-------+
| user_id              | int(11)    | NO   |     | 0       |       |
| games_id             | int(11)    | YES  | MUL | NULL    |       |
| own                  | tinyint(1) | YES  |     | NULL    |       |
| complete             | tinyint(1) | YES  |     | NULL    |       |
| box_condition        | int(11)    | YES  | MUL | NULL    |       |
| game_condition       | int(11)    | YES  | MUL | NULL    |       |
| manual_condition     | int(11)    | YES  | MUL | NULL    |       |
| inserts_condition    | int(11)    | YES  | MUL | NULL    |       |
| notes                | text       | YES  |     | NULL    |       |
| spine_card_condition | int(11)    | YES  | MUL | NULL    |       |
| count                | int(11)    | NO   |     | 1       |       |
+----------------------+------------+------+-----+---------+-------+

mysql> describe console_general
    -> ;
+------------+---------+------+-----+---------+----------------+
| Field      | Type    | Null | Key | Default | Extra          |
+------------+---------+------+-----+---------+----------------+
| console_id | int(11) | NO   | PRI | NULL    | auto_increment |
| eng_name   | text    | YES  |     | NULL    |                |
| jap_name   | text    | YES  |     | NULL    |                |
+------------+---------+------+-----+---------+----------------+

Here is my controller:
class InventoryController < ApplicationController
  def test

    # These work fine
    @user = User.find_by(params[:id])
    @ownership = Ownership.where(user_id: 1)

    # This is the variable I've been working on, not sure if I'm on the right track or not.
    # @console =  Ownership.joins(games: {console_general: :console_id})
  end
end

And here are my models:
class Ownership < ActiveRecord::Base
self.pluralize_table_names = false

belongs_to :games

Ownership.joins(:games)

end

class Games < ActiveRecord::Base
belongs_to :console_general
belongs_to :region
belongs_to :image
has_many :ownership

Games.joins(:region, :console_general, :image)
end

lass ConsoleGeneral < ActiveRecord::Base
self.pluralize_table_names = false

has_many :games
has_many :accessories
end

I hope that makes sense.
EDIT:
Manipulating the given answer a bit I was able to get it. The Model associations were correct, but the controller instance variable didn't work at first, here's what I did

Ownership.joins(:games => :console_general).uniq.pluck(:eng_name)

This worked great. Thanks for all your help guys.

A:

class User < ActiveRecord::Base
  has_many :ownerships
  has_many :games, through: :ownerships
end

class Ownership < ActiveRecord::Base
  belongs_to :user
  belongs_to :game
end

class Game < ActiveRecord::Base
  has_many :ownerships
  has_many :users, through: :ownerships
  belongs_to :console_general
end

class ConsoleGeneral < ActiveRecord::Base
  has_many :games
end

Railsguide
Then for
select distinct console_general.eng_name from ownership
inner join games ongames.id=ownership.games_id
inner join console_general on console_general.console_id=games.console_general_id

...if the point of that is to see all that consoles that have any games then you could do:
ConsoleGenerals.joins(:games).uniq.pluck(:eng_name)

pluck selects only the eng_name, uniq yields the 'select distinct', and joins(:games) will force the presence of associated games.
Or this if you want to restrict to owned games
ConsoleGenerals.joins(:games => :ownerships).uniq.pluck(:eng_name)


Q:

printing list of categories as a column

I am taking example from pandas documentation. Let us say I have a series after reading an excel file
import pandas as pd
s = pd.Series(["a","b","c","a"], dtype="category")

I know I can get different categories by
scat=s.cat.categories
print scat

For which I get
Index([u'a', u'b', u'c'], dtype='object')

I was wondering what is a good way to make this list appear as a column. Something like
a
b
c

I could get rid of u' by doing np.asarray but still do not get the format I need.

A:

I'm not sure by what you mean when you say 'appear' as a column.
You can create a list instead of an index via:
>>> s.cat.categories.tolist()
['a', 'b', 'c']

Or you can simply print them out in a column structure using a for loop:
for c in s.cat.categories:
    print c

a
b
c

Or you could create a series (or dataframe):
>>> pd.Series(s.cat.categories)
0    a
1    b
2    c
dtype: object

>>> pd.DataFrame(s.cat.categories)
   0
0  a
1  b
2  c

A:

I think it is no problem - 'u' means unicode string:
s = pd.Series(["a","b","c","a"], dtype="category")
print s
0    a
1    b
2    c
3    a
dtype: category
Categories (3, object): [a, b, c]

scat=s.cat.categories
print scat
Index([u'a', u'b', u'c'], dtype='object')

print scat[0]
a

print type(scat[0])
<type 'str'>

If you want print column without loop use numpy reshape:
print len(scat)
3
print scat.values.reshape(len(scat),1)
[['a']
 ['b']
 ['c']]


Q:

What is the significance or use for the engagement ring quest item?

When rummaging through every cabinet or box or container in Prey (2017), one of the items I've found was an engagement ring. This is marked as a Quest Item (grey backgroung) in my inventory and I cannot recycle it, yet I found no quest relating to it (while there are quests relating to some other items I may have found by accident).
Did I miss some quest relating to this ring?

A:

According to https://www.polygon.com/prey-guide-walkthrough/2017/5/23/15679592/with-this-ring-optional-objective-kevin-nicole-hague-wedding-ring-cargo-bay-executive-suites, this is an objective for a quest you get in the Cargo Bay area.


Q:

Execute bash command within java program

It's been quite a while since I'm looking for but I don't find the solution. I'm trying to execute bash command on Linux within .jar file.
For that, I tried many things, including this :
Process p = new ProcessBuilder("java", "-jar", "M1_MIAGE_PDL_VIZ_GROUPE3.jar", "menu").start();
Runtime.getRuntime().exec("/bin/sh -c java -jar M1_MIAGE_PDL_VIZ_GROUPE3.jar menu");
Runtime.getRuntime().exec(new String[]{"/bin/sh -c", "java -jar M1_MIAGE_PDL_VIZ_GROUPE3.jar menu"});

So, when I click on the .jar file, I would like to that the program open a bash, and execute the command (java -jar ...), to execute another part of the program.
Any ideas as to how to do it ?

A:

To understand this, you first need to understand how you would run that command at a shell prompt.
$ sh -c "java -jar M1_MIAGE_PDL_VIZ_GROUPE3.jar menu"

Note where the double quotes are.  The first argument is -c.  The second argument is the stuff inside the quotes; i.e. java -jar M1_MIAGE_PDL_VIZ_GROUPE3.jar menu
Now we translate that into Java:
Process p = new ProcessBuilder(
   "/bin/sh",
   "-c",
   "java -jar M1_MIAGE_PDL_VIZ_GROUPE3.jar menu").start();

Having said that, the above doesn't actually achieve anything.  Certainly, it doesn't open a fresh console window to display the console output etcetera.  Unlike Windows "CMD.exe", UNIX / Linux shells do not provide console / terminal functionality.  For that you need to use a "terminal" application.
For example, if you are using GNOME
Process p = new ProcessBuilder(
   "gnome-terminal",
   "-e",
   "java -jar M1_MIAGE_PDL_VIZ_GROUPE3.jar menu").start();

will (probably) do what you are trying to do.


Q:

SQL count summation query across multiple sets of Access tables

I have a MS Access query (created with SQL) that counts the occurrences of non-NULL values in a date column in an equipment status table.  The table contains all of the equipment for a particular manufacturing plant.  The query also counts the total equipment, with our without NULL values. There are a total of 12 different plants, each with its own identical set of Access tables. I need to create a consolidated SQL query that creates a summation of each of the counts into a master count for all of the plants.
The structure of the status table, named '_review_status' is:
equip_number, text
review_a_analysis, date
review_b_analysis, date
review_c_analysis, date
review_d_analysis, date
review_e_analysis, date
review_f_analysis, date
review_g_analysis, date

The results of the working query (on one table) look like this.
a   b   c   d   e   f   g   equip_count
17  31  0   94  13  12  44  1249

The new results should look exactly like the above, except that the number will all be larger because the query is looking at all 12 sets of tables.
Here is the working one-table query:
SELECT
Count(dept1_review_status.review_a_analysis) AS a,
Count(dept1_review_status.review_b_analysis) AS b,
Count(dept1_review_status.review_c_analysis) AS c,
Count(dept1_review_status.review_d_analysis) AS d,
Count(dept1_review_status.review_e_analysis) AS e,
Count(dept1_review_status.review_f_analysis) AS f,
Count(dept1_review_status.review_g_analysis) AS g,
Count(dept1_equipment.dept1_equip_number) AS equip_count
FROM dept1_equipment
LEFT JOIN dept1_review_status
ON dept1_equipment.dept1_equip_number =
dept1_review_status.dept1_equip_number;

The join on the dept1_equipment table is used to get the full count of all of the equipment in each department.
Many thanks.
Bob

A:

Consider running a union query of all 12 group by aggregate queries and then run another final aggregate query using the saved union query:
UNION
SELECT
   Count(dept1_review_status.review_a_analysis) AS a,
   Count(dept1_review_status.review_b_analysis) AS b,
   Count(dept1_review_status.review_c_analysis) AS c,
   Count(dept1_review_status.review_d_analysis) AS d,
   Count(dept1_review_status.review_e_analysis) AS e,
   Count(dept1_review_status.review_f_analysis) AS f,
   Count(dept1_review_status.review_g_analysis) AS g,
   Count(dept1_equipment.dept1_equip_number) AS equip_count
FROM dept1_equipment LEFT JOIN dept1_review_status
ON dept1_equipment.dept1_equip_number = dept1_review_status.dept1_equip_number;

UNION ALL

SELECT
   Count(dept2_review_status.review_a_analysis) AS a,
   Count(dept2_review_status.review_b_analysis) AS b,
   Count(dept2_review_status.review_c_analysis) AS c,
   Count(dept2_review_status.review_d_analysis) AS d,
   Count(dept2_review_status.review_e_analysis) AS e,
   Count(dept2_review_status.review_f_analysis) AS f,
   Count(dept2_review_status.review_g_analysis) AS g,
   Count(dept2_equipment.dept2_equip_number) AS equip_count
FROM dept2_equipment LEFT JOIN dept2_review_status
ON dept2_equipment.dept2_equip_number = dept2_review_status.dept2_equip_number;

UNION ALL

SELECT
   Count(dept3_review_status.review_a_analysis) AS a,
   Count(dept3_review_status.review_b_analysis) AS b,
   Count(dept3_review_status.review_c_analysis) AS c,
   Count(dept3_review_status.review_d_analysis) AS d,
   Count(dept3_review_status.review_e_analysis) AS e,
   Count(dept3_review_status.review_f_analysis) AS f,
   Count(dept3_review_status.review_g_analysis) AS g,
   Count(dept3_equipment.dept3_equip_number) AS equip_count
FROM dept3_equipment LEFT JOIN dept3_review_status
ON dept3_equipment.dept3_equip_number = dept3_review_status.dept3_equip_number;

...other 9 tables...

FINAL
SELECT Sum(unionqry.a),
       Sum(unionqry.b),
       Sum(unionqry.c),
       Sum(unionqry.d),
       Sum(unionqry.e),
       Sum(unionqry.f),
       Sum(unionqry.g),
       Sum(unionqry.h),
       Sum(unionqry.equip_count)
FROM unionqry

Alternatively, you can incorporate all in one query if MS Access allows depending on complexity:
SELECT Sum(unionqry.a),
       Sum(unionqry.b),
       Sum(unionqry.c),
       Sum(unionqry.d),
       Sum(unionqry.e),
       Sum(unionqry.f),
       Sum(unionqry.g),
       Sum(unionqry.h),
       Sum(unionqry.equip_count)
FROM (...above union query)... As unionqry


Q:

Reusing an IEnumerable results in false result, e.g. on .Any()

I'm a little lost in deferred execution land:
I declare an instance of an IEnumerable implementing class
var wordEnumerable = new WordEnumerable(_text);

Then I iterate over it (the first word is "Lorem")
foreach (var word in wordEnumerable)
                    Console.WriteLine(word);

.. which is written to the console.
Now right thereafter in code I do a
Console.WriteLine(wordEnumerable.Any(w => w == "Lorem"));

.. and get a False as output.
Now If I put the .Any(..) part above the foreach loop I do get a true, however the loop does start with the second word.
My expectation was that .Net creates different runtime 'contexts' for each call to an IEnumerable and its underlying IEnumerator so they don't interfere... I wouldn't want to .Reset() it by hand in order to get a proper result?
What am I missing here?
Update:

Link to IEnumerable implementation: https://gist.github.com/814352
Link to IEnumerator implementation: https://gist.github.com/814354
.. and finally the underlying text parser implementation: https://gist.github.com/814358

.. It is basically an IEnumerable that allows me to iterate over the words within a given string.

A:

Your expectation is correct - Any will call GetEnumerator again to get a fresh IEnumerator<T>. That should be fine if you've implemented IEnumerable<T> correctly. My guess is that your implementation of WordEnumerable is incorrect. Please post the code :)
What happens if you write:
Console.WriteLine("First");
foreach (var word in wordEnumerable)
{
    Console.WriteLine(word);
}

Console.WriteLine("Second");
foreach (var word in wordEnumerable)
{
    Console.WriteLine(word);
}

? The other thing to check is that WordEnumerable implements IEnumerable<string> rather than IEnumerable<object>, otherwise your == check will be a reference identity check.


Q:

How to display JS objects in view

There is already a question from our friend Vinicius Scaramel with this problem, but there is no answer solution, so come on:
I'm getting an object in JSON format via http.get on Ionic, (using AngularJS), but when viewing it in the view with {{}} it only displays [object Object], and it does not display my object itself. I'm already losing my hair trying to solve. Let's code it:
Role of my provider who gives the GET
 getChamadoSelecionado(){
    return this.http.get(this.LINK + "/chamadoSelecionado");
  }

my array receiving my object through GET
ionViewDidLoad() { //funcao que é executada quando abre a view
  console.log('ionViewDidLoad ChamadoPage');
  this.ChamadosProvider.getChamadoSelecionado().subscribe(    // chamando minha funcao que da o GET na minha api, e retorna o objeto
    data => {
      const objeto_retorno = JSON.parse((data as any)._body); // inserindo na variavel os dados que preciso que estão em data._body (convertido em objeto atraves do JSON.parse)
      this.objetoChamadoSelecionado = objeto_retorno;   //atribuindo o objeto ao meu array
      console.log(this.objetoChamadoSelecionado);
      }, error => {
        console.log(error);
      })
    }

so far everything is running very well, giving a console.log in my variable that received the return of JSON is beautiful:
enter image description here
My View's Code
<ion-header>

  <ion-navbar>
    <ion-title>Chamado</ion-title>
  </ion-navbar>

</ion-header>

<ion-content padding >

{{objetoChamadoSelecionado}}

</ion-content>

This is where it should display my object, but it displays only this
enter image description here
also does not work:

objetoChamadoSelecionado.numero

for example, and I can not get anything ... The strangest thing of all is that on another page I have a return from a list of objects, using a * ngFor works normal ...

A:

Use json pipe to see the object with properties

{{ objetoChamadoSelecionado | json }}

Or access it properties as you mentioned above, but your objetoChamadoSelecionado must be initialized first. Without it will give you an error while data is not set.


Q:

why is this code showing memory error?maybe there is problem with while loop

this code is to find a subset of a string, which has unique characters.
make k  parts of the string and t then print these parts while not includeing the same character in the string
    def merge_the_tools(string, k):
        l = len(string)
        start = 0
        t = []
        ans = []
        while True:
            put=''

            for i in range(start,start+k):
                put += string[i]

            start = k
            t.append(put)
            if start + k == l:
                break

        for i in t:
            ss = set(i)
            s = ''
            for j in ss:
                s += j

            ans.append(s)
            for i  in s:
                print(I)
   merge_the_tools('AABBAACC',2)

I think there is a problem with ,while loop which I'm not able to find.

A:

Your need is not clear and I will respond with my understanding of your code.
you need to change the value of your start or k because here you will be stuck in start = 2 and k = 2.
Change the line
Start = k

by
start += k

it should work and stop running for infinite time.


Q:

How to inject Vuetify into my custom vue plugin

I would like to create a Vue plugin with a function which programatically renders a Vue component. That component depends on Vuetify. Everything works fine if I use vanilla HTML/CSS in that component, but using Vuetify-related things in there (e.g. a ) does not work. I assume that I didn't inject vuetify itself into the component correctly.
In my custom component, I tried importing every Vuetify component separately, but without success. I also tried creating the component with the syntax: new Vue({vuetify}), but also without success.
import MyCustomComponent from '@/components/MyCustomComponent'
import vuetify from '@/plugins/vuetify';

export default {
  install(Vue, options) {
    function renderMyCustomComponent() {
        const CustomComponent= Vue.extend(MyCustomComponent)
        Vue.use(vuetify)
        let instance = new CustomComponent()
        instance.$mount()
        document.body.appendChild(instance.$el)
    }

    Vue.prototype.$renderMyComponent = renderMyCustomComponent
  }

}

The error message indicates, that vuetify (or at least some of it's properties) are not available in my component
[Vue warn]: Error in getter for watcher "isDark": "TypeError: Cannot read property 'dark' of undefined"
HINT/EDIT: I am using Vuetify 2.0. The way Vuetify is injected into the app changed a little bit. Here's the code of my vuetify plugin file:
import Vue from 'vue';
import Vuetify from 'vuetify';
import 'vuetify/dist/vuetify.min.css';
import de from 'vuetify/es5/locale/de';

Vue.use(Vuetify)

export default new Vuetify({
  theme: {
    themes: {
      light: {
        primary: '#3f51b5',
        secondary: '#b0bec5',
        accent: '#8c9eff',
        error: '#b71c1c'
      },
    },
  },
});

A:

Not sure if you solved this issue, but I had the same problem where Vuetify in a plugin would not be initialized correctly.
Vuetify documentation states that you need to define a vuetify option when creating your vue instance:
new Vue({
  vuetify,
}).$mount('#app')

Fortunately, custom Vue plugins has an options parameter that we can use.
Here is the code that consumes your plugin:
const options = {}; // add other options here! (vuex, router etc.)
Vue.use(YourCustomPlugin, options);

new Vue(options).$mount('#app');

And here is your plugin code:
import vuetify from "./src/plugins/vuetify";

export default {
    install(Vue, options) { // options is undefined unless you pass the options param!
        Vue.component('my-custom-component', MyCustomComponent);
        Vue.use(Vuetify);
        options.vuetify = vuetify;
    }
};

The vuetify module is very simple:
import Vuetify from "vuetify";
import "vuetify/dist/vuetify.min.css";

const opts = {}

export default new Vuetify(opts);


Q:

¿Por qué no se carga el contenido de mi Custom Post Type?

Tengo el siguiente código:
                $las_ofertas = new WP_Query(array(
                    'post_type' => 'oferta',
                    'posts_per_page' => 5
                ));

                $ciudad = get_post_meta($post->ID, 'oferta_ciudad', true);
                $fecha = get_post_meta($post->ID, 'oferta_date', true);
                $descripcion = get_post_meta($post->ID, 'oferta_descripcion', true);

                if ( $las_ofertas->have_posts() ) {
                    while ( $las_ofertas->have_posts() ) : $las_ofertas->the_post(); ?>

<a href="<?php the_permalink(); ?>"><?php the_title(); ?>

                            <?php if( $ciudad ) {  ?>
<?php echo ($ciudad); ?>

                            <?php  } else {?>
La oferta no especifica la ciudad en la que desarrollará el trabajo.
 <?php } ?>

                            <?php if( $fecha ) {  ?>
<?php echo ($fecha); ?>

                            <?php  } else {?>
La oferta no especifica la fecha de inicio.
 <?php } ?>

                            <?php if( $descripcion ) {  ?>

Descripción:

<?php echo ($descripcion); ?>

                            <?php  } else {?>
La empresa no ofrece detalles del trabajo.
 <?php } ?>

<a href="<?php the_permalink(); ?>" class="btn"><?php _e('Ver oferta...') ?>

                    <?php endwhile;
                } else { ?>

No existen ofertas para mostrar.

                <?php } ?>
                <?php wp_reset_postdata();

Cuando lo veo en el front-end, sólo aparece el título de la Oferta, mas no el contenido de la misma, es decir, la función ´get_post_meta();´ no recoge los valores del CPT.

A:

Al patecer tienes mal ubicadas las varables, deberian estar dentro del loop y encerradas entre una etiquta php. Te beria quedar de la siguiente manera:
<?php $las_ofertas = new WP_Query(array(
'post_type' => 'oferta',
'posts_per_page' => 5
)); ?>

<?php if ( $las_ofertas->have_posts() ) {
while ( $las_ofertas->have_posts() ) : $las_ofertas->the_post(); ?>

<?php
$ciudad = get_post_meta($post->ID, 'oferta_ciudad', true);
$fecha = get_post_meta($post->ID, 'oferta_date', true);
$descripcion = get_post_meta($post->ID, 'oferta_descripcion', true);
?>

<a href="<?php the_permalink(); ?>"><?php the_title(); ?>

    <?php if( $ciudad ) {  ?>
<?php echo ($ciudad); ?>

    <?php  } else {?>
La oferta no especifica la ciudad en la que desarrollará el trabajo.
 <?php } ?>

    <?php if( $fecha ) {  ?>
<?php echo ($fecha); ?>

    <?php  } else {?>
La oferta no especifica la fecha de inicio.
 <?php } ?>

    <?php if( $descripcion ) {  ?>

Descripción:

<?php echo ($descripcion); ?>

    <?php  } else {?>
La empresa no ofrece detalles del trabajo.
 <?php } ?>

<a href="<?php the_permalink(); ?>" class="btn"><?php _e('Ver oferta...') ?>

No existen ofertas para mostrar.


Q:

PLS-00103: Encountered the symbol "end-of-file" when expecting one of the following: := . ( % ;

Can not run following SQL from ant's sql task:
BEGIN
   DBMS_AQADM.CREATE_QUEUE_TABLE(
   queue_table => 'MY_QUEUE',
   queue_payload_type => 'sys.aq$_jms_map_message');

   DBMS_AQADM.CREATE_QUEUE(
   queue_name => 'MY_QUEUE',
   queue_table => 'MY_QUEUE');

   DBMS_AQADM.START_QUEUE (
   queue_name => 'MY_QUEUE');

END;
/

There are following errror:
CreateMyQueue:
      [sql] Executing resource: /u1/bin/sql/createMyQueue.sql
      [sql] Failed to execute:   BEGIN DBMS_AQADM.CREATE_QUEUE_TABLE( queue_table => 'MY_QUEUE', queue_payload_type => 'sys.aq\$_jms_map_message')

BUILD FAILED
/u1/bin/.tools/build.xml:194: java.sql.SQLException: ORA-06550: line 1, column 118:
PLS-00103: Encountered the symbol "end-of-file" when expecting one of the following:
   := . ( % ;

What is wrong with SQL?

A:

Here is the solution!
http://www.javaddicts.net/blog/index.php/2005/06/13/executing-oracle-plsql-from-ant/
Following parameters should be used
delimiter="/"
delimitertype="row"
<project name="SWPDEPLOYMENT" basedir="." default="all">
   <target name="createMyQueue">
      <sql driver="oracle.jdbc.driver.OracleDriver"
           url="${sqlurl}"
           userid="${userid}"
           password="${pwd}"
           print="yes"
           delimiter="/"
           delimitertype="row"
           >
        <fileset dir=".">
           <include name="createMyQueue.sql"/>
        </fileset>
      </sql>
   </target>


Q:

Unwrapping issue in swift

I am new to swift, so apologies for funny question, but I am quite tanged in this optional type and the unwrapping thing.
So, I am trying to create a calculator for which I have a UITextField to display the digits while pressed or result after calculation and off course some buttons representing digits.

Now I have action methods attached which my digit buttons and return button properly.
I have my UITextField declared like following which is implicitly unwrapped and a mutable string array which is also unwrapped-
@IBOutlet weak var displayTextField: UITextField!
var digitArray : [String]!

The append digit method works fine which just take the digit from the button and displays it in the textfield by appending. But I am getting a Bad Access error in the enter method. I guess, I am trying to add the item in the array improperly. Can anyone please help.
@IBAction func appendDigit(sender: UIButton) {
        let digit = sender.currentTitle!
        displayTextField.text = digit + displayTextField.text
}
@IBAction func enter(sender: UIButton) {
        digitArray.append(displayTextField.text)
}

A:

digitArray is declared but not initialized.
var digitArray = [String]()

The initializer syntax is either a pair of parentheses after the type let x = Type() or in case of an array with the type annotation and a pair of square brackets let x : [Type] = [].
As the compiler infers the type, the declaration [String] is not needed.
Declare variables non optional whenever possible, you will get more and better help by the compiler.


Q:

Is "What I'm doing is" followed by an infinitive or gerund form?

Title says everything. American English please (but if it's different in British English, please point that out as well)

A:

To answer this kind of question I find it best to consult a large corpus.  This enables me to answer the question based on what people actually do rather than offer an answer that is opinion-based and prescriptive.
Using Sketch Engine (https://www.sketchengine.co.uk) I did a search for what I am doing is to in the huge "English Web 2013 (enTenTen13)" corpus, consisting of 19,685,733,337 words.
I found 24 examples, all appearing to have been written by competent writers, where the infinitive is used in a noun phrase that is expressing an equivalent to the preceding what I am doing is.

A search for "what I am doing is" yields 1,172 examples.  The following is a picture of the first page of a random sample (250 examples) of the overall set. I have added green rectangles to show where the gerund is used in a noun phrase that amounts to the equivalent of what I am doing.  There are thirteen of these on the page of 30 examples.  1172 divided by 30 equals roughly 39.  Multiply 39 by 13 and you get 507.  So there are probably around 500 examples in the corpus of a gerund being used in a noun phrase equivalent to what I am doing is.
We can conclude that the gerund is far more common in this kind of equivalent construction.  However, as the gerund examples that are not enclosed in green triangles show, the construction is not limited to the expression of equivalents to what I am doing is.


Q:

Django Pagination from ?page= to /page/

I have this view:
class PageView(ListView):
    # ... code ...
    paginate_by = 4

In template I have something like:

              {% if page_obj.has_previous %}
                  previous
              {% endif %}

                  Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}.

              {% if page_obj.has_next %}
                  next
              {% endif %}

How can I transform GET variable ?page=number to look like /page/number/ in django?

A:

I cannot test it now but you should be able to re-use all of ListView.
Have a look at django.views.generic.list.MultipleObjectMixin#paginate_queryset:
def paginate_queryset(self, queryset, page_size):
    """
    Paginate the queryset, if needed.
    """
    paginator = self.get_paginator(
        queryset, page_size, orphans=self.get_paginate_orphans(),
        allow_empty_first_page=self.get_allow_empty())
    page_kwarg = self.page_kwarg

    # HERE
    page = self.kwargs.get(page_kwarg) or self.request.GET.get(page_kwarg) or 1

    try:
        page_number = int(page)
    except ValueError:
        if page == 'last':
            page_number = paginator.num_pages
        else:
            raise Http404(_("Page is not 'last', nor can it be converted to an int."))
    try:
        page = paginator.page(page_number)
        return (paginator, page, page.object_list, page.has_other_pages())
    except InvalidPage as e:
        raise Http404(_('Invalid page (%(page_number)s): %(message)s') % {
            'page_number': page_number,
            'message': str(e)
        })

This means that Django looks for the page number first in the view's kwargs, and then in the get parameters.
The values in self.kwargs come from the view's own **kwargs - see django.views.generic.base.View#as_view. This means you should be able to just define a URL like url(r'^event/(?P<page>'d+)/$' and use it with your existing CBV - it should pick up the page number on its own.


Q:

Repository is changed after push on mercurial

When I create repository and push on server and when we clone the repository in local system the files are come with red signal means they are changed.
When we compare both repository I found that the content of files in .hg folder is changed.
Can anyone pls tell me how to remove this problem!
Edit:
When we change the .hg folder the red icon becomes green!!!!

A:

If you take 1 modified (changed) file, watch the diff closely, and only see the difference is in new lines only, this is the classical newlines mess.
(happens to most people when working crossplatform)
There is a ready to use Mercurial Extension, taking care of this is problem.
It's called eol.
Learn how to use it and the problem from here:
https://www.mercurial-scm.org/wiki/EolExtension


Q:

How do I get started creating Mac applications?

I am currently an iPhone application developer. As an iPhone developer, I figured I could also create and sell Mac applications now that there is a Mac Application Store.
I have learned from Apple that - similar to what is required for the iPhone - I need to join their Mac Developer program for $99 in order to submit applications to the Mac Application Store.
My question is multi-part:

How similar is developing for the Mac to developing for the iPhone?
What resources are available for learning how to create Mac Applications?

A:

You're in luck!  They've got many of the same foundations (Cocoa, Foundation, Obj-C)!  I made my biggest initial strides in mac programming reading Cocoa Programming for Mac OS by Aaron Hillegass.
http://www.amazon.com/Cocoa-Programming-Mac-OS-3rd/dp/0321503619/ref=trdrt_list_asin

A:

In basic terms Mac programming can be though of as a "superset" of iPhone programming. Note that this is not strictly true, but provides a rough idea of things.
There are things such as garbage collection, foundation classes, Cocoa Bindings, Carbon, etc. that have no presence on IOS.
So to answer your first question, noit's not the same but it is similar.
There are some great answers to a similar question here: From iPhone to Mac programming
In general the resources you will want to start with are Apple's own, provided on the Mac Dec Center website. http://developer.apple.com/devcenter/mac/index.action


Q:

fill_parent is not filling entire screen in LinearLayout

I tried to search for this answer and the closest I got to an answer was to add android:resizable="true", which is deprecated. I apologize if this question has been answered but I couldn't find it if it was.
Anyway, my app is not filling the entire screen. The method I was using was working in android 2.2 but I am now using a 2.3 emulator and it's not working. I am not sure if this is actually the issue or not.
Now to the problem...
I am creating a temperature converter app (yes, it's homework) and the app is not filling the entire screen even though I say fill_parent for the layout_width and height in the LinearLayout. A suggestion I saw was to use a RelativeLayout, which I could do I suppose but it seems like a band-aid, not a solution. Shouldn't this work?
Here is my code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:gravity="center_vertical"
    android:background="@color/white"
    >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Temperature Converter"
        android:textColor="@color/black"
        />

    <RadioGroup xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/convertGroup"
        android:orientation="vertical"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        >
        <RadioButton android:id="@+id/CtoF"
            android:orientation="vertical"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Celsius to Fahrenheit"
            android:textColor="@color/black"
            />
        <RadioButton android:id="@+id/FtoC"
            android:orientation="vertical"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Fahrenheit to Celsius"
            android:textColor="@color/black"
            />
    </RadioGroup>

    <EditText
        android:id="@+id/tempInput"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:singleLine="true"
        android:hint="Temperature"
    />

    <TextView
        android:id="@+id/converted"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textColor="@color/black"
    />
</LinearLayout>

Here is the result:

A:

Add below code in menifest after application tag
<supports-screens android:resizeable="true"
                      android:smallScreens="true"
                      android:normalScreens="true"
                      android:largeScreens="true"

                      android:anyDensity="true" />


Q:

generate calendar of a given month and year in haskell

I have been learning haskell since a week and is facing different problems. This time I have to create a calendar from a given month and year. I am almost done but the problem is that I could not start filling days from starting day.
My solution is
getDaysInMonth year month=(nDays,sDay)
                          where nDays = gregorianMonthLength year month
                                sDay= digitToInt(last(showWeekDate (fromGregorian year month 01)))
year=2013
month=10
months=["JANUARY","FEBRUARY","MARCH","APRIL","MAY","JUNE","JULY","AUGUST","SEPTEMBER","OCTOBER","NOVEMBER","DECEMBER"]
mnth=months!!(month-1)
monthDate = getDaysInMonth year month
startAt=snd(monthDate)
totalDays = fst(monthDate)
printLine = "\n"++concat ["+---\t" | r <- [1..7]]
check x | x>totalDays=""
        | x<=totalDays=show x
genDays n m="\n "++concat[check(x)++"\t|"|x<-[n..m]]
genD 6=""
genD sP=genDays ((sP-1)*7+1) (sP*7) ++genD (sP+1)
generateCalendar=printLine++"\n "++
                        concat [[r]++"\t|" | r <- mnth]++printLine++
                        "\n Sun\t|Mon\t|Tue\t|Wed\t|Thu\t|Fri\t|Sat"++printLine++
                        genD 1
main=do
     putStrLn generateCalendar

Output of this program is like this
+---+---+---+---+---+---+---
 O  |C  |T  |O  |B  |E  |R  |
+---+---+---+---+---+---+---
 Sun|Mon|Tue|Wed|Thu|Fri|Sat
+---+---+---+---+---+---+---
 1  |2  |3  |4  |5  |6  |7  |
 8  |9  |10 |11 |12 |13 |14 |
 15 |16 |17 |18 |19 |20 |21 |
 22 |23 |24 |25 |26 |27 |28 |
 29 |30 |31 |   |   |   |   |

So the problem is that October month should start from Monday. I think the implementation of the solution is little mess but how can I solve this problem ?
Thanks in advance

A:

A more "functional" approach to this problem would be:

Create a list of 35 strings, each string is either the empty string or a (stringified) number.
Break up the list into chunks of 7 elements each (so you get five chunks)
For each chunk render the elements as a row in the calendar.

For example, for the month October 2013 the list of 35 strings would be:
cells = [ "", "", "", "1", "2", "3", ..., "31", "", "" ]

The chunks can be created using this helper function:
chunksOf7 (a:b:c:d:e:f:g:rest) = [ [a,b,c,d,e,f,g] ] ++ chunksOf7 rest
chunksOf7 xs = xs

(There are better ways to define chunksOf7, but this will suffice.)
And to render a chunk:
renderChunk cells =  (concat $ map renderCell cells) ++ "\n"
renderCell c = pad 3 c ++ "|"
pad n str = str ++ (replicate (n-(length str)) ' ')

pad n str pads the string str with spaces on the right until the total length is n.
replicate n a creates a list of with the value a repeated n times.
And to put it all together (once you have your cells list):
renderCalendarBody cells =  concat (map renderChunk chunks)
  where chunks = chunksOf7 cells

Now, given a year and a month, you just have to write a function to define what cells is.
The cells list is going to consists of:

some number of leading empty strings
followed by 1 through 30 (or 31 or whatever the last day of the month is)
followed by some number of trailing empty strings

i.e.:
cellsForYearAndMonth y m = (replicate n1 "")
                              ++ [ show d | d <- [1..lastday] ]
                              ++ (replicate n2 "")
  where lastday = ...
        n1 = ... number of leading empty strings ...
        n2 = ... number of trailing empty strings ...

A:

Thanks @user5402. Finally I got working version
import Data.Time.Calendar
import Data.Time.Calendar.WeekDate
import Data.Char
year=2014
month=2
months=["JANUARY","FEBRUARY","MARCH","APRIL","MAY","JUNE","JULY","AUGUST","SEPTEMBER","OCTOBER","NOVEMBER","DECEMBER"]
mnth=months!!(month-1)
monthDate = getDaysInMonth year month
startAt=snd(monthDate)
totalDays = fst(monthDate)

getDaysInMonth year month=(nDays,sDay)
                      where nDays = gregorianMonthLength year month
                            sDay= digitToInt(last(showWeekDate (fromGregorian year month 01)))
cells = (replicate n1 "")
                          ++ [ show d | d <- [1..lastday] ]
                          ++ (replicate n2 "")
          where lastday = totalDays
                n1=(startAt-1)
                n2=(7-(totalDays-(29-startAt)))
chunksOf7 []=[]
chunksOf7 (a:b:c:d:e:f:g:rest) = [ [a,b,c,d,e,f,g] ] ++ chunksOf7 rest

pad n str = str ++ (replicate (n-(length str)) ' ')
renderCell c = pad 3 c ++ "|"
renderChunk cells =  (concat $ map renderCell cells) ++ "\n"

printLine = "\n"++concat ["+---" | r <- [1..7]]++"\n"
monthLine=concat [[r]++" |" | r <- mnth]
dayLine="Sun|Mon|Tue|Wed|Thu|Fri|Sat"
heading=concat[printLine,"Year: ",show year,printLine,monthLine,printLine,dayLine,printLine]

renderCalendarBody cells =  heading++concat (map renderChunk chunks)
  where chunks = chunksOf7 cells

main= do putStrLn $ renderCalendarBody cells


Q:

Hide HTML element if user is on an iOS device?

I want the code to check if a user is on an iOS device, and then, if they are not, hide the HTML input type "Play" button.
So, in my code, I'm sure if my iOS checking is wrong, of the code to hide the "Play" button, or both:
<!DOCTYPE html>

<title>NEW ENTRY TEST</title>

<video id="vid" src="http://awp.diaart.org/ali/test/movies/testmovie.mov" width="640" height="480" autoplay></video>

<input type="submit" value="Play" onclick="document.getElementById('vid').play();">

Basically I just want this play button to display, only if the user is on an iOS device.
I know it's not working because the play button still displays on a regular (non-iOS) computer.
Curious to hear anyone's thoughts on this.

A:

jsFiddle example here.
Firstly, it should be wrapped inside a $(document).ready:
$(document).ready(function(){
  var iOS = false,
  p = navigator.platform;
  if( p === 'iPad' || p === 'iPhone' || p === 'iPod' ) {
     iOS = true;
  }
  if (iOS === false) {
     $("input[type=button]").hide();
  }
});

Now, the only potential problem you have left is your check case case using navigator.platform.
According to the specification, navigator.platform returns one of the following values:
"Win32", "Linux i686", "MacPPC", "MacIntel" - none of which match your check case.
However, other sources on the internet seem to suggest that it does indeed return "iPhone", "iPad" etc. on the respective devices. As I don't own one of these devices, I can't test that theory out. But if it doesn't work as suggested, there are other documented ways to detect the iPhone, iPad and iPod - see Detect iPad users using jQuery?.
Once you've tested a solution that detects all three iOS products, store it in your p variable and your code should function as you wish.

Side Notes:

You should only have one , and can merge the two seperate


Q:

Android ListView not refreshing after change cursor

the following code is used to populate an endless ListView.
When the user reach the end of the list, the app call the async task to get more items, then on post execute the new cursor is returned and merged with the previous.
The problem is this code does not work on ICS and Jelly Bean, but works on Froyo and Gingerbread.
On ICS and JellyBean the listview gets empty, but if you log cursor size you get the size of the merged cursor.
Cursor[] cursors = new Cursor[2];
//actual cursor
cursors[0] = resourceCursor.getCursor();
//new cursor returned by async task
cursors[1] = result;
MergeCursor mergeCursor = new MergeCursor(cursors);
resourceCursor.changeCursor(mergeCursor);

A:

Ok, i found a solution, seems an ungly solution, but it works.
On my research all the problems seemed to address to an issue after Honeycumb, so i changed the API Level to 11, to get swapCursor available, and then, on my code:
Cursor[] cursors = new Cursor[2];
//actual cursor
cursors[0] = resourceAdapterCursor.getCursor();
//new cursor returned by async task
cursors[1] = result;
MergeCursor mergeCursor = new MergeCursor(cursors);
if (android.os.Build.VERSION.SDK_INT > android.os.Build.VERSION_CODES.GINGERBREAD){
    resourceAdapterCursor.swapCursor(mergeCursor);
} else {
    resourceAdapterCursor.changeCursor(mergeCursor);
}

Thanks!
Best regards.
Rodrigo


Q:

Android converting calendar in one TimeZone to local TimeZone

I am using following code to convert timezone (GMT-3) to device local timezone.
int hour=17,minute=0,day=12,month=6,year=2014;

Calendar cal = new GregorianCalendar(TimeZone.getTimeZone("GMT-3"));
cal.set(year, (month-1), day,hour,minute);

cal.setTimeZone(TimeZone.getDefault());
Log.d("Time", cal.get(Calendar.DATE)+"/"+cal.get(Calendar.MONTH)+"/"+cal.get(Calendar.YEAR)+" , "+cal.get(Calendar.HOUR_OF_DAY)+":"+cal.get(Calendar.MINUTE)+" "+cal.get(Calendar.AM_PM));

My local timezone is GMT+5:30
Expected result is
Time 13/5/2014, 1:30 0
But I am getting the result
12/5/2014 , 13:30 1

A:

Sorry for you, GregorianCalendar is sometimes the hell. Your problem is following:
If you immediately set the timezone after having set the fields for year, month etc. then this mutable calendar class will only shift the timezone retaining the already set fields containing the local time. Those fields for year, month etc. will NOT be recalculated. This behaviour causes a shift on the global timeline represented by cal.getTime(), too.
In order to force the calendar object to recalculate the fields you need to call a getter. Watch out for following code and especially remove the comment marks to see the effect.
int hour = 17, minute = 0, day = 12, month = 6, year = 2014;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mmZ");
TimeZone tz1 = TimeZone.getTimeZone("GMT-3");
sdf.setTimeZone(tz1);

Calendar cal = new GregorianCalendar(tz1);
cal.set(year, (month - 1), day, hour, minute);
//      System.out.println(sdf.format(cal.getTime()));
//      System.out.println("Hour=" + cal.get(Calendar.HOUR_OF_DAY));

TimeZone tz2 = TimeZone.getTimeZone("GMT+0530");
sdf.setTimeZone(tz2);
cal.setTimeZone(tz2);
System.out.println(sdf.format(cal.getTime()));
System.out.println("Hour=" + cal.get(Calendar.HOUR_OF_DAY));

Output with comment-disabled lines:
2014-06-12T17:00+0530
Hour=17

Output with enabled lines after having removed the comment marks:
2014-06-12T17:00-0300
Hour=17
2014-06-13T01:30+0530
Hour=1


Q:

Kafka Producer error Expiring 10 record(s) for TOPIC:XXXXXX: 6686 ms has passed since batch creation plus linger time

Kafka Version : 0.10.2.1,
Kafka Producer error Expiring 10 record(s) for TOPIC:XXXXXX: 6686 ms has passed since batch creation plus linger time
org.apache.kafka.common.errors.TimeoutException: Expiring 10 record(s) for TOPIC:XXXXXX: 6686 ms has passed since batch creation plus linger time

Any clue will be appreciated ..

A:

This exception is occuring because you are queueing records at a much faster rate than they can be sent.
When you call the send method, the ProducerRecord will be stored in an internal buffer for sending to the broker. The method returns immediately once the ProducerRecord has been buffered, regardless of whether it has been sent.
Records are grouped into batches for sending to the broker, to reduce the transport overheard per message and increase throughput.
Once a record is added into a batch, there is a time limit for sending that batch to ensure that it has been sent within a specified duration. This is controlled by the Producer configuration parameter, request.timeout.ms, which defaults to 30 seconds.
If the batch has been queued longer than the timeout limit, the exception will be thrown. Records in that batch will be removed from the send queue.
Producer configs block.on.buffer.full, metadata.fetch.timeout.ms and timeout.ms have been removed. They were initially deprecated in Kafka 0.9.0.0.
Therefore give a try for increasing request.timeout.ms
Still, if you have any problem related to throughput, you can also refer following blog


Q:

Dimension of the annihilator (Linear algebra done right, 3.106)

$V$ is finite-dim vector space, and $\text{U}$ its subspace, and $\text{V}'$ and $\text{U}'$ are their dual counterparts. $\text{U}^0 = \{ \phi \in \text{V}': \phi(u) = 0 $ for all u $ \in \text{U} \}$, then it's proved in Axler's 3.106 that:
$\text{dim U} + \text{dim U}^0 = \text{dim V}$
by taking $i \in \mathcal{L}(U,V) $, defined as $i(u) = i$ for $u \in \text{U}$ and, after applying the Fundamental Theorem of Linear Algebra on $i'$, showing that $\text{null } i' = \text{U}^0$ and $\text{range i}' = \text{U}$ (and $\text{dim V}' = \text {dim V}$)
What I don't understand, is how can the result for the single map $i$ be generalized to  all the (sub)spaces. Can somebody clear that up for me? Thanks

A:

It is incorrect to say that we have used a single map $i$ to conclude a statement about all subspaces. Rather, we have chosen a subspace $U$, constructed a map $i$ using that subspace $U$, and then used this map to make a conclusion about the subspace $U$. Because there was nothing special about the subspace $U$ (i.e. our choice of subspace was arbitrary), we were able to conclude a statement about all subspaces.
An equivalent perspective is this: what we have constructed is a map $i_U$ that depends on our choice of subspace $U$. By considering the relationship that every subspace $U$ has to the image and kernel of its corresponding map $i_U'$, we have reached a conclusion about all subspaces $U$.


Q:

How to fix the error "Unfortunately closed myapp" in android?

In my app, i have a listview. If i click on one of the item in the list it will traverse to another intent which gives me to edit the values. It's not working for me for only one listitem. it will close the application. I checked the logcat. I saw it as IndexOutOfBound exception. Not able to fix it. Please help me.
lvDetail.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id)
            {
                HashMap<String, String> map = new HashMap<String, String>();
                map = valuesList.get(position);

                DesigId = map.get(Desig_ID);
                DesigName = map.get(Desig);
                Desc1 = map.get(Desc);

                Intent in = new Intent(ViewAndUpdate.this, EnterDetails.class);
                in.putExtra("DesigId", "" + DesigId);
                in.putExtra("Desig", "" + DesigName);
                in.putExtra("Desc", "" + Desc1);
                startActivity(in);

            }
        });

This is the logcat part:
01-31 12:17:32.693: E/AndroidRuntime(2263): FATAL EXCEPTION: main
01-31 12:17:32.693: E/AndroidRuntime(2263): java.lang.IndexOutOfBoundsException: Invalid index 10, size is 10
01-31 12:17:32.693: E/AndroidRuntime(2263):     at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:251)
01-31 12:17:32.693: E/AndroidRuntime(2263):     at java.util.ArrayList.get(ArrayList.java:304)

A:

It said size is 10 it means 0 to 9 but your position is 10 ! try positon-1 instead of position