问:
Rename file using File.Move give IOException
I am writing a simple application that will rename JPEGs with the date/time they were taken before the current filename. This is so that I can combine all the photos that I took with those of my partner (different camera makes and filenames).

The following piece of code is where the failure occurs:

```<code>private void RenameFile(String oldFilename, String newFilename)
{
    if (File.Exists(oldFilename)
    {
        File.Move(oldFilename, newFilename);
    }
}
</code>```

Example values: oldFilename = "E:\001.jpg" | newFilename = "E:\2009-08-07 06h05 -- 001.jpg"

The exception I am getting is:

```<code>System.IO.IOException was unhandled
  Message=The process cannot access the file because it is being used by another process.
  Source=mscorlib
  StackTrace:
       at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
       at System.IO.__Error.WinIOError()
       at System.IO.File.Move(String sourceFileName, String destFileName)
       at RenamePhotos.Form1.btnRenamePhotos_Click(Object sender, EventArgs e) in C:\Users\Neil Deadman\Desktop\RenamePhotos\RenamePhotos\Form1.cs:line 107
       at System.Windows.Forms.Control.OnClick(EventArgs e)
       at System.Windows.Forms.Button.OnClick(EventArgs e)
       at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
       at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
       at System.Windows.Forms.Control.WndProc(Message& m)
       at System.Windows.Forms.ButtonBase.WndProc(Message& m)
       at System.Windows.Forms.Button.WndProc(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
       at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
       at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
       at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.Run(Form mainForm)
       at RenamePhotos.Program.Main() in C:\Users\Neil Deadman\Desktop\RenamePhotos\RenamePhotos\Program.cs:line 18
       at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
</code>```

If I use File.Copy instead then it works, but I have two files and can't delete the original and using File.Delete I get the same (or similar) exception.

During some tests, if I rename it to E:\a001.jpg then it seems to work?? The filename is valid as I can rename it using Windows Explorer. :S

Any ideas? The fact that some renames work seems to say it isn't a locking issue?

Cheers Neil

答: I got this error when I misinterpreted the File.Move documentation ("Moves a specified file to a new location, providing the option to specify a new file name") to mean that if you only specify the destination directory and not a new file name, it would work.  Of course it does not; you must specify not only a new directory but also the file name, even if it's the same as the source.  I have no idea why that mistake got turned into "being used by another process" though.</p>

Body:
I am writing a simple application that will rename JPEGs with the date/time they were taken before the current filename. This is so that I can combine all the photos that I took with those of my partner (different camera makes and filenames).

The following piece of code is where the failure occurs:

private void RenameFile(String oldFilename, String newFilename)
{
    if (File.Exists(oldFilename)
    {
        File.Move(oldFilename, newFilename);
    }
}

Example values: oldFilename = "E:\001.jpg" | newFilename = "E:\2009-08-07 06h05 -- 001.jpg"

The exception I am getting is:

System.IO.IOException was unhandled
  Message=The process cannot access the file because it is being used by another process.
  Source=mscorlib
  StackTrace:
       at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
       at System.IO.__Error.WinIOError()
       at System.IO.File.Move(String sourceFileName, String destFileName)
       at RenamePhotos.Form1.btnRenamePhotos_Click(Object sender, EventArgs e) in C:\Users\Neil Deadman\Desktop\RenamePhotos\RenamePhotos\Form1.cs:line 107
       at System.Windows.Forms.Control.OnClick(EventArgs e)
       at System.Windows.Forms.Button.OnClick(EventArgs e)
       at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
       at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
       at System.Windows.Forms.Control.WndProc(Message& m)
       at System.Windows.Forms.ButtonBase.WndProc(Message& m)
       at System.Windows.Forms.Button.WndProc(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
       at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
       at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
       at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.Run(Form mainForm)
       at RenamePhotos.Program.Main() in C:\Users\Neil Deadman\Desktop\RenamePhotos\RenamePhotos\Program.cs:line 18
       at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()

If I use File.Copy instead then it works, but I have two files and can't delete the original and using File.Delete I get the same (or similar) exception.

During some tests, if I rename it to E:\a001.jpg then it seems to work?? The filename is valid as I can rename it using Windows Explorer. :S

Any ideas? The fact that some renames work seems to say it isn't a locking issue?

Cheers Neil


来源: stackexchange

问:
Compare two times (without dates) using the Python time module
How could something this simple be this tricky?

I want to create two times.

Time1 is a date-unaware time of UTC 8:30pm (20:30).
Time2 is any other time (hour, minute, second) on the planet.

Hard as I've searched, the documentation and the stackoverflow examples all use the datetime module and include creating a date with the time. I just need to compare two times and, if needed, adjust Time2 to UTC.

答:
It turned out that @AdrienMatissart's comment was the clue needed to figure this simple issue out. The trick was to create a datetime object for today's date at 20:30 UTC. Then to create another datetime object for the current time. By localizing the current system time to UTC, daylight savings is accounted for and the datetime objects can be compared.</p>

```<code>import pytz, datetime
UTC_TZ = pytz.utc

# use combine() to create a specific datetime in today's future
end = datetime.datetime.combine(datetime.date.today(), datetime.time(20, 30, tzinfo=UTC_TZ) )

# get the current system datetime and localize to account for daylight savings
right_now = datetime.datetime.now(tz=UTC_TZ)

# then I compare
if end > right_now:
    # some action
</code>```

ContentLicense: CC BY-SA 3.0

Body:
It turned out that @AdrienMatissart's comment was the clue needed to figure this simple issue out. The trick was to create a datetime object for today's date at 20:30 UTC. Then to create another datetime object for the current time. By localizing the current system time to UTC, daylight savings is accounted for and the datetime objects can be compared.

import pytz, datetime
UTC_TZ = pytz.utc

# use combine() to create a specific datetime in today's future
end = datetime.datetime.combine(datetime.date.today(), datetime.time(20, 30, tzinfo=UTC_TZ) )

# get the current system datetime and localize to account for daylight savings
right_now = datetime.datetime.now(tz=UTC_TZ)

# then I compare
if end > right_now:
    # some action


问:
Recyclerview not call onCreateViewHolder
My RecyclerView does not call onCreateViewHolder, onBindViewHolder even MenuViewHolder constructor, therefore nothing appears in RecyclerView.
I put logs for debugging, and no log is shown.
What might be the problem?

My adapter:

public class MenuAdapter extends RecyclerView.Adapter<MenuAdapter.MenuViewHolder> {
private LayoutInflater inflater;
List<Menu> data = Collections.emptyList();

public MenuAdapter(Context context, List<Menu> data) {
    Log.i("DEBUG", "Constructor");
    inflater = LayoutInflater.from(context);
    Log.i("DEBUG MENU - CONSTRUCTOR", inflater.toString());
    this.data = data;
    for(Menu menu: this.data){
        Log.i("DEBUG MENU - CONSTRUCTOR", menu.menu);
    }
}

@Override
public MenuViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = inflater.inflate(R.layout.row_menu, parent, false);
    MenuViewHolder holder = new MenuViewHolder(view);
    return holder;
}

@Override
public void onBindViewHolder(MenuViewHolder holder, int position) {
    Log.i("DEBUG MENU", "onBindViewHolder");
    Menu current = data.get(position);
    holder.title.setText(current.menu);
}

@Override
public int getItemCount() {
    return 0;
}

class MenuViewHolder extends RecyclerView.ViewHolder {
    TextView title;
    ImageView icon;

    public MenuViewHolder(View itemView) {
        super(itemView);
        title = (TextView) itemView.findViewById(R.id.menuText);
    }
}
```

<p>My custom row XML:</p>

<pre class="lang-xml prettyprint-override"><code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="match_parent">

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/menuText"
    android:text="Dummy Text"
    android:layout_gravity="center_vertical"
    android:textColor="#222"/>
</code>```

and my Fragment:

public NavigationFragment() {
    // Required empty public constructor
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mUserLearnedDrawer = Boolean.valueOf(readFromPreferences(getActivity(), KEY_USER_LEARNED_DRAWER, "false"));
    if (savedInstanceState != null) {
        mFromSavedInstaceState = true;
    }
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment

    View view = inflater.inflate(R.layout.fragment_navigation, container, false);
    RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.drawer_list);
    MenuAdapter adapter = new MenuAdapter(getActivity(), getData());
    recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
    recyclerView.setAdapter(adapter);
    return view;
}
```

答:
In my case, my list size was 0 and it was not calling the onCreateViewHolder
method. I needed to display a message at center for the empty list as a placeholder so I did it like this and it worked like charm. Answer by @Konstantin Burov helped.</p>

```<code>  @Override
public int getItemCount() {
    if (contactList.size() == 0) {
        return 1;
    } else {
        return contactList.size();
    }
}
</code>```

Body:
My RecyclerView does not call onCreateViewHolder, onBindViewHolder even MenuViewHolder constructor, therefore nothing appears in RecyclerView.
I put logs for debugging, and no log is shown.
What might be the problem?

My adapter:

public class MenuAdapter extends RecyclerView.Adapter<MenuAdapter.MenuViewHolder> {
private LayoutInflater inflater;
List<Menu> data = Collections.emptyList();

public MenuAdapter(Context context, List<Menu> data) {
    Log.i("DEBUG", "Constructor");
    inflater = LayoutInflater.from(context);
    Log.i("DEBUG MENU - CONSTRUCTOR", inflater.toString());
    this.data = data;
    for(Menu menu: this.data){
        Log.i("DEBUG MENU - CONSTRUCTOR", menu.menu);
    }
}

@Override
public MenuViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = inflater.inflate(R.layout.row_menu, parent, false);
    MenuViewHolder holder = new MenuViewHolder(view);
    return holder;
}

@Override
public void onBindViewHolder(MenuViewHolder holder, int position) {
    Log.i("DEBUG MENU", "onBindViewHolder");
    Menu current = data.get(position);
    holder.title.setText(current.menu);
}

@Override
public int getItemCount() {
    return 0;
}

class MenuViewHolder extends RecyclerView.ViewHolder {
    TextView title;
    ImageView icon;

    public MenuViewHolder(View itemView) {
        super(itemView);
        title = (TextView) itemView.findViewById(R.id.menuText);
    }
}

My custom row XML:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="match_parent">

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/menuText"
    android:text="Dummy Text"
    android:layout_gravity="center_vertical"
    android:textColor="#222"/>

and my Fragment:

public NavigationFragment() {
    // Required empty public constructor
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mUserLearnedDrawer = Boolean.valueOf(readFromPreferences(getActivity(), KEY_USER_LEARNED_DRAWER, "false"));
    if (savedInstanceState != null) {
        mFromSavedInstaceState = true;
    }
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment

    View view = inflater.inflate(R.layout.fragment_navigation, container, false);
    RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.drawer_list);
    MenuAdapter adapter = new MenuAdapter(getActivity(), getData());
    recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
    recyclerView.setAdapter(adapter);
    return view;
}

Body:
In my case, my list size was 0 and it was not calling the onCreateViewHolder
method. I needed to display a message at center for the empty list as a placeholder so I did it like this and it worked like charm. Answer by @Konstantin Burov helped.

  @Override
public int getItemCount() {
    if (contactList.size() == 0) {
        return 1;
    } else {
        return contactList.size();
    }
}


问:
looking for a UTF-8 text editor
I am looking for a (simple) text editor that can handle text in different encodings in the same document.

I need to develop some sites with mixed Japanese and English text and the editors I have now (on an English Windows system) are unable to display the Japanese text.
Jedit files don't display the Japanese text I have inputted but when I look at the file in a browser it shows up correctly.
Gvim shows all Japanese text in the editor as question marks and also in the browser.
In Gvim inputting the kanji works (you input the pronounciation and then press space bar to get the kanji) but when you confirm the kanji you want it replaces that kanji with question marks. (1 question mark for every kanji).

Can someone recommend me a text editor to edit html and php files that is able to display utf-8 encoded text and also save as an utf-8 file ?

thank you.

After reading about emacs I installed it. see below.

Thanks everybody for the hints.
if you don't have a unicode font yet you have to find one online or buy one.
here are the instructions to install the font on a windows system http://support.microsoft.com/kb/314960

jEdit
I changed my font in Jedit to a UTF font and now the Japanese shows up normally.
inputting the Japanese is still problematic as you don't see what you are typing.
(to change your font to edit files go to Utilities -> Global Options -> text area
select a Unicode font and you'll be able to see the Japanese characters.

gVim
I am still trying to figure out how to add a font in gvim. Once I know how to do that I ll update this.

Emacs
Emacs does not show the kanji correctly, they are displayed as ??? but at least I can see what I type in Japanese and select the right word.

so at this point I have to say that in jEdit I can see Japanese text but I can't input Japanese text. Gvim I can input Japanese text but inside the text area it is displayed as ??? and the same goes for Emacs.
adding a font in emacs and gvim is sadly enough not a trivial task.
At the moment I use notepad with the Arial unicode MS font and saving as UTF-8 file as my Japanese editor. Not ideal but at least it works.

答:
I've never had a problem with vim as long as I use a font that actually contains the characters I want. It needs to be a monospace font. :set enc=utf8 to get to utf8 mode. Then you can use :digraph command to get a display of available characters, and see how each is displayed.

To add a font, add it in Windows (Control Panel/Fonts/Add Font). If it's a monospace font, it will then show up in vin in /Edit/Font.

ContentLicense: CC BY-SA 2.5

Title: looking for a UTF-8 text editor

OwnerDisplayName: le dorfier


问:
NopCommerce and DotNetNuke
I have both nopCommerce and DotNetNuke installed on my server. All I need is to be able to share the users between both apps.

can you tell me the easiest solution to make a bridge between them.

Thanks

答:
As an alternative, you should take a look at:
http://www.sysdatanet.com/nopCommerce/DotNetNuke_nopCommerce.aspx

I haven't used it but it seems like it might be a good approach.

Title: NopCommerce and DotNetNuke


问:
Printing index of duplicate numbers in array javascript
I need to find the first duplicate number in array and then print index of this number in console. In my code below I reach the moment when code finds the duplicate but prints its index. In simple words, 2 is duplictaing in array but it's stands in first place so I need to print index "0".

var sameNum = [2, 4, 5, 2, 3, 5, 1, 2, 4];
var firstIndex = [];

for (var i = 0; i < sameNum.length; i++) {
  for (var j = i; j < sameNum.length; j++) {
    if (i != j && sameNum[i] == sameNum[j]) {
      firstIndex = [i];
    }
  }
}
console.log(firstIndex);```

答:
Nested loops, in this case, are a bad solution. It gives O(n^2) complexity, where we can solve linearly with a map.

We can use a map to track letters that showed up so far in a single loop:

var sameNum = [1, 2 ,3 ,4 ,5 ,6 ,6 ,7 ,8 ,9];
var lettersMap = {};
var firstIndex = -1;

for (var i = 0; i < sameNum.length; i++) {
  if (lettersMap[sameNum[i]]) {
    firstIndex = i;
    break;
  }
  else {
    lettersMap[sameNum[i]] = true;
  }
};

console.log(firstIndex);```


问:
React Native Expo make call, send SMS or Email
How can I make calls or send SMS and Email messages with React Native Expo framework?

I am contemplating between using Expo or not and one of the concerns - support of some third-party libs. Typically with react native you would use well written Communications library. Can I use it with Expo project or I should use something else?

答: The react-native-communications library would work just fine with Expo -- it is just JavaScript and depends on the "Linking" API. If you're curious about why this works, you can see some more information on how Linking works in Expo in the Linking guide. But go ahead and use react-native-communications if that covers your use case!</p>


问:
spread syntax in typescript
I'm trying to extend a class in an Angular project and I want to pass arguments to the parent class using the rest/spread syntax of ES2015 like the answer to this question

```<code>constructor(...args) {
    super(...args);
}
</code>```

but I get an error Supplied parameters do not match any signature of call target and my app won't compile.

I made a contrived example using the typescript playground. Does anyone know how to get this to work without having to explicitly write the arguments of the parent class methods?

UPDATE: As pointed out by Teddy Sterne I actually don't need to use this for the constructor because it has the same arguments. I actually want to use this for a method that returns an observable. I want to catch errors by overriding the method and returning super.parentMethod(...args).catch(/* deal with error */)

答:
This question was asked and answered in this issue: https://github.com/Microsoft/TypeScript/issues/11679

You are correct assuming it's because of type checking. Lets assume the parent constructor expects a fixed number of parameters. At the point super(...args) is declared, the compiler doesn't know the actual number of passed parameters. Therefore it flags it as unsafe.

Title: spread syntax in typescript

Body:
I'm trying to extend a class in an Angular project and I want to pass arguments to the parent class using the rest/spread syntax of ES2015 like the answer to this question

constructor(...args) {
    super(...args);
}

but I get an error Supplied parameters do not match any signature of call target and my app won't compile.

I made <a href="https://www.typescriptlang.org/play/#src=class%20Greeter%20%7B%0D%0A%20%20%20%20greeting%3A%20string%3B%0D%0A%20%20%20%20constructor(message%3A%20string)%20%7B%0D%0A%20%20%20%20%20%20%20%20this.greeting%20%3D%20message%3B%0D%0A%20%20%20%20%7D%0D%0A%20%20%20%20greet()%20%7B%0D%0A%20%20%20%20%20%20%20%20return%20%22Hello%2C%20%22%20%2B%20this.greeting%3B%0D%0A%20%20%20%20%7D%0D%0A%7D%0D%0A%0D%0Aclass%20PersonGreeter%20extends%20Greeter%20%7B%0D%0A%20%20%20%20constructor(...args)%20%7B%0D%0A%20%20%20%20%20%20%20%20super(...args)%3B%0D%0A%20%20%20%20%7D%0D%0A%7D%0D%0A%0D%0Alet%20greeter%20%3D%20new%20Greeter(%22world%22)%3B%0D%0A%0D%0Alet%20button%20%3D%20document.createElement('button')%3B%0D%0Abutton.textContent%20%3D%20%22Say%20Hello%22%3B%0D%0Abutton.onclick%20%3D%20function()%20%7B%0D%0A%20%20%20%20alert(greeter.greet())%3B%0D%0A%7D%0D%0A%0D%0Adocument.body.appendChild(button)%3B#src=class%20Greeter%20%7B%0D%0A%20%20%20%20greeting%3A%20string%3B%0D%0A%20%20%20%20constructor(message%3A%20string)%20%7B%0D%0A%20%20%20%20%20%20%20%20this.greeting%20%3D%20message%3B%0D%0A%20%20%20%20%7D%0D%0A%20%20%20%20greet()%20%7B%0D%0A%20%20%20%20%20%20%20%20return%20%22Hello%2C%20%22%20%2B%20this.greeting%3B%0D%0A%20%20%20%20%7D%0D%0A%7D%0D%0A%2F*%20This%20doesn't%20work%0D%0Aclass%20PersonGreeter%20extends%20Greeter%20%7B%0D%0A%20%20%20%20constructor(...args)%20%7B%0D%0A%20%20%20%20%20%20%20%20super(...args)%3B%0D%0A%20%20%20%20%7D%0D%0A%7D*%2F%0D%0A%0D%0Aclass%20PersonGreeter%20extends%20Greeter%20%7B%0D%0A%20%20%20%20constructor(name%3A%20string)%20%7B%0D%0A%20%20%20%20%20%20%20%20super(name)%3B%0D%0A%20%20%20%20%7D%0D%0A%7D%0D%0A%0D%0Alet%20greeter%20%3D%20new%20PersonGreeter(%22Mr.%20Smith%22)%3B%0D%0A%0D%0Alet%20button%20%3D%20document.createElement('button')%3B%0D%0Abutton.textContent%20%3D%20%22Say%20Hello%22%3B%0D%0Abutton.onclick%20%3D%20function()%20%7B%0D%0A%20%20%20%20alert(greeter.greet())%3B%0D%0A%7D%0D%0A%0D%0Adocument.body.appendChild(button)%3B#src=class%20Greeter%20%7B%0D%0A%20%20%20%20greeting%3A%20string%3B%0D%0A%20%20%20%20constructor(message%3A%20string)%20%7B%0D%0A%20%20%20%20%20%20%20%20this.greeting%20%3D%20message%3B%0D%0A%20%20%20%20%7D%0D%0A%20%20%20%20greet(salutation%3A%20string%20%3D%20'Hello')%20%7B%0D%0A%20%20%20%20%20%20%20%20return%20salutation%20%2B%20%22%2C%20%22%20%2B%20this.greeting%3B%0D%0A%20%20%20%20%7D%0D%0A%7D%0D%0A%0D%0A%2F%2F%20This%20doesn't%20work%0D%0Aclass%20PersonGreeter%20extends%20Greeter%20%7B%0D%0A%20%20%20%20constructor(...args)%20%7B%0D%0A%20%20%20%20%20%20%20%20super(...args)%3B%0D%0A%20%20%20%20%7D%0D%0A%20%20%20%20greet(...args)%20%7B%0D%0A%20%20%20%20%20%20%20%20return%20super.greet(...args)%3B%0D%0A%20%20%20%20%7D%0D%0A%7D%0D%0A%0D%0Alet%20greeter%20%3D%20new%20PersonGreeter(%22Mr.%20Smith%22)%3B%0D%0A%0D%0Alet%20button%20%3D%20document.createElement('button')%3B%0D%0Abutton.textContent%20%3D%20%22Say%20Hello%22%3B%0D%0Abutton.onclick%20%3D%20function()%20%7B%0D%0A%20%20%20%20alert(greeter.greet())%3B%0D%0A%7D%0D%0A%0D%0Adocument.body.appendChild(button)%3B" rel="nofollow noreferrer">a contrived example using the typescript playground. Does anyone know how to get this to work without having to explicitly write the arguments of the parent class methods?

UPDATE: As pointed out by Teddy Sterne I actually don't need to use this for the constructor because it has the same arguments. I actually want to use this for a method that returns an observable. I want to catch errors by overriding the method and returning super.parentMethod(...args).catch(/* deal with error */)


问:
Error about left-recursive in ANTLR . Need to do what now?
```<code>//Expression

exp: exp1 ASS_OP exp | exp1;

exp1: exp1 OR_OP exp2 | exp2;

exp2: exp2 AND_OP exp3 | exp3;

exp3: exp4 (EQUAL_OP | NOT_EQUAL_OP) exp4 | exp4;

exp4: exp5 (LESS_OP|GREATER_OP|LESS_EQUAL_OP|GREATER_EQUAL_OP) exp5 | exp5;

exp5: exp5 (ADD_OP | SUB_OP) exp6 | exp6;

exp6: exp6 (MUL_OP | DIV_OP | MOD_OP) exp7 | exp7;

exp7: (ADD_OP | SUB_OP | NOT_OP) exp7 | exp8;

exp8: LB exp RB | expl;

expl: invocation_exp | index_exp | ID | INTLIT |FLOATLIT | BOOLEANLIT | STRINGLIT;

index_exp: exp LSB exp RSB;

invocation_exp: ID LB (exp (COMMA exp)*)? RB;
</code>```

[error] error(119): MC.g4::: The following sets of rules are mutually left-recursive [exp, index_exp, exp1, exp2, exp3, exp4, exp5, exp6, exp7, exp8, expl]

[trace] Stack trace suppressed: run last *:Antlr generates lexer and parser for the full output.

Hi, I'm new. I read some topics so that ANTLR4 supports only direct left-recursion. And authors seem don't want to change that. So anyone can help me fix my code? Thank for reading this.

答:
One of the great things about ANTLR4 as opposed to some of the older tools is that you don't often have to "chain" your operator precedence like this:

```<code>exp: exp1 ASS_OP exp | exp1;
exp1: exp1 OR_OP exp2 | exp2;
exp2: exp2 AND_OP exp3 | exp3;
</code>```

I remember those days of chaining expression rules for strict BNF grammars.  But in ANTLR4, we can do better and have a clearer grammar too.  Since the rules are evaluated top to bottom, the highest-predecence rules are listed first like in this snippet:

```<code>expr
 : expr POW<assoc=right> expr           #powExpr
 | MINUS expr                           #unaryMinusExpr
 | NOT expr                             #notExpr
 | expr op=(MULT | DIV | MOD) expr      #multiplicationExpr
 | expr op=(PLUS | MINUS) expr          #additiveExpr
 | expr op=(LTEQ | GTEQ | LT | GT) expr #relationalExpr
 | expr op=(EQ | NEQ) expr              #equalityExpr
 | expr AND expr                        #andExpr
 | expr OR expr                         #orExpr
 | atom                                 #atomExpr
</code>```

This might solve your operator precedence issues without wrangling with mutual left recursion.  Highest precedence at top, with power (exponentiation) in this example (and by mathematical convention) having the highest binding in an expression.

Body:
//Expression

exp: exp1 ASS_OP exp | exp1;

exp1: exp1 OR_OP exp2 | exp2;

exp2: exp2 AND_OP exp3 | exp3;

exp3: exp4 (EQUAL_OP | NOT_EQUAL_OP) exp4 | exp4;

exp4: exp5 (LESS_OP|GREATER_OP|LESS_EQUAL_OP|GREATER_EQUAL_OP) exp5 | exp5;

exp5: exp5 (ADD_OP | SUB_OP) exp6 | exp6;

exp6: exp6 (MUL_OP | DIV_OP | MOD_OP) exp7 | exp7;

exp7: (ADD_OP | SUB_OP | NOT_OP) exp7 | exp8;

exp8: LB exp RB | expl;

expl: invocation_exp | index_exp | ID | INTLIT |FLOATLIT | BOOLEANLIT | STRINGLIT;

index_exp: exp LSB exp RSB;

invocation_exp: ID LB (exp (COMMA exp)*)? RB;

[error] error(119): MC.g4::: The following sets of rules are mutually left-recursive [exp, index_exp, exp1, exp2, exp3, exp4, exp5, exp6, exp7, exp8, expl]

[trace] Stack trace suppressed: run last *:Antlr generates lexer and parser for the full output.

Hi, I'm new. I read some topics so that ANTLR4 supports only direct left-recursion. And authors seem don't want to change that. So anyone can help me fix my code? Thank for reading this.

Body:
One of the great things about ANTLR4 as opposed to some of the older tools is that you don't often have to "chain" your operator precedence like this:

exp: exp1 ASS_OP exp | exp1;
exp1: exp1 OR_OP exp2 | exp2;
exp2: exp2 AND_OP exp3 | exp3;

I remember those days of chaining expression rules for strict BNF grammars.  But in ANTLR4, we can do better and have a clearer grammar too.  Since the rules are evaluated top to bottom, the highest-predecence rules are listed first like in this snippet:

expr
 : expr POW<assoc=right> expr           #powExpr
 | MINUS expr                           #unaryMinusExpr
 | NOT expr                             #notExpr
 | expr op=(MULT | DIV | MOD) expr      #multiplicationExpr
 | expr op=(PLUS | MINUS) expr          #additiveExpr
 | expr op=(LTEQ | GTEQ | LT | GT) expr #relationalExpr
 | expr op=(EQ | NEQ) expr              #equalityExpr
 | expr AND expr                        #andExpr
 | expr OR expr                         #orExpr
 | atom                                 #atomExpr

This might solve your operator precedence issues without wrangling with mutual left recursion.  Highest precedence at top, with power (exponentiation) in this example (and by mathematical convention) having the highest binding in an expression.


问:
React-Redux API documentation symbols
I'm reading the react-redux documentation and I found this:

[mapStateToProps(state, [ownProps]): stateProps] (Function)

I don't understand exactly what "[ ]" means, or what is the ":" symbol used for in this context.
I remember that jQuery also uses this for it's API documentation. Example:

.slideToggle([duration][,complete])

Is there any convention for writing/reading these?

答: "[]" means not nesessary, but can be used.</p>

Title: React-Redux API documentation symbols


问:
How to get id or name of iframe using javascript?
I have one iframe:

```<code><iframe id="frame" name="frame" src="test.html"></iframe>
</code>```

Now, I want to get id or name that iframe and alert it, I used:

```<code>if (document.getelementbyid('frame') = frame) alert('OK');
</code>```

But it doesn't work.

答:
if you want to check iframe has existed and then id and name attribute try this</p>

```<code>el = document.getElementById('frame')
if (el != null) {
    alert('id :' + el.id)
    if (el.name!=""){
        alert('name: ' + el.name)
    }
    else{
        alert('frame do not have name attribute')
    }
}else{
    alert('frame do not exist')
}
</code>```

Body:
I have one iframe:

Now, I want to get id or name that iframe and alert it, I used:

if (document.getelementbyid('frame') = frame) alert('OK');

But it doesn't work.

Body:
if you want to check iframe has existed and then id and name attribute try this

el = document.getElementById('frame')
if (el != null) {
    alert('id :' + el.id)
    if (el.name!=""){
        alert('name: ' + el.name)
    }
    else{
        alert('frame do not have name attribute')
    }
}else{
    alert('frame do not exist')
}


问:
SSIS prevent delete after insert if insert fails
I have a requirement to use SSIS to pull data from somewhere, put it in a SQL database table, then delete the source data. I have seen this answer SSIS : delete rows after an update or insert and option #3 (add a multicast to split the 2 operations) looks good but I have a concern...

What happens if the insert to the destination fails? Will my records still be deleted? I want to make sure I don't lose any data by accident due to a failed insert - is there a better way?

I'm using SQL Server 2012 to execute the SSIS package.

Thanks

答: If you use a multicast, then yes, the delete will happen even if the insert fails.   If you want to make the delete dependent on the insert, you would need to do them in separate consecutive tasks with a precedence constraint between them.</p>


问:
Angular 4 Routes meaning of plus and sharp symbol in augular starter?
Repo is https://github.com/AngularClass/angular-starter

I saw all these + and # for referencing inside loadChildren as well as naming inside the folder...

Went to angular reference https://angular.io/api/router/LoadChildren saw NOTHING about these sort of convention.

答:
The hash (#) is part of the loadChildren syntax. It separates the path to the lazy loaded module from the class name of the lazy loaded module. Here is an example:

```<code>@NgModule({
    imports: [
        RouterModule.forRoot([
            { path: 'welcome', component: WelcomeComponent },
            {
                path: 'products',
                canActivate: [ AuthGuard ],
                data: { preload: true },
                loadChildren: 'app/products/product.module#ProductModule'
            },
            { path: '', redirectTo: 'welcome', pathMatch: 'full' },
            { path: '**', component: PageNotFoundComponent }
        ]
    ],
    exports: [ RouterModule ]
})
export class AppRoutingModule { }
</code>```

The + may just be a symbol used in the folder name. I have not seen that usage before but it may mean something to that particular team.

Body:
The hash (#) is part of the loadChildren syntax. It separates the path to the lazy loaded module from the class name of the lazy loaded module. Here is an example:

@NgModule({
    imports: [
        RouterModule.forRoot([
            { path: 'welcome', component: WelcomeComponent },
            {
                path: 'products',
                canActivate: [ AuthGuard ],
                data: { preload: true },
                loadChildren: 'app/products/product.module#ProductModule'
            },
            { path: '', redirectTo: 'welcome', pathMatch: 'full' },
            { path: '**', component: PageNotFoundComponent }
        ]
    ],
    exports: [ RouterModule ]
})
export class AppRoutingModule { }

The + may just be a symbol used in the folder name. I have not seen that usage before but it may mean something to that particular team.


问:
ASP.net "{Controller}/" returning 403.14 error
I am having a curious issue with one of my projects in development. The issue is with links to a certain URL "//localhost:62168/Images/Index". I have buttons linking to that URL but when "//localhost:62168/Images/" is accessed it returns a HTTP Error 403.14 - Forbidden error. See the below Image:

localhost//Images/

Oddly enough though, when I enter the URL exactly ("localhost:62168/Images/Index") it loads the page properly. See the below Image:

localhost/Images/Index

I've done plenty of research online and I believe it may be an issue with routing so below I've added the code of my "RouteConfig.cs" file. Unfortunately, I am new to ASP.net and MVC and not knowledgeable on proper Routing procedures:

```<code>using System.Web.Mvc;
using System.Web.Routing;

namespace ReedHampton
{
    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
        }
    }
}
</code>```

I've also tried multiple other "solutions" presented in other online forums to no avail. These include:

Adding "directoryBrowse enabled="true" " to web.config

Running "C:\windows\Microsoft.NET\Framework64\v4.0.30319> aspnet_regiis.exe -i" in Command Prompt

Going through IIS Express and registering IIS Express and ASP.Net

I would greatly appreciate any help that anyone can provide!

答:
IIS will attempt to short-circuit the request if it finds something on the filesystem that matches the URL. In other words, I'd assume you have an Images directory in your document root. Therefore, IIS will attempt to hit this directory, rather than pass the request on to the ASP.NET machinery. Since you've disabled directory browsing, you get a 403.

Long and short, you need to keep your ASP.NET MVC routes unique from what you have physically in your document root. You could change the name of the Images directory to something like img, or put it in a parent folder like the default of /Content/Images. Otherwise, you'll need to change your controller name or create a custom route to that controller not called /Images.

Body:
I am having a curious issue with one of my projects in development. The issue is with links to a certain URL "//localhost:62168/Images/Index". I have buttons linking to that URL but when "//localhost:62168/Images/" is accessed it returns a HTTP Error 403.14 - Forbidden error. See the below Image:

localhost//Images/

Oddly enough though, when I enter the URL exactly ("localhost:62168/Images/Index") it loads the page properly. See the below Image:

localhost/Images/Index

I've done plenty of research online and I believe it may be an issue with routing so below I've added the code of my "RouteConfig.cs" file. Unfortunately, I am new to ASP.net and MVC and not knowledgeable on proper Routing procedures:

using System.Web.Mvc;
using System.Web.Routing;

namespace ReedHampton
{
    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
        }
    }
}

I've also tried multiple other "solutions" presented in other online forums to no avail. These include:

Adding "directoryBrowse enabled="true" " to web.config

Running "C:\windows\Microsoft.NET\Framework64\v4.0.30319> aspnet_regiis.exe -i" in Command Prompt

Going through IIS Express and registering IIS Express and ASP.Net

I would greatly appreciate any help that anyone can provide!


答:
You can use the "j" to get the index of duplicate values, like this

var sameNum = [1, 3, 2 ,3 ,4 ,5 ,6 ,6 ,7 ,8 ,9];
var firstIndex = [];

for(var i = 0; i < sameNum.length; i++) {
  for(var j = i; j < sameNum.length; j++) {
    if(i != j && sameNum[i] == sameNum[j]) {
      console.log("--------"+sameNum[i]+"--------");
      console.log("Index: "+ j);
    }
  }
}```

Title: Printing index of duplicate numbers in array javascript

Body:
I need to find the first duplicate number in array and then print index of this number in console. In my code below I reach the moment when code finds the duplicate but prints its index. In simple words, 2 is duplictaing in array but it's stands in first place so I need to print index "0".

var sameNum = [2, 4, 5, 2, 3, 5, 1, 2, 4];
var firstIndex = [];

for (var i = 0; i < sameNum.length; i++) {
  for (var j = i; j < sameNum.length; j++) {
    if (i != j && sameNum[i] == sameNum[j]) {
      firstIndex = [i];
    }
  }
}
console.log(firstIndex);


问:
How to make mouseenter function loop
I would like to make a function where if the user hovers his cursor over an image, the image changes and cycles through a bunch of images I've designated. I've achieved this previously, but instead of on  hover, I used on click which is fairly easier.

In short how do I make the images cycle on mouseenter?

My code:

```<code>var n = 0;

var images = ["3.jpeg","4.jpeg","6.jpeg","7.jpeg","8.jpeg","10.jpeg","12.jpeg","13.jpeg","14.jpeg","15.jpeg","16.jpeg"];

var image = $('#himg');

image.on('mouseenter', function change() {

    var newN = n+1;

    if (newN >= images.length) { newN = 0 };

    image.attr('src', images[n]);

    image.fadeOut(200, function () {
        image.attr('src', images[newN]);
        image.fadeIn();
        n = newN;
    });
});
</code>```

答:
mouseenter only fires once, when the mouse moves into the range of the dom element. When the mouse finally leaves, a mouseleave event is fired. You can use this to start an interval to cycle through your images.

```<code>var n = 0;

var images = ["3.jpeg","4.jpeg","6.jpeg","7.jpeg","8.jpeg","10.jpeg","12.jpeg","13.jpeg","14.jpeg","15.jpeg","16.jpeg"];

var image = $('#himg');

var intervalId;
var intervalTimeout = 200;

image.on('mouseenter', function change() {
    intervalId = setInterval(function() {
      var newN = n+1;

      if (newN >= images.length) { newN = 0 };

      image.attr('src', images[n]);

      image.fadeOut(200, function () {
          image.attr('src', images[newN]);
          image.fadeIn();
          n = newN;
      });
    }, intervalTimeout);
});

image.on('mouseleave', function() {
  clearInterval(intervalId);
});
</code>```

Title: How to make mouseenter function loop

Body:
I would like to make a function where if the user hovers his cursor over an image, the image changes and cycles through a bunch of images I've designated. I've achieved this previously, but instead of on  hover, I used on click which is fairly easier.

In short how do I make the images cycle on mouseenter?

My code:

var n = 0;

var images = ["3.jpeg","4.jpeg","6.jpeg","7.jpeg","8.jpeg","10.jpeg","12.jpeg","13.jpeg","14.jpeg","15.jpeg","16.jpeg"];

var image = $('#himg');

image.on('mouseenter', function change() {

    var newN = n+1;

    if (newN >= images.length) { newN = 0 };

    image.attr('src', images[n]);

    image.fadeOut(200, function () {
        image.attr('src', images[newN]);
        image.fadeIn();
        n = newN;
    });
});

Body:
mouseenter only fires once, when the mouse moves into the range of the dom element. When the mouse finally leaves, a mouseleave event is fired. You can use this to start an interval to cycle through your images.

var n = 0;

var images = ["3.jpeg","4.jpeg","6.jpeg","7.jpeg","8.jpeg","10.jpeg","12.jpeg","13.jpeg","14.jpeg","15.jpeg","16.jpeg"];

var image = $('#himg');

var intervalId;
var intervalTimeout = 200;

image.on('mouseenter', function change() {
    intervalId = setInterval(function() {
      var newN = n+1;

      if (newN >= images.length) { newN = 0 };

      image.attr('src', images[n]);

      image.fadeOut(200, function () {
          image.attr('src', images[newN]);
          image.fadeIn();
          n = newN;
      });
    }, intervalTimeout);
});

image.on('mouseleave', function() {
  clearInterval(intervalId);
});


问:
Microsoft One Drive solution for Files and Folders - Around 300 Systems
I need Files and Folders backup of 300 Windows 8+ System. I opted One Drive Solution. So do i need to buy 300 License of One Drive for Business or Can i buy 1 license and can create and share 300 folders for each person?

In any of the option, the user can upload data to their space but admin can see all the folders.

答:
Firstly, at an enterprise level, we should not consider onedrive as cloud storage as it is a kind of online file sync service.
So, you should go for a backup software to manage your 300+ system's backup and restorations.
The main point of backing up is to preserve data the backup solution has to be bullet-proof. Thus, a backup solution has to be able to encrypt backups and securely transfer data over the network.
Veeam, Microsoft DPM and other EMC products can be an option but it totally depends upon the backup requirements.
you need software which can backup your data to any preferred storage like NAS and Cloud. You can try Cloudberry Backup Software as it provides "Cloud to Cloud", "Cloud to Local" and "Local to Cloud"</p>


答:
You need to pay attention on uppercase letters. This should be

```<code>document.getElementById('frame')
</code>```

Also in if You are using one equal sign which is assignment operator. Comparing operator You should use are two equal signs, so whole if should looks like this

```<code>if (document.getElementById('frame') == frame) alert('OK');
</code>```

But answering the question: every HTMLElement object (which You can get from methods like that getElementById) has properties like id and name which is what You want.

So You can assign gotten iframe and then use variable to get id and name:

```<code>let iframe = document.getElementsByTagName("iframe")[0];
console.log(iframe.id, iframe.name);
</code>```

getElementsByTagName returns all elements with passed tag as array so if You have only one iframe on site, You can get first element from returned array in the same var declaration.

Title: How to get id or name of iframe using javascript?

Body:
You need to pay attention on uppercase letters. This should be

document.getElementById('frame')

Also in if You are using one equal sign which is assignment operator. Comparing operator You should use are two equal signs, so whole if should looks like this

if (document.getElementById('frame') == frame) alert('OK');

But answering the question: every HTMLElement object (which You can get from methods like that getElementById) has properties like id and name which is what You want.

So You can assign gotten iframe and then use variable to get id and name:

let iframe = document.getElementsByTagName("iframe")[0];
console.log(iframe.id, iframe.name);

getElementsByTagName returns all elements with passed tag as array so if You have only one iframe on site, You can get first element from returned array in the same var declaration.


问:
.htaccess redirect question mark with no parameters
I have several URLs with question marks that need to be removed.  For example, I need to redirect this URL:

```<code>http://example.net/?/services
</code>```

To this URL:

```<code>http://example.net/services
</code>```

I have many more like this, so I would like something that can catch everything with the question mark and properly redirect it.  Many of the answers I found were trying to use QUERY_STRING as the condition for the rewrite, but without parameters this does not help. After some digging I found a RewiteCond that works, but the RewriteRule redirects to the homepage, rather than the URL without the question mark. What I have currently is this:

```<code># Remove question mark from string
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /(index\.php)?\?([^&\ ]+)
RewriteRule ^ /%1? [L,R=301]

# Removes index.php from ExpressionEngine URLs
RewriteCond %{THE_REQUEST} ^GET.*index\.php [NC]
RewriteRule (.*?)index\.php/*(.*) /$1$2 [R=301,NE,L]

# Directs all EE web requests through the site index file
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php?/$1 [L]
</code>```

The first block is the rewrite that I have so far, and the next two are for the CMS url routing. What seems to be happening is that my rewrite in the first block is not keeping the rest of the url.  I have tried several combinations and can't seem to figure out how to keep the rest of the url intact.

答:
Many of the answers I found were trying to use QUERY_STRING as the condition for the rewrite, but without parameters this does not help.

Yes, this is exactly what the first URL, with a question mark, contains. So, I'm not sure why "this does not help"? In the URL http://example.net/?/services, /services is the query string. Whether there are key/value pairs (ie. "parameters") is irrelevant.

To redirect URLs of the form http://example.net/?/services, that consist of no URL-path and only a query string, try something like:

```<code># Remove question mark from string
RewriteCond %{QUERY_STRING} ^/(.+)
RewriteRule ^$ /%1? [R,L]
</code>```

%1 is a backreference to the captured group in the last matched CondPattern (ie. (.+), which captures services). This assumes that the query string (after the ?) always starts with a slash, as in your example. (Incidentally, this is also what your front controller is doing, in reverse, so I assume it must be correct.)

The trailing ? on the substitution removes the original query string from the request.

Make sure you clear your browser cache, as any earlier/erroneous 301s will have been cached by the browser.

If this is intended to be a permanent (301) redirect then change R to R=301, but only when you are sure it's working OK.

Body:
I have several URLs with question marks that need to be removed.  For example, I need to redirect this URL:

http://example.net/?/services

To this URL:

http://example.net/services

I have many more like this, so I would like something that can catch everything with the question mark and properly redirect it.  Many of the answers I found were trying to use QUERY_STRING as the condition for the rewrite, but without parameters this does not help. After some digging I found a RewiteCond that works, but the RewriteRule redirects to the homepage, rather than the URL without the question mark. What I have currently is this:

# Remove question mark from string
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /(index\.php)?\?([^&\ ]+)
RewriteRule ^ /%1? [L,R=301]

# Removes index.php from ExpressionEngine URLs
RewriteCond %{THE_REQUEST} ^GET.*index\.php [NC]
RewriteRule (.*?)index\.php/*(.*) /$1$2 [R=301,NE,L]

# Directs all EE web requests through the site index file
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php?/$1 [L]

The first block is the rewrite that I have so far, and the next two are for the CMS url routing. What seems to be happening is that my rewrite in the first block is not keeping the rest of the url.  I have tried several combinations and can't seem to figure out how to keep the rest of the url intact.

Body:
Many of the answers I found were trying to use QUERY_STRING as the condition for the rewrite, but without parameters this does not help.

Yes, this is exactly what the first URL, with a question mark, contains. So, I'm not sure why "this does not help"? In the URL http://example.net/?/services, /services is the query string. Whether there are key/value pairs (ie. "parameters") is irrelevant.

To redirect URLs of the form http://example.net/?/services, that consist of no URL-path and only a query string, try something like:

# Remove question mark from string
RewriteCond %{QUERY_STRING} ^/(.+)
RewriteRule ^$ /%1? [R,L]

%1 is a backreference to the captured group in the last matched CondPattern (ie. (.+), which captures services). This assumes that the query string (after the ?) always starts with a slash, as in your example. (Incidentally, this is also what your front controller is doing, in reverse, so I assume it must be correct.)

The trailing ? on the substitution removes the original query string from the request.

Make sure you clear your browser cache, as any earlier/erroneous 301s will have been cached by the browser.

If this is intended to be a permanent (301) redirect then change R to R=301, but only when you are sure it's working OK.


问:
Copy MAC terminal output to my clipboard without mouse but by using shortcut from keyboard
I have the following:

After typing (pwd),

how can I copy my terminal output (/sdcard/Android/data) using my keyboard and not another command or my mouse?

NOTE: I looked online but I only found ways on how to copy the last output using another command which makes it even more tedious since using a mouse will be faster.

答:
macOS contains two terminal commands dealing with the clipboard: pbcopy and pbpaste (for whatever reason they use the term pasteboard instead of clipboard). You can just pipe content into pbcopy or out of pbpaste to copy or paste from the clipboard.

To copy the current working directory, as in your example, you would write:

```<code>$ pwd | pbcopy
</code>```

EDIT: okay, just saw the requirement to copy it with the keyboard, and not with another command… So ignore my answer, will probably delete it soon.

Body:
macOS contains two terminal commands dealing with the clipboard: pbcopy and pbpaste (for whatever reason they use the term pasteboard instead of clipboard). You can just pipe content into pbcopy or out of pbpaste to copy or paste from the clipboard.

To copy the current working directory, as in your example, you would write:

$ pwd | pbcopy

EDIT: okay, just saw the requirement to copy it with the keyboard, and not with another command… So ignore my answer, will probably delete it soon.


问:
Capybara: page.execute_script() not working
I am trying to simulate drag and drop using jquery.simulate library in rspec feature.The execute_script lines in spec are:

```<code> page.execute_script("$('#slide_1').draggable();")
 page.evaluate_script("$('#slide_1').simulate('drag', {dragTarget: '#library_swap', interpolation: {stepWidth: 10, stepDelay: 300 }});")
 page.evaluate_script("$('#slide_1').simulate('drop');")
</code>```

If I run the lines inside the execute script over chrome console,its working fine(drag-drop simulation works),but not working with execute_script

答:
Since you're not getting any errors, the JS code you're passing to execute_script is actually being executed.  Since you're not seeing the behavior you expect the most likely explanation is that you're executing the JS before the element is actually on the page, which would then just silently do nothing.  The one thing that confuses me about the code is why you're calling draggable on the #slide_1 element since I would assume that had already been called in your app.  Anyway - add an expectation before your execute_script calls to make sure the element is actually on the page

```<code>expect(page).to have_css('#slide_1')
execute_script("$('#slide_1')...
</code>```

Also note, there shouldn't be any reason you need to use three different execute_script calls for this, you could just combine them all into one.  In recent versions of Capybara you can also DRY up the commands by not specifying the selector again and instead passing the element to execute_script

```<code>slider = page.find(:css, '#slide_1')
execute_script("$(arguments[0]). ...    ", slider)
</code>```

Body:
I am trying to simulate drag and drop using jquery.simulate library in rspec feature.The execute_script lines in spec are:

 page.execute_script("$('#slide_1').draggable();")
 page.evaluate_script("$('#slide_1').simulate('drag', {dragTarget: '#library_swap', interpolation: {stepWidth: 10, stepDelay: 300 }});")
 page.evaluate_script("$('#slide_1').simulate('drop');")

If I run the lines inside the execute script over chrome console,its working fine(drag-drop simulation works),but not working with execute_script

Body:
Since you're not getting any errors, the JS code you're passing to execute_script is actually being executed.  Since you're not seeing the behavior you expect the most likely explanation is that you're executing the JS before the element is actually on the page, which would then just silently do nothing.  The one thing that confuses me about the code is why you're calling draggable on the #slide_1 element since I would assume that had already been called in your app.  Anyway - add an expectation before your execute_script calls to make sure the element is actually on the page

expect(page).to have_css('#slide_1')
execute_script("$('#slide_1')...

Also note, there shouldn't be any reason you need to use three different execute_script calls for this, you could just combine them all into one.  In recent versions of Capybara you can also DRY up the commands by not specifying the selector again and instead passing the element to execute_script

slider = page.find(:css, '#slide_1')
execute_script("$(arguments[0]). ...    ", slider)


问:
'Uncaught SyntaxError: Unexpected token :'

$(onReady);

function onReady() {
    console.log('jq');
    $('#submitButton').on('click', calcDistance);
}

function calcDistance() {
    console.log('button clicked');

    $.ajax({
        type:'GET',
        dataType: 'jsonp',
        contentType: "application/json",
        url:"https://www.zipcodeapi.com/rest/WvKkFrPlOUywte1GcfPJVGmhqHjTLwQH1B2H2R3QMCmfQoV2DLMzr8QRQ9KBGBiI/distance.json/55044/55124/mile/",
        header: {
             "Access-Control-Allow-Origin": "*"
         },
        success: function(res) {
            console.log( 'back from ther server with',res );

        },
        error: function( err ){
            console.log( err );
        }

    });
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title></title>
        <script
  src="https://code.jquery.com/jquery-3.2.1.min.js"
  integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
  crossorigin="anonymous"></script>
        <script src="client.js" charset="utf-8"></script>
    </head>
    <body>
        <h1>Zipcode</h1>
        <!-- <input id='firstZipcode' type="text" name="" value="First Zipcode">
        <input id='secondZipcode' type="text" name="" value="Second Zipcode"> -->
        <button id='submitButton' type="button" name="button">Enter</button>

    </body>
</html></code>```

I am making a call to the zipcode api and i am getting the error "Uncaught SyntaxError: Unexpected token :". I have no idea where that is coming from. I am totally lost on how i would fix this. Is it in the header when i make the ajax call? Do i need the content-type somewhere in there? The two zipcodes are hard coded into the url.

答:
In the first line you have '$(onReady);'.
Try

```<code>jQuery(document).ready(function($){
..put all your other code here.
}
</code>```

From what I can gather from your posted code it's the '$' that's not recognised, as it hasn't been bound to jQuery.

Body:
$(onReady);

function onReady() {
    console.log('jq');
    $('#submitButton').on('click', calcDistance);
}

function calcDistance() {
    console.log('button clicked');

    $.ajax({
        type:'GET',
        dataType: 'jsonp',
        contentType: "application/json",
        url:"https://www.zipcodeapi.com/rest/WvKkFrPlOUywte1GcfPJVGmhqHjTLwQH1B2H2R3QMCmfQoV2DLMzr8QRQ9KBGBiI/distance.json/55044/55124/mile/",
        header: {
             "Access-Control-Allow-Origin": "*"
         },
        success: function(res) {
            console.log( 'back from ther server with',res );

        },
        error: function( err ){
            console.log( err );
        }

    });
}

<!DOCTYPE html>

        <meta charset="utf-8">
        <title></title>

Zipcode

        <button id='submitButton' type="button" name="button">Enter</button>

I am making a call to the zipcode api and i am getting the error "Uncaught SyntaxError: Unexpected token :". I have no idea where that is coming from. I am totally lost on how i would fix this. Is it in the header when i make the ajax call? Do i need the content-type somewhere in there? The two zipcodes are hard coded into the url.

Body:
In the first line you have '$(onReady);'.
Try

jQuery(document).ready(function($){
..put all your other code here.
}

From what I can gather from your posted code it's the '$' that's not recognised, as it hasn't been bound to jQuery.


问:
Python: Requests won't POST if I have punctuation in my data
I have a small_file.txt file that contains:

```<code>1asdfaksdjfhlaksjdhflkjashdflkjhasldkjfhlaksdfhasdf:
2asdfaksdjfhlaksjdhflkjashdflkjhasldkjfhlaksdfhasdf:
3asdfaksdjfhlaksjdhflkjashdflkjhasldkjfhlaksdfhasdf
4asdfaksdjfhlaksjdhflkjashdflkjhasldkjfhlaksdfhasdf:
</code>```

Notice the colons at the end, they are just regular strings.

When I try to send it using python requests it doesn't work. For some reason, it waits for the first line with a colon and then sends all the lines starting from there. So for example, in the file above, it will POST only:

```<code>3asdfaksdjfhlaksjdhflkjashdflkjhasldkjfhlaksdfhasdf
4asdfaksdjfhlaksjdhflkjashdflkjhasldkjfhlaksdfhasdf:
</code>```

How can I fix this issue? I'm not sure what is going on.

Here is a simple version of my code:

```<code>import requests
import sys
import json
import os

token                    = 'nVQowAng0c'
url                      = "https://api.hipchat.com/v2/room/test_room/share/file"
headers                  = {'Content-type': 'multipart/related; boundary=boundary123456'}
headers['Authorization'] = "Bearer " + token

filepath = 'small_file.csv'
data     = open(filepath, 'rb').read()

payload = """\
--boundary123456
Content-Type: application/json; charset=UTF-8
Content-Disposition: attachment; name="metadata"
--boundary123456
Content-Disposition: attachment; name="file"; filename="{0}"
{1}
--boundary123456--\
""".format(os.path.basename(filepath), data)

r = requests.post(url, headers=headers, data=payload)
r.raise_for_status()
</code>```

When I try to send something like a .csv file with a timestamp on every row, nothing will get sent because each row has a colon.

答:
Your immediate error is that you misencoded the MIME multipart elements. Each part has two sections, headers and contents, with a double newline between. Yours is missing the second newline, add it in:

```<code>payload = """\
--boundary123456
Content-Type: application/json; charset=UTF-8
Content-Disposition: attachment; name="metadata"

--boundary123456
Content-Disposition: attachment; name="file"; filename="{0}"

{1}
--boundary123456--\
""".format(os.path.basename(filepath), data)
</code>```

I'd not manually build the contents, but re-purpose the requests-toolbelt project to let you upload your data in a streaming fashion:

```<code>from requests_toolbelt import MultipartEncoder

class MultipartRelatedEncoder(MultipartEncoder):
    """A multipart/related encoder"""
    @property
    def content_type(self):
        return str(
            'multipart/related; boundary={0}'.format(self.boundary_value)
        )

    def _iter_fields(self):
        # change content-disposition from form-data to attachment
        for field in super(MultipartRelatedEncoder, self)._iter_fields():
            content_type = field.headers['Content-Type']
            field.make_multipart(
                content_disposition='attachment',
                content_type=content_type)
            yield field

m = MultipartRelatedEncoder(
    fields={
        'metadata': (None, '', 'application/json; charset=UTF-8'),
        'file': (os.path.basename(filepath), open(filepath, 'rb'), 'text/csv'),
    }
)

headers['Content-type'] = m.content_type

r = requests.post(url, data=m, headers=headers)
</code>```

I've adapted the requests_toolbelt.MultipartEncoder class to emit a multipart/related data stream rather than a multipart/form-data message.

Note that I pass in the open file object, and not the file data itself; this because the MultipartEncoder lets you stream the data to the remote server, the file doesn't have to be read into memory in one.

You probably want to pass in actual JSON data in the metadata part; replace the empty string in the (None, '', 'application/json; charset=UTF-8' tuple with a valid JSON document.

Body:
I have a small_file.txt file that contains:

1asdfaksdjfhlaksjdhflkjashdflkjhasldkjfhlaksdfhasdf:
2asdfaksdjfhlaksjdhflkjashdflkjhasldkjfhlaksdfhasdf:
3asdfaksdjfhlaksjdhflkjashdflkjhasldkjfhlaksdfhasdf
4asdfaksdjfhlaksjdhflkjashdflkjhasldkjfhlaksdfhasdf:

Notice the colons at the end, they are just regular strings.

When I try to send it using python requests it doesn't work. For some reason, it waits for the first line with a colon and then sends all the lines starting from there. So for example, in the file above, it will POST only:

3asdfaksdjfhlaksjdhflkjashdflkjhasldkjfhlaksdfhasdf
4asdfaksdjfhlaksjdhflkjashdflkjhasldkjfhlaksdfhasdf:

How can I fix this issue? I'm not sure what is going on.

Here is a simple version of my code:

import requests
import sys
import json
import os

token                    = 'nVQowAng0c'
url                      = "https://api.hipchat.com/v2/room/test_room/share/file"
headers                  = {'Content-type': 'multipart/related; boundary=boundary123456'}
headers['Authorization'] = "Bearer " + token

filepath = 'small_file.csv'
data     = open(filepath, 'rb').read()

payload = """\
--boundary123456
Content-Type: application/json; charset=UTF-8
Content-Disposition: attachment; name="metadata"
--boundary123456
Content-Disposition: attachment; name="file"; filename="{0}"
{1}
--boundary123456--\
""".format(os.path.basename(filepath), data)

r = requests.post(url, headers=headers, data=payload)
r.raise_for_status()

When I try to send something like a .csv file with a timestamp on every row, nothing will get sent because each row has a colon.

Body:
Your immediate error is that you misencoded the MIME multipart elements. Each part has two sections, headers and contents, with a double newline between. Yours is missing the second newline, add it in:

payload = """\
--boundary123456
Content-Type: application/json; charset=UTF-8
Content-Disposition: attachment; name="metadata"

--boundary123456
Content-Disposition: attachment; name="file"; filename="{0}"

{1}
--boundary123456--\
""".format(os.path.basename(filepath), data)

I'd not manually build the contents, but re-purpose the requests-toolbelt project to let you upload your data in a streaming fashion:

from requests_toolbelt import MultipartEncoder

class MultipartRelatedEncoder(MultipartEncoder):
    """A multipart/related encoder"""
    @property
    def content_type(self):
        return str(
            'multipart/related; boundary={0}'.format(self.boundary_value)
        )

    def _iter_fields(self):
        # change content-disposition from form-data to attachment
        for field in super(MultipartRelatedEncoder, self)._iter_fields():
            content_type = field.headers['Content-Type']
            field.make_multipart(
                content_disposition='attachment',
                content_type=content_type)
            yield field

m = MultipartRelatedEncoder(
    fields={
        'metadata': (None, '', 'application/json; charset=UTF-8'),
        'file': (os.path.basename(filepath), open(filepath, 'rb'), 'text/csv'),
    }
)

headers['Content-type'] = m.content_type

r = requests.post(url, data=m, headers=headers)

I've adapted the requests_toolbelt.MultipartEncoder class to emit a multipart/related data stream rather than a multipart/form-data message.

Note that I pass in the open file object, and not the file data itself; this because the MultipartEncoder lets you stream the data to the remote server, the file doesn't have to be read into memory in one.

You probably want to pass in actual JSON data in the metadata part; replace the empty string in the (None, '', 'application/json; charset=UTF-8' tuple with a valid JSON document.


问:
Most performant way to use a background image throughout an iphone application
I have an image that I want to use as the background for every view in my application including several modal views.

Right now I'm just creating a new UIColor for each view:

```<code>view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"metal-bg.png"]];
</code>```

This works for the most part but with the modal views there is a brief period during the sliding animation before the background image displays when I can see through the modal view to the view below it.

Is there a better way to do this?
Such as setting up some sort of global object that all the views can use?

答:
I was just wondering about this yesterday.

I haven't tried this, but I suspect that it may be possible to add a UIImage to the Application's delegate and then use that image in every view.

Try this:

[self.view setBackgroundColor:[[[UIApplication sharedApplication] delegate] bgImageColor]];

Body:
I have an image that I want to use as the background for every view in my application including several modal views.

Right now I'm just creating a new UIColor for each view:

view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"metal-bg.png"]];

This works for the most part but with the modal views there is a brief period during the sliding animation before the background image displays when I can see through the modal view to the view below it.

Is there a better way to do this?
Such as setting up some sort of global object that all the views can use?


问:
SQL conditional select with for/while loop
This is the table:

```<code>Order_ID|Priority|Status
A       |3       |Normal
A       |4       |Urgent
B       |6       |Urgent
B       |7       |Normal
C       |8       |Normal
C       |9       |Urgent
</code>```

How do I select the Order_ID and Status where a row's priority is higher for that ID? For example, in this case, the output of the query given the above data should be:

```<code>A - Urgent
B - Normal
C - Urgent
</code>```

答:
The record with the highest priority -->> there is no record with a higher priority

```<code>SELECT *
FROM order_status o
WHERE NOT EXISTS(
        SELECT *
        FROM order_status x
        WHERE x.order_id = o.order_id
        AND x.priority > o.priority
        )
        ;
</code>```

Body:
This is the table:

Order_ID|Priority|Status
A       |3       |Normal
A       |4       |Urgent
B       |6       |Urgent
B       |7       |Normal
C       |8       |Normal
C       |9       |Urgent

How do I select the Order_ID and Status where a row's priority is higher for that ID? For example, in this case, the output of the query given the above data should be:

A - Urgent
B - Normal
C - Urgent

Body:
The record with the highest priority -->> there is no record with a higher priority

SELECT *
FROM order_status o
WHERE NOT EXISTS(
        SELECT *
        FROM order_status x
        WHERE x.order_id = o.order_id
        AND x.priority > o.priority
        )
        ;


问:
Plotting grouped data in R along with their percentages
My data is in this form

```<code>df$new  df$y
0.5     A
0.0     D
1.0     D
1.0     M
1.0     A
1.0     MNY
1.0     NO
0.0     NO
1.0     PV
0.5     PV
1.0     S
0.0     S
</code>```

I just know basic plot, so i used

```<code>barplot(df$new,names.arg = df$y)
</code>```

But In the X-Axis there should be unique values, how can i get this?  also their percentages

Percentages should be within them. Ex: A = 1.5/2 => 75%

答:
Or,   you can do this in base R with aggregate.

```<code>Tab1 = aggregate(df$new, list(df$y), sum)
Tab1$x = Tab1$x / aggregate(df$y, list(df$y), length)$x
barplot(Tab1$x, names.arg=Tab1$Group.1)
</code>```

Body:
My data is in this form

df$new  df$y
0.5     A
0.0     D
1.0     D
1.0     M
1.0     A
1.0     MNY
1.0     NO
0.0     NO
1.0     PV
0.5     PV
1.0     S
0.0     S

I just know basic plot, so i used

barplot(df$new,names.arg = df$y)

But In the X-Axis there should be unique values, how can i get this?  also their percentages

Percentages should be within them. Ex: A = 1.5/2 => 75%

Body:
Or,   you can do this in base R with aggregate.

Tab1 = aggregate(df$new, list(df$y), sum)
Tab1$x = Tab1$x / aggregate(df$y, list(df$y), length)$x
barplot(Tab1$x, names.arg=Tab1$Group.1)


问:
mysql need to extract median value from query
I have the following query from which I need to extract the median value of total_views.

```<code>    SELECT
    @rownum:=@rownum + 1 AS row_num, total_views, projectId
FROM
    (SELECT
        a.creation,
            a.projectId,
            devices,
            browserIds,
            devices + browserIds AS total_views
    FROM
        ((SELECT
        projectId, creation
    FROM
        event
    WHERE
        kind = 'project_creation'
            AND creation > '2017-04-28') a
    INNER JOIN ((SELECT
        COUNT(DISTINCT deviceId) AS devices, projectId, creation
    FROM
        event
    WHERE
        kind = 'open' AND component = 'mobile'
    GROUP BY projectId) b
    JOIN (SELECT
        COUNT(DISTINCT browserId) AS browserIds, projectId, creation
    FROM
        event
    WHERE
        kind = 'open' AND component = 'web'
    GROUP BY projectId) c ON b.projectId = c.projectId) ON a.projectId = b.projectId
        OR a.projectId = c.projectId)
    ORDER BY total_views ASC) d,
    (SELECT @rownum:=0) e
;
</code>```

This a part of the result :

```<code>1   1   151
2   1   256
3   1   301
4   2   404
5   2   305
6   3   895
7   4   654
8   4   369
9   9   874
10  10  123
</code>```

I need to extend the query to extract the median value of total_views.
Any ideas?

答:
Found the solution, needed to use the value of the @rownum variable instead of using the value of the field row_num to determine the position of the middle value.
I then calculate the average value of the total_views in the middle of the result set.
(Average of two middle values if the result has an even number of lines. average of the middle value if the resultset has an odd number of lines, which is the same as the middle value).
thus using the condition :

```<code>WHERE row_num in (CEIL(@rownum/2), FLOOR(@rownum/2))
</code>```

full query:

```<code>SELECT avg(total_views) from
(SELECT
    @rownum:=@rownum + 1 AS row_num, total_views, projectId
FROM
    (SELECT
        a.creation,
            a.projectId,
            devices,
            browserIds,
            devices + browserIds AS total_views
    FROM
        ((SELECT
        projectId, creation
    FROM
        event
    WHERE
        kind = 'project_creation'
            AND creation > '2017-04-28') a
    INNER JOIN ((SELECT
        COUNT(DISTINCT deviceId) AS devices, projectId, creation
    FROM
        event
    WHERE
        kind = 'open' AND component = 'mobile'
    GROUP BY projectId) b
    JOIN (SELECT
        COUNT(DISTINCT browserId) AS browserIds, projectId, creation
    FROM
        event
    WHERE
        kind = 'open' AND component = 'web'
    GROUP BY projectId) c ON b.projectId = c.projectId) ON a.projectId = b.projectId
        OR a.projectId = c.projectId)
    ORDER BY total_views ASC) d,
    (SELECT @rownum:=0) e) f WHERE row_num in (CEIL(@rownum/2), FLOOR(@rownum/2))
;
</code>```

Body:
I have the following query from which I need to extract the median value of total_views.

    SELECT
    @rownum:=@rownum + 1 AS row_num, total_views, projectId
FROM
    (SELECT
        a.creation,
            a.projectId,
            devices,
            browserIds,
            devices + browserIds AS total_views
    FROM
        ((SELECT
        projectId, creation
    FROM
        event
    WHERE
        kind = 'project_creation'
            AND creation > '2017-04-28') a
    INNER JOIN ((SELECT
        COUNT(DISTINCT deviceId) AS devices, projectId, creation
    FROM
        event
    WHERE
        kind = 'open' AND component = 'mobile'
    GROUP BY projectId) b
    JOIN (SELECT
        COUNT(DISTINCT browserId) AS browserIds, projectId, creation
    FROM
        event
    WHERE
        kind = 'open' AND component = 'web'
    GROUP BY projectId) c ON b.projectId = c.projectId) ON a.projectId = b.projectId
        OR a.projectId = c.projectId)
    ORDER BY total_views ASC) d,
    (SELECT @rownum:=0) e
;

This a part of the result :

1   1   151
2   1   256
3   1   301
4   2   404
5   2   305
6   3   895
7   4   654
8   4   369
9   9   874
10  10  123

I need to extend the query to extract the median value of total_views.
Any ideas?

Body:
Found the solution, needed to use the value of the @rownum variable instead of using the value of the field row_num to determine the position of the middle value.
I then calculate the average value of the total_views in the middle of the result set.
(Average of two middle values if the result has an even number of lines. average of the middle value if the resultset has an odd number of lines, which is the same as the middle value).
thus using the condition :

WHERE row_num in (CEIL(@rownum/2), FLOOR(@rownum/2))

full query:

SELECT avg(total_views) from
(SELECT
    @rownum:=@rownum + 1 AS row_num, total_views, projectId
FROM
    (SELECT
        a.creation,
            a.projectId,
            devices,
            browserIds,
            devices + browserIds AS total_views
    FROM
        ((SELECT
        projectId, creation
    FROM
        event
    WHERE
        kind = 'project_creation'
            AND creation > '2017-04-28') a
    INNER JOIN ((SELECT
        COUNT(DISTINCT deviceId) AS devices, projectId, creation
    FROM
        event
    WHERE
        kind = 'open' AND component = 'mobile'
    GROUP BY projectId) b
    JOIN (SELECT
        COUNT(DISTINCT browserId) AS browserIds, projectId, creation
    FROM
        event
    WHERE
        kind = 'open' AND component = 'web'
    GROUP BY projectId) c ON b.projectId = c.projectId) ON a.projectId = b.projectId
        OR a.projectId = c.projectId)
    ORDER BY total_views ASC) d,
    (SELECT @rownum:=0) e) f WHERE row_num in (CEIL(@rownum/2), FLOOR(@rownum/2))
;


问:
Client => Server communication with Vaadin + GWT
I'm developing a GWT widget for an existing vaadin application and so far everything has worked out fine,
until I needed to call a server-side function from the client and get a value from it to the client.

more detailed issue:
There is a server-side function that gets certain values from a connected database.
Now I want to get access this function from the client-side,
since I need the values to update something in the widget.

According to Vaadin and GWT documentations you're supposed to use RPC for this,
and I already implemented multiple functions on the server-side that bascially do the opposite
(send something from the server to the client, initiate a call of a client function from server code etc.)

From my understanding I'm supposed to call a void return function on the server by using rpc (the part I can't get to work)
then I could make that function on the server use a server=>client rpc to send that value back to the client (already working)

Is this the definite solution and if so how do I properly implement the client=>server part
and if not, what would be a good solution?

I've already tried something like https://vaadin.com/wiki/-/wiki/Main/Sending+events+from+the+client+to+the+server+using+RPC
but somehow can't figure out how to call the method while in the widget class and not in the connector class
There just seems to be something missing? and is this even the right approach?

parts of the current code:

DrawwServerRPC

```<code>public interface DrawwServerRPC extends ServerRpc {
   public void updateE(String e);
}
</code>```

relevant part of Draww.java on server

```<code>protected DrawwServerRPC = new DrawwServerRPC () {
    public void updateE(String e){
        // gets some values from a db and then sends them back to the client
        // via rpc (both points working fine)
    }
};

public Draww() {
    registerRpc(rpc);
}
</code>```

part of the connector class, this is supposed to be called when a specific method in the DrawwWidget class (client) is called, instead of on a click

```<code>getWidget().addClickHandler(new ClickHandler() {
        public void onClick(ClickEvent event) {
            final MouseEventDetails mouseDetails = MouseEventDetailsBuilder
                .buildMouseEventDetails(event.getNativeEvent(),
                            getWidget().getElement());
            rpc.updateE("test");
        }
    });
</code>```

So my main issue is, how do I now properly access this method (most likely over the connector method) when a specific function in the DrawwWidget class on the Client is called?

And how do I then pass the value from the client method to the connector (or even server side) method? => need to somehow call the updateE method on the server from client side code (by using connector/rpc)

edit:
so here is a bit longer explanation of how I solved it in the end according to the idea I got from Mika's answer and this

added an Interface

```<code>public interface customListener {
    void customEvent (String s);
}
</code>```

adjusted the DrawwWidget:

```<code>public class DrawwWidget extends Label{
private customListener MyListener;
//...
private void someFunction() {
    String something = ...;
    if (myListener != null) myListener.customEvent(something);
    }

public void setMyListener(customListener listener) {
    this.myListener = listener;
    }

}
</code>```

and finally implemented the listener in the connector class:

```<code>public class DrawwConnector extends AbstractComponentConnector implements customListener {
DrawwServerRpc rpc = RpcProxy.create(DrawwServerRpc.class, this);
public DrawwConnector () {
    //lots of irrelevant Server => Client rpc things
    getWidget().setMyListener(this);
}

@Override
public void customEvent(String s) {
    rpc.doSomething(s);
}
</code>```

Now I can call the server side "doSomething" method from wherever I want in the widget by using the "customEvent (String s)" Method

答:
You can interact with client side with custom widgets or javascript extensions. For visible components custom widget is usually suitable solution.

You can follow similar convention in client side as Vaadin generally follows in server side and register a listener from connector to your widget. For example:

```<code>@Override
protected Widget createWidget() {
    MyWidget widget = GWT.create(MyWidget.class);
    widget.addMyListener(new MyListener() {
        @Override
        public void onSomeEvent(ClientData data) {
            rpc.onEventFromClient(data);
        }
    });
    return widget;
}
</code>```

Widget is a GWT component and usually you can find some existing GWT component that you can extend. If not, then it is possible to create plain HTML elements from the widget, good reference for this is the source code for existing GWT components.

Here is an example of a widget that has a text and you can click on the widget.

```<code>import com.google.gwt.user.client.ui.Label;
// ... only relevant imports included
public class MyWidget extends Label {
    private List<MyListener> listeners = new ArrayList<MyListener>();

    public MyWidget() {
        addStyleName("m-my-label");
        // Add GWT event listeners for events that you want to capture.
        addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent event) {
                notifyListeners();
            }
        });
    }

    private void notifyListeners() {
        for (MyListener listener : listeners) {
            listener.onSomeEvent(new ClientData("Hello from widget"));
        }
    }
}
</code>```

Body:
I'm developing a GWT widget for an existing vaadin application and so far everything has worked out fine,
until I needed to call a server-side function from the client and get a value from it to the client.

more detailed issue:
There is a server-side function that gets certain values from a connected database.
Now I want to get access this function from the client-side,
since I need the values to update something in the widget.

According to Vaadin and GWT documentations you're supposed to use RPC for this,
and I already implemented multiple functions on the server-side that bascially do the opposite
(send something from the server to the client, initiate a call of a client function from server code etc.)

From my understanding I'm supposed to call a void return function on the server by using rpc (the part I can't get to work)
then I could make that function on the server use a server=>client rpc to send that value back to the client (already working)

Is this the definite solution and if so how do I properly implement the client=>server part
and if not, what would be a good solution?

I've already tried something like https://vaadin.com/wiki/-/wiki/Main/Sending+events+from+the+client+to+the+server+using+RPC
but somehow can't figure out how to call the method while in the widget class and not in the connector class
There just seems to be something missing? and is this even the right approach?

parts of the current code:

DrawwServerRPC

public interface DrawwServerRPC extends ServerRpc {
   public void updateE(String e);
}

relevant part of Draww.java on server

protected DrawwServerRPC = new DrawwServerRPC () {
    public void updateE(String e){
        // gets some values from a db and then sends them back to the client
        // via rpc (both points working fine)
    }
};

public Draww() {
    registerRpc(rpc);
}

part of the connector class, this is supposed to be called when a specific method in the DrawwWidget class (client) is called, instead of on a click

getWidget().addClickHandler(new ClickHandler() {
        public void onClick(ClickEvent event) {
            final MouseEventDetails mouseDetails = MouseEventDetailsBuilder
                .buildMouseEventDetails(event.getNativeEvent(),
                            getWidget().getElement());
            rpc.updateE("test");
        }
    });

So my main issue is, how do I now properly access this method (most likely over the connector method) when a specific function in the DrawwWidget class on the Client is called?

And how do I then pass the value from the client method to the connector (or even server side) method? => need to somehow call the updateE method on the server from client side code (by using connector/rpc)

edit:
so here is a bit longer explanation of how I solved it in the end according to the idea I got from Mika's answer and this

added an Interface

public interface customListener {
    void customEvent (String s);
}

adjusted the DrawwWidget:

public class DrawwWidget extends Label{
private customListener MyListener;
//...
private void someFunction() {
    String something = ...;
    if (myListener != null) myListener.customEvent(something);
    }

public void setMyListener(customListener listener) {
    this.myListener = listener;
    }

}

and finally implemented the listener in the connector class:

public class DrawwConnector extends AbstractComponentConnector implements customListener {
DrawwServerRpc rpc = RpcProxy.create(DrawwServerRpc.class, this);
public DrawwConnector () {
    //lots of irrelevant Server => Client rpc things
    getWidget().setMyListener(this);
}

@Override
public void customEvent(String s) {
    rpc.doSomething(s);
}

Now I can call the server side "doSomething" method from wherever I want in the widget by using the "customEvent (String s)" Method

Body:
You can interact with client side with custom widgets or javascript extensions. For visible components custom widget is usually suitable solution.

You can follow similar convention in client side as Vaadin generally follows in server side and register a listener from connector to your widget. For example:

@Override
protected Widget createWidget() {
    MyWidget widget = GWT.create(MyWidget.class);
    widget.addMyListener(new MyListener() {
        @Override
        public void onSomeEvent(ClientData data) {
            rpc.onEventFromClient(data);
        }
    });
    return widget;
}

Widget is a GWT component and usually you can find some existing GWT component that you can extend. If not, then it is possible to create plain HTML elements from the widget, good reference for this is the source code for existing GWT components.

Here is an example of a widget that has a text and you can click on the widget.

import com.google.gwt.user.client.ui.Label;
// ... only relevant imports included
public class MyWidget extends Label {
    private List<MyListener> listeners = new ArrayList<MyListener>();

    public MyWidget() {
        addStyleName("m-my-label");
        // Add GWT event listeners for events that you want to capture.
        addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent event) {
                notifyListeners();
            }
        });
    }

    private void notifyListeners() {
        for (MyListener listener : listeners) {
            listener.onSomeEvent(new ClientData("Hello from widget"));
        }
    }
}


问:
Fortran floating point equality
I have a Fortran program that tests equality in two floating point numbers. It can be condensed to what is shown below. When this program is run with "0.1" given as a command line argument, I expect it to print "what I expected" but instead it prints "strange". I understand that this is probably due to a floating point rounding issue, but am hoping someone might be able to explain exactly how I should change inputvariable to make this code print "what I expected" with a command line argument of 0.1

```<code>program equalitytest
  character(len=3) :: arg1
  real*8           :: inputvariable
  CALL GET_COMMAND_ARGUMENT(1,arg1)
  READ(arg1,*) inputvariable
  IF (inputvariable.EQ.0.1) THEN
    PRINT*, "what I expected"
  ELSE
    PRINT*, "strange"
  ENDIF
end program equalitytest
</code>```

Run as follows:

```<code>./equalitytest 0.1
strange
</code>```

答:
As a general point, there should be very few reasons why one should need to compare equality with real numbers. If I ever find myself writing such code, I tend to pause and have a think about what I am trying to achieve. What real-world condition is actually a reflection of this?

The exception to the above relate to zeros, either when writing robust code which checks for and handles possible divisions by zero, or for cases searching for a convergent solution to an equation - in the latter case, this should be considered using a delta anyway.

If there really is a need for this check, why not outsource it to a standard library within the project, e.g.

```<code>module mylib
    use iso_fortran_env

    implicit none
    private

    public :: isReal4EqualReal4
    public :: isReal4EqualReal8
    public :: isReal8EqualReal4
    public :: isReal8EqualReal8

    real(real32), parameter :: delta4 = 0.001
    real(real64), parameter :: delta8 = 0.0000000001

    contains

        logical function isReal4EqualReal4(lhs, rhs) result(equal)
            real(real32), intent(in) :: lhs
            real(real32), intent(in) :: rhs
            equal = (abs(lhs - rhs) .le. delta4)
        end function isReal4EqualReal4

        logical function isReal4EqualReal8(lhs, rhs) result(equal)
            real(real32), intent(in) :: lhs
            real(real64), intent(in) :: rhs
            equal = (abs(lhs - real(rhs,4)) .le. delta4)
        end function isReal4EqualReal8

        logical function isReal8EqualReal4(lhs, rhs) result(equal)
            real(real64), intent(in) :: lhs
            real(real32), intent(in) :: rhs
            equal = isReal4EqualReal8(rhs, lhs)
        end function isReal8EqualReal4

        logical function isReal8EqualReal8(lhs, rhs) result(equal)
            real(real64), intent(in) :: lhs
            real(real64), intent(in) :: rhs
            equal = (dabs(lhs - rhs) .le. delta8)
        end function isReal8EqualReal8

end module mylib
</code>```

EDIT: Forgot to add that one of the benefits of the above is the compiler will warn me if I'm attempting to compare two real numbers of different types while using the wrong interface

EDIT: Updated to use portable real number definitions.

Title: Fortran floating point equality

Body:
I have a Fortran program that tests equality in two floating point numbers. It can be condensed to what is shown below. When this program is run with "0.1" given as a command line argument, I expect it to print "what I expected" but instead it prints "strange". I understand that this is probably due to a floating point rounding issue, but am hoping someone might be able to explain exactly how I should change inputvariable to make this code print "what I expected" with a command line argument of 0.1

program equalitytest
  character(len=3) :: arg1
  real*8           :: inputvariable
  CALL GET_COMMAND_ARGUMENT(1,arg1)
  READ(arg1,*) inputvariable
  IF (inputvariable.EQ.0.1) THEN
    PRINT*, "what I expected"
  ELSE
    PRINT*, "strange"
  ENDIF
end program equalitytest

Run as follows:

./equalitytest 0.1
strange

Body:
As a general point, there should be very few reasons why one should need to compare equality with real numbers. If I ever find myself writing such code, I tend to pause and have a think about what I am trying to achieve. What real-world condition is actually a reflection of this?

The exception to the above relate to zeros, either when writing robust code which checks for and handles possible divisions by zero, or for cases searching for a convergent solution to an equation - in the latter case, this should be considered using a delta anyway.

If there really is a need for this check, why not outsource it to a standard library within the project, e.g.

module mylib
    use iso_fortran_env

    implicit none
    private

    public :: isReal4EqualReal4
    public :: isReal4EqualReal8
    public :: isReal8EqualReal4
    public :: isReal8EqualReal8

    real(real32), parameter :: delta4 = 0.001
    real(real64), parameter :: delta8 = 0.0000000001

    contains

        logical function isReal4EqualReal4(lhs, rhs) result(equal)
            real(real32), intent(in) :: lhs
            real(real32), intent(in) :: rhs
            equal = (abs(lhs - rhs) .le. delta4)
        end function isReal4EqualReal4

        logical function isReal4EqualReal8(lhs, rhs) result(equal)
            real(real32), intent(in) :: lhs
            real(real64), intent(in) :: rhs
            equal = (abs(lhs - real(rhs,4)) .le. delta4)
        end function isReal4EqualReal8

        logical function isReal8EqualReal4(lhs, rhs) result(equal)
            real(real64), intent(in) :: lhs
            real(real32), intent(in) :: rhs
            equal = isReal4EqualReal8(rhs, lhs)
        end function isReal8EqualReal4

        logical function isReal8EqualReal8(lhs, rhs) result(equal)
            real(real64), intent(in) :: lhs
            real(real64), intent(in) :: rhs
            equal = (dabs(lhs - rhs) .le. delta8)
        end function isReal8EqualReal8

end module mylib

EDIT: Forgot to add that one of the benefits of the above is the compiler will warn me if I'm attempting to compare two real numbers of different types while using the wrong interface

EDIT: Updated to use portable real number definitions.


问:
Obtain initial value based on the text in first td
I have HTML like so:

```<code><table id="resultsTable">
  <tbody role="alert" aria-live="polite" aria-relevant="all">
    <tr class="subRow odd" data-activitylogid="6459056" data-auditidentity="18487186" data-auditid="f831583e-d1a9-4e35-ac92-82a5cb48c62e">
      <td class="  sorting_1">UserSelection</td>
      <td class=" "><a class="auditaction">Update</a></td>
    </tr>
    <tr class="subRow even" data-activitylogid="6459056" data-auditidentity="18487179" data-auditid="88506880-632f-4e17-bceb-ebd4e20e435a">
      <td class="  sorting_1">Procedure</td>
      <td class=" "><a class="auditaction">Update</a></td>
    </tr>
</code>```

I am attempting to get the auditidentity data value like so:

```<code>        var uniqueKeys = [];
        $('#resultsTable').find('tbody > tr').each(function() {

          var tableName = $(this).find('td:eq(0)').text();
          var tableAction = $(this).find('td:eq(1)').text();
          var uniqueKey = tableName + '#' + tableAction;

          if (uniqueKeys.indexOf(uniqueKey) < 0) {
            uniqueKeys.push(uniqueKey);
          } else {
            //alert(tableName);
            //var initValue = $('#resultsTable tr td:first-child:contains(''' + tableName + ''')).data('auditidentity');
            //alert(initValue);
            var activityLogId = $(this).data('activitylogid');
            var auditidentity = $(this).data('auditidentity');
            var tableNameString = $(this).find('td:eq(0)').text();
            var actionType = $(this).find('td:eq(1)').text();
            //$(resultsTable).find('tbody > tr > td:first').contains(tableName).data('auditidentity', initValue + ',' + auditidentity);

            // After we have what we need, remove the combined row
            $(this).remove();
          }

        });
</code>```

The commented out initValue line is not correct, and the console displays:

```<code>VM572:56 Uncaught SyntaxError: missing )
</code>```

For the life of me I cannot see why.  To be clear, what I am after is the first row's data where the first cell is a specific text value.

答:
Could be related to the quotes; try using double quotes in your selector to avoid confusion with the multiple single quotes.</p>

```<code>var initValue = $("#resultsTable tr td:first-child:contains('" + tableName + "')").parent().data('auditidentity');
</code>```

Body:
I have HTML like so:

      UserSelection
      Update

      Procedure
      Update

I am attempting to get the auditidentity data value like so:

        var uniqueKeys = [];
        $('#resultsTable').find('tbody > tr').each(function() {

          var tableName = $(this).find('td:eq(0)').text();
          var tableAction = $(this).find('td:eq(1)').text();
          var uniqueKey = tableName + '#' + tableAction;

          if (uniqueKeys.indexOf(uniqueKey) < 0) {
            uniqueKeys.push(uniqueKey);
          } else {
            //alert(tableName);
            //var initValue = $('#resultsTable tr td:first-child:contains(''' + tableName + ''')).data('auditidentity');
            //alert(initValue);
            var activityLogId = $(this).data('activitylogid');
            var auditidentity = $(this).data('auditidentity');
            var tableNameString = $(this).find('td:eq(0)').text();
            var actionType = $(this).find('td:eq(1)').text();
            //$(resultsTable).find('tbody > tr > td:first').contains(tableName).data('auditidentity', initValue + ',' + auditidentity);

            // After we have what we need, remove the combined row
            $(this).remove();
          }

        });

The commented out initValue line is not correct, and the console displays:

VM572:56 Uncaught SyntaxError: missing )

For the life of me I cannot see why.  To be clear, what I am after is the first row's data where the first cell is a specific text value.

Body:
Could be related to the quotes; try using double quotes in your selector to avoid confusion with the multiple single quotes.

var initValue = $("#resultsTable tr td:first-child:contains('" + tableName + "')").parent().data('auditidentity');