问:
Problem in creating a new column using for loop
I have to create a new column 'Action' in a dataframe whose values are :
1 if the next day's Close Price is greater than the present day's
-1 if the next day's Close Price is less than the present day's
that is,
Action[i] = 1 if Close Price[i+1]>Close Price[i]
Action[i] = -1 if Close Price[i+1]

I have used the following code:

```<code>dt =  pd.read_csv("C:\Subhro\ML_Internship\HDFC_Test.csv", sep=',',header=0)
df = pd.DataFrame(dt)

for i in df.index:
   if(df['Close Price'][i+1]>df['Close Price'][i]):
       df['Action'][i]=1
   elif(df['Close Price'][i+1]<df['Close Price'][i]):
       df['Action'][i]=-1
</code>```

print(df)
 But I am getting an error :
KeyError: 'Action'
in line:
df['Action'][i]=1

Please help me out

答:
You are getting the key error because you don't have a column called action. Any of the following before the loop will resolve the error:

```<code>df['Action'] = 0
</code>```

or

```<code>df['Action'] = np.nan
</code>```

However, you will get warnings because of the way you are assigning the cell values. (See here)

It is recommended that you instead use e.g.

```<code>df.loc[i, "Action"] = 1
</code>```

Note that with this method, you won't even need to create an empty "Action" column before the loop.

Body:
I have to create a new column 'Action' in a dataframe whose values are :
1 if the next day's Close Price is greater than the present day's
-1 if the next day's Close Price is less than the present day's
that is,
Action[i] = 1 if Close Price[i+1]>Close Price[i]
Action[i] = -1 if Close Price[i+1]

I have used the following code:

dt =  pd.read_csv("C:\Subhro\ML_Internship\HDFC_Test.csv", sep=',',header=0)
df = pd.DataFrame(dt)

for i in df.index:
   if(df['Close Price'][i+1]>df['Close Price'][i]):
       df['Action'][i]=1
   elif(df['Close Price'][i+1]<df['Close Price'][i]):
       df['Action'][i]=-1

print(df)
 But I am getting an error :
KeyError: 'Action'
in line:
df['Action'][i]=1

Please help me out

Body:
You are getting the key error because you don't have a column called action. Any of the following before the loop will resolve the error:

df['Action'] = 0

or

df['Action'] = np.nan

However, you will get warnings because of the way you are assigning the cell values. (See here)

It is recommended that you instead use e.g.

df.loc[i, "Action"] = 1

Note that with this method, you won't even need to create an empty "Action" column before the loop.


来源: stackexchange

问:
How to populate my Django Model 'updated_by' field with logged in User automatically using a formset?
I am a beginner with Django and I have been enjoying it so far. I figured out how to use model formsets, but I cannot figure out how to make my form automatically use logged in User as the 'updated_by' field.

models.py

```<code>class Inventory(models.Model):
    item = models.CharField(max_length=50, unique=True)
    stock = models.IntegerField()
    par = models.IntegerField()
    date_updated = models.DateTimeField(auto_now=True)
    updated_by = models.ForeignKey(User, on_delete=models.PROTECT)

    def __str__(self):
        return self.item

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    image = models.ImageField(default='default.jpg', upload_to='profile_pics')
    phone = PhoneField(blank='True', help_text='Contact Phone Number')

    def __str__(self):
        return f'{self.user.username} Profile'

    def save(self):
        super().save()
</code>```

答:
I would use the 'commit=False' argument which will create a new object and assign it without saving to your database.  You can then set the user attribute and call save() with no arguments.

For example, this is how I assigned the user attribute to my blog app.

in views.py

```<code>if form.is_valid():
            # Create a new entry and assign to new_article.
            new_article = form.save(commit=False)

            # Set the new article attribute to the current user.
            new_article.user = request.user

            # Save to database now the object has all the required data.
            new_article.save()
</code>```

Here is the full code for the add_article view if this helps.

```<code>@login_required
def add_article(request):
    """ Add a new article. """
    if request.method != 'POST':
        # No data submitted, create a blank form.
        form = AddArticleForm()
    else:
        # POST data submitted, process data.
        form = AddArticleForm(request.POST, request.FILES)
        if form.is_valid():
            new_article = form.save(commit=False)
            new_article.author = request.user
            new_article.save()
            return back_to_blog_page()

    context = {'form': form}
    return render(request, 'add_article.html', context)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am a beginner with Django and I have been enjoying it so far. I figured out how to use model formsets, but I cannot figure out how to make my form automatically use logged in User as the 'updated_by' field.

models.py

class Inventory(models.Model):
    item = models.CharField(max_length=50, unique=True)
    stock = models.IntegerField()
    par = models.IntegerField()
    date_updated = models.DateTimeField(auto_now=True)
    updated_by = models.ForeignKey(User, on_delete=models.PROTECT)

    def __str__(self):
        return self.item

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    image = models.ImageField(default='default.jpg', upload_to='profile_pics')
    phone = PhoneField(blank='True', help_text='Contact Phone Number')

    def __str__(self):
        return f'{self.user.username} Profile'

    def save(self):
        super().save()

Body:
I would use the 'commit=False' argument which will create a new object and assign it without saving to your database.  You can then set the user attribute and call save() with no arguments.

For example, this is how I assigned the user attribute to my blog app.

in views.py

if form.is_valid():
            # Create a new entry and assign to new_article.
            new_article = form.save(commit=False)

            # Set the new article attribute to the current user.
            new_article.user = request.user

            # Save to database now the object has all the required data.
            new_article.save()

Here is the full code for the add_article view if this helps.

@login_required
def add_article(request):
    """ Add a new article. """
    if request.method != 'POST':
        # No data submitted, create a blank form.
        form = AddArticleForm()
    else:
        # POST data submitted, process data.
        form = AddArticleForm(request.POST, request.FILES)
        if form.is_valid():
            new_article = form.save(commit=False)
            new_article.author = request.user
            new_article.save()
            return back_to_blog_page()

    context = {'form': form}
    return render(request, 'add_article.html', context)


问:
Fuzzy string matching using Difflib get_matching_blocks not detecting all substrings
I'm trying to find all occurrences of a word in paragraph and I want it to account for spelling mistakes as well. Code:

```<code>to_search="caterpillar"
search_here= "caterpillar are awesome animal catterpillar who like other humans but not other caterpilar"
#search_here has the word caterpillar repeated but with spelling mistakes

s= SequenceMatcher(None, to_search, search_here).get_matching_blocks()
print(s)

#Output  : [Match(a=0, b=0, size=11), Match(a=3, b=69, size=0)]
#Expected: [Match(a=0, b=0, size=11), Match(a=0, b=32, size=11), Match(a=0, b=81, size=11)]
</code>```

Difflib get_matching_blocks only detects the first instance of "caterpillar" in the search_here string. I want it to give me output of all closely matching blocks i.e. it should identify "caterpillar","catterpillar" and "caterpilar"

How can I solve this problem?

答:
You could calculate the edit distance of each word vs. to_search. Then, you can select all the words that have "low enough" edit distance (a score of 0 means exact match).

Thanks to your question, I have discovered that there is a pip-install-able edit_distance Python module. Here are a couple examples I just tried out for the first time:

```<code>>>> edit_distance.SequenceMatcher('fabulous', 'fibulous').ratio()
0.875
>>> edit_distance.SequenceMatcher('fabulous', 'wonderful').ratio()
0.11764705882352941
>>> edit_distance.SequenceMatcher('fabulous', 'fabulous').ratio()
1.0
>>> edit_distance.SequenceMatcher('fabulous', '').ratio()
0.0
>>> edit_distance.SequenceMatcher('caterpillar', 'caterpilar').ratio()
0.9523809523809523
</code>```

So, it looks like the ratio method gives you a number between 0 and 1 (inclusive) where 1 is an exact match and 0 is... not even in the same league XD. So yeah, you could select words that have a ratio greater than 1 - epsilon, where epsilon is maybe 0.1 or thereabouts.

Body:
I'm trying to find all occurrences of a word in paragraph and I want it to account for spelling mistakes as well. Code:

to_search="caterpillar"
search_here= "caterpillar are awesome animal catterpillar who like other humans but not other caterpilar"
#search_here has the word caterpillar repeated but with spelling mistakes

s= SequenceMatcher(None, to_search, search_here).get_matching_blocks()
print(s)

#Output  : [Match(a=0, b=0, size=11), Match(a=3, b=69, size=0)]
#Expected: [Match(a=0, b=0, size=11), Match(a=0, b=32, size=11), Match(a=0, b=81, size=11)]

Difflib get_matching_blocks only detects the first instance of "caterpillar" in the search_here string. I want it to give me output of all closely matching blocks i.e. it should identify "caterpillar","catterpillar" and "caterpilar"

How can I solve this problem?

Body:
You could calculate the edit distance of each word vs. to_search. Then, you can select all the words that have "low enough" edit distance (a score of 0 means exact match).

Thanks to your question, I have discovered that there is a pip-install-able edit_distance Python module. Here are a couple examples I just tried out for the first time:

>>> edit_distance.SequenceMatcher('fabulous', 'fibulous').ratio()
0.875
>>> edit_distance.SequenceMatcher('fabulous', 'wonderful').ratio()
0.11764705882352941
>>> edit_distance.SequenceMatcher('fabulous', 'fabulous').ratio()
1.0
>>> edit_distance.SequenceMatcher('fabulous', '').ratio()
0.0
>>> edit_distance.SequenceMatcher('caterpillar', 'caterpilar').ratio()
0.9523809523809523

So, it looks like the ratio method gives you a number between 0 and 1 (inclusive) where 1 is an exact match and 0 is... not even in the same league XD. So yeah, you could select words that have a ratio greater than 1 - epsilon, where epsilon is maybe 0.1 or thereabouts.


问:
Why compiler says Works cannot be resolved to a type?
I just want to declare a generic type for simple things but the compiler get errors that type is not resolved!
this is how i did in main:

```<code>//Main and Works are in same file
public class Main {
    public static void main(String[] args) {
        Works<Integer> a = new Works<Integer>();   //this line got problem
        a.add(2);
        a.add(0);
        a.add(15);
        a.add(-8);
        a.add(6);
        System.out.println(a.getMin());
    }
}
</code>```

and this is my class declaration
`

```<code>//generic class declaration
class Works<T extends Comparable> {
    private ArrayList<T> works = new ArrayList<T>();

    public void add(T item) {
        works.add(item);
    }

    public T getMin() throws IllegalStateException {
        if (works.size() == 0) {
            throw new IllegalStateException("Your task table is empty");
        }
        T tmp = Collections.min(works);
        remove(tmp);
        return tmp;
    }

    public Comparable[] getLess(T element, boolean remove) {
        Collections.sort(works);
        if (remove) {
            remove(element);
        }
        return works.subList(0, works.indexOf(element)).toArray();
    }
}
</code>```

`

答:
I don't know what is your package structure.

If they are in different package, then you have to import the class.

For example :

Create Main class in package com.example and Works class in com.example.demo :

```<code>package com.example;

