问:
Can`t extend the JavaScript native method declaration when use TypeScript
I try to extend JS native String class adding the new method but get TS2339 error.</p>

```<code>interface String {
  transl(): string;
}

String.prototype.transl = function() { // TS2339: Property 'transl' does not exist on type 'String'.
  return 'xxx';
};

'ff'.transl();
</code>```

答:
Your code is technically correct, and works in the TypeScript playground, which leads me to believe that the problem is being caused by having this code inside of a module.

When you write an interface within a module, or namespace, it contributes to the naming context of that module or namespace. i.e. you may well be adding a new interface named String to your local naming context, rather than merging your interface declaration with the global String interface.

You can fix this by placing your interface in the global context, so it has the same common root as the one from the lib.d.ts file. Or using declare global from within a module:

```<code>declare global {
  interface String {
    transl(): string;
  }
}

String.prototype.transl = function () {
  return 'xxx';
};

'ff'.transl();
</code>```

Body:
I try to extend JS native String class adding the new method but get TS2339 error.

interface String {
  transl(): string;
}

String.prototype.transl = function() { // TS2339: Property 'transl' does not exist on type 'String'.
  return 'xxx';
};

'ff'.transl();

Body:
Your code is technically correct, and works in the TypeScript playground, which leads me to believe that the problem is being caused by having this code inside of a module.

When you write an interface within a module, or namespace, it contributes to the naming context of that module or namespace. i.e. you may well be adding a new interface named String to your local naming context, rather than merging your interface declaration with the global String interface.

You can fix this by placing your interface in the global context, so it has the same common root as the one from the lib.d.ts file. Or using declare global from within a module:

declare global {
  interface String {
    transl(): string;
  }
}

String.prototype.transl = function () {
  return 'xxx';
};

'ff'.transl();


来源: stackexchange

问:
Use table column in hive window range
I am trying to collect_list over a window, and i want to limit the window size dynamically based on the one column value from same table.

```<code>select concat_ws('->', collect_list(CASE WHEN b.colA IN ("bla", "blabla") THEN concat_ws("-", colB,colC) END) OVER (PARTITION BY colD ORDER BY time-stamp ROWS BETWEEN colE PRECEDING AND CURRENT ROW)) AS myCol from ( select colA,colB,colC,colD,colE from mytable) a

colA|colB|colC|colD|colE|time-stamp
bla|abc|pqr|INDIA|1|2017-12-10
bla|abc|pqr|CHINA|1|2017-12-11
bla|abc|pqr|INDIA|2|2017-12-12
bla|abc|pqr|INDIA|3|2017-12-13
bla|abc|pqr|CHINA|2|2017-12-14
</code>```

here hive doesnt accept colE in the range which has valid numaric values. i get error:

```<code>Error while compiling statement: FAILED: ParseException line 177:89 cannot recognize input near 'colE' 'preceding' 'AND' in windowframeboundary
</code>```

答:
From the documentation here. Hive does not expetect any columns after the between word. The following are the available options</p>

```<code>(ROWS | RANGE) BETWEEN (UNBOUNDED | [num]) PRECEDING AND ([num] PRECEDING | CURRENT ROW | (UNBOUNDED | [num]) FOLLOWING)
(ROWS | RANGE) BETWEEN CURRENT ROW AND (CURRENT ROW | (UNBOUNDED | [num]) FOLLOWING)
(ROWS | RANGE) BETWEEN [num] FOLLOWING AND (UNBOUNDED | [num]) FOLLOWING
</code>```

ContentLicense: CC BY-SA 3.0

Title: Use table column in hive window range

Body:
I am trying to collect_list over a window, and i want to limit the window size dynamically based on the one column value from same table.

select concat_ws('->', collect_list(CASE WHEN b.colA IN ("bla", "blabla") THEN concat_ws("-", colB,colC) END) OVER (PARTITION BY colD ORDER BY time-stamp ROWS BETWEEN colE PRECEDING AND CURRENT ROW)) AS myCol from ( select colA,colB,colC,colD,colE from mytable) a

colA|colB|colC|colD|colE|time-stamp
bla|abc|pqr|INDIA|1|2017-12-10
bla|abc|pqr|CHINA|1|2017-12-11
bla|abc|pqr|INDIA|2|2017-12-12
bla|abc|pqr|INDIA|3|2017-12-13
bla|abc|pqr|CHINA|2|2017-12-14

here hive doesnt accept colE in the range which has valid numaric values. i get error:

Error while compiling statement: FAILED: ParseException line 177:89 cannot recognize input near 'colE' 'preceding' 'AND' in windowframeboundary

Body:
From the documentation here. Hive does not expetect any columns after the between word. The following are the available options

(ROWS | RANGE) BETWEEN (UNBOUNDED | [num]) PRECEDING AND ([num] PRECEDING | CURRENT ROW | (UNBOUNDED | [num]) FOLLOWING)
(ROWS | RANGE) BETWEEN CURRENT ROW AND (CURRENT ROW | (UNBOUNDED | [num]) FOLLOWING)
(ROWS | RANGE) BETWEEN [num] FOLLOWING AND (UNBOUNDED | [num]) FOLLOWING


问:
XmlSerializer to convert to XmlElement or string
I am storing developer notes in XML files within the project, to eliminate storing them on a SQL instance to reduce database calls.

I have my class set up to be Serialized

```<code>[Serializable]
public class NoteDto
{
    [NonSerialized]
    private string _project;

    public string Date { get; set; }
    public string Time { get; set; }
    public string Author { get; set; }
    public string NoteText { get; set; }
    public string Project
    {
        get => _project;
        set => _project = value;
    }
}
</code>```

to create this element

```<code><Note>
  <Date></Date>
  <Time></Time>
  <NoteText></NoteText>
  <Author></Author>
</Note>
</code>```

The reason I do not want Project property serialized, is that the Note Element is in a parent element (NotesFor).

```<code><NotesFor id="project value here">
  // note element here
