问:
How to print prime numbers in specific format
I have to ask the user to input a number, and print out the prime factors.

However, this is DIFFERENT from other prime-factor codes as I need to print it in a specific format.

If the user inputs 27, I have to print out

3^3

if the use inputs 28, I have to print out

2^2*7

I know how to print out just the prime factors, so that if the user inputs 27, it would print out

3 3 3

However, I have a hard time trying to figure out how to put in the ^ sign in and the * sign. I figured I would have to count the numbers that are the same and make an if loop(possibly), but I have no clue as to how to do that.

```<code>import java.util.*;

public class Prime{
   public static void main(String[] args) {
      Scanner input= new Scanner (System.in);

      System.out.println("Enter a number");
      int num= input.nextInt();
      String prim = "";

      for (int i = 2; i <= num ; i++) {
         while (num % i == 0) {
            prim += i + " ";
            num /= i;
         }
      }

      System.out.println("Prime factors are: " + prim);

   }

}
</code>```

The code above just prints out the factors, and what I have to do right now is change the format using ^ and *.

Can anyone help me out?

Any help is appreciated.

答:
Here the code frequency of the number is identified which is j variable the and the i represents the value than the frequency is checked for 1 and greater than 1 and its appended correctly to have the format required.

```<code> public static void main(String[] args) {
                 Scanner input= new Scanner (System.in);
                  String result="";
                  System.out.println("Enter a number");
                   int num= input.nextInt();
                  String prim = "";

                  for (int i = 2; i <= num ; i++) {
                      int j=0;
                     while (num % i == 0) {
                        j++;
                        prim += i;
                        num /= i;
                     }
                   if(j>0){
                 if(j>1){
                   result=result+i+"^"+j+"*";
                 }else{
                     result=result+i+"*";
                 }
                }
                  }

                  System.out.println("Prime factors are: " +result.substring(0,result.length()-1));

               }
</code>```

Body:
I have to ask the user to input a number, and print out the prime factors.

However, this is DIFFERENT from other prime-factor codes as I need to print it in a specific format.

If the user inputs 27, I have to print out

3^3

if the use inputs 28, I have to print out

2^2*7

I know how to print out just the prime factors, so that if the user inputs 27, it would print out

3 3 3

However, I have a hard time trying to figure out how to put in the ^ sign in and the * sign. I figured I would have to count the numbers that are the same and make an if loop(possibly), but I have no clue as to how to do that.

import java.util.*;

public class Prime{
   public static void main(String[] args) {
      Scanner input= new Scanner (System.in);

      System.out.println("Enter a number");
      int num= input.nextInt();
      String prim = "";

      for (int i = 2; i <= num ; i++) {
         while (num % i == 0) {
            prim += i + " ";
            num /= i;
         }
      }

      System.out.println("Prime factors are: " + prim);

   }

}

The code above just prints out the factors, and what I have to do right now is change the format using ^ and *.

Can anyone help me out?

Any help is appreciated.

Body:
Here the code frequency of the number is identified which is j variable the and the i represents the value than the frequency is checked for 1 and greater than 1 and its appended correctly to have the format required.

 public static void main(String[] args) {
                 Scanner input= new Scanner (System.in);
                  String result="";
                  System.out.println("Enter a number");
                   int num= input.nextInt();
                  String prim = "";

                  for (int i = 2; i <= num ; i++) {
                      int j=0;
                     while (num % i == 0) {
                        j++;
                        prim += i;
                        num /= i;
                     }
                   if(j>0){
                 if(j>1){
                   result=result+i+"^"+j+"*";
                 }else{
                     result=result+i+"*";
                 }
                }
                  }

                  System.out.println("Prime factors are: " +result.substring(0,result.length()-1));

               }


来源: stackexchange

问:
dialogCornerRadius, fontVariationSettings, ttcIndex... not found after installing and linking dependency to my app

Context

This problems covers android and react-native projects (including Expo ejected ones).

I was working with a recently ejected Expo (React Native) project. I had just installed OneSignal node package to my project.

```<code>npm install react-native-onesignal && react-native link react-native-onsignal
</code>```

Then on my Android project, inside the android/app/build.gradle file (where the sdkNumbers, and dependencies and libs are) I had the following setting:

```<code>  android {
  compileSdkVersion 28
  buildToolsVersion '28.0.0'

  defaultConfig {
    ...
    minSdkVersion 21
    targetSdkVersion 28
    ...
  }
</code>```

...and in the same file, in the dependencies section I had my recently linked lib (onesignal)...

```<code>dependencies {
  compile project(':react-native-onesignal')
  ...
}
</code>```

So, my native Android project is set to be built using the API 28 features (basically that's what all the sdkNumbers set to 28 mean).

Problem

dialogCornerRadius not found.

fontVariationSettings not found.

ttcIndex not found.

The error I am getting when I try to build my Android app is:

```<code>    > Task :react-native-onesignal:verifyReleaseResources FAILED

    FAILURE: Build failed with an exception.

    * What went wrong:
    Execution failed for task ':react-native-onesignal:verifyReleaseResources'.
    > java.util.concurrent.ExecutionException: com.android.builder.internal.aapt.v2.Aapt2Exception: Android resource linking failed
      Output:  /node_modules/react-native-onesignal/android/build/intermediates/res/merged/release/values-v28/values-v28.xml:7:
error: resource android:attr/dialogCornerRadius not found.
      /node_modules/react-native-onesignal/android/build/intermediates/res/merged/release/values-v28/values-v28.xml:11:
error: resource android:attr/dialogCornerRadius not found.
      /node_modules/react-native-onesignal/android/build/intermediates/res/merged/release/values/values.xml:970:
error: resource android:attr/fontVariationSettings not found.
      /node_modules/react-native-onesignal/android/build/intermediates/res/merged/release/values/values.xml:971:
error: resource android:attr/ttcIndex not found.
      error: failed linking references.
</code>```

Trials

I tried to change all my com.android.support libraries to the latest version (28) as well. The problem remained.

I tried to undo the AndroidX migration. The problem changed to some Proguard crazy stuff. Too insane, I came back to AndroidX.

答:
Solution

I just had to update my dependency (onesignal) build.gradle file which was located in the path node_modules/react-native-onesignal/android/build.gradle.

Basically I changed the onesignal's compileSdkVersion from 26

```<code>android {
    compileSdkVersion safeExtGet('compileSdkVersion', 26)
    buildToolsVersion safeExtGet('buildToolsVersion', '26.0.2')
</code>```

to 28

```<code>android {
    compileSdkVersion 28
    buildToolsVersion safeExtGet('buildToolsVersion', '26.0.2')
</code>```

It builds fine and notification works now.

TL; DR

I changed the onesignal's build.gradle compileSdkVersion to same as the main Android build.gradle file.

ContentLicense: CC BY-SA 4.0

Body:
Context

This problems covers android and react-native projects (including Expo ejected ones).

I was working with a recently ejected Expo (React Native) project. I had just installed OneSignal node package to my project.

npm install react-native-onesignal && react-native link react-native-onsignal

Then on my Android project, inside the android/app/build.gradle file (where the sdkNumbers, and dependencies and libs are) I had the following setting:

  android {
  compileSdkVersion 28
  buildToolsVersion '28.0.0'

  defaultConfig {
    ...
    minSdkVersion 21
    targetSdkVersion 28
    ...
  }

...and in the same file, in the dependencies section I had my recently linked lib (onesignal)...

dependencies {
  compile project(':react-native-onesignal')
  ...
}

So, my native Android project is set to be built using the API 28 features (basically that's what all the sdkNumbers set to 28 mean).

Problem

dialogCornerRadius not found.

fontVariationSettings not found.

ttcIndex not found.

The error I am getting when I try to build my Android app is:

    > Task :react-native-onesignal:verifyReleaseResources FAILED

    FAILURE: Build failed with an exception.

    * What went wrong:
    Execution failed for task ':react-native-onesignal:verifyReleaseResources'.
    > java.util.concurrent.ExecutionException: com.android.builder.internal.aapt.v2.Aapt2Exception: Android resource linking failed
      Output:  /node_modules/react-native-onesignal/android/build/intermediates/res/merged/release/values-v28/values-v28.xml:7:
error: resource android:attr/dialogCornerRadius not found.
      /node_modules/react-native-onesignal/android/build/intermediates/res/merged/release/values-v28/values-v28.xml:11:
error: resource android:attr/dialogCornerRadius not found.
      /node_modules/react-native-onesignal/android/build/intermediates/res/merged/release/values/values.xml:970:
error: resource android:attr/fontVariationSettings not found.
      /node_modules/react-native-onesignal/android/build/intermediates/res/merged/release/values/values.xml:971:
error: resource android:attr/ttcIndex not found.
      error: failed linking references.

Trials

I tried to change all my com.android.support libraries to the latest version (28) as well. The problem remained.

I tried to undo the AndroidX migration. The problem changed to some Proguard crazy stuff. Too insane, I came back to AndroidX.

Body:
Solution

I just had to update my dependency (onesignal) build.gradle file which was located in the path node_modules/react-native-onesignal/android/build.gradle.

Basically I changed the onesignal's compileSdkVersion from 26

android {
    compileSdkVersion safeExtGet('compileSdkVersion', 26)
    buildToolsVersion safeExtGet('buildToolsVersion', '26.0.2')

to 28

android {
    compileSdkVersion 28
    buildToolsVersion safeExtGet('buildToolsVersion', '26.0.2')

It builds fine and notification works now.

TL; DR

I changed the onesignal's build.gradle compileSdkVersion to same as the main Android build.gradle file.


问:
Publishing Google Sheet Addon- api_console_project_id error
I am trying to publish Google Sheet Addon just of users of my domain to install manually (not auto install for all users)

I've extracted my code from Google Sheets into a stand-alone script and try to deploy:

Which pops up a Chrome Store Listing draft; which I fill out:

I fill out the long Chrome Store Listing form but when I publish I get:

"There is no API Console project with the id specified in the manifest's api_console_project_id field."

My understanding is if you write your code in Google Script editor (https://script.google.com) that you should not and can not modify the project's manifest file so not sure where to go from here.

答:
Chris was right - you have to configure the G-Suite Marketplace first; I've created instructions based on weeks of trial and error:

https://docs.google.com/document/d/1gG0_EClZC4ztKHDT2yn8v9NmUh_-sqYFe9vGg6Snxgg/edit?usp=sharing


问:
Dereference a pointer in specific case
Can anyone tell me why this piece of code does not work? It always says segmentation fault

```<code>int main()
{
    int a = 10;
    int b = (int)&a;
    int *c = (int*)b;
    printf("%d", *c);

    return 0;
}
</code>```

When I print the value of c, it is the address of a as I expect, but when I deference it, a segmentation fault happens. Assume that this is a 32bit compiler.

答:
a is an int and gets the value 10.

b is an int and gets as a value an int, the address of a casted as an int.

c is a pointer to an int and gets the value b casted to be a pointer to an int.

The value of b was the address of a, but casted as an int.

So c "should" point to a and with *c you "should" get 10. The problem is that on your machine the size of an int and the size of a pointer to an int are not the same and in the first cast you truncated the value of &a to fit into the size of an int and lost some digits of the address.

Now in b there is an int containing only some digit of the address of a and therefore a completely different address , so when you try to access the memory at that address (with *c ) you're not accessing a, but some memory somewhere else that in this case happens to be invalid.

Title: Dereference a pointer in specific case

Body:
Can anyone tell me why this piece of code does not work? It always says segmentation fault

int main()
{
    int a = 10;
    int b = (int)&a;
    int *c = (int*)b;
    printf("%d", *c);

    return 0;
}

When I print the value of c, it is the address of a as I expect, but when I deference it, a segmentation fault happens. Assume that this is a 32bit compiler.


问:
what is the difference between any[] and [] in typescript
So the first example here works,

```<code>protected createGroups(sortedItems: Array<TbpeItem>): any[] {
    let groups: any[] = [];
    return groups;

}
</code>```

but the second one gives a typescript error:
    type any[] not assignable to type []

```<code>protected createGroups(sortedItems: Array<TbpeItem>): [] {
    let groups: any[] = [];
    return groups;

}
</code>```

答: any[] is an array where the item is of type any. [] is the empty tuple. Tuples are represented in typescript as arrays where the type of each position is known (ex [boolean, number] is a tuple where the first item is a boolean and the second is a number). When checking compatibility for tuples the size has to be the same, so this means nothing but [] is assignable to the empty tuple type. Read more about tuples here

Body:
So the first example here works,

protected createGroups(sortedItems: Array<TbpeItem>): any[] {
    let groups: any[] = [];
    return groups;

}

but the second one gives a typescript error:
    type any[] not assignable to type []

protected createGroups(sortedItems: Array<TbpeItem>): [] {
    let groups: any[] = [];
    return groups;

}


问:
How to close a JavaFX application on window close?
In Swing you can simply use setDefaultCloseOperation() to shut down the entire application when the window is closed.

However in JavaFX I can't find an equivalent. I have multiple windows open and I want to close the entire application if a window is closed. What is the way to do that in JavaFX?

Edit:

I understand that I can override setOnCloseRequest() to perform some operation on window close. The question is what operation should be performed to terminate the entire application?

```<code>stage.setOnCloseRequest(new EventHandler<WindowEvent>() {
    @Override
    public void handle(WindowEvent event) {
        stop();
    }
});
</code>```

The stop() method defined in Application class does nothing.

答:
Instead of playing around with onCloseRequest handlers or window events, I prefer calling Platform.setImplicitExit(true) the beginning of the application.

According to JavaDocs:

"If this attribute is true, the JavaFX runtime will implicitly
  shutdown when the last window is closed; the JavaFX launcher will call
  the Application.stop() method and terminate the JavaFX
  application thread."

Example:

@Override
void start(Stage primaryStage) {
    Platform.setImplicitExit(true)
    ...
    // create stage and scene
}
```

ContentLicense: CC BY-SA 3.0

Body:
In Swing you can simply use setDefaultCloseOperation() to shut down the entire application when the window is closed.

However in JavaFX I can't find an equivalent. I have multiple windows open and I want to close the entire application if a window is closed. What is the way to do that in JavaFX?

Edit:

I understand that I can override setOnCloseRequest() to perform some operation on window close. The question is what operation should be performed to terminate the entire application?

stage.setOnCloseRequest(new EventHandler<WindowEvent>() {
    @Override
    public void handle(WindowEvent event) {
        stop();
    }
});

The stop() method defined in Application class does nothing.


问:
Redux Observable / RxJS: How to create custom observable?
I'm trying to do websocket setup in an redux-observable epic, and i'm going with an approach similar to this guy: https://github.com/MichalZalecki/connect-rxjs-to-react/issues/1

However, it looks like my first stab at wiring things up isn't working, even though it looks the same as the guy above:

```<code>import 'rxjs';
import Observable from 'rxjs';

import * as scheduleActions from '../ducks/schedule';

export default function connectSocket(action$, store) {
  return action$.ofType(scheduleActions.CANCEL_RSVP)
    .map(action => {
      new Observable(observer => {
        // do websocket stuff here
        observer.next('message text');
      });
    })
    .map(text => {
      console.log("xxxxxxxxxxxxx: ", text);
      return scheduleActions.rsvpCancelled(1);
    });
};
</code>```

However, I'm getting a Object is not a constructor error:

=== UPDATE ===

Looks like the suggestion to destructure the { Observable } export worked!

Not the only issue is that text doesn't seem to cross over to the next  method...

```<code>import 'rxjs';
import { Observable } from 'rxjs';

import * as scheduleActions from '../ducks/schedule';

export default function connectSocket(action$, store) {
  return action$.ofType(scheduleActions.CANCEL_RSVP)
    .map(action => {
      new Observable(observer => {
        // do websocket stuff here
        observer.next('message text');
      });
    })
    .map(text => {
      console.log("xxxxxxxxxxxxx: ", text); // prints undefined
      return scheduleActions.rsvpCancelled(1);
    });
};
</code>```

答: You can take a look at Demo. Visit at Create Custom Observable</p>

Body:
I'm trying to do websocket setup in an redux-observable epic, and i'm going with an approach similar to this guy: https://github.com/MichalZalecki/connect-rxjs-to-react/issues/1

However, it looks like my first stab at wiring things up isn't working, even though it looks the same as the guy above:

import 'rxjs';
import Observable from 'rxjs';

import * as scheduleActions from '../ducks/schedule';

export default function connectSocket(action$, store) {
  return action$.ofType(scheduleActions.CANCEL_RSVP)
    .map(action => {
      new Observable(observer => {
        // do websocket stuff here
        observer.next('message text');
      });
    })
    .map(text => {
      console.log("xxxxxxxxxxxxx: ", text);
      return scheduleActions.rsvpCancelled(1);
    });
};

However, I'm getting a Object is not a constructor error:

=== UPDATE ===

Looks like the suggestion to destructure the { Observable } export worked!

Not the only issue is that text doesn't seem to cross over to the next  method...

import 'rxjs';
import { Observable } from 'rxjs';

import * as scheduleActions from '../ducks/schedule';

export default function connectSocket(action$, store) {
  return action$.ofType(scheduleActions.CANCEL_RSVP)
    .map(action => {
      new Observable(observer => {
        // do websocket stuff here
        observer.next('message text');
      });
    })
    .map(text => {
      console.log("xxxxxxxxxxxxx: ", text); // prints undefined
      return scheduleActions.rsvpCancelled(1);
    });
};


问:
EWS Oauth login expires, have to login every time application starts
I am having problem in VB.Net code that connects to Mailbox using EWS. A mail account required 2F auth, 2F auth works but the problem is - EWS Oauth login expires, have to login every time application starts.

```<code>Using AcquireTokenSilentAsync, it doesn’t work
authenticationresult = authenticationContext.AcquireTokenSilentAsync(serverName, clientID).Result
</code>```

```<code>AcquireTokenAsync to authenticate
authenticationresult = authenticationContext.AcquireTokenAsync(serverName, clientID, clientAppUri, oPlatformParameters).Result
</code>```

A VB.Net example that solves this will be helpful.

答:
If you already have the access token, why do you need to recreate it every time instead of reusing authenticationresult.AccessToken?

See https://learn.microsoft.com/en-us/exchange/client-developer/exchange-web-services/how-to-authenticate-an-ews-application-by-using-oauth

Body:
I am having problem in VB.Net code that connects to Mailbox using EWS. A mail account required 2F auth, 2F auth works but the problem is - EWS Oauth login expires, have to login every time application starts.

Using AcquireTokenSilentAsync, it doesn’t work
authenticationresult = authenticationContext.AcquireTokenSilentAsync(serverName, clientID).Result

AcquireTokenAsync to authenticate
authenticationresult = authenticationContext.AcquireTokenAsync(serverName, clientID, clientAppUri, oPlatformParameters).Result

A VB.Net example that solves this will be helpful.


问:
Return instance of generic type
I wrote a generic class and want to crate its instance from a static method. The problem is that I can’t create generic instance of the object. I know that it sounds confusing and it is better to show the code.

```<code>public class Parameter<T> : IParameter<T>
{
    public string Name { get; set; }
    public T Value { get; set; }

    public bool IsValid()
    {
        if (String.IsNullOrEmpty(Name))
            return false;

        return (typeof(T) == typeof(String)) ||
               typeof(T) == typeof(bool) ||
               typeof(T) == typeof(int) ||
               typeof(T) == typeof(double);
    }

    public XElement ToXml()
    {
        if (!IsValid())
            throw new InvalidParameterException();

        var xElement = new XElement("Parameter", Value,
                                    new XAttribute("Type", typeof (T)),
                                    new XAttribute("Name", Name));
        return xElement;
    }

    public static Parameter<T> FromXml(XElement xElement)
    {
        var sType = xElement.Attributes()
                    .Where(attribute => attribute.Name == "Type")
                    .Single().Name.ToString();
        var name = xElement.Attributes()
                                .Where(attribute => attribute.Name == "Name")
                                .Single().Name.ToString();
        var sValue = xElement.Value;//need to use this
        var typeVar = Type.GetType(sType);// and this to create proper instance of Parameter<T>

        //I need somehow set T equal to typeVar here and Set
        return new Parameter<T>() {Name = name};//this is wrong.
        //I need return either Parameter<int> or Paramter<double> or Parameter<string> or Parameter<bool>
        //basing on typeVar
    }
}
</code>```

I'm not sure if this possible at all... but looks like it is trivial object design requirement. Any ideas?
Thanks!

UPD: I'm using .NET 4.0. Does it make any difference? :)

UPD2: Looking at the problem now I see that this is a silly question. And it is impossible to return such "generic" objects.

答:
The problem is: T is evaluated at compile time. The compiler does not have any chance to know, to which actual type your 'sType' will evaluate at runtime. Also, in the compiled assembly, no generics exist anymore. Therefore, in order to construct a type at runtime, based on condition which can only get evaluated at runtime, you will have to pesent the compiler a concrete type for compiling anyway. So somewhere you may decide your return type in an if .. else cascade like that:

```<code>if (sType is String)
   return new Parameter<String>()

else if (sType is double)
   return new Parameter<double>()
...
</code>```

This may be placed inside a factory class or right near to the XElement class, I guess.
In order to be able to return Parameter for example, you may use an interface (or a common base class, like in another answer), which may stand for all Parameter variants. This is the reason, why the method, which parses the Xml IMO is better placed outside of Parameter.

Also, since it seems, you are cert of 'deserializing' from XML, consider using some de-/serializer functionality ;)

Title: Return instance of generic type

Body:
I wrote a generic class and want to crate its instance from a static method. The problem is that I can’t create generic instance of the object. I know that it sounds confusing and it is better to show the code.

public class Parameter<T> : IParameter<T>
{
    public string Name { get; set; }
    public T Value { get; set; }

    public bool IsValid()
    {
        if (String.IsNullOrEmpty(Name))
            return false;

        return (typeof(T) == typeof(String)) ||
               typeof(T) == typeof(bool) ||
               typeof(T) == typeof(int) ||
               typeof(T) == typeof(double);
    }

    public XElement ToXml()
    {
        if (!IsValid())
            throw new InvalidParameterException();

        var xElement = new XElement("Parameter", Value,
                                    new XAttribute("Type", typeof (T)),
                                    new XAttribute("Name", Name));
        return xElement;
    }

    public static Parameter<T> FromXml(XElement xElement)
    {
        var sType = xElement.Attributes()
                    .Where(attribute => attribute.Name == "Type")
                    .Single().Name.ToString();
        var name = xElement.Attributes()
                                .Where(attribute => attribute.Name == "Name")
                                .Single().Name.ToString();
        var sValue = xElement.Value;//need to use this
        var typeVar = Type.GetType(sType);// and this to create proper instance of Parameter<T>

        //I need somehow set T equal to typeVar here and Set
        return new Parameter<T>() {Name = name};//this is wrong.
        //I need return either Parameter<int> or Paramter<double> or Parameter<string> or Parameter<bool>
        //basing on typeVar
    }
}

I'm not sure if this possible at all... but looks like it is trivial object design requirement. Any ideas?
Thanks!

UPD: I'm using .NET 4.0. Does it make any difference? :)

UPD2: Looking at the problem now I see that this is a silly question. And it is impossible to return such "generic" objects.

Body:
The problem is: T is evaluated at compile time. The compiler does not have any chance to know, to which actual type your 'sType' will evaluate at runtime. Also, in the compiled assembly, no generics exist anymore. Therefore, in order to construct a type at runtime, based on condition which can only get evaluated at runtime, you will have to pesent the compiler a concrete type for compiling anyway. So somewhere you may decide your return type in an if .. else cascade like that:

if (sType is String)
   return new Parameter<String>()

else if (sType is double)
   return new Parameter<double>()
...

This may be placed inside a factory class or right near to the XElement class, I guess.
In order to be able to return Parameter for example, you may use an interface (or a common base class, like in another answer), which may stand for all Parameter variants. This is the reason, why the method, which parses the Xml IMO is better placed outside of Parameter.

Also, since it seems, you are cert of 'deserializing' from XML, consider using some de-/serializer functionality ;)


答:
Probably the easiest way would be to keep track of all prime factors, count the repetitions for each prime and then print for each prime it's repetitions after ^.

Going with object oriented design you could create your own class that holds information about factor and it's repetitions. Then when you find new factor, instead of appending the string, you either update the counter in existing object corresponding to this factor or you create new one with counter set to 1. Then you iterate over this collection and you just print for each object ^ and * between objects.

Edit: After some thought, you can just repeat division by number and count how many times you can do that. Here's the loop:

```<code>    for (int i = 2; i <= num ; i++) {
        int counter = 0;
        while (num % i == 0) {
            counter ++;
            num /= i;
        }
        if( counter > 0) {
            if( !firstFactor ) {
                prim += "*";
            }
            firstFactor = false;
            prim += i;
            if( counter > 1) {
                prim += "^" + counter;
            }
        }
    }
</code>```

Title: How to print prime numbers in specific format

Body:
Probably the easiest way would be to keep track of all prime factors, count the repetitions for each prime and then print for each prime it's repetitions after ^.

Going with object oriented design you could create your own class that holds information about factor and it's repetitions. Then when you find new factor, instead of appending the string, you either update the counter in existing object corresponding to this factor or you create new one with counter set to 1. Then you iterate over this collection and you just print for each object ^ and * between objects.

Edit: After some thought, you can just repeat division by number and count how many times you can do that. Here's the loop:

    for (int i = 2; i <= num ; i++) {
        int counter = 0;
        while (num % i == 0) {
            counter ++;
            num /= i;
        }
        if( counter > 0) {
            if( !firstFactor ) {
                prim += "*";
            }
            firstFactor = false;
            prim += i;
            if( counter > 1) {
                prim += "^" + counter;
            }
        }
    }


问:
Python Anaconda - How to Safely Uninstall
I installed Python Anaconda on Mac (OS Mavericks). I wanted to revert to the default version of Python on my Mac. What's the best way to do this? Should I delete the ~/anaconda directory? Any other changes required?

Currently when I run which python I get this path:

/Users/username/anaconda/bin/python

答:
```<code>rm -rf ~/anaconda3
</code>```

It was enough

Body:
rm -rf ~/anaconda3

It was enough


问:
Spring boot Application Failed to Start in Linux
Spring boot project can be run in local eclipse and windows environment use -jar. However , in the Linux environment, here are some problems to cause the Application Failed to Start. But the Process is always Running.

Spring Version is 1.5.19 , this is multiple modules project , logs in the Linux server is :

```<code>The web application [ROOT] appears to have started a thread named [CleanCursors-2-thread-1] but has failed to stop it. This is very likely to create a memory leak. Stack trace of thread:

***************************
APPLICATION FAILED TO START
***************************

Description:

The Tomcat connector configured to listen on port 28081 failed to start. The port may already be in use or the connector may be misconfigured.

Action:

Verify the connector's configuration, identify and stop any process that's listening on port 28081, or configure this application to listen on another port.

</code>```

I'm sure the port has not been occupied by any other processes. It make me confused that in the local environment , everything is Ok.

Some code in Pom.xml

```<code><dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <!--exclusions slf4j-log4j12-->
            <exclusions>
                <exclusion>
                    <groupId>org.slf4j</groupId>
                    <artifactId>slf4j-log4j12</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <!-- Spring db template -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <!-- Spring db template -->
        <!-- ${environments.${env}.sslPWD} related -->
        <dependency>
            <groupId>com.github.ulisesbocchio</groupId>
            <artifactId>jasypt-spring-boot-starter</artifactId>
            <version>1.18</version>
        </dependency>
        <!-- ${environments.${env}.sslPWD} related -->
        <!-- Spring boot security -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <!-- Spring boot security -->
        <!-- Monitor Spring boot app -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <!-- Monitor Spring boot app -->
</code>```

Hope Linux server no errors.

答:
Had the same problem today, turns out i had one springboot docker container that i forgot about and it was still running and it was blocking the port in which Tomcat would start.

please run the following commands in your terminal:

sudo ss -tulpn | grep LISTEN

Also, install lsof and run: lsof -i :28081 to see if any process is listening on the port.

Body:
Spring boot project can be run in local eclipse and windows environment use -jar. However , in the Linux environment, here are some problems to cause the Application Failed to Start. But the Process is always Running.

Spring Version is 1.5.19 , this is multiple modules project , logs in the Linux server is :

The web application [ROOT] appears to have started a thread named [CleanCursors-2-thread-1] but has failed to stop it. This is very likely to create a memory leak. Stack trace of thread:

***************************
APPLICATION FAILED TO START
***************************

Description:

The Tomcat connector configured to listen on port 28081 failed to start. The port may already be in use or the connector may be misconfigured.

Action:

Verify the connector's configuration, identify and stop any process that's listening on port 28081, or configure this application to listen on another port.

I'm sure the port has not been occupied by any other processes. It make me confused that in the local environment , everything is Ok.

Some code in Pom.xml

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>

            <exclusions>
                <exclusion>
                    <groupId>org.slf4j</groupId>
                    <artifactId>slf4j-log4j12</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>

        <dependency>
            <groupId>com.github.ulisesbocchio</groupId>
            <artifactId>jasypt-spring-boot-starter</artifactId>
            <version>1.18</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>

Hope Linux server no errors.


问:
How to correctly set the Uri of an image from a folder selected by the user to show in an ImageView?
I need to display an image which I know the file name but I don't know the folder, which must be specified by the user.

I use Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE); to get the folder from the user. It returns an Uri with a path along these lines:

content://com.android.externalstorage.documents/tree/primary%3ADownload

Now I need to display an image from this folder in an ImageView. I tried the following:

```<code>Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(),
Uri.parse(chosenFolder + "/image.png"));
ImageView imageView = findViewById(R.id.imageview);
imageView.setImageBitmap(bitmap);
</code>```

The first line throws the following exception:

java.lang.IllegalArgumentException: Invalid URI: content://com.android.externalstorage.documents/tree/primary%3ADownload/image.png

Replacing %3A by : doesn't work.

How to correctly set the Uri to display the image?

答:
i think you should use file path and not URI . A content:// Uri does not have to represent a file on the filesystem .

try this :

```<code>String filePath = null;
if (chosenFolder != null && "content".equals(chosenFolder.getScheme())) {
    Cursor cursor = this.getContentResolver().query(chosenFolder, new String[] { android.provider.MediaStore.Images.ImageColumns.DATA }, null, null, null);
    cursor.moveToFirst();
    filePath = cursor.getString(0);
    cursor.close();
} else {
    filePath = chosenFolder.getPath();
}
</code>```

and then create bitmap with file path :

```<code>Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(),
Uri.parse(filepath+ "/image.png"));
</code>```

Body:
I need to display an image which I know the file name but I don't know the folder, which must be specified by the user.

I use Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE); to get the folder from the user. It returns an Uri with a path along these lines:

content://com.android.externalstorage.documents/tree/primary%3ADownload

Now I need to display an image from this folder in an ImageView. I tried the following:

Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(),
Uri.parse(chosenFolder + "/image.png"));
ImageView imageView = findViewById(R.id.imageview);
imageView.setImageBitmap(bitmap);

The first line throws the following exception:

java.lang.IllegalArgumentException: Invalid URI: content://com.android.externalstorage.documents/tree/primary%3ADownload/image.png

Replacing %3A by : doesn't work.

How to correctly set the Uri to display the image?

Body:
i think you should use file path and not URI . A content:// Uri does not have to represent a file on the filesystem .

try this :

String filePath = null;
if (chosenFolder != null && "content".equals(chosenFolder.getScheme())) {
    Cursor cursor = this.getContentResolver().query(chosenFolder, new String[] { android.provider.MediaStore.Images.ImageColumns.DATA }, null, null, null);
    cursor.moveToFirst();
    filePath = cursor.getString(0);
    cursor.close();
} else {
    filePath = chosenFolder.getPath();
}

and then create bitmap with file path :

Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(),
Uri.parse(filepath+ "/image.png"));


问:
IModuleNotFoundError: No module named 'django' in VS Code editor while no problem with terminal
I'm new to django, and want to use it in VS Code. However, "ModuleNotFoundError: No module named 'django'" blocked me.

I've pip installed virtual environment, it worked fine in terminal.

on terminal, it shows:

```<code>(myenv) Kates-MacBook:~ kate.wang$ python3
Python 3.7.1 (v3.7.1:260ec2c36a, Oct 20 2018, 03:13:28)
[Clang 6.0 (clang-600.0.57)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import django
>>> from django.shortcuts import render
>>>
</code>```

on VS Code, it outputs:

```<code>[Running] python -u "/Users/kate.wang/myenv/my_django_project/blog/views.py"
Traceback (most recent call last):
File "/Users/kate.wang/myenv/my_django_project/blog/views.py", line 1, in <module>
from django.shortcuts import render
ModuleNotFoundError: No module named 'django'
</code>```

My VS Code Settings are:

```<code>{
"workbench.iconTheme": "vs-minimal",
"editor.fontSize": 15,
"editor.fontLigatures": true,
"terminal.integrated.fontSize": 14,
"workbench.startupEditor": "newUntitledFile",
"workbench.activityBar.visible": true,
"python.dataScience.sendSelectionToInteractiveWindow": true,
"workbench.sideBar.location": "left",
"workbench.colorTheme": "Visual Studio Dark",
"editor.minimap.enabled": false,
"kite.showWelcomeNotificationOnStartup": false,
"python.pythonPath": "python3.7",
"python.venvPath": "/Users/kate.wang/myenv"
</code>```

}

This problem has bothered me for days since I've been trying different solutions from stackoverflow and other websites the first time it poped up and didn't find a way to solve it.

Thank you for your time to help me.

答:
You are not using your virtual environment's python in python.pythonPath. You need to change it to:

```<code>"python.pythonPath": "/Users/kate.wang/myenv/bin/python",
</code>```

Body:
I'm new to django, and want to use it in VS Code. However, "ModuleNotFoundError: No module named 'django'" blocked me.

I've pip installed virtual environment, it worked fine in terminal.

on terminal, it shows:

(myenv) Kates-MacBook:~ kate.wang$ python3
Python 3.7.1 (v3.7.1:260ec2c36a, Oct 20 2018, 03:13:28)
[Clang 6.0 (clang-600.0.57)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import django
>>> from django.shortcuts import render
>>>

on VS Code, it outputs:

[Running] python -u "/Users/kate.wang/myenv/my_django_project/blog/views.py"
Traceback (most recent call last):
File "/Users/kate.wang/myenv/my_django_project/blog/views.py", line 1, in <module>
from django.shortcuts import render
ModuleNotFoundError: No module named 'django'

My VS Code Settings are:

{
"workbench.iconTheme": "vs-minimal",
"editor.fontSize": 15,
"editor.fontLigatures": true,
"terminal.integrated.fontSize": 14,
"workbench.startupEditor": "newUntitledFile",
"workbench.activityBar.visible": true,
"python.dataScience.sendSelectionToInteractiveWindow": true,
"workbench.sideBar.location": "left",
"workbench.colorTheme": "Visual Studio Dark",
"editor.minimap.enabled": false,
"kite.showWelcomeNotificationOnStartup": false,
"python.pythonPath": "python3.7",
"python.venvPath": "/Users/kate.wang/myenv"

}

This problem has bothered me for days since I've been trying different solutions from stackoverflow and other websites the first time it poped up and didn't find a way to solve it.

Thank you for your time to help me.

Body:
You are not using your virtual environment's python in python.pythonPath. You need to change it to:

"python.pythonPath": "/Users/kate.wang/myenv/bin/python",


问:
Iterate Mediator over json arrays
I'd like to iterate the results array of a json message

```<code>{
   "results":[
      {
         "category":"mdl",
         "subcategory":"ip",
         "ip":"103.14.120.121",
         "subtype":"IP-MDL",
         "date":"1405074556",
         "longitude":"75.3333",
         "latitude":"19.8833",
         "country":"India",
         "city":"Aurangabad",
         "organization":"Good Domain Registry Private Limited",
         "isp":"Good Domain Registry Private Limited"
      },
      {
         "category":"mdl",
         "subcategory":"ip",
         "ip":"108.162.198.96",
         "subtype":"IP-MDL",
         "date":"1405074556",
         "longitude":"-122.3933",
         "latitude":"37.7697",
         "country":"United States",
         "city":"San Francisco",
         "organization":"CloudFlare",
         "isp":"CloudFlare"
      }
   ]
}
</code>```

unfortunately iteration mediator doesn't seem to accept non xpath expression
anyone knows how to iterate over the previous message json results the same way i do it in xml ?
I'd like to use ESB json-native support but doesn't seem to be able to break down json messages as with XML (i've tried iterate mediator, json payload factory and script mediator without any success)

```<code>            <iterate expression="json-eval(results)">
               <target>
                  <sequence>
                     <property name="messageType" value="application/json" scope="axis2"/>
                     <payloadFactory media-type="json">
<format>
{
"event":{
"providerName":"$1",
"providerSource":"$2",
"providerClassification":"$3",
"providerVersion":"$4",
"body":{
"results":{$5}
}
}
}
</format>
<args>
                                <arg value="bdigital"/>
                                <arg evaluator="json" expression="$.results.category"/>
<arg evaluator="json" expression="$.results.subcategory"/>
                                <arg value="1.0"/>
                                <arg evaluator="json" expression="$.results"/>
</args>
</payloadFactory>
                     <call>
                        <endpoint>
                           <http method="post"
                                 uri-template="http://BD-VM-PP-CIC01:8280/services/CICQueue"/>
                        </endpoint>
                     </call>
                  </sequence>
               </target>
            </iterate>
</code>```

thanks in advance,

答:
There is a new version in WSO2 EI in which you can iterate over JSON using JSON Path. You can do something like below.

```<code>         <iterate id="iterate-over-users" preservePayload="true" attachPath="json-eval($.results)" expression="json-eval($.results)">
            <target>
               <sequence>
                  <send>
                     <endpoint>
                        <http method="POST" uri-template="http://backend.com"/>
                     </endpoint>
                  </send>
               </sequence>
            </target>
         </iterate>
</code>```

Refer to the following blog for more info. https://medium.com/@arunans23/iterate-over-json-payload-with-wso2-enterprise-integrator-8ccb9cdd2c70

Title: Iterate Mediator over json arrays

Body:
I'd like to iterate the results array of a json message

{
   "results":[
      {
         "category":"mdl",
         "subcategory":"ip",
         "ip":"103.14.120.121",
         "subtype":"IP-MDL",
         "date":"1405074556",
         "longitude":"75.3333",
         "latitude":"19.8833",
         "country":"India",
         "city":"Aurangabad",
         "organization":"Good Domain Registry Private Limited",
         "isp":"Good Domain Registry Private Limited"
      },
      {
         "category":"mdl",
         "subcategory":"ip",
         "ip":"108.162.198.96",
         "subtype":"IP-MDL",
         "date":"1405074556",
         "longitude":"-122.3933",
         "latitude":"37.7697",
         "country":"United States",
         "city":"San Francisco",
         "organization":"CloudFlare",
         "isp":"CloudFlare"
      }
   ]
}

unfortunately iteration mediator doesn't seem to accept non xpath expression
anyone knows how to iterate over the previous message json results the same way i do it in xml ?
I'd like to use ESB json-native support but doesn't seem to be able to break down json messages as with XML (i've tried iterate mediator, json payload factory and script mediator without any success)

            <iterate expression="json-eval(results)">
               <target>
                  <sequence>
                     <property name="messageType" value="application/json" scope="axis2"/>
                     <payloadFactory media-type="json">
<format>
{
"event":{
"providerName":"$1",
"providerSource":"$2",
"providerClassification":"$3",
"providerVersion":"$4",
"body":{
"results":{$5}
}
}
}
</format>
<args>
                                <arg value="bdigital"/>
                                <arg evaluator="json" expression="$.results.category"/>
<arg evaluator="json" expression="$.results.subcategory"/>
                                <arg value="1.0"/>
                                <arg evaluator="json" expression="$.results"/>
</args>
</payloadFactory>
                     <call>
                        <endpoint>
                           <http method="post"
                                 uri-template="http://BD-VM-PP-CIC01:8280/services/CICQueue"/>
                        </endpoint>
                     </call>
                  </sequence>
               </target>
            </iterate>

thanks in advance,

Body:
There is a new version in WSO2 EI in which you can iterate over JSON using JSON Path. You can do something like below.

         <iterate id="iterate-over-users" preservePayload="true" attachPath="json-eval($.results)" expression="json-eval($.results)">
            <target>
               <sequence>
                  <send>
                     <endpoint>
                        <http method="POST" uri-template="http://backend.com"/>
                     </endpoint>
                  </send>
               </sequence>
            </target>
         </iterate>

Refer to the following blog for more info. https://medium.com/@arunans23/iterate-over-json-payload-with-wso2-enterprise-integrator-8ccb9cdd2c70


问:
The navigation prop is missing for this navigator react navigation 3.x

I am new to react native and I am using React navigation 3.x.  This is
  my project structure.

```<code> Mydemo
  ----routes
      --Home.route.js
  ----src
      --pages
        --AddUser.js
  ----App.js
</code>```

Below I am sharing my route configurations:-

Home.route.js code:-

```<code>import { createStackNavigator, createAppContainer } from "react-navigation";
import AddUser from '../src/pages/AddUser';

const HomeStack = createStackNavigator({
        Add:{
            screen: AddUser
        }
    })

export default createAppContainer(HomeStack);
</code>```

App.js Code:-

```<code>import {createSwitchNavigator} from 'react-navigation';

import HomeStack from './routes/Home.route';

export default createSwitchNavigator({
  Home: HomeStack
}, {
  initialRouteName: 'Home',
});
</code>```

But I am getting this error:-

The navigation prop is missing for this navigator.

can anyone please guide me about what I am doing wrong ?
Thank you.

答:
createAppContainer must be on top of your navigation config =>

Home.route.js

```<code>import { createStackNavigator } from "react-navigation";
import AddUser from '../src/pages/AddUser';

export default createStackNavigator({
    Add: AddUser
})
</code>```

App.js

```<code>import {createSwitchNavigator, createAppContainer} from 'react-navigation';

import HomeStack from './routes/Home.route';

const AppNavigator = createSwitchNavigator({
  Home: HomeStack
}, {
  initialRouteName: 'Home',
});

export default createAppContainer(AppNavigator);
</code>```

Body:
I am new to react native and I am using React navigation 3.x.  This is
  my project structure.

 Mydemo
  ----routes
      --Home.route.js
  ----src
      --pages
        --AddUser.js
  ----App.js

Below I am sharing my route configurations:-

Home.route.js code:-

import { createStackNavigator, createAppContainer } from "react-navigation";
import AddUser from '../src/pages/AddUser';

const HomeStack = createStackNavigator({
        Add:{
            screen: AddUser
        }
    })

export default createAppContainer(HomeStack);

App.js Code:-

import {createSwitchNavigator} from 'react-navigation';

import HomeStack from './routes/Home.route';

export default createSwitchNavigator({
  Home: HomeStack
}, {
  initialRouteName: 'Home',
});

But I am getting this error:-

The navigation prop is missing for this navigator.

can anyone please guide me about what I am doing wrong ?
Thank you.

Body:
createAppContainer must be on top of your navigation config =>

Home.route.js

import { createStackNavigator } from "react-navigation";
import AddUser from '../src/pages/AddUser';

export default createStackNavigator({
    Add: AddUser
})

App.js

import {createSwitchNavigator, createAppContainer} from 'react-navigation';

import HomeStack from './routes/Home.route';

const AppNavigator = createSwitchNavigator({
  Home: HomeStack
}, {
  initialRouteName: 'Home',
});

export default createAppContainer(AppNavigator);


问:
Layout with 2 columns and 2 rows
I have a .container
with 2 columns and in the second column .right I want to have 2 rows
but the first row .content should use the remaining space

this is the HTML markup

```<code><div class="container">
    <div class="left">left</div>
    <div class="right">
        <div class="content">content</div>
        <div class="footer">footer</div>
    </div>
</div>
</code>```

this is the CSS

```<code>.container {
    display: flex;
    flex-direction: row;
    height: 400px; /* the remaining space  in the screen will be nice */
}

.left {
    width: 300px;
}

.right {
    flex-grow: 1;
}

.content {
    align-self: stretch; /* this is not doing anything*/
}

.footer {

}
</code>```

and this is how it should look

```<code>+--------+----------------------+
|        |                      |
|        |                      |
|        |       content        |
|  left  |                      |
|        |                      |
|        +----------------------+
|        |       footer         |
+--------+----------------------+
</code>```

答:
Working example jsfiddle</p>

```<code>.container {
    display: flex;
    flex-direction: row;
    height: 100VH;
}

.left {
    width: 200px;
    border: 1px solid;
}

.right {
    flex-grow: 1;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
}

.content {
    border: 1px solid #333;
    border-bottom: 0;
    flex-grow: 1;

}

.footer {
    border: 2px solid;
    height: 100px;
}
</code>```

Title: Layout with 2 columns and 2 rows

Body:
I have a .container
with 2 columns and in the second column .right I want to have 2 rows
but the first row .content should use the remaining space

this is the HTML markup

left

content

footer

this is the CSS

.container {
    display: flex;
    flex-direction: row;
    height: 400px; /* the remaining space  in the screen will be nice */
}

.left {
    width: 300px;
}

.right {
    flex-grow: 1;
}

.content {
    align-self: stretch; /* this is not doing anything*/
}

.footer {

}

and this is how it should look

+--------+----------------------+
|        |                      |
|        |                      |
|        |       content        |
|  left  |                      |
|        |                      |
|        +----------------------+
|        |       footer         |
+--------+----------------------+

Body:
Working example jsfiddle

.container {
    display: flex;
    flex-direction: row;
    height: 100VH;
}

.left {
    width: 200px;
    border: 1px solid;
}

.right {
    flex-grow: 1;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
}

.content {
    border: 1px solid #333;
    border-bottom: 0;
    flex-grow: 1;

}

.footer {
    border: 2px solid;
    height: 100px;
}


问:
Passing a column name as an argument for KDB select query?
I would like to pass a column name into a Q function to query a loaded table.

Example:

```<code>getDistinct:{[x] select count x from raw}
getDistinct "HEADER"
</code>```

This doesn't work as the Q documentation says I cannot pass column as arguments. Is there a way to bypass this?

答:
When q interprets x it will treat it as a string, it has no reference to the column, so your output would just be count "HEADER".

If you want to pass in the column as a string you need to build the whole select statement then use value

```<code>{value "select count  ",x," from tab"} "HEADER"
</code>```

However, the recommended method would be to use a functional select. Below I use parse to build the functional select equivalent using the parse tree.

```<code>/Create sample table
tab:([]inst:10?`MSFT`GOOG`AAPL;time:10?.z.p;price:10?10f)

/Generate my parse tree to get my functional form
.Q.s parse "select count i by inst from tab"

/Build this into my function
{?[`tab;();(enlist x)!enlist x;(enlist `countDistinct)!enlist (#:;`i)]} `inst
</code>```

Note that you have to pass the column in as a symbol. Additionally the #:i is just the k equivalent to count i.

Update for multiple columns

```<code>tab:([]inst:10?`MSFT`GOOG`AAPL;time:10?.z.p;price:10?10f;cntr:10`HK`SG`UK`US)
{?[`tab;();(x)!x;(enlist `countDistinct)!enlist (#:;`i)]} `inst`cntr
</code>```

Body:
I would like to pass a column name into a Q function to query a loaded table.

Example:

getDistinct:{[x] select count x from raw}
getDistinct "HEADER"

This doesn't work as the Q documentation says I cannot pass column as arguments. Is there a way to bypass this?

Body:
When q interprets x it will treat it as a string, it has no reference to the column, so your output would just be count "HEADER".

If you want to pass in the column as a string you need to build the whole select statement then use value

{value "select count  ",x," from tab"} "HEADER"

However, the recommended method would be to use a functional select. Below I use parse to build the functional select equivalent using the parse tree.

/Create sample table
tab:([]inst:10?`MSFT`GOOG`AAPL;time:10?.z.p;price:10?10f)

/Generate my parse tree to get my functional form
.Q.s parse "select count i by inst from tab"

/Build this into my function
{?[`tab;();(enlist x)!enlist x;(enlist `countDistinct)!enlist (#:;`i)]} `inst

Note that you have to pass the column in as a symbol. Additionally the #:i is just the k equivalent to count i.

Update for multiple columns

tab:([]inst:10?`MSFT`GOOG`AAPL;time:10?.z.p;price:10?10f;cntr:10`HK`SG`UK`US)
{?[`tab;();(x)!x;(enlist `countDistinct)!enlist (#:;`i)]} `inst`cntr


问:
How to get last sunday's date from today's date using shell script?
I want to print the date of last Sunday by taking today's date as input for all days of the week except Sunday, but if it is Sunday then it should print today's date.  I tried this,

```<code>a=`date -dlast-sunday +%Y%m%d`
</code>```

but this gives a date of Sunday before the last one.

答:
Could you please try following.</p>

```<code>cal |
awk -v dat=$(date +%d) '
{
  for(i=1;i<=NF;i++){
    if($i==dat){
      if(i!=1){
         print "Last Sunday is: "$1
      }
      else{
         print "This day itself is Sunday."
      }
    }
  }
}'
</code>```

Body:
I want to print the date of last Sunday by taking today's date as input for all days of the week except Sunday, but if it is Sunday then it should print today's date.  I tried this,

a=`date -dlast-sunday +%Y%m%d`

but this gives a date of Sunday before the last one.

Body:
Could you please try following.

cal |
awk -v dat=$(date +%d) '
{
  for(i=1;i<=NF;i++){
    if($i==dat){
      if(i!=1){
         print "Last Sunday is: "$1
      }
      else{
         print "This day itself is Sunday."
      }
    }
  }
}'


问:
Ajax URL not correct with subfolder implemented
I implemented my project in a subfolder. I am putting it in /var/www/html/subfolder

The link to my subfolder project looks like this

https://mytestingsite.com/subfolder

Ajax

```<code>$.ajax({
  url: "/subfolder/testroute",
  data: data,
  dataType: json
});
</code>```

When i call an ajax, my url will be

url : "/subfolder/testroute"

But the url return https://mytestingsite.com/testroute

I exptected the url return as https://mytestingsite.com/subfolder/testroute

I found that if i put my url as

url : "/subfolder/subfolder/testroute"

Then the url only will return https://mytestingsite.com/subfolder/testroute

Is anything wrong with my route?

答:
Try this:</p>

```<code>var baseurl = window.location.protocol + "//" + window.location.host;

$.ajax({
  url: baseurl + "/subfolder/testroute",
  data: data,
  dataType: json
});
</code>```

Body:
I implemented my project in a subfolder. I am putting it in /var/www/html/subfolder

The link to my subfolder project looks like this

https://mytestingsite.com/subfolder

Ajax

$.ajax({
  url: "/subfolder/testroute",
  data: data,
  dataType: json
});

When i call an ajax, my url will be

url : "/subfolder/testroute"

But the url return https://mytestingsite.com/testroute

I exptected the url return as https://mytestingsite.com/subfolder/testroute

I found that if i put my url as

url : "/subfolder/subfolder/testroute"

Then the url only will return https://mytestingsite.com/subfolder/testroute

Is anything wrong with my route?

Body:
Try this:

var baseurl = window.location.protocol + "//" + window.location.host;

$.ajax({
  url: baseurl + "/subfolder/testroute",
  data: data,
  dataType: json
});


问:
Multiple nested elements inside div with fixed height
```<code><div id=“maincontainer”>
    <div>Some data</div>
    <div id = "imagecontainer"> My image is here</div>
    <div id = “button-row”>
        <button id=“imagebutton” class="selected" type="button">Image</button>
        <button id=“videobutton” type="button">Video</button>
    </div>
</div>
</code>```

My parent div #maincontainer has fixed height - 200 px and width.
It is probably not a good practice to make height fixed, however, this is required for me to resolve another issue.

How can I make all child elements to fit into this container?

Before setting the size to 200 px, all child elements fitted well into #maincontainer. However, after setting fixed height, I can see that my #imagecontainer and #button-row overflowing my parent container.

Do I need to set height to all child elements?

What if I have multiple nested child containers inside of my main container?

答:
It is easy, we can fix all inner elements under the main div.

The first step is: Add position relative property in outer div.

The second step is: Add position absolute in every inner div(elements) which you want fixed.

Body:
Some data

 My image is here

        <button id=“imagebutton” class="selected" type="button">Image</button>
        <button id=“videobutton” type="button">Video</button>

My parent div #maincontainer has fixed height - 200 px and width.
It is probably not a good practice to make height fixed, however, this is required for me to resolve another issue.

How can I make all child elements to fit into this container?

Before setting the size to 200 px, all child elements fitted well into #maincontainer. However, after setting fixed height, I can see that my #imagecontainer and #button-row overflowing my parent container.

Do I need to set height to all child elements?

What if I have multiple nested child containers inside of my main container?


问:
Access promise resolve in on click handler in React
This use case has three steps:

1.Make API call to check if record exists

2.If record exists, then ask user if they want to add it to a group

3.If user clicks ok on the displayed modal where we ask them, continue with another network request.

I am trying to get User Input using a modal confirm written in a custom component and based on the fact if user clicks Ok or cancel, I want to make a network request.

I cannot get access to the promise resolve function, even if I assign it to a variable that is accessible by the "onClick" handler.

I've already tried to access the promise resolve function inside the onClick handler of the button that the user clicks. It turns out to be undefined.

getUserResponse is sent as an argument to another function that exists in a separate JS file where all network calls are made. It is being called there after the record has been found to exist as a result of an API call

```<code>let outsideResolve;
const getUserResponse = async () => {
    return await new Promise((resolve, reject) => {
      outsideResolve = resolve;
    });
  };

const confirmAddRecord = event => {
    event.preventDefault();
    //resolve the promise after the button click
    outsideResolve(); //error: outsideResolve is not a function
    };

return (
      <div>
        <p>Record Exists would you like to add them to the group?</p>
        <button onClick={confirmAddRecord}>Add Existing record !</button>
      </div>
    );

*********************************
in another file (networkCalls.js), getUserResponse is sent
as an argument to a method called in the file summarized above
try {
    let userResponse = await getUserResponse();
    console.log(userResponse);
    //Do more stuff after the reply comes in
  } catch (error) {
    console.log(error);
  }
</code>```

I have created a codeSandbox to re-create the problem in more detail:
https://codesandbox.io/s/promisemodal-tke67

答:
If I understood you correctly - main issue that you had is getting access to info from your original (check if user exists) API call. Based on that returned info you wanted to take another action.

Please see my solution to your issue (tested on your codesandbox). Here is a fork of it with implementation (https://codesandbox.io/s/promisemodal-z2r5i)

index.js below

```<code>import React, { useState } from "react";
import ReactDOM from "react-dom";

import {
  ADD_NEW_RECORD,
  MAKE_API_CALL_AFTER_RECORD_CHECK
} from "./networkCalls";

import "./styles.css";

function App() {
  const [isModalOpen, setIsModelOpen] = useState(false);
  const [infoFromCreateRecord, setInfoFromCreateRecord] = useState({});

  const createRecord = () => {
    ADD_NEW_RECORD(isModalOpen, setIsModelOpen, setInfoFromCreateRecord);
  };

  const confirmAddRecord = () => {
    MAKE_API_CALL_AFTER_RECORD_CHECK(infoFromCreateRecord);
    setIsModelOpen(false);
  };

  const renderModal = () => {
    return (
      <div>
        <p>Record Exists would you like to add them to the group?</p>
        <button onClick={confirmAddRecord}>Add Existing record !</button>
      </div>
    );
  };

  return (
    <div className="App">
      <p>Add record by pressing this button</p>
      <button onClick={createRecord}>Create record </button>
      {isModalOpen ? renderModal() : ""}
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
</code>```

networkCalls.js below

```<code>export const ADD_NEW_RECORD = (
  isModalOpen,
  setIsModalOpen,
  setInfoFromCreateRecord
) => {
  //checking from an API of record exists

  const checkIfRecordExists = new Promise((resolve, reject) => {
    setTimeout(() => {
      console.log("Record Exists");
      resolve("Record Exists");
    }, 1000);
  });

  //record exists, ask the user if they want to add them to the group
  checkIfRecordExists.then(() => {
    setInfoFromCreateRecord({
      importantInfo: "record does exits"
    });
    setIsModalOpen(!isModalOpen);
  });
};

export const MAKE_API_CALL_AFTER_RECORD_CHECK = infoFromCreateRecord => {
  // do some stuff with the info from the first API call

  const doSomethingAfterRecordCheck = new Promise((resolve, reject) => {
    setTimeout(() => {
      console.log(infoFromCreateRecord);
      resolve("User got added to the group!");
    }, 1000);
  });

  doSomethingAfterRecordCheck.then(() => {
    console.log("do something after adding the user to the group");
  });
};
</code>```

Body:
This use case has three steps:

1.Make API call to check if record exists

2.If record exists, then ask user if they want to add it to a group

3.If user clicks ok on the displayed modal where we ask them, continue with another network request.

I am trying to get User Input using a modal confirm written in a custom component and based on the fact if user clicks Ok or cancel, I want to make a network request.

I cannot get access to the promise resolve function, even if I assign it to a variable that is accessible by the "onClick" handler.

I've already tried to access the promise resolve function inside the onClick handler of the button that the user clicks. It turns out to be undefined.

getUserResponse is sent as an argument to another function that exists in a separate JS file where all network calls are made. It is being called there after the record has been found to exist as a result of an API call

let outsideResolve;
const getUserResponse = async () => {
    return await new Promise((resolve, reject) => {
      outsideResolve = resolve;
    });
  };

const confirmAddRecord = event => {
    event.preventDefault();
    //resolve the promise after the button click
    outsideResolve(); //error: outsideResolve is not a function
    };

return (

Record Exists would you like to add them to the group?

        <button onClick={confirmAddRecord}>Add Existing record !</button>

    );

*********************************
in another file (networkCalls.js), getUserResponse is sent
as an argument to a method called in the file summarized above
try {
    let userResponse = await getUserResponse();
    console.log(userResponse);
    //Do more stuff after the reply comes in
  } catch (error) {
    console.log(error);
  }

I have created a codeSandbox to re-create the problem in more detail:
https://codesandbox.io/s/promisemodal-tke67

Body:
If I understood you correctly - main issue that you had is getting access to info from your original (check if user exists) API call. Based on that returned info you wanted to take another action.

Please see my solution to your issue (tested on your codesandbox). Here is a fork of it with implementation (https://codesandbox.io/s/promisemodal-z2r5i)

index.js below

import React, { useState } from "react";
import ReactDOM from "react-dom";

import {
  ADD_NEW_RECORD,
  MAKE_API_CALL_AFTER_RECORD_CHECK
} from "./networkCalls";

import "./styles.css";

function App() {
  const [isModalOpen, setIsModelOpen] = useState(false);
  const [infoFromCreateRecord, setInfoFromCreateRecord] = useState({});

  const createRecord = () => {
    ADD_NEW_RECORD(isModalOpen, setIsModelOpen, setInfoFromCreateRecord);
  };

  const confirmAddRecord = () => {
    MAKE_API_CALL_AFTER_RECORD_CHECK(infoFromCreateRecord);
    setIsModelOpen(false);
  };

  const renderModal = () => {
    return (
      <div>
        <p>Record Exists would you like to add them to the group?</p>
        <button onClick={confirmAddRecord}>Add Existing record !</button>
      </div>
    );
  };

  return (
    <div className="App">
      <p>Add record by pressing this button</p>
      <button onClick={createRecord}>Create record </button>
      {isModalOpen ? renderModal() : ""}
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

networkCalls.js below

export const ADD_NEW_RECORD = (
  isModalOpen,
  setIsModalOpen,
  setInfoFromCreateRecord
) => {
  //checking from an API of record exists

  const checkIfRecordExists = new Promise((resolve, reject) => {
    setTimeout(() => {
      console.log("Record Exists");
      resolve("Record Exists");
    }, 1000);
  });

  //record exists, ask the user if they want to add them to the group
  checkIfRecordExists.then(() => {
    setInfoFromCreateRecord({
      importantInfo: "record does exits"
    });
    setIsModalOpen(!isModalOpen);
  });
};

export const MAKE_API_CALL_AFTER_RECORD_CHECK = infoFromCreateRecord => {
  // do some stuff with the info from the first API call

  const doSomethingAfterRecordCheck = new Promise((resolve, reject) => {
    setTimeout(() => {
      console.log(infoFromCreateRecord);
      resolve("User got added to the group!");
    }, 1000);
  });

  doSomethingAfterRecordCheck.then(() => {
    console.log("do something after adding the user to the group");
  });
};


问:
"No installed app with label 'admin'" running Django migration. The app is installed correctly
I am trying to use admin.LogEntry objects during a datamigration on Django 1.7

The 'django.contrib.admin' app is listed on INSTALLED_APPS.

On the shell, it works:

```<code>>>> from django.apps import apps
>>> apps.get_model('admin', 'LogEntry')
django.contrib.admin.models.LogEntry
</code>```

But during the migration, it fails:

```<code>def do_it(apps, schema_editor):
    LogEntry = apps.get_model('admin', 'LogEntry')
</code>```

Fails like this:

```<code>django-admin migrate
(...)
LookupError: No installed app with label 'admin'.
</code>```

Using a debugger, I got that the 'admin' is not installed:

```<code>ipdb> apps.get_apps()
[]
ipdb> apps.all_models.keys()
['website', 'google', 'allauth', 'twitter', 'busca', 'conteudo', 'django_mobile', 'django_filters', 'videocenter', 'tinymce', 'oferta', 'programacaotv', 'contenttypes', 'suit', 'haystack', 'destaque', 'filer', 'galeria', 'auth', 'facebook', 'paintstore', 'critica', 'disqus', 'fichas', 'omeletop', 'autocomplete_light', 'modelsv1', 'temas', 'django_extensions', 'adv_cache_tag', 'taggit', 'social', 'personalidade']
</code>```

WHY??

答: I also had this same error of "no installed app label 'admin' ". I was able to solve it by running the pip install sqlparse command</p>

Body:
I am trying to use admin.LogEntry objects during a datamigration on Django 1.7

The 'django.contrib.admin' app is listed on INSTALLED_APPS.

On the shell, it works:

>>> from django.apps import apps
>>> apps.get_model('admin', 'LogEntry')
django.contrib.admin.models.LogEntry

But during the migration, it fails:

def do_it(apps, schema_editor):
    LogEntry = apps.get_model('admin', 'LogEntry')

Fails like this:

django-admin migrate
(...)
LookupError: No installed app with label 'admin'.

Using a debugger, I got that the 'admin' is not installed:

ipdb> apps.get_apps()
[]
ipdb> apps.all_models.keys()
['website', 'google', 'allauth', 'twitter', 'busca', 'conteudo', 'django_mobile', 'django_filters', 'videocenter', 'tinymce', 'oferta', 'programacaotv', 'contenttypes', 'suit', 'haystack', 'destaque', 'filer', 'galeria', 'auth', 'facebook', 'paintstore', 'critica', 'disqus', 'fichas', 'omeletop', 'autocomplete_light', 'modelsv1', 'temas', 'django_extensions', 'adv_cache_tag', 'taggit', 'social', 'personalidade']

WHY??


问:
How to find the first set of character that does not contain repeated character stand next to each other in a string
I have tried like in the code below but it only work if there is only one character set and the character set appear in the middle of the string. If the set appear more than once and appear at the end or the start of the string, the result is false.

```<code>    String str = "aaabbccdddefghjjkklmn";

for(int i = 1; i < str.length() - 1; i++){
    if (str.charAt(i) != str.charAt(i+1) && str.charAt(i) != str.charAt(i-1)){
        System.out.print(str.charAt(i));
    }
}
</code>```

With the string above, the result should be "efgh" only but the code above display "efghlm"

答:
Your method is correct. Just that you need to break the loop once repeating character is found, AFTER you found the first set of non-repeating characters.

Below snippet is JavaScript equivalent of your code

 var str = "aaabbccdddefghjjkklmn";

var result = "";
for(var i = 1; i < str.length - 1; i++){
    // Find for non-repeating character
    if (str.charAt(i) != str.charAt(i+1) && str.charAt(i) != str.charAt(i-1)){
        result += str.charAt(i)
    }
    else {
      // Repeating character found
      // exit loop if non-repeating character already
      // found
      if (result.length > 0) {
        break;
      }
    }
}

console.log(result);```

Body:
I have tried like in the code below but it only work if there is only one character set and the character set appear in the middle of the string. If the set appear more than once and appear at the end or the start of the string, the result is false.

    String str = "aaabbccdddefghjjkklmn";

for(int i = 1; i < str.length() - 1; i++){
    if (str.charAt(i) != str.charAt(i+1) && str.charAt(i) != str.charAt(i-1)){
        System.out.print(str.charAt(i));
    }
}

With the string above, the result should be "efgh" only but the code above display "efghlm"


问:
ORM vs Handcoded Data Access Layer
I'm a bit scared to ask this question as it may start a religous war so I want to be really clear on what I'm looking for. I'm looking for a reason(s) why you would or have jumped one way or the other and also for items to add to my lists. I'm looking for the big ticket, big bang items. Also, items specific to a product, maybe, if they are really relevant. At this point I'm trying to evaluate ORM vs Manual not product A vs product B.

ORM Advantages

```
 - Quick to code and low maintenance (in some/most scenarios)
 - Additional features for "free" (no developer effort)
```

Hand Coded Advantages

```
 - More Efficient (at runtime, maybe not at dev time?)
 - Less layers of complexity
 - Most ORMS seem to struggle with being retricted to sprocs only
```

In the interests of full disclosure, I really don't like the idea of "something" executing code against my database that I can't directly modify, if I see fit but I can see the potentially massive development time advatages of an ORM.

Its probably also worth noting I'm in a .Net world

[edit]
(the question at Using an ORM or plain SQL? seems to answer many of the questions and reinforce the point about performance)

So, to alter my question slightly

Has any built an app using an ORM in the early stages and then gradually replaced with with a handcoded DAL? What were the pitfalls of this approach?

[Further Edit - getting to the heart of the problem now]
Having a website be able to execute any SQL against my database is scary. If all access is through sprocs my database lives in nice, safe, comfortable isolation. Using exclusively sprocs removes a lot of, if not all, SQL injection attack vectors. Any comments on that?

答: Stored Procs don't remove the risk of sql injection. The person that is likely to concat queries in code is just as likely to do so in a stored proc. And any good ORM doesn't do string concats anyway so there is no issue.</p>

OwnerDisplayName: Frustrating Developments

ContentLicense: CC BY-SA 2.5

Title: ORM vs Handcoded Data Access Layer

Body:
I'm a bit scared to ask this question as it may start a religous war so I want to be really clear on what I'm looking for. I'm looking for a reason(s) why you would or have jumped one way or the other and also for items to add to my lists. I'm looking for the big ticket, big bang items. Also, items specific to a product, maybe, if they are really relevant. At this point I'm trying to evaluate ORM vs Manual not product A vs product B.

ORM Advantages

 - Quick to code and low maintenance (in some/most scenarios)
 - Additional features for "free" (no developer effort)

Hand Coded Advantages

 - More Efficient (at runtime, maybe not at dev time?)
 - Less layers of complexity
 - Most ORMS seem to struggle with being retricted to sprocs only

In the interests of full disclosure, I really don't like the idea of "something" executing code against my database that I can't directly modify, if I see fit but I can see the potentially massive development time advatages of an ORM.

Its probably also worth noting I'm in a .Net world

[edit]
(the question at Using an ORM or plain SQL? seems to answer many of the questions and reinforce the point about performance)

So, to alter my question slightly

Has any built an app using an ORM in the early stages and then gradually replaced with with a handcoded DAL? What were the pitfalls of this approach?

[Further Edit - getting to the heart of the problem now]
Having a website be able to execute any SQL against my database is scary. If all access is through sprocs my database lives in nice, safe, comfortable isolation. Using exclusively sprocs removes a lot of, if not all, SQL injection attack vectors. Any comments on that?

LastEditorDisplayName: Frustrating Developments

OwnerDisplayName: Craig


答:
The issue causing you to miss the beginning and end values is the way you constructed the for loop.

It should be:

```<code>for (int i = 0; i < str.length(); i++)
</code>```

You therefore need to handle the edge cases differently.

```<code>if ( (i+1 >= str.length() || str.charAt(i) != str.charAt(i+1)) && (i-1 < 0 || str.charAt(i) != str.charAt(i-1)) )
</code>```

This way, you are including the first and last indices without accessing out of range. Additionally, if you want to ensure that you only get the first instance of characters, you need some code to break out of the loop. Assign a boolean to true when the check returns true. If the check returns false, check to see if your found boolean is true. If so, break out of the loop.

```<code>boolean foundMatch = false;
for (int i = 0; i < str.length(); i++) {
    if ( (i+1 >= str.length() || str.charAt(i) != str.charAt(i+1)) && (i-1 < 0 || str.charAt(i) != str.charAt(i-1)) ) {
        System.out.print(str.charAt(i));
        foundMatch = true;
    }
    else {
        if (foundMatch == true) break;
    }
}
</code>```

Title: How to find the first set of character that does not contain repeated character stand next to each other in a string

Body:
The issue causing you to miss the beginning and end values is the way you constructed the for loop.

It should be:

for (int i = 0; i < str.length(); i++)

You therefore need to handle the edge cases differently.

if ( (i+1 >= str.length() || str.charAt(i) != str.charAt(i+1)) && (i-1 < 0 || str.charAt(i) != str.charAt(i-1)) )

This way, you are including the first and last indices without accessing out of range. Additionally, if you want to ensure that you only get the first instance of characters, you need some code to break out of the loop. Assign a boolean to true when the check returns true. If the check returns false, check to see if your found boolean is true. If so, break out of the loop.

boolean foundMatch = false;
for (int i = 0; i < str.length(); i++) {
    if ( (i+1 >= str.length() || str.charAt(i) != str.charAt(i+1)) && (i-1 < 0 || str.charAt(i) != str.charAt(i-1)) ) {
        System.out.print(str.charAt(i));
        foundMatch = true;
    }
    else {
        if (foundMatch == true) break;
    }
}


问:
How to use multiple PUT fuctions in Web api C#
Multiple put method working in local iis, but not in live server.

```<code>         Webapi Config:

     config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
           name: "ApiById",
           routeTemplate: "api/{controller}/{id}",
           defaults: new { id = RouteParameter.Optional }
       );

        config.Routes.MapHttpRoute(
           name: "ApiByName",
           routeTemplate: "api/{controller}/{action}/{name}",
           defaults: new { id = RouteParameter.Optional }
       );

        config.Routes.MapHttpRoute(
           name: "ApiByAction",
           routeTemplate: "api/{controller}/{action}",
           defaults: new { id = RouteParameter.Optional }
       );

        config.Routes.MapHttpRoute(
          name: "ApiByActionName",
          routeTemplate: "api/{controller}/{action}/{id}/",
          defaults: new { id = RouteParameter.Optional }
      );

   [HttpPut]

    public async Task<int> DeleteCity(Guid? Id)
    {
        City updateCity = await db.City.Where(x => x.Id == Id).FirstOrDefaultAsync();
        updateCity.IsActive = 0;
        await db.SaveChangesAsync();
        return 1;
    }

    [HttpPut]
    [Route("api/city/DeleteCitys/{Id}")]
    public async Task<int> DeleteCitys(Guid? Id)
    {
        City updateCity = await db.City.Where(x => x.Id == Id).FirstOrDefaultAsync();
        updateCity.IsActive = 1;
        await db.SaveChangesAsync();
        return 3;
    }
</code>```

http://freedompg.softwarecubes.com/api/city/76F84F4C-22C8-4EF8-B593-B3605CF9AD14

Output : 1 is Correct

http://freedompg.softwarecubes.com/api/city/DeleteCitys/76F84F4C-22C8-4EF8-B593-B3605CF9AD14

Output : 1 is wrong (call the previous function)

答:
Your code should be like this. You need to have the route for the DeleteCity also</p>

```<code>[HttpPut]
[Route("api/city/{Id}")]
public async Task<int> DeleteCity(Guid? Id)
{
    City updateCity = await db.City.Where(x => x.Id == Id).FirstOrDefaultAsync();
    updateCity.IsActive = 0;
    await db.SaveChangesAsync();
    return 1;
}

[HttpPut]
[Route("api/city/DeleteCitys/{Id}")]
public async Task<int> DeleteCitys(Guid? Id)
{
    City updateCity = await db.City.Where(x => x.Id == Id).FirstOrDefaultAsync();
    updateCity.IsActive = 1;
    await db.SaveChangesAsync();
    return 3;
}
</code>```

Body:
Multiple put method working in local iis, but not in live server.

         Webapi Config:

     config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
           name: "ApiById",
           routeTemplate: "api/{controller}/{id}",
           defaults: new { id = RouteParameter.Optional }
       );

        config.Routes.MapHttpRoute(
           name: "ApiByName",
           routeTemplate: "api/{controller}/{action}/{name}",
           defaults: new { id = RouteParameter.Optional }
       );

        config.Routes.MapHttpRoute(
           name: "ApiByAction",
           routeTemplate: "api/{controller}/{action}",
           defaults: new { id = RouteParameter.Optional }
       );

        config.Routes.MapHttpRoute(
          name: "ApiByActionName",
          routeTemplate: "api/{controller}/{action}/{id}/",
          defaults: new { id = RouteParameter.Optional }
      );

   [HttpPut]

    public async Task<int> DeleteCity(Guid? Id)
    {
        City updateCity = await db.City.Where(x => x.Id == Id).FirstOrDefaultAsync();
        updateCity.IsActive = 0;
        await db.SaveChangesAsync();
        return 1;
    }

    [HttpPut]
    [Route("api/city/DeleteCitys/{Id}")]
    public async Task<int> DeleteCitys(Guid? Id)
    {
        City updateCity = await db.City.Where(x => x.Id == Id).FirstOrDefaultAsync();
        updateCity.IsActive = 1;
        await db.SaveChangesAsync();
        return 3;
    }

http://freedompg.softwarecubes.com/api/city/76F84F4C-22C8-4EF8-B593-B3605CF9AD14

Output : 1 is Correct

http://freedompg.softwarecubes.com/api/city/DeleteCitys/76F84F4C-22C8-4EF8-B593-B3605CF9AD14

Output : 1 is wrong (call the previous function)

Body:
Your code should be like this. You need to have the route for the DeleteCity also

[HttpPut]
[Route("api/city/{Id}")]
public async Task<int> DeleteCity(Guid? Id)
{
    City updateCity = await db.City.Where(x => x.Id == Id).FirstOrDefaultAsync();
    updateCity.IsActive = 0;
    await db.SaveChangesAsync();
    return 1;
}

[HttpPut]
[Route("api/city/DeleteCitys/{Id}")]
public async Task<int> DeleteCitys(Guid? Id)
{
    City updateCity = await db.City.Where(x => x.Id == Id).FirstOrDefaultAsync();
    updateCity.IsActive = 1;
    await db.SaveChangesAsync();
    return 3;
}


问:
Footer floats to middle on the page
Is there any way to set footer at the bottom of the page?
Footer should be 100% width and .wrapper 960px as well.

I already tried:

position: relative; - sticks between .content tags

position: absolute; - sticks to .nav

position: fixed; - could be a solution, but I don't need it all the time, just at bottom of the last page.

to move .footer outside .wrapper and set .wrapper:not(footer); - footer sticked to the bottom, but the width hasn't changed.

Any suggestion how is possible to set it up at the bottom?

@charset "UTF-8";
@import url('https://fonts.googleapis.com/css?family=Montserrat|Nunito+Sans|Roboto&display=swap');
* {
  margin: 0;
  padding: 0;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
}

html {
  scroll-behavior: smooth;
  word-wrap: break-word;
}

html,
body,
header,
main {
  height: 100%;
}

body {
  width: 100%;
  font-family: Roboto, Verdana, sans-serif;
  font-size: 1em;
  background-image: url(../images/extra_clean_paper.png);
  background-repeat: repeat;
}

header {
  text-align: center;
  background-color: yellow;
}

#hero-header {
  position: relative;
  top: 50%;
  left: 50%;
  -webkit-transform: translate(-50%, -50%);
  -ms-transform: translate(-50%, -50%);
  transform: translate(-50%, -50%);
}

#hero-btn {
  width: 50px;
  height: 50px;
  position: absolute;
  bottom: 4em;
  left: 50%;
  -webkit-transform: translateX(-50%);
  -ms-transform: translateX(-50%);
  transform: translateX(-50%);
}

.hero-btn a {
  position: relative;
  display: inline-block;
  color: black;
  text-decoration: none;
  -webkit-transition: opacity .3s;
  -o-transition: opacity .3s;
  transition: opacity .3s;
}

.hero-btn a:hover {
  opacity: 0.5;
}

header a {
  padding-top: 70px;
}

header a span {
  position: absolute;
  top: 0;
  left: 50%;
  width: 24px;
  height: 24px;
  margin-left: -12px;
  border-left: 1px solid black;
  border-bottom: 1px solid black;
  -webkit-transform: rotate(-45deg);
  -ms-transform: rotate(-45deg);
  transform: rotate(-45deg);
  -webkit-animation: sdb07 2s infinite;
  animation: sdb07 2s infinite;
  opacity: 0;
}

header a span:nth-of-type(1) {
  -webkit-animation-delay: 0s;
  animation-delay: 0s;
}

header a span:nth-of-type(2) {
  top: 16px;
  -webkit-animation-delay: .15s;
  animation-delay: .15s;
}

header a span:nth-of-type(3) {
  top: 32px;
  -webkit-animation-delay: .3s;
  animation-delay: .3s;
}

@-webkit-keyframes sdb07 {
  0% {
    opacity: 0;
  }
  50% {
    opacity: 1;
  }
  100% {
    opacity: 0;
  }
}

@keyframes sdb07 {
  0% {
    opacity: 0;
  }
  50% {
    opacity: 1;
  }
  100% {
    opacity: 0;
  }
}

#resp-nav {
  text-align: center;
  display: none;
  background-color: grey;
}

#resp-nav i {
  font-size: 2em;
  color: white;
}

#nav {
  text-align: center;
  background-color: dimgray;
  z-index: 2;
}

main:not(#footer) {
  max-width: 960px;
  margin: 0 auto;
}

.container {
  background-color: #eeeeee;
  border: 1px solid red;
  border-radius: 5px;
  clear: both;
  overflow: hidden;
  margin-top: 1em;
  min-height: 100%;
  padding: 3.125em 0.625em;
  -webkit-box-shadow: 0 15px 20px rgba(0, 0, 0, 0.3);
  box-shadow: 0 15px 20px rgba(0, 0, 0, 0.3);
}

.aboutme img {
  width: 100%;
  height: auto;
}

.aboutme .col-40 {
  margin-top: 1em;
  padding-left: 1em;
  padding-right: 1em;
  width: 39%;
}

.aboutme .col-60 {
  margin-top: 1em;
  padding-left: 1em;
  padding-right: 1em;
  width: 59%;
}

.left {
  float: left;
}

.right {
  float: right;
}

.table {
  display: table;
  border-collapse: collapse;
  table-layout: fixed;
}

.hobbies .table-row {
  display: table-row;
  border-bottom: 0.1em solid darkgrey;
}

.hobbies .table-row:last-child {
  border: 0;
}

.hobbies .table-cell {
  display: table-cell;
  padding-left: 1em;
  padding-right: 1em;
  vertical-align: middle;
  text-align: center;
  width: 50%;
}

.portfolio .col-50 {
  margin-top: 1em;
  padding-left: 1em;
  padding-right: 1em;
  width: 49%;
}

.projects .flex-row {
  display: flex;
  flex-wrap: wrap;
  width: 100%;
  padding-right: 15px;
  padding-left: 15px;
  margin-right: auto;
  margin-left: auto;
}

.projects .col-33 {
  position: relative;
  width: 100%;
  max-width: 33%;
  -ms-flex: 0 0 33%;
  -webkit-box-flex: 0;
  -webkit-flex: 0 0 33%;
  flex: 0 0 33%;
}

.projects .services-box {
  background: #f9f9f9;
  padding: 10px;
  margin: 20px 5px 0 5px;
}

footer {
  background: red;
  height: 50px;
  width: 100%;
  position: relative;
  bottom: 0;
  left: 0;
  margin-top: 10px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><header id="link-hero-page">
  <div id="hero-header">
  </div>
</header>
<nav>
  <ul id="nav">
  </ul>
</nav>
<main>
  <section id="link-main" class="aboutme container">
    <div class="col-40 left">
    </div>
    <article class="col-60 right">
    </article>
  </section>
  <section id="link-hobbies" class="hobbies container">
    <div class="table">
      <div class="table-row">
        <article class="table-cell">
        </article>
      </div>
      <div class="table-row">
        <div class="table-cell">
        </div>
        <article class="table-cell">
        </article>
      </div>
      <div class="table-row">
        <article class="table-cell">
        </article>
      </div>
    </div>
  </section>
  <section id="link-portfolio" class="portfolio container">
    <article class="col-50 left">
    </article>
    <article class="col-50 right">
    </article>
  </section>
  <section id="link-projects" class="projects container">
    <div class="flex-row">
      <div class="col-33">
        <article class="services-box">
        </article>
      </div>
      <div class="col-33">
        <article class="services-box">
        </article>
      </div>
      <div class="col-33">
        <article class="services-box">
        </article>
      </div>
    </div>
  </section>
  <section id="link-contacts" class="contacts container">

  </section>
</main>
<!--FOOTER-->
<footer>
  <address>
    <p style="text-align: center;">LOREM LOREM LOREM LOREM LOREM</p>
   </address>
</footer></code>```

https://jsfiddle.net/1adkjLw0/

答:
Just move your footer outside of the wrapper.

       * {
    margin: 0;
    padding: 0;
  }

  html,
  body {
    height: 100%;
  }

  body {
    width: 100%;
  }

  .nav {
    background: green;
    height: 50px;
  }

  .wrapper {
    max-width: 500px;
    margin: 0 auto;
  }

  .content {
    background: yellow;
    margin-top: 10px;
    height: 100px;
  }

  .footer {
    background: red;
    height: 50px;
    width: 100%;
    position: relative;
    bottom: 0;
    left: 0;
    margin-top: 10px;
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="nav"></div>
<div class="wrapper">
  <div class="content"></div>
  <div class="content"></div>
  <div class="content"></div>
  <div class="content"></div>
  <div class="content"></div>
  <div class="content"></div>
</div>
<div class="footer"></div></code>```

Title: Footer floats to middle on the page

Body:
Is there any way to set footer at the bottom of the page?
Footer should be 100% width and .wrapper 960px as well.

I already tried:

position: relative; - sticks between .content tags

position: absolute; - sticks to .nav

position: fixed; - could be a solution, but I don't need it all the time, just at bottom of the last page.

to move .footer outside .wrapper and set .wrapper:not(footer); - footer sticked to the bottom, but the width hasn't changed.

Any suggestion how is possible to set it up at the bottom?

@charset "UTF-8";
@import url('https://fonts.googleapis.com/css?family=Montserrat|Nunito+Sans|Roboto&display=swap');
* {
  margin: 0;
  padding: 0;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
}

html {
  scroll-behavior: smooth;
  word-wrap: break-word;
}

html,
body,
header,
main {
  height: 100%;
}

body {
  width: 100%;
  font-family: Roboto, Verdana, sans-serif;
  font-size: 1em;
  background-image: url(../images/extra_clean_paper.png);
  background-repeat: repeat;
}

header {
  text-align: center;
  background-color: yellow;
}

#hero-header {
  position: relative;
  top: 50%;
  left: 50%;
  -webkit-transform: translate(-50%, -50%);
  -ms-transform: translate(-50%, -50%);
  transform: translate(-50%, -50%);
}

#hero-btn {
  width: 50px;
  height: 50px;
  position: absolute;
  bottom: 4em;
  left: 50%;
  -webkit-transform: translateX(-50%);
  -ms-transform: translateX(-50%);
  transform: translateX(-50%);
}

.hero-btn a {
  position: relative;
  display: inline-block;
  color: black;
  text-decoration: none;
  -webkit-transition: opacity .3s;
  -o-transition: opacity .3s;
  transition: opacity .3s;
}

.hero-btn a:hover {
  opacity: 0.5;
}

header a {
  padding-top: 70px;
}

header a span {
  position: absolute;
  top: 0;
  left: 50%;
  width: 24px;
  height: 24px;
  margin-left: -12px;
  border-left: 1px solid black;
  border-bottom: 1px solid black;
  -webkit-transform: rotate(-45deg);
  -ms-transform: rotate(-45deg);
  transform: rotate(-45deg);
  -webkit-animation: sdb07 2s infinite;
  animation: sdb07 2s infinite;
  opacity: 0;
}

header a span:nth-of-type(1) {
  -webkit-animation-delay: 0s;
  animation-delay: 0s;
}

header a span:nth-of-type(2) {
  top: 16px;
  -webkit-animation-delay: .15s;
  animation-delay: .15s;
}

header a span:nth-of-type(3) {
  top: 32px;
  -webkit-animation-delay: .3s;
  animation-delay: .3s;
}

@-webkit-keyframes sdb07 {
  0% {
    opacity: 0;
  }
  50% {
    opacity: 1;
  }
  100% {
    opacity: 0;
  }
}

@keyframes sdb07 {
  0% {
    opacity: 0;
  }
  50% {
    opacity: 1;
  }
  100% {
    opacity: 0;
  }
}

#resp-nav {
  text-align: center;
  display: none;
  background-color: grey;
}

#resp-nav i {
  font-size: 2em;
  color: white;
}

#nav {
  text-align: center;
  background-color: dimgray;
  z-index: 2;
}

main:not(#footer) {
  max-width: 960px;
  margin: 0 auto;
}

.container {
  background-color: #eeeeee;
  border: 1px solid red;
  border-radius: 5px;
  clear: both;
  overflow: hidden;
  margin-top: 1em;
  min-height: 100%;
  padding: 3.125em 0.625em;
  -webkit-box-shadow: 0 15px 20px rgba(0, 0, 0, 0.3);
  box-shadow: 0 15px 20px rgba(0, 0, 0, 0.3);
}

.aboutme img {
  width: 100%;
  height: auto;
}

.aboutme .col-40 {
  margin-top: 1em;
  padding-left: 1em;
  padding-right: 1em;
  width: 39%;
}

.aboutme .col-60 {
  margin-top: 1em;
  padding-left: 1em;
  padding-right: 1em;
  width: 59%;
}

.left {
  float: left;
}

.right {
  float: right;
}

.table {
  display: table;
  border-collapse: collapse;
  table-layout: fixed;
}

.hobbies .table-row {
  display: table-row;
  border-bottom: 0.1em solid darkgrey;
}

.hobbies .table-row:last-child {
  border: 0;
}

.hobbies .table-cell {
  display: table-cell;
  padding-left: 1em;
  padding-right: 1em;
  vertical-align: middle;
  text-align: center;
  width: 50%;
}

.portfolio .col-50 {
  margin-top: 1em;
  padding-left: 1em;
  padding-right: 1em;
  width: 49%;
}

.projects .flex-row {
  display: flex;
  flex-wrap: wrap;
  width: 100%;
  padding-right: 15px;
  padding-left: 15px;
  margin-right: auto;
  margin-left: auto;
}

.projects .col-33 {
  position: relative;
  width: 100%;
  max-width: 33%;
  -ms-flex: 0 0 33%;
  -webkit-box-flex: 0;
  -webkit-flex: 0 0 33%;
  flex: 0 0 33%;
}

.projects .services-box {
  background: #f9f9f9;
  padding: 10px;
  margin: 20px 5px 0 5px;
}

footer {
  background: red;
  height: 50px;
  width: 100%;
  position: relative;
  bottom: 0;
  left: 0;
  margin-top: 10px;
}

  <address>

LOREM LOREM LOREM LOREM LOREM

   </address>

https://jsfiddle.net/1adkjLw0/

Body:
Just move your footer outside of the wrapper.

       * {
    margin: 0;
    padding: 0;
  }

  html,
  body {
    height: 100%;
  }

  body {
    width: 100%;
  }

  .nav {
    background: green;
    height: 50px;
  }

  .wrapper {
    max-width: 500px;
    margin: 0 auto;
  }

  .content {
    background: yellow;
    margin-top: 10px;
    height: 100px;
  }

  .footer {
    background: red;
    height: 50px;
    width: 100%;
    position: relative;
    bottom: 0;
    left: 0;
    margin-top: 10px;
  }

<div class="nav"></div>
<div class="wrapper">
  <div class="content"></div>
  <div class="content"></div>
  <div class="content"></div>
  <div class="content"></div>
  <div class="content"></div>
  <div class="content"></div>
</div>
<div class="footer"></div>