问:
ng2-pdfjs-viewer print function prints the entire html page rather than the embedded pdf document within the viewer
I am using the ng2-pdfjs-viewer extension to embed a pdf document within a page so that I can print the document. It works fine on browsers. However, it tries to print the entire html page on android and ios devices. I am using Angular 5.2.0 with .Net Core.

Here is the html tag:

```<code><ng2-pdfjs-viewer #pdfViewerOnDemand
                  [pdfSrc]="pdfDoc"
                  [downloadFileName]="'pdfDoc.pdf'"
                  [download]="true"
                  [print]="true">
</ng2-pdfjs-viewer>
</code>```

答: Apparently this is a bug and does not seem to have worked before on mobile devices. I have opened an issue on github for those who come across this issue in the near future: https://github.com/intbot/ng2-pdfjs-viewer/issues/76</p>

Body:
I am using the ng2-pdfjs-viewer extension to embed a pdf document within a page so that I can print the document. It works fine on browsers. However, it tries to print the entire html page on android and ios devices. I am using Angular 5.2.0 with .Net Core.

Here is the html tag:

<ng2-pdfjs-viewer #pdfViewerOnDemand
                  [pdfSrc]="pdfDoc"
                  [downloadFileName]="'pdfDoc.pdf'"
                  [download]="true"
                  [print]="true">
</ng2-pdfjs-viewer>


来源: stackexchange

问:
Logic Apps Email Trigger - Get original Alias
Found a very similar question here: Email aliases not returned as "To" address in logic app

TLDR: From within a logic app "When a new email arrives" trigger, How do I get the original alias that the email was sent to?

I have a logic app that creates a ticket based off an email sent to an outlook box. Now I want to be able to choose aspects of the ticket based off of whether or not the email was sent to the mailbox itself or an alias of the mailbox. The problem I'm having is that by the time logic apps gets a hold of the email, the alias address has already been replaced with the actual box's address ("alias1@place.com" -> "actualbox@place.com").

The actual mail in the inbox has the original email's alias information in the headers, but I can only get them by looking at the properties in outlook. I've tried to get the original "To" internetheader information both within logic apps (by exporting the email to blob storage and looking at headers there) and with the Microsoft Graph API. Sadly, the email exported by logic apps doesn't have the alias information and Graph API has pretty much every header but "To". At least one other person has lamented the lack of To

That said, the actual email still has the original alias information. Can someone help me get that information in logic apps without jumping through too many hoops? A many hoop solution is welcome if none other can be found though.

答: What API are you using? In Outlook Object Model / MAPI / EWS, you need to retrieve the PR_TRANSPORT_MESSAGE_HEADERS MAPI property (DASL name http://schemas.microsoft.com/mapi/proptag/0x007D001F)

ContentLicense: CC BY-SA 4.0


问:
FFTW Segfault (Likely simple answer)
I'm trying to write a simple FFTW routine (version 2), and I think I've just about got the bones down, but I'm running into a persistent segfault when I call the fftwnd_one function (I'm doing a one dimensional transform, but I'm using the n-dimensional code for modularity's sake).  However, I believe my problem to be in the plan creation; could anyone offer some insight as to what's wrong with this code?  I'd greatly appreciate it if so - thank you!

For reference, the function that I'm working with here is sin(x).  I realize that not all of the mathematical operations have been implemented, I'm just trying to get the FFTW2 library working first, then I can make the data useful.

```<code>#include <stdio.h>
#include <fftw.h>
#include <math.h>
#include <complex.h>

int main(){
  int i;
  fftw_complex in[8];
  fftwnd_plan p;
  const int *n;
  int temp = (int)pow(2, 2)*pow(3,2)*pow(5,1)*pow(7,1)*pow(11,1)*pow(13,0);
  n = &temp;

  in[0].re = 0;
  in[1].re = (sqrt(2)/2);
  in[2].re = 1;
  in[3].re = (sqrt(2)/2);
  in[4].re = 0;
  in[5].re = -(sqrt(2)/2);
  in[6].re = -1;
  in[7].re = -(sqrt(2)/2);

  for(i = 0; i < 8; i++){
    (in[i]).im = 0;
  }

  p = fftwnd_create_plan(8, n, FFTW_FORWARD, FFTW_ESIMATE | FFTW_IN_PLACE);
  fftwnd_one(p, &in[0], NULL);
  fftwnd_destroy_plan(p);

  printf("Sin\n");
  for(i = 0; i < 8; i++){
    printf("%d\n", n[i]);
  }
  return 0;
}
</code>```

答:
The first two parameters to fftwnd_create_plan look completely wrong. It seems you just want to create a plan for 1D FFT with size 8 (which raises the question as to why you're using fftwnd_create_plan if you only need a 1D FFT ?). The call should be something like:

```<code>const int n = 8;
p = fftwnd_create_plan(1,   // rank = 1, i.e. 1D
                       &n,  // size of first (and only) dimension = n = 8
                       FFTW_FORWARD,
                       FFTW_ESIMATE | FFTW_IN_PLACE);
</code>```

ContentLicense: CC BY-SA 3.0

Title: FFTW Segfault (Likely simple answer)

Body:
I'm trying to write a simple FFTW routine (version 2), and I think I've just about got the bones down, but I'm running into a persistent segfault when I call the fftwnd_one function (I'm doing a one dimensional transform, but I'm using the n-dimensional code for modularity's sake).  However, I believe my problem to be in the plan creation; could anyone offer some insight as to what's wrong with this code?  I'd greatly appreciate it if so - thank you!

For reference, the function that I'm working with here is sin(x).  I realize that not all of the mathematical operations have been implemented, I'm just trying to get the FFTW2 library working first, then I can make the data useful.

#include <stdio.h>
#include <fftw.h>
#include <math.h>
#include <complex.h>

int main(){
  int i;
  fftw_complex in[8];
  fftwnd_plan p;
  const int *n;
  int temp = (int)pow(2, 2)*pow(3,2)*pow(5,1)*pow(7,1)*pow(11,1)*pow(13,0);
  n = &temp;

  in[0].re = 0;
  in[1].re = (sqrt(2)/2);
  in[2].re = 1;
  in[3].re = (sqrt(2)/2);
  in[4].re = 0;
  in[5].re = -(sqrt(2)/2);
  in[6].re = -1;
  in[7].re = -(sqrt(2)/2);

  for(i = 0; i < 8; i++){
    (in[i]).im = 0;
  }

  p = fftwnd_create_plan(8, n, FFTW_FORWARD, FFTW_ESIMATE | FFTW_IN_PLACE);
  fftwnd_one(p, &in[0], NULL);
  fftwnd_destroy_plan(p);

  printf("Sin\n");
  for(i = 0; i < 8; i++){
    printf("%d\n", n[i]);
  }
  return 0;
}

Body:
The first two parameters to fftwnd_create_plan look completely wrong. It seems you just want to create a plan for 1D FFT with size 8 (which raises the question as to why you're using fftwnd_create_plan if you only need a 1D FFT ?). The call should be something like:

const int n = 8;
p = fftwnd_create_plan(1,   // rank = 1, i.e. 1D
                       &n,  // size of first (and only) dimension = n = 8
                       FFTW_FORWARD,
                       FFTW_ESIMATE | FFTW_IN_PLACE);


问:
create tuple of nth element in the cartesian product of input vectors
I have a python function which returns the nth-element in the cartesian product of a number of input arrays

def prod(n, arrs):
    out = []

    for i,arr in enumerate(arrs):
        denom = numpy.prod([ len(p) for p in arrs[i+1:] ], dtype=int)
        idx = n // denom % len(arr)
        out.append( arr[idx] )

    return out
```

<p>This works great:</p>

<pre class="lang-py prettyprint-override"><code>a = [ 1000, 1100, 1200, 1300, 1400 ]
b = [ 1.0, 1.5, 2.0, 2.5, 3.0, 3.5 ]
c = [ -2, -1, 0, 1, 2 ]

for n in range(20, 30):
    i = prod(n, [a, b, c])
    print(n, i)
</code>```

```<code>[1000, 3.0, -2]
[1000, 3.0, -1]
[1000, 3.0, 0]
[1000, 3.0, 1]
[1000, 3.0, 2]
[1000, 3.5, -2]
[1000, 3.5, -1]
[1000, 3.5, 0]
[1000, 3.5, 1]
[1000, 3.5, 2]
</code>```

Now I would like to translate this to C++ (max standard C++-17)

template<typename... Ts>
auto prod(std::size_t n, const std::vector<Ts>&... vs)
    -> std::tuple<const std::decay_t<typename std::vector<Ts>::value_type>&...>
{
    // template magic here
}
```

Can someone help me with the template magic required to construct the tuple using the above formula?

答:
We can use the "indices trick" to get us indices associated with the different vectors.

This gets us the following C++14 solution:

```<code>#include <tuple>
#include <vector>
#include <cstdlib>

using std::array;
using std::size_t;

template <size_t NDim>
constexpr array<size_t, NDim> delinearize_coordinates(
    size_t n, array<size_t, NDim> dimensions)
{
    // This might be optimizable into something nicer, maybe even a one-liner
    array<size_t, NDim> result{};
    for(size_t i = 0; i < NDim; i++) {
        result[NDim-1-i] = n % dimensions[NDim-1-i];
        n = n / dimensions[NDim-1-i];
    };
    return result;
}

template<size_t... Is, typename... Ts>
auto prod_inner(
    std::index_sequence<Is...>,
    size_t n,
    const std::vector<Ts>&... vs)
    -> std::tuple<const std::decay_t<typename std::vector<Ts>::value_type>&...>
{
    auto vs_as_tuple = std::make_tuple( vs ... );
    auto coordinates = delinearize_coordinates<sizeof...(Ts)>(n, { vs.size()... });
    return { std::get<Is>(vs_as_tuple)[coordinates[Is]] ... };
}

template<typename... Ts>
auto prod(size_t n, const std::vector<Ts>&... vs)
    -> std::tuple<const std::decay_t<typename std::vector<Ts>::value_type>&...>
{
    return prod_inner(std::make_index_sequence<sizeof...(Ts)>{}, n,
        std::forward<const std::vector<Ts>&>(vs)...);
}
</code>```

Notes:

Unlike in your code, I've factored-out the function which translates a single number into a sequence of coordinates.

I think you can get this down to C++11 if you provide your own make_index_sequence.

Body:
I have a python function which returns the nth-element in the cartesian product of a number of input arrays

def prod(n, arrs):
    out = []

    for i,arr in enumerate(arrs):
        denom = numpy.prod([ len(p) for p in arrs[i+1:] ], dtype=int)
        idx = n // denom % len(arr)
        out.append( arr[idx] )

    return out

This works great:

a = [ 1000, 1100, 1200, 1300, 1400 ]
b = [ 1.0, 1.5, 2.0, 2.5, 3.0, 3.5 ]
c = [ -2, -1, 0, 1, 2 ]

for n in range(20, 30):
    i = prod(n, [a, b, c])
    print(n, i)

[1000, 3.0, -2]
[1000, 3.0, -1]
[1000, 3.0, 0]
[1000, 3.0, 1]
[1000, 3.0, 2]
[1000, 3.5, -2]
[1000, 3.5, -1]
[1000, 3.5, 0]
[1000, 3.5, 1]
[1000, 3.5, 2]

Now I would like to translate this to C++ (max standard C++-17)

template<typename... Ts>
auto prod(std::size_t n, const std::vector<Ts>&... vs)
    -> std::tuple<const std::decay_t<typename std::vector<Ts>::value_type>&...>
{
    // template magic here
}

Can someone help me with the template magic required to construct the tuple using the above formula?

Body:
We can use the "indices trick" to get us indices associated with the different vectors.

This gets us the following C++14 solution:

#include <tuple>
#include <vector>
#include <cstdlib>

using std::array;
using std::size_t;

template <size_t NDim>
constexpr array<size_t, NDim> delinearize_coordinates(
    size_t n, array<size_t, NDim> dimensions)
{
    // This might be optimizable into something nicer, maybe even a one-liner
    array<size_t, NDim> result{};
    for(size_t i = 0; i < NDim; i++) {
        result[NDim-1-i] = n % dimensions[NDim-1-i];
        n = n / dimensions[NDim-1-i];
    };
    return result;
}

template<size_t... Is, typename... Ts>
auto prod_inner(
    std::index_sequence<Is...>,
    size_t n,
    const std::vector<Ts>&... vs)
    -> std::tuple<const std::decay_t<typename std::vector<Ts>::value_type>&...>
{
    auto vs_as_tuple = std::make_tuple( vs ... );
    auto coordinates = delinearize_coordinates<sizeof...(Ts)>(n, { vs.size()... });
    return { std::get<Is>(vs_as_tuple)[coordinates[Is]] ... };
}

template<typename... Ts>
auto prod(size_t n, const std::vector<Ts>&... vs)
    -> std::tuple<const std::decay_t<typename std::vector<Ts>::value_type>&...>
{
    return prod_inner(std::make_index_sequence<sizeof...(Ts)>{}, n,
        std::forward<const std::vector<Ts>&>(vs)...);
}

Notes:

Unlike in your code, I've factored-out the function which translates a single number into a sequence of coordinates.

I think you can get this down to C++11 if you provide your own make_index_sequence.


问:
How can I add entity to relation only with ID without fetching it?
I am creating a Many-To-Many relation

```<code>@Entity({
    name: 'product'
})
export class Product {
    @PrimaryGeneratedColumn()
    id: number;

    @Column()
    name: string;

    @Column({type: 'decimal', precision: 13, scale: 2})
    price: number;

    @ManyToMany(() => Tag, (tag: Tag) => tag.products)
    @JoinTable({
        name: 'product_tag'
    })
    tags: Tag[];

    @CreateDateColumn()
    createdAt: Timestamp;

    @UpdateDateColumn()
    updatedAt: Timestamp;
}
</code>```

```<code>@Entity({
    name: 'tag'
})
export class Tag {
    @PrimaryGeneratedColumn()
    id: number;

    @Column()
    name: string;

    @ManyToMany(() => Product, (product: Product) => product.tags)
    products: Product[];

    @CreateDateColumn()
    createdAt: Timestamp;

    @UpdateDateColumn()
    updatedAt: Timestamp;
}
</code>```

let say there is some tag in db . eg: Tag = [{id: 1, name: 'pc'}, {id: 2, name: 'laptop'}]

And I have product Product = [{id: 1, name: 'Zenbook', price: 10000 }]

Now  I need to add those tags to the product.

I wanted do something  like this

```<code>const product = await this.repository.findOne({id: 1});

product.tags = [{id: 1}, {id:2}];

await this.repository.save(product);
</code>```

I know this is wrong.

How can I do this?

Thank You

答:
I had this question too and it took some digging but I found Working with Relations in the TypeORM docs

For your situation you want

await getConnection()
    .createQueryBuilder()
    .relation(Product, "tags")
    .of(product)
    /**
     * Adds (binds) given value to entity relation.
     * Value can be entity, entity id or entity id map (if entity has composite ids).
     * Value also can be array of entities, array of entity ids or array of entity id maps (if entity has composite ids).
     * Works only for many-to-many and one-to-many relations.
     * For many-to-one and one-to-one use #set method instead.
     */
    .add([1, 2]);
```

Body:
I am creating a Many-To-Many relation

@Entity({
    name: 'product'
})
export class Product {
    @PrimaryGeneratedColumn()
    id: number;

    @Column()
    name: string;

    @Column({type: 'decimal', precision: 13, scale: 2})
    price: number;

    @ManyToMany(() => Tag, (tag: Tag) => tag.products)
    @JoinTable({
        name: 'product_tag'
    })
    tags: Tag[];

    @CreateDateColumn()
    createdAt: Timestamp;

    @UpdateDateColumn()
    updatedAt: Timestamp;
}

@Entity({
    name: 'tag'
})
export class Tag {
    @PrimaryGeneratedColumn()
    id: number;

    @Column()
    name: string;

    @ManyToMany(() => Product, (product: Product) => product.tags)
    products: Product[];

    @CreateDateColumn()
    createdAt: Timestamp;

    @UpdateDateColumn()
    updatedAt: Timestamp;
}

let say there is some tag in db . eg: Tag = [{id: 1, name: 'pc'}, {id: 2, name: 'laptop'}]

And I have product Product = [{id: 1, name: 'Zenbook', price: 10000 }]

Now  I need to add those tags to the product.

I wanted do something  like this

const product = await this.repository.findOne({id: 1});

product.tags = [{id: 1}, {id:2}];

await this.repository.save(product);

I know this is wrong.

How can I do this?

Thank You


问:
Unable to deploy app to Windows 10 IOT
I'm using Windows 7 with VS 2015 Community to develop a UWP app and trying to deploy it to a Raspberry Pi 3 running Windows 10 IOT. Authentication mode is set to no authentication and I have started the remote debugger manually over ssh.

When I try to deploy the app to the pi using VS, I get this:

Error : DEP2500 : Registration succeeded, but package registration
  information cannot be found. The layout folder is
  "C:\Data\Users\DefaultAccount\AppData\Local\DevelopmentFiles\APPNAME"

I previously had this error and was able to change the package name and it deployed successfully, but that is no longer working. I can open up the IOT web server on the pi and start the app from there and it runs correctly, but then I am unable to debug.

I have also tried using different authentication modes but they each have their own problems.

Windows authentication yields:

WindowsAppDeployer::Unable to connect to the Microsoft Visual Studio
  Remote Debugger named '192.168.1.42'.  Connection request was rejected
  by the remote debugger. Ensure that the remote debugger is running in
  'Windows Authentication' mode.

Universal authentication yields:

Error : DEP6701 : Bootstrapping failed with unexpected error: 'Error :
  DEP6960 : Source file does not exist: C:\Program Files (x86)\Common
  Files\Microsoft Shared\Phone
  Tools\14.0\Debugger\target\armv4i\msvsmon.exe'.   App1

I'm new to UWP and am not familiar with Windows 10 so any help would be appreciated

答: I had this problem when switching from Debug to Release when deploying to the Hololens. I fixed it by uninstalling the app from the Hololens then re-deploying.

Title: Unable to deploy app to Windows 10 IOT


问:
File types (mime types) issue in Outlook web addin using Fabric UI
I am working on an Outlook Web Addin using Fabric UI framework. Im using Fabric UI Core without React or AngularJS. I am facing an issue in getting File Types (MIME types) icons. Whatever references I found online for File types in Fabric UI are for React framework.

Is there a way to get file types in Fabric UI with plain Javascript without React? I found the following links where file types are available:

https://spoprod-a.akamaihd.net/files/fabric/assets/item-types/16/csv.svg

https://static2.sharepointonline.com/files/fabric/assets/brand-icons/document/svg/pptx_16x1.svg

I can write a simple JS code to pass appropriate file extension in the above URL to load the intended file type icon. For example :

https://static2.sharepointonline.com/files/fabric/assets/brand-icons/document/svg/[file extension]_16x1.svg

Is it correct to get file types this way? Are these URLs reliable source for getting file types icon?

Any help is appreciated with thanks.

答:
@uifabric/file-type-icons is the current package containing the set of file type icon mappings. It includes a registration helper along with a few functions to derive a given extension to an image mapping.

@uifabric/styling contains the general icon helper getIcon to pull registered icons from any icon registrations.

I've made a codesandbox example here using vanilla JS:
https://codesandbox.io/s/uifabric-filetypeicons-example-yoyp6

...and a cleaner more interactive example in React:
https://codesandbox.io/s/file-type-icons-2s54c

The important steps are:

Call initializeFileTypeIcons to register file type icons in the icon registry.

Call getIconProps({ extension: 'docx', size: 16 }) to get details on the iconName to map to.

Call getIcon to get the details of the icon, where you can access the url, which you can inject into raw HTML or use your framework of choice to render an img.

Note that the styling package has a peer dependency on React, so I needed to add it, but it is not being used here. This is something we could certainly improve on.

Hope this helps.


问:
Handling Android preferences without magic strings
Im using Androids built in way of handling preferences which works by writing all settings in an xml file. It's really nice but I can't find any good way of doing it without using magic strings in the xml and Java code.

The only way I could think of is to save the preference key as String but that doesn't feels right either. Anyone got a good way of solving this?

答:
You can move your "magic string" to string resources:

In you preference xml file:

```<code><EditTextPreference
        android:key="@string/preferences_pdn_key"
        android:title="@string/preferences_pdn_title"
        android:summary="@string/preferences_pdn_summary"
        android:dialogMessage="@string/input_pdn_message" />
</code>```

In your values/strings.xml files:

```<code>...
<string name="preferences_pdn_key">pdn</string>
...
</code>```

You then can reference preference from your Activity or PreferenceActivity:

```<code>SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String pdnKey = getString(R.string.prefernece_pdn_key);
String pdn = sharedPreferences.getString(pdnKey, null);
</code>```

If you don't like to fetch preference keys from string resources all the time you can do yet another trick:

```<code>public class PreferenceNames {

    /* categories */
    public static final String LoginCategory = MyApplication.getResourceString(R.string.preferences_login_category_key);
    ...

    /* preferences */
    public static final String Pdn = MyApplication.getResourceString(R.string.preferences_pdn_key);
    ...
}
</code>```

So you can now reference you preference key next way:

```<code>SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String pdn = sharedPreferences.getString(PreferenceNames.Pdn, null);
</code>```

And here is how your MyApplication class should look like:

```<code>public class MyApplication extends Application {
    private static VvmApplication s_instance;

    public MyApplication(){
        s_instance = this;
    }

    public static Context getContext(){
        return s_instance;
    }

    public static String getResourceString(int resId){
        return getContext().getString(resId);
    }
}
</code>```

Plus you need to add next thing to your AndroidManifest.xml:

```<code><application android:name="com.mypackage.application.MyApplication" ... >
...
</application>
</code>```

Body:
You can move your "magic string" to string resources:

In you preference xml file:

<EditTextPreference
        android:key="@string/preferences_pdn_key"
        android:title="@string/preferences_pdn_title"
        android:summary="@string/preferences_pdn_summary"
        android:dialogMessage="@string/input_pdn_message" />

In your values/strings.xml files:

...
<string name="preferences_pdn_key">pdn</string>
...

You then can reference preference from your Activity or PreferenceActivity:

SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String pdnKey = getString(R.string.prefernece_pdn_key);
String pdn = sharedPreferences.getString(pdnKey, null);

If you don't like to fetch preference keys from string resources all the time you can do yet another trick:

public class PreferenceNames {

    /* categories */
    public static final String LoginCategory = MyApplication.getResourceString(R.string.preferences_login_category_key);
    ...

    /* preferences */
    public static final String Pdn = MyApplication.getResourceString(R.string.preferences_pdn_key);
    ...
}

So you can now reference you preference key next way:

SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String pdn = sharedPreferences.getString(PreferenceNames.Pdn, null);

And here is how your MyApplication class should look like:

public class MyApplication extends Application {
    private static VvmApplication s_instance;

    public MyApplication(){
        s_instance = this;
    }

    public static Context getContext(){
        return s_instance;
    }

    public static String getResourceString(int resId){
        return getContext().getString(resId);
    }
}

Plus you need to add next thing to your AndroidManifest.xml:

<application android:name="com.mypackage.application.MyApplication" ... >
...
</application>


答:
I like using Pandas for handling excel files.

This tutorial is great to understand its capabilities: https://www.dataquest.io/blog/excel-and-pandas/

Title: Change default order of the sheets in the Book object in pyexcel

Body:
I'm trying to created a WorkBook using pyexcel follow this tutorial. But I note when I execute this code

import pyexcel

content = {
     'c':
         [
             [1.0, 2.0, 3.0],
             [4.0, 5.0, 6.0],
             [7.0, 8.0, 9.0]
         ],
     'b':
         [
             ['X', 'Y', 'Z'],
             [1.0, 2.0, 3.0],
             [4.0, 5.0, 6.0]
         ],
     'a':
         [
             ['O', 'P', 'Q'],
             [3.0, 2.0, 1.0],
             [4.0, 3.0, 2.0]
         ]
 }

book = pyexcel.Book(content)
print(book)

The sheets of the work are in decrease order c, b, a. But the __str__ version of the Book object sort the sheets alphabetically and I want the decrease order like in the dictonary. There is a way of archieve this in pyexcel or other tool? This is es output of the __str__ version of the Book.

a:
+-----+-----+-----+
| O   | P   | Q   |
+-----+-----+-----+
| 3.0 | 2.0 | 1.0 |
+-----+-----+-----+
| 4.0 | 3.0 | 2.0 |
+-----+-----+-----+
b:
+-----+-----+-----+
| X   | Y   | Z   |
+-----+-----+-----+
| 1.0 | 2.0 | 3.0 |
+-----+-----+-----+
| 4.0 | 5.0 | 6.0 |
+-----+-----+-----+
c:
+-----+-----+-----+
| 1.0 | 2.0 | 3.0 |
+-----+-----+-----+
| 4.0 | 5.0 | 6.0 |
+-----+-----+-----+
| 7.0 | 8.0 | 9.0 |
+-----+-----+-----+


问:
Cannot convert jupyter notebook to pdf
I get the following error when  I try to convert jupyter notebook to pdf.

I'd appreciate your help. Thank you.

答:
As the error says, you need to install xelatex and add it to your path so that the conversion can take place.

Can you follow the instruction here to install xelatex onto your system. Once done check in your cmd line that it is installed by doing the following,

```<code>latex --version
</code>```

If this shows the version then it should work fine.

Edit:

Working Solution:

Ok. Thank you so much. It worked. I downloaded MikTex from (miktex.org/download). I made sure it is on the same path. Ran your command 'xetex --version' to make sure it's in the same path. Went back to jupyter notebook and was able to convert it to pdf. Thank you.

Possible Solution:

Go here go to 'JupyterLab' which will allow you to open jupyter notebooks. Once opened( it is slow, so be patient) open your local file and then simply export it to pdf. This will not require any dependencies like on local side.

Title: Cannot convert jupyter notebook to pdf

Body:
As the error says, you need to install xelatex and add it to your path so that the conversion can take place.

Can you follow the instruction here to install xelatex onto your system. Once done check in your cmd line that it is installed by doing the following,

latex --version

If this shows the version then it should work fine.

Edit:

Working Solution:

Ok. Thank you so much. It worked. I downloaded MikTex from (miktex.org/download). I made sure it is on the same path. Ran your command 'xetex --version' to make sure it's in the same path. Went back to jupyter notebook and was able to convert it to pdf. Thank you.

Possible Solution:

Go here go to 'JupyterLab' which will allow you to open jupyter notebooks. Once opened( it is slow, so be patient) open your local file and then simply export it to pdf. This will not require any dependencies like on local side.


问:
jquery if $this has not ClassName do action
I see many answers but none of them seem to be working.

All my buttons have the "Trev" class. I want to check if the clicked class, also contains the "Namdons" class, and if so, do some code. However if not, do some code.

Some code that half works is:

```<code>$(".Trev").click
(
    function(e)
    {

        if($(this).hasClass("Namdons"))
        {
            console.log("Namdons");
        }
        else
        {
            console.log("Asdf");
        }
        e.preventDefault();

    }
);
</code>```

However the "else" condition is not executing.

I've tried:

```<code>$(".Trev").click
(
    function(e)
    {

        if($(this).hasClass("Namdons"))
        {
            console.log("Namdons");
        }
        if(!$(this).hasClass("Namdons"))   //added apostrophe
        {
            console.log("Asdf");
        }
        e.preventDefault();

    }
);
</code>```

as per these pages:

How to check if an element does NOT have a specific class?
How do I use hasClass to detect if a class is NOT the class I want?

The "not" command does not apply as I'm only wanting to procure a single element and not select a bunch of them. Explained more on those pages.

HTML:

```<code><div class="Trev Width50" onclick="Button('buttonname')"></div>
</code>```

and

```<code><button onclick="Namdons()" class="Namdons Trev TextAlignCenter">ButtonTitle</button>
</code>```

also tried changing the Width50 div to a button:

```<code><button class="Trev Width50" onclick="Button('buttonname')"></button>
</code>```

There also doesn't seem to be an "elseif" in javascript is that correct?

Thanks.

答:
Since you tag javascript i put example in vanilla js. I leave it for you to translate it to jQuery. I also put notes inside:

const trev = document.querySelectorAll('button.trev'); // get button with .trev style
for (var i=0; i < trev.length; i++) { // itterate them
  trev[i].addEventListener('click', function() { // add click event
    if (this.classList.contains('Namdons')) {alert('This is .Namdons');} // if it has .Namdons alert it
    else {alert('This is NOT .Namdons');} // it not alert that
  });
} ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button class="Trev TextAlignCenter">ButtonTitle</button>
<button class="Namdons Trev TextAlignCenter">ButtonTitle</button>
<button class="Trev TextAlignCenter">ButtonTitle</button>
<button class="Namdons Trev TextAlignCenter">ButtonTitle</button>
<button class="Trev TextAlignCenter">ButtonTitle</button></code>```

Read more about classList on MDN

Body:
I see many answers but none of them seem to be working.

All my buttons have the "Trev" class. I want to check if the clicked class, also contains the "Namdons" class, and if so, do some code. However if not, do some code.

Some code that half works is:

$(".Trev").click
(
    function(e)
    {

        if($(this).hasClass("Namdons"))
        {
            console.log("Namdons");
        }
        else
        {
            console.log("Asdf");
        }
        e.preventDefault();

    }
);

However the "else" condition is not executing.

I've tried:

$(".Trev").click
(
    function(e)
    {

        if($(this).hasClass("Namdons"))
        {
            console.log("Namdons");
        }
        if(!$(this).hasClass("Namdons"))   //added apostrophe
        {
            console.log("Asdf");
        }
        e.preventDefault();

    }
);

as per these pages:

How to check if an element does NOT have a specific class?
How do I use hasClass to detect if a class is NOT the class I want?

The "not" command does not apply as I'm only wanting to procure a single element and not select a bunch of them. Explained more on those pages.

HTML:

and

<button onclick="Namdons()" class="Namdons Trev TextAlignCenter">ButtonTitle</button>

also tried changing the Width50 div to a button:

<button class="Trev Width50" onclick="Button('buttonname')"></button>

There also doesn't seem to be an "elseif" in javascript is that correct?

Thanks.

Body:
Since you tag javascript i put example in vanilla js. I leave it for you to translate it to jQuery. I also put notes inside:

const trev = document.querySelectorAll('button.trev'); // get button with .trev style
for (var i=0; i < trev.length; i++) { // itterate them
  trev[i].addEventListener('click', function() { // add click event
    if (this.classList.contains('Namdons')) {alert('This is .Namdons');} // if it has .Namdons alert it
    else {alert('This is NOT .Namdons');} // it not alert that
  });
}

<button class="Trev TextAlignCenter">ButtonTitle</button>
<button class="Namdons Trev TextAlignCenter">ButtonTitle</button>
<button class="Trev TextAlignCenter">ButtonTitle</button>
<button class="Namdons Trev TextAlignCenter">ButtonTitle</button>
<button class="Trev TextAlignCenter">ButtonTitle</button>

Read more about classList on MDN


问:
How to get the count of products registered per day in the last 7 days using Laravel
I have a table with products.
In this table I have a column with the date of the products' cacastrast.

I was looking at Carbon and wanted to implement a method in my Laravel application that showed the quantity of products in the last 7 days.

In Java I used this method:

```<code>public Date getSevenDays() {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.DAY_OF_MONTH, cal.get(Calendar.DATE) - 7);
        Date lastSevenDays = cal.getTime();
        return lastSevenDays;
    }
</code>```

how could i adapt using Carbon so that he returned the quantity of products registered in the last 7 days?
the return would be an array like this:

```<code>[6,4,18,11,5,16,7]
</code>```

答:
Why not just fetch all records in last 7 days and group by date</p>

```<code>use Carbon\Carbon;

$productsByDay = Product::where('created_at', '>=', Carbon::now()->subDays(7))
                ->groupBy('date')
                ->orderBy('date', 'DESC')
                ->get([
                DB::raw('DATE(created_at) as date'),
                DB::raw('COUNT(*) as "products"')
])->pluck('products','date')->toArray();
//I recommend key by date, so that if you have no products on a date, you still have the dates in order.

//you can pass timezone in now() method of carbon, if you timezone is different than the timezone stored in DB
</code>```

Body:
I have a table with products.
In this table I have a column with the date of the products' cacastrast.

I was looking at Carbon and wanted to implement a method in my Laravel application that showed the quantity of products in the last 7 days.

In Java I used this method:

public Date getSevenDays() {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.DAY_OF_MONTH, cal.get(Calendar.DATE) - 7);
        Date lastSevenDays = cal.getTime();
        return lastSevenDays;
    }

how could i adapt using Carbon so that he returned the quantity of products registered in the last 7 days?
the return would be an array like this:

[6,4,18,11,5,16,7]

Body:
Why not just fetch all records in last 7 days and group by date

use Carbon\Carbon;

$productsByDay = Product::where('created_at', '>=', Carbon::now()->subDays(7))
                ->groupBy('date')
                ->orderBy('date', 'DESC')
                ->get([
                DB::raw('DATE(created_at) as date'),
                DB::raw('COUNT(*) as "products"')
])->pluck('products','date')->toArray();
//I recommend key by date, so that if you have no products on a date, you still have the dates in order.

//you can pass timezone in now() method of carbon, if you timezone is different than the timezone stored in DB


问:
There is no package called 'stringi' when using library 'car'

Purpose

I was trying to use vif() function from the car package of R.

Initial Error Messages

When I first executed vif(X), an error message popped up as:

```<code>Error in vif(mod1) : could not find function "vif"
</code>```

I tried library(car) and get a following error as:

```<code>Error: package or namespace load failed for ‘car’ in loadNamespace(i, c(lib.loc, .libPaths()), versionCheck = vI[[i]]):
 there is no package called ‘stringi’
</code>```

References

I read and tried the following references until I solved the problem:

https://github.com/gagolews/stringi/issues/178

答:
Solution

Step 1: Remove "stringi"

```<code>$ wget https://github.com/Rexamine/stringi/archive/master.zip
$ unzip master.zip
$ R CMD INSTALL stringi-master --preclean
</code>```

Step 2: Reinstall "stringi" from binary (NOT source)

```<code>R$ install.packages('stringi')
</code>```

You will be asked:

```<code>There is a binary version available but the source version is later:
        binary source needs_compilation
stringi  1.4.5  1.4.6              TRUE

Do you want to install from sources the package which needs compilation? (Yes/no/cancel)
</code>```

Please answer no to install from binary.

Solved

Now try:

```<code>R$ library(car)
R$ ?vif
</code>```

And everything works fine.

Body:
Purpose

I was trying to use vif() function from the car package of R.

Initial Error Messages

When I first executed vif(X), an error message popped up as:

Error in vif(mod1) : could not find function "vif"

I tried library(car) and get a following error as:

Error: package or namespace load failed for ‘car’ in loadNamespace(i, c(lib.loc, .libPaths()), versionCheck = vI[[i]]):
 there is no package called ‘stringi’

References

I read and tried the following references until I solved the problem:

https://github.com/gagolews/stringi/issues/178

Body:
Solution

Step 1: Remove "stringi"

$ wget https://github.com/Rexamine/stringi/archive/master.zip
$ unzip master.zip
$ R CMD INSTALL stringi-master --preclean

Step 2: Reinstall "stringi" from binary (NOT source)

R$ install.packages('stringi')

You will be asked:

There is a binary version available but the source version is later:
        binary source needs_compilation
stringi  1.4.5  1.4.6              TRUE

Do you want to install from sources the package which needs compilation? (Yes/no/cancel)

Please answer no to install from binary.

Solved

Now try:

R$ library(car)
R$ ?vif

And everything works fine.


问:
How would you find the maximum number a string has been repeated consecutively in a list?
Say for example a list looks like this:

```<code>['ABC', 'ABC', 'XYZ', 'ABC', 'ABC', 'ABC']
</code>```

And you pass in 'ABC'
It should return the number 3, since the maximum number of times 'ABC' has repeated consecutively is 3.
How would you go about doing this?

I've tried iterating through the list checking if the index is 'ABC', and if the next index is 'ABC', but this makes finding the maximum number almost impossible.

答:
Try:

from itertools import groupby

x=['ABC', 'ABC', 'XYZ', 'ABC', 'ABC', 'ABC']

y=dict(sorted([(gr, len(list(val))) for gr, val in groupby(x, lambda el: el)], key=lambda el: el[1]))
```

<p>It will return <code>dict</code> of maximal consecutive occurrences per element - so to get it for <code>ABC</code> just do:</p>

<pre class="lang-py prettyprint-override"><code>>> y["ABC"]
3
</code>```

In short what's happening there - groupby will group consecutive occurrences together.

len(list(val)) will count them.

Next we sort them to get the elements with highest number of consecutive occurrences at the end.

Then we convert to dict - leveraging the fact, that in case of multiple occurrences of the same key - dict always takes the last one, which thanks to sorting will always be the one with highest number of occurrences.

Body:
Say for example a list looks like this:

['ABC', 'ABC', 'XYZ', 'ABC', 'ABC', 'ABC']

And you pass in 'ABC'
It should return the number 3, since the maximum number of times 'ABC' has repeated consecutively is 3.
How would you go about doing this?

I've tried iterating through the list checking if the index is 'ABC', and if the next index is 'ABC', but this makes finding the maximum number almost impossible.

Body:
Try:

from itertools import groupby

x=['ABC', 'ABC', 'XYZ', 'ABC', 'ABC', 'ABC']

y=dict(sorted([(gr, len(list(val))) for gr, val in groupby(x, lambda el: el)], key=lambda el: el[1]))

It will return dict of maximal consecutive occurrences per element - so to get it for ABC just do:

>> y["ABC"]
3

In short what's happening there - groupby will group consecutive occurrences together.

len(list(val)) will count them.

Next we sort them to get the elements with highest number of consecutive occurrences at the end.

Then we convert to dict - leveraging the fact, that in case of multiple occurrences of the same key - dict always takes the last one, which thanks to sorting will always be the one with highest number of occurrences.


问:
How to write a dataframe/list into a csv-file?
I have written the following code and I want to write the output into a csv file. How can I do this? Thanks for helping me.
Here is an extract from my code:

```<code>columnNames = ['Stride Length', 'Stand Duration', 'Swing Duration', 'Douple Support Time', 'Relation Swing Stand']

resultsPerRowRatio = list()

for i in range(len(stepData)):
     stepDataLeft = stepData.to_numpy()[i, 0:5]
     stepDataRight = stepData.to_numpy()[i, 5:10]
     dataF = pd.DataFrame({'stepDataLeft': stepDataLeft, 'stepDataRight': stepDataRight}, index=columnNames)

     #Symmetry Ratio:
     dataF['Symmetry Ratio Row']=np.where(dataF['stepDataLeft'] < dataF['stepDataRight'],sv.symmetryRatio(dataF['stepDataLeft'],dataF['stepDataRight']), sv.symmetryRatio(dataF['stepDataRight'],dataF['stepDataLeft']))
     resultsPerRowRatio.append(dataF)

print("Symmetry Ratio: "+str(resultsPerRowRatio))
</code>```

This is my output:

I want to write this in a csv file. But I don't know how. I have already tried various options.

答:
This is an approach to consider using to_csv():

to_csv() Parameters(more are available, but this is simple case):

header: column header, True to include or False to exclude

mode: 'a' to append to an existing file, 'w' for creating and writing a new file

index: True to include indexing, False to exclude

Example:

```<code>PATH = your_folder_path
FILENAME = output_file_name

if os.path.isfile(PATH+FILENAME):
    dataF.to_csv(PATH+FILENAME, header=False, mode='a', index=True)
else:
    dataF.to_csv(PATH+FILENAME, header=True, mode='w', index=True)
</code>```

This structure will do a logic check to see if your output file already exists in the folder path you've defined, if it does exist, it will append the data to the csv file without the associated header column names via the to_csv() call. If it doesn't exist, it will generate a new csv file and include the column names as a header.

Body:
I have written the following code and I want to write the output into a csv file. How can I do this? Thanks for helping me.
Here is an extract from my code:

columnNames = ['Stride Length', 'Stand Duration', 'Swing Duration', 'Douple Support Time', 'Relation Swing Stand']

resultsPerRowRatio = list()

for i in range(len(stepData)):
     stepDataLeft = stepData.to_numpy()[i, 0:5]
     stepDataRight = stepData.to_numpy()[i, 5:10]
     dataF = pd.DataFrame({'stepDataLeft': stepDataLeft, 'stepDataRight': stepDataRight}, index=columnNames)

     #Symmetry Ratio:
     dataF['Symmetry Ratio Row']=np.where(dataF['stepDataLeft'] < dataF['stepDataRight'],sv.symmetryRatio(dataF['stepDataLeft'],dataF['stepDataRight']), sv.symmetryRatio(dataF['stepDataRight'],dataF['stepDataLeft']))
     resultsPerRowRatio.append(dataF)

print("Symmetry Ratio: "+str(resultsPerRowRatio))

This is my output:

I want to write this in a csv file. But I don't know how. I have already tried various options.

Body:
This is an approach to consider using to_csv():

to_csv() Parameters(more are available, but this is simple case):

header: column header, True to include or False to exclude

mode: 'a' to append to an existing file, 'w' for creating and writing a new file

index: True to include indexing, False to exclude

Example:

PATH = your_folder_path
FILENAME = output_file_name

if os.path.isfile(PATH+FILENAME):
    dataF.to_csv(PATH+FILENAME, header=False, mode='a', index=True)
else:
    dataF.to_csv(PATH+FILENAME, header=True, mode='w', index=True)

This structure will do a logic check to see if your output file already exists in the folder path you've defined, if it does exist, it will append the data to the csv file without the associated header column names via the to_csv() call. If it doesn't exist, it will generate a new csv file and include the column names as a header.


问:
WPF Telerik Rad Map Polygon Data binding to Polygon Data within class
I am trying to add polygons to the telerik rad map with a PolygonData class embedded within a parent class.

```<code>public class PolygonClass
{
    public int ID { get; set; }
    public PolygonData Polygon { get; set; }
}
</code>```

I'm trying to bind my VisualizationLayer.ItemSource to the 'Polygon' Property within 'PolygonClass' because I need to reference an ID value in various other places of my application. The only way I've recently been able to make this work is by binding to a property of ObservableCollection.

Has anyone else ran into this and knows of a solution? Thanks in advance.

答:
There are several ways to achieve your requirement.

You can populate the Items collection of VisualizaztionLayer (instead of ItemsSource) with PolygonData objects. Any additional information, like the the ID, can be stored in the ExtendedData property of the PolygonData.

```<code>PolygonData polygon = new PolygonData();
polygon.ExtendedData["ID"] = 3;
</code>```

Or you can use the map bindable wrappers inside the ItemTemplate property of VisualizationLayer. In your case the wrapper that should be used is MapPolygonView.

```<code><telerik:VisualizationLayer.ItemTemplate>
    <DataTemplate>
        <telerik:MapPolygonView Points="{Binding Polygon.Points}" />
    </DataTemplate>
</telerik:VisualizationLayer.ItemTemplate>
</code>```

Note that in this case, you won't need the PolygonData in your PolygonClass, because the MapPolygonView will automatically generate one and add in the VisualizationLayer. Instead, you can define the shape information (like points and fill) in PolygonClass and data bind to those.

Body:
I am trying to add polygons to the telerik rad map with a PolygonData class embedded within a parent class.

public class PolygonClass
{
    public int ID { get; set; }
    public PolygonData Polygon { get; set; }
}

I'm trying to bind my VisualizationLayer.ItemSource to the 'Polygon' Property within 'PolygonClass' because I need to reference an ID value in various other places of my application. The only way I've recently been able to make this work is by binding to a property of ObservableCollection.

Has anyone else ran into this and knows of a solution? Thanks in advance.

Body:
There are several ways to achieve your requirement.

You can populate the Items collection of VisualizaztionLayer (instead of ItemsSource) with PolygonData objects. Any additional information, like the the ID, can be stored in the ExtendedData property of the PolygonData.

PolygonData polygon = new PolygonData();
polygon.ExtendedData["ID"] = 3;

Or you can use the map bindable wrappers inside the ItemTemplate property of VisualizationLayer. In your case the wrapper that should be used is MapPolygonView.

<telerik:VisualizationLayer.ItemTemplate>
    <DataTemplate>
        <telerik:MapPolygonView Points="{Binding Polygon.Points}" />
    </DataTemplate>
</telerik:VisualizationLayer.ItemTemplate>

Note that in this case, you won't need the PolygonData in your PolygonClass, because the MapPolygonView will automatically generate one and add in the VisualizationLayer. Instead, you can define the shape information (like points and fill) in PolygonClass and data bind to those.


问:
Failed to markdown parser function in php using regex
Let's write a simple markdown parser function that will take in a single line of markdown and be translated into the appropriate HTML. To keep it simple, we'll support only one feature of markdown in atx syntax: headers.

Headers are designated by (1-6) hashes followed by a space, followed by text. The number of hashes determines the header level of the HTML output.

Examples

```<code># Header will become <h1>Header</h1>
## Header will become <h2>Header</h2>
###### Header will become <h6>Header</h6>
</code>```

My code :

```<code>function markdown_parser ($markdown) {
$regex = '/(?:(#+)(.+?)\n)|(?:(.+?)\n\s*=+\s*\n)/';
$headerText = $markdown."\n";
$headerText = preg_replace_callback(
    $regex,
    function($matches){
        if (!preg_match('/\s/',$matches[2])) {
            return "#".$matches[2];
        }
        if($matches[1] != ""){
           $h_num = strlen($matches[1]);
           return html_entity_decode("<h$h_num>".trim($matches[2])."</h$h_num>");
        }
    },
    $headerText
);
return $headerText;
}
</code>```

its not working as failed test case :

```<code>Failed asserting that two strings are identical.
Expected: Behind # The Scenes
Actual  : Behind <h1>The Scenes</h1>
</code>```

答:
What i understood is you want to limit your markdown conversion to a range of 1-6 depth for your title.

Give a try to this code :

```<code>function markdown_parser ($markdown) {
    $regex = '/(?:(#+)(.+?)\n)|(?:(.+?)\n\s*=+\s*\n)/';
    $headerText = $markdown."\n";
    $headerText = preg_replace_callback(
        $regex,
        function($matches) use ($markdown){
            if (!preg_match('/\s/',$matches[2])) {
                return "#".$matches[2];
            }
            if($matches[1] != ""){
                $h_num = strlen($matches[1]);
                if (\in_array($h_num, \range(1, 6), true)) {
                    return html_entity_decode("<h$h_num>" . trim($matches[2]) . "</h$h_num>");
                }

                return $markdown;
            }
        },
        $headerText
    );
    return $headerText;
}
</code>```

I only add a condition to check if your number of hashtag is in range of 1 until 6if (\in_array($h_num, \range(1, 6), true)) {

Body:
Let's write a simple markdown parser function that will take in a single line of markdown and be translated into the appropriate HTML. To keep it simple, we'll support only one feature of markdown in atx syntax: headers.

Headers are designated by (1-6) hashes followed by a space, followed by text. The number of hashes determines the header level of the HTML output.

Examples

# Header will become
Header

## Header will become
Header

###### Header will become
Header

My code :

function markdown_parser ($markdown) {
$regex = '/(?:(#+)(.+?)\n)|(?:(.+?)\n\s*=+\s*\n)/';
$headerText = $markdown."\n";
$headerText = preg_replace_callback(
    $regex,
    function($matches){
        if (!preg_match('/\s/',$matches[2])) {
            return "#".$matches[2];
        }
        if($matches[1] != ""){
           $h_num = strlen($matches[1]);
           return html_entity_decode("<h$h_num>".trim($matches[2])."</h$h_num>");
        }
    },
    $headerText
);
return $headerText;
}

its not working as failed test case :

Failed asserting that two strings are identical.
Expected: Behind # The Scenes
Actual  : Behind
The Scenes

Body:
What i understood is you want to limit your markdown conversion to a range of 1-6 depth for your title.

Give a try to this code :

function markdown_parser ($markdown) {
    $regex = '/(?:(#+)(.+?)\n)|(?:(.+?)\n\s*=+\s*\n)/';
    $headerText = $markdown."\n";
    $headerText = preg_replace_callback(
        $regex,
        function($matches) use ($markdown){
            if (!preg_match('/\s/',$matches[2])) {
                return "#".$matches[2];
            }
            if($matches[1] != ""){
                $h_num = strlen($matches[1]);
                if (\in_array($h_num, \range(1, 6), true)) {
                    return html_entity_decode("<h$h_num>" . trim($matches[2]) . "</h$h_num>");
                }

                return $markdown;
            }
        },
        $headerText
    );
    return $headerText;
}

I only add a condition to check if your number of hashtag is in range of 1 until 6if (\in_array($h_num, \range(1, 6), true)) {


问:
macOS send keystroke to the active app periodically
I am trying to send a keystroke (command+ shift+ r) to a macOS (Mojave) app called "Dbeaver" every minute as long as DBeaver is the active app. I have tried the following with no effect.

```<code>tell application "System Events"
    set activeApp to name of first application process whose frontmost is true
    if "DBeaver" is in activeApp then
        tell application "System Events" to keystroke "r" using {command down, shift down}

    end if
end tell
</code>```

The script works perfectly fine if its simple like the following:

```<code>activate application "DBeaver"
tell application "System Events" to keystroke "r" using {command down, shift down}
</code>```

答:
You want to avoid using something like a repeat loop, as that will block the app's user interface (for quitting or to just avoid the spinning wheel of death).  A relatively easy way to repeat stuff like that is to make a stay-open application, and put your repeating code in the idle handler, which uses a timer - for example:

```<code>on idle
    tell application "System Events"
        set activeApp to name of first application process whose frontmost is true
        if "DBeaver" is in activeApp then
            tell application "System Events" to keystroke "r" using {command down, shift down}
        end if
    end tell
    return 60 -- do it again in 60 seconds
end
</code>```

The statements in the idle handler are run when the app is idle; the return value determines the number of seconds before the handler is run again.

Body:
I am trying to send a keystroke (command+ shift+ r) to a macOS (Mojave) app called "Dbeaver" every minute as long as DBeaver is the active app. I have tried the following with no effect.

tell application "System Events"
    set activeApp to name of first application process whose frontmost is true
    if "DBeaver" is in activeApp then
        tell application "System Events" to keystroke "r" using {command down, shift down}

    end if
end tell

The script works perfectly fine if its simple like the following:

activate application "DBeaver"
tell application "System Events" to keystroke "r" using {command down, shift down}

Body:
You want to avoid using something like a repeat loop, as that will block the app's user interface (for quitting or to just avoid the spinning wheel of death).  A relatively easy way to repeat stuff like that is to make a stay-open application, and put your repeating code in the idle handler, which uses a timer - for example:

on idle
    tell application "System Events"
        set activeApp to name of first application process whose frontmost is true
        if "DBeaver" is in activeApp then
            tell application "System Events" to keystroke "r" using {command down, shift down}
        end if
    end tell
    return 60 -- do it again in 60 seconds
end

The statements in the idle handler are run when the app is idle; the return value determines the number of seconds before the handler is run again.


问:
Docker - Laravel - Not able to set it up
I am simply unable to get my laravel app up and running on nginx reverse proxy on digital ocean using docker. Please tell me what I am doing wrong. I am getting 502 or 500 errors.

My Dockerfile is:

```<code>FROM php:7.2.2-fpm

WORKDIR /app
COPY . /app

CMD php artisan serve --host=127.0.0.1 --port=8000
EXPOSE 8000

</code>```

and my docker-compose.yml file is

```<code>version: "3"

services:
  # App php-fpm service
  app:
    build: ./
    container_name: livechats_app
    restart: unless-stopped
    expose:
      - 80
    environment:
      VIRTUAL_HOST: livechats.mikolaj.dk
      VIRTUAL_PORT: 8000
      LETSENCRYPT_HOST: livechats.mikolaj.dk
      LETSENCRYPT_EMAIL: mikoo1991@yahoo.com
</code>```

答:
Exposing a port, doesn't bind it to the host, it only share with other services inside docker network

Dockerfile:

```<code>FROM php:7.2.2-fpm

WORKDIR /app
COPY . /app

EXPOSE 8000
CMD php artisan serve --host=127.0.0.1 --port=8000
</code>```

docker-compose.yml:

```<code>version: "3"

services:
  # App php-fpm service
  app:
    build: ./
    container_name: livechats_app
    restart: unless-stopped
    ports:
      - "80:8000"
    expose:
      - 80
    environment:
      VIRTUAL_HOST: livechats.mikolaj.dk
      VIRTUAL_PORT: 8000
      LETSENCRYPT_HOST: livechats.mikolaj.dk
      LETSENCRYPT_EMAIL: mikoo1991@yahoo.com
</code>```

Body:
I am simply unable to get my laravel app up and running on nginx reverse proxy on digital ocean using docker. Please tell me what I am doing wrong. I am getting 502 or 500 errors.

My Dockerfile is:

FROM php:7.2.2-fpm

WORKDIR /app
COPY . /app

CMD php artisan serve --host=127.0.0.1 --port=8000
EXPOSE 8000

and my docker-compose.yml file is

version: "3"

services:
  # App php-fpm service
  app:
    build: ./
    container_name: livechats_app
    restart: unless-stopped
    expose:
      - 80
    environment:
      VIRTUAL_HOST: livechats.mikolaj.dk
      VIRTUAL_PORT: 8000
      LETSENCRYPT_HOST: livechats.mikolaj.dk
      LETSENCRYPT_EMAIL: mikoo1991@yahoo.com

Body:
Exposing a port, doesn't bind it to the host, it only share with other services inside docker network

Dockerfile:

FROM php:7.2.2-fpm

WORKDIR /app
COPY . /app

EXPOSE 8000
CMD php artisan serve --host=127.0.0.1 --port=8000

docker-compose.yml:

version: "3"

services:
  # App php-fpm service
  app:
    build: ./
    container_name: livechats_app
    restart: unless-stopped
    ports:
      - "80:8000"
    expose:
      - 80
    environment:
      VIRTUAL_HOST: livechats.mikolaj.dk
      VIRTUAL_PORT: 8000
      LETSENCRYPT_HOST: livechats.mikolaj.dk
      LETSENCRYPT_EMAIL: mikoo1991@yahoo.com


问:
Template object gets "does not name a type."
I want to create a class that contains a struct with a template.  But it gives this error, and though I've seen other similar questions, I don't understand how or if I can declare this in a way that does not give this error.  thanks for your help.

```<code># include <iostream>

using namespace std;

template <class T>
class MyTmpl {
public:
    MyTmpl() {}
    T body;
};

struct s1_t {
    std::string s;
    int x;
};

MyTmpl<s1_t> myc();
myc.body.s = "s1";
myc.body.x = 7;

int main(int argc, char** argv) {
    //std::cout << myc.body.s << ':' << myc.body.x << std::endl;
}
</code>```

This gives:

```<code>x.cpp:24:1: error: 'myc' does not name a type
    myc.body.s = "s1";
    ^
</code>```

答:
```<code>myc.body.s = "s1";
myc.body.x = 7;
</code>```

Your immediate error is because you have this code where no code should be (at file level, outside of any function). You need to move it into main (or somewhere else that is is allowed to be, but probably main in this case).

The reason you see the does not name a type is simply because code is unexpected at that point so the compiler thinks you're trying to declare something (like, for example, int x;).

You'll get the same error with the code snippet:

```<code>//using nontype = int;
nontype x;
</code>```

because nontype is not actually a type. If you however uncomment the using (a slightly more modern typedef), the nontype becomes a type and the error disappears.

Your second problem is that MyTmpl<s1_t> myc(); is a function declaration, something that would become evident if you included in your main:

```<code>auto x = myc();
</code>```

The linker would then complain about the lack of a myc function definition. You should change it to:

```<code>MyTmpl<s1_t> myc; // without the ().
</code>```

Your third problem is that, while you're using the C++ language, you're not quite yet using the C++ mindset.  The whole point of classes is to encapsulate behaviour and state, something that's rather nullified if everything in your class is public :-)

Eventually (with experience), you'll get into the habit of privatising as much as possible, providing constructors, getters, setters, and so forth. Not an immediate issue for you but certainly something you'll want to work toward.

With those changes (other the the "C++ification") and uncommenting your output statement, the following resulting code compiles and runs fine, producing s1:7 as expected:

```<code>#include <iostream>

template <class T> class MyTmpl {
    public:

    MyTmpl() { }
    T body;
};

struct s1_t {
    std::string s;
    int x;
};

MyTmpl<s1_t> myc;  // variable, rather than function.
// code not allowed here.

int main() {
    myc.body.s = "s1";  // code allowed here.
    myc.body.x = 7;
    std::cout << myc.body.s << ':' << myc.body.x << std::endl;
}
</code>```

Body:
I want to create a class that contains a struct with a template.  But it gives this error, and though I've seen other similar questions, I don't understand how or if I can declare this in a way that does not give this error.  thanks for your help.

# include <iostream>

using namespace std;

template <class T>
class MyTmpl {
public:
    MyTmpl() {}
    T body;
};

struct s1_t {
    std::string s;
    int x;
};

MyTmpl<s1_t> myc();
myc.body.s = "s1";
myc.body.x = 7;

int main(int argc, char** argv) {
    //std::cout << myc.body.s << ':' << myc.body.x << std::endl;
}

This gives:

x.cpp:24:1: error: 'myc' does not name a type
    myc.body.s = "s1";
    ^

Body:
myc.body.s = "s1";
myc.body.x = 7;

Your immediate error is because you have this code where no code should be (at file level, outside of any function). You need to move it into main (or somewhere else that is is allowed to be, but probably main in this case).

The reason you see the does not name a type is simply because code is unexpected at that point so the compiler thinks you're trying to declare something (like, for example, int x;).

You'll get the same error with the code snippet:

//using nontype = int;
nontype x;

because nontype is not actually a type. If you however uncomment the using (a slightly more modern typedef), the nontype becomes a type and the error disappears.

Your second problem is that MyTmpl<s1_t> myc(); is a function declaration, something that would become evident if you included in your main:

auto x = myc();

The linker would then complain about the lack of a myc function definition. You should change it to:

MyTmpl<s1_t> myc; // without the ().

Your third problem is that, while you're using the C++ language, you're not quite yet using the C++ mindset.  The whole point of classes is to encapsulate behaviour and state, something that's rather nullified if everything in your class is public :-)

Eventually (with experience), you'll get into the habit of privatising as much as possible, providing constructors, getters, setters, and so forth. Not an immediate issue for you but certainly something you'll want to work toward.

With those changes (other the the "C++ification") and uncommenting your output statement, the following resulting code compiles and runs fine, producing s1:7 as expected:

#include <iostream>

template <class T> class MyTmpl {
    public:

    MyTmpl() { }
    T body;
};

struct s1_t {
    std::string s;
    int x;
};

MyTmpl<s1_t> myc;  // variable, rather than function.
// code not allowed here.

int main() {
    myc.body.s = "s1";  // code allowed here.
    myc.body.x = 7;
    std::cout << myc.body.s << ':' << myc.body.x << std::endl;
}


问:
Check the type of a required module and if it returns right object based on its type
In a nodejs contest i would like to leave free the choice of how to write typescript modules (or even javascript) that perform operations on an observable. However, I need to know what type of function has been chosen in order to be able to use the right operator on the observable. The question is better understood by looking at the example:

```<code>import { Observable } from "rxjs";
import { concatMap, map } from "rxjs/operators";

function attachOperation( in$:Observable<MyObject>, modulePath:string ):Observable<MyObject>{

  //types of modules that can be loaded
  type ObservableOperation = ( x: Observable<MyObject> ) => Observable<MyObject>
  type PromiseOperation = (x: MyObject ) => Promise<MyObject>
  type FunctionOperation = (x: MyObject ) => MyObject

  const operation = require(modulePath)

  let outObservable:Observable<MyObject>

  if( /* is ObservableOperation type */ ){

    outObservable = operation(in$)

  }else if( /* is PromiseOperation type */ ){

    outObservable = in$.pipe( concatMap( myObj => operation( myObj ) ) )

  }else if( /* is FunctionOperation type */ ){

    outObservable = in$.pipe( map( myObj => operation(myObj) ) )

  }else{

    throw new Error('not valid operation module')

  }

  return outObservable

}
</code>```

How can i check (in the if statements) what type of module was loaded?

Edit: i also need to throw an error if the module does not returns the right object based on its type

答:
TypeScript isn't capable of runtime type-checking, so while a solution to the problem as you describe could be possible, I would still suggest making your problem/solution less 'clever'.

"Dynamic" solutions often seem very appealing, but successfully implementing them is rarely worth the hassle. For instance, you could probably get the result you want with static analysis of the TypeScript imports combined with custom code generation to bring that type data into runtime. But I would guess you really don't want to go down that road.

You could achieve similar results by tying behavior to the import path, e.g. exports from paths resembling src/function/**/*.js are handled as functions, exports from src/observable/**/*.js are handled as observable factories, etc.

Error handling becomes simpler here too. You can throw if you call an exported function and it doesn't return the sort of value you expect.

Body:
In a nodejs contest i would like to leave free the choice of how to write typescript modules (or even javascript) that perform operations on an observable. However, I need to know what type of function has been chosen in order to be able to use the right operator on the observable. The question is better understood by looking at the example:

import { Observable } from "rxjs";
import { concatMap, map } from "rxjs/operators";

function attachOperation( in$:Observable<MyObject>, modulePath:string ):Observable<MyObject>{

  //types of modules that can be loaded
  type ObservableOperation = ( x: Observable<MyObject> ) => Observable<MyObject>
  type PromiseOperation = (x: MyObject ) => Promise<MyObject>
  type FunctionOperation = (x: MyObject ) => MyObject

  const operation = require(modulePath)

  let outObservable:Observable<MyObject>

  if( /* is ObservableOperation type */ ){

    outObservable = operation(in$)

  }else if( /* is PromiseOperation type */ ){

    outObservable = in$.pipe( concatMap( myObj => operation( myObj ) ) )

  }else if( /* is FunctionOperation type */ ){

    outObservable = in$.pipe( map( myObj => operation(myObj) ) )

  }else{

    throw new Error('not valid operation module')

  }

  return outObservable

}

How can i check (in the if statements) what type of module was loaded?

Edit: i also need to throw an error if the module does not returns the right object based on its type


问:
How do I upload a file given its absolute path in rust?
My objective is to upload a file on ipfs.io using Rust programming language. I am firing a command-line tool to do so and the command itself works but when implemented using Rust, it fails.

The actual command is:

```<code>➜  ~ ipfs add ~/dev/learning-rust/upload-file-to-ipfs/src/main.rs
added QmPUGDCiLvjEiETVDVMHqgJ8xxtQ5Hu7YEMzFqRfE8vDfq main.rs
</code>```

Now, my Rust code is:

```<code>use std::io;
use std::process::Command;

fn main() {
    // ask user to provide the file path to be uploaded on ipfs
    println!("Please enter the file path to upload on IPFS: ");
    let mut file_path = String::new();
    io::stdin()
        .read_line(&mut file_path)
        .expect("Failed to read temperature.");
    // uploading a file
    let output = Command::new("ipfs")
        .arg("add")
        .arg(file_path)
        .output()
        .expect("ipfs command failed to start");
    println!("Output is: {:?}", output);
    // println!("The hash digest is: {:?}", output.stdout);
}
</code>```

This fails with the following error:

```<code>Output is: Output { status: ExitStatus(ExitStatus(256)), stdout: "", stderr: "Error: lstat /Users/aviralsrivastava/dev/learning-rust/upload-file-to-ipfs/src/main.rs\n: no such file or directory\n\nUSAGE\n  ipfs add <path>... - Add a file or directory to ipfs.\n\n  ipfs add [--recursive | -r] [--quiet | -q] [--quieter | -Q] [--silent] [--progress | -p] [--trickle | -t] [--only-hash | -n] [--wrap-with-directory | -w] [--hidden | -H] [--chunker=<chunker> | -s] [--pin=false] [--raw-leaves] [--nocopy] [--fscache] [--cid-version=<cid-version>] [--] <path>...\n\n  Adds contents of <path> to ipfs. Use -r to add directories (recursively).\n\nUse \'ipfs add --help\' for more information about this command.\n\n" }
</code>```

I referred to  this to answer and read the official documentation, all in vain.

How do I upload a file given absolute and/or relative path and return the hash in the print statement?

答:
Your problem isn't with Command it's with read_line, which will read all bytes up to and including the newline character (see here). Therefore your path ends up containing the newline character, which is why the file cannot be found.

To solve this, you need to make sure that the file path doesn't contain the trailing newline, e.g. by calling trim_end on it before passing it to the command.

Body:
My objective is to upload a file on ipfs.io using Rust programming language. I am firing a command-line tool to do so and the command itself works but when implemented using Rust, it fails.

The actual command is:

➜  ~ ipfs add ~/dev/learning-rust/upload-file-to-ipfs/src/main.rs
added QmPUGDCiLvjEiETVDVMHqgJ8xxtQ5Hu7YEMzFqRfE8vDfq main.rs

Now, my Rust code is:

use std::io;
use std::process::Command;

fn main() {
    // ask user to provide the file path to be uploaded on ipfs
    println!("Please enter the file path to upload on IPFS: ");
    let mut file_path = String::new();
    io::stdin()
        .read_line(&mut file_path)
        .expect("Failed to read temperature.");
    // uploading a file
    let output = Command::new("ipfs")
        .arg("add")
        .arg(file_path)
        .output()
        .expect("ipfs command failed to start");
    println!("Output is: {:?}", output);
    // println!("The hash digest is: {:?}", output.stdout);
}

This fails with the following error:

Output is: Output { status: ExitStatus(ExitStatus(256)), stdout: "", stderr: "Error: lstat /Users/aviralsrivastava/dev/learning-rust/upload-file-to-ipfs/src/main.rs\n: no such file or directory\n\nUSAGE\n  ipfs add <path>... - Add a file or directory to ipfs.\n\n  ipfs add [--recursive | -r] [--quiet | -q] [--quieter | -Q] [--silent] [--progress | -p] [--trickle | -t] [--only-hash | -n] [--wrap-with-directory | -w] [--hidden | -H] [--chunker=<chunker> | -s] [--pin=false] [--raw-leaves] [--nocopy] [--fscache] [--cid-version=<cid-version>] [--] <path>...\n\n  Adds contents of <path> to ipfs. Use -r to add directories (recursively).\n\nUse \'ipfs add --help\' for more information about this command.\n\n" }

I referred to  this to answer and read the official documentation, all in vain.

How do I upload a file given absolute and/or relative path and return the hash in the print statement?


问:
Failed to load resource: the server responded with a status of 404 (Not Found) in React.js Project deployed
When I deploy my react project into Surge, the build is successful and can get the app URL.
But when I link to the URL, I can see one blank page and some bunch of errors in the inspect console:

```<code>Failed to load resource: the server responded with a status of 404 (Not Found) 3.138a0231.chunk.css
Failed to load resource: the server responded with a status of 404 (Not Found) main.bd0d3f99.chunk.js:1
Failed to load resource: the server responded with a status of 404 (Not Found) main.bd0d3f99.chunk.css:1
Failed to load resource: the server responded with a status of 404 (Not Found)
Failed to load resource: the server responded with a status of 404 (Not Found)
Failed to load resource: the server responded with a status of 404 (Not Found) manifest.json:1
Manifest: Line: 1, column: 1, Syntax error. manifest.json:1
Failed to load resource: the server responded with a status of 404 (Not Found) 3.138a0231.chunk.css
Failed to load resource: the server responded with a status of 404 (Not Found) 3.138a0231.chunk.css
Failed to load resource: the server responded with a status of 404 (Not Found) main.bd0d3f99.chunk.css:1
</code>```

Here is the react start script in my package.json file.

```<code>"scripts": {
  "build": "REACT_APP_BACKEND=true PUBLIC_URL='/sing-app-react' node scripts/build.js",
  "start": "node scripts/start.js",
  "start:backend": "REACT_APP_BACKEND=true node scripts/start.js",
  "test": "node scripts/test.js"
},
</code>```

And the link address to css file that causes the erros https://lopsided-dinner.surge.sh/sing-app-react/static/css/3.138a0231.chunk.css

答:
https://lopsided-dinner.surge.sh/sing-app-react/static/css/3.138a0231.chunk.css

This website url built by react script should be something like https://your domain/static/css...

Remove the PUBLIC_URL in your build script and run build again.

It leads the build source to /static/....

Hopefully that makes sense to you!

Body:
When I deploy my react project into Surge, the build is successful and can get the app URL.
But when I link to the URL, I can see one blank page and some bunch of errors in the inspect console:

Failed to load resource: the server responded with a status of 404 (Not Found) 3.138a0231.chunk.css
Failed to load resource: the server responded with a status of 404 (Not Found) main.bd0d3f99.chunk.js:1
Failed to load resource: the server responded with a status of 404 (Not Found) main.bd0d3f99.chunk.css:1
Failed to load resource: the server responded with a status of 404 (Not Found)
Failed to load resource: the server responded with a status of 404 (Not Found)
Failed to load resource: the server responded with a status of 404 (Not Found) manifest.json:1
Manifest: Line: 1, column: 1, Syntax error. manifest.json:1
Failed to load resource: the server responded with a status of 404 (Not Found) 3.138a0231.chunk.css
Failed to load resource: the server responded with a status of 404 (Not Found) 3.138a0231.chunk.css
Failed to load resource: the server responded with a status of 404 (Not Found) main.bd0d3f99.chunk.css:1

Here is the react start script in my package.json file.

"scripts": {
  "build": "REACT_APP_BACKEND=true PUBLIC_URL='/sing-app-react' node scripts/build.js",
  "start": "node scripts/start.js",
  "start:backend": "REACT_APP_BACKEND=true node scripts/start.js",
  "test": "node scripts/test.js"
},

And the link address to css file that causes the erros https://lopsided-dinner.surge.sh/sing-app-react/static/css/3.138a0231.chunk.css


答:
I think what you looking for is [here][1]

[1]: http://developer.android.com/guide/topics/data/data-storage.html take a look at shared preferences.

Title: Handling Android preferences without magic strings

Body:
Im using Androids built in way of handling preferences which works by writing all settings in an xml file. It's really nice but I can't find any good way of doing it without using magic strings in the xml and Java code.

The only way I could think of is to save the preference key as String but that doesn't feels right either. Anyone got a good way of solving this?


问:
How to distinguish a user-defined class and API class using Eclipse JDT ITypeBinding
I am using the following code while parsing a method invocation:

ITypeBinding typeBinding = node.getExpression().resolveTypeBinding();
if ( typeBinding != null) //type resolution found actual type
    {
        className = typeBinding.getName();
    }
```

<p>where className is a String containing the name of the type. Is there a way to distinguish between user-defined Java class names and API class names or external/included library class names in a method invocation?</p>

<p>For example, given a complete invocation <code>String.valueOf(c);</code>, I want to detect <code>String</code> as a non-user-defined class name with a method invocation <code>valueOf</code>.</p>

<p>For the following code snippet:
<code>MyCalculator calc = new MyCalculator();
calc.add(1,2);
</code></p>

<p>Given the invocation <code>calc.add(1,2)</code>, I want to detect <code>MyCalculator</code> as a user-defined class name with a method invocation <code>add</code></p>

<p>I am including a code snippet showing how I set up parsing. Maybe someone can point put any errors in the setup.</p>

``` private static CompilationUnit parse(String unit) {
    ASTParser parser = ASTParser.newParser(AST.JLS8);
    parser.setResolveBindings(true);
    parser.setKind(ASTParser.K_COMPILATION_UNIT);
    parser.setBindingsRecovery(true);

    File f = new File(currentFilePath);
    String unitName = f.getName();
    parser.setUnitName(unitName);

    String[] sources = {Constants.SOURCES};
    String[] classpath = {Constants.CLASSPATH};

    parser.setEnvironment(classpath, sources, new String[] { "UTF-8"}, true);
    parser.setSource(unit.toCharArray());

    return (CompilationUnit) parser.createAST(null);
}
```

where Constants.SOURCES is public static String SOURCES = "F:\\BluetoothChat"; the path to the root folder of the Java project being parsed.

答:
JDT's Java Model has the notion that every IType is contained in an IPackageFragment which is rooted in an IPackageFragmentRoot. The latter represents either a source folder or a library (jar, class folder etc.).

This means, if you have resolved AST (DOM), you could ask the ITypeBinding representing the method receiver: getJavaElement(). The result should actually be an IType, which will tell you its package fragment root if you just say type.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT).

Looking at the package fragment root there are several options to figure out, what exactly you have, e.g., isArchive(). Also getResolvedClasspathEntry() can tell you, how this thing got pulled into compilation. Based on this information you can draw whatever line you wish between "your" code and "API".

Body:
I am using the following code while parsing a method invocation:

ITypeBinding typeBinding = node.getExpression().resolveTypeBinding();
if ( typeBinding != null) //type resolution found actual type
    {
        className = typeBinding.getName();
    }

where className is a String containing the name of the type. Is there a way to distinguish between user-defined Java class names and API class names or external/included library class names in a method invocation?

For example, given a complete invocation String.valueOf(c);, I want to detect String as a non-user-defined class name with a method invocation valueOf.

For the following code snippet:
MyCalculator calc = new MyCalculator();
calc.add(1,2);

Given the invocation calc.add(1,2), I want to detect MyCalculator as a user-defined class name with a method invocation add

I am including a code snippet showing how I set up parsing. Maybe someone can point put any errors in the setup.

 private static CompilationUnit parse(String unit) {
    ASTParser parser = ASTParser.newParser(AST.JLS8);
    parser.setResolveBindings(true);
    parser.setKind(ASTParser.K_COMPILATION_UNIT);
    parser.setBindingsRecovery(true);

    File f = new File(currentFilePath);
    String unitName = f.getName();
    parser.setUnitName(unitName);

    String[] sources = {Constants.SOURCES};
    String[] classpath = {Constants.CLASSPATH};

    parser.setEnvironment(classpath, sources, new String[] { "UTF-8"}, true);
    parser.setSource(unit.toCharArray());

    return (CompilationUnit) parser.createAST(null);
}

where Constants.SOURCES is public static String SOURCES = "F:\\BluetoothChat"; the path to the root folder of the Java project being parsed.


问:
Getting a 500 Internal Server Error when rewriting 2 specific URLs
I keep getting a 500 internal server error when trying to rewrite these one specific URLs/files (item.php & purchase.php), the rest works.

I have tried many ways to fix this but nothing seemed to work, which is weird because all other URLs do work, but these 2 just seem to not want to work for some reason.

.htaccess file

```<code>Options -Indexes
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php

ErrorDocument 500 "500"
ErrorDocument 404 "404"
ErrorDocument 403 "403"

RewriteRule ^users/([^/]*)$ /user/profile.php?username=$1
RewriteRule ^users/([^/]*)/inventory$ /user/GetUserInventory.php?username=$1

RewriteRule ^market/item/([^/]*)$ /market/item.php?id=$1
RewriteRule ^market/item/([^/]*)/purchase$ /market/purchase.php?id=$1

RewriteRule ^community/([^/]*)$ /communities/view.php?id=$1
RewriteRule ^community/([^/]*)/join$ /communities/join.php?id=$1
RewriteRule ^community/([^/]*)/manage$ /communities/manage.php?id=$1

RewriteRule ^game/([^/]*)$ /games/view.php?id=$1
</code>```

item.php

<?php
    include_once('../private/header.php');
    $item = $handler->query("SELECT * FROM items WHERE id=" . $_GET['id']);
    $gB = $item->fetch(PDO::FETCH_OBJ);

    echo '

    image.'.png" class="responsive-img">

'.$gB->name.'
    '.$gB->type.'

'.$gB->description.'

    ';

    if ($gB->onsale == 1){
        echo 'id.'/purchase" class="modal-trigger waves-effect waves-light btn green">Purchase';
    } else {
        echo 'Offsale';
    }

    echo '

    Creator
    creator.'" style="padding-top:12px;font-size:16px;display:inline-block;">'.$gB->creator.'
    ';

    if($gB->collectable == 'true'){
        if($gB->amount == 0)
            echo '
            Sold Out
            ';
        }else{
            echo '
            '.$gB->amount.' Remaining
            ';
    }

    echo '

'.$gB->created.'

Time Created

'.$gB->created.'

Last Updated

???

Owners

    ';

    include_once('../private/footer.php');
```

<p><strong>purchase.php</strong></p>

<pre class="lang-php prettyprint-override"><code><?php
    include_once('../private/config.php');

    if ($user){
        $money=$myu->CurrencyCoins;
        $id=$_GET['id'];
        $item = $handler->query("SELECT * FROM items WHERE id=" . $id);
        $gB = $item->fetch(PDO::FETCH_OBJ);
        $amount=$gB->amount;

        if ($gB->onsale == 1){
            if ($money >= $gB->price){
                if ($gB->collectable != "true"){
                    if ($amount != 0){
                        $new = ($money - $gB->price);
                        $handler->query("UPDATE `users` SET `CurrencyCoins`='".$new."' WHERE `id`='".$myu->id."'");
                        $handler->query("INSERT INTO inventory (item,user) VALUES (".$id.",".$myu->id.")");
                    }
            } else {
                if ($amount >= 1){
                    $amount1=($amount - 1);
                    $new = ($money - $gB->price);
                    $handler->query("UPDATE `users` SET `CurrencyCoins`='".$new."' WHERE `id`='".$myu->id."'");
                    $handler->query("UPDATE `items` SET `amount`='".$amount1."' WHERE `id`='".$gB->id."'");
                    $handler->query("INSERT INTO inventory (item,user) VALUES (".$id.",".$myu->id.")");
                } else {
                    echo '<center><h2>Item is sold out!</h2></center>';
                }
                }
            }
        } else {
        echo '<center><h2>Item not on sale!</h2></center>';
        }
    }

    echo '<head><meta http-equiv="refresh" content="1; url='.$serverUrl.'/account/character"></head>';
</code>```

答:
```<code>RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php
</code>```

These directives should be at the end of your .htaccess file, after the other rewrites. They are also incorrect - although by placing them at the end of the file it will avoid the immediate issue, but could still cause problems with other URLs.

In its current state, when you request example.com/market/item/1 (where it would seem, /market is a physical directory, and /item.php is a file in that directory) then...

In brief... it results in an endless rewrite loop:

```<code>/market/item/1.php
/market/item/1.php.php
/market/item/1.php.php.php
/market/item/1.php.php.php.php
etc.
</code>```

Which breaks (after 10 iterations) with a 500 response being sent to the browser.

A very similar process happens when requesting /market/item/1/purchase:

```<code>/market/item/1/purchase.php
/market/item/1/purchase.php.php
/market/item/1/purchase.php.php.php
/market/item/1/purchase.php.php.php.php
etc.
</code>```

In detail...

REQUEST_FILENAME is /market/item (ignoring the directory-prefix) and PATH_INFO is /1 (important for later). /market/item is not a directory (1st condition), but /market/item.php is a file (2nd condition) - so both conditions are successfully met.

The RewriteRule directive then rewrites /market/item/1 to /market/item/1.php (clearly incorrect and not the intention). Since there is no L flag on this rule, processing continues... for the sake of the remaining rules, the PATH_INFO (from the initial request, /1) is appended to the resulting URL to become /market/item/1.php/1 (the DPI flag - discard path info - was created to prevent this specific behaviour).

/market/item/1.php/1 does not match any further rules in the current pass, so the rewrite engine starts over at the top with /market/item/1.php.

REQUEST_FILENAME is again /market/item and PATH_INFO is now /1.php. /market/item is not a directory (1st condition), but /market/item.php is a file (2nd condition) - so both conditions are successfully met a second time.

The RewriteRule directive then rewrites /market/item/1.php to /market/item/1.php.php. Since there is no L flag on this rule, processing continues... for the sake of the remaining rules, the PATH_INFO (from the request, /1.php this time) is appended to the resulting URL to become /market/item/1.php.php/1.php.

/market/item/1.php.php/1.php does not match any further rules in the current pass, so the rewrite engine starts over at the top with /market/item/1.php.php.

GOTO #4 (with updated URL-path) etc. etc. etc. rewrite loop, 500 error.

And a very similar process happens when requesting /market/item/1/purchase. The REQUEST_FILENAME is the same /market/item (so it again checks that /market/item.php exists, not purchase.php), except that the PATH_INFO is /1/purchase (not /1). And the initial URL-path that the .php extension is appended to is naturaly /market/item/1/purchase (not /market/item/1).

Fix

If you've followed that "confusing muddle", you'll see that the condition that checks for the existence of the "path/to/file" + ".php" is not necessarily the same as the rule that actually rewrites the request to "URL-path" + ".php". ("path/to/file" is not the same as the "URL-path"). To fix this, it should be written as:

```<code>RewriteCond %{DOCUMENT_ROOT}/$1.php -f
RewriteRule (.*) $1.php [L]
</code>```

No real need for the directory check here, since if it was a directory, the file check that follows must fail (unless you have directory names that end in .php). The %{DOCUMENT_ROOT}/$1.php check is now effectively "the same" as $1.php (the file being rewritten to).

The literal dot does not need to be backslash escaped in the RewriteCond TestString - this is an "ordinary" string, not a regex.

Don't forget the L flag(s). And this rule block should now go at the end of the .htaccess file.

Summary

```<code>Options -Indexes
RewriteEngine on

ErrorDocument 500 "500"
ErrorDocument 404 "404"
ErrorDocument 403 "403"

RewriteRule ^users/([^/]*)$ /user/profile.php?username=$1 [L]
RewriteRule ^users/([^/]*)/inventory$ /user/GetUserInventory.php?username=$1 [L]

RewriteRule ^market/item/([^/]*)$ /market/item.php?id=$1 [L]
RewriteRule ^market/item/([^/]*)/purchase$ /market/purchase.php?id=$1 [L]

RewriteRule ^community/([^/]*)$ /communities/view.php?id=$1 [L]
RewriteRule ^community/([^/]*)/join$ /communities/join.php?id=$1 [L]
RewriteRule ^community/([^/]*)/manage$ /communities/manage.php?id=$1 [L]

RewriteRule ^game/([^/]*)$ /games/view.php?id=$1 [L]

# Append .php on remaining requests
RewriteCond %{DOCUMENT_ROOT}/$1.php -f
RewriteRule (.*) $1.php [L]
</code>```

Body:
I keep getting a 500 internal server error when trying to rewrite these one specific URLs/files (item.php & purchase.php), the rest works.

I have tried many ways to fix this but nothing seemed to work, which is weird because all other URLs do work, but these 2 just seem to not want to work for some reason.

.htaccess file

Options -Indexes
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php

ErrorDocument 500 "500"
ErrorDocument 404 "404"
ErrorDocument 403 "403"

RewriteRule ^users/([^/]*)$ /user/profile.php?username=$1
RewriteRule ^users/([^/]*)/inventory$ /user/GetUserInventory.php?username=$1

RewriteRule ^market/item/([^/]*)$ /market/item.php?id=$1
RewriteRule ^market/item/([^/]*)/purchase$ /market/purchase.php?id=$1

RewriteRule ^community/([^/]*)$ /communities/view.php?id=$1
RewriteRule ^community/([^/]*)/join$ /communities/join.php?id=$1
RewriteRule ^community/([^/]*)/manage$ /communities/manage.php?id=$1

RewriteRule ^game/([^/]*)$ /games/view.php?id=$1

item.php

<?php
    include_once('../private/header.php');
    $item = $handler->query("SELECT * FROM items WHERE id=" . $_GET['id']);
    $gB = $item->fetch(PDO::FETCH_OBJ);

    echo '

    image.'.png" class="responsive-img">

'.$gB->name.'
    '.$gB->type.'

'.$gB->description.'

    ';

    if ($gB->onsale == 1){
        echo 'id.'/purchase" class="modal-trigger waves-effect waves-light btn green">Purchase';
    } else {
        echo 'Offsale';
    }

    echo '

    Creator
    creator.'" style="padding-top:12px;font-size:16px;display:inline-block;">'.$gB->creator.'
    ';

    if($gB->collectable == 'true'){
        if($gB->amount == 0)
            echo '
            Sold Out
            ';
        }else{
            echo '
            '.$gB->amount.' Remaining
            ';
    }

    echo '

'.$gB->created.'

Time Created

'.$gB->created.'

Last Updated

???

Owners

    ';

    include_once('../private/footer.php');

purchase.php

<?php
    include_once('../private/config.php');

    if ($user){
        $money=$myu->CurrencyCoins;
        $id=$_GET['id'];
        $item = $handler->query("SELECT * FROM items WHERE id=" . $id);
        $gB = $item->fetch(PDO::FETCH_OBJ);
        $amount=$gB->amount;

        if ($gB->onsale == 1){
            if ($money >= $gB->price){
                if ($gB->collectable != "true"){
                    if ($amount != 0){
                        $new = ($money - $gB->price);
                        $handler->query("UPDATE `users` SET `CurrencyCoins`='".$new."' WHERE `id`='".$myu->id."'");
                        $handler->query("INSERT INTO inventory (item,user) VALUES (".$id.",".$myu->id.")");
                    }
            } else {
                if ($amount >= 1){
                    $amount1=($amount - 1);
                    $new = ($money - $gB->price);
                    $handler->query("UPDATE `users` SET `CurrencyCoins`='".$new."' WHERE `id`='".$myu->id."'");
                    $handler->query("UPDATE `items` SET `amount`='".$amount1."' WHERE `id`='".$gB->id."'");
                    $handler->query("INSERT INTO inventory (item,user) VALUES (".$id.",".$myu->id.")");
                } else {
                    echo '
Item is sold out!
';
                }
                }
            }
        } else {
        echo '
Item not on sale!
';
        }
    }

    echo '<meta http-equiv="refresh" content="1; url='.$serverUrl.'/account/character">';

Body:
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php

These directives should be at the end of your .htaccess file, after the other rewrites. They are also incorrect - although by placing them at the end of the file it will avoid the immediate issue, but could still cause problems with other URLs.

In its current state, when you request example.com/market/item/1 (where it would seem, /market is a physical directory, and /item.php is a file in that directory) then...

In brief... it results in an endless rewrite loop:

/market/item/1.php
/market/item/1.php.php
/market/item/1.php.php.php
/market/item/1.php.php.php.php
etc.

Which breaks (after 10 iterations) with a 500 response being sent to the browser.

A very similar process happens when requesting /market/item/1/purchase:

/market/item/1/purchase.php
/market/item/1/purchase.php.php
/market/item/1/purchase.php.php.php
/market/item/1/purchase.php.php.php.php
etc.

In detail...

REQUEST_FILENAME is /market/item (ignoring the directory-prefix) and PATH_INFO is /1 (important for later). /market/item is not a directory (1st condition), but /market/item.php is a file (2nd condition) - so both conditions are successfully met.

The RewriteRule directive then rewrites /market/item/1 to /market/item/1.php (clearly incorrect and not the intention). Since there is no L flag on this rule, processing continues... for the sake of the remaining rules, the PATH_INFO (from the initial request, /1) is appended to the resulting URL to become /market/item/1.php/1 (the DPI flag - discard path info - was created to prevent this specific behaviour).

/market/item/1.php/1 does not match any further rules in the current pass, so the rewrite engine starts over at the top with /market/item/1.php.

REQUEST_FILENAME is again /market/item and PATH_INFO is now /1.php. /market/item is not a directory (1st condition), but /market/item.php is a file (2nd condition) - so both conditions are successfully met a second time.

The RewriteRule directive then rewrites /market/item/1.php to /market/item/1.php.php. Since there is no L flag on this rule, processing continues... for the sake of the remaining rules, the PATH_INFO (from the request, /1.php this time) is appended to the resulting URL to become /market/item/1.php.php/1.php.

/market/item/1.php.php/1.php does not match any further rules in the current pass, so the rewrite engine starts over at the top with /market/item/1.php.php.

GOTO #4 (with updated URL-path) etc. etc. etc. rewrite loop, 500 error.

And a very similar process happens when requesting /market/item/1/purchase. The REQUEST_FILENAME is the same /market/item (so it again checks that /market/item.php exists, not purchase.php), except that the PATH_INFO is /1/purchase (not /1). And the initial URL-path that the .php extension is appended to is naturaly /market/item/1/purchase (not /market/item/1).

Fix

If you've followed that "confusing muddle", you'll see that the condition that checks for the existence of the "path/to/file" + ".php" is not necessarily the same as the rule that actually rewrites the request to "URL-path" + ".php". ("path/to/file" is not the same as the "URL-path"). To fix this, it should be written as:

RewriteCond %{DOCUMENT_ROOT}/$1.php -f
RewriteRule (.*) $1.php [L]

No real need for the directory check here, since if it was a directory, the file check that follows must fail (unless you have directory names that end in .php). The %{DOCUMENT_ROOT}/$1.php check is now effectively "the same" as $1.php (the file being rewritten to).

The literal dot does not need to be backslash escaped in the RewriteCond TestString - this is an "ordinary" string, not a regex.

Don't forget the L flag(s). And this rule block should now go at the end of the .htaccess file.

Summary

Options -Indexes
RewriteEngine on

ErrorDocument 500 "500"
ErrorDocument 404 "404"
ErrorDocument 403 "403"

RewriteRule ^users/([^/]*)$ /user/profile.php?username=$1 [L]
RewriteRule ^users/([^/]*)/inventory$ /user/GetUserInventory.php?username=$1 [L]

RewriteRule ^market/item/([^/]*)$ /market/item.php?id=$1 [L]
RewriteRule ^market/item/([^/]*)/purchase$ /market/purchase.php?id=$1 [L]

RewriteRule ^community/([^/]*)$ /communities/view.php?id=$1 [L]
RewriteRule ^community/([^/]*)/join$ /communities/join.php?id=$1 [L]
RewriteRule ^community/([^/]*)/manage$ /communities/manage.php?id=$1 [L]

RewriteRule ^game/([^/]*)$ /games/view.php?id=$1 [L]

# Append .php on remaining requests
RewriteCond %{DOCUMENT_ROOT}/$1.php -f
RewriteRule (.*) $1.php [L]


问:
Unrecognized selector sent to instance for Bar Button
I'm making a Twitter app on Xcode and have encountered a frustrating error.

I'm tryna make the Tweet bar button present modally.

When I run the code it crashes if I click "Tweet"
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[Twitter.TweetViewController _finishDecodingLayoutGuideConnections:]: unrecognized selector sent to instance 0x7fb1a25512c0'
*** First throw call stack:
libc++abi.dylib: terminating with uncaught exception of type NSException

```<code>import UIKit

class TweetViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

    @IBOutlet weak var tweetTextView: UITextView!

    @IBAction func cancel(_ sender: Any) {
        dismiss(animated: true, completion: nil)
    }

    @IBAction func Tweet(_ sender: Any) {
        if (!tweetTextView.text.isEmpty) {
            TwitterAPICaller.client?.postTweet(tweetString: tweetTextView.text, success:{ self.dismiss(animated: true, completion: nil)
            }, failure: { (error) in
                print("Error posting tweet \(error)")
                self.dismiss(animated: true, completion: nil)
                })
            } else {
            self.dismiss(animated: true, completion: nil)

        }
    }
</code>```

I looked up people with similar issues but could not find an solution that helped.

答:
Verify the IBOutlets and IBActions are properly connected. These crash happens when the XIB and Class files are not properly connected.

Try to remove the connections and add it again. Also rename the property names if the error persist.

Body:
I'm making a Twitter app on Xcode and have encountered a frustrating error.

I'm tryna make the Tweet bar button present modally.

When I run the code it crashes if I click "Tweet"
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[Twitter.TweetViewController _finishDecodingLayoutGuideConnections:]: unrecognized selector sent to instance 0x7fb1a25512c0'
*** First throw call stack:
libc++abi.dylib: terminating with uncaught exception of type NSException

import UIKit

class TweetViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

    @IBOutlet weak var tweetTextView: UITextView!

    @IBAction func cancel(_ sender: Any) {
        dismiss(animated: true, completion: nil)
    }

    @IBAction func Tweet(_ sender: Any) {
        if (!tweetTextView.text.isEmpty) {
            TwitterAPICaller.client?.postTweet(tweetString: tweetTextView.text, success:{ self.dismiss(animated: true, completion: nil)
            }, failure: { (error) in
                print("Error posting tweet \(error)")
                self.dismiss(animated: true, completion: nil)
                })
            } else {
            self.dismiss(animated: true, completion: nil)

        }
    }

I looked up people with similar issues but could not find an solution that helped.