问:
Calling a Class Object From a Dictionary as an Object
I have a dictionary of class objects. I need to pull the object to have it perform one of it's functions. The objects do not have variable names, they are made by a for loop.

Here's what I tried:

```<code>    class Pawn(object):
     def legal_moves(self):
         ...
         return moves_list

    ...
    # main
    dictionary = {'a2': <class '__main__.Pawn'>, 'b2': <class '__main__.Pawn'> etc.}

    pawn_obj = dictionary['a2']

    moves = pawn_obj.legal_moves()
</code>```

FULLER VERSION OF CODE:

```<code>  class Pawn(Piece):
    def __init__(self, color):
        self.type = "P"
        super(Pawn, self).__init__(color, self.type)

    def legal_moves(self, position, map):
        self.l_moves = []
        file = int(position[:1])
        rank = int(position[1:])

        if self.color == "w" and rank == 2:
            move1 = str(rank + 1) + str(file)
            move2 = str(rank + 2) + str(file)
            self.l_moves.append(move1)
            self.l_moves.append(move2)
        return self.l_moves

#main
b = Board(white_view=True)

p = Pawn("w")

p = b.map.get("12")
print(type(p))

moves = p.legal_moves("12", b.map)
print(moves)
</code>```

RETURNS:

```<code><class '__main__.Pawn'>

 File "C:/Users/" line 173, in <module>
  moves = p.legal_moves("12", b.map)

TypeError: 'list' object is not callable

Process finished with exit code 1```
```

答:
I agree with Barmar's comment.

I would CTRL-F the project for self.legal_moves looking for a place where its value is set to a list.

The additional code you posted shows that Pawn has an attribute l_moves that is a list.  Maybe that attribute started life as Pawn.legal_moves before you created the Pawn.legal_moves() function and you missed renaming it somewhere?

Try adding these debugging lines to get a hint about what that attribute really contains in your case:

p = b.map.get("12")
print(type(p))

# new lines
print(type(p.legal_moves))  # if <class 'list'>, we're on the right track; if <class 'method'> we need to look elsewhere
print(p.legal_moves))  # if it's a list, its contents might give you a clue about where it's being set

moves = p.legal_moves("12", b.map)
```

Body:
I have a dictionary of class objects. I need to pull the object to have it perform one of it's functions. The objects do not have variable names, they are made by a for loop.

Here's what I tried:

    class Pawn(object):
     def legal_moves(self):
         ...
         return moves_list

    ...
    # main
    dictionary = {'a2': <class '__main__.Pawn'>, 'b2': <class '__main__.Pawn'> etc.}

    pawn_obj = dictionary['a2']

    moves = pawn_obj.legal_moves()

FULLER VERSION OF CODE:

  class Pawn(Piece):
    def __init__(self, color):
        self.type = "P"
        super(Pawn, self).__init__(color, self.type)

    def legal_moves(self, position, map):
        self.l_moves = []
        file = int(position[:1])
        rank = int(position[1:])

        if self.color == "w" and rank == 2:
            move1 = str(rank + 1) + str(file)
            move2 = str(rank + 2) + str(file)
            self.l_moves.append(move1)
            self.l_moves.append(move2)
        return self.l_moves

#main
b = Board(white_view=True)

p = Pawn("w")

p = b.map.get("12")
print(type(p))

moves = p.legal_moves("12", b.map)
print(moves)

RETURNS:

<class '__main__.Pawn'>

 File "C:/Users/" line 173, in <module>
  moves = p.legal_moves("12", b.map)

TypeError: 'list' object is not callable

Process finished with exit code 1```


来源: stackexchange

问:
RegEx for matching an alphanumeric pattern with quantifier
I am trying to limit the digits between 4 and 6 in my regex but it is not working

Minimum range works but the max range does not work:

Some Text-1  = validates

Some Text-201901 = validates

Some Text-20190101 = passes the validation where it should fail

Now if I add $ at the end then none of the above work.

Code:

```<code>^[A-Z ]{3,}-\d{4,6}
</code>```

答:
I'm not quite sure, what we might wish to pass and fail, however based on your original expression my guess is that this might be what we might want to start with with an i flag:

```<code>^[A-Z ]{3,}-\d{1,6}$
</code>```

or without i flag:

```<code>^[A-Za-z ]{3,}-\d{1,6}$
</code>```

Demo

Test

const regex = /^[A-Z ]{3,}-\d{1,6}$/gmi;
const str = `Some Text-1
Some Text-201901
Some Text-20190101`;
let m;

while ((m = regex.exec(str)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }

    // The result can be accessed through the `m`-variable.
    m.forEach((match, groupIndex) => {
        console.log(`Found match, group ${groupIndex}: ${match}`);
    });
}```

RegEx

If this expression wasn't desired, it can be modified/changed in regex101.com.

RegEx Circuit

jex.im visualizes regular expressions:

ContentLicense: CC BY-SA 4.0

Body:
I am trying to limit the digits between 4 and 6 in my regex but it is not working

Minimum range works but the max range does not work:

Some Text-1  = validates

Some Text-201901 = validates

Some Text-20190101 = passes the validation where it should fail

Now if I add $ at the end then none of the above work.

Code:

^[A-Z ]{3,}-\d{4,6}

Body:
I'm not quite sure, what we might wish to pass and fail, however based on your original expression my guess is that this might be what we might want to start with with an i flag:

^[A-Z ]{3,}-\d{1,6}$

or without i flag:

^[A-Za-z ]{3,}-\d{1,6}$

Demo

Test

const regex = /^[A-Z ]{3,}-\d{1,6}$/gmi;
const str = `Some Text-1
Some Text-201901
Some Text-20190101`;
let m;

while ((m = regex.exec(str)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }

    // The result can be accessed through the `m`-variable.
    m.forEach((match, groupIndex) => {
        console.log(`Found match, group ${groupIndex}: ${match}`);
    });
}

RegEx

If this expression wasn't desired, it can be modified/changed in regex101.com.

RegEx Circuit

jex.im visualizes regular expressions:


问:
How can I test that my before_save callback does the right thing
I have a callback on my ActiveRecord model as shown below:

```<code>  before_save :sync_to_external_apis

  def sync_to_external_apis
    [user, assoc_user].each {|cuser|
      if cuser.google_refresh
        display_user = other_user(cuser.id)
        api = Google.new(:user => cuser)
        contact = api.sync_user(display_user)
      end
    }
  end
</code>```

I would like to write an rspec test which tests that calling save! on an instance of this model causes sync_user to be called on a new Google instance when google_refresh is true. How could I do this?

答:
The usual method for testing is to ensure the results are as expected. Since you're using an API in this case that may complicate things. You may find that using mocha to create a mock object you can send API calls would allow you to substitute the Google class with something that works just as well for testing purposes.

A simpler, yet clunkier approach is to have a "test mode" switch:

```<code>def sync_to_external_apis
  [ user, assoc_user ].each do |cuser|
    if (Rails.env.test?)
      @synced_users ||= [ ]
      @synced_users << cuser
    else
      # ...
    end
  end
end

def did_sync_user?(cuser)
  @synced_users and @synced_users.include?(cuser)
end
</code>```

This is a straightforward approach, but it will not validate that your API calls are being made correctly.

ContentLicense: CC BY-SA 3.0

Body:
I have a callback on my ActiveRecord model as shown below:

  before_save :sync_to_external_apis

  def sync_to_external_apis
    [user, assoc_user].each {|cuser|
      if cuser.google_refresh
        display_user = other_user(cuser.id)
        api = Google.new(:user => cuser)
        contact = api.sync_user(display_user)
      end
    }
  end

I would like to write an rspec test which tests that calling save! on an instance of this model causes sync_user to be called on a new Google instance when google_refresh is true. How could I do this?

Body:
The usual method for testing is to ensure the results are as expected. Since you're using an API in this case that may complicate things. You may find that using mocha to create a mock object you can send API calls would allow you to substitute the Google class with something that works just as well for testing purposes.

A simpler, yet clunkier approach is to have a "test mode" switch:

def sync_to_external_apis
  [ user, assoc_user ].each do |cuser|
    if (Rails.env.test?)
      @synced_users ||= [ ]
      @synced_users << cuser
    else
      # ...
    end
  end
end

def did_sync_user?(cuser)
  @synced_users and @synced_users.include?(cuser)
end

This is a straightforward approach, but it will not validate that your API calls are being made correctly.


问:
Java Runtime version for JDK12
It's not really an error but when I am checking the runtime version it gives me the following, does that mean am I doing something wrong?</p>

```<code>jshell> Runtime.version()
$3 ==> 12.0.1+12
</code>```

答:
Current version of OpenJDK = 12.0.1+12

Nothing is amiss. Version 12.0.1 Build 12 is the currently shipping version of the OpenJDK implementation of Java.

See this screenshot of the AdoptOpenJDK website. Notice the version number 12.0.1+12 circled here in orange.

To understand the semantics of the version numbering for Java 10 and later, see JEP 322: Time-Based Release Versioning.

Title: Java Runtime version for JDK12

Body:
It's not really an error but when I am checking the runtime version it gives me the following, does that mean am I doing something wrong?

jshell> Runtime.version()
$3 ==> 12.0.1+12


问:
Apache2 authentication against ldap fails with "user not found"
i installed slapd (2.4.40+dfsg-1+deb8u2) recently, and i' m trying to get apache2 (2.4.10-10+deb8u7) authenticated through ldap. The system itself is debian (8.6).

Ldap should run on localhost on the default port, and using phpldapadmin the DN ( cn=admin,dc=1000,dc=hu ) seems to be ok. For apache2 authenticaion i use .htaccess file, and basic authentication (htpasswd file) works also fine.

My configucation is:

```<code>AuthName "Add your login message here."
AuthType Basic
AuthBasicProvider ldap
AuthLDAPURL "ldap://localhost:389/dc=1000,dc=hu?sAMAccountName?sub?(objectClass=*)"
AuthLDAPBindDN "cn=admin,dc=1000,dc=hu"
AuthLDAPBindPassword ******
require ldap-user testtest test ttest
</code>```

.

Whatever i do, i got the "user not found" error in apache2 logs:

```<code>==> /var/log/apache2/error.log <==
[Sat Jan 21 12:54:29.272676 2017] [auth_basic:error] [pid 27767] [client 127.0.0.1:52852] AH01618: user ttest not found: /t1/

==> /var/log/apache2/access.log <==
127.0.0.1 - ttest [21/Jan/2017:12:54:29 +0100] "GET /t1/ HTTP/1.1" 401 738 "-" "Mozilla/5.0 (X11; Linux x86_64; rv:45.0) Gecko/20100101 Firefox/45.0"

==> /var/log/apache2/error.log <==
[Sat Jan 21 12:54:44.388323 2017] [auth_basic:error] [pid 27766] [client 127.0.0.1:52854] AH01618: user test not found: /t1/

==> /var/log/apache2/access.log <==
127.0.0.1 - test [21/Jan/2017:12:54:44 +0100] "GET /t1/ HTTP/1.1" 401 738 "-" "Mozilla/5.0 (X11; Linux x86_64; rv:45.0) Gecko/20100101 Firefox/45.0"

==> /var/log/apache2/error.log <==
[Sat Jan 21 12:54:49.460321 2017] [auth_basic:error] [pid 27770] [client 127.0.0.1:52856] AH01618: user testtest not found: /t1/

==> /var/log/apache2/access.log <==
127.0.0.1 - testtest [21/Jan/2017:12:54:49 +0100] "GET /t1/ HTTP/1.1" 401 738 "-" "Mozilla/5.0 (X11; Linux x86_64; rv:45.0) Gecko/20100101 Firefox/45.0"
</code>```

ttest, test and testtest are username, sn, cn in my system.

Password for AuthLDAPBindPassword is triple checked, also for the user.

Where do i make the mistake? Does the AuthLDAPURL have the right value in this scenario?

答:
I was getting the same error and it was related to using the default attribute 'uid' with Active Directory, rather than specifying sAMAccountName.</p>

```<code>AuthLDAPURL ldap://192.168.1.1:389/dc=domain,dc=local?sAMAccountName
</code>```

Body:
i installed slapd (2.4.40+dfsg-1+deb8u2) recently, and i' m trying to get apache2 (2.4.10-10+deb8u7) authenticated through ldap. The system itself is debian (8.6).

Ldap should run on localhost on the default port, and using phpldapadmin the DN ( cn=admin,dc=1000,dc=hu ) seems to be ok. For apache2 authenticaion i use .htaccess file, and basic authentication (htpasswd file) works also fine.

My configucation is:

AuthName "Add your login message here."
AuthType Basic
AuthBasicProvider ldap
AuthLDAPURL "ldap://localhost:389/dc=1000,dc=hu?sAMAccountName?sub?(objectClass=*)"
AuthLDAPBindDN "cn=admin,dc=1000,dc=hu"
AuthLDAPBindPassword ******
require ldap-user testtest test ttest

.

Whatever i do, i got the "user not found" error in apache2 logs:

==> /var/log/apache2/error.log <==
[Sat Jan 21 12:54:29.272676 2017] [auth_basic:error] [pid 27767] [client 127.0.0.1:52852] AH01618: user ttest not found: /t1/

==> /var/log/apache2/access.log <==
127.0.0.1 - ttest [21/Jan/2017:12:54:29 +0100] "GET /t1/ HTTP/1.1" 401 738 "-" "Mozilla/5.0 (X11; Linux x86_64; rv:45.0) Gecko/20100101 Firefox/45.0"

==> /var/log/apache2/error.log <==
[Sat Jan 21 12:54:44.388323 2017] [auth_basic:error] [pid 27766] [client 127.0.0.1:52854] AH01618: user test not found: /t1/

==> /var/log/apache2/access.log <==
127.0.0.1 - test [21/Jan/2017:12:54:44 +0100] "GET /t1/ HTTP/1.1" 401 738 "-" "Mozilla/5.0 (X11; Linux x86_64; rv:45.0) Gecko/20100101 Firefox/45.0"

==> /var/log/apache2/error.log <==
[Sat Jan 21 12:54:49.460321 2017] [auth_basic:error] [pid 27770] [client 127.0.0.1:52856] AH01618: user testtest not found: /t1/

==> /var/log/apache2/access.log <==
127.0.0.1 - testtest [21/Jan/2017:12:54:49 +0100] "GET /t1/ HTTP/1.1" 401 738 "-" "Mozilla/5.0 (X11; Linux x86_64; rv:45.0) Gecko/20100101 Firefox/45.0"

ttest, test and testtest are username, sn, cn in my system.

Password for AuthLDAPBindPassword is triple checked, also for the user.

Where do i make the mistake? Does the AuthLDAPURL have the right value in this scenario?

Body:
I was getting the same error and it was related to using the default attribute 'uid' with Active Directory, rather than specifying sAMAccountName.

AuthLDAPURL ldap://192.168.1.1:389/dc=domain,dc=local?sAMAccountName


问:
Hugo + blogdown: Rendering error with date param
I have tried to setup a portfolio using blogdown, Hugo with Blackburn theme. Once I rendered the website, the posts are picking up a weird date format. I could not narrow down the source of the error. Any leads on this would be highly helpful. Thanks.

```<code>[params]
  # Shown in the home page

  # CSS name for highlight.js
  highlightjs = "androidstudio"
  dateFormat = "22 May 2019, 21:34"
</code>```

答:
Your date format is invalid. What you want is:

```<code>dateFormat = "02 Jan 2006, 15:04"
</code>```

Date formatting in Hugo (and Go Lang) may feel peculiar at first, but the Hugo docs have helpful examples.

Body:
I have tried to setup a portfolio using blogdown, Hugo with Blackburn theme. Once I rendered the website, the posts are picking up a weird date format. I could not narrow down the source of the error. Any leads on this would be highly helpful. Thanks.

[params]
  # Shown in the home page

  # CSS name for highlight.js
  highlightjs = "androidstudio"
  dateFormat = "22 May 2019, 21:34"

Body:
Your date format is invalid. What you want is:

dateFormat = "02 Jan 2006, 15:04"

Date formatting in Hugo (and Go Lang) may feel peculiar at first, but the Hugo docs have helpful examples.


问:
How do I make the program do something when an object is destroyed?
I have plane(as in air plane) objects in my program, they get destroyed when bullets hit them but they also get destroyed after 5 seconds, when they exit the screen.

I also have a health script that resets the whole thing when it goes down to 0, and I want to remove a point every time the object is destroyed, but only when off screen. So I keep the scripts separate.

I use this in the ships spawn script to destroy them after 5 seconds, simple enough.

```<code>Destroy(spawnedPlane, 5f);
</code>```

It would be perfect if I could just have some code that does "Destroy this object after X seconds AND add this to this value". Because as I understand it, "destroy" only accepts 2 parameters and nothing else.

Surely it is possible but I am at a loss. Still very new to this. Sorry if this is very unclear but I barely know what I'm doing myself.

答:
Just use a coroutine to wait and then subtract a point and destroy the object at the same time.

void Start()
{
    // your startup script
    StartCoroutine(DestroyAfterSeconds(5f));
}

IEnumerator DestroyAfterSeconds(float seconds)
{
    // wait for X amount of seconds before continuing on
    yield return new WaitForSeconds(seconds);

    /*
     *  this runs after the wait.
     *  if the coroutine is on the same gameobject that you are
     *  destroying, it will stop after you run Destroy(), so subtract
     *  the point first.
     * */
    points--;
    Destroy(spawnedPlane);
}
```

Body:
I have plane(as in air plane) objects in my program, they get destroyed when bullets hit them but they also get destroyed after 5 seconds, when they exit the screen.

I also have a health script that resets the whole thing when it goes down to 0, and I want to remove a point every time the object is destroyed, but only when off screen. So I keep the scripts separate.

I use this in the ships spawn script to destroy them after 5 seconds, simple enough.

Destroy(spawnedPlane, 5f);

It would be perfect if I could just have some code that does "Destroy this object after X seconds AND add this to this value". Because as I understand it, "destroy" only accepts 2 parameters and nothing else.

Surely it is possible but I am at a loss. Still very new to this. Sorry if this is very unclear but I barely know what I'm doing myself.


问:
Link to App store with no redirects?
Apple recommends an itms:// link for native applications linking to the app store, however a link such as the following ends up opening itunes first, then redirecting to the app store:

```<code>itms://itunes.com/apps/Reactors
</code>```

How do you open the app store directly with no redirects to iTunes or Safari?  It appears that even the usage of phobos.apple.com is being depreciated.

On fast devices it can take several seconds to animate the native app away, animate itunes in place, find the redirect, animate itunes away, animate the app store in place, and find the app. It makes the app seem poorly designed to have all that page flipping occur before bringing the user to what they requested.

Example code:

```<code>[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"itms://itunes.com/apps/Reactors"]]
</code>```

答: Instead of using "itms://" use "itms-apps://".</p>

Title: Link to App store with no redirects?

Body:
Apple recommends an itms:// link for native applications linking to the app store, however a link such as the following ends up opening itunes first, then redirecting to the app store:

itms://itunes.com/apps/Reactors

How do you open the app store directly with no redirects to iTunes or Safari?  It appears that even the usage of phobos.apple.com is being depreciated.

On fast devices it can take several seconds to animate the native app away, animate itunes in place, find the redirect, animate itunes away, animate the app store in place, and find the app. It makes the app seem poorly designed to have all that page flipping occur before bringing the user to what they requested.

Example code:

[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"itms://itunes.com/apps/Reactors"]]


问:
Is it possible to force data immutability in a python function?
Say I define a list object and only want it to be read-only in a function I define. In C++, you'd do this with a const reference. Is there any way to do this with a python function? Does this make sense with respect to writing "pythonic" code or am I just trying to apply a C++ paradigm incorrectly?</p>

答:
Use a tuple, instead:

```<code>>>> hash([1,2,3])
Traceback (most recent call last):
  File "<pyshell#7>", line 1, in <module>
    hash([1,2,3])