</NotesFor>
</code>```

I need the Project string to search for the Node where the NotesFor element id = Project
then append the created element to the end of its children.

So that leaves two questions

Do I create an XElement and append to current node or do I create a string
to append to the node in the Xml file? I don't work much with Xml so I am
not sure what the standard protocol is to update Xml files.

Is there a better way to accomplish what I am trying to do?

答:
You don't need to mark the class serializable.

```<code>public class NoteDto
{
    public string Date { get; set; }
    public string Time { get; set; }
    public string Author { get; set; }
    public string NoteText { get; set; }
    [XmlIgnore]
    public string Project { get; set; }
}
</code>```

You can serialize this with the following code, which I've implemented as an extension method:

```<code>public static string ToXml<T>(this T thing)
{
    if (thing == null)
        return null;

    var builder = new StringBuilder();

    new XmlSerializer(typeof(T)).Serialize(new StringWriter(builder), thing);

    return builder.ToString();
}
</code>```

Which gets used like this:

```<code>var note = new NoteDto
{
    Date = "1/1/2018",
    Time = "4:00 PM",
    Author = "Some Guy",
    NoteText = "My Note",
    Project = "A Project"
};
var xml = note.ToXml();
</code>```

Body:
I am storing developer notes in XML files within the project, to eliminate storing them on a SQL instance to reduce database calls.

I have my class set up to be Serialized

[Serializable]
public class NoteDto
{
    [NonSerialized]
    private string _project;

    public string Date { get; set; }
    public string Time { get; set; }
    public string Author { get; set; }
    public string NoteText { get; set; }
    public string Project
    {
        get => _project;
        set => _project = value;
    }
}

to create this element

<Note>
  <Date></Date>
  <Time></Time>
  <NoteText></NoteText>
  <Author></Author>
</Note>

The reason I do not want Project property serialized, is that the Note Element is in a parent element (NotesFor).

<NotesFor id="project value here">
  // note element here
</NotesFor>

I need the Project string to search for the Node where the NotesFor element id = Project
then append the created element to the end of its children.

So that leaves two questions

Do I create an XElement and append to current node or do I create a string
to append to the node in the Xml file? I don't work much with Xml so I am
not sure what the standard protocol is to update Xml files.

Is there a better way to accomplish what I am trying to do?

Body:
You don't need to mark the class serializable.

public class NoteDto
{
    public string Date { get; set; }
    public string Time { get; set; }
    public string Author { get; set; }
    public string NoteText { get; set; }
    [XmlIgnore]
    public string Project { get; set; }
}

You can serialize this with the following code, which I've implemented as an extension method:

public static string ToXml<T>(this T thing)
{
    if (thing == null)
        return null;

    var builder = new StringBuilder();

    new XmlSerializer(typeof(T)).Serialize(new StringWriter(builder), thing);

    return builder.ToString();
}

Which gets used like this:

var note = new NoteDto
{
    Date = "1/1/2018",
    Time = "4:00 PM",
    Author = "Some Guy",
    NoteText = "My Note",
    Project = "A Project"
};
var xml = note.ToXml();


问:
Use Case Diagram - Web Server(external) or just Admin?
I am making a Use Case Diagram for my application which involves verifying users.The verification process involves an external web server.Along with this i have admin as an actor.Should i include Web server(actor) or should i just leave it as a use case for admin?
My Use Case Diagram</p>

答:
Actor: external element which is involved in a use case. It could be a human or "whatever".

So the first point to know is : is this web server included or not in your system ?

If the web server is in your system, it could not be an actor, if it is external to your system and participates to a use case, this is an actor.

A use case is a BehavioredClassifier which may have InterfaceRealizations, and owns a set of Behaviors. (p 172)

A use case is a set of actions, it would be strange that a server could be a use case.

The arrow between actor is not the right one. The bullet near the actor is unknown for me.

There are primarry and secondary actors (web server) but we can not which is what.

The extend is not usefull since View Alternatives is used by one use case only. And this is not the right arrow for extend (a dash one with open arrow)

You can add some generalizations relation between Care taker and doctor and Care taker and Chemist : they activate the same set of use cases.

Your Admin manages users only, he can't do any actions of the normal users. Is it right ? In some context Admin gets all rights.

Then you can read a lot's of post about UC and the fact that a UC does not model a function.


问:
Kerning problems when drawing text character by character
I'm trying to draw strings character by character to add lighting effects to shapes composed of text.

```<code>while (i != line.length()) {
c = line.substring(i, i + 1);

cWidth = g.getFontMetrics().stringWidth(c);

g.drawString(c, xx += cWidth, yy);
i++;
}
</code>```

The problem is, the width of a character isn't the actual distance it's drawn from another character when those two characters are printed as a string. Is there any way to get the correct distance in graphics2d?

答: The problem is that kerning defines the spacing of pairs of letters, and iterating over a string char-by-char gives the kerning system no chance to kick in. I think you'll have to use either a fixed-width font or rework your lighting effect so it works with full strings instead of single chars.

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to draw strings character by character to add lighting effects to shapes composed of text.

while (i != line.length()) {
c = line.substring(i, i + 1);

cWidth = g.getFontMetrics().stringWidth(c);

g.drawString(c, xx += cWidth, yy);
i++;
}

The problem is, the width of a character isn't the actual distance it's drawn from another character when those two characters are printed as a string. Is there any way to get the correct distance in graphics2d?


问:
Connections in mxgraph
I want to know how to avoid bidirectional connections. For example:

http://i.stack.imgur.com/4HR4H.png

Is there any way to do this?

I work with mxGraph, javascript.

EDIT: Sorry, maybe I didn’t explain well, I mean if we have two cells (a---> b) cannot be (a <--- b) this may be detected in real time.

答:
you can check out this example Validation - Using multiplicities for automatically validating a graph.

mxMultiplicity defines invalid connections along with the error messages that they produce.

Title: Connections in mxgraph


问:
Issue with out system.Array Conversion for solidworks plugin C#
I just got thrown into a C# project for solidWorks that I'm not too comfortable with. I need to convert this out System.Array to a string[]. Then that string is called and converted from out System.Array to out EdmLib.EdmBatchError2[].

TLDR: out System.Array' to a string[].

Code:

```<code>private void GetSerialNumberGenerators()
{
    IEdmSerNoGen7 utility = this.m_vault.CreateUtility(EdmUtility.EdmUtil_SerNoGen) as IEdmSerNoGen7;
    Array ppoRetNames = Array.CreateInstance(typeof(string[]), 0);
    utility.GetSerialNumberNames(out ppoRetNames);
    this.comboBoxSerialNumber.DataSource = (object) ppoRetNames;
}
</code>```

Severity    Code    Description Project File    Line    Suppression State
Error   CS1503  Argument 1: cannot convert from 'out System.Array' to 'out string[]'

答:
It's simple as

```<code>string[] ppoRetNames;
GetSerialNumberNames(out ppoRetNames);
</code>```

This is the way to declare a string[]. Don't initialize it yourself because GetSerialNumberNames will do it (out-parameter). No need to use Array.CreateInstance.

Apart from that you are creating a jagged array because you pass typeof(string[]) not typeof(string). You need a one dimensional array so this would be correct:

```<code>Array someArray = Array.CreateInstance(typeof(string), 0);
string[] ppoRetNames = (string[])someArray;  // so a cast is what was missing
</code>```

Body:
I just got thrown into a C# project for solidWorks that I'm not too comfortable with. I need to convert this out System.Array to a string[]. Then that string is called and converted from out System.Array to out EdmLib.EdmBatchError2[].

TLDR: out System.Array' to a string[].

Code:

private void GetSerialNumberGenerators()
{
    IEdmSerNoGen7 utility = this.m_vault.CreateUtility(EdmUtility.EdmUtil_SerNoGen) as IEdmSerNoGen7;
    Array ppoRetNames = Array.CreateInstance(typeof(string[]), 0);
    utility.GetSerialNumberNames(out ppoRetNames);
    this.comboBoxSerialNumber.DataSource = (object) ppoRetNames;
}

Severity    Code    Description Project File    Line    Suppression State
Error   CS1503  Argument 1: cannot convert from 'out System.Array' to 'out string[]'

Body:
It's simple as

string[] ppoRetNames;
GetSerialNumberNames(out ppoRetNames);

This is the way to declare a string[]. Don't initialize it yourself because GetSerialNumberNames will do it (out-parameter). No need to use Array.CreateInstance.

Apart from that you are creating a jagged array because you pass typeof(string[]) not typeof(string). You need a one dimensional array so this would be correct:

Array someArray = Array.CreateInstance(typeof(string), 0);
string[] ppoRetNames = (string[])someArray;  // so a cast is what was missing


问:
Git disk usage per branch
Do you know if there is a way to list the space usage of a git repository per branch ? (like df or du would)

By "the space usage" for a branch I mean "the space used by the commits which are not yet shared accross other branches of the repository".

答:
I had the same problem this morning and wrote a quick script:

```<code>for a in $(git branch -a | grep remotes | awk '{print $1}' | sed 's/remotes\/origin\///'); do echo -n ${a} -\ ; git clean -d -x -f > /dev/null 2>&1 ;git checkout ${a} > /dev/null 2>&1; du -hs -I --exclude-dir=.git .;done
</code>```

This will checkout every remote branch after resetting their content to make sure we cleanly checkout it. Then it will display the size without the .git directory.

With this, I was able to find the person who pushed a branch with a big file in it.

Please remember to do this in another cloned directory as it will wipe out everything that is not committed

Title: Git disk usage per branch

Body:
I had the same problem this morning and wrote a quick script:

for a in $(git branch -a | grep remotes | awk '{print $1}' | sed 's/remotes\/origin\///'); do echo -n ${a} -\ ; git clean -d -x -f > /dev/null 2>&1 ;git checkout ${a} > /dev/null 2>&1; du -hs -I --exclude-dir=.git .;done

This will checkout every remote branch after resetting their content to make sure we cleanly checkout it. Then it will display the size without the .git directory.

With this, I was able to find the person who pushed a branch with a big file in it.

Please remember to do this in another cloned directory as it will wipe out everything that is not committed

ContentLicense: CC BY-SA 4.0


问:
Is it a bad way to force a List to a HashMap?
I will submit my code, explain it, and ask you questions.

The following code is part of the Controller code.

```<code>        HashMap<String, Object> result = bService.getBoardListPage(params, page-1);
     System.out.println("result : " + result);
     // Deriving the desired value among the List values ??existing in the HashMap -----------------------------------------
     List<?> list = (List<?>) result.get("boardList");

     for(int i = 0; i < list.size(); i++)
     {
        HashMap<String, Object> map = (HashMap<String, Object>) list.get(i);
        System.out.println("map 1 : " + map);
        int all_boardIDX = (Integer) map.get("board_idx");
        HashMap<String, Object> replyBoard = bService.boardApplicableReplyBoard(all_boardIDX);

        map.put("hh", replyBoard);
        System.out.println("map 2 : " + map);
     }
     // -------------------------------------------------------------------------------------