import com.example.demo.Works;

public class Main {
    public static void main(String[] args) {
        Works<Integer> a = new Works<Integer>();   //this line got problem
        a.add(2);
        a.add(0);
        a.add(15);
        a.add(-8);
        a.add(6);
        System.out.println(a.getMin());
    }
}
</code>```

```<code>package com.example.demo;

//generic class declaration
public class Works<T extends Comparable> {
    private ArrayList<T> works = new ArrayList<T>();

    public void add(T item) {
        works.add(item);
    }

    public T getMin() throws IllegalStateException {
        if (works.size() == 0) {
            throw new IllegalStateException("Your task table is empty");
        }
        T tmp = Collections.min(works);
        remove(tmp);
        return tmp;
    }

    public Comparable[] getLess(T element, boolean remove) {
        Collections.sort(works);
        if (remove) {
            remove(element);
        }
        return works.subList(0, works.indexOf(element)).toArray();
    }
}
</code>```

If you want to keep Works class in same package. then define the Works with default scope in Main.java like this below :

```<code>package com.example;

//generic class declaration
class Works<T extends Comparable> {
    private ArrayList<T> works = new ArrayList<T>();

    public void add(T item) {
        works.add(item);
    }

    public T getMin() throws IllegalStateException {
        if (works.size() == 0) {
            throw new IllegalStateException("Your task table is empty");
        }
        T tmp = Collections.min(works);
        remove(tmp);
        return tmp;
    }

    public Comparable[] getLess(T element, boolean remove) {
        Collections.sort(works);
        if (remove) {
            remove(element);
        }
        return works.subList(0, works.indexOf(element)).toArray();
    }
}

public class Main {
    public static void main(String[] args) {
        Works<Integer> a = new Works<Integer>();   //this line got problem
        a.add(2);
        a.add(0);
        a.add(15);
        a.add(-8);
        a.add(6);
        System.out.println(a.getMin());
    }
}
</code>```

Body:
I just want to declare a generic type for simple things but the compiler get errors that type is not resolved!
this is how i did in main:

//Main and Works are in same file
public class Main {
    public static void main(String[] args) {
        Works<Integer> a = new Works<Integer>();   //this line got problem
        a.add(2);
        a.add(0);
        a.add(15);
        a.add(-8);
        a.add(6);
        System.out.println(a.getMin());
    }
}

and this is my class declaration
`

//generic class declaration
class Works<T extends Comparable> {
    private ArrayList<T> works = new ArrayList<T>();

    public void add(T item) {
        works.add(item);
    }

    public T getMin() throws IllegalStateException {
        if (works.size() == 0) {
            throw new IllegalStateException("Your task table is empty");
        }
        T tmp = Collections.min(works);
        remove(tmp);
        return tmp;
    }

    public Comparable[] getLess(T element, boolean remove) {
        Collections.sort(works);
        if (remove) {
            remove(element);
        }
        return works.subList(0, works.indexOf(element)).toArray();
    }
}

`

Body:
I don't know what is your package structure.

If they are in different package, then you have to import the class.

For example :

Create Main class in package com.example and Works class in com.example.demo :

package com.example;

import com.example.demo.Works;

public class Main {
    public static void main(String[] args) {
        Works<Integer> a = new Works<Integer>();   //this line got problem
        a.add(2);
        a.add(0);
        a.add(15);
        a.add(-8);
        a.add(6);
        System.out.println(a.getMin());
    }
}

package com.example.demo;

//generic class declaration
public class Works<T extends Comparable> {
    private ArrayList<T> works = new ArrayList<T>();

    public void add(T item) {
        works.add(item);
    }

    public T getMin() throws IllegalStateException {
        if (works.size() == 0) {
            throw new IllegalStateException("Your task table is empty");
        }
        T tmp = Collections.min(works);
        remove(tmp);
        return tmp;
    }

    public Comparable[] getLess(T element, boolean remove) {
        Collections.sort(works);
        if (remove) {
            remove(element);
        }
        return works.subList(0, works.indexOf(element)).toArray();
    }
}

If you want to keep Works class in same package. then define the Works with default scope in Main.java like this below :

package com.example;

//generic class declaration
class Works<T extends Comparable> {
    private ArrayList<T> works = new ArrayList<T>();

    public void add(T item) {
        works.add(item);
    }

    public T getMin() throws IllegalStateException {
        if (works.size() == 0) {
            throw new IllegalStateException("Your task table is empty");
        }
        T tmp = Collections.min(works);
        remove(tmp);
        return tmp;
    }

    public Comparable[] getLess(T element, boolean remove) {
        Collections.sort(works);
        if (remove) {
            remove(element);
        }
        return works.subList(0, works.indexOf(element)).toArray();
    }
}

public class Main {
    public static void main(String[] args) {
        Works<Integer> a = new Works<Integer>();   //this line got problem
        a.add(2);
        a.add(0);
        a.add(15);
        a.add(-8);
        a.add(6);
        System.out.println(a.getMin());
    }
}


问:
Traversing a vector vs array which one is faster?
While traversing a vector and a array which one is faster and helpful in compititive programming? </p>

答: They are equal in speed because the underlying data is in both cases a contiguous block of memory where only a simple pointer arithmetics is needed to move to arbitrary element.</p>


问:
Make sure that method returns a List<String> and not just a List. in java
```<code>public static void main(String[] args) {
    ArrayList idList = new ArrayList<String>();
    idList.add(0,"a");
    idList.add(1,"b");
    idList.add(2,"c");
    for (String uuid : idList) {
      System.out.println(uuid);
    }
  }
</code>```

In "uuid : idList"

"Type mismatch: cannot convert from element type Object to String"

What's wrong?

答:
You didn't define type of your array so you can't use foreach in this way.

you can do this (define the type):

```<code>public static void main(String[] args) {

    ArrayList<String> idList = new ArrayList<String>();
    idList.add(0,"a");
    idList.add(1, "b");
    idList.add(2, "c");
    for (String uuid : idList) {
      System.out.println(uuid);
    }

}
</code>```

or (use foreach on Object not String):

```<code>public static void main(String[] args) {

    ArrayList idList = new ArrayList<String>();
    idList.add(0,"a");
    idList.add(1, "b");
    idList.add(2, "c");
    for (Object uuid : idList) {
      System.out.println(uuid);
    }

}
</code>```

Body:
public static void main(String[] args) {
    ArrayList idList = new ArrayList<String>();
    idList.add(0,"a");
    idList.add(1,"b");
    idList.add(2,"c");
    for (String uuid : idList) {
      System.out.println(uuid);
    }
  }

In "uuid : idList"

"Type mismatch: cannot convert from element type Object to String"

What's wrong?

Body:
You didn't define type of your array so you can't use foreach in this way.

you can do this (define the type):

public static void main(String[] args) {

    ArrayList<String> idList = new ArrayList<String>();
    idList.add(0,"a");
    idList.add(1, "b");
    idList.add(2, "c");
    for (String uuid : idList) {
      System.out.println(uuid);
    }

}

or (use foreach on Object not String):

public static void main(String[] args) {

    ArrayList idList = new ArrayList<String>();
    idList.add(0,"a");
    idList.add(1, "b");
    idList.add(2, "c");
    for (Object uuid : idList) {
      System.out.println(uuid);
    }

}


问:
validateDOMNesting(...): <button> Warning
I'm making a website using React.

When my website has lots of text, I'll show a button such as show more or less.

In my project, It works well, but always show a warning about validateDOMNesting(...): <button>

My sample code like this.

const [show, setShow] = useState(false);

function handleShow() {
  show ? setShow(false) : setShow(true);
}

<CardActionArea>
  <Button onClick={handleShow}>
    { show ? text : text.substr(0, 100) + "..." }
  </Button>
</CardActionArea>
```

I think CardActionArea is a button component, it makes a nested button now.

But if I declare href property in button, it doesn't make a warning.

Is there a good way that doesn't make a warning not using href property?

答:
Issue: With your code you've placed a button within a button which is a no-no.

From the Material-UI CardActionArea docs

Inheritance

The props of the ButtonBase component are also available. You can take
  advantage of this behavior to target nested components.

And if you cruise on over to the ButtonBase docs you'll see it is by default a 'button' component.

Option 1: Move button logic to CardActionArea and set the component prop of the Button to anything not a button, like a span. This makes the entire card action area have the onClick handler and responsive.

```<code><CardActionArea onClick={handleShow}>
  <Button component="span">
    { show ? text : text.substr(0, 100) + "..." }
  </Button>
</CardActionArea>
</code>```

Option 2: Keep as-is and set the component prop of the CardActionArea to anything other than 'button'. This will leave only the button with the onClick handler, the card action area will register clicks, i.e. the ripple effect, but will by unresponsive otherwise.

```<code><CardActionArea component="span">
  <Button onClick={handleShow}>
    { show ? text : text.substr(0, 100) + "..." }
  </Button>
</CardActionArea>
</code>```

Between the two option 1 is, IMO, the preferred option as it makes the entire action area responsive, but this is based entirely on only the facts presented and your needs/design could be different or more complex.

Body:
I'm making a website using React.

When my website has lots of text, I'll show a button such as show more or less.

In my project, It works well, but always show a warning about validateDOMNesting(...): <button>

My sample code like this.

const [show, setShow] = useState(false);

function handleShow() {
  show ? setShow(false) : setShow(true);
}

<CardActionArea>
  <Button onClick={handleShow}>
    { show ? text : text.substr(0, 100) + "..." }
  </Button>
</CardActionArea>

I think CardActionArea is a button component, it makes a nested button now.

But if I declare href property in button, it doesn't make a warning.

Is there a good way that doesn't make a warning not using href property?

Body:
Issue: With your code you've placed a button within a button which is a no-no.

From the Material-UI CardActionArea docs

Inheritance

The props of the ButtonBase component are also available. You can take
  advantage of this behavior to target nested components.

And if you cruise on over to the ButtonBase docs you'll see it is by default a 'button' component.

Option 1: Move button logic to CardActionArea and set the component prop of the Button to anything not a button, like a span. This makes the entire card action area have the onClick handler and responsive.

<CardActionArea onClick={handleShow}>
  <Button component="span">
    { show ? text : text.substr(0, 100) + "..." }
  </Button>
</CardActionArea>

Option 2: Keep as-is and set the component prop of the CardActionArea to anything other than 'button'. This will leave only the button with the onClick handler, the card action area will register clicks, i.e. the ripple effect, but will by unresponsive otherwise.

<CardActionArea component="span">
  <Button onClick={handleShow}>
    { show ? text : text.substr(0, 100) + "..." }
  </Button>
</CardActionArea>

Between the two option 1 is, IMO, the preferred option as it makes the entire action area responsive, but this is based entirely on only the facts presented and your needs/design could be different or more complex.


问:
Retrofit returns null, expecting string?
I'm a complete Android beginner. Below are the various components. Overall, I'm trying to get the value at a column (entered as a parameter) given a username.