TypeError: unhashable type: 'list'
>>> hash((1,2,3))
2528502973977326415
>>>
</code>```

hash can define whether it is mutable or not, and produces an error of TypeError: unhashable type if it's mutable, such as lists, OTOH tuple will return some large numbers (don't need to care in this particular case), we can use a try except if you want to:

```<code>try:
    hash((1,2,3))
    print('Immutable object')
except:
    print('Mutable object')
</code>```

Which outputs:

```<code>Immutable object
</code>```

Body:
Use a tuple, instead:

>>> hash([1,2,3])
Traceback (most recent call last):
  File "<pyshell#7>", line 1, in <module>
    hash([1,2,3])
TypeError: unhashable type: 'list'
>>> hash((1,2,3))
2528502973977326415
>>>

hash can define whether it is mutable or not, and produces an error of TypeError: unhashable type if it's mutable, such as lists, OTOH tuple will return some large numbers (don't need to care in this particular case), we can use a try except if you want to:

try:
    hash((1,2,3))
    print('Immutable object')
except:
    print('Mutable object')

Which outputs:

Immutable object


问:
Reordering arrays
Say, I have an array that looks like this:

```<code>var playlist = [
    {artist:"Herbie Hancock", title:"Thrust"},
    {artist:"Lalo Schifrin", title:"Shifting Gears"},
    {artist:"Faze-O", title:"Riding High"}
];
</code>```

How can I move an element to another position?

I want to move for example, {artist:"Lalo Schifrin", title:"Shifting Gears"} to the end.

I tried using splice, like this:

```<code>var tmp = playlist.splice(2,1);
playlist.splice(2,0,tmp);
</code>```

But it doesn't work.

答:
With ES6 you can do something like this:

```<code>const swapPositions = (array, a ,b) => {
  [array[a], array[b]] = [array[b], array[a]]
}

let array = [1,2,3,4,5];
swapPositions(array,0,1);

/// => [2, 1, 3, 4, 5]
</code>```

Title: Reordering arrays

Body:
Say, I have an array that looks like this:

var playlist = [
    {artist:"Herbie Hancock", title:"Thrust"},
    {artist:"Lalo Schifrin", title:"Shifting Gears"},
    {artist:"Faze-O", title:"Riding High"}
];

How can I move an element to another position?

I want to move for example, {artist:"Lalo Schifrin", title:"Shifting Gears"} to the end.

I tried using splice, like this:

var tmp = playlist.splice(2,1);
playlist.splice(2,0,tmp);

But it doesn't work.

Body:
With ES6 you can do something like this:

const swapPositions = (array, a ,b) => {
  [array[a], array[b]] = [array[b], array[a]]
}

let array = [1,2,3,4,5];
swapPositions(array,0,1);

/// => [2, 1, 3, 4, 5]


问:
I need help converting text file to xml in Java
I need help converting a text file to an xml file.

This is how I want the converted text file to look like:

```<code>   <ItemBonusDefinition>
        <id>88</id>
        <bonuses>
            <short>1</short>
            <short>1</short>
            <short>1</short>
        </bonuses>
    </ItemBonusDefinition>
    <ItemBonusDefinition>
        <id>89</id>
        <bonuses>
            <short>1</short>
            <short>1</short>
            <short>1</short>
        </bonuses>
    </ItemBonusDefinition>
</code>```

This is what the text file looks like:

```<code>88
1.0
1.0
1.0
89
1.0
1.0
1.0
</code>```

This is my code:

```<code>package com.test.tools;

import java.io.BufferedReader;
import java.io.FileReader;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.sax.SAXTransformerFactory;
import javax.xml.transform.sax.TransformerHandler;
import javax.xml.transform.stream.StreamResult;

import org.dom4j.Element;
import org.xml.sax.SAXException;
import com.arlania.signlink;

public class ToXML {

    BufferedReader in;
    StreamResult out;
    TransformerHandler th;

    public static void main(String args[]) {
        new ToXML().begin();
    }

    public void begin() {
        try {
            in = new BufferedReader(new FileReader(signlink.getCacheDirectory()+"items2.txt"));
            out = new StreamResult(signlink.getCacheDirectory()+"items4.xml");
            openXml();
            String str;
            while ((str = in.readLine()) != null) {
                process(str);
            }
            in.close();
            closeXml();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void openXml() throws ParserConfigurationException, TransformerConfigurationException, SAXException {

        SAXTransformerFactory tf = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
        th = tf.newTransformerHandler();

        // pretty XML output
        Transformer serializer = th.getTransformer();
        serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
        serializer.setOutputProperty(OutputKeys.INDENT, "yes");

        th.setResult(out);
        th.startDocument();
        th.startElement(null, null, "list", null);
        th.startElement(null, null, "ItemBonusDefinition", null);
    }

    /**
     * Lists all the ints in <id> and the double in <short>. id are item id's and short is the bonus for the item id's
     * @param s
     * @throws SAXException
     */
    public void process(String s) throws SAXException {
        if (isInteger(s)) {
            th.startElement(null, null, "id", null);
            th.characters(s.toCharArray(), 0, s.length());
            th.endElement(null, null, "id");
        } else if (isDouble(s)) {
            th.startElement(null, null, "short", null);
            th.characters(s.toCharArray(), 0, s.length());
            th.endElement(null, null, "short");
        }
    }

    public void closeXml() throws SAXException {
        th.endElement(null, null, "ItemBonusDefinition");
        th.endElement(null, null, "list");
        th.endDocument();
    }

    public boolean isDouble( String str ){
        try{
            Double.parseDouble( str );
            return true;
        }
        catch( Exception e ){
            return false;
        }
    }

    public boolean isInteger(Object object) {
        if(object instanceof Integer) {
            return true;
        } else {
            String string = object.toString();

            try {
                Integer.parseInt(string);
            } catch(Exception e) {
                return false;
            }
        }

        return true;
    }
}
</code>```

The code outputs this:

```<code><ItemBonusDefinition>
        <id>88</id>
        <short>1.0</short>
        <short>1.0</short>
        <short>1.0</short>
        <id>89</id>
        <short>1.0</short>
        <short>1.0</short>
        <short>1.0</short>
</code>```

I need help adding the <bonuses> correctly as in the first example and <ItemBonusDefinition> aswell. It must look EXACTLY as in the first example. I will appreciate any help I can get :)

答:
Try this dom4j code, it can generate xml file you want.

```<code>package test;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

public class Convert {

    private static final int LINES_PER_ELEMENT = 4;
    private static final int COUNT_OF_ELEMENTS = 2;
    private static final int ID_INDEX = 0;

    public static List<String> getFile() {
        List<String> list = new ArrayList<String>();
        File file = new File("text");
        BufferedReader br = null;
        try {
            InputStream in = new FileInputStream(file);
            Reader reader = new InputStreamReader(in);
            br = new BufferedReader(reader);
            String line = null;
            while((line = br.readLine()) != null) {
                list.add(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return list;
    }

    public static Document getXml(List<String> lines) {
        Element root = DocumentHelper.createElement("root");
        Document document = DocumentHelper.createDocument(root);
        String[][] strArr = new String[COUNT_OF_ELEMENTS][LINES_PER_ELEMENT];
        for(int i = 0;i < COUNT_OF_ELEMENTS;i++) {
            for(int j = 0;j < LINES_PER_ELEMENT;j++) {
                strArr[i][j] = lines.get((i + 1) * (j + 1) - 1);
            }
        }

        for(int i = 0;i < COUNT_OF_ELEMENTS;i++) {
            Element itemBonusDefinition = root.addElement("ItemBonusDefinition");
            String[] elemValues = strArr[i];
            Element id = itemBonusDefinition.addElement("id");
            Element bonus = itemBonusDefinition.addElement("bonus");
            for(int j = 0;j < elemValues.length;j++) {
                if(j == ID_INDEX) {
                    id.setText(elemValues[j]);
                } else {
                    Element shorT = bonus.addElement("short");
                    shorT.setText(elemValues[j]);
                }
            }
        }
        return document;
    }

    public static void main(String[] args) throws IOException {
        List<String> lines = getFile();
        Document document = getXml(lines);
        OutputStream out = new FileOutputStream("C:\\Users\\admin\\Desktop\\test11.xml");
        Writer wr = new OutputStreamWriter(out);
        OutputFormat format = OutputFormat.createPrettyPrint();
        XMLWriter writer = new XMLWriter(wr,format);
        writer.write(document);
        writer.close();
    }
}
</code>```

The result is like this:

```<code><?xml version="1.0" encoding="UTF-8"?>

 <root>
   <ItemBonusDefinition>
     <id>88</id>
     <bonus>
       <short>1.0</short>
       <short>1.0</short>
       <short>1.0</short>
     </bonus>
   </ItemBonusDefinition>
   <ItemBonusDefinition>
     <id>1.0</id>
     <bonus>
       <short>1.0</short>
       <short>1.0</short>
       <short>1.0</short>
     </bonus>
   </ItemBonusDefinition>
 </root>
</code>```

Body:
I need help converting a text file to an xml file.

This is how I want the converted text file to look like:

   <ItemBonusDefinition>
        <id>88</id>
        <bonuses>
            <short>1</short>
            <short>1</short>
            <short>1</short>
        </bonuses>
    </ItemBonusDefinition>
    <ItemBonusDefinition>
        <id>89</id>
        <bonuses>
            <short>1</short>
            <short>1</short>
            <short>1</short>
        </bonuses>
    </ItemBonusDefinition>

This is what the text file looks like:

88
1.0
1.0
1.0
89
1.0
1.0
1.0

This is my code:

package com.test.tools;

import java.io.BufferedReader;
import java.io.FileReader;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.sax.SAXTransformerFactory;
import javax.xml.transform.sax.TransformerHandler;
import javax.xml.transform.stream.StreamResult;

import org.dom4j.Element;
import org.xml.sax.SAXException;
import com.arlania.signlink;

public class ToXML {

    BufferedReader in;
    StreamResult out;
    TransformerHandler th;

    public static void main(String args[]) {
        new ToXML().begin();
    }

    public void begin() {
        try {
            in = new BufferedReader(new FileReader(signlink.getCacheDirectory()+"items2.txt"));
            out = new StreamResult(signlink.getCacheDirectory()+"items4.xml");
            openXml();
            String str;
            while ((str = in.readLine()) != null) {
                process(str);
            }
            in.close();
            closeXml();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void openXml() throws ParserConfigurationException, TransformerConfigurationException, SAXException {

        SAXTransformerFactory tf = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
        th = tf.newTransformerHandler();

        // pretty XML output
        Transformer serializer = th.getTransformer();
        serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
        serializer.setOutputProperty(OutputKeys.INDENT, "yes");

        th.setResult(out);
        th.startDocument();
        th.startElement(null, null, "list", null);
        th.startElement(null, null, "ItemBonusDefinition", null);
    }

    /**
     * Lists all the ints in <id> and the double in <short>. id are item id's and short is the bonus for the item id's
     * @param s
     * @throws SAXException
     */
    public void process(String s) throws SAXException {
        if (isInteger(s)) {
            th.startElement(null, null, "id", null);
            th.characters(s.toCharArray(), 0, s.length());
            th.endElement(null, null, "id");
        } else if (isDouble(s)) {
            th.startElement(null, null, "short", null);
            th.characters(s.toCharArray(), 0, s.length());
            th.endElement(null, null, "short");
        }
    }

    public void closeXml() throws SAXException {
        th.endElement(null, null, "ItemBonusDefinition");
        th.endElement(null, null, "list");
        th.endDocument();
    }

    public boolean isDouble( String str ){
        try{
            Double.parseDouble( str );
            return true;
        }
        catch( Exception e ){
            return false;
        }
    }

    public boolean isInteger(Object object) {
        if(object instanceof Integer) {
            return true;
        } else {
            String string = object.toString();

            try {
                Integer.parseInt(string);
            } catch(Exception e) {
                return false;
            }
        }

        return true;
    }
}

The code outputs this:

<ItemBonusDefinition>
        <id>88</id>
        <short>1.0</short>
        <short>1.0</short>
        <short>1.0</short>
        <id>89</id>
        <short>1.0</short>
        <short>1.0</short>
        <short>1.0</short>

I need help adding the <bonuses> correctly as in the first example and <ItemBonusDefinition> aswell. It must look EXACTLY as in the first example. I will appreciate any help I can get :)

Body:
Try this dom4j code, it can generate xml file you want.

package test;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

public class Convert {

    private static final int LINES_PER_ELEMENT = 4;
    private static final int COUNT_OF_ELEMENTS = 2;
    private static final int ID_INDEX = 0;

    public static List<String> getFile() {
        List<String> list = new ArrayList<String>();
        File file = new File("text");
        BufferedReader br = null;
        try {
            InputStream in = new FileInputStream(file);
            Reader reader = new InputStreamReader(in);
            br = new BufferedReader(reader);
            String line = null;
            while((line = br.readLine()) != null) {
                list.add(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return list;
    }

    public static Document getXml(List<String> lines) {
        Element root = DocumentHelper.createElement("root");
        Document document = DocumentHelper.createDocument(root);
        String[][] strArr = new String[COUNT_OF_ELEMENTS][LINES_PER_ELEMENT];
        for(int i = 0;i < COUNT_OF_ELEMENTS;i++) {
            for(int j = 0;j < LINES_PER_ELEMENT;j++) {
                strArr[i][j] = lines.get((i + 1) * (j + 1) - 1);
            }
        }

        for(int i = 0;i < COUNT_OF_ELEMENTS;i++) {
            Element itemBonusDefinition = root.addElement("ItemBonusDefinition");
            String[] elemValues = strArr[i];
            Element id = itemBonusDefinition.addElement("id");
            Element bonus = itemBonusDefinition.addElement("bonus");
            for(int j = 0;j < elemValues.length;j++) {
                if(j == ID_INDEX) {
                    id.setText(elemValues[j]);
                } else {
                    Element shorT = bonus.addElement("short");
                    shorT.setText(elemValues[j]);
                }
            }
        }
        return document;
    }

    public static void main(String[] args) throws IOException {
        List<String> lines = getFile();
        Document document = getXml(lines);
        OutputStream out = new FileOutputStream("C:\\Users\\admin\\Desktop\\test11.xml");
        Writer wr = new OutputStreamWriter(out);
        OutputFormat format = OutputFormat.createPrettyPrint();
        XMLWriter writer = new XMLWriter(wr,format);
        writer.write(document);
        writer.close();
    }
}

The result is like this:

<?xml version="1.0" encoding="UTF-8"?>

 <root>
   <ItemBonusDefinition>
     <id>88</id>
     <bonus>
       <short>1.0</short>
       <short>1.0</short>
       <short>1.0</short>
     </bonus>
   </ItemBonusDefinition>
   <ItemBonusDefinition>
     <id>1.0</id>
     <bonus>
       <short>1.0</short>
       <short>1.0</short>
       <short>1.0</short>
     </bonus>
   </ItemBonusDefinition>
 </root>


问:
Is Runnable an interface or an object in Java?
While creating threads I see code like:-

```<code>Runnable watdaheck = new Runnable()
{
System.out.println("java with time contradicts itself");
}
</code>```

From what I know an interface cannot be instantiated so I fail to understand how we can write Runnable() for creating anonymous class. An interface can be given a reference but cannot be instantiated is what we are taught in polymorphism.

答:
I just modify a bit your code.

```<code> Runnable watdaheck = new Runnable()
    {
         public void run(){
             System.out.println("java with time contradicts itself");
         }
    }
</code>```

The right part

```<code>new Runnable()
    {
         public void run(){
             System.out.println("java with time contradicts itself");
         }
    }
</code>```

is an instance of an anonymous class that implements interface Runnable
The left part Runnable watdaheck, watdaheck is a reference that refers to above object.
Your code is same with below code:

```<code>class SubRunnable implements Runnable{
   public void run(){
       //do something
   }
}
Runnable r = new SubRunnable();
</code>```

You should read more about anonymous class in Java. https://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html

Body:
While creating threads I see code like:-

Runnable watdaheck = new Runnable()
{
System.out.println("java with time contradicts itself");
}

From what I know an interface cannot be instantiated so I fail to understand how we can write Runnable() for creating anonymous class. An interface can be given a reference but cannot be instantiated is what we are taught in polymorphism.

Body:
I just modify a bit your code.

 Runnable watdaheck = new Runnable()
    {
         public void run(){
             System.out.println("java with time contradicts itself");
         }
    }

The right part

new Runnable()
    {
         public void run(){
             System.out.println("java with time contradicts itself");
         }
    }

is an instance of an anonymous class that implements interface Runnable
The left part Runnable watdaheck, watdaheck is a reference that refers to above object.
Your code is same with below code:

class SubRunnable implements Runnable{
   public void run(){
       //do something
   }
}
Runnable r = new SubRunnable();

You should read more about anonymous class in Java. https://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html


问:
How to use default csrf-token from AJAX request in Laravel
I'm using Vuejs and I want to make an secure AJAX request (with axios) to my laravel server, but I think that CSRF protections doesn't work because I change the token of the frontend part and even then I can interact with the database.

I read that Laravel come with a file named [bootstrap.js] (https://laravel.com/docs/5.8/csrf#csrf-introduction) it is assumed that this file does this task by default, but it doesn't work for me. I think it's beacuse webpack doens't load the file when I run npm run watch but I don't know how to load it,

I searched for an answer but I only find Bootstrap tutorials :/

答:
You should add VerifyCsrfToken middleware for the API group
(app/Http/Kernel.php)</p>


问:
Java: need to see if each char in input string, matches any char in "alphabet"
I am implementing a DFA.  The given alphabet is {a, b}.

I've got it telling me if the input string is accepted or not.  (it's got an easy "accept" rule -- the first & last character of the input string must be the same)

What I am trying to do, though, is to check if each character in the input string, is allowed per the prescribed "alphabet".

So, as a boolean, it would return false if the input string is "abcdefg" (for instance)... and it would return true if the input string is "abbaabbbbba" (for instance)

I need to check if a is in the alphabet... then if b is in the alphabet... then if c is in the alphabet... and so forth for each character in the input string.

I've tried variations of loops of different kinds, (I don't remember every single variation!) comparing inputString.charAt(i) with each character in the alphabet... but so far nothing is working like i need/want it to.

for instance, right now I'm trying:

```<code>  public boolean isInAlphabet(String inputString) {
    if(inputString == " ") {
      System.out.println("   -> empty string is not in our alphabet");
      return false;
    }

    for(int i = 0; i < inputString.length(); i++) {
      Character check = inputString.charAt(i);
      System.out.print(check);  // just to see what it's doing

      if(check.equals(alphabet.charAt(0)) || check.equals(alphabet.charAt(1))) {
        System.out.println("   -> your input string is in our alphabet");

        return true;
      }
      else{
        System.out.println("   -> your input string is *not* in our alphapet");
        return false;
      }
    }
    return false;
  }
</code>```

the alphabet is represented as:

```<code>String alphabet = "ab";
</code>```

and the input string is like:

```<code>String inputString = "abcdefg";
</code>```

Thing is, it stops checking after it finds that the first character in the input string, is in the alphabet.

Like:

```<code>test input string: abcdefg
is test input string in our alphabet?
a   -> your input string is in our alphabet
</code>```

... and that's all the further checking it does.

How do I get it to check the whole input string -- each character of the input string, against the alphabet?

Like i said, I can't even remember all the things I've tried so far, but it's been at least a dozen.  The more I try the more confused I get.  This feels so easy, but yet I'm not sure how to get it to work.

答:
I am assuming here that if alphabet contains all the characters from inputString and inputString's first and last character same then it's valid.

But for example, Alphabet = {a,b} and the inputString="aaaaa". So, I am assuming this input also will be valid. (If that's what you are looking for then you can use the following logic to solve it.)
I am taking HashSet for alphabet and then we can iterate the whole string and check whether alphabet contains it or not. The below code is used to convert a string of alphabet to HashSet.

```<code>    String str="ab";
    for(char ch:str.toCharArray()){
        alphabet.add(ch);
    }
</code>```

Now, to implement a method to check for valid input, you can consider the below code.

```<code>public boolean isInAlphabet(String inputString) {
    if(inputString==null || inputString.length()==0) return false;
    if(inputString.charAt(0)!=inputString.charAt(inputString.length()-1)) return false;
    for(char ch:inputString.toCharArray()){
        if(!alphabet.contains(ch)) return false;
    }
    return true;
}
</code>```

Body:
I am implementing a DFA.  The given alphabet is {a, b}.

I've got it telling me if the input string is accepted or not.  (it's got an easy "accept" rule -- the first & last character of the input string must be the same)

What I am trying to do, though, is to check if each character in the input string, is allowed per the prescribed "alphabet".

So, as a boolean, it would return false if the input string is "abcdefg" (for instance)... and it would return true if the input string is "abbaabbbbba" (for instance)

I need to check if a is in the alphabet... then if b is in the alphabet... then if c is in the alphabet... and so forth for each character in the input string.

I've tried variations of loops of different kinds, (I don't remember every single variation!) comparing inputString.charAt(i) with each character in the alphabet... but so far nothing is working like i need/want it to.

for instance, right now I'm trying:

  public boolean isInAlphabet(String inputString) {
    if(inputString == " ") {
      System.out.println("   -> empty string is not in our alphabet");
      return false;
    }

    for(int i = 0; i < inputString.length(); i++) {
      Character check = inputString.charAt(i);
      System.out.print(check);  // just to see what it's doing

      if(check.equals(alphabet.charAt(0)) || check.equals(alphabet.charAt(1))) {
        System.out.println("   -> your input string is in our alphabet");

        return true;
      }
      else{
        System.out.println("   -> your input string is *not* in our alphapet");
        return false;
      }
    }
    return false;
  }

the alphabet is represented as:

String alphabet = "ab";

and the input string is like:

String inputString = "abcdefg";

Thing is, it stops checking after it finds that the first character in the input string, is in the alphabet.

Like:

test input string: abcdefg
is test input string in our alphabet?
a   -> your input string is in our alphabet

... and that's all the further checking it does.

How do I get it to check the whole input string -- each character of the input string, against the alphabet?

Like i said, I can't even remember all the things I've tried so far, but it's been at least a dozen.  The more I try the more confused I get.  This feels so easy, but yet I'm not sure how to get it to work.

Body:
I am assuming here that if alphabet contains all the characters from inputString and inputString's first and last character same then it's valid.

But for example, Alphabet = {a,b} and the inputString="aaaaa". So, I am assuming this input also will be valid. (If that's what you are looking for then you can use the following logic to solve it.)
I am taking HashSet for alphabet and then we can iterate the whole string and check whether alphabet contains it or not. The below code is used to convert a string of alphabet to HashSet.

    String str="ab";
    for(char ch:str.toCharArray()){
        alphabet.add(ch);
    }

Now, to implement a method to check for valid input, you can consider the below code.

public boolean isInAlphabet(String inputString) {
    if(inputString==null || inputString.length()==0) return false;
    if(inputString.charAt(0)!=inputString.charAt(inputString.length()-1)) return false;
    for(char ch:inputString.toCharArray()){
        if(!alphabet.contains(ch)) return false;
    }
    return true;
}


问:
Rails 3 - Testing controller's GET method - trying to use JSON and getting 406 errors
I have a simple controller that specifies:

```<code>respond_to :json
</code>```

When I try to build a functional test that calls it like this:

```<code>test "GET" do
  get 'index', :format => :json
end
</code>```

Everything works just fine.  If, however, I try to pass a query parameter in like this:

```<code>test "GET" do
  get 'index', {:my_param = '1234'}, :format => :json
end
</code>```

I get a 406 error returned from the controller.  If I dump the response via response.inspect, I can see that the @status = 406 and the @header has a content-type of text/html.  If I dump the response via response.inspect for the simple case that doesn't pass a query parameter, I see that the @header has a content-type of application/json as I request in the code.

Does anyone have any ideas what I'm doing wrong here?  I'm suspecting that I'm screwing up ruby syntax with hashes or something but I'm bumping my head against the wall and not getting anywhere.

I'm on a Mac running Ruby 1.9 and Rails 3.0.5.

Thanks in advance!

答:
This is the function you are calling:

```<code>get(action, parameters = nil, session = nil, flash = nil)
</code>```

The :format part is still a parameter, certainly not a session or flash. Try:

```<code>get 'index', {:my_param => '1234', :format => :json}
</code>```

Oh, important note, use '=>', not '=' ... that's a hash, not an assignment.

Body:
I have a simple controller that specifies:

respond_to :json

When I try to build a functional test that calls it like this:

test "GET" do
  get 'index', :format => :json
end

Everything works just fine.  If, however, I try to pass a query parameter in like this:

test "GET" do
  get 'index', {:my_param = '1234'}, :format => :json
end

I get a 406 error returned from the controller.  If I dump the response via response.inspect, I can see that the @status = 406 and the @header has a content-type of text/html.  If I dump the response via response.inspect for the simple case that doesn't pass a query parameter, I see that the @header has a content-type of application/json as I request in the code.

Does anyone have any ideas what I'm doing wrong here?  I'm suspecting that I'm screwing up ruby syntax with hashes or something but I'm bumping my head against the wall and not getting anywhere.

I'm on a Mac running Ruby 1.9 and Rails 3.0.5.

Thanks in advance!

Body:
This is the function you are calling:

get(action, parameters = nil, session = nil, flash = nil)

The :format part is still a parameter, certainly not a session or flash. Try:

get 'index', {:my_param => '1234', :format => :json}

Oh, important note, use '=>', not '=' ... that's a hash, not an assignment.


问:
How to make sure the following function did not over-allocate?
I'm trying to make a function that gets number of columns and rows (width and height), build a 2D matrix, and then return the address of Matrix[0][0] back to a pointer in the original caller-function.

```<code>int **allocateMatrix(int width, int height) // function that allocate
//memory for 2D matrix and check that memory allocation was successful
{
    int **Matrix;
    int row;
    Matrix = (int**)malloc(sizeof(int*)*height);
    if (!Matrix)
    {
        printf("failed to allocate memory. this program is over.\n");
        exit(1);
    }
    for (row = 0; row < height; row++)
    {   Matrix[row] = (int*)malloc(sizeof(int)*width);
      if (!Matrix[row])
      {
        printf("failed to allocate memory. this program is over.\n");
        exit(1);
      }
    }
    return Matrix;
}
</code>```

during the allocating i watched the whole thing through the debugger and it seems to create a way-too-big matrix then i intended, and an unexpected behavior in general.
such as: height =5, width =5,
though Matrix[0][30] - exist and reachable.

moreover, Im not sure about the address im returning.

答:
There are no problems with your allocation. In C if you go outside the boundaries and you're lucky you get a segmentation fault signal and the program terminates (if you haven't installed a particular signal handler for this signal), but if you land on some valid memory you get access to that memory and risk to corrupt something.

As others said in the comments C won't catch coding mistakes but if you compile with the flags -Wall -pedantic -g the compiler will generate some warnings when something is off and some time it'll even give you an hint on how to fix the mistake. Learn also how to use valgrind.

Body:
I'm trying to make a function that gets number of columns and rows (width and height), build a 2D matrix, and then return the address of Matrix[0][0] back to a pointer in the original caller-function.

int **allocateMatrix(int width, int height) // function that allocate
//memory for 2D matrix and check that memory allocation was successful
{
    int **Matrix;
    int row;
    Matrix = (int**)malloc(sizeof(int*)*height);
    if (!Matrix)
    {
        printf("failed to allocate memory. this program is over.\n");
        exit(1);
    }
    for (row = 0; row < height; row++)
    {   Matrix[row] = (int*)malloc(sizeof(int)*width);
      if (!Matrix[row])
      {
        printf("failed to allocate memory. this program is over.\n");
        exit(1);
      }
    }
    return Matrix;
}

during the allocating i watched the whole thing through the debugger and it seems to create a way-too-big matrix then i intended, and an unexpected behavior in general.
such as: height =5, width =5,
though Matrix[0][30] - exist and reachable.

moreover, Im not sure about the address im returning.


问:
Excel macro for data reformatting
I need to reformat a 33500 row of data in excel. I am trying to write a macro that would do this for me.

I have put some nested loop to solve the issue

```<code>Dim i As Integer
Dim m As Integer
Dim n As Integer
Dim K As Integer
Dim p As Integer
Dim c As Integer

For c = 0 To 10

    For n = 5 To 10

        K = 14 + 7 * (n - 5)

        For i = 0 To 7
            m = 14 + 8 * c
            ActiveSheet.Cells(m + i, n).Select
            Selection.Copy

            ActiveSheet.Cells(K + i, 37).Select
            ActiveSheet.Paste
        Next i

    Next n

Next c
</code>```

I am stuck at how to get this operation done for 32500 rows

答:
Excel's Integer has a range of values from -32,768 to 32,767 so formatting 33,500 rows might be a problem.  Assuming that you are happy with how your code works, changing your variable types to Long might be a good start.

BTW, you should avoid SELECTing cells as it slows down the code and can lead to errors.  You can easily copy and paste between cells using soemthing like

```<code>Cells(m + i, n).Copy Destination:=Cells(K + i, 37)
</code>```

Title: Excel macro for data reformatting

Body:
I need to reformat a 33500 row of data in excel. I am trying to write a macro that would do this for me.

I have put some nested loop to solve the issue

Dim i As Integer
Dim m As Integer
Dim n As Integer
Dim K As Integer
Dim p As Integer
Dim c As Integer

For c = 0 To 10

    For n = 5 To 10

        K = 14 + 7 * (n - 5)

        For i = 0 To 7
            m = 14 + 8 * c
            ActiveSheet.Cells(m + i, n).Select
            Selection.Copy

            ActiveSheet.Cells(K + i, 37).Select
            ActiveSheet.Paste
        Next i

    Next n

Next c

I am stuck at how to get this operation done for 32500 rows

Body:
Excel's Integer has a range of values from -32,768 to 32,767 so formatting 33,500 rows might be a problem.  Assuming that you are happy with how your code works, changing your variable types to Long might be a good start.

BTW, you should avoid SELECTing cells as it slows down the code and can lead to errors.  You can easily copy and paste between cells using soemthing like

Cells(m + i, n).Copy Destination:=Cells(K + i, 37)


问:
Segmented Control Position Changes With Storyboard
I have built a simple IOS app to coordinate with my bluetooth device that I built. In doing so, I use segmented control on the main storyboard to turn it on and off, which works just fine. I can then move to a settings page which has another segmented control box, which stays in its current position only if I move forward in the storyboard. If I move back to the main screen then go back to settings, it is in its first position, not the last position where it was placed.

Shortly after, I thought it could be that the segment was not connected to the ViewController.swift, but after trying to connect it in the same manner as before, my app kept crashing whenever I tried accessing settings.

Settings.swift Setup

答:
How are you saving the segment state ?

Have you try save your last state in UserDefaults and load it?
https://medium.com/@nimjea/userdefaults-in-swift-4-d1a278a0ec79

I hope you fix this.


问:
How Do I Fix A Flexbox Sticky Footer In IE11
I have created a sticky footer using flexbox. It works in all browsers apart from IE11.

Codepen

html {
  box-sizing: border-box;
}

*, *:before, *:after {
  box-sizing: inherit;
}

.Page {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  flex: 1;
}

.Page-header {
  background: blue;
}

.Page-footer {
  background: green;
}

.Page-body {
  background: red;
  flex: 1;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="Page">
  <header class="Page-header">
    HEADER
  </header>
  <div class="Page-body">
    BODY
  </div>
  <footer class="Page-footer">
    FOOTER
  </footer>
</div></code>```

Why is it breaking in IE11 and how can I fix it?

答:
I got around it using flexbug's recommendation of changing min-height on the body to just height

Only works for certain circumstances, sticky footers seem to be one of the common use cases.

Body:
I have created a sticky footer using flexbox. It works in all browsers apart from IE11.

Codepen

html {
  box-sizing: border-box;
}

*, *:before, *:after {
  box-sizing: inherit;
}

.Page {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  flex: 1;
}

.Page-header {
  background: blue;
}

.Page-footer {
  background: green;
}

.Page-body {
  background: red;
  flex: 1;
}

    HEADER

    BODY

    FOOTER

Why is it breaking in IE11 and how can I fix it?


问:
Strongly typed dataset using variables for column names
I am currently referencing a generic DataSet via an index and would like to convert this to a strongly-typed DataSet of the table type.  The issue is that my index to the DataRow is a variable.

Currently I am doing the following where the History_Column value is pulled from the database.

    e.Dr[c.History_Column.ToString()] = Entry;

I would like to define the DataRow ('Dr' in the example) as a type of the table so I can do something similar to the following:

    e.Dr.COLUMN_NAME = Entry;

How can I use dynamic variables in this fashion?

Thanks!

答:
A strongly-typed dataset is a class in your application that derives from the built-in dataset class.  You have to add them to your project in visual studio.  Here are some directions for creating strongly typed datasets.

However, I suggest that you take the opportunity to refactor and get away from datasets altogether (if you can).  Entity Framework provides strongly typed property accessors for each column, a better "unit-of-work" pattern, a graphical database mapping tool, and it is much easier to use.


问:
Node try to find package removed long time ago in :app:bundleReleaseJsAndAssets stage only
I'm working on an app build with react-native.

I installed a package "haul" and
remove it after I read it's doc more decide not to use it.

then I encounter a problem

```<code>internal/modules/cjs/loader.js:638
    throw err;
    ^

Error: Cannot find module 'PATH/node_modules/haul/bin/cli.js'
</code>```

I did the sequence
rm -rf node_modules
watchman watch-del-all
rm -rf $TMPDIR/react-*
rm -rf $TMPDIR/metro-*
rm -rf $TMPDIR/haste-*
npm start -- --reset-cache

and the problem is gone.

today I try to build a release package, and the problem is back.

only this time it happens in :app:bundleReleaseJsAndAssets stage only.

I tried a lot of things: remove yarn cache, switch to npm to manage node_modules, switch node version..

this time it won't fix.

I can't even find the string "haul" in my project.

答:
```<code>project.ext.react = [
  cliPath: "node_modules/haul/bin/cli.js"
]
</code>```

is still in build.gradle,
don't know why text find didn't spot it.

anyway, it's fixed now.

Body:
I'm working on an app build with react-native.

I installed a package "haul" and
remove it after I read it's doc more decide not to use it.

then I encounter a problem

internal/modules/cjs/loader.js:638
    throw err;
    ^

Error: Cannot find module 'PATH/node_modules/haul/bin/cli.js'

I did the sequence
rm -rf node_modules
watchman watch-del-all
rm -rf $TMPDIR/react-*
rm -rf $TMPDIR/metro-*
rm -rf $TMPDIR/haste-*
npm start -- --reset-cache

and the problem is gone.

today I try to build a release package, and the problem is back.

only this time it happens in :app:bundleReleaseJsAndAssets stage only.

I tried a lot of things: remove yarn cache, switch to npm to manage node_modules, switch node version..

this time it won't fix.

I can't even find the string "haul" in my project.

Body:
project.ext.react = [
  cliPath: "node_modules/haul/bin/cli.js"
]

is still in build.gradle,
don't know why text find didn't spot it.

anyway, it's fixed now.


问:
How to stop an array from generating too many objects?
I've built an array to generate 8 iterations of random pairs of cards for a total of 16 cards. However it is instead producing 17 cards. I can not see why it is producing this extra card or how to stop it.

I'm new to Xcode and Swift obviously so my debugging skills are Nil.  I've inserted print statements and used breakpoints to try to understand where the extra card is coming from. It seems to be happening at the very start of the CardModel class, perhaps in the way I wrote the method at the beginning.

```<code>class CardModel {

    func getCards() -> [Card] {
        //print("2nd Check")
        // Declare an array to store the generated cards
        var generatedCardsArray = [Card()]

        print("number of random pairs \(generatedCardsArray.count)")

        // Randomly generate pairs of cards
        for _ in 1...8 {

            print("number of random pairs \(generatedCardsArray.count)")

            // Get a random number
            let randomNumber = arc4random_uniform(13) + 1

            // Log the number
            print("Random # \(randomNumber)")

            // Create the first card object
            let cardOne = Card()
            cardOne.imageName = "card\(randomNumber)"

            generatedCardsArray.append(cardOne)

            // Create the second card object
            let cardTwo = Card()
            cardTwo.imageName = "card\(randomNumber)"

            generatedCardsArray.append(cardTwo)
</code>```

I expected this to output 16 random pairs but it is outputting 17

答:
This line:

```<code>var generatedCardsArray = [Card()]
</code>```

that you are using to initialise an empty array is actually creating an array with one entry. Try this instead:-

```<code>var generatedCardsArray : [Card] = []
</code>```

You're then correctly generating 16 cards (8 pairs) but you already have one to start with, that's 17.

Body:
I've built an array to generate 8 iterations of random pairs of cards for a total of 16 cards. However it is instead producing 17 cards. I can not see why it is producing this extra card or how to stop it.

I'm new to Xcode and Swift obviously so my debugging skills are Nil.  I've inserted print statements and used breakpoints to try to understand where the extra card is coming from. It seems to be happening at the very start of the CardModel class, perhaps in the way I wrote the method at the beginning.

class CardModel {

    func getCards() -> [Card] {
        //print("2nd Check")
        // Declare an array to store the generated cards
        var generatedCardsArray = [Card()]

        print("number of random pairs \(generatedCardsArray.count)")

        // Randomly generate pairs of cards
        for _ in 1...8 {

            print("number of random pairs \(generatedCardsArray.count)")

            // Get a random number
            let randomNumber = arc4random_uniform(13) + 1

            // Log the number
            print("Random # \(randomNumber)")

            // Create the first card object
            let cardOne = Card()
            cardOne.imageName = "card\(randomNumber)"

            generatedCardsArray.append(cardOne)

            // Create the second card object
            let cardTwo = Card()
            cardTwo.imageName = "card\(randomNumber)"

            generatedCardsArray.append(cardTwo)

I expected this to output 16 random pairs but it is outputting 17

Body:
This line:

var generatedCardsArray = [Card()]

that you are using to initialise an empty array is actually creating an array with one entry. Try this instead:-

var generatedCardsArray : [Card] = []

You're then correctly generating 16 cards (8 pairs) but you already have one to start with, that's 17.


问:
How to assert for an error using axios and async / await
I am trying to write a test that asserts that a specific type of error is thrown with Async / Await and axios. However, when I run my test, I get the following. Why is jest not properly rejecting my promise? Thanks!

Error: expect(received).rejects.toThrow()

Expected received Promise to reject, instead it resolved to value

  {"data": "response", "status": 404}

api.js:

```<code>import axios from 'axios';
import SpecialError from './specialError.js';

const get = async () => {
  try {
    const response = await axios.get('sampleUrl', { withCredentials: true });
    return response;
  } catch (error) {
    throw new SpecialError(error);
  }
};

export default get;
</code>```

specialError.js:

```<code>export default class SpecialError extends Error {
  constructor() {
    super();
    this.isSpecialError = true;
  }
}
</code>```

api.test.js:

```<code>import axios from 'axios';
import get from './api';
import SpecialError from './specialError.js';

test('testing the api get method', async () => {
  axios.get.mockImplementation(() => Promise.resolve({
    data: 'response',
    status: 404,
  }));

  const expectedError = new SpecialError('foo');

  await expect(get()).rejects.toEqual(expectedError);
});
</code>```

答:
axios.get is mocked to resolve to an object so get resolves to that object.

It looks like you are testing the error case, in which case axios.get should be mocked to reject:

```<code>import axios from 'axios';
import get from './code';

test('testing the api get method', async () => {
  jest.spyOn(axios, 'get').mockRejectedValue(new Error('error'));
  await expect(get()).rejects.toThrow('error');  // Success!
});
</code>```

Update

OP updated the question to ask how to test for a specific kind of error.

You'll probably want to throw the error like this:

```<code>try {
  // ...
} catch (error) {
  throw new SpecialError(error.message);  // <= just use the error message
}
</code>```

...and SpecialError should probably pass its args to super like this:

```<code>export default class SpecialError extends Error {
  constructor(...args) {
    super(...args);  // <= pass args to super
    this.isSpecialError = true;
  }
}
</code>```

...but given those changes you can test like this:

```<code>import axios from 'axios';
import get from './api';
import SpecialError from './specialError.js';

test('testing the api get method', async () => {
  jest.spyOn(axios, 'get').mockRejectedValue(new Error('the error'));
  const promise = get();
  await expect(promise).rejects.toThrow(SpecialError);  // <= throws a SpecialError...
  await expect(promise).rejects.toThrow('the error');  // <= ...with the correct message
});
</code>```

Note that testing for a particular error type and message is a bit tricky since toThrow lets you check for one or the other, but not both at the same time.  You can get around this limitation by testing for each individually.

Body:
I am trying to write a test that asserts that a specific type of error is thrown with Async / Await and axios. However, when I run my test, I get the following. Why is jest not properly rejecting my promise? Thanks!

Error: expect(received).rejects.toThrow()

Expected received Promise to reject, instead it resolved to value

  {"data": "response", "status": 404}

api.js:

import axios from 'axios';
import SpecialError from './specialError.js';

const get = async () => {
  try {
    const response = await axios.get('sampleUrl', { withCredentials: true });
    return response;
  } catch (error) {
    throw new SpecialError(error);
  }
};

export default get;

specialError.js:

export default class SpecialError extends Error {
  constructor() {
    super();
    this.isSpecialError = true;
  }
}

api.test.js:

import axios from 'axios';
import get from './api';
import SpecialError from './specialError.js';

test('testing the api get method', async () => {
  axios.get.mockImplementation(() => Promise.resolve({
    data: 'response',
    status: 404,
  }));

  const expectedError = new SpecialError('foo');

  await expect(get()).rejects.toEqual(expectedError);
});

Body:
axios.get is mocked to resolve to an object so get resolves to that object.

It looks like you are testing the error case, in which case axios.get should be mocked to reject:

import axios from 'axios';
import get from './code';

test('testing the api get method', async () => {
  jest.spyOn(axios, 'get').mockRejectedValue(new Error('error'));
  await expect(get()).rejects.toThrow('error');  // Success!
});

Update

OP updated the question to ask how to test for a specific kind of error.

You'll probably want to throw the error like this:

try {
  // ...
} catch (error) {
  throw new SpecialError(error.message);  // <= just use the error message
}

...and SpecialError should probably pass its args to super like this:

export default class SpecialError extends Error {
  constructor(...args) {
    super(...args);  // <= pass args to super
    this.isSpecialError = true;
  }
}

...but given those changes you can test like this:

import axios from 'axios';
import get from './api';
import SpecialError from './specialError.js';

test('testing the api get method', async () => {
  jest.spyOn(axios, 'get').mockRejectedValue(new Error('the error'));
  const promise = get();
  await expect(promise).rejects.toThrow(SpecialError);  // <= throws a SpecialError...
  await expect(promise).rejects.toThrow('the error');  // <= ...with the correct message
});

Note that testing for a particular error type and message is a bit tricky since toThrow lets you check for one or the other, but not both at the same time.  You can get around this limitation by testing for each individually.


问:
How can I hook c# fields with Theos
I am trying to use theos to hook some class variables values in ios game. This game is built with unity so I used il2cppdumper to dump classes, methods, and fields for the game. The problem is the output syntax for il2cppdumper is c#. I don't know much c# but it uses a different type of data called "fields". Fields in c# are different from properties in objective c. I want to hook the getter or the setter of a field so I can change its value. How can I do that?</p>

答: In C# you can not hook fields, since they are read and written directly. C# has properties with getters and setters but they are a different member type.</p>

Title: How can I hook c# fields with Theos


问:
Keras, How to get the output of each layer?
I have trained a binary classification model with CNN, and here is my code

```<code>model = Sequential()
model.add(Convolution2D(nb_filters, kernel_size[0], kernel_size[1],
                        border_mode='valid',
                        input_shape=input_shape))
model.add(Activation('relu'))
model.add(Convolution2D(nb_filters, kernel_size[0], kernel_size[1]))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=pool_size))
# (16, 16, 32)
model.add(Convolution2D(nb_filters*2, kernel_size[0], kernel_size[1]))
model.add(Activation('relu'))
model.add(Convolution2D(nb_filters*2, kernel_size[0], kernel_size[1]))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=pool_size))
# (8, 8, 64) = (2048)
model.add(Flatten())
model.add(Dense(1024))
model.add(Activation('relu'))
model.add(Dropout(0.5))
model.add(Dense(2))  # define a binary classification problem
model.add(Activation('softmax'))

model.compile(loss='categorical_crossentropy',
              optimizer='adadelta',
              metrics=['accuracy'])
model.fit(x_train, y_train,
          batch_size=batch_size,
          nb_epoch=nb_epoch,
          verbose=1,
          validation_data=(x_test, y_test))
</code>```

And here, I wanna get the output of each layer just like TensorFlow, how can I do that?

答:
Based on all the good answers of this thread, I wrote a library to fetch the output of each layer. It abstracts all the complexity and has been designed to be as user-friendly as possible:

https://github.com/philipperemy/keract

It handles almost all the edge cases.

Hope it helps!

Body:
I have trained a binary classification model with CNN, and here is my code

model = Sequential()
model.add(Convolution2D(nb_filters, kernel_size[0], kernel_size[1],
                        border_mode='valid',
                        input_shape=input_shape))
model.add(Activation('relu'))
model.add(Convolution2D(nb_filters, kernel_size[0], kernel_size[1]))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=pool_size))
# (16, 16, 32)
model.add(Convolution2D(nb_filters*2, kernel_size[0], kernel_size[1]))
model.add(Activation('relu'))
model.add(Convolution2D(nb_filters*2, kernel_size[0], kernel_size[1]))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=pool_size))
# (8, 8, 64) = (2048)
model.add(Flatten())
model.add(Dense(1024))
model.add(Activation('relu'))
model.add(Dropout(0.5))
model.add(Dense(2))  # define a binary classification problem
model.add(Activation('softmax'))

model.compile(loss='categorical_crossentropy',
              optimizer='adadelta',
              metrics=['accuracy'])
model.fit(x_train, y_train,
          batch_size=batch_size,
          nb_epoch=nb_epoch,
          verbose=1,
          validation_data=(x_test, y_test))

And here, I wanna get the output of each layer just like TensorFlow, how can I do that?


问:
this product didn't install successfully: unable to connect to remote server
I'm trying to install python and WFastCGI using IIS web platform installer it fails and give me this error :

Here is the log :

Link for full log text

答:
As far as I know, we couldn't install the python with fastcgi directly through the platform.

I suggest you could install it by downloading the python installer and using the powershell commnd.

More details, you could refer to below command:

Download and install the python.exe from this url.

Run below command with the powershell.

pip install wfastcgi

More details about how to run python applicaiton on the IIS, you could refer to below article:

https://gist.github.com/dvas0004/3d26c25d614c54ecdf296003d68cddaa


问:
Spring boot java.lang.ClassNotFoundException
I have created a simple spring boot application. I am able to mvn clean install and the jar is getting created successfully. But when I try to run java -jar or mvn spring-boot:run the execution fails with

"Could not find or load main class
  com.xyx.webpage.xyx Caused by:
  java.lang.ClassNotFoundException:
  com.xyx.webpage.xyx"

Please see my pom for more details

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.xyx</groupId>
<artifactId>webpage</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>

<name>webpage</name>
<description>Demo project for Spring Boot</description>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.1.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
    <spring-cloud.version>Greenwich.M3</spring-cloud.version>
    <!-- <start-class>com.xyx.webpage.xyx</start-class> -->
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-rest</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-tomcat</artifactId>
        <scope>provided</scope>
    </dependency>

    <!-- JSTL for JSP -->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
    </dependency>

    <!-- Need this to compile JSP -->
    <dependency>
        <groupId>org.apache.tomcat.embed</groupId>
        <artifactId>tomcat-embed-jasper</artifactId>
        <scope>provided</scope>
    </dependency>

    <!-- Need this to compile JSP,
        tomcat-embed-jasper version is not working, no idea why -->
    <dependency>
        <groupId>org.eclipse.jdt.core.compiler</groupId>
        <artifactId>ecj</artifactId>
        <version>4.6.1</version>
        <scope>provided</scope>
    </dependency>

    <!-- Optional, test for static content, bootstrap CSS-->
    <dependency>
        <groupId>org.webjars</groupId>
        <artifactId>bootstrap</artifactId>
        <version>3.3.7</version>
    </dependency>
</dependencies>

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>${spring-cloud.version}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <configuration>
            <mainClass>com.xyx.webpage.xyx</mainClass>
        </configuration>
        </plugin>
    </plugins>
</build>

<repositories>
    <repository>
        <id>spring-milestones</id>
        <name>Spring Milestones</name>
        <url>https://repo.spring.io/milestone</url>
        <snapshots>
            <enabled>false</enabled>
        </snapshots>
    </repository>
</repositories>

</project>
</code>```

答:
Using this should resolve the issue

In pom.xml, add

```<code>    <properties>
        <start-class>com.hiringcupid.webpage.HiringApplication</start-class>
        ...
    </properties>
</code>```

Remember, I am using Springboot 2

Body:
I have created a simple spring boot application. I am able to mvn clean install and the jar is getting created successfully. But when I try to run java -jar or mvn spring-boot:run the execution fails with

"Could not find or load main class
  com.xyx.webpage.xyx Caused by:
  java.lang.ClassNotFoundException:
  com.xyx.webpage.xyx"

Please see my pom for more details

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.xyx</groupId>
<artifactId>webpage</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>

<name>webpage</name>
<description>Demo project for Spring Boot</description>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.1.RELEASE</version>
    <relativePath/>
</parent>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
    <spring-cloud.version>Greenwich.M3</spring-cloud.version>

</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-rest</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-tomcat</artifactId>
        <scope>provided</scope>
    </dependency>

    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
    </dependency>

    <dependency>
        <groupId>org.apache.tomcat.embed</groupId>
        <artifactId>tomcat-embed-jasper</artifactId>
        <scope>provided</scope>
    </dependency>

    <dependency>
        <groupId>org.eclipse.jdt.core.compiler</groupId>
        <artifactId>ecj</artifactId>
        <version>4.6.1</version>
        <scope>provided</scope>
    </dependency>

    <dependency>
        <groupId>org.webjars</groupId>
        <artifactId>bootstrap</artifactId>
        <version>3.3.7</version>
    </dependency>
</dependencies>

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>${spring-cloud.version}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <configuration>
            <mainClass>com.xyx.webpage.xyx</mainClass>
        </configuration>
        </plugin>
    </plugins>
</build>

<repositories>
    <repository>
        <id>spring-milestones</id>
        <name>Spring Milestones</name>
        <url>https://repo.spring.io/milestone</url>
        <snapshots>
            <enabled>false</enabled>
        </snapshots>
    </repository>
</repositories>

</project>

Body:
Using this should resolve the issue

In pom.xml, add

    <properties>
        <start-class>com.hiringcupid.webpage.HiringApplication</start-class>
        ...
    </properties>

Remember, I am using Springboot 2


问:
positioning problem with uisplitviewcontroller in left view
i got a little problem, when launching my splitview in landscape, there is a little black space above my left view controller:

after rotating my ipad to portrait and switching back to landscape, the space is gone.

if i load the uitableviewcontroller directly into the left view, and not in a navigationcontroller, it works fine:

any ideas why this is happening ??

```<code>// Produkte
    self.produkteMainTableVC = [[produkteMainTableViewController alloc] initWithStyle:UITableViewStylePlain];
    UINavigationController *produkteMainNavigationController = [[UINavigationController alloc] initWithRootViewController:self.produkteMainTableVC];
    self.produkteDetailVC = [[produkteDetailViewController alloc] initWithNibName:@"produkteDetailViewController" bundle:nil];
    self.produkteSplitVC = [[UISplitViewController alloc] init];

    self.produkteSplitVC.delegate = self.produkteDetailVC;
    self.produkteMainTableVC.produkteDetailVC = produkteDetailVC;
    [self.produkteSplitVC setViewControllers:[NSArray arrayWithObjects:produkteMainNavigationController,self.produkteDetailVC,nil]];
</code>```

thanks for all help!

edit:
its exactly 20px like the statusbar. does that help anyone?

edit2:

doing something like this:

```<code>if(self.navigationController.navigationBar.frame.origin.y >= 20.0) {

        self.navigationController.navigationBar.frame = CGRectMake(self.navigationController.navigationBar.frame.origin.x, 0.0, self.navigationController.navigationBar.frame.size.width, self.navigationController.navigationBar.frame.size.height);
    }
</code>```

results that:

a little improvement i would say. but i have no idea how to stick my tableview underneath the navigationbar.

答:
Here's what I did, and it seems to work fine.

I created my own custom tab-view controller, derived from UIViewController.  In viewDidLoad I add a UITabBar to the bottom of the view and set the delegate to myself so I can handle tab changes.  (I return this UITabBar as the rotatingFooterView)  Tab changes result in swapping the current view controller, just like a real UITabBarController.  When swapping view controllers (sometimes a UISplitViewController, hosting a UINavigationController in the master view), I add and position the view-controller's view within my view, above the UITabBar.  I'm also careful to forward viewWill/DidAppear/Disappear calls to the current view controller, as well as each of the will/didRotate messages.

ContentLicense: CC BY-SA 2.5

Body:
i got a little problem, when launching my splitview in landscape, there is a little black space above my left view controller:

after rotating my ipad to portrait and switching back to landscape, the space is gone.

if i load the uitableviewcontroller directly into the left view, and not in a navigationcontroller, it works fine:

any ideas why this is happening ??

// Produkte
    self.produkteMainTableVC = [[produkteMainTableViewController alloc] initWithStyle:UITableViewStylePlain];
    UINavigationController *produkteMainNavigationController = [[UINavigationController alloc] initWithRootViewController:self.produkteMainTableVC];
    self.produkteDetailVC = [[produkteDetailViewController alloc] initWithNibName:@"produkteDetailViewController" bundle:nil];
    self.produkteSplitVC = [[UISplitViewController alloc] init];

    self.produkteSplitVC.delegate = self.produkteDetailVC;
    self.produkteMainTableVC.produkteDetailVC = produkteDetailVC;
    [self.produkteSplitVC setViewControllers:[NSArray arrayWithObjects:produkteMainNavigationController,self.produkteDetailVC,nil]];

thanks for all help!

edit:
its exactly 20px like the statusbar. does that help anyone?

edit2:

doing something like this:

if(self.navigationController.navigationBar.frame.origin.y >= 20.0) {

        self.navigationController.navigationBar.frame = CGRectMake(self.navigationController.navigationBar.frame.origin.x, 0.0, self.navigationController.navigationBar.frame.size.width, self.navigationController.navigationBar.frame.size.height);
    }

results that:

a little improvement i would say. but i have no idea how to stick my tableview underneath the navigationbar.


问:
How to pass file name to two commands in single line
I want to combine two commands in a single line as follows.

I want to execute these two commands.
1. dos2unix dir/file_name
2. git add dir/file_name

I want:

dos_add = dos2unix | git add file_name
so dos_add is my  alias.

in git-bash it should like:
c:\dir(dfsds4343) $ dos_add dir/file.txt

Which executes dos2unix and git add both on a file.

答:
Thanks @WilliamPursell

It can be done by
1. hit this command into gitbash

```<code>gitbash:$ code ~/.gitconfig
</code>```

add following code

```<code>[alias]
    ad = "!ad() { dos2unix.exe "$1" && git add "$1"; }; ad"
</code>```

just use:
gitbash:$ git ad filename.text

Body:
Thanks @WilliamPursell

It can be done by
1. hit this command into gitbash

gitbash:$ code ~/.gitconfig

add following code

[alias]
    ad = "!ad() { dos2unix.exe "$1" && git add "$1"; }; ad"

just use:
gitbash:$ git ad filename.text


问:
Is there a way to apply the application.html.erb layout to the static folders?
I would like to know if there is a way to make the pages in the rails public folder to be rendered as common pages, that are put on the application.html.erb

I tried using render '/file.html', layout: true but it doesn't seem to work.
When I put them to be accessed via link in views, this being link_to 'test file', '/file.html' my application css is applied but if I refresh the page it goes away.

答:
I don't know it will help or not but try making controller for that file.
Example:
Test_Controller

```<code> class TestController < ApplicationController
     def file
          #Read text form the file.. Used in file.html.erb
          @data = File.read("/Desktop/test.txt")
     end
end
</code>```

file.html.erb

```<code> <h1 align="center"> <b>I am in test file action</b> </h1>
 <p class="pcenter"> <%= @data %></p>
</code>```

where you need that file use,

```<code> <%=link_to "File", controller: "Test", action: "file" %>
</code>```

and on routes.rb

```<code>Rails.application.routes.draw do
get 'test/file'
</code>```

Body:
I don't know it will help or not but try making controller for that file.
Example:
Test_Controller

 class TestController < ApplicationController
     def file
          #Read text form the file.. Used in file.html.erb
          @data = File.read("/Desktop/test.txt")
     end
end

file.html.erb

 <h1 align="center"> <b>I am in test file action</b> </h1>
 <p class="pcenter"> <%= @data %></p>

where you need that file use,

 <%=link_to "File", controller: "Test", action: "file" %>

and on routes.rb

Rails.application.routes.draw do
get 'test/file'


问:
Is it possible to force data immutability in a python function?
Say I define a list object and only want it to be read-only in a function I define. In C++, you'd do this with a const reference. Is there any way to do this with a python function? Does this make sense with respect to writing "pythonic" code or am I just trying to apply a C++ paradigm incorrectly?</p>

答:
In Python, all variables are references, so having an equivalent of C's const wouldn't really do anything. If the pointed-to object is mutable, you can mutate it; if it's immutable, you can't.

However, there are some types that are mutable, and some that aren't. Lists are mutable, but tuples are not. So if you pass your data as a tuple, you're guaranteed the function can't do anything to it.

To use a C metaphor, a list of integers is somewhat like an int[], and a tuple of integers is a const int[]. When you pass them to a function, it doesn't matter if you're passing a const reference or a non-const reference; what matters is whether the thing it references is const or not.


问:
entering input causing link change
This sort of links back to a previous question that I made. The goal was to change the iframe src with a text input. After lots of experimentation, it worked. However, this has arisen a new problem. After I enter the link and submit it, it adds /?link=linkhere to the end of the page and refreshes it. Then, once it's refreshed, the original src comes back, making it useless.
Here's the most important code:

```<code> <iframe
  id="minecraftFrame"
  src="//classic.minecraft.net"
  height="500"
  width="800"
  frameborder="0"
  scrolling="no"
  allowfullscreen="true">
</iframe>
<input type="text" id="myInput" name="input">
<button class="button" onclick="changeChannel()">Go</button>
<script>
function changeChannel(){
  document.getElementById("iFrame").src = document.getElementById("myInput").value;
}
</script>
</code>```

I'm unsure of what to try at this point, since I'm not too experienced with javascript. I just don't want the main page to refresh after change the src.

答:
You need to prevent default, i.e. stop event bubbling which is resulting in reload. See if that works for you. Seems like it should as you are submitting the form which would result in refresh of the page.</p>

```<code>function changeChannel() {
  event.preventDefault();
  // ...
}
</code>```

Title: entering input causing link change

Body:
This sort of links back to a previous question that I made. The goal was to change the iframe src with a text input. After lots of experimentation, it worked. However, this has arisen a new problem. After I enter the link and submit it, it adds /?link=linkhere to the end of the page and refreshes it. Then, once it's refreshed, the original src comes back, making it useless.
Here's the most important code:

<input type="text" id="myInput" name="input">
<button class="button" onclick="changeChannel()">Go</button>

I'm unsure of what to try at this point, since I'm not too experienced with javascript. I just don't want the main page to refresh after change the src.

Body:
You need to prevent default, i.e. stop event bubbling which is resulting in reload. See if that works for you. Seems like it should as you are submitting the form which would result in refresh of the page.

function changeChannel() {
  event.preventDefault();
  // ...
}