</code>```

Above that, the code is to reply to the post. (It's Reply. not comment)

```<code>HashMap<String, Object> result = bService.getBoardListPage(params, page-1);
</code>```

The above result contains information about the posts.

The log of result is shown below.

```<code>result : {current=1, last=1, start=1, end=10, boardList=[{phone_2=9959, comment_count=0, phone_1=010, board_idx=6, phone_3=7432, board_title=zzz, pw=1, sex=false, birth=1993-12-04, board_writer=test2, board_readNum=1, board_content=hhh, fileCount=0, board_writeDate=2017-12-07 18:44:44.0, authority=false, name=이, id=test2, idx=3, board_goodNum=0, email=rkdhfl1470@naver.com}
</code>```

I want to put information about the reply in the boardList that exists in result !

So, I got the boardList as below.

```<code>List<?> list = (List<?>) result.get("boardList");
</code>```

Then I turned around the for statement for the size of the list, and worked on the for statement as follows to include the reply information.

```<code>          for(int i = 0; i < list.size(); i++)
         {
            HashMap<String, Object> map = (HashMap<String, Object>) list.get(i);
            System.out.println("map 1 : " + map);
            int all_boardIDX = (Integer) map.get("board_idx");
            HashMap<String, Object> replyBoard = bService.boardApplicableReplyBoard(all_boardIDX);

            map.put("hh", replyBoard);
            System.out.println("map 2 : " + map);
         }
</code>```

As a result, it worked the way I wanted!

```<code>map 2 : {phone_2=9959, comment_count=0, hh={rb_title=[답글] Test, rb_writeDate=2017-12-07 15:38:03.0, board_idx=1, rb_idx=1, rb_writer=admin, rb_content=HH, rb_readNum=0, idx=1}
</code>```

But I'm not feeling well.

The reason is that, This is because in the code below, a warning such as "Type safety: Uncheckd cast from capture # 3-of? To HashMap " has occurred.

```<code>HashMap<String, Object> map = (HashMap<String, Object>) list.get(i);
</code>```

So I'm curious. Did I write the code correctly?

How can I improve my code?

And is not it right to cast the List type to a HashMap?

As a beginner I have a lot of questions. Please tell me your opinion.

Thank you for seeing the long sentence.

答:
And is not it right to cast the List type to a HashMap?

It's fine if you can guarantee it won't throw a java.lang.ClassCastException. You know exactly what objects are going into the lists/maps, so its fine.

OR

You can define your list like this:

List<HashMap<String, Object>>

Which I think will get rid of the warning. Then you don't have to cast it anymore either.

Type safety is really there to help you. Or others that need to maintain your code in the future. Using List<HashMap<String, Object>> you are telling the compiler that this List will always contain elements of HashMap<String, Object>. So you'll actually get compile-time errors if you attempt to treat the elements of your List as if they were objects of a different Class.

Whereas with List<?> you aren't telling the compiler anything that will allow it keep your code type-safe (ie. avoid throwing java.lang.ClassCastException). So if you screw up, you'll only see the errors at Runtime and only under a failure condition.

Hope that makes sense!

Body:
I will submit my code, explain it, and ask you questions.

The following code is part of the Controller code.

        HashMap<String, Object> result = bService.getBoardListPage(params, page-1);
     System.out.println("result : " + result);
     // Deriving the desired value among the List values ??existing in the HashMap -----------------------------------------
     List<?> list = (List<?>) result.get("boardList");

     for(int i = 0; i < list.size(); i++)
     {
        HashMap<String, Object> map = (HashMap<String, Object>) list.get(i);
        System.out.println("map 1 : " + map);
        int all_boardIDX = (Integer) map.get("board_idx");
        HashMap<String, Object> replyBoard = bService.boardApplicableReplyBoard(all_boardIDX);

        map.put("hh", replyBoard);
        System.out.println("map 2 : " + map);
     }
     // -------------------------------------------------------------------------------------

Above that, the code is to reply to the post. (It's Reply. not comment)

HashMap<String, Object> result = bService.getBoardListPage(params, page-1);

The above result contains information about the posts.

The log of result is shown below.

result : {current=1, last=1, start=1, end=10, boardList=[{phone_2=9959, comment_count=0, phone_1=010, board_idx=6, phone_3=7432, board_title=zzz, pw=1, sex=false, birth=1993-12-04, board_writer=test2, board_readNum=1, board_content=hhh, fileCount=0, board_writeDate=2017-12-07 18:44:44.0, authority=false, name=이, id=test2, idx=3, board_goodNum=0, email=rkdhfl1470@naver.com}

I want to put information about the reply in the boardList that exists in result !

So, I got the boardList as below.

List<?> list = (List<?>) result.get("boardList");

Then I turned around the for statement for the size of the list, and worked on the for statement as follows to include the reply information.

          for(int i = 0; i < list.size(); i++)
         {
            HashMap<String, Object> map = (HashMap<String, Object>) list.get(i);
            System.out.println("map 1 : " + map);
            int all_boardIDX = (Integer) map.get("board_idx");
            HashMap<String, Object> replyBoard = bService.boardApplicableReplyBoard(all_boardIDX);

            map.put("hh", replyBoard);
            System.out.println("map 2 : " + map);
         }

As a result, it worked the way I wanted!

map 2 : {phone_2=9959, comment_count=0, hh={rb_title=[답글] Test, rb_writeDate=2017-12-07 15:38:03.0, board_idx=1, rb_idx=1, rb_writer=admin, rb_content=HH, rb_readNum=0, idx=1}

But I'm not feeling well.

The reason is that, This is because in the code below, a warning such as "Type safety: Uncheckd cast from capture # 3-of? To HashMap " has occurred.

HashMap<String, Object> map = (HashMap<String, Object>) list.get(i);

So I'm curious. Did I write the code correctly?

How can I improve my code?

And is not it right to cast the List type to a HashMap?

As a beginner I have a lot of questions. Please tell me your opinion.

Thank you for seeing the long sentence.


问:
Can not get item of JSON-response
I am trying to create a AJAX call - and I would like to work with the response.

This is my response I see in my browser's network console:

```<code>{
    "message": "success",
    "file": "dump.xml"
}
</code>```

And this is what I want to do:

```<code>onComplete: function onComplete(data) {
            var vm = this;
            console.log(data.file);
            this.$set('upload', data);
            this.$set('filename', file);

            this.modal.show();
        }
</code>```

Okay. Well - I'm getting a response and if I write data to console.log, I'm getting this:

```<code>{"message":"success","file":"dump.xml"}
</code>```

But if I try to do:

```<code>console.log(data.file);
</code>```

I'm getting undefined. But why?

答:
Most probably your data will be a JSON string. You have parse it into an Object like below

```<code>onComplete: function onComplete(data) {
        data = JSON.parse(data)
        var vm = this;
        console.log(data.file);
        this.$set('upload', data);
        this.$set('filename', file);

        this.modal.show();
    }
</code>```

Title: Can not get item of JSON-response

Body:
I am trying to create a AJAX call - and I would like to work with the response.

This is my response I see in my browser's network console:

{
    "message": "success",
    "file": "dump.xml"
}

And this is what I want to do:

onComplete: function onComplete(data) {
            var vm = this;
            console.log(data.file);
            this.$set('upload', data);
            this.$set('filename', file);

            this.modal.show();
        }

Okay. Well - I'm getting a response and if I write data to console.log, I'm getting this:

{"message":"success","file":"dump.xml"}

But if I try to do:

console.log(data.file);

I'm getting undefined. But why?

Body:
Most probably your data will be a JSON string. You have parse it into an Object like below

onComplete: function onComplete(data) {
        data = JSON.parse(data)
        var vm = this;
        console.log(data.file);
        this.$set('upload', data);
        this.$set('filename', file);

        this.modal.show();
    }


问:
locking orientation does not work on ipad ios 8 swift xcode 6.2
I locked the app orientation to portrait from the general app setting like this

but still when i run my application on ipad, it rotates!?

so where should i lock the orientation ?

why apple added this feature to settings, while it is not working !?

UPDATE:

I tried to implement this viewController as the general for all the viewController as well.

```<code>import Foundation
import UIKit

class GeneralViewController: UIViewController {

    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        let value = UIInterfaceOrientation.Portrait.rawValue
        UIDevice.currentDevice().setValue(value, forKey: "orientation")
    }

    override func supportedInterfaceOrientations() -> Int {
        return Int(UIInterfaceOrientationMask.Portrait.rawValue)
    }

    override func preferredInterfaceOrientationForPresentation() -> UIInterfaceOrientation {
        return UIInterfaceOrientation.Portrait
    }

    override func shouldAutorotate() -> Bool {
        return false
    }
}
</code>```

this pic taken from the main navigationController of my app.

still did not work!

how on earth this thing works?

答:
This would be a comment added to Mohammed Elrashidy solution but I don't have the reputation to make comments. I am using XCode 9.1 and Swift 3.

My app requires some graphing screens to autorotate but all the other screens to remain fixed. My issue was that the "iPad" device configuration in General > Deployment Info was configured inconsistently with the iPhone and Universal devices. I had "Portrait", "Landscape Left" and "Landscape Right" checked for iPhone and Universal but all of the orientations checked for iPad (including "Upside Down"). Simply unchecking "Upside Down" caused the iPad device to honor the shouldAutorotate and supportedInterfaceOrientations calls in my Swift logic.

My Info.plist now looks like the following and I can programmatically turn autorotation on or off for the iPad.

```<code><key>UISupportedInterfaceOrientations</key>
<array>
    <string>UIInterfaceOrientationPortrait</string>
    <string>UIInterfaceOrientationLandscapeLeft</string>
    <string>UIInterfaceOrientationLandscapeRight</string>
</array>
<key>UISupportedInterfaceOrientations~ipad</key>
<array>
    <string>UIInterfaceOrientationPortrait</string>
    <string>UIInterfaceOrientationLandscapeLeft</string>
    <string>UIInterfaceOrientationLandscapeRight</string>
</array>
</code>```

Body:
I locked the app orientation to portrait from the general app setting like this

but still when i run my application on ipad, it rotates!?

so where should i lock the orientation ?

why apple added this feature to settings, while it is not working !?

UPDATE:

I tried to implement this viewController as the general for all the viewController as well.

import Foundation
import UIKit

class GeneralViewController: UIViewController {

    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        let value = UIInterfaceOrientation.Portrait.rawValue
        UIDevice.currentDevice().setValue(value, forKey: "orientation")
    }

    override func supportedInterfaceOrientations() -> Int {
        return Int(UIInterfaceOrientationMask.Portrait.rawValue)
    }

    override func preferredInterfaceOrientationForPresentation() -> UIInterfaceOrientation {
        return UIInterfaceOrientation.Portrait
    }

    override func shouldAutorotate() -> Bool {
        return false
    }
}

this pic taken from the main navigationController of my app.

still did not work!

how on earth this thing works?

Body:
This would be a comment added to Mohammed Elrashidy solution but I don't have the reputation to make comments. I am using XCode 9.1 and Swift 3.

My app requires some graphing screens to autorotate but all the other screens to remain fixed. My issue was that the "iPad" device configuration in General > Deployment Info was configured inconsistently with the iPhone and Universal devices. I had "Portrait", "Landscape Left" and "Landscape Right" checked for iPhone and Universal but all of the orientations checked for iPad (including "Upside Down"). Simply unchecking "Upside Down" caused the iPad device to honor the shouldAutorotate and supportedInterfaceOrientations calls in my Swift logic.

My Info.plist now looks like the following and I can programmatically turn autorotation on or off for the iPad.

<key>UISupportedInterfaceOrientations</key>
<array>
    <string>UIInterfaceOrientationPortrait</string>
    <string>UIInterfaceOrientationLandscapeLeft</string>
    <string>UIInterfaceOrientationLandscapeRight</string>
</array>
<key>UISupportedInterfaceOrientations~ipad</key>
<array>
    <string>UIInterfaceOrientationPortrait</string>
    <string>UIInterfaceOrientationLandscapeLeft</string>
    <string>UIInterfaceOrientationLandscapeRight</string>
</array>


答:
You are receiving it as a string. You have to parse it first to JSON by:

```<code>data = JSON.parse(data);
console.log( data.file )
</code>```

OTHER OPTION: Or you can define it on request, add dataType: "json" so that you will receive json.

Like:

```<code>   $.ajax(
   {

      type: "POST",
      dataType: "json",
      url: url,
      data: {},
      success: function( response ) {}
  }
</code>```

Title: Can not get item of JSON-response

Body:
You are receiving it as a string. You have to parse it first to JSON by:

data = JSON.parse(data);
console.log( data.file )

OTHER OPTION: Or you can define it on request, add dataType: "json" so that you will receive json.

Like:

   $.ajax(
   {

      type: "POST",
      dataType: "json",
      url: url,
      data: {},
      success: function( response ) {}
  }


问:
Converting code in Java 8 streams
Is there any easy way to convert this code into java 8 using streams and forEach.

```<code>List<List<IStitchable>> listOfEnvelopes = new ArrayList<>();
List<IStitchable> statementsInEnvelope = new ArrayList<>();
int totalPages = 0;

for(byte[] byteArray :byteArrays){
    totalPages = totalPages + getPagesInDocument(byteArray);

    if(totalPages/2>MAX_SHEETS_FOR_OVERSIZE_ENVELOPE){
        totalPages = 0;
        listOfEnvelopes.add(statementsInEnvelope);
        tatementsInEnvelope = new ArrayList<IStitchable>();
    }

    statementsInEnvelope.add(createStitchableFromSnapshot(byteArray));
}
</code>```

I tried to do something like

```<code>byteArrays.stream().forEach(byteArray->{
    totalPages = totalPages + getPagesInDocument(byteArray);
    if(totalPages/2>MAX_SHEETS_FOR_OVERSIZE_ENVELOPE){
        totalPages = 0;
        listOfEnvelopes.add(statementsInEnvelope);
        statementsInEnvelope = new ArrayList<IStitchable>();
    }
    statementsInEnvelope.add(createStitchableFromSnapshot(byteArray));
});
</code>```

but then I cannot use totalPages and statementsInEnvelope within ForEach,
they cannot be accessed from the forEach scope

Lastly is there any cleaner way to refactor this thing. Any ideas would be appreciated.

答:
The simplest solution is to use AtomicInteger:

```<code>List<List<IStitchable>> listOfEnvelopes = new ArrayList<>();
List<IStitchable> statementsInEnvelope = new ArrayList<>();
AtomicInteger totalPages = new AtomicInteger();

byteArrays.stream().forEach(byteArray -> {
  totalPages.addAndGet(getPagesInDocument(byteArray));

  if(totalPages.get() / 2 > MAX_SHEETS_FOR_OVERSIZE_ENVELOPE){
    totalPages.set(0);
    listOfEnvelopes.add(new ArrayList<>(statementsInEnvelope));
    statementsInEnvelope.clear();
  }
  statementsInEnvelope.add(createStitchableFromSnapshot(byteArray));
});
</code>```

Title: Converting code in Java 8 streams

Body:
Is there any easy way to convert this code into java 8 using streams and forEach.

List<List<IStitchable>> listOfEnvelopes = new ArrayList<>();
List<IStitchable> statementsInEnvelope = new ArrayList<>();
int totalPages = 0;

for(byte[] byteArray :byteArrays){
    totalPages = totalPages + getPagesInDocument(byteArray);

    if(totalPages/2>MAX_SHEETS_FOR_OVERSIZE_ENVELOPE){
        totalPages = 0;
        listOfEnvelopes.add(statementsInEnvelope);
        tatementsInEnvelope = new ArrayList<IStitchable>();
    }

    statementsInEnvelope.add(createStitchableFromSnapshot(byteArray));
}

I tried to do something like

byteArrays.stream().forEach(byteArray->{
    totalPages = totalPages + getPagesInDocument(byteArray);
    if(totalPages/2>MAX_SHEETS_FOR_OVERSIZE_ENVELOPE){
        totalPages = 0;
        listOfEnvelopes.add(statementsInEnvelope);
        statementsInEnvelope = new ArrayList<IStitchable>();
    }
    statementsInEnvelope.add(createStitchableFromSnapshot(byteArray));
});

but then I cannot use totalPages and statementsInEnvelope within ForEach,
they cannot be accessed from the forEach scope

Lastly is there any cleaner way to refactor this thing. Any ideas would be appreciated.

Body:
The simplest solution is to use AtomicInteger:

List<List<IStitchable>> listOfEnvelopes = new ArrayList<>();
List<IStitchable> statementsInEnvelope = new ArrayList<>();
AtomicInteger totalPages = new AtomicInteger();

byteArrays.stream().forEach(byteArray -> {
  totalPages.addAndGet(getPagesInDocument(byteArray));

  if(totalPages.get() / 2 > MAX_SHEETS_FOR_OVERSIZE_ENVELOPE){
    totalPages.set(0);
    listOfEnvelopes.add(new ArrayList<>(statementsInEnvelope));
    statementsInEnvelope.clear();
  }
  statementsInEnvelope.add(createStitchableFromSnapshot(byteArray));
});


问:
Combine two simple SQL queries two one query
I have two queries and I want to combine them into one query

1st query: this query finds the average for each student in each subject:

```<code>SELECT
    StudentFirstName, StudentLastName, ClassName,
    AVG(Grade) AS 'average for this subject'
FROM tests
INNER JOIN students ON tests.StudentID = students.StudentID
GROUP BY StudentFirstName, StudentLastName, ClassName;
</code>```

2nd query: this query finds the average for each student his total average for whole his final grades:

```<code>SELECT
    StudentFirstName, StudentLastName, AVG(average) AS total_average
FROM
    (SELECT
         StudentFirstName, StudentLastName, AVG(Grade) AS average
     FROM
         tests
     INNER JOIN
         students ON tests.StudentID = students.StudentID
     GROUP BY
         StudentFirstName, StudentLastName, ClassName) AS t
GROUP BY
    StudentFirstName, StudentLastName;
</code>```

For example: the  grades of me(aka Error404) are:

Algebra: first exam: 99, second exam: 97, third exam: 96 ---> 1st query gives Average: 97.3333 for this subject

Machine-learning: first exam: 95, second exam: 94 ---> 1st query gives Average: 94.5 for this subject

2nd query returns total average of AVG(97.3333,94.5)=95.91665 for student named error404

Table 1 - Students:

```<code>      pk-INT           VARCHAR             VARCHAR
    +-----------+------------------+-----------------+
    | StudentID | StudentFirstName | StudentLastName |
    +-----------+------------------+-----------------+
    |         1 | agam             | rafaeli         |
    |         2 | amir             | aizinger        |
    |         3 | avi              | caspi           |
    |         4 | avia             | wolf            |
    +-----------+------------------+-----------------+
</code>```

Table 2 - Tests:

```<code> PK-VARCHR    PK-VARCHR     PK&FK-INT   INT
+------------+------------+-----------+-------+
| TestDate   | ClassName  | StudentID | Grade |
+------------+------------+-----------+-------+
| 2017-07-01 | Algebra    |         1 |    88 |
| 2017-08-02 | Algo       |         1 |    97 |
| 2017-09-01 | Algebra    |         1 |    80 |
| 2017-09-01 | Algebra    |         1 |    97 |
| 2017-09-01 | Set-theory |         1 |    85 |
| 2017-09-04 | Calcules   |         1 |    86 |
| 2016-05-03 | Set-theory |         2 |    84 |
| 2016-07-02 | Calcules   |         2 |    89 |
| 2016-07-04 | Algo       |         2 |    83 |
| 2016-07-05 | Algebra    |         2 |    79 |
| 2016-06-03 | Algebra    |         3 |    99 |
| 2016-07-02 | Algo       |         3 |    97 |
| 2016-07-03 | Calcules   |         3 |    96 |
| 2016-09-03 | Set-theory |         3 |    95 |
| 2016-06-03 | Algebra    |         4 |    78 |
+------------+------------+-----------+-------+
</code>```

Sample data:

```<code>DROP DATABASE IF EXISTS error404;
CREATE DATABASE error404;

USE error404

CREATE TABLE students
(
    StudentID        INT NOT NULL AUTO_INCREMENT,
    StudentFirstName VARCHAR(25),
    StudentLastName  VARCHAR(25),
    PRIMARY KEY (StudentID)
);

INSERT INTO students (StudentFirstName, StudentLastName)
VALUES ('agam', 'rafaeli'), ('amir', 'aizinger'), ('avi', 'caspi'),
       ('avia', 'wolf ');

CREATE TABLE tests
(
    testid    INT NOT NULL AUTO_INCREMENT,
    TestDate  DATE,
    ClassName VARCHAR(25),
    StudentID INT NOT NULL,
    Grade     INT NOT NULL,
    PRIMARY KEY (testid),
    KEY (StudentID)
);

INSERT INTO tests (TestDate, ClassName, StudentID, Grade)
VALUES ('2017-07-01', 'Algebra', 1, 88),
       ('2017-08-02', 'Algo', 1, 97),
       ('2017-09-01', 'Algebra', 1, 80),
       ('2017-09-01', 'Algebra', 1, 97),
       ('2017-09-01', 'Set-theory', 1, 85),
       ('2017-09-04', 'Calculus', 1, 86),
       ('2016-05-03', 'Set-theory', 2, 84),
       ('2016-07-02', 'Calculus', 2, 89),
       ('2016-07-04', 'Algo', 2, 83),
       ('2016-07-05', 'Algebra', 2, 79),
       ('2016-06-03', 'Algebra', 3, 99),
       ('2016-07-02', 'Algo', 3, 97),
       ('2016-07-03', 'Calculus', 3, 96),
       ('2016-09-03', 'Set-theory', 3, 95),
       ('2016-06-03', 'Algebra', 4, 78);
</code>```

I want this result:

```<code>+--------------+--------------+--------------+--------------+--------------+
| StFirstName  | StLastName   | ClassName    | aveInSubject | totalAve     |
+--------------+--------------+--------------+--------------+--------------+
| name1        | lname1       | algebra      |  80          |  87          |
| name1        | lname1       | algo         |  88          |  87          |
| name1        | lname1       | calcul       |  93          |  87          |
| name2        | lname2       | algebra      |  70          |  74.3        |
| name2        | lname2       | algo         |  76          |  74.3        |
| name2        | lname2       | calcul       |  77          |  74.3        |
+--------------+--------------+--------------+--------------+--------------+
</code>```

答:
You can join the result of per subject average and total average per student.

```<code>SELECT t1.*,t2.totalAvg
FROM (SELECT StudentFirstName,StudentLastName,ClassName,AVG(Grade) AS `average for this subject`
      FROM tests
      INNER JOIN students ON tests.StudentID=students.StudentID
      GROUP BY StudentFirstName,StudentLastName,ClassName
     ) t1
JOIN (SELECT StudentFirstName,StudentLastName,AVG(`average for this subject`) as totalAvg
      FROM (SELECT StudentFirstName,StudentLastName,ClassName,AVG(Grade) AS `average for this subject`
            FROM tests
            INNER JOIN students ON tests.StudentID=students.StudentID
            GROUP BY StudentFirstName,StudentLastName,ClassName
           ) t
      GROUP BY StudentFirstName,StudentLastName
     ) t2
ON t1.StudentFirstName=t2.StudentFirstName and t1.StudentLastName=t2.StudentLastName
</code>```

EDIT: For future versions of MySQL (starting version 8.0) with window functions, the query could be simplified to

```<code>select studentfirstname,studentlastname,classname,avgPerSubject
,sum(avgPerSubject) over w/count(*) over w as totalAvg
from (select distinct
      s.studentfirstname,s.studentlastname,t.classname,
      avg(t.grade) over(partition by s.studentfirstname,s.studentlastname,t.classname) as avgPerSubject
      from tests t
      join students s on s.studentid=t.studentid
     ) t
window w as (partition by studentfirstname,studentlastname)
</code>```

Body:
I have two queries and I want to combine them into one query

1st query: this query finds the average for each student in each subject:

SELECT
    StudentFirstName, StudentLastName, ClassName,
    AVG(Grade) AS 'average for this subject'
FROM tests
INNER JOIN students ON tests.StudentID = students.StudentID
GROUP BY StudentFirstName, StudentLastName, ClassName;

2nd query: this query finds the average for each student his total average for whole his final grades:

SELECT
    StudentFirstName, StudentLastName, AVG(average) AS total_average
FROM
    (SELECT
         StudentFirstName, StudentLastName, AVG(Grade) AS average
     FROM
         tests
     INNER JOIN
         students ON tests.StudentID = students.StudentID
     GROUP BY
         StudentFirstName, StudentLastName, ClassName) AS t
GROUP BY
    StudentFirstName, StudentLastName;

For example: the  grades of me(aka Error404) are:

Algebra: first exam: 99, second exam: 97, third exam: 96 ---> 1st query gives Average: 97.3333 for this subject

Machine-learning: first exam: 95, second exam: 94 ---> 1st query gives Average: 94.5 for this subject

2nd query returns total average of AVG(97.3333,94.5)=95.91665 for student named error404

Table 1 - Students:

      pk-INT           VARCHAR             VARCHAR
    +-----------+------------------+-----------------+
    | StudentID | StudentFirstName | StudentLastName |
    +-----------+------------------+-----------------+
    |         1 | agam             | rafaeli         |
    |         2 | amir             | aizinger        |
    |         3 | avi              | caspi           |
    |         4 | avia             | wolf            |
    +-----------+------------------+-----------------+

Table 2 - Tests:

 PK-VARCHR    PK-VARCHR     PK&FK-INT   INT
+------------+------------+-----------+-------+
| TestDate   | ClassName  | StudentID | Grade |
+------------+------------+-----------+-------+
| 2017-07-01 | Algebra    |         1 |    88 |
| 2017-08-02 | Algo       |         1 |    97 |
| 2017-09-01 | Algebra    |         1 |    80 |
| 2017-09-01 | Algebra    |         1 |    97 |
| 2017-09-01 | Set-theory |         1 |    85 |
| 2017-09-04 | Calcules   |         1 |    86 |
| 2016-05-03 | Set-theory |         2 |    84 |
| 2016-07-02 | Calcules   |         2 |    89 |
| 2016-07-04 | Algo       |         2 |    83 |
| 2016-07-05 | Algebra    |         2 |    79 |
| 2016-06-03 | Algebra    |         3 |    99 |
| 2016-07-02 | Algo       |         3 |    97 |
| 2016-07-03 | Calcules   |         3 |    96 |
| 2016-09-03 | Set-theory |         3 |    95 |
| 2016-06-03 | Algebra    |         4 |    78 |
+------------+------------+-----------+-------+

Sample data:

DROP DATABASE IF EXISTS error404;
CREATE DATABASE error404;

USE error404

CREATE TABLE students
(
    StudentID        INT NOT NULL AUTO_INCREMENT,
    StudentFirstName VARCHAR(25),
    StudentLastName  VARCHAR(25),
    PRIMARY KEY (StudentID)
);

INSERT INTO students (StudentFirstName, StudentLastName)
VALUES ('agam', 'rafaeli'), ('amir', 'aizinger'), ('avi', 'caspi'),
       ('avia', 'wolf ');

CREATE TABLE tests
(
    testid    INT NOT NULL AUTO_INCREMENT,
    TestDate  DATE,
    ClassName VARCHAR(25),
    StudentID INT NOT NULL,
    Grade     INT NOT NULL,
    PRIMARY KEY (testid),
    KEY (StudentID)
);

INSERT INTO tests (TestDate, ClassName, StudentID, Grade)
VALUES ('2017-07-01', 'Algebra', 1, 88),
       ('2017-08-02', 'Algo', 1, 97),
       ('2017-09-01', 'Algebra', 1, 80),
       ('2017-09-01', 'Algebra', 1, 97),
       ('2017-09-01', 'Set-theory', 1, 85),
       ('2017-09-04', 'Calculus', 1, 86),
       ('2016-05-03', 'Set-theory', 2, 84),
       ('2016-07-02', 'Calculus', 2, 89),
       ('2016-07-04', 'Algo', 2, 83),
       ('2016-07-05', 'Algebra', 2, 79),
       ('2016-06-03', 'Algebra', 3, 99),
       ('2016-07-02', 'Algo', 3, 97),
       ('2016-07-03', 'Calculus', 3, 96),
       ('2016-09-03', 'Set-theory', 3, 95),
       ('2016-06-03', 'Algebra', 4, 78);

I want this result:

+--------------+--------------+--------------+--------------+--------------+
| StFirstName  | StLastName   | ClassName    | aveInSubject | totalAve     |
+--------------+--------------+--------------+--------------+--------------+
| name1        | lname1       | algebra      |  80          |  87          |
| name1        | lname1       | algo         |  88          |  87          |
| name1        | lname1       | calcul       |  93          |  87          |
| name2        | lname2       | algebra      |  70          |  74.3        |
| name2        | lname2       | algo         |  76          |  74.3        |
| name2        | lname2       | calcul       |  77          |  74.3        |
+--------------+--------------+--------------+--------------+--------------+

Body:
You can join the result of per subject average and total average per student.

SELECT t1.*,t2.totalAvg
FROM (SELECT StudentFirstName,StudentLastName,ClassName,AVG(Grade) AS `average for this subject`
      FROM tests
      INNER JOIN students ON tests.StudentID=students.StudentID
      GROUP BY StudentFirstName,StudentLastName,ClassName
     ) t1
JOIN (SELECT StudentFirstName,StudentLastName,AVG(`average for this subject`) as totalAvg
      FROM (SELECT StudentFirstName,StudentLastName,ClassName,AVG(Grade) AS `average for this subject`
            FROM tests
            INNER JOIN students ON tests.StudentID=students.StudentID
            GROUP BY StudentFirstName,StudentLastName,ClassName
           ) t
      GROUP BY StudentFirstName,StudentLastName
     ) t2
ON t1.StudentFirstName=t2.StudentFirstName and t1.StudentLastName=t2.StudentLastName

EDIT: For future versions of MySQL (starting version 8.0) with window functions, the query could be simplified to

select studentfirstname,studentlastname,classname,avgPerSubject
,sum(avgPerSubject) over w/count(*) over w as totalAvg
from (select distinct
      s.studentfirstname,s.studentlastname,t.classname,
      avg(t.grade) over(partition by s.studentfirstname,s.studentlastname,t.classname) as avgPerSubject
      from tests t
      join students s on s.studentid=t.studentid
     ) t
window w as (partition by studentfirstname,studentlastname)


问:
FATAL EXCEPTION: AsyncTask #1:java.lang.RuntimeException: An error occured while executing doInBackground()
I'm trying to translate a language to another language with Microsoft Text Translator API. I already have this working on java, but when I ported it to Android. It gives me this error. It seems to be pointing me out to IOUtils but I think i already added that prerequisite in the Project Structure. Is there anyway to not use the IOUtils though?. Like OutputStream?. It seems that IOUtils is the problem, but IDK. I can't understand the logcat error. :/

my logcat is here:

```<code>E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
                  java.lang.RuntimeException: An error occured while executing doInBackground()
                      at android.os.AsyncTask$3.done(AsyncTask.java:299)
                      at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
                      at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
                      at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
                      at java.util.concurrent.FutureTask.run(FutureTask.java:137)
                      at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
                      at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
                      at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
                      at java.lang.Thread.run(Thread.java:856)
                   Caused by: java.lang.ExceptionInInitializerError
                      at org.apache.commons.io.IOUtils.write(IOUtils.java:2049)
                      at com.example.joshu.translatorownimplementation.MainActivity.translate(MainActivity.java:101)
                      at com.example.joshu.translatorownimplementation.MainActivity$LongOperation.doInBackground(MainActivity.java:70)
                      at com.example.joshu.translatorownimplementation.MainActivity$LongOperation.doInBackground(MainActivity.java:55)
                      at android.os.AsyncTask$2.call(AsyncTask.java:287)
                      at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
                      at java.util.concurrent.FutureTask.run(FutureTask.java:137)
                      at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
                      at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
                      at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
                      at java.lang.Thread.run(Thread.java:856)
                   Caused by: java.lang.NoClassDefFoundError: java.nio.charset.StandardCharsets
                      at org.apache.commons.io.Charsets.<clinit>(Charsets.java:120)
                      at org.apache.commons.io.IOUtils.write(IOUtils.java:2049)
                      at com.example.joshu.translatorownimplementation.MainActivity.translate(MainActivity.java:101)
                      at com.example.joshu.translatorownimplementation.MainActivity$LongOperation.doInBackground(MainActivity.java:70)
                      at com.example.joshu.translatorownimplementation.MainActivity$LongOperation.doInBackground(MainActivity.java:55)
                      at android.os.AsyncTask$2.call(AsyncTask.java:287)
                      at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
                      at java.util.concurrent.FutureTask.run(FutureTask.java:137)
                      at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
                      at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
                      at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
                      at java.lang.Thread.run(Thread.java:856)
</code>```

Here is my Code:

```<code>import org.apache.commons.io.IOUtils;

import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import javax.net.ssl.HttpsURLConnection;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MSTranslateAPI {

   private static String output;

    private static String key = "<MS KEY for Translator API>";

  public static void main(String[] args) throws Exception {
    // TODO: Specify your translation requirements here:
    String fromLang = "en";
    String toLang = "ko";
    String text = "Hello Friend";

    MSTranslateAPI.translate(fromLang, toLang, text);

  }

  public static void translate(String fromLang, String toLang, String text) throws Exception {

     String authenticationUrl = "https://api.cognitive.microsoft.com/sts/v1.0/issueToken";
    HttpsURLConnection authConn = (HttpsURLConnection) new URL(authenticationUrl).openConnection();
    authConn.setDoOutput(true);
    authConn.setRequestMethod("POST");
    authConn.setRequestProperty("Ocp-Apim-Subscription-Key", key);
    IOUtils.write("", authConn.getOutputStream(), "UTF-8");
    String token = IOUtils.toString(authConn.getInputStream(), "UTF-8");
    authConn.disconnect();

    System.out.println("TOKEN: "+token);

    if(authConn.getResponseCode()==200) {
         String appId = URLEncoder.encode("Bearer " + token, "UTF-8");
    String text2 = URLEncoder.encode(text, "UTF-8");
    String from = fromLang;
    String to = toLang;
    String translatorTextApiUrl ="https://api.microsofttranslator.com/v2/http.svc/GetTranslations?appid="+appId+"&text="+text2+"&from="+from+"&to="+to+"&maxTranslations=5";

    HttpsURLConnection translateConn = (HttpsURLConnection) new URL(translatorTextApiUrl).openConnection();
    translateConn.setRequestMethod("POST");
    translateConn.setDoOutput(true);
    IOUtils.write("", translateConn.getOutputStream(), "UTF-8");
    String resp = IOUtils.toString(translateConn.getInputStream(), "UTF-8");
    translateConn.disconnect();
    System.out.println(resp+"\n\n");
    }
    else    {

    }

  }

}
</code>```

答: The stacktrace in the logcat message indicates the StandardCharsets class is not available. According to https://developer.android.com/reference/java/nio/charset/StandardCharsets.html, the class is in the android JDK, but requires API version 19 or higher. You could upgrade the android version you target if you want to keep your use of IOUtils.</p>

Body:
I'm trying to translate a language to another language with Microsoft Text Translator API. I already have this working on java, but when I ported it to Android. It gives me this error. It seems to be pointing me out to IOUtils but I think i already added that prerequisite in the Project Structure. Is there anyway to not use the IOUtils though?. Like OutputStream?. It seems that IOUtils is the problem, but IDK. I can't understand the logcat error. :/

my logcat is here:

E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
                  java.lang.RuntimeException: An error occured while executing doInBackground()
                      at android.os.AsyncTask$3.done(AsyncTask.java:299)
                      at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
                      at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
                      at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
                      at java.util.concurrent.FutureTask.run(FutureTask.java:137)
                      at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
                      at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
                      at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
                      at java.lang.Thread.run(Thread.java:856)
                   Caused by: java.lang.ExceptionInInitializerError
                      at org.apache.commons.io.IOUtils.write(IOUtils.java:2049)
                      at com.example.joshu.translatorownimplementation.MainActivity.translate(MainActivity.java:101)
                      at com.example.joshu.translatorownimplementation.MainActivity$LongOperation.doInBackground(MainActivity.java:70)
                      at com.example.joshu.translatorownimplementation.MainActivity$LongOperation.doInBackground(MainActivity.java:55)
                      at android.os.AsyncTask$2.call(AsyncTask.java:287)
                      at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
                      at java.util.concurrent.FutureTask.run(FutureTask.java:137)
                      at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
                      at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
                      at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
                      at java.lang.Thread.run(Thread.java:856)
                   Caused by: java.lang.NoClassDefFoundError: java.nio.charset.StandardCharsets
                      at org.apache.commons.io.Charsets.<clinit>(Charsets.java:120)
                      at org.apache.commons.io.IOUtils.write(IOUtils.java:2049)
                      at com.example.joshu.translatorownimplementation.MainActivity.translate(MainActivity.java:101)
                      at com.example.joshu.translatorownimplementation.MainActivity$LongOperation.doInBackground(MainActivity.java:70)
                      at com.example.joshu.translatorownimplementation.MainActivity$LongOperation.doInBackground(MainActivity.java:55)
                      at android.os.AsyncTask$2.call(AsyncTask.java:287)
                      at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
                      at java.util.concurrent.FutureTask.run(FutureTask.java:137)
                      at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
                      at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
                      at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
                      at java.lang.Thread.run(Thread.java:856)

Here is my Code:

import org.apache.commons.io.IOUtils;

import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import javax.net.ssl.HttpsURLConnection;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MSTranslateAPI {

   private static String output;

    private static String key = "<MS KEY for Translator API>";

  public static void main(String[] args) throws Exception {
    // TODO: Specify your translation requirements here:
    String fromLang = "en";
    String toLang = "ko";
    String text = "Hello Friend";

    MSTranslateAPI.translate(fromLang, toLang, text);

  }

  public static void translate(String fromLang, String toLang, String text) throws Exception {

     String authenticationUrl = "https://api.cognitive.microsoft.com/sts/v1.0/issueToken";
    HttpsURLConnection authConn = (HttpsURLConnection) new URL(authenticationUrl).openConnection();
    authConn.setDoOutput(true);
    authConn.setRequestMethod("POST");
    authConn.setRequestProperty("Ocp-Apim-Subscription-Key", key);
    IOUtils.write("", authConn.getOutputStream(), "UTF-8");
    String token = IOUtils.toString(authConn.getInputStream(), "UTF-8");
    authConn.disconnect();

    System.out.println("TOKEN: "+token);

    if(authConn.getResponseCode()==200) {
         String appId = URLEncoder.encode("Bearer " + token, "UTF-8");
    String text2 = URLEncoder.encode(text, "UTF-8");
    String from = fromLang;
    String to = toLang;
    String translatorTextApiUrl ="https://api.microsofttranslator.com/v2/http.svc/GetTranslations?appid="+appId+"&text="+text2+"&from="+from+"&to="+to+"&maxTranslations=5";

    HttpsURLConnection translateConn = (HttpsURLConnection) new URL(translatorTextApiUrl).openConnection();
    translateConn.setRequestMethod("POST");
    translateConn.setDoOutput(true);
    IOUtils.write("", translateConn.getOutputStream(), "UTF-8");
    String resp = IOUtils.toString(translateConn.getInputStream(), "UTF-8");
    translateConn.disconnect();
    System.out.println(resp+"\n\n");
    }
    else    {

    }

  }

}


问:
Exposing multiple ports of container on kubernetes
I am trying to run my custom marklogic image on my local minkube cluster. Marklogic exposes multiple different ports for management (8001) and for querying (8000). Is there a way to expose multiple ports of a container on kubernetes?

This is what I tried:

```<code># try to run container with multiple ports exposed.
kubectl run ml3 --image=marklogic-initial-install:9.0-3.1 --port=8001 --port 8002
# create service to expose the container
kubectl expose deployment ml3 --type=LoadBalancer
# use qinikube to open the exposed ports
minikube service ml3
</code>```

Is this possible at all?

This section in the kubernetes docs suggests that it is indeed possible:

https://kubernetes.io/docs/concepts/services-networking/service/#multi-port-services

But it only talks about how to configure services to expose multiple ports, it does not say how to achieve this for containers -- which should be a prerequisite.

Thanks!

答:
From what I see in your command, you would need to specify in kubectl expose which of the two ports this service will work with. If there are two ports that perform different operations, then it makes sense to have two services (otherwise you would not know which of the two ports would be used in each request). So, my advice would be to execute two kubectl expose commands (in the --port part you can put whatever you wish):

```<code>kubectl expose deployment ml3 --type=LoadBalancer --name=management --port=80 --target-port=8000
kubectl expose deployment ml3 --type=LoadBalancer --name=query --port=80 --target-port=8001
</code>```

So, you would have one service for querying and another for management.

Another alternative would be using one service with two different ports, but I am not sure if this is doable using kubectl expose. It would make sense in this case to use a yaml file:

```<code>kind: Service
apiVersion: v1
metadata:
  name: my-service
spec:
  selector:
    app: MyApp <-- use a proper selector for your pods
  ports:
  - name: management
    protocol: TCP
    port: 80
    targetPort: 8000
  - name: query
    protocol: TCP
    port: 81
    targetPort: 8001
</code>```

Body:
I am trying to run my custom marklogic image on my local minkube cluster. Marklogic exposes multiple different ports for management (8001) and for querying (8000). Is there a way to expose multiple ports of a container on kubernetes?

This is what I tried:

# try to run container with multiple ports exposed.
kubectl run ml3 --image=marklogic-initial-install:9.0-3.1 --port=8001 --port 8002
# create service to expose the container
kubectl expose deployment ml3 --type=LoadBalancer
# use qinikube to open the exposed ports
minikube service ml3

Is this possible at all?

This section in the kubernetes docs suggests that it is indeed possible:

https://kubernetes.io/docs/concepts/services-networking/service/#multi-port-services

But it only talks about how to configure services to expose multiple ports, it does not say how to achieve this for containers -- which should be a prerequisite.

Thanks!

Body:
From what I see in your command, you would need to specify in kubectl expose which of the two ports this service will work with. If there are two ports that perform different operations, then it makes sense to have two services (otherwise you would not know which of the two ports would be used in each request). So, my advice would be to execute two kubectl expose commands (in the --port part you can put whatever you wish):

kubectl expose deployment ml3 --type=LoadBalancer --name=management --port=80 --target-port=8000
kubectl expose deployment ml3 --type=LoadBalancer --name=query --port=80 --target-port=8001

So, you would have one service for querying and another for management.

Another alternative would be using one service with two different ports, but I am not sure if this is doable using kubectl expose. It would make sense in this case to use a yaml file:

kind: Service
apiVersion: v1
metadata:
  name: my-service
spec:
  selector:
    app: MyApp <-- use a proper selector for your pods
  ports:
  - name: management
    protocol: TCP
    port: 80
    targetPort: 8000
  - name: query
    protocol: TCP
    port: 81
    targetPort: 8001


答:
I think the problem is that data is a JSON string, so it will be printed in console, but when you call data.file it will be undefined. as string doesn't have a file property.

You need to parse your data object, before accessing file property:

```<code>data = JSON.parse(data);
console.log(data.file);
</code>```

Title: Can not get item of JSON-response

Body:
I think the problem is that data is a JSON string, so it will be printed in console, but when you call data.file it will be undefined. as string doesn't have a file property.

You need to parse your data object, before accessing file property:

data = JSON.parse(data);
console.log(data.file);


问:
Two associations between same tables with Ruby On Rails
I have an app with Two Models Stadium & Team, they have a many-to-many relationship and are joined in the middle by a join table.

My current structure looks like this:

```<code>class Team < ActiveRecord::Base
    has_many :stadiumteams, :class_name => 'StadiumTeam'
    has_many :stadiums, :through => :stadiumteams
end

class Stadium < ActiveRecord::Base
    has_many :stadiumteams, :class_name => 'StadiumTeam'
    has_many :teams, :through => :stadiumteams
end

class StadiumTeam < ActiveRecord::Base
    belongs_to :stadium
    belongs_to :team
end
</code>```

This relationship show “current residents for a stadium”. But now I also want to have a relationship that can display old residents.

For example Tottenham (Team) used to play at White Hart Lane (Stadium) But now play at (Wembley) Stadium.

I am planning to do the following. But I am unsure if this will work or if there is a better way to do it?

Team

```<code>class Team < ActiveRecord::Base
    has_many :stadiumteams, :class_name => 'StadiumTeam'
    has_many :stadiums, :through => :stadiumteams

    #has_many :oldstadiums, :class_name => 'OldStadium'
    #has_many :stadiums, :through => :oldstadiums
end
</code>```

Stadium

```<code>class Stadium < ActiveRecord::Base

    has_many :stadiumteams, :class_name => 'StadiumTeam'
    has_many :teams, :through => :stadiumteams

    #has_many :oldstadiums, :class_name => 'OldStadium'
    #has_many :teams, :through => :oldstadiums
end
</code>```

New Join Table

```<code>class OldStadium < ActiveRecord::Base
    belongs_to :stadium
    belongs_to :team
end
</code>```

Any help is very appreciated!

EDIT: (Input fields)
Here's how the code for my inputs currently looks:

```<code><%= f.association :teams, label: 'Current Residents', class:'select2-field', placeholder: "Select teams", collection: @teams, input_html: { multiple: true }, hint: 'Select one or multiple teams.'%>

<%= f.association :teams, label: 'Old Residents', class:'select2-field', placeholder: "Select teams", collection: @teams, input_html: { multiple: true }, hint: 'Select one or multiple teams.' %>
</code>```

And my params

```<code>   def stadium_params
      params.require(:stadium).permit(:name, :capacity, :city, :country, :location_name, :address, :longitude, :latitude, :image, :surface, :official_opening_date, :cost, :web_url, :also_known_as, :record_attendance, :team_ids => [])
    end
</code>```

答:
You can define relations with a lambda to append an additional where clause in the relation:

```<code>class Team < ActiveRecord::Base
    has_many :stadiumteams, :class_name => 'StadiumTeam'

    has_many stadiums, :through => :stadiumteams
    has_many :current_stadiums, ->{ where(stadiumteams: { current_home: true }) }, :through => :stadiumteams, :class_name => 'Stadium', :source => :stadium
    has_many :previous_stadiums, ->{ where(stadiumteams: { current_home: false }) }, :through => :stadiumteams, :class_name =>'Stadium', :source => :stadium
end

class Stadium < ActiveRecord::Base
    has_many :stadiumteams, :class_name => 'StadiumTeam'

    has_many :teams, :through => :stadiumteams
    has_many :current_teams, ->{ where(stadiumteams: { current_home: true }) }, :through => :stadiumteams, :class_name => 'Team', :source => :team
    has_many :previous_teams, ->{ where(stadiumteams: { current_home: false }) }, :through => :stadiumteams, :class_name =>'Team'. :source => :team
end

class StadiumTeam < ActiveRecord::Base
    belongs_to :stadium
    belongs_to :team
end
</code>```

And then you should be able to do (in rails console):

```<code>team = Team.first
stadium = Stadium.first
team.previous_stadiums <<
team.save
team.reload.previous_stadiums.include?(stadium)
# => should return true
</code>```

So this way you can simply use in your UI a input for the association :previous_teams and :current_teams:

```<code>f.association :current_teams, #...
</code>```

Body:
I have an app with Two Models Stadium & Team, they have a many-to-many relationship and are joined in the middle by a join table.

My current structure looks like this:

class Team < ActiveRecord::Base
    has_many :stadiumteams, :class_name => 'StadiumTeam'
    has_many :stadiums, :through => :stadiumteams
end

class Stadium < ActiveRecord::Base
    has_many :stadiumteams, :class_name => 'StadiumTeam'
    has_many :teams, :through => :stadiumteams
end

class StadiumTeam < ActiveRecord::Base
    belongs_to :stadium
    belongs_to :team
end

This relationship show “current residents for a stadium”. But now I also want to have a relationship that can display old residents.

For example Tottenham (Team) used to play at White Hart Lane (Stadium) But now play at (Wembley) Stadium.

I am planning to do the following. But I am unsure if this will work or if there is a better way to do it?

Team

class Team < ActiveRecord::Base
    has_many :stadiumteams, :class_name => 'StadiumTeam'
    has_many :stadiums, :through => :stadiumteams

    #has_many :oldstadiums, :class_name => 'OldStadium'
    #has_many :stadiums, :through => :oldstadiums
end

Stadium

class Stadium < ActiveRecord::Base

    has_many :stadiumteams, :class_name => 'StadiumTeam'
    has_many :teams, :through => :stadiumteams

    #has_many :oldstadiums, :class_name => 'OldStadium'
    #has_many :teams, :through => :oldstadiums
end

New Join Table

class OldStadium < ActiveRecord::Base
    belongs_to :stadium
    belongs_to :team
end

Any help is very appreciated!

EDIT: (Input fields)
Here's how the code for my inputs currently looks:

<%= f.association :teams, label: 'Current Residents', class:'select2-field', placeholder: "Select teams", collection: @teams, input_html: { multiple: true }, hint: 'Select one or multiple teams.'%>

<%= f.association :teams, label: 'Old Residents', class:'select2-field', placeholder: "Select teams", collection: @teams, input_html: { multiple: true }, hint: 'Select one or multiple teams.' %>

And my params

   def stadium_params
      params.require(:stadium).permit(:name, :capacity, :city, :country, :location_name, :address, :longitude, :latitude, :image, :surface, :official_opening_date, :cost, :web_url, :also_known_as, :record_attendance, :team_ids => [])
    end

Body:
You can define relations with a lambda to append an additional where clause in the relation:

class Team < ActiveRecord::Base
    has_many :stadiumteams, :class_name => 'StadiumTeam'

    has_many stadiums, :through => :stadiumteams
    has_many :current_stadiums, ->{ where(stadiumteams: { current_home: true }) }, :through => :stadiumteams, :class_name => 'Stadium', :source => :stadium
    has_many :previous_stadiums, ->{ where(stadiumteams: { current_home: false }) }, :through => :stadiumteams, :class_name =>'Stadium', :source => :stadium
end

class Stadium < ActiveRecord::Base
    has_many :stadiumteams, :class_name => 'StadiumTeam'

    has_many :teams, :through => :stadiumteams
    has_many :current_teams, ->{ where(stadiumteams: { current_home: true }) }, :through => :stadiumteams, :class_name => 'Team', :source => :team
    has_many :previous_teams, ->{ where(stadiumteams: { current_home: false }) }, :through => :stadiumteams, :class_name =>'Team'. :source => :team
end

class StadiumTeam < ActiveRecord::Base
    belongs_to :stadium
    belongs_to :team
end

And then you should be able to do (in rails console):

team = Team.first
stadium = Stadium.first
team.previous_stadiums <<
team.save
team.reload.previous_stadiums.include?(stadium)
# => should return true

So this way you can simply use in your UI a input for the association :previous_teams and :current_teams:

f.association :current_teams, #...


问:
Default text on textarea jQuery?
I have a textarea that i would like to show some default text on page load. Once the textarea is clicked i would like to have the text disappear and possibly if user clicked in textarea and did not type anything in and then clicked out of textarea the default text will show again.

I have searched Google and on here but i can only seem to find tutorials relating to text boxes and NOT textareas, plus i already am using a class on the textarea so cannot depend on class for it to work.

Does anyone have some simple jQuery code they would like to share with me to do what i want above?

答:
Simple enough:

```<code>$(function() {
  $('textarea.autoDefault').focus(function() {
     if($(this).val() === $(this).data('default') && !$(this).data('edited')) {
        $(this).val('');
     }
  }).change(function() {
     $(this).data('edited', this.value.length > 0);
  }).blur(function() {
     if($(this).val().length === 0) {
        $(this).val($(this).data('default'));
     }
  }).blur(); //fire blur event initially
});
</code>```

HTML markup:

```<code><textarea class="autoDefault" rows="10" cols="25" data-default="some default text"></textarea>
</code>```

jsFiddle example

Title: Default text on textarea jQuery?

Body:
Simple enough:

$(function() {
  $('textarea.autoDefault').focus(function() {
     if($(this).val() === $(this).data('default') && !$(this).data('edited')) {
        $(this).val('');
     }
  }).change(function() {
     $(this).data('edited', this.value.length > 0);
  }).blur(function() {
     if($(this).val().length === 0) {
        $(this).val($(this).data('default'));
     }
  }).blur(); //fire blur event initially
});

HTML markup:

<textarea class="autoDefault" rows="10" cols="25" data-default="some default text"></textarea>

jsFiddle example


问:
Design Choices for storing images on Google App Engine
I'm developing an application that I'm thinking of hosting on GAE, hopefully within the free tier. It's an "own-time" project and I find the GAE documentation pretty incomprehensible when it comes to working out which products are available, how much they cost, and how they should be used.

The app relies on users being able to upload images with some meta data. The meta data needs to be searchable and allow the images to be displayed.

My problem comes with where to save the images. I'm storing the metadata in the DataStore. Google seem to imply that I should store the images in either Cloud Storage or the Blob Store, with a preference for Cloud Storage. This seems to be chargeable.

I also see mention of the Image Service - is this something else I should consider?

答:
From Default Google Cloud Storage bucket:

Applications can use a Default Google Cloud Storage bucket, which has
  free quota and doesn't require billing to be enabled for the app. You
  create this free default bucket in the Google Cloud Platform Console
  App Engine settings page for your project.

So you can use GCS without being charged as long as you don't exceed the free quota.

You also probably want to stick with the standard environment for its free quota. From App Engine Pricing:

App Engine applications run as instances within the standard
  environment or the flexible environment.

Instances within the standard environment have access to a daily limit
  of resource usage that is provided at no charge defined by a set of
  quotas. Beyond that level, applications will incur charges as
  outlined below. To control your application costs, you can set a
  spending limit. To estimate costs for the standard environment,
  use the pricing calculator.

For instances within the flexible environment, services and APIs are
  priced as described below.

And for images-related options, from  Overview of Images API for Java:

Java 8 on App Engine supports Java's native image manipulation
  classes such as AWT and Java2D alongside the App Engine
  Images API.


问:
How to send from JAVA String(path of file) to C?
i want to send from java some paths to C.

For example i have a folder that have 4 subfoldes... From java i read the length of them from the code below and it returns me 4.

```<code>     public static int GetLength(){File file = new File("C:\\Registrations");
           File[] files = file.listFiles(new FileFilter(){
             public boolean accept(File f) {
                 return f.isDirectory();   }});
                  return files.length;}     }
</code>```

Now with a thread i start to call the function that connect with C

```<code>      public Start(){ Thread listeningThread = new Thread(new Runnable(){
        public void run(){
        new Match(GetDBNumber());  }  });
        listeningThread.start();}
</code>```

So far all good. Now from MATCH(int x) class i want to call a C code and every time give the path of the Main folder each time

```<code>    *PSEUDOCODE*      public class Match {
                       public Match( int len){
                      System.out.println("subfolders  : "+len);
                      for (i=0; i<len; i++)
                      {     //Some way call C programm (like an exe)
                            //with the first,second,third,fourth path
                      }
                        ....      }
</code>```

The C code that will recieve the path will be look like that...

```<code>            int main()     {
            FILE *fp = fopen(FilePATH, "r");
            ......
            ......
            return 0;                                 }
</code>```

I try with ProcessBuilder but i cant send the path every time with this way...

```<code>          ProcessBuilder p = new ProcessBuilder();
           //receive.exe is the exe that Codeblocks create after built the C code
          p.command("C:\\Users\\PC\\Documents\\NetBeansProjects\\TEST\\C\\recieve.exe");
         try {
             p.start();
             } catch (Exception e) {System.out.println("Error");

            }
</code>```

答:
As stated by Eric Fitzsimmons,
you will need to use JNI to pass a String value from Java to C.

The C part will need to be in a dll that is available to the Java program.

Wikipedia has a JNI article

Oracle has an in-depth JNI write-up

Edit Concerning JNI.
If you want to send a value between Java and C,
there are only a few ways to do it.

JNI. As stated, Java Native Interface is built for this. This seems to be the best solution.

Use an external Data store. Write something to a data store (maybe a file or a database) on one side and read it on the other side (sides being Java and C).

Write a stand-alone C program that writes to standard out. Launch that program from within Java. Read what was written in java.  This is not a great idea.

Body:
i want to send from java some paths to C.

For example i have a folder that have 4 subfoldes... From java i read the length of them from the code below and it returns me 4.

     public static int GetLength(){File file = new File("C:\\Registrations");
           File[] files = file.listFiles(new FileFilter(){
             public boolean accept(File f) {
                 return f.isDirectory();   }});
                  return files.length;}     }

Now with a thread i start to call the function that connect with C

      public Start(){ Thread listeningThread = new Thread(new Runnable(){
        public void run(){
        new Match(GetDBNumber());  }  });
        listeningThread.start();}

So far all good. Now from MATCH(int x) class i want to call a C code and every time give the path of the Main folder each time

    *PSEUDOCODE*      public class Match {
                       public Match( int len){
                      System.out.println("subfolders  : "+len);
                      for (i=0; i<len; i++)
                      {     //Some way call C programm (like an exe)
                            //with the first,second,third,fourth path
                      }
                        ....      }

The C code that will recieve the path will be look like that...

            int main()     {
            FILE *fp = fopen(FilePATH, "r");
            ......
            ......
            return 0;                                 }

I try with ProcessBuilder but i cant send the path every time with this way...

          ProcessBuilder p = new ProcessBuilder();
           //receive.exe is the exe that Codeblocks create after built the C code
          p.command("C:\\Users\\PC\\Documents\\NetBeansProjects\\TEST\\C\\recieve.exe");
         try {
             p.start();
             } catch (Exception e) {System.out.println("Error");

            }