```<code>Call<DefaultResponse> call2 = RetrofitClient.getInstance().getApi().getInformation("fullname","billy@gmail.com");

    call2.enqueue(new Callback<DefaultResponse>() {
        @Override
        public void onResponse(Call<DefaultResponse> call2, Response<DefaultResponse> response) {

            String informationReturned = response.body().getMsg();
            textView.append("\n"+informationReturned);
        }

        @Override
        public void onFailure(Call<DefaultResponse> call2, Throwable t) {

        }

    });
</code>```

The DefaultResponse class:

```<code>import com.google.gson.annotations.SerializedName;

public class DefaultResponse {

    @SerializedName("error")
    private boolean err;

    @SerializedName("message")
    private String msg;

    public DefaultResponse(boolean err, String msg) {
        this.err = err;
        this.msg = msg;
    }

    public boolean isErr() {
        return err;
    }

    public String getMsg() {
        return msg;
    }
}
</code>```

The get call

```<code>@GET("getInformation/{field}/{username}")
Call<DefaultResponse> getInformation(@Path("field") String field, @Path("username") String username);
</code>```

The weird part is the PHP code works fine, as confirmed by Postman when I entered GET command http://localhost/MyApi/public/getInformation/fullname/billy@gmail.com

Any guidance would be greatly appreciated! I don't really know how to get psat this and I've been troubleshooting for hours :(

答:
you said you are expecting a string so you could use call with the String type directly in this way.

```<code>Call<String> call2 = RetrofitClient.getInstance().getApi().getInformation("fullname","billy@gmail.com");

call2.enqueue(new Callback<String>() {
    @Override
    public void onResponse(Call<String> call2, Response<String> response) {

        String informationReturned = response.body().getMsg();
        textView.append("\n"+informationReturned);
    }

    @Override
    public void onFailure(Call<String> call2, Throwable t) {

    }
});
</code>```

you can get call like this

```<code>    @GET("getInformation/{field}/{username}")
Call < String > getInformation(@Path("field") String field, @Path("username") String username);
</code>```

Body:
I'm a complete Android beginner. Below are the various components. Overall, I'm trying to get the value at a column (entered as a parameter) given a username.

Call<DefaultResponse> call2 = RetrofitClient.getInstance().getApi().getInformation("fullname","billy@gmail.com");

    call2.enqueue(new Callback<DefaultResponse>() {
        @Override
        public void onResponse(Call<DefaultResponse> call2, Response<DefaultResponse> response) {

            String informationReturned = response.body().getMsg();
            textView.append("\n"+informationReturned);
        }

        @Override
        public void onFailure(Call<DefaultResponse> call2, Throwable t) {

        }

    });

The DefaultResponse class:

import com.google.gson.annotations.SerializedName;

public class DefaultResponse {

    @SerializedName("error")
    private boolean err;

    @SerializedName("message")
    private String msg;

    public DefaultResponse(boolean err, String msg) {
        this.err = err;
        this.msg = msg;
    }

    public boolean isErr() {
        return err;
    }

    public String getMsg() {
        return msg;
    }
}

The get call

@GET("getInformation/{field}/{username}")
Call<DefaultResponse> getInformation(@Path("field") String field, @Path("username") String username);

The weird part is the PHP code works fine, as confirmed by Postman when I entered GET command http://localhost/MyApi/public/getInformation/fullname/billy@gmail.com

Any guidance would be greatly appreciated! I don't really know how to get psat this and I've been troubleshooting for hours :(

Body:
you said you are expecting a string so you could use call with the String type directly in this way.

Call<String> call2 = RetrofitClient.getInstance().getApi().getInformation("fullname","billy@gmail.com");

call2.enqueue(new Callback<String>() {
    @Override
    public void onResponse(Call<String> call2, Response<String> response) {

        String informationReturned = response.body().getMsg();
        textView.append("\n"+informationReturned);
    }

    @Override
    public void onFailure(Call<String> call2, Throwable t) {

    }
});

you can get call like this

    @GET("getInformation/{field}/{username}")
Call < String > getInformation(@Path("field") String field, @Path("username") String username);


问:
How to add commas to number every 3 digits in Objective C?
If I have a number int aNum = 2000000 how do I format this so that I can display it as the NSString 2,000,000?

答:
For those who need to do it with strings of numbers and not just integers (I.e. Big Numbers) I made the following macro:</p>

```<code>#define addCommas(__string) (\
(^NSString *(void){\
NSString *__numberString = __string;\
NSString *__integerPortion = __numberString;\
NSString *__decimalPortion = @"";\
if ([__string containsString:@"."]) {\
__integerPortion = [__numberString componentsSeparatedByString:@"."][0];\
__decimalPortion = st(@".%@", [__numberString componentsSeparatedByString:@"."][1]);\
}\
int __i = (int)__integerPortion.length-3;\
while (__i > 0) {\
__integerPortion = st(@"%@,%@", substringInRange(__integerPortion, 0, __i), substringInRange(__integerPortion, __i, (int)__integerPortion.length));\
__i -= 3;\
}\
__numberString = st(@"%@%@", __integerPortion, __decimalPortion);\
return __numberString;\
})()\
)
</code>```

ContentLicense: CC BY-SA 2.5

Body:
For those who need to do it with strings of numbers and not just integers (I.e. Big Numbers) I made the following macro:

#define addCommas(__string) (\
(^NSString *(void){\
NSString *__numberString = __string;\
NSString *__integerPortion = __numberString;\
NSString *__decimalPortion = @"";\
if ([__string containsString:@"."]) {\
__integerPortion = [__numberString componentsSeparatedByString:@"."][0];\
__decimalPortion = st(@".%@", [__numberString componentsSeparatedByString:@"."][1]);\
}\
int __i = (int)__integerPortion.length-3;\
while (__i > 0) {\
__integerPortion = st(@"%@,%@", substringInRange(__integerPortion, 0, __i), substringInRange(__integerPortion, __i, (int)__integerPortion.length));\
__i -= 3;\
}\
__numberString = st(@"%@%@", __integerPortion, __decimalPortion);\
return __numberString;\
})()\
)


问:
How to define an optional entry point into custom Mac OS X framework / dynamic library?
In Windows there is a DllMain and DLL_PROCESS_ATTACH / DLL_PROCESS_DETACH flags, which allow to initialize / free resources after DLL is attached to a process... So how can I specify an entry point in case of OS X? As always, I can't find anything useful in Apple documentation :(

答:
Wouldn't that work?</p>

```<code>__attribute__((constructor)) void DllMain()
{
  // code
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Wouldn't that work?

__attribute__((constructor)) void DllMain()
{
  // code
}


问:
How to calculate the shipping cost based on distance
I wrote the following code which takes 2 inputs from user

weight of package

miles

I'm having trouble with the miles part.

This is part of my homework which asks to write a code that outputs the following (regarding the miles):

The program calculates the cost to ship based on distance.it cost
  $6.66 for each 250 miles or part thereof. For example, if the distance
  is 251 miles then the cost based on distance is $13.32. I need help
  with this part.

This is the code I wrote so far:

```<code>#include <stdio.h>

int main() {

    //*** Naming of variables
    float weight;
    int distance;
    float costpackageweight;
    float costdistancetoship;
    //*** asking user for first input of the number of miles to ship a package
    printf(" Please enter the number of miles to ship the package \n");
    scanf_s("%d", &distance);

    //*** asking user for 2nd input of the weight of the package to ship
    printf(" Please enter the weight of the package to ship \n");
    scanf_s("%f", &weight);

    printf(" Package weight is %.2lf pounds. \n", weight);

    printf(" Distance to ship is %d miles. \n", distance);

    if (weight <= 10) {
        printf(" Cost to ship based on weight is..: $10.00 \n");
    }
    else if (weight > 10) {
        costpackageweight = (weight - 10) * 1.55f;
        printf(" Cost to ship based on weight is..: $%.2lf \n", costpackageweight);
    }

    if (distance < 250) {
        printf(" Cost to ship based on distance is: $6.66 \n");
    }
    else if (distance > 250) {
        costdistancetoship = (distance % 250)*6.66f;
        printf(" Cost to ship based on distance is: %.2lf \n", costdistancetoship);
    }
}
</code>```

答:
You could do the following in order to find the multipler needed:

```<code>#include <stdio.h>

int main(void) {
//*** Naming of variables
float weight;
int distance, distanceMul;
float costpackageweight;
float costdistancetoship;
//*** asking user for first input of the number of miles to ship a package
printf(" Please enter the number of miles to ship the package \n");
scanf("%d", &distance);

//*** asking user for 2nd input of the weight of the package to ship
printf(" Please enter the weight of the package to ship \n");
scanf("%f", &weight);

printf(" Package weight is %.2lf pounds. \n", weight);

printf(" Distance to ship is %d miles. \n", distance);

if (weight <= 10) {
    printf(" Cost to ship based on weight is..: $10.00 \n");
}
else if (weight > 10) {
    costpackageweight = (weight - 10) * 1.55f;
    printf(" Cost to ship based on weight is..: $%.2lf \n", costpackageweight);
}

distanceMul = (distance + 249) / 250;
printf("%d\n", distanceMul);
costdistancetoship = distanceMul * 6.66f;
printf(" Cost to ship based on distance is:%.2lf \n", costdistancetoship);

}
</code>```

Without using the if-else it is unnecessary.

The logic is:

When you divide the distance by 250, it will be casted to int type no matter the result, but because you need to start from 1 you add 1. Once calculated the desired multiplier you should just multiply it by the cost to get the desired result no matter what is the distance.

250 miles -> 1 * 6.66

251 miles -> 2 * 6.66

503 miles -> 3 * 6.66

Body:
I wrote the following code which takes 2 inputs from user

weight of package

miles

I'm having trouble with the miles part.

This is part of my homework which asks to write a code that outputs the following (regarding the miles):

The program calculates the cost to ship based on distance.it cost
  $6.66 for each 250 miles or part thereof. For example, if the distance
  is 251 miles then the cost based on distance is $13.32. I need help
  with this part.

This is the code I wrote so far:

#include <stdio.h>

int main() {

    //*** Naming of variables
    float weight;
    int distance;
    float costpackageweight;
    float costdistancetoship;
    //*** asking user for first input of the number of miles to ship a package
    printf(" Please enter the number of miles to ship the package \n");
    scanf_s("%d", &distance);

    //*** asking user for 2nd input of the weight of the package to ship
    printf(" Please enter the weight of the package to ship \n");
    scanf_s("%f", &weight);

    printf(" Package weight is %.2lf pounds. \n", weight);

    printf(" Distance to ship is %d miles. \n", distance);

    if (weight <= 10) {
        printf(" Cost to ship based on weight is..: $10.00 \n");
    }
    else if (weight > 10) {
        costpackageweight = (weight - 10) * 1.55f;
        printf(" Cost to ship based on weight is..: $%.2lf \n", costpackageweight);
    }

    if (distance < 250) {
        printf(" Cost to ship based on distance is: $6.66 \n");
    }
    else if (distance > 250) {
        costdistancetoship = (distance % 250)*6.66f;
        printf(" Cost to ship based on distance is: %.2lf \n", costdistancetoship);
    }
}

Body:
You could do the following in order to find the multipler needed:

#include <stdio.h>

int main(void) {
//*** Naming of variables
float weight;
int distance, distanceMul;
float costpackageweight;
float costdistancetoship;
//*** asking user for first input of the number of miles to ship a package
printf(" Please enter the number of miles to ship the package \n");
scanf("%d", &distance);

//*** asking user for 2nd input of the weight of the package to ship
printf(" Please enter the weight of the package to ship \n");
scanf("%f", &weight);

printf(" Package weight is %.2lf pounds. \n", weight);

printf(" Distance to ship is %d miles. \n", distance);

if (weight <= 10) {
    printf(" Cost to ship based on weight is..: $10.00 \n");
}
else if (weight > 10) {
    costpackageweight = (weight - 10) * 1.55f;
    printf(" Cost to ship based on weight is..: $%.2lf \n", costpackageweight);
}

distanceMul = (distance + 249) / 250;
printf("%d\n", distanceMul);
costdistancetoship = distanceMul * 6.66f;
printf(" Cost to ship based on distance is:%.2lf \n", costdistancetoship);

}

Without using the if-else it is unnecessary.

The logic is:

When you divide the distance by 250, it will be casted to int type no matter the result, but because you need to start from 1 you add 1. Once calculated the desired multiplier you should just multiply it by the cost to get the desired result no matter what is the distance.

250 miles -> 1 * 6.66

251 miles -> 2 * 6.66

503 miles -> 3 * 6.66


问:
What is `AS $$` in sql functions?

CREATE FUNCTION one() RETURNS integer AS $$
    SELECT 1 AS result;
$$ LANGUAGE SQL;
```

<p>why i cant write like this:</p>

<pre class="lang-sql prettyprint-override"><code>CREATE FUNCTION one() RETURNS integer
    SELECT 1 AS result;
</code>```

what is AS $$?

what is $$ LANGUAGE SQL?

what is $$?

答:
In PostgreSQL it is a feature called dollar-quoting, which allows you to include a body of text without escaping the single quotes

Using it as

```<code>CREATE OR REPLACE FUNCTION hello_world(param_your_name text)
RETURNS text AS
$$
SELECT 'Hello world. My name is ' || param_your_name || '.';
$$
language sql STRICT;
</code>```

which is easier to read than

```<code>CREATE OR REPLACE FUNCTION hello_world(param_your_name text)
RETURNS text AS
'
SELECT ''Hello world. My name is '' || param_your_name || ''.'';
'
language sql STRICT;
</code>```

Read more here - https://www.postgresonline.com/journal/archives/376-Dollar-quoting-for-escaping-single-quotes.html

Title: What is `AS $$` in sql functions?

Body:
CREATE FUNCTION one() RETURNS integer AS $$
    SELECT 1 AS result;
$$ LANGUAGE SQL;

why i cant write like this:

CREATE FUNCTION one() RETURNS integer
    SELECT 1 AS result;

what is AS $$?

what is $$ LANGUAGE SQL?

what is $$?

Body:
In PostgreSQL it is a feature called dollar-quoting, which allows you to include a body of text without escaping the single quotes

Using it as

CREATE OR REPLACE FUNCTION hello_world(param_your_name text)
RETURNS text AS
$$
SELECT 'Hello world. My name is ' || param_your_name || '.';
$$
language sql STRICT;

which is easier to read than

CREATE OR REPLACE FUNCTION hello_world(param_your_name text)
RETURNS text AS
'
SELECT ''Hello world. My name is '' || param_your_name || ''.'';
'
language sql STRICT;

Read more here - https://www.postgresonline.com/journal/archives/376-Dollar-quoting-for-escaping-single-quotes.html


问:
Can't use with import in Pytorch
When I import torch, there's a problem like this:

```<code>C: lUsers / ruiha Desktopl flappy_DQL>python flappy.py
Traceback (most recent call last):
File "flappy.py", line 2, in <module>
import torch
File "C: IUsers I rui ha /AppDat a / Local Programs I Python/ Python37 libIsite-packagesI torchl__init__.py", line 81, in <mod
ctypes.CDLL(dll)
File "C: LUsersI ruiha lAppDat a l Local | Programs I Python/ Python37 liblctypesl__init_.py", line 364, in _init_
self._handle = _dlopen(self._name, mode)
OSError: [WinError 126] The specified module could not be found
</code>```

答:
Since this is a very common problem when you have multiple versions of pythons. It is recommended to use a virtual environment to avoid this:

```<code>python3 -m venv pytorch-env
pytorch-env\Scripts\activate.bat
...
pip install ...

python flappy.py
</code>```

See more information at https://docs.python.org/3/tutorial/venv.html.
Good luck!

Title: Can't use with import in Pytorch

Body:
When I import torch, there's a problem like this:

C: lUsers / ruiha Desktopl flappy_DQL>python flappy.py
Traceback (most recent call last):
File "flappy.py", line 2, in <module>
import torch
File "C: IUsers I rui ha /AppDat a / Local Programs I Python/ Python37 libIsite-packagesI torchl__init__.py", line 81, in <mod
ctypes.CDLL(dll)
File "C: LUsersI ruiha lAppDat a l Local | Programs I Python/ Python37 liblctypesl__init_.py", line 364, in _init_
self._handle = _dlopen(self._name, mode)
OSError: [WinError 126] The specified module could not be found

Body:
Since this is a very common problem when you have multiple versions of pythons. It is recommended to use a virtual environment to avoid this:

python3 -m venv pytorch-env
pytorch-env\Scripts\activate.bat
...
pip install ...

python flappy.py

See more information at https://docs.python.org/3/tutorial/venv.html.
Good luck!


问:
Highlight a specific part of the text in SwiftUI
Hello I'm new to Swift and am using SwiftUI for my project where I download some weather data and I display it in the ContentView().

I would like to highlight some part of the Text if it contains some specific word, but I don't have any idea how to start.

In ContentView(), I have tried to set a function receiving the string downloaded from web and return a string. I believe this is wrong, because SwiftUI does not apply the modifiers at the all for the Text.

For example, in my ContentView() I would like the word thunderstorm to have the .bold() modifier:

```<code>struct ContentView: View {
  let testo : String = "There is a thunderstorm in the area"

  var body: some View {
    Text(highlight(str: testo))
  }

  func highlight(str: String) -> String {
    let textToSearch = "thunderstorm"
    var result = ""

    if str.contains(textToSearch) {
      let index = str.startIndex
      result = String( str[index])
    }

    return result
  }

}
</code>```

答:
iOS 13, Swift 5. There is a generic solution described in this medium article. Using it you can highlight any text anywhere with the only catch being it cannot be more then 64 characters in length, since it using bitwise masks.

https://medium.com/@marklucking/an-interesting-challenge-with-swiftui-9ebb26e77376

This is the basic code in the article.

```<code>ForEach((0 ..< letter.count), id: \.self) { column in
      Text(letter[column])
        .foregroundColor(colorCode(gate: Int(self.gate), no: column) ? Color.black: Color.red)
        .font(Fonts.futuraCondensedMedium(size: fontSize))

    }
</code>```

And this one to mask the text...

```<code>func colorCode(gate:Int, no:Int) -> Bool {

 let bgr = String(gate, radix:2).pad(with: "0", toLength: 16)
 let bcr = String(no, radix:2).pad(with: "0", toLength: 16)
 let binaryColumn = 1 << no - 1

 let value = UInt64(gate) & UInt64(binaryColumn)
 let vr = String(value, radix:2).pad(with: "0", toLength: 16)

 print("bg ",bgr," bc ",bcr,vr)
 return value > 0 ? true:false
}
</code>```

Body:
Hello I'm new to Swift and am using SwiftUI for my project where I download some weather data and I display it in the ContentView().

I would like to highlight some part of the Text if it contains some specific word, but I don't have any idea how to start.

In ContentView(), I have tried to set a function receiving the string downloaded from web and return a string. I believe this is wrong, because SwiftUI does not apply the modifiers at the all for the Text.

For example, in my ContentView() I would like the word thunderstorm to have the .bold() modifier:

struct ContentView: View {
  let testo : String = "There is a thunderstorm in the area"

  var body: some View {
    Text(highlight(str: testo))
  }

  func highlight(str: String) -> String {
    let textToSearch = "thunderstorm"
    var result = ""

    if str.contains(textToSearch) {
      let index = str.startIndex
      result = String( str[index])
    }

    return result
  }

}

Body:
iOS 13, Swift 5. There is a generic solution described in this medium article. Using it you can highlight any text anywhere with the only catch being it cannot be more then 64 characters in length, since it using bitwise masks.

https://medium.com/@marklucking/an-interesting-challenge-with-swiftui-9ebb26e77376

This is the basic code in the article.

ForEach((0 ..< letter.count), id: \.self) { column in
      Text(letter[column])
        .foregroundColor(colorCode(gate: Int(self.gate), no: column) ? Color.black: Color.red)
        .font(Fonts.futuraCondensedMedium(size: fontSize))

    }

And this one to mask the text...

func colorCode(gate:Int, no:Int) -> Bool {

 let bgr = String(gate, radix:2).pad(with: "0", toLength: 16)
 let bcr = String(no, radix:2).pad(with: "0", toLength: 16)
 let binaryColumn = 1 << no - 1

 let value = UInt64(gate) & UInt64(binaryColumn)
 let vr = String(value, radix:2).pad(with: "0", toLength: 16)

 print("bg ",bgr," bc ",bcr,vr)
 return value > 0 ? true:false
}


问:
Create a New Column by evaluating multiple columns
I have a data.frame dt_info that looks like the following:

```<code>date       col_1     col_2    col_3  ... col_100
d/m/y       info1     n/a      n/a   ...  n/a
d/m/y       n/a       n/a     info2  ...  n/a
d/m/y       n/a       n/a       n/a  ...  infon
</code>```

The output I'm looking for should be like this:

```<code>date       col_1     col_2    col_3  ... col_100    new_col
d/m/y       info1     n/a      n/a   ...  n/a         info1
d/m/y       n/a       n/a     info2  ...  n/a         info2
d/m/y       n/a       n/a       n/a  ...  infon       infon
</code>```

I'm using this code line

```<code>dt_info$new_col <- apply(dt_info[2],1, function(x){
ifelse(x != "n/a", x, "")})
</code>```

That kinda do what I want but I have two issues
I'm not able to go do it for each column using [1:n]
If I change Manually the [] index and run the code, the whole column got replaced.

What am I lacking in my script?
Is there another way to achieve what I'm trying to do?

答:
You may easily subset your data row-wise to the elements that are not (!) %in% "n/a".

```<code>dt_info$new_col <- apply(dt_info[-1], 1, function(x) x[!x %in% "n/a"])
dt_info
#    date col_1 col_2 col_3 col_100 new_col
# 1 d/m/y info1   n/a   n/a     n/a   info1
# 2 d/m/y   n/a   n/a info2     n/a   info2
# 3 d/m/y   n/a   n/a   n/a   infon   infon
</code>```

However, the "n/a" strings are a bit strange; you could make them "true" NA,

```<code>dt_info2 <- as.data.frame(lapply(dt_info, function(x) {x[x %in% "n/a"] <- NA;x}))
</code>```

and use na.omit then, which is much more efficient.

```<code>dt_info2$new_col <- apply(dt_info2[-1], 1, na.omit)
#    date col_1 col_2 col_3 col_100 new_col
# 1 d/m/y info1  <NA>  <NA>    <NA>   info1
# 2 d/m/y  <NA>  <NA> info2    <NA>   info2
# 3 d/m/y  <NA>  <NA>  <NA>   infon   infon
</code>```

Data:

```<code>dt_info <- read.table(header=TRUE, text="date       col_1     col_2    col_3   col_100
'd/m/y'       info1     'n/a'      'n/a'     'n/a'
'd/m/y'       'n/a'       'n/a'     info2    'n/a'
'd/m/y'       'n/a'       'n/a'       'n/a'    infon")
</code>```

Body:
I have a data.frame dt_info that looks like the following:

date       col_1     col_2    col_3  ... col_100
d/m/y       info1     n/a      n/a   ...  n/a
d/m/y       n/a       n/a     info2  ...  n/a
d/m/y       n/a       n/a       n/a  ...  infon

The output I'm looking for should be like this:

date       col_1     col_2    col_3  ... col_100    new_col
d/m/y       info1     n/a      n/a   ...  n/a         info1
d/m/y       n/a       n/a     info2  ...  n/a         info2
d/m/y       n/a       n/a       n/a  ...  infon       infon

I'm using this code line

dt_info$new_col <- apply(dt_info[2],1, function(x){
ifelse(x != "n/a", x, "")})

That kinda do what I want but I have two issues
I'm not able to go do it for each column using [1:n]
If I change Manually the [] index and run the code, the whole column got replaced.

What am I lacking in my script?
Is there another way to achieve what I'm trying to do?

Body:
You may easily subset your data row-wise to the elements that are not (!) %in% "n/a".

dt_info$new_col <- apply(dt_info[-1], 1, function(x) x[!x %in% "n/a"])
dt_info
#    date col_1 col_2 col_3 col_100 new_col
# 1 d/m/y info1   n/a   n/a     n/a   info1
# 2 d/m/y   n/a   n/a info2     n/a   info2
# 3 d/m/y   n/a   n/a   n/a   infon   infon

However, the "n/a" strings are a bit strange; you could make them "true" NA,

dt_info2 <- as.data.frame(lapply(dt_info, function(x) {x[x %in% "n/a"] <- NA;x}))

and use na.omit then, which is much more efficient.

dt_info2$new_col <- apply(dt_info2[-1], 1, na.omit)
#    date col_1 col_2 col_3 col_100 new_col
# 1 d/m/y info1  <NA>  <NA>    <NA>   info1
# 2 d/m/y  <NA>  <NA> info2    <NA>   info2
# 3 d/m/y  <NA>  <NA>  <NA>   infon   infon

Data:

dt_info <- read.table(header=TRUE, text="date       col_1     col_2    col_3   col_100
'd/m/y'       info1     'n/a'      'n/a'     'n/a'
'd/m/y'       'n/a'       'n/a'     info2    'n/a'
'd/m/y'       'n/a'       'n/a'       'n/a'    infon")


问:
swift CoreData predicates to filter all the child data of a given parent
There are two entities Child and Parent. Parent and Child is one to many relationship, one Parent with many Child.

The code I referred to is as following and it can filter all the data of Child level whose Attribute text contains yes:

```<code>@State private var predicate: NSPredicate? = NSPredicate(format: "text contains[c] %@", "yes")
@ObservedObject private var db = CoreDataDB<Child>()

for child in self.db.loadDB(predicate: self.predicate):
    ....
</code>```

What I want to do is to get all the Child level's data belong to current Child data's Parent.

```<code>var child: Child

// How to write this line???
@State private var predicate: NSPredicate? = NSPredicate(format: "parent = %@", "self.child.parent")

@ObservedObject private var db = CoreDataDB<Child>()

for child in self.db.loadDB(predicate: self.predicate):
    ....
</code>```

I do not know how to write the predicate above to filter data that belong to the same Parent with current child in current child's View.

NSPredicate(format: "parent = %@", "self.child.parent") will get nothing when for child in self.db.loadDB(predicate: self.predicate):.

NSPredicate(format: "child.parent = %@", "self.child.parent") will get error saying keypath child.parent not found in entity <NSSQLEntity Child id=1> with userInfo of (null)

What I need to say is that text of Child Entity in the code is an Attribute I created, but parent of Child Entity is auto created by the one to many relationship with Parent Entity. I cannot see parent Attribute in xcdataModelId file but I can use it in the code.

Thanks for any help.

答:
Here

```<code>NSPredicate(format: "parent = %@", "self.child.parent")
</code>```

you substitute a string for the %@ placeholder. What you want is

```<code>NSPredicate(format: "parent = %@", self.child.parent)
</code>```

which searches for all entities whose parent is equal to the parent of self.child.

Body:
There are two entities Child and Parent. Parent and Child is one to many relationship, one Parent with many Child.

The code I referred to is as following and it can filter all the data of Child level whose Attribute text contains yes:

@State private var predicate: NSPredicate? = NSPredicate(format: "text contains[c] %@", "yes")
@ObservedObject private var db = CoreDataDB<Child>()

for child in self.db.loadDB(predicate: self.predicate):
    ....

What I want to do is to get all the Child level's data belong to current Child data's Parent.

var child: Child

// How to write this line???
@State private var predicate: NSPredicate? = NSPredicate(format: "parent = %@", "self.child.parent")

@ObservedObject private var db = CoreDataDB<Child>()

for child in self.db.loadDB(predicate: self.predicate):
    ....

I do not know how to write the predicate above to filter data that belong to the same Parent with current child in current child's View.

NSPredicate(format: "parent = %@", "self.child.parent") will get nothing when for child in self.db.loadDB(predicate: self.predicate):.

NSPredicate(format: "child.parent = %@", "self.child.parent") will get error saying keypath child.parent not found in entity <NSSQLEntity Child id=1> with userInfo of (null)

What I need to say is that text of Child Entity in the code is an Attribute I created, but parent of Child Entity is auto created by the one to many relationship with Parent Entity. I cannot see parent Attribute in xcdataModelId file but I can use it in the code.

Thanks for any help.

Body:
Here

NSPredicate(format: "parent = %@", "self.child.parent")

you substitute a string for the %@ placeholder. What you want is

NSPredicate(format: "parent = %@", self.child.parent)

which searches for all entities whose parent is equal to the parent of self.child.


问:
React Navigation - Nested Redirect
I have following Navigation Structure

```<code>const HomeTabNavigator = () => (
    <Tab.Navigator>
        <Tab.Screen name="HomeStackNavigator"/>
        <Tab.Screen name="SearchStackNavigator"/>
        <Tab.Screen name="AccountStackNavigator" />
    </Tab.Navigator>
);

const HomeStackNavigator = () => {
    return (
        <HomeStack.Navigator headerMode="none">
            <HomeStack.Screen name="HomeScreen" component={HomeScreen}/>
        </HomeStack.Navigator>
    )
}

const SearchStackNavigator = () => {
    return (
        <SearchStack.Navigator headerMode="none">
            <SearchStack.Screen name="SearchScreen" component={SearchScreen}/>
            <SearchStack.Screen name="SearchDetailScreen" component={SearchDetailScreen}/>
        </SearchStack.Navigator>
    );
}

const AccountStackNavigator = () => {
    return(
        <AccountStack.Navigator headerMode="none">
            <AccountStack.Screen name="AccountScreen" component={AccountScreen}/>
            <AppointmentStack.Screen name="ItemListScreen" component={ItemListScreen}/>
            <AppointmentStack.Screen name="ItemDetailScreen" component={ItemDetailScreen}/>
        </AccountStack.Navigator>
    );
}
</code>```

From any screen, I want to navigate to ItemDetailScreen found in AccountStackNavigator, let's say, I want to navigate from HomeScreen. However when I click on back button of ItemDetailScreen it must redirect me to ItemListScreen and the back button on this screen must redirect me to AccountScreen.

I am using the following screen for redirect.

```<code>this.props.navigation.navigate('AccountStackNavigator', {
    screen: 'AppointmentListScreen',
    params: {
        screen: 'AccountScreen'
    }
});
</code>```

This redirects me from HomeScreen to AppointmentListScreen and when I click back here, it redirects me to AccountScreen which is perfect. Now here is my Issue, when I use this code.

```<code>this.props.navigation.navigate('AccountStackNavigator', {
    screen: 'AppointmentDetailScreen',
    params: {
        screen: 'AppointmentListScreen',
        params: {
            screen: 'AccountScreen'
        }
    }
});
</code>```

It redirects me to AppointmentDetailScreen perfectly, however, when I click on back button here, it redirects me to HomeScreen whereas I want it to be redirected with the following flow.

```<code>AppointmentDetailScreen > AppointmentListScreen > AccountScreen
</code>```

I have tried so many way to achieve this, but nothing seems to work for me, can anyone help in right direction please.

Thank you.

答: It was frustrating using @react-navigation/bottom-tabs to achieve this mainly because it lacks animation between switching screens giving user a weird experience, hence I moved to @react-navigation/material-top-tabs and it worked well.

Title: React Navigation - Nested Redirect

Body:
I have following Navigation Structure

const HomeTabNavigator = () => (
    <Tab.Navigator>
        <Tab.Screen name="HomeStackNavigator"/>
        <Tab.Screen name="SearchStackNavigator"/>
        <Tab.Screen name="AccountStackNavigator" />
    </Tab.Navigator>
);

const HomeStackNavigator = () => {
    return (
        <HomeStack.Navigator headerMode="none">
            <HomeStack.Screen name="HomeScreen" component={HomeScreen}/>
        </HomeStack.Navigator>
    )
}

const SearchStackNavigator = () => {
    return (
        <SearchStack.Navigator headerMode="none">
            <SearchStack.Screen name="SearchScreen" component={SearchScreen}/>
            <SearchStack.Screen name="SearchDetailScreen" component={SearchDetailScreen}/>
        </SearchStack.Navigator>
    );
}

const AccountStackNavigator = () => {
    return(
        <AccountStack.Navigator headerMode="none">
            <AccountStack.Screen name="AccountScreen" component={AccountScreen}/>
            <AppointmentStack.Screen name="ItemListScreen" component={ItemListScreen}/>
            <AppointmentStack.Screen name="ItemDetailScreen" component={ItemDetailScreen}/>
        </AccountStack.Navigator>
    );
}

From any screen, I want to navigate to ItemDetailScreen found in AccountStackNavigator, let's say, I want to navigate from HomeScreen. However when I click on back button of ItemDetailScreen it must redirect me to ItemListScreen and the back button on this screen must redirect me to AccountScreen.

I am using the following screen for redirect.

this.props.navigation.navigate('AccountStackNavigator', {
    screen: 'AppointmentListScreen',
    params: {
        screen: 'AccountScreen'
    }
});

This redirects me from HomeScreen to AppointmentListScreen and when I click back here, it redirects me to AccountScreen which is perfect. Now here is my Issue, when I use this code.

this.props.navigation.navigate('AccountStackNavigator', {
    screen: 'AppointmentDetailScreen',
    params: {
        screen: 'AppointmentListScreen',
        params: {
            screen: 'AccountScreen'
        }
    }
});

It redirects me to AppointmentDetailScreen perfectly, however, when I click on back button here, it redirects me to HomeScreen whereas I want it to be redirected with the following flow.

AppointmentDetailScreen > AppointmentListScreen > AccountScreen

I have tried so many way to achieve this, but nothing seems to work for me, can anyone help in right direction please.

Thank you.


问:
Why do I get a traceback error when importing my own modules?
When I tried to import one of my modules such as from the file call.py:

```<code>def call_name1(name) :
    print(name.title(), 'is present!')
</code>```

Into the test file test.py:

```<code>import call

call_name1('kevin')
</code>```

It gives me a traceback error :

```<code>Traceback (most recent call last):
  File "/Users/kahsengho/PycharmProjects/Projects/test.py", line 3, in <module>
    call_name1('lebron')
NameError: name 'call_name1' is not defined
</code>```

What have I done wrong? Because I have placed these two files in the same folder.

答:
I found a working code for this!</p>

```<code>import call

call.call_name1('Kevin')
</code>```

Body:
When I tried to import one of my modules such as from the file call.py:

def call_name1(name) :
    print(name.title(), 'is present!')

Into the test file test.py:

import call

call_name1('kevin')

It gives me a traceback error :

Traceback (most recent call last):
  File "/Users/kahsengho/PycharmProjects/Projects/test.py", line 3, in <module>
    call_name1('lebron')
NameError: name 'call_name1' is not defined

What have I done wrong? Because I have placed these two files in the same folder.

Body:
I found a working code for this!

import call

call.call_name1('Kevin')


问:
How to get a UITableView's visible sections?
UITableView provides the methods indexPathsForVisibleRows and visibleCells, but how can I get the visible sections?

答:
Swift 4 and Swift 5

We can do the following since an empty section could still have a visible header view:

```<code>extension UITableView {

    var indexesOfVisibleSections: [Int] {
        var indexes = [Int]()
        (0 ..< numberOfSections).forEach {
            let headerRect = (style == .plain ?
                              rect(forSection: $0) :
                              rectForHeader(inSection: $0))
            // The "visible part" of the tableView is based on the
            // content offset and the tableView's size.
            let visiblePartOfTableView =
                CGRect(x: contentOffset.x, y: contentOffset.y,
                       width: bounds.size.width, height: bounds.size.height)
            if (visiblePartOfTableView.intersects(headerRect)) {
                indexes.append($0)
            }
        }
        return indexes
    }

}
</code>```

Body:
Swift 4 and Swift 5

We can do the following since an empty section could still have a visible header view:

extension UITableView {

    var indexesOfVisibleSections: [Int] {
        var indexes = [Int]()
        (0 ..< numberOfSections).forEach {
            let headerRect = (style == .plain ?
                              rect(forSection: $0) :
                              rectForHeader(inSection: $0))
            // The "visible part" of the tableView is based on the
            // content offset and the tableView's size.
            let visiblePartOfTableView =
                CGRect(x: contentOffset.x, y: contentOffset.y,
                       width: bounds.size.width, height: bounds.size.height)
            if (visiblePartOfTableView.intersects(headerRect)) {
                indexes.append($0)
            }
        }
        return indexes
    }

}


问:
I have Eyelid bones set up (and working) in Blender, but I can't figure out how to control the bones in Unity
In Blender I have a bone on each eyelid. In Blender, they make the character's eyelids move up and down, as expected.

But I can't figure out how to get that same behavior going on in Unity. When I import the FBX model into Unity (Armature included) and find an eyelid bone and move its transform, nothing happens to the character's eyelid.

Why would moving the bones in Blender do something, but in Unity nothing happens? Appreciate any help.

Also, I made sure the Rig was 'Humanoid' and that an Avatar was correctly set up, if that matters.

EDIT: The answer was that you use Pose Mode to create Blendshapes and then export the model with those Blendshapes into Unity!! :D

答: The answer was that you move the bones in Pose Mode to create Blendshapes and then export the model with those Blendshapes into Unity!! :D</p>


问:
nswag generated client with wrong response type
This is autogenerated Angular service file from C# controller with help of nswag swagger client generation. This below code has all the services. In component i am trying to call getCompanyInfoOption() api. But i am not getting response data that i am sending from controller.

```<code>/* tslint:disable */
/* eslint-disable */
//----------------------
// <auto-generated>
//     Generated using the NSwag toolchain v13.6.0.0 (NJsonSchema v10.1.18.0 (Newtonsoft.Json v12.0.0.0)) (http://NSwag.org)
// </auto-generated>
//----------------------
// ReSharper disable InconsistentNaming

import { mergeMap as _observableMergeMap, catchError as _observableCatch } from 'rxjs/operators';
import { Observable, throwError as _observableThrow, of as _observableOf } from 'rxjs';
import { Injectable, Inject, Optional, InjectionToken } from '@angular/core';
import { HttpClient, HttpHeaders, HttpResponse, HttpResponseBase } from '@angular/common/http';

export const API_BASE_URL = new InjectionToken<string>('API_BASE_URL');

@Injectable({
providedIn:'root'
})
export class CompanyInfoService {
    private http: HttpClient;
    private baseUrl: string;
    protected jsonParseReviver: ((key: string, value: any) => any) | undefined = undefined;

    constructor(@Inject(HttpClient) http: HttpClient, @Optional() @Inject(API_BASE_URL) baseUrl?: string) {
        this.http = http;
        this.baseUrl = baseUrl ? baseUrl : "https://localhost:44311";
    }

    getCompanyInfoOption(): Observable<FileResponse | null> {
        let url_ = this.baseUrl + "/api/company-info";
        url_ = url_.replace(/[?&]$/, "");

        let options_ : any = {
            observe: "response",
            responseType: "blob",
            headers: new HttpHeaders({
                "Accept": "application/octet-stream"
            })
        };

        return this.http.request("get", url_, options_).pipe(_observableMergeMap((response_ : any) => {
            return this.processGetCompanyInfoOption(response_);
        })).pipe(_observableCatch((response_: any) => {
            if (response_ instanceof HttpResponseBase) {
                try {
                    return this.processGetCompanyInfoOption(<any>response_);
                } catch (e) {
                    return <Observable<FileResponse | null>><any>_observableThrow(e);
                }
            } else
                return <Observable<FileResponse | null>><any>_observableThrow(response_);
        }));
    }

    protected processGetCompanyInfoOption(response: HttpResponseBase): Observable<FileResponse | null> {
        const status = response.status;
        const responseBlob =
            response instanceof HttpResponse ? response.body :
            (<any>response).error instanceof Blob ? (<any>response).error : undefined;

        let _headers: any = {}; if (response.headers) { for (let key of response.headers.keys()) { _headers[key] = response.headers.get(key); }}
        if (status === 200 || status === 206) {
            const contentDisposition = response.headers ? response.headers.get("content-disposition") : undefined;
            const fileNameMatch = contentDisposition ? /filename="?([^"]*?)"?(;|$)/g.exec(contentDisposition) : undefined;
            const fileName = fileNameMatch && fileNameMatch.length > 1 ? fileNameMatch[1] : undefined;
            return _observableOf({ fileName: fileName, data: <any>responseBlob, status: status, headers: _headers });
        } else if (status !== 200 && status !== 204) {
            return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => {
            return throwException("An unexpected server error occurred.", status, _responseText, _headers);
            }));
        }
        return _observableOf<FileResponse | null>(<any>null);
    }
</code>```

how can i call this service in my component? i am trying to call with subscribe method in ngOnInit of component

```<code>  ngOnInit(): void {
      this.service.getCompanyInfoOption().subscribe(
        value => {
          console.log(value);
        },
        error => console.error(JSON.stringify(error)),
        () => console.log('done')
      );
  }
</code>```

I am getting this output after calling getCompanyInfoOption api

Console Log

My c# controller

ASP .net core C# controller

The type of response of compantInfoOption send in ok is given below

conpanyInfoOption type

答:
I guess there is something wrong with the generated code, because your controller return type isn't correct, try using ActionResult, then the generated api will return the proper result instead of expecting a file response. </p>

<p>in your case </p>

```<code>public async Task<ActionResult<CompanyInfoOptionAc>> GetCompanyInfo(){
//etc
}
</code>```

Body:
This is autogenerated Angular service file from C# controller with help of nswag swagger client generation. This below code has all the services. In component i am trying to call getCompanyInfoOption() api. But i am not getting response data that i am sending from controller.

/* tslint:disable */
/* eslint-disable */
//----------------------
// <auto-generated>
//     Generated using the NSwag toolchain v13.6.0.0 (NJsonSchema v10.1.18.0 (Newtonsoft.Json v12.0.0.0)) (http://NSwag.org)
// </auto-generated>
//----------------------
// ReSharper disable InconsistentNaming

import { mergeMap as _observableMergeMap, catchError as _observableCatch } from 'rxjs/operators';
import { Observable, throwError as _observableThrow, of as _observableOf } from 'rxjs';
import { Injectable, Inject, Optional, InjectionToken } from '@angular/core';
import { HttpClient, HttpHeaders, HttpResponse, HttpResponseBase } from '@angular/common/http';

export const API_BASE_URL = new InjectionToken<string>('API_BASE_URL');

@Injectable({
providedIn:'root'
})
export class CompanyInfoService {
    private http: HttpClient;
    private baseUrl: string;
    protected jsonParseReviver: ((key: string, value: any) => any) | undefined = undefined;

    constructor(@Inject(HttpClient) http: HttpClient, @Optional() @Inject(API_BASE_URL) baseUrl?: string) {
        this.http = http;
        this.baseUrl = baseUrl ? baseUrl : "https://localhost:44311";
    }

    getCompanyInfoOption(): Observable<FileResponse | null> {
        let url_ = this.baseUrl + "/api/company-info";
        url_ = url_.replace(/[?&]$/, "");

        let options_ : any = {
            observe: "response",
            responseType: "blob",
            headers: new HttpHeaders({
                "Accept": "application/octet-stream"
            })
        };

        return this.http.request("get", url_, options_).pipe(_observableMergeMap((response_ : any) => {
            return this.processGetCompanyInfoOption(response_);
        })).pipe(_observableCatch((response_: any) => {
            if (response_ instanceof HttpResponseBase) {
                try {
                    return this.processGetCompanyInfoOption(<any>response_);
                } catch (e) {
                    return <Observable<FileResponse | null>><any>_observableThrow(e);
                }
            } else
                return <Observable<FileResponse | null>><any>_observableThrow(response_);
        }));
    }

    protected processGetCompanyInfoOption(response: HttpResponseBase): Observable<FileResponse | null> {
        const status = response.status;
        const responseBlob =
            response instanceof HttpResponse ? response.body :
            (<any>response).error instanceof Blob ? (<any>response).error : undefined;

        let _headers: any = {}; if (response.headers) { for (let key of response.headers.keys()) { _headers[key] = response.headers.get(key); }}
        if (status === 200 || status === 206) {
            const contentDisposition = response.headers ? response.headers.get("content-disposition") : undefined;
            const fileNameMatch = contentDisposition ? /filename="?([^"]*?)"?(;|$)/g.exec(contentDisposition) : undefined;
            const fileName = fileNameMatch && fileNameMatch.length > 1 ? fileNameMatch[1] : undefined;
            return _observableOf({ fileName: fileName, data: <any>responseBlob, status: status, headers: _headers });
        } else if (status !== 200 && status !== 204) {
            return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => {
            return throwException("An unexpected server error occurred.", status, _responseText, _headers);
            }));
        }
        return _observableOf<FileResponse | null>(<any>null);
    }

how can i call this service in my component? i am trying to call with subscribe method in ngOnInit of component

  ngOnInit(): void {
      this.service.getCompanyInfoOption().subscribe(
        value => {
          console.log(value);
        },
        error => console.error(JSON.stringify(error)),
        () => console.log('done')
      );
  }

I am getting this output after calling getCompanyInfoOption api

Console Log

My c# controller

ASP .net core C# controller

The type of response of compantInfoOption send in ok is given below

conpanyInfoOption type

Body:
I guess there is something wrong with the generated code, because your controller return type isn't correct, try using ActionResult, then the generated api will return the proper result instead of expecting a file response.

in your case

public async Task<ActionResult<CompanyInfoOptionAc>> GetCompanyInfo(){
//etc
}


问:
Date selected from calendar control doesn't change in Textbox at runtime
I have to save date selected from  ajax calender control,when i select date from ajax calender control it shows in textbox,but when i save this date i got the previous value of date not the cureently selected value,i have written this code on btnsave_Click event

my .CS code is as follow:

```<code>protected void btnsave_Click(object sender, EventArgs e)
{
    DateTime bdate = DateTime.ParseExact(txtBirthDate.Text, "dd/MM/yyyy", null);
}
</code>```

my .aspx code for calender control:

```<code><td>
    <asp:TextBox ID="txtBirthDate" runat="server" ReadOnly="true"  CssClass="Txtprop" ></asp:TextBox>
    <cc1:CalendarExtender ID="calDOB" runat="server" TargetControlID="txtBirthDate" Format="dd/MM/yyyy" ></cc1:CalendarExtender>
</td>
</code>```

答:
To solve this set the CalendarExtender's SelectedDate in the textbox.Text data = change to whatever it is in the textbox and it will stick. Setting SelectedDate sets the textbox field at the same time.

Easy fix example

```<code>'protected void txDate_TextChanged(object sender, EventArgs e)
{
        txDate_CalendarExtender.SelectedDate = Convert.ToDateTime(txDate.Text);
}'
</code>```

Body:
I have to save date selected from  ajax calender control,when i select date from ajax calender control it shows in textbox,but when i save this date i got the previous value of date not the cureently selected value,i have written this code on btnsave_Click event

my .CS code is as follow:

protected void btnsave_Click(object sender, EventArgs e)
{
    DateTime bdate = DateTime.ParseExact(txtBirthDate.Text, "dd/MM/yyyy", null);
}

my .aspx code for calender control:

    <asp:TextBox ID="txtBirthDate" runat="server" ReadOnly="true"  CssClass="Txtprop" ></asp:TextBox>
    <cc1:CalendarExtender ID="calDOB" runat="server" TargetControlID="txtBirthDate" Format="dd/MM/yyyy" ></cc1:CalendarExtender>

Body:
To solve this set the CalendarExtender's SelectedDate in the textbox.Text data = change to whatever it is in the textbox and it will stick. Setting SelectedDate sets the textbox field at the same time.

Easy fix example

'protected void txDate_TextChanged(object sender, EventArgs e)
{
        txDate_CalendarExtender.SelectedDate = Convert.ToDateTime(txDate.Text);
}'


问:
module 'pandas' has no attribute 'series'
i got this error while running this code

import numpy as np
import pandas as pd
labels = ['a','b','c']
my_list = [10,20,30]
arr = np.array(my_list)
d = {'a':10,'b':20,'c':30}
pd.series(data = my_list)
```

<p>full error msg</p>

<pre class="lang-py prettyprint-override"><code>AttributeError                            Traceback (most recent call last)
<ipython-input-10-494578c29940> in <module>
----> 1 pd.series(data = my_list)

F:\New folder (8)\lib\site-packages\pandas\__init__.py in __getattr__(name)
    260             return _SparseArray
    261
--> 262         raise AttributeError(f"module 'pandas' has no attribute '{name}'")
    263
    264

AttributeError: module 'pandas' has no attribute 'series'
</code>```

答:
Series is a Pandas class, so it starts with a capital letter. The below should work.

```<code>pd.Series(data = my_list)
</code>```

Body:
i got this error while running this code

import numpy as np
import pandas as pd
labels = ['a','b','c']
my_list = [10,20,30]
arr = np.array(my_list)
d = {'a':10,'b':20,'c':30}
pd.series(data = my_list)

full error msg

AttributeError                            Traceback (most recent call last)
<ipython-input-10-494578c29940> in <module>
----> 1 pd.series(data = my_list)

F:\New folder (8)\lib\site-packages\pandas\__init__.py in __getattr__(name)
    260             return _SparseArray
    261
--> 262         raise AttributeError(f"module 'pandas' has no attribute '{name}'")
    263
    264

AttributeError: module 'pandas' has no attribute 'series'

Body:
Series is a Pandas class, so it starts with a capital letter. The below should work.

pd.Series(data = my_list)


问:
"Cannot find module" when using raw-loader and TypeScript
I'm trying to include some WebGL vertex and fragment shaders by importing them as strings.

I have a project structure like this:

```<code>myproj/
  src/
    shad/
      foo.frg
      foo.vtx
    shad.d.ts
    Foo.ts
  dist/
    ...
  built/
    ...
  tsconfig.json
  package.json
  webpack.config.js
</code>```

shad.d.ts

```<code>declare module '*.vtx' {
    const content: string;
    export default content;
}

declare module '*.frg' {
    const content: string;
    export default content;
}
</code>```

Foo.ts

```<code>import stuff from 'shad/foo.frg'

console.log(stuff)
</code>```

tsconfig.json

```<code>{
    "include": [
        "src/**/*",
        "src/shad/**/*.vtx",
        "src/shad/**/*.frg",
    ],
    "exclude": ["node_modules"],
    "compilerOptions": {
        "target": "ES2018",
        "module": "es2015",
        "declaration": true,
        "sourceMap": true,
        "outDir": "built",
        "composite": true,
        "strict": true,
        "esModuleInterop": true,
        "forceConsistentCasingInFileNames": true
    }
}
</code>```

webpack.config.js

```<code>const path = require('path');

module.exports = {
  entry: {
    test: './src/Foo.ts',
  },
  mode:    'development',
  devtool: 'inline-source-map',
  devServer: {
    contentBase: './dist'
  },
  module: {
    rules: [
      {
        test:    /\.tsx?$/,
        use:     'ts-loader',
        exclude: [
          /node_modules/,
        ]
      },
      {
        test: /\.(vtx|frg)$/i,
        use:  'raw-loader',
      },
    ],
  },
  resolve: {
    extensions: [ '.tsx', '.ts', '.js', '.vtx', '.frg' ],
  },
  output: {
    filename: '[name].bundle.js',
    path:      path.resolve(__dirname, 'dist'),
  },
};
</code>```

When I npx webpack, I get:

```<code>ERROR in ./src/Foo.ts
Module not found: Error: Can't resolve 'shad/foo.frg' in '/Users/tbabb/test/tmp/tsproj/src'
 @ ./src/Foo.ts 1:0-33 4:16-21
</code>```

Also, the src/shad/ folder and its contents are absent from the built/ directory.

I've been around and around in all the docs for TypeScript and Webpack, as well as plenty of other answers here. From most of what I've read, the existence and contents of shad.d.ts should be enough to solve this problem, but it doesn't— and I don't even know how to figure out why.

What's going on? What do I have to do to import a raw file in Webpack with TypeScript? (Or at the very least, what can I do to figure out why this isn't being found?)

答:
In this particular repro case, I accidentally omitted the "./" from the import in Foo.ts. It should read:

```<code>import stuff from './shad/foo.frg'
</code>```

The actual problem that prompted this question I have narrowed down to an apparent bug with project references in raw-loader.

Body:
I'm trying to include some WebGL vertex and fragment shaders by importing them as strings.

I have a project structure like this:

myproj/
  src/
    shad/
      foo.frg
      foo.vtx
    shad.d.ts
    Foo.ts
  dist/
    ...
  built/
    ...
  tsconfig.json
  package.json
  webpack.config.js

shad.d.ts

declare module '*.vtx' {
    const content: string;
    export default content;
}

declare module '*.frg' {
    const content: string;
    export default content;
}

Foo.ts

import stuff from 'shad/foo.frg'

console.log(stuff)

tsconfig.json

{
    "include": [
        "src/**/*",
        "src/shad/**/*.vtx",
        "src/shad/**/*.frg",
    ],
    "exclude": ["node_modules"],
    "compilerOptions": {
        "target": "ES2018",
        "module": "es2015",
        "declaration": true,
        "sourceMap": true,
        "outDir": "built",
        "composite": true,
        "strict": true,
        "esModuleInterop": true,
        "forceConsistentCasingInFileNames": true
    }
}

webpack.config.js

const path = require('path');

module.exports = {
  entry: {
    test: './src/Foo.ts',
  },
  mode:    'development',
  devtool: 'inline-source-map',
  devServer: {
    contentBase: './dist'
  },
  module: {
    rules: [
      {
        test:    /\.tsx?$/,
        use:     'ts-loader',
        exclude: [
          /node_modules/,
        ]
      },
      {
        test: /\.(vtx|frg)$/i,
        use:  'raw-loader',
      },
    ],
  },
  resolve: {
    extensions: [ '.tsx', '.ts', '.js', '.vtx', '.frg' ],
  },
  output: {
    filename: '[name].bundle.js',
    path:      path.resolve(__dirname, 'dist'),
  },
};

When I npx webpack, I get:

ERROR in ./src/Foo.ts
Module not found: Error: Can't resolve 'shad/foo.frg' in '/Users/tbabb/test/tmp/tsproj/src'
 @ ./src/Foo.ts 1:0-33 4:16-21

Also, the src/shad/ folder and its contents are absent from the built/ directory.

I've been around and around in all the docs for TypeScript and Webpack, as well as plenty of other answers here. From most of what I've read, the existence and contents of shad.d.ts should be enough to solve this problem, but it doesn't— and I don't even know how to figure out why.

What's going on? What do I have to do to import a raw file in Webpack with TypeScript? (Or at the very least, what can I do to figure out why this isn't being found?)

Body:
In this particular repro case, I accidentally omitted the "./" from the import in Foo.ts. It should read:

import stuff from './shad/foo.frg'

The actual problem that prompted this question I have narrowed down to an apparent bug with project references in raw-loader.


问:
Beginner Question : How to upload and work w/ PHP files on a website?
Since a long time, we have been planning to make a website for our App. Now our App is under-development stage, and we need to make a website for it.

Now, what we want to do is upload a PHP page to our website, and work with it like :
xxxxxxx.com/test.php?index=1.

We have the PHP file/code ready, we just don't know how to get a website, domain, hosting and how to upload a PHP file so we could work like specified above ... It would be a normal site, just like others with some bunch of menus, and a nice design. Our most important requirement is to upload and work with the PHP file :)

Hope you understand our Question - any help is appreciated! :)

Thanks!

答:
First of all, you need a PHP hosting for that. Assuming that you have one. Then you can simple upload the directory containing PHP files to the hosting server using an FTP Client.

I recommend using Filezilla but you can use whichever you like. Hosting Servers also provide ftp facilities. Check with you hosting provider.

This dev article by Joeylene Rivera gives all step by step details.


问:
Not able to get auto generated Id, using JPA
I have two Entities. One is UserEntity and other is TaskEntity.

```<code>@Entity
@Table(name="user")
public class UserEntity {
    @Id
    private String userEmail;
    private String password;
    @OneToMany(cascade = CascadeType.ALL)
    @JoinColumn(name="user_email")
    private List<TaskEntity> tasks;

    //getter setter for variables
}
</code>```

```<code>@Entity
@Table(name="task")
public class TaskEntity {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;
    private String name;
    private String description;
    private String statusDate;
    private String status;

    //getter setter for variables
}
</code>```

Now I want to create a new task based on userEmail, so this I am doing as follow in DAO class:

```<code>    @PersistenceContext
    EntityManager em;
    public Integer addNewTaskByUserEmail(Task task, String userEmail) {
        UserEntity userEntity = em.find(UserEntity.class, userEmail);
        TaskEntity taskEntity = new TaskEntity();
        taskEntity.setName(task.getName());
        taskEntity.setDescription(task.getDescription());
        taskEntity.setStatus(task.getStatus());
        taskEntity.setStatusDate(task.getDate());
        userEntity.getTasks().add(taskEntity);
        return taskEntity.getId();
    }
</code>```

But in the return statement of I am getting null in service class. How can I return the auto-generated taskId?

答:
A possible issue is you are not saving a task associated with the user. Save the task and then you might be able to get the taskId.

```<code>public Integer addNewTaskByUserEmail(Task task, String userEmail) {
    UserEntity userEntity = em.find(UserEntity.class, userEmail);
    TaskEntity taskEntity = new TaskEntity();
    taskEntity.setName(task.getName());
    taskEntity.setDescription(task.getDescription());
    taskEntity.setStatus(task.getStatus());
    taskEntity.setStatusDate(task.getDate());
    em.getTransaction().begin();
    em.persist(taskEntity);
    em.getTransaction().commit();
    userEntity.getTasks().add(taskEntity);
    return taskEntity.getId();
}
</code>```

OR

```<code>    @Autowired TaskRepository taskRepository

    public Integer addNewTaskByUserEmail(Task task, String userEmail) {
        UserEntity userEntity = em.find(UserEntity.class, userEmail);
        TaskEntity taskEntity = new TaskEntity();
        taskEntity.setName(task.getName());
        taskEntity.setDescription(task.getDescription());
        taskEntity.setStatus(task.getStatus());
        taskEntity.setStatusDate(task.getDate());
        taskEntity = taskRepository.save(taskEntity)
        userEntity.getTasks().add(taskEntity);
        return taskEntity.getId();
    }
</code>```

Where TaskRepository will be

```<code>@Repository
public interface TaskRepository extends JpaRepository<TaskEntity, Integer>
{

}
</code>```

Body:
I have two Entities. One is UserEntity and other is TaskEntity.

@Entity
@Table(name="user")
public class UserEntity {
    @Id
    private String userEmail;
    private String password;
    @OneToMany(cascade = CascadeType.ALL)
    @JoinColumn(name="user_email")
    private List<TaskEntity> tasks;

    //getter setter for variables
}

@Entity
@Table(name="task")
public class TaskEntity {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;
    private String name;
    private String description;
    private String statusDate;
    private String status;

    //getter setter for variables
}

Now I want to create a new task based on userEmail, so this I am doing as follow in DAO class:

    @PersistenceContext
    EntityManager em;
    public Integer addNewTaskByUserEmail(Task task, String userEmail) {
        UserEntity userEntity = em.find(UserEntity.class, userEmail);
        TaskEntity taskEntity = new TaskEntity();
        taskEntity.setName(task.getName());
        taskEntity.setDescription(task.getDescription());
        taskEntity.setStatus(task.getStatus());
        taskEntity.setStatusDate(task.getDate());
        userEntity.getTasks().add(taskEntity);
        return taskEntity.getId();
    }

But in the return statement of I am getting null in service class. How can I return the auto-generated taskId?

Body:
A possible issue is you are not saving a task associated with the user. Save the task and then you might be able to get the taskId.

public Integer addNewTaskByUserEmail(Task task, String userEmail) {
    UserEntity userEntity = em.find(UserEntity.class, userEmail);
    TaskEntity taskEntity = new TaskEntity();
    taskEntity.setName(task.getName());
    taskEntity.setDescription(task.getDescription());
    taskEntity.setStatus(task.getStatus());
    taskEntity.setStatusDate(task.getDate());
    em.getTransaction().begin();
    em.persist(taskEntity);
    em.getTransaction().commit();
    userEntity.getTasks().add(taskEntity);
    return taskEntity.getId();
}

OR

    @Autowired TaskRepository taskRepository

    public Integer addNewTaskByUserEmail(Task task, String userEmail) {
        UserEntity userEntity = em.find(UserEntity.class, userEmail);
        TaskEntity taskEntity = new TaskEntity();
        taskEntity.setName(task.getName());
        taskEntity.setDescription(task.getDescription());
        taskEntity.setStatus(task.getStatus());
        taskEntity.setStatusDate(task.getDate());
        taskEntity = taskRepository.save(taskEntity)
        userEntity.getTasks().add(taskEntity);
        return taskEntity.getId();
    }

Where TaskRepository will be

@Repository
public interface TaskRepository extends JpaRepository<TaskEntity, Integer>
{

}


问:
laravel new blog not work mockery/mockery 1.4.0
Today I wanted to create a new project with Laravel with this command

```<code>laravel new blog
</code>```

But I get this error

```<code>Crafting application...
Loading composer repositories with package information
Installing dependencies (including require-dev) from lock file
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - Installation request for mockery/mockery 1.4.0 -> satisfiable by mockery/mockery[1.4.0].
    - mockery/mockery 1.4.0 requires php ^7.3.0 -> your PHP version (7.2.23) does not satisfy that requirement.
</code>```

Why should php7.3 be read when Laravel himself says at least php7.2.5 ???

答:
You can just run

composer create-project --prefer-dist laravel/laravel <project_name>

It'll automatically fall-back to mockery^1.3.1

Body:
Today I wanted to create a new project with Laravel with this command

laravel new blog

But I get this error

Crafting application...
Loading composer repositories with package information
Installing dependencies (including require-dev) from lock file
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - Installation request for mockery/mockery 1.4.0 -> satisfiable by mockery/mockery[1.4.0].
    - mockery/mockery 1.4.0 requires php ^7.3.0 -> your PHP version (7.2.23) does not satisfy that requirement.

Why should php7.3 be read when Laravel himself says at least php7.2.5 ???


问:
Autocomplete with different values than the title
I'm trying to make an autocomplete form using jquery, but I've run into an issue. I'm trying to make it so that when a user starts typing in the name of a place that's in our database, it shows them the full name of the place in the autocomplete, but when they click on it, the textbox gets filled with the address of the place that can be located with google maps. What would be the best way to accomplish this?</p>

答:
Here a very rough sketch of some code that will get you started. By no means is it complete, but it should give you a good jumping off point. Hope it helps

```<code>$("#mySearchBox").change(function(){
/*
    send a ajax request to receive a json object.
    We use the callback function to populate the
    a div tag "autocomplete" with the names
*/
$.getJSON("http://myurl.com/myPage?search="+$(this).val()
        function(data){
          $.each(data.items, function(i,item){
            /*
                Assume item looks like this

                item = {[{"address": 100 Main st",
                           "name": "Bob and Joe's Dinner"],
                            ...
                       }
            */
                /* Populate autocomplete with new spans
                   We use the text attribute to hold the address
                   You may want to look in to jquery data() feature.
                */
                $("#autoComplete").append('<span text="'+ item.address +
                                          '" class="searchResult">'+ item.name +'</span>');
          });
        });
</code>```

});

```<code>$("#autoComplete .searchResults").click(function(){
    /*
        Here we handle what the user clicks on.
        Pull out the address from the attr and
        put that back in the mySearchBox
    */
    var address = $(this).attr("text");

    //Load the adress back int the textfield
    $("#mySearchBox").val = address;
});
</code>```

OwnerDisplayName: Sliggy

Body:
Here a very rough sketch of some code that will get you started. By no means is it complete, but it should give you a good jumping off point. Hope it helps

$("#mySearchBox").change(function(){
/*
    send a ajax request to receive a json object.
    We use the callback function to populate the
    a div tag "autocomplete" with the names
*/
$.getJSON("http://myurl.com/myPage?search="+$(this).val()
        function(data){
          $.each(data.items, function(i,item){
            /*
                Assume item looks like this

                item = {[{"address": 100 Main st",
                           "name": "Bob and Joe's Dinner"],
                            ...
                       }
            */
                /* Populate autocomplete with new spans
                   We use the text attribute to hold the address
                   You may want to look in to jquery data() feature.
                */
                $("#autoComplete").append('<span text="'+ item.address +
                                          '" class="searchResult">'+ item.name +'</span>');
          });
        });

});

$("#autoComplete .searchResults").click(function(){
    /*
        Here we handle what the user clicks on.
        Pull out the address from the attr and
        put that back in the mySearchBox
    */
    var address = $(this).attr("text");

    //Load the adress back int the textfield
    $("#mySearchBox").val = address;
});

OwnerDisplayName: Scott