问:
Could not load SWT library in Eclipse in Mac
When I tried to run a plug-in project as Eclipse Application, I get following error.

```<code>eclipse.buildId=unknown
java.version=1.8.0_152
java.vendor=Oracle Corporation
BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=en_US
Framework arguments:  -product org.eclipse.platform.ide
Command-line arguments:  -product org.eclipse.platform.ide -data /{HOME}/eclipse-workspace/../runtime-New_configuration -dev file:/{HOME}/eclipse-workspace/.metadata/.plugins/org.eclipse.pde.core/New_configuration/dev.properties -os win32 -ws win32 -arc$

!ENTRY org.eclipse.osgi 4 0 2017-12-07 23:43:27.145
!MESSAGE Application error
!STACK 1
java.lang.UnsatisfiedLinkError: Could not load SWT library. Reasons:
        no swt-win32-4530 in java.library.path
        no swt-win32 in java.library.path
        Can't load library: /{HOME}/.swt/lib/macosx/x86_64/libswt-win32-4530.jnilib
        Can't load library: /{HOME}/.swt/lib/macosx/x86_64/libswt-win32.jnilib

        at org.eclipse.swt.internal.Library.loadLibrary(Library.java:327)
        at org.eclipse.swt.internal.Library.loadLibrary(Library.java:236)
        at org.eclipse.swt.internal.C.<clinit>(C.java:16)
        at org.eclipse.swt.widgets.Display.<clinit>(Display.java:138)
        at org.eclipse.ui.internal.Workbench.createDisplay(Workbench.java:774)
        at org.eclipse.ui.PlatformUI.createDisplay(PlatformUI.java:162)
        at org.eclipse.ui.internal.ide.application.IDEApplication.createDisplay(IDEApplication.java:169)
        at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:111)
        at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196)
        at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:134)
        at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:104)
        at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:380)
        at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:235)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:669)
        at org.eclipse.equinox.launcher.Main.basicRun(Main.java:608)
</code>```

Then, I found out that the folder "/{HOME}/.swt/lib/macosx/x86_64" acctually is empty. I guess this is the reason, but I do not know how to reinstall SWT(I have googled a while though)

Eclipse Version: Oxygen.1a Release (4.7.1a) (64-bit)

Java Version:

```<code>java version "1.8.0_152"
Java(TM) SE Runtime Environment (build 1.8.0_152-b16)
Java HotSpot(TM) 64-Bit Server VM (build 25.152-b16, mixed mode)
</code>```

Mac Version: 10.12 (64-bit)

答:
The command line arguments:

-os win32 -ws win32
```

<p>show that you are trying to run this as a Windows application - which isn't going to work on macOS</p>

<p>Check that the Arguments tab of the Run Configuration has something like:</p>

<pre class="lang-none prettyprint-override"><code>-os ${target.os} -ws ${target.ws} -arch ${target.arch} -nl ${target.nl}
</code>```

in the program arguments and that the 'Environment' section of your current Target Platform is blank or specifies macOS.

Body:
When I tried to run a plug-in project as Eclipse Application, I get following error.

eclipse.buildId=unknown
java.version=1.8.0_152
java.vendor=Oracle Corporation
BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=en_US
Framework arguments:  -product org.eclipse.platform.ide
Command-line arguments:  -product org.eclipse.platform.ide -data /{HOME}/eclipse-workspace/../runtime-New_configuration -dev file:/{HOME}/eclipse-workspace/.metadata/.plugins/org.eclipse.pde.core/New_configuration/dev.properties -os win32 -ws win32 -arc$

!ENTRY org.eclipse.osgi 4 0 2017-12-07 23:43:27.145
!MESSAGE Application error
!STACK 1
java.lang.UnsatisfiedLinkError: Could not load SWT library. Reasons:
        no swt-win32-4530 in java.library.path
        no swt-win32 in java.library.path
        Can't load library: /{HOME}/.swt/lib/macosx/x86_64/libswt-win32-4530.jnilib
        Can't load library: /{HOME}/.swt/lib/macosx/x86_64/libswt-win32.jnilib

        at org.eclipse.swt.internal.Library.loadLibrary(Library.java:327)
        at org.eclipse.swt.internal.Library.loadLibrary(Library.java:236)
        at org.eclipse.swt.internal.C.<clinit>(C.java:16)
        at org.eclipse.swt.widgets.Display.<clinit>(Display.java:138)
        at org.eclipse.ui.internal.Workbench.createDisplay(Workbench.java:774)
        at org.eclipse.ui.PlatformUI.createDisplay(PlatformUI.java:162)
        at org.eclipse.ui.internal.ide.application.IDEApplication.createDisplay(IDEApplication.java:169)
        at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:111)
        at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196)
        at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:134)
        at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:104)
        at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:380)
        at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:235)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:669)
        at org.eclipse.equinox.launcher.Main.basicRun(Main.java:608)

Then, I found out that the folder "/{HOME}/.swt/lib/macosx/x86_64" acctually is empty. I guess this is the reason, but I do not know how to reinstall SWT(I have googled a while though)

Eclipse Version: Oxygen.1a Release (4.7.1a) (64-bit)

Java Version:

java version "1.8.0_152"
Java(TM) SE Runtime Environment (build 1.8.0_152-b16)
Java HotSpot(TM) 64-Bit Server VM (build 25.152-b16, mixed mode)

Mac Version: 10.12 (64-bit)

Body:
The command line arguments:

-os win32 -ws win32

show that you are trying to run this as a Windows application - which isn't going to work on macOS

Check that the Arguments tab of the Run Configuration has something like:

-os ${target.os} -ws ${target.ws} -arch ${target.arch} -nl ${target.nl}

in the program arguments and that the 'Environment' section of your current Target Platform is blank or specifies macOS.


来源: stackexchange

问:
How best to do a JavaScript array with non-consecutive indexes?
I'm writing a Google Chrome extension, in JavaScript, and I want to use an array to store a bunch of objects, but I want the indexes to be specific non-consecutive ID numbers.

(This is because I need to be able to efficiently look up the values later, using an ID number that comes from another source outside my control.)

For example:

```<code>var myObjects = [] ;

myObjects[471] = {foo: "bar"} ;

myObjects[3119] = {hello: "goodbye"}
</code>```

When I do console.log(myObjects), in the console I see the entire array printed out, with all the thousands of 'missing' indexes showing undefined.

My question is: does this matter? Is this wasting any memory?

And even if it's not wasting memory, surely whenever I loop over the array, it wastes CPU if I have to manually skip over every missing value?

I tried using an object instead of an array, but it seems you can't use numbers as object keys. I'm hoping there's a better way to achieve this?

答:
You can simply use an object instead here, having keys as integers, like this:

```<code>var myObjects = {};
myObjects[471] = {foo: "bar"};
myObjects[3119] = {hello: "goodbye"};
</code>```

This allows you to store anything on the object, functions, etc.  To enumerate (since it's an object now) over it you'll want a different syntax though, a for...in loop, like this:

```<code>for(var key in myObjects) {
  if(myObjects.hasOwnProperty(key)) {
    console.log("key: " + key, myObjects[key]);
  }
}
</code>```

For your other specific questions:

My question is: does this matter? Is this wasting any memory?

Yes, it wastes a bit of memory for the allocation (more-so for iterating over it) - not much though, does it matter...that depends on how spaced out the keys are.

And even if it's not wasting memory, surely whenever I loop over the array, it wastes CPU if I have to manually skip over every missing value?

Yup, extra cycles are used here.

I tried using an object instead of an array, but it seems you can't use numbers as object keys. I'm hoping there's a better way to achieve this?

Sure you can!, see above.

ContentLicense: CC BY-SA 2.5

Body:
I'm writing a Google Chrome extension, in JavaScript, and I want to use an array to store a bunch of objects, but I want the indexes to be specific non-consecutive ID numbers.

(This is because I need to be able to efficiently look up the values later, using an ID number that comes from another source outside my control.)

For example:

var myObjects = [] ;

myObjects[471] = {foo: "bar"} ;

myObjects[3119] = {hello: "goodbye"}

When I do console.log(myObjects), in the console I see the entire array printed out, with all the thousands of 'missing' indexes showing undefined.

My question is: does this matter? Is this wasting any memory?

And even if it's not wasting memory, surely whenever I loop over the array, it wastes CPU if I have to manually skip over every missing value?

I tried using an object instead of an array, but it seems you can't use numbers as object keys. I'm hoping there's a better way to achieve this?

Body:
You can simply use an object instead here, having keys as integers, like this:

var myObjects = {};
myObjects[471] = {foo: "bar"};
myObjects[3119] = {hello: "goodbye"};

This allows you to store anything on the object, functions, etc.  To enumerate (since it's an object now) over it you'll want a different syntax though, a for...in loop, like this:

for(var key in myObjects) {
  if(myObjects.hasOwnProperty(key)) {
    console.log("key: " + key, myObjects[key]);
  }
}

For your other specific questions:

My question is: does this matter? Is this wasting any memory?

Yes, it wastes a bit of memory for the allocation (more-so for iterating over it) - not much though, does it matter...that depends on how spaced out the keys are.

And even if it's not wasting memory, surely whenever I loop over the array, it wastes CPU if I have to manually skip over every missing value?

Yup, extra cycles are used here.

I tried using an object instead of an array, but it seems you can't use numbers as object keys. I'm hoping there's a better way to achieve this?

Sure you can!, see above.


问:
How do I finetune ResNet50 Keras to only classify images in 2 classes (cats vs. dogs) instead of all 1000 imagenet classes?
How do I finetune ResNet50 Keras to only classify images in 2 classes (cats vs. dogs) instead of all 1000 imagenet classes? I used Python and was able to classify random images with ResNet50 and keras with the 1000 ImageNet classes. Now I want to fine tune my code so that it only classifies cats vs. dogs, using the Kaggle images instead of ImageNet. How do I go about doing that?</p>

答:
There are several ways of applying Transfer Learning and it's trial & error what works best. However, ImageNet includes multiple types of cats and dogs in its 1000 classes, which is why I would do the following:

Add a single Dense layer to your model with 2 outputs

Set only the last layer to trainable

Retrain the network using only images of cats and dogs

This will get solid results rather quickly because you're only training one layer. Meaning, you don't have to backpropagate through the entire network. In addition, your model only has to learn a rather linear mapping from the original cats and dogs subclasses to this binary output.

ContentLicense: CC BY-SA 3.0


问:
Switch to the next children route with condition in angular
I want to make a custom router in Angular.
Here is my example router from Angular document with some changes :

```<code>const crisisCenterRoutes: Routes = [
  {
    path: 'crisis-center',
    component: CrisisCenterComponent,
    children: [
      {
        path: 'main',
        component: CrisisListComponent,
        children: [
          {
            path: '',
            component: CrisisComponent
          },
          {
            path: '',
            component: CrisisPublicComponent
          }
        ]
      }
    ]
  }
];
</code>```

There are two children under main path. Both children have the same path!!! I know this is impossible in this code. However I want to have these components with the same path with the condition if user is authorized we load first child if not load the second child.  I know we can do it in some ways such as ng-container with condition in the component but I want to know if I could have a custom router.

答:
It sounds like what you really want is a route guard. A route guard allows you to perform a check (such as whether the user is authorized). If the check is true, you route to the defined route. Otherwise you route to an alternate route.

Your route configuration would then just have the one "happy path" route. The route guard would route the user to the "failed authorization" path using code.

Here is an example path:

```<code>            {
                path: 'movies',
                canActivate: [AuthGuard],
                component: MovieListComponent
            },
</code>```

And here is the route guard:

```<code>import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, RouterStateSnapshot, Router,
         CanActivate } from '@angular/router';

import { AuthService } from './auth.service';

@Injectable()
export  class AuthGuard implements CanActivate {

    constructor(private authService: AuthService,
                private router: Router) { }

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
        return this.checkLoggedIn(state.url);
    }

    checkLoggedIn(url: string): boolean {
        if (this.authService.isLoggedIn()) {
            return true;
        }

        // Retain the attempted URL for redirection
        this.authService.redirectUrl = url;
        this.router.navigate(['/login']);   // <-- Here is the alternate route
        return false;
    }
}
</code>```

If the user is authorized, they are routed to the primary route defined in the path (MovieListComponent in my example.) If the user is not authorized, the guard routes the user to the login route as shown above.

You can find the complete working example here: https://github.com/DeborahK/MovieHunter-routing

Body:
I want to make a custom router in Angular.
Here is my example router from Angular document with some changes :

const crisisCenterRoutes: Routes = [
  {
    path: 'crisis-center',
    component: CrisisCenterComponent,
    children: [
      {
        path: 'main',
        component: CrisisListComponent,
        children: [
          {
            path: '',
            component: CrisisComponent
          },
          {
            path: '',
            component: CrisisPublicComponent
          }
        ]
      }
    ]
  }
];

There are two children under main path. Both children have the same path!!! I know this is impossible in this code. However I want to have these components with the same path with the condition if user is authorized we load first child if not load the second child.  I know we can do it in some ways such as ng-container with condition in the component but I want to know if I could have a custom router.

Body:
It sounds like what you really want is a route guard. A route guard allows you to perform a check (such as whether the user is authorized). If the check is true, you route to the defined route. Otherwise you route to an alternate route.

Your route configuration would then just have the one "happy path" route. The route guard would route the user to the "failed authorization" path using code.

Here is an example path:

            {
                path: 'movies',
                canActivate: [AuthGuard],
                component: MovieListComponent
            },

And here is the route guard:

import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, RouterStateSnapshot, Router,
         CanActivate } from '@angular/router';

import { AuthService } from './auth.service';

@Injectable()
export  class AuthGuard implements CanActivate {

    constructor(private authService: AuthService,
                private router: Router) { }

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
        return this.checkLoggedIn(state.url);
    }

    checkLoggedIn(url: string): boolean {
        if (this.authService.isLoggedIn()) {
            return true;
        }

        // Retain the attempted URL for redirection
        this.authService.redirectUrl = url;
        this.router.navigate(['/login']);   // <-- Here is the alternate route
        return false;
    }
}

If the user is authorized, they are routed to the primary route defined in the path (MovieListComponent in my example.) If the user is not authorized, the guard routes the user to the login route as shown above.

You can find the complete working example here: https://github.com/DeborahK/MovieHunter-routing


问:
Expo: Change default IOS simulator
I am new in expo and react-native
Whenever i run the app from IOS simulator (inside expo) it always boots up the IphoneX. If i need to change the simulator,I have to open it through Xcode, is there any way we can change the default simulator ?

答:
Just launch simulator on which you want to run app and then run command i.e. "yarn run ios" or "npm run ios" to run on simulator. App will run on both simulator.

If it doesn't work then quit all simulator and then run the command i.e. "yarn run ios" or "npm run ios", then app automatically run on simulator which was latter launched.

Hope this may help you!

Title: Expo: Change default IOS simulator


问:
how to install numba and link to llvm & llvmlite to import it in Python27
When I am trying to run python file .py that uses numba it gives me the below error

```<code> Traceback (most recent call last):
 File "C:\Myfile.py", line 16, in <module>
 import myfile2 as m
 File "C:\myfile2.py", line 8, in <module>
  import numba
  File "C:\Python27\lib\site-packages\numba\__init__.py", line 9, in <module>
  from . import config, errors, runtests, types
  File "C:\Python27\lib\site-packages\numba\config.py", line 11, in <module>
  import llvmlite.binding as ll
  File "C:\Python27\lib\site-packages\llvmlite\binding\__init__.py", line 6, in <module>
  from .dylib import *
  File "C:\Python27\lib\site-packages\llvmlite\binding\dylib.py", line 4, in <module>
  from . import ffi
  File "C:\Python27\lib\site-packages\llvmlite\binding\ffi.py", line 50, in <module>
   raise e
  WindowsError: [Error 126] The specified module could not be found
</code>```

I've tried to isntall numba from command propmt as below :

```<code>  pip install numba
</code>```

but it gives me a message that it already exists before

```<code>  Requirements already satisfied...........etc
</code>```

so could anyone help me to fix this error ? also How to install numba and link it with llvm and llvmlite ?

答:
I've uninstall the python and re-install it again
and install the below packages in order

```<code> pip install scikit_learn
 pip install numby+mkl
 pip install scipy
 pip install  numba
 pip install  matplotlib
</code>```

also I've installed mini conda and it is working fine as well

Body:
When I am trying to run python file .py that uses numba it gives me the below error

 Traceback (most recent call last):
 File "C:\Myfile.py", line 16, in <module>
 import myfile2 as m
 File "C:\myfile2.py", line 8, in <module>
  import numba
  File "C:\Python27\lib\site-packages\numba\__init__.py", line 9, in <module>
  from . import config, errors, runtests, types
  File "C:\Python27\lib\site-packages\numba\config.py", line 11, in <module>
  import llvmlite.binding as ll
  File "C:\Python27\lib\site-packages\llvmlite\binding\__init__.py", line 6, in <module>
  from .dylib import *
  File "C:\Python27\lib\site-packages\llvmlite\binding\dylib.py", line 4, in <module>
  from . import ffi
  File "C:\Python27\lib\site-packages\llvmlite\binding\ffi.py", line 50, in <module>
   raise e
  WindowsError: [Error 126] The specified module could not be found

I've tried to isntall numba from command propmt as below :

  pip install numba

but it gives me a message that it already exists before

  Requirements already satisfied...........etc

so could anyone help me to fix this error ? also How to install numba and link it with llvm and llvmlite ?

Body:
I've uninstall the python and re-install it again
and install the below packages in order

 pip install scikit_learn
 pip install numby+mkl
 pip install scipy
 pip install  numba
 pip install  matplotlib

also I've installed mini conda and it is working fine as well


问:
Proper model set up
I am new to stackoverflow, so my apologies if this is formatted poorly.

In my current project I have a model Driver, which has many trips.  Those trips have many mileages, backhauls, picks, drops and hours.  When I create a new trip, i want to be able to associate it to the driver, but I also want to be able to add the mileages, backhauls, picks and drops and hours on the same page.  I am unsure how to structure my routes for this.  I have been successful in creating a trip for a driver without adding on the additional models to the trip but from there I am stumped.  I have only created the mileage model/controller so far for what needs to be associated with the trip.  Any nudge in the right direction would be greatly appreciated.

Driver Model

```<code>class Driver < ApplicationRecord
  has_many :trips
end
</code>```

Trip Model

```<code>class Trip < ApplicationRecord
  belongs_to :driver
  has_many :mileages
  accepts_nested_attributes_for :mileages
  default_scope {order(date: :asc)}
  validates :total, presence: true
  validates :date, presence: true
  validates_uniqueness_of :trip_number, :allow_nil => true, :allow_blank =>
  true

end
</code>```

Mileage Model

```<code>class Mileage < ApplicationRecord
  belongs_to :trip
end
</code>```

Trips controller

```<code>def index
  @trips = Trip.all
end

def show
end

def new
  @driver = Driver.find(params[:driver_id])
  @trip = Trip.new
end

def edit
end

def create
  @driver = Driver.find(params[:driver_id])
  @trip = Trip.new(trip_params)
  @driver.trips.create(trip_params)
  respond_to do |format|
    if @driver.trips.create(trip_params)
      flash[:notice] = "Trip successfully created"
      redirect_to new_driver_trip_path(@driver)
    else
      flash[:warning] = "Unable to create trip"
      redirect_to new_driver_trip_path(@driver)
    end
end
private

  def set_trip
    @trip = Trip.find(params[:id])
  end

  def trip_params
    params.require(:trip).permit(:trip_number, :date, :driver_id, :total)
  end

end
</code>```

Mileage Controller

```<code>  def new
    @mileage = Mileage.new
  end

  def create
    @mileage.create(mileage_params)
  end

  private

    def mileage_params
      params.require(:mileage).permit(:miles, :rate, :total)
    end
  end
end
</code>```

Driver Controller

```<code>  def index
    @drivers = Driver.all
  end

  def show
  end

  def new
    @driver = Driver.new
  end

  def edit
  end

  def create
    @driver = Driver.new(driver_params)

    respond_to do |format|
      if @driver.save
          format.html { redirect_to @driver, notice: 'Driver was
           successfully created.' }
          format.json { render :show, status: :created, location: @driver }
      else
        format.html { render :new }
        format.json { render json: @driver.errors, status:
         :unprocessable_entity }
      end
    end
  end
  private

    def set_driver
      @driver = Driver.find(params[:id])
    end

    def driver_params
      params.require(:driver).permit(:first_name, :last_name, :email, :unit)
    end
end
</code>```

答:
If you want to create nested models on the same page. i.e. milages within trip page using accepts_nested_attributes_for, You can use cocoon gem.

https://github.com/nathanvda/cocoon

Drifting Ruby has a video that shows the process in detail that is easy to follow.
https://www.youtube.com/watch?v=56xjUOAAZY8

You can do it manually as well but it will require a little bit more work.
With cocoon you will do have a Driver Controller and Trip controller but you don't need a Milage controller since it is handled with nested_attributes via Trip Controller.

If you want to do it manually, you will need a bit of JavaScript. You can follow Ryan Bates RailsCast on this topic.
railscasts.com/episodes/196-nested-model-form-revised

Title: Proper model set up

Body:
I am new to stackoverflow, so my apologies if this is formatted poorly.

In my current project I have a model Driver, which has many trips.  Those trips have many mileages, backhauls, picks, drops and hours.  When I create a new trip, i want to be able to associate it to the driver, but I also want to be able to add the mileages, backhauls, picks and drops and hours on the same page.  I am unsure how to structure my routes for this.  I have been successful in creating a trip for a driver without adding on the additional models to the trip but from there I am stumped.  I have only created the mileage model/controller so far for what needs to be associated with the trip.  Any nudge in the right direction would be greatly appreciated.

Driver Model

class Driver < ApplicationRecord
  has_many :trips
end

Trip Model

class Trip < ApplicationRecord
  belongs_to :driver
  has_many :mileages
  accepts_nested_attributes_for :mileages
  default_scope {order(date: :asc)}
  validates :total, presence: true
  validates :date, presence: true
  validates_uniqueness_of :trip_number, :allow_nil => true, :allow_blank =>
  true

end

Mileage Model

class Mileage < ApplicationRecord
  belongs_to :trip
end

Trips controller

def index
  @trips = Trip.all
end

def show
end

def new
  @driver = Driver.find(params[:driver_id])
  @trip = Trip.new
end

def edit
end

def create
  @driver = Driver.find(params[:driver_id])
  @trip = Trip.new(trip_params)
  @driver.trips.create(trip_params)
  respond_to do |format|
    if @driver.trips.create(trip_params)
      flash[:notice] = "Trip successfully created"
      redirect_to new_driver_trip_path(@driver)
    else
      flash[:warning] = "Unable to create trip"
      redirect_to new_driver_trip_path(@driver)
    end
end
private

  def set_trip
    @trip = Trip.find(params[:id])
  end

  def trip_params
    params.require(:trip).permit(:trip_number, :date, :driver_id, :total)
  end

end

Mileage Controller

  def new
    @mileage = Mileage.new
  end

  def create
    @mileage.create(mileage_params)
  end

  private

    def mileage_params
      params.require(:mileage).permit(:miles, :rate, :total)
    end
  end
end

Driver Controller

  def index
    @drivers = Driver.all
  end

  def show
  end

  def new
    @driver = Driver.new
  end

  def edit
  end

  def create
    @driver = Driver.new(driver_params)

    respond_to do |format|
      if @driver.save
          format.html { redirect_to @driver, notice: 'Driver was
           successfully created.' }
          format.json { render :show, status: :created, location: @driver }
      else
        format.html { render :new }
        format.json { render json: @driver.errors, status:
         :unprocessable_entity }
      end
    end
  end
  private

    def set_driver
      @driver = Driver.find(params[:id])
    end

    def driver_params
      params.require(:driver).permit(:first_name, :last_name, :email, :unit)
    end
end


问:
Python Selenium: Unable to click on a user name field
I am attempting to locate a user name field that does not have an ID or other locator that I can easily find using Selenium Web Driver.

Using Chrome's Inspect Element, the HTML for this object is as follows

```<code><div aria-hidden="true" style="cursor:text" data-bind="text: hintText, css: hintCss" class="placeholder">someone@example.com</div>
</code>```

What would be the best way to locate this page object?

Thanks

答:
Either of these should work (if it is the first div-element of this class type)

```<code>driver.find_element_by_class_name('placeholder')
driver.find_element_by_css_selector('div.placeholder')
driver.find_element_by_xpath("//div[@class='placeholder']")
</code>```

If there are more elements which match use the find_elements version of the methods and use the index of the returned list the get the element you need.

Body:
I am attempting to locate a user name field that does not have an ID or other locator that I can easily find using Selenium Web Driver.

Using Chrome's Inspect Element, the HTML for this object is as follows

someone@example.com

What would be the best way to locate this page object?

Thanks

Body:
Either of these should work (if it is the first div-element of this class type)

driver.find_element_by_class_name('placeholder')
driver.find_element_by_css_selector('div.placeholder')
driver.find_element_by_xpath("//div[@class='placeholder']")

If there are more elements which match use the find_elements version of the methods and use the index of the returned list the get the element you need.


问:
jquery simple modal help on window load
I'm trying to something like this  if in the html there is a div called "#super" load it in the simple modal if not do nothing.  I managed to do this with the my skill :D which is none:  to load the modal if the #super exists, but it still loads doesn't matter if it exitst or not.  PLease help  I'm absolute noob on jquery.

```<code>    if( $('super') ){    $("#super").modal({onOpen: function (dialog) {

    dialog.overlay.fadeIn('slow', function () {
        dialog.container.slideDown('slow', function () {
            dialog.data.fadeIn('slow');
        });
    });
}});
</code>```

I'm using this jquery plugin link text

答:
The problem is this check

```<code>if( $('#super') )
</code>```

will always return true, since the jQuery function always return a jQuery object which is not a false value.

Instead try this

```<code>if( $('#super').length > 0 )
</code>```

Title: jquery simple modal help on window load

Body:
I'm trying to something like this  if in the html there is a div called "#super" load it in the simple modal if not do nothing.  I managed to do this with the my skill :D which is none:  to load the modal if the #super exists, but it still loads doesn't matter if it exitst or not.  PLease help  I'm absolute noob on jquery.

    if( $('super') ){    $("#super").modal({onOpen: function (dialog) {

    dialog.overlay.fadeIn('slow', function () {
        dialog.container.slideDown('slow', function () {
            dialog.data.fadeIn('slow');
        });
    });
}});

I'm using this jquery plugin link text

Body:
The problem is this check

if( $('#super') )

will always return true, since the jQuery function always return a jQuery object which is not a false value.

Instead try this

if( $('#super').length > 0 )


问:
Shiny conditionalpanel to bypass multiple dependent sliders
I have a relatively complex app that I am building and I want users to drag coupled sliders to set the weights for some calculations. These should always sum to 100%. I looked at this and that but I have real problems with reactivity and isolation and the updateslider option seems to work for up two sliders.

So instead, I transposed the problem. I will message the user that the weights need to sum to 100% if they don't and show the example plotoutput if they do. Simples right? Well, no, as the conditions are not conforming. After looking at this and this and this, I cannot get it to work.

I provide a reproducible example below to demonstrate this problem - I suspect it's because of my awkwardness with reactivity and observers in shiny.

```<code>library(shiny)

# Define UI for application that draws a histogram
ui <- fluidPage(

   # Application title
   titlePanel("testing 1 2 3"),

   # Sidebar with a slider input for number of bins
   sidebarLayout(
      sidebarPanel(
      ),

      # Show a plot of the generated distribution
      mainPanel(
         fluidRow(

            column(width = 2,
                   offset = 0,
                   align = "center",
                   sliderInput(inputId = "sld_1",
                               label = "weight",
                               min = 0,
                               max = 1,
                               value = 0.25,
                               step = 0.05,
                               animate = TRUE)
                   ,
                   sliderInput(inputId = "sld_2",
                               label = "weight",
                               min = 0,
                               max = 1,
                               value = 0.25,
                               step = 0.05,
                               animate = TRUE)
                   ,
                   sliderInput(inputId = "sld_3",
                               label = "weight",
                               min = 0,
                               max = 1,
                               value = 0.25,
                               step = 0.05,
                               animate = TRUE)
                   ,
                   sliderInput(inputId = "sld_4",
                               label = "weight",
                               min = 0,
                               max = 1,
                               value = 0.25,
                               step = 0.05,
                               animate = TRUE)
            ) #slider columns
            ,
            column(width = 9,
                   offset = 0,
                   align = "center",
                   conditionalPanel(
                      condition = "output.myCondition == FALSE",
                      textOutput(outputId = "distPrint")
                   ) #conditional1
                   ,
                   conditionalPanel(
                      condition = "output.myCondition == TRUE",
                      plotOutput(outputId = "distPlot")
                   ) #conditional2
            ) #column
         )#fluidrow
      )
   )
)

# Define server logic required to draw a histogram
server <- function(input, output,session) {

   dister <-   reactive({
      if( !is.null(input$sld_1) &&
          !is.null(input$sld_2) &&
          !is.null(input$sld_3) &&
          !is.null(input$sld_4) &&
          sum(input$sld_1,input$sld_2,input$sld_3,input$sld_4)==1
      ) {
         rnorm(input$sld_1*1000)
      } else {c(0,1,2,3,4,5)}
   })

   output.myCondition <- reactive({
      if( !is.null(input$sld_1) &&
          !is.null(input$sld_2) &&
          !is.null(input$sld_3) &&
          !is.null(input$sld_4) &&
          sum(input$sld_1,input$sld_2,input$sld_3,input$sld_4)==1
      ) {
              TRUE
      } else {FALSE}
   })

   output$distPlot <- renderPlot({
      x<-dister()
      hist(x)
   })

   output$distPrint <- renderText({
      print("The weights must sum to 100%")
   })
}

# Run the application
shinyApp(ui = ui, server = server)
</code>```

答:
Here is a slightly different approach, using the shinyjs package:

We create two div's, one for the plot (plotdiv) and one for the error (errordiv)

We create a reactiveVal to hold the ditribution

An observeEvent updates the reactiveVal only if our sliders change and they sum to 1. In that case, we hide the errordiv, and show the plotdiv. Otherwise, we show the error and hide the plot.

So:

```<code>library(shiny)
library(shinyjs)

# Define UI for application that draws a histogram
ui <- fluidPage(

  # Application title
  titlePanel("testing 1 2 3"),
  shinyjs::useShinyjs(),

  # Sidebar with a slider input for number of bins
  sidebarLayout(
    sidebarPanel(
    ),

    # Show a plot of the generated distribution
    mainPanel(
      fluidRow(

        column(width = 2,
               offset = 0,
               align = "center",
               sliderInput(inputId = "sld_1",
                           label = "weight",
                           min = 0,
                           max = 1,
                           value = 0.25,
                           step = 0.05,
                           animate = TRUE)
               ,
               sliderInput(inputId = "sld_2",
                           label = "weight",
                           min = 0,
                           max = 1,
                           value = 0.25,
                           step = 0.05,
                           animate = TRUE)
               ,
               sliderInput(inputId = "sld_3",
                           label = "weight",
                           min = 0,
                           max = 1,
                           value = 0.25,
                           step = 0.05,
                           animate = TRUE)
               ,
               sliderInput(inputId = "sld_4",
                           label = "weight",
                           min = 0,
                           max = 1,
                           value = 0.25,
                           step = 0.05,
                           animate = TRUE)
        ) #slider columns
        ,
        column(width = 9,
               offset = 0,
               align = "center",
               div(id="plotdiv",
                   plotOutput(outputId = "distPlot")
               ),
               shinyjs::hidden(
                 div(id="errordiv",
                     p("The weights must sum to one!")
                 )
               )
        ) #column
      )#fluidrow
    )
  )
)

# Define server logic required to draw a histogram
server <- function(input, output,session) {

  dister <- reactiveVal()

  observeEvent({
    input$sld_1
    input$sld_2
    input$sld_3
    input$sld_4},{
      if( !is.null(input$sld_1) &&
          !is.null(input$sld_2) &&
          !is.null(input$sld_3) &&
          !is.null(input$sld_4) &&
          sum(input$sld_1,input$sld_2,input$sld_3,input$sld_4)==1
      ) {
        dister(rnorm(input$sld_1*1000))
        shinyjs::show("plotdiv")
        shinyjs::hide("errordiv")
      }
      else
      {
        shinyjs::hide("plotdiv")
        shinyjs::show("errordiv")
      }
    })

  output$distPlot <- renderPlot({
    x<-dister()
    hist(x)
  })

}

# Run the application
shinyApp(ui = ui, server = server)
</code>```

I hope this helps!

Body:
I have a relatively complex app that I am building and I want users to drag coupled sliders to set the weights for some calculations. These should always sum to 100%. I looked at this and that but I have real problems with reactivity and isolation and the updateslider option seems to work for up two sliders.

So instead, I transposed the problem. I will message the user that the weights need to sum to 100% if they don't and show the example plotoutput if they do. Simples right? Well, no, as the conditions are not conforming. After looking at this and this and this, I cannot get it to work.

I provide a reproducible example below to demonstrate this problem - I suspect it's because of my awkwardness with reactivity and observers in shiny.

library(shiny)

# Define UI for application that draws a histogram
ui <- fluidPage(

   # Application title
   titlePanel("testing 1 2 3"),

   # Sidebar with a slider input for number of bins
   sidebarLayout(
      sidebarPanel(
      ),

      # Show a plot of the generated distribution
      mainPanel(
         fluidRow(

            column(width = 2,
                   offset = 0,
                   align = "center",
                   sliderInput(inputId = "sld_1",
                               label = "weight",
                               min = 0,
                               max = 1,
                               value = 0.25,
                               step = 0.05,
                               animate = TRUE)
                   ,
                   sliderInput(inputId = "sld_2",
                               label = "weight",
                               min = 0,
                               max = 1,
                               value = 0.25,
                               step = 0.05,
                               animate = TRUE)
                   ,
                   sliderInput(inputId = "sld_3",
                               label = "weight",
                               min = 0,
                               max = 1,
                               value = 0.25,
                               step = 0.05,
                               animate = TRUE)
                   ,
                   sliderInput(inputId = "sld_4",
                               label = "weight",
                               min = 0,
                               max = 1,
                               value = 0.25,
                               step = 0.05,
                               animate = TRUE)
            ) #slider columns
            ,
            column(width = 9,
                   offset = 0,
                   align = "center",
                   conditionalPanel(
                      condition = "output.myCondition == FALSE",
                      textOutput(outputId = "distPrint")
                   ) #conditional1
                   ,
                   conditionalPanel(
                      condition = "output.myCondition == TRUE",
                      plotOutput(outputId = "distPlot")
                   ) #conditional2
            ) #column
         )#fluidrow
      )
   )
)

# Define server logic required to draw a histogram
server <- function(input, output,session) {

   dister <-   reactive({
      if( !is.null(input$sld_1) &&
          !is.null(input$sld_2) &&
          !is.null(input$sld_3) &&
          !is.null(input$sld_4) &&
          sum(input$sld_1,input$sld_2,input$sld_3,input$sld_4)==1
      ) {
         rnorm(input$sld_1*1000)
      } else {c(0,1,2,3,4,5)}
   })

   output.myCondition <- reactive({
      if( !is.null(input$sld_1) &&
          !is.null(input$sld_2) &&
          !is.null(input$sld_3) &&
          !is.null(input$sld_4) &&
          sum(input$sld_1,input$sld_2,input$sld_3,input$sld_4)==1
      ) {
              TRUE
      } else {FALSE}
   })

   output$distPlot <- renderPlot({
      x<-dister()
      hist(x)
   })

   output$distPrint <- renderText({
      print("The weights must sum to 100%")
   })
}

# Run the application
shinyApp(ui = ui, server = server)

Body:
Here is a slightly different approach, using the shinyjs package:

We create two div's, one for the plot (plotdiv) and one for the error (errordiv)

We create a reactiveVal to hold the ditribution

An observeEvent updates the reactiveVal only if our sliders change and they sum to 1. In that case, we hide the errordiv, and show the plotdiv. Otherwise, we show the error and hide the plot.

So:

library(shiny)
library(shinyjs)

# Define UI for application that draws a histogram
ui <- fluidPage(

  # Application title
  titlePanel("testing 1 2 3"),
  shinyjs::useShinyjs(),

  # Sidebar with a slider input for number of bins
  sidebarLayout(
    sidebarPanel(
    ),

    # Show a plot of the generated distribution
    mainPanel(
      fluidRow(

        column(width = 2,
               offset = 0,
               align = "center",
               sliderInput(inputId = "sld_1",
                           label = "weight",
                           min = 0,
                           max = 1,
                           value = 0.25,
                           step = 0.05,
                           animate = TRUE)
               ,
               sliderInput(inputId = "sld_2",
                           label = "weight",
                           min = 0,
                           max = 1,
                           value = 0.25,
                           step = 0.05,
                           animate = TRUE)
               ,
               sliderInput(inputId = "sld_3",
                           label = "weight",
                           min = 0,
                           max = 1,
                           value = 0.25,
                           step = 0.05,
                           animate = TRUE)
               ,
               sliderInput(inputId = "sld_4",
                           label = "weight",
                           min = 0,
                           max = 1,
                           value = 0.25,
                           step = 0.05,
                           animate = TRUE)
        ) #slider columns
        ,
        column(width = 9,
               offset = 0,
               align = "center",
               div(id="plotdiv",
                   plotOutput(outputId = "distPlot")
               ),
               shinyjs::hidden(
                 div(id="errordiv",
                     p("The weights must sum to one!")
                 )
               )
        ) #column
      )#fluidrow
    )
  )
)

# Define server logic required to draw a histogram
server <- function(input, output,session) {

  dister <- reactiveVal()

  observeEvent({
    input$sld_1
    input$sld_2
    input$sld_3
    input$sld_4},{
      if( !is.null(input$sld_1) &&
          !is.null(input$sld_2) &&
          !is.null(input$sld_3) &&
          !is.null(input$sld_4) &&
          sum(input$sld_1,input$sld_2,input$sld_3,input$sld_4)==1
      ) {
        dister(rnorm(input$sld_1*1000))
        shinyjs::show("plotdiv")
        shinyjs::hide("errordiv")
      }
      else
      {
        shinyjs::hide("plotdiv")
        shinyjs::show("errordiv")
      }
    })

  output$distPlot <- renderPlot({
    x<-dister()
    hist(x)
  })

}

# Run the application
shinyApp(ui = ui, server = server)

I hope this helps!


问:
Convert a List of Strings into a single String using ArrayUtils in java
I have below code

```<code>List<String> test = new ArrayList<String>();
test.add("one");
test.add("two");
test.add("three");
</code>```

Need output as "one,two,three" in a single string using Array Utils. Need a single line solution.

答:
```<code>       List<String> test = new ArrayList<String>();
        test.add("one");
        test.add("two");
        test.add("three");
       Iterator it = test.iterator();

       while(it.hasNext()){

      String s=it.next();
      StringBuilder sb = new StringBuilder();

     sb.append(s);
}
</code>```

Body:
I have below code

List<String> test = new ArrayList<String>();
test.add("one");
test.add("two");
test.add("three");

Need output as "one,two,three" in a single string using Array Utils. Need a single line solution.


问:
How to unregister device backbutton on moving to model or when moving to another page from sidemenu
I have override the registerbackbuttonaction inside my home page and unregistering my backbutton action ionViewDidLeave it works fine when i push to another page from my home page.

Issues:

I have written this.nav.push("pagename") inside my app.component.ts file For side menu items. because of this i am not able to go back onclick of device back button after over-ridding the device back button.

When i remove the over-ridding back button function from my entire app i am getting the output what i am expecting.

This also happens when on opening model page also my lifecycle event is not triggering.

Here is my code

ts file

```<code>initializeBackButtonCustomHandler(){

    let self = this
    this.platform.ready().then(() => {

    self.unregisterBackButtonAction = self.platform.registerBackButtonAction(() => {
      if (this.menuCtrl.getOpen() != null) {
        this.menuCtrl.close();
        return
      }else if(this.modal && this.modal.index === 0) {
        console.log("invoking modal value")
        /* closes modal */
        // this.modal.dismiss();
        this.viewCtrl.dismiss();
        return

      }
      this.toast = this.toastCtrl.create({
        message: "Press back again to exit the app",
        position: 'bottom',
        duration: 1500
      });
        this.toast.present();
        this.clickCount = this.clickCount + 1;
        this.toast.onDidDismiss(() => {
          this.clickCount = 0;
        })

      if(this.clickCount == 2){
        this.clickCount = 0;
        this.toast.dismiss();
          this.platform.exitApp();
      }
    }, 10)
  });
  }

  ionViewDidEnter(){
    this.initializeBackButtonCustomHandler();

}

  ionViewDidLeave() {
    this.unregisterBackButtonAction && this.unregisterBackButtonAction();

}
</code>```

The above code works fine when i do push it is unregistering the back button but for model and sidemenu part it is not working.

答:
Instead of unregistering the back button you can pop to your previous page when it can go back and exit the app when it has no back state. I guess the following code could help you achieve this,</p>

```<code>platform.registerBackButtonAction(()=>{
          let nav = this.app.getActiveNav();
            if(nav.canGoBack()){
              nav.pop();
            }else{
                let ismodalopened=this.app._appRoot._modalPortal.getActive();
                if(ismodalopened){
                  app.navPop();
                }else{

                    let alertController = this.alertCtrl.create({
                      title: 'Confirm',
                      message: 'Are you sure you want to exit?',
                      buttons: [{
                        text: "Exit",
                        handler: () => { platform.exitApp(); }
                      }, {
                        text: "Cancel",
                        role: 'cancel'
                      }]
                    })
                    alertController.present();
                }
            }
        });
</code>```

Body:
I have override the registerbackbuttonaction inside my home page and unregistering my backbutton action ionViewDidLeave it works fine when i push to another page from my home page.

Issues:

I have written this.nav.push("pagename") inside my app.component.ts file For side menu items. because of this i am not able to go back onclick of device back button after over-ridding the device back button.

When i remove the over-ridding back button function from my entire app i am getting the output what i am expecting.

This also happens when on opening model page also my lifecycle event is not triggering.

Here is my code

ts file

initializeBackButtonCustomHandler(){

    let self = this
    this.platform.ready().then(() => {

    self.unregisterBackButtonAction = self.platform.registerBackButtonAction(() => {
      if (this.menuCtrl.getOpen() != null) {
        this.menuCtrl.close();
        return
      }else if(this.modal && this.modal.index === 0) {
        console.log("invoking modal value")
        /* closes modal */
        // this.modal.dismiss();
        this.viewCtrl.dismiss();
        return

      }
      this.toast = this.toastCtrl.create({
        message: "Press back again to exit the app",
        position: 'bottom',
        duration: 1500
      });
        this.toast.present();
        this.clickCount = this.clickCount + 1;
        this.toast.onDidDismiss(() => {
          this.clickCount = 0;
        })

      if(this.clickCount == 2){
        this.clickCount = 0;
        this.toast.dismiss();
          this.platform.exitApp();
      }
    }, 10)
  });
  }

  ionViewDidEnter(){
    this.initializeBackButtonCustomHandler();

}

  ionViewDidLeave() {
    this.unregisterBackButtonAction && this.unregisterBackButtonAction();

}

The above code works fine when i do push it is unregistering the back button but for model and sidemenu part it is not working.

Body:
Instead of unregistering the back button you can pop to your previous page when it can go back and exit the app when it has no back state. I guess the following code could help you achieve this,

platform.registerBackButtonAction(()=>{
          let nav = this.app.getActiveNav();
            if(nav.canGoBack()){
              nav.pop();
            }else{
                let ismodalopened=this.app._appRoot._modalPortal.getActive();
                if(ismodalopened){
                  app.navPop();
                }else{

                    let alertController = this.alertCtrl.create({
                      title: 'Confirm',
                      message: 'Are you sure you want to exit?',
                      buttons: [{
                        text: "Exit",
                        handler: () => { platform.exitApp(); }
                      }, {
                        text: "Cancel",
                        role: 'cancel'
                      }]
                    })
                    alertController.present();
                }
            }
        });


问:
Tinymce doesn't save the text as it was submitted
I have set tinymce in my website so that the user can use the toolbar while writing text as well as to upload a picture. Unfortunately I have realized the problem related to tinymce.

```<code>$(document).ready(function() {
 tinymce.init({
 selector: "#market-product_info, #market-delivery_info, #market-facility_info",
 language_url: '/frontend/web/js/tinymce/langs/zh_CN.js',
 menubar:true,
 statusbar: true,
 relative_urls : false,
 branding: false,
 plugins: [
           "advlist autolink lists link image charmap print preview hr anchor pagebreak",
           "searchreplace wordcount visualblocks visualchars code fullscreen",
           "save table contextmenu directionality emoticons template paste textcolor",
           "emoticons template paste textcolor colorpicker textpattern",
           "save"
 ],
  toolbar1: "undo redo | bold italic underline | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | forecolor |styleselect | link unlink anchor |link image | preview code ",
  image_advtab: true,
  // enable title field in the Image dialog

 image_title: true,
  // enable automatic uploads of images represented by blob or data URIs
  automatic_uploads: true,
  // URL of our upload handler (for more details check: https://www.tinymce.com/docs/configure/file-image-upload/#images_upload_url)
  // images_upload_url: 'postAcceptor.php',
  // here we add custom filepicker only to Image dialog
  file_picker_types: 'image',
  // and here's our custom image picker
  file_picker_callback: function(cb, value, meta) {
    var input = document.createElement('input');
    input.setAttribute('type', 'file');
    input.setAttribute('accept', 'image/*');

    // Note: In modern browsers input[type="file"] is functional without
    // even adding it to the DOM, but that might not be the case in some older
    // or quirky browsers like IE, so you might want to add it to the DOM
    // just in case, and visually hide it. And do not forget do remove it
    // once you do not need it anymore.

    input.onchange = function() {
      var file = this.files[0];

      var reader = new FileReader();
      reader.onload = function () {
        // Note: Now we need to register the blob in TinyMCEs image blob
        // registry. In the next release this part hopefully won't be
        // necessary, as we are looking to handle it internally.
        var id = 'blobid' + (new Date()).getTime();
        var blobCache =  tinymce.activeEditor.editorUpload.blobCache;
        var base64 = reader.result.split(',')[1];
        var blobInfo = blobCache.create(id, file, base64);
        blobCache.add(blobInfo);

        // call the callback and populate the Title field with the file name
        cb(blobInfo.blobUri(), { title: file.name });
      };
      reader.readAsDataURL(file);
    };
    input.click();
  }
  });
});
</code>```

The problem is when a user creates a table or uses any toolbar options (bold, italic, text color or etc.) and submits, in the database the information is received as the user inserted, however if the user wants to edit the info and resubmit, then in the textarea all the words are just displayed without any table or any toolbar features. I would like to have it in a way that the user finds his/her text as it was submitted before if he/she wants to edit the text.

答:
Have you try to create textarea :

```<code><textarea style="width: 100%;" name="description" id="description"></textarea>
</code>```

then set content of the textarea :

```<code>$('#description').html('<table><tr><th>user info table</th></tr></table>');
</code>```

then init the tinyMCE :

```<code>tinyMCE.init({
    // input tinyMCE options
    ...
});
</code>```

Body:
I have set tinymce in my website so that the user can use the toolbar while writing text as well as to upload a picture. Unfortunately I have realized the problem related to tinymce.

$(document).ready(function() {
 tinymce.init({
 selector: "#market-product_info, #market-delivery_info, #market-facility_info",
 language_url: '/frontend/web/js/tinymce/langs/zh_CN.js',
 menubar:true,
 statusbar: true,
 relative_urls : false,
 branding: false,
 plugins: [
           "advlist autolink lists link image charmap print preview hr anchor pagebreak",
           "searchreplace wordcount visualblocks visualchars code fullscreen",
           "save table contextmenu directionality emoticons template paste textcolor",
           "emoticons template paste textcolor colorpicker textpattern",
           "save"
 ],
  toolbar1: "undo redo | bold italic underline | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | forecolor |styleselect | link unlink anchor |link image | preview code ",
  image_advtab: true,
  // enable title field in the Image dialog

 image_title: true,
  // enable automatic uploads of images represented by blob or data URIs
  automatic_uploads: true,
  // URL of our upload handler (for more details check: https://www.tinymce.com/docs/configure/file-image-upload/#images_upload_url)
  // images_upload_url: 'postAcceptor.php',
  // here we add custom filepicker only to Image dialog
  file_picker_types: 'image',
  // and here's our custom image picker
  file_picker_callback: function(cb, value, meta) {
    var input = document.createElement('input');
    input.setAttribute('type', 'file');
    input.setAttribute('accept', 'image/*');

    // Note: In modern browsers input[type="file"] is functional without
    // even adding it to the DOM, but that might not be the case in some older
    // or quirky browsers like IE, so you might want to add it to the DOM
    // just in case, and visually hide it. And do not forget do remove it
    // once you do not need it anymore.

    input.onchange = function() {
      var file = this.files[0];

      var reader = new FileReader();
      reader.onload = function () {
        // Note: Now we need to register the blob in TinyMCEs image blob
        // registry. In the next release this part hopefully won't be
        // necessary, as we are looking to handle it internally.
        var id = 'blobid' + (new Date()).getTime();
        var blobCache =  tinymce.activeEditor.editorUpload.blobCache;
        var base64 = reader.result.split(',')[1];
        var blobInfo = blobCache.create(id, file, base64);
        blobCache.add(blobInfo);

        // call the callback and populate the Title field with the file name
        cb(blobInfo.blobUri(), { title: file.name });
      };
      reader.readAsDataURL(file);
    };
    input.click();
  }
  });
});

The problem is when a user creates a table or uses any toolbar options (bold, italic, text color or etc.) and submits, in the database the information is received as the user inserted, however if the user wants to edit the info and resubmit, then in the textarea all the words are just displayed without any table or any toolbar features. I would like to have it in a way that the user finds his/her text as it was submitted before if he/she wants to edit the text.

Body:
Have you try to create textarea :

<textarea style="width: 100%;" name="description" id="description"></textarea>

then set content of the textarea :

$('#description').html('<table><tr><th>user info table</th></tr></table>');

then init the tinyMCE :

tinyMCE.init({
    // input tinyMCE options
    ...
});


问:
Regex: How to detect a pattern if an undesired sub pattern comes before the pattern?
I'm new to regex and I'm trying to use Java to detect a sequence of either: lowercase, uppercase, or digits, but not JUST digits separated by periods.
Restriction: No consecutive periods.

The sample String I have is: @@@951.324.1@@@foo1.bar2.123proccess.this.subString

I currently have the following regex: ((\p{Alnum})+\.)+(\p{Alnum})+

I'm trying to have the pattern recognize foo1.bar2.123proccess.this.subString but my regex gives me 951.324.1 since it's a sub-pattern of the pattern I defined.

How would I go about detecting the subString foo1.bar2.123proccess.this.subString

I would imagine the general nature would be: The entire returned String should have at least 1 lowercase or uppercase char, but I'm hopelessly confused on how I would detect that in the String.

答:
You may use

```<code>String rx = "\\d+(?:\\.\\d+)+|(\\p{Alnum}+(?:\\.\\p{Alnum}+)+)";
</code>```

See the regex demo (pattern adjusted since regex101 does not support Java POSIX character class syntax)

The point is to match and skip dot-separated digit chunks, and only match and capture what you need. See Java demo:

```<code>String s = "@@@951.324.1@@@abc.123";
String rx = "\\d+(?:\\.\\d+)+|(\\p{Alnum}+(?:\\.\\p{Alnum}+)+)";
Pattern pattern = Pattern.compile(rx);
Matcher matcher = pattern.matcher(s);
while (matcher.find()){
    if (matcher.group(1) != null) {
        System.out.println(matcher.group(1));
    }
}  // => abc.123
</code>```

Body:
You may use

String rx = "\\d+(?:\\.\\d+)+|(\\p{Alnum}+(?:\\.\\p{Alnum}+)+)";

See the regex demo (pattern adjusted since regex101 does not support Java POSIX character class syntax)

The point is to match and skip dot-separated digit chunks, and only match and capture what you need. See Java demo:

String s = "@@@951.324.1@@@abc.123";
String rx = "\\d+(?:\\.\\d+)+|(\\p{Alnum}+(?:\\.\\p{Alnum}+)+)";
Pattern pattern = Pattern.compile(rx);
Matcher matcher = pattern.matcher(s);
while (matcher.find()){
    if (matcher.group(1) != null) {
        System.out.println(matcher.group(1));
    }
}  // => abc.123


问:
c# When I export db data to excel file, file name was broken
When I try to export DB data to excel file,

English file name is no problem, but when I try to set file name Korean

file name was broken.

But when I open exported excel file, it opens well and all texts are also okay.

How can I fix save file name code?

My code is below.

btnSaveClick Event

```<code>  protected void btnMemSaveExcel_Click(object sender, EventArgs e)
    {
        //set Excel header as string[] ExcelHeaders

        try
        {
            //Get siteTitle to use Excel file name.
            string siteTitle = SPContext.Current.Site.OpenWeb().Title;

            //some codes..
            ExcelExport(Page.Response, ds.Tables[0], siteTitle + "_MemberList", siteTitle + "_MemberList", ExcelHeader, true)
        }
    }
</code>```

Excel Export

```<code>private static void ExcelExport(HttpResponse response, DataTable dataTable, string fileName, string sheetTitle, string[] colHeader, bool borderLine)
{
    ExcelWorkSheet ws = null;
    int rowNum = 1;

    if(dataTable != null && dataTable.Rows.Count > 0)
    {
        ExcelPackage pck = new ExcelPackage();
        ws = pck.WorkBook.Worksheets.Add(sheetTitle);

        //set header, set data, etc

        response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        response.AddHeader("content-disposition", string.Format("attachment; filename={0}.xlsx", fileName));

        response.BinaryWrite(pck.GetAsByteArray());
        response.End();
    }
}
</code>```

答:
I solved that problem.

Added new line

```<code>string fileSaveName = HttpUtility.UrlPathEncode("fileName.TrimEnd());
</code>```

And modify code

```<code>response.AddHeader("content-dispositon", string.Format("attachment; filename={0}.xlsx", fileSaveName));
</code>```

Body:
When I try to export DB data to excel file,

English file name is no problem, but when I try to set file name Korean

file name was broken.

But when I open exported excel file, it opens well and all texts are also okay.

How can I fix save file name code?

My code is below.

btnSaveClick Event

  protected void btnMemSaveExcel_Click(object sender, EventArgs e)
    {
        //set Excel header as string[] ExcelHeaders

        try
        {
            //Get siteTitle to use Excel file name.
            string siteTitle = SPContext.Current.Site.OpenWeb().Title;

            //some codes..
            ExcelExport(Page.Response, ds.Tables[0], siteTitle + "_MemberList", siteTitle + "_MemberList", ExcelHeader, true)
        }
    }

Excel Export

private static void ExcelExport(HttpResponse response, DataTable dataTable, string fileName, string sheetTitle, string[] colHeader, bool borderLine)
{
    ExcelWorkSheet ws = null;
    int rowNum = 1;

    if(dataTable != null && dataTable.Rows.Count > 0)
    {
        ExcelPackage pck = new ExcelPackage();
        ws = pck.WorkBook.Worksheets.Add(sheetTitle);

        //set header, set data, etc

        response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        response.AddHeader("content-disposition", string.Format("attachment; filename={0}.xlsx", fileName));

        response.BinaryWrite(pck.GetAsByteArray());
        response.End();
    }
}

Body:
I solved that problem.

Added new line

string fileSaveName = HttpUtility.UrlPathEncode("fileName.TrimEnd());

And modify code

response.AddHeader("content-dispositon", string.Format("attachment; filename={0}.xlsx", fileSaveName));


问:
Need regex help to modify an XML file
I'm trying to modify an XML file which contains elements holding opening times for branches of a business.  The XML file is inconsistent because for some branches it has just an opening time and a closing time, others have an opening time, a closing time for lunch, a post-lunch opening time and a closing time.

Examples of both types below:

```<code><monday>10.00,17.00</monday>
<monday>09.00,12.30,13.30,17.00</monday>
</code>```

I want to reformat these strings to a better format such as the ones below:

```<code><monday>
  <open>10.00</open>
  <lunch></lunch>
  <close>17.00</close>
</monday>

<monday>
  <open>09.00</open>
  <lunch>12.30 - 13.30</lunch>
  <close>17.00</close>
</monday>
</code>```

I've been trying to use BBEdit regular expressions on my Mac to make the changes but I'm having difficulty, specifically I think because I'm not sure how I can get the regular expression to replace a subset of the text I tell it to match on.  For example, in pseudo code I want the regular expression to do this:

replace <monday>time1,time2</monday>

with <monday><open>time1</open><lunch></lunch><close>time2</close></monday>

replace <monday>time1,time2,time3,time4</monday>

with <monday><open>time1</open><lunch>time2 - time3</lunch><close>time4</close></monday>

I'm not too familiar with regular expressions so I'm making some errors I'm sure but so far I've been trying the below:

replace >#+\.#+,#+\.#+<
with ><open>#+\.#+<open><lunch></lunch><close>#+.\#+<

I understand this isn't going to work anyway because I'm telling the regex to replace the numbers it matches with #+ with the strings '#+' etc.

How can I achieve what I want to do by regex or other means and also how to I tell the regular expression to use an expression for comparison but only replace a subset of the characters it matches?

答:
Well I figured it out quicker than I expected.  Here are the expressions I used:

I used the following find string:

```<code>(<[a-z]+day>)([0-9]+\.[0-9]+),([0-9]+\.[0-9]+)(</[a-z]+day>)
</code>```

...and the following replace string:

```<code>\1<open>\2</open><lunch></lunch><close>\3</close>\4
</code>```

to match the following lines:

```<code><monday>10.00,17.00</monday>
</code>```

which resulted in the following output:

```<code><monday><open>10.00</open><lunch></lunch><close>17.00</close></monday>
</code>```

Title: Need regex help to modify an XML file

Body:
I'm trying to modify an XML file which contains elements holding opening times for branches of a business.  The XML file is inconsistent because for some branches it has just an opening time and a closing time, others have an opening time, a closing time for lunch, a post-lunch opening time and a closing time.

Examples of both types below:

<monday>10.00,17.00</monday>
<monday>09.00,12.30,13.30,17.00</monday>

I want to reformat these strings to a better format such as the ones below:

<monday>
  <open>10.00</open>
  <lunch></lunch>
  <close>17.00</close>
</monday>

<monday>
  <open>09.00</open>
  <lunch>12.30 - 13.30</lunch>
  <close>17.00</close>
</monday>

I've been trying to use BBEdit regular expressions on my Mac to make the changes but I'm having difficulty, specifically I think because I'm not sure how I can get the regular expression to replace a subset of the text I tell it to match on.  For example, in pseudo code I want the regular expression to do this:

replace <monday>time1,time2</monday>

with <monday><open>time1</open><lunch></lunch><close>time2</close></monday>

replace <monday>time1,time2,time3,time4</monday>

with <monday><open>time1</open><lunch>time2 - time3</lunch><close>time4</close></monday>

I'm not too familiar with regular expressions so I'm making some errors I'm sure but so far I've been trying the below:

replace >#+\.#+,#+\.#+<
with ><open>#+\.#+<open><lunch></lunch><close>#+.\#+<

I understand this isn't going to work anyway because I'm telling the regex to replace the numbers it matches with #+ with the strings '#+' etc.

How can I achieve what I want to do by regex or other means and also how to I tell the regular expression to use an expression for comparison but only replace a subset of the characters it matches?

Body:
Well I figured it out quicker than I expected.  Here are the expressions I used:

I used the following find string:

(<[a-z]+day>)([0-9]+\.[0-9]+),([0-9]+\.[0-9]+)(</[a-z]+day>)

...and the following replace string:

\1<open>\2</open><lunch></lunch><close>\3</close>\4

to match the following lines:

<monday>10.00,17.00</monday>

which resulted in the following output:

<monday><open>10.00</open><lunch></lunch><close>17.00</close></monday>


问:
Weight Decay and input normalization
I'm new to tensorflow and find that the sample CNN programs are using weight decay to avoid huge weight while they do not always normalize the input in the first place.

Does the weight decay serve the same purpose as the input normalization?

What is the difference between them?

答:
Weight decay is a type of regularisation used to control overfitting of the model. Weight decay is more commonly known as L2 Normalisation. Weight decay is used more in common in shallow learning algorithms like linear regression, logistic regression etc. In deep learning (ex: which uses CNN), weight decay is not so common. In fact other regularisation methods like dropout is used.

Input normalisation on the other hand refers to zero centering your input data and limiting the range of the input data. This procedure helps in quick convergence of the data.

There is no general fixed rule on how this two concepts has to be applied. Hence, you may have seen some variations of this two concepts.

Title: Weight Decay and input normalization


问:
Div background-image have x Scroll that i need to remove
I have a div that should have a background-image. The image resolution is high, I need it to take the width/height of the screen size viewport. Scrolling up and down is OK.

The issue is that i am having scroll right/left, i need it removed so that the image fills the whole screen without any x scroll. I put overflow-x:hidden; but the scroll remains. Even overflow:hidden; didn't do the trick.

```<code>#bgImg{

background-image: linear-gradient(rgba(0, 0, 0, 0.7), rgba(0, 0, 0, 0.7)), url("images/header.jpg");
background-size: cover;
background-position: center;
/* background-repeat: no-repeat; */
height: 100vh;
max-width: 100vw;
overflow-x:hidden;
/* padding-bottom: 30px; */
}
</code>```

答:
It works good for me, but try to add margin 0 and padding 0 to your body tag.</p>

```<code>body{
  margin:0;
  padding:0;
}
</code>```

Body:
I have a div that should have a background-image. The image resolution is high, I need it to take the width/height of the screen size viewport. Scrolling up and down is OK.

The issue is that i am having scroll right/left, i need it removed so that the image fills the whole screen without any x scroll. I put overflow-x:hidden; but the scroll remains. Even overflow:hidden; didn't do the trick.

#bgImg{

background-image: linear-gradient(rgba(0, 0, 0, 0.7), rgba(0, 0, 0, 0.7)), url("images/header.jpg");
background-size: cover;
background-position: center;
/* background-repeat: no-repeat; */
height: 100vh;
max-width: 100vw;
overflow-x:hidden;
/* padding-bottom: 30px; */
}

Body:
It works good for me, but try to add margin 0 and padding 0 to your body tag.

body{
  margin:0;
  padding:0;
}


答:
You need to remove margin/padding from body element and apply the overflow property on parent container and not the element with the background (if needed) :

```<code>body {
    margin:0;
    padding:0;
}
</code>```

Title: Div background-image have x Scroll that i need to remove

Body:
You need to remove margin/padding from body element and apply the overflow property on parent container and not the element with the background (if needed) :

body {
    margin:0;
    padding:0;
}


问:
How to make a string interpreted as a condition with Python?
I need to use the following syntax to filter the list operations:

```<code>a = [ope for ope in operations if ope[0] == 1]
</code>```

The if statement condition is variable and may contain multiple conditions:

```<code>a = [ope for ope in operations if ope[0] == 1 and ope[1] == "test"]
</code>```

I use a function to build the condition and return it as a string:

```<code>>>>> c = makeCondition(**{"id": 1, "title": 'test'})
>>>> c
"ope[0] == 1 and ope[1] == 'test'"
</code>```

Is there a way to integrate the c variable into the list filtering? Something like this (of course, the c variable is evaluated as a string in the below example):

```<code> a = [ope for ope in operations if c]
</code>```

Thanks for help!

答: As commented, if you want to change the string to be considered as an expression, you can use eval(string).

Body:
I need to use the following syntax to filter the list operations:

a = [ope for ope in operations if ope[0] == 1]

The if statement condition is variable and may contain multiple conditions:

a = [ope for ope in operations if ope[0] == 1 and ope[1] == "test"]

I use a function to build the condition and return it as a string:

>>>> c = makeCondition(**{"id": 1, "title": 'test'})
>>>> c
"ope[0] == 1 and ope[1] == 'test'"

Is there a way to integrate the c variable into the list filtering? Something like this (of course, the c variable is evaluated as a string in the below example):

 a = [ope for ope in operations if c]

Thanks for help!


问:
A book that contains, Shor's algorithm, McEliece cryptosystem, Lattice-based cryptography, Discrete logarithm
I am looking for a book that contains descriptions of the topics: Shor's algorithm, McEliece cryptosystem, Lattice-based cryptography, Discrete logarithm; and possibly others.

Does anyone know a single book or a few that would contain there topics?

答:
There is "Post-Quantum Cryptography" published by Daniel J. Bernstein. The book is more of a general overview and doesn't go that far into details.
It contains sections about lattice based, hash based and code based cryptography.
Shor's algorithm as well as discrete logarithm aren't handled in depth, but there is a general overview.
I think the best way to get into the details is by studying the respective scientific papers.</p>


问:
How to simply fill a TableView for iPhone
I have got an UITableView. How to simply fill it with three elements, for example "e1", "e2", "e3" ?

答:
UITableView is a component that rewards study. Read the local doc pages on UITableView and its datasource and delegate protocols.
There is a table view programming guide in the docs as well. It is a good read.
Some of it took me a while to grok and I am still refining my approach each time I implement one.
Using the API and implementing the methods it requires, you should be able to bend it to your will.

Hellra1ser's example should push you in the right direction. Lookup those methods first, you will be using them alot.

OwnerDisplayName: bigzpanda

LastEditorDisplayName: Chris Hanson

OwnerDisplayName: Ryan Townshend

LastEditorDisplayName: Ryan Townshend


问:
UITextView autoscroll to last line
When writing in a UITextView more text than can fit entirely inside it, the text will scroll up and the cursor will often place itself one or two lines above the view's bottom line. This is a bit frustrating as I want my application to make good use of the entire height of the text view.

Basically what I want is to configure the UITextView to write up to it's lowest part and not use it just for scrolling.

I've seen some similar questions here, here and here. However I've not seen a proper solution yet.

Thanks

答:
excellent solution is in subclass UITextView add lines

```<code>-(void) setContentOffset:(CGPoint)contentOffset {
    [self setContentInset:UIEdgeInsetsZero];
    [super setContentOffset:contentOffset];
}
</code>```

It's work!

Title: UITextView autoscroll to last line

Body:
excellent solution is in subclass UITextView add lines

-(void) setContentOffset:(CGPoint)contentOffset {
    [self setContentInset:UIEdgeInsetsZero];
    [super setContentOffset:contentOffset];
}

It's work!


问:
Why can't gitlab-runner clone my project? (Incorrect hostname, failed to connect)
I set-up a Gitlab server and need to run tests Windows using gitlab-runner.exe.

The gitlab-runner's executor is set to shell, the config.toml looks like

```<code>concurrent = 1
check_interval = 0

[[runners]]
  name = "PC123"
  url = "http://1.2.3.4/ci"
  token = "cd2b093adc5ca09ea41ee4eadb0752"
  executor = "shell"
  [runners.cache]
</code>```

When the test is spawned on a commit it fails with

```<code>Cloning into 'C:/git/builds/ac70aeb9/0/test/myproject'...
fatal: unable to access 'http://gitlab-ci-token:xxxxxxxxxxxxxxxxxxxx@localhost/test/boundaries.git/': Failed to connect to localhost port 80: Connection refused
</code>```

I suppose the problem is the hostname "localhost" in the URL, which refers to the machine gitlab-runner is on. When I set-up the server in the beginning I used 'localhost' as the servers hostname. This was probably not the best idea. :)

In the meantime I changed this "localgit", but the URL does not adjust, it still shows "localhost". (Server restarted, gitlab-runner servive restart).

Could it be that the server's hostname is stored somewhere in the original repo that I cloned when the hostname was still localhost? .git/config shows the correct IP:

```<code>[remote "origin"]
    url = http://1.2.3.4/test/myproject.git
</code>```

I found another question (GitLab runner unable to clone repository via http) that mentions a way to add other hosts to gitlab-runner's config.toml, like

```<code>[runners.docker]
    extra_hosts = ["ci.mygitlab:127.0.0.1"]
</code>```

But I must use the shell executor, not docker.

答:
As described here, the solution is to replace the entry host: localhost in the Gitlab config file /home/git/gitlab/config/gitlab.yml with the IP address of the host.

Before replacing:

```<code>  gitlab:
    ## Web server settings (note: host is the FQDN, do not include http://)
    host: localhost
</code>```

After replacing:

```<code>  gitlab:
    ## Web server settings (note: host is the FQDN, do not include http://)
    host: 10.0.1.2
</code>```

Body:
I set-up a Gitlab server and need to run tests Windows using gitlab-runner.exe.

The gitlab-runner's executor is set to shell, the config.toml looks like

concurrent = 1
check_interval = 0

[[runners]]
  name = "PC123"
  url = "http://1.2.3.4/ci"
  token = "cd2b093adc5ca09ea41ee4eadb0752"
  executor = "shell"
  [runners.cache]

When the test is spawned on a commit it fails with

Cloning into 'C:/git/builds/ac70aeb9/0/test/myproject'...
fatal: unable to access 'http://gitlab-ci-token:xxxxxxxxxxxxxxxxxxxx@localhost/test/boundaries.git/': Failed to connect to localhost port 80: Connection refused

I suppose the problem is the hostname "localhost" in the URL, which refers to the machine gitlab-runner is on. When I set-up the server in the beginning I used 'localhost' as the servers hostname. This was probably not the best idea. :)

In the meantime I changed this "localgit", but the URL does not adjust, it still shows "localhost". (Server restarted, gitlab-runner servive restart).

Could it be that the server's hostname is stored somewhere in the original repo that I cloned when the hostname was still localhost? .git/config shows the correct IP:

[remote "origin"]
    url = http://1.2.3.4/test/myproject.git

I found another question (GitLab runner unable to clone repository via http) that mentions a way to add other hosts to gitlab-runner's config.toml, like

[runners.docker]
    extra_hosts = ["ci.mygitlab:127.0.0.1"]

But I must use the shell executor, not docker.

Body:
As described here, the solution is to replace the entry host: localhost in the Gitlab config file /home/git/gitlab/config/gitlab.yml with the IP address of the host.

Before replacing:

  gitlab:
    ## Web server settings (note: host is the FQDN, do not include http://)
    host: localhost

After replacing:

  gitlab:
    ## Web server settings (note: host is the FQDN, do not include http://)
    host: 10.0.1.2

ContentLicense: CC BY-SA 4.0


问:
How to use same method but to call different methods in response every time?
I have method InfoDetails(); I need to call that method in different methods but in response for that different methods to call other methods. So want i want is something like this:

```<code>InfoDetails(methodName){
  this.methodName(params);
}
</code>```

Any suggestion how can i do that?

答:
You can simply call the method passed as parameter but I would check if it’s of the type function just to be a bit more defensive </p>

```<code>InfoDetails(methodName, params){
    if(typeof methodName === ‘function’){
       methodName(params);
    }
}
</code>```

Body:
I have method InfoDetails(); I need to call that method in different methods but in response for that different methods to call other methods. So want i want is something like this:

InfoDetails(methodName){
  this.methodName(params);
}

Any suggestion how can i do that?

Body:
You can simply call the method passed as parameter but I would check if it’s of the type function just to be a bit more defensive

InfoDetails(methodName, params){
    if(typeof methodName === ‘function’){
       methodName(params);
    }
}


问:
Creating a Dictionary Composite Key out of Every Permutation in a String[] within a String[][]
I have a Dictionary<string,string> that is acting as the composite key for another Dictionary.

I also have some string[] arrays that contains the necessary strings to be used as the composite key.

For example:

```<code>//Dictionary that will use composite key
Dictionary<Dictionary<string, string>, decimal> lookUpDictionary = new Dictionary<Dictionary<string, string>, decimal>();

//The composite key dictionary
Dictionary<string, string> compositeKey = new Dictionary<string, string>();

//Array containing strings
string[] array1 = { "aa", "bb", "cc" };
string[] array2 = { "xx", "yy", "zz" };

//A container for the array of individual units
string[][] arrayOfArrays = {array1,array2};
</code>```

I would like to make the composite key out of every possible combination pair of strings within each array.  For example, I'd like to fill the compositeKey thats a Dictionary<string, string> with every permutation of the array1 string[]...Such as:

```<code>aa aa
aa bb
aa cc
bb aa
bb bb
bb cc
cc aa
cc bb
cc cc
</code>```

and for the second array:

```<code>xx xx
xx yy
xx zz
yy xx
yy yy
yy zz
zz xx
zz yy
zz zz
</code>```

What I have tried is this nested loop algorithm that seems to work for getting the permutations I want in the right order.

```<code>Dictionary<string, string> compositeKey = new Dictionary<string, string>();

string[] array1 = { "aa", "bb", "cc" };
string[] array2 = { "xx", "yy", "zz" };

string[][] arrayOfArrays = {array1,array2};

//for every string[] in the arrayofarrays[][]
foreach(string[] array in arrayOfArrays)
{
    //for every string in each of those string[] arrays in the arrayOfArrays[][]
    foreach(string word in array)
    {
        //get every combination including itself
        foreach(string wordsPair in array)
        {
            string[] permutation = { word, wordsPair };
            Console.WriteLine(permutation[0] + permutation[1]);
            try
            {
                //compositeKey.Add(permutation[0], permutation[1]);
                //string value = compositeKey[permutation[0]];
                //Console.WriteLine(value);
            }
            catch
            {

            }

        }

    }
}
</code>```

The section within the try catch block is where I am having trouble.  I can't seem to create the compositeKey correctly.  Is this because of the nested loop, or am I using dictionarys completely wrong.

Edit:  It would seem that I am trying to use dictionary in a wrong way.  Is there any suggestion on the type of datatype that should be used here?

Any advice is appreciated.

答:
When creating all possible combinations, you are looking for a Cartesian Join, in your case an array with itself. It can be easily implemented with a help of Linq

```<code>  string[] array1 = { "aa", "bb", "cc" };
  //string[] array2 = { "xx", "yy", "zz" };

  string[][] arrayOfArrays = array1
    .SelectMany(left => array1, (left, right) => new string[] { left, right })
    .ToArray();
</code>```

Test:

```<code>  string test = string.Join(Environment.NewLine, arrayOfArrays
    .Select(line => $"[{string.Join(", ", line)}]"));

  Console.WriteLine(test);
</code>```

Outcome:

```<code>[aa, aa]
[aa, bb]
[aa, cc]
[bb, aa]
[bb, bb]
[bb, cc]
[cc, aa]
[cc, bb]
[cc, cc]
</code>```

Please, notice, that you shouldn't use string[] as a key in a dictionary since array's implementation doesn't override GetHashCode and Equals:

```<code>   // Don't do this! Do not use string[] as a key...
   Dictionary<string[], string> demo = new Dictionary<string[], string>() {
     {new string[] {"a", "b"}, "c"},
   };

   string[] key = new string[] {"a", "b"};

   // ... And that's the reason why:
   if (!demo.ContainsKey(key))
     Console.WriteLine("Oops!");
</code>```

You may want to choose Tuple<string, string> instead:

```<code>  string[] array1 = { "aa", "bb", "cc" };

  Dictionary<Tuple<string, string>, string> dictionary = array1
    .SelectMany(left => array1, (left, right) => new Tuple<string, string>(left, right))
    .ToDictionary(item => item,
                  item => "value for " + string.Join(" & ", item.Item1, item.Item2));

  Console.WriteLine(string.Join(Environment.NewLine, dictionary));
</code>```

Outcome:

```<code>[(aa, aa), value for aa & aa]
[(aa, bb), value for aa & bb]
[(aa, cc), value for aa & cc]
[(bb, aa), value for bb & aa]
[(bb, bb), value for bb & bb]
[(bb, cc), value for bb & cc]
[(cc, aa), value for cc & aa]
[(cc, bb), value for cc & bb]
[(cc, cc), value for cc & cc]
</code>```

Body:
I have a Dictionary<string,string> that is acting as the composite key for another Dictionary.

I also have some string[] arrays that contains the necessary strings to be used as the composite key.

For example:

//Dictionary that will use composite key
Dictionary<Dictionary<string, string>, decimal> lookUpDictionary = new Dictionary<Dictionary<string, string>, decimal>();

//The composite key dictionary
Dictionary<string, string> compositeKey = new Dictionary<string, string>();

//Array containing strings
string[] array1 = { "aa", "bb", "cc" };
string[] array2 = { "xx", "yy", "zz" };

//A container for the array of individual units
string[][] arrayOfArrays = {array1,array2};

I would like to make the composite key out of every possible combination pair of strings within each array.  For example, I'd like to fill the compositeKey thats a Dictionary<string, string> with every permutation of the array1 string[]...Such as:

aa aa
aa bb
aa cc
bb aa
bb bb
bb cc
cc aa
cc bb
cc cc

and for the second array:

xx xx
xx yy
xx zz
yy xx
yy yy
yy zz
zz xx
zz yy
zz zz

What I have tried is this nested loop algorithm that seems to work for getting the permutations I want in the right order.

Dictionary<string, string> compositeKey = new Dictionary<string, string>();

string[] array1 = { "aa", "bb", "cc" };
string[] array2 = { "xx", "yy", "zz" };

string[][] arrayOfArrays = {array1,array2};

//for every string[] in the arrayofarrays[][]
foreach(string[] array in arrayOfArrays)
{
    //for every string in each of those string[] arrays in the arrayOfArrays[][]
    foreach(string word in array)
    {
        //get every combination including itself
        foreach(string wordsPair in array)
        {
            string[] permutation = { word, wordsPair };
            Console.WriteLine(permutation[0] + permutation[1]);
            try
            {
                //compositeKey.Add(permutation[0], permutation[1]);
                //string value = compositeKey[permutation[0]];
                //Console.WriteLine(value);
            }
            catch
            {

            }

        }

    }
}

The section within the try catch block is where I am having trouble.  I can't seem to create the compositeKey correctly.  Is this because of the nested loop, or am I using dictionarys completely wrong.

Edit:  It would seem that I am trying to use dictionary in a wrong way.  Is there any suggestion on the type of datatype that should be used here?

Any advice is appreciated.

Body:
When creating all possible combinations, you are looking for a Cartesian Join, in your case an array with itself. It can be easily implemented with a help of Linq

  string[] array1 = { "aa", "bb", "cc" };
  //string[] array2 = { "xx", "yy", "zz" };

  string[][] arrayOfArrays = array1
    .SelectMany(left => array1, (left, right) => new string[] { left, right })
    .ToArray();

Test:

  string test = string.Join(Environment.NewLine, arrayOfArrays
    .Select(line => $"[{string.Join(", ", line)}]"));

  Console.WriteLine(test);

Outcome:

[aa, aa]
[aa, bb]
[aa, cc]
[bb, aa]
[bb, bb]
[bb, cc]
[cc, aa]
[cc, bb]
[cc, cc]

Please, notice, that you shouldn't use string[] as a key in a dictionary since array's implementation doesn't override GetHashCode and Equals:

   // Don't do this! Do not use string[] as a key...
   Dictionary<string[], string> demo = new Dictionary<string[], string>() {
     {new string[] {"a", "b"}, "c"},
   };

   string[] key = new string[] {"a", "b"};

   // ... And that's the reason why:
   if (!demo.ContainsKey(key))
     Console.WriteLine("Oops!");

You may want to choose Tuple<string, string> instead:

  string[] array1 = { "aa", "bb", "cc" };

  Dictionary<Tuple<string, string>, string> dictionary = array1
    .SelectMany(left => array1, (left, right) => new Tuple<string, string>(left, right))
    .ToDictionary(item => item,
                  item => "value for " + string.Join(" & ", item.Item1, item.Item2));

  Console.WriteLine(string.Join(Environment.NewLine, dictionary));

Outcome:

[(aa, aa), value for aa & aa]
[(aa, bb), value for aa & bb]
[(aa, cc), value for aa & cc]
[(bb, aa), value for bb & aa]
[(bb, bb), value for bb & bb]
[(bb, cc), value for bb & cc]
[(cc, aa), value for cc & aa]
[(cc, bb), value for cc & bb]
[(cc, cc), value for cc & cc]


问:
[Python]; Parser error: Too many columns specified
I just want to read a simple .csv file with a header specifying the column types.
The following is the code:

```<code>import pandas as pd
url="https://www.dropbox.com/s/n6yt908tgetuq63/LasVegasTripAdvisorReviews-Dataset.csv?dl=0"
names=['User country','Nr. reviews','Nr. hotel reviews','Helpful
votes','Score','Period of stay','Traveler Type','Pool','Gym','Tennis
court','Spa','Casino','Free internet','Hotel name','Hotel stars','Nr.
rooms','User continent','Member years','Review month','Review weekday']
data=pd.read_csv(url, names=names, header=0, delimiter=';',
error_bad_lines=False)
print(data.shape)
</code>```

OUT:-

ParserError: Too many columns specified: expected 20 and found 2

P.S:The URL is public and can be accessed

答:
The problem is the URL doesn't directly lead to the .csv file. It leads to the entire html page.

You can see that by removing the names argument

pd.read_csv(url, header=0, delimiter=';', error_bad_lines=False)

This successfully executes, but when inspecting the returned values, you'll see html code and JavaScript scripts.

What you need to do is make sure you provide actual csv as input (try another source for the .csv file)

Body:
I just want to read a simple .csv file with a header specifying the column types.
The following is the code:

import pandas as pd
url="https://www.dropbox.com/s/n6yt908tgetuq63/LasVegasTripAdvisorReviews-Dataset.csv?dl=0"
names=['User country','Nr. reviews','Nr. hotel reviews','Helpful
votes','Score','Period of stay','Traveler Type','Pool','Gym','Tennis
court','Spa','Casino','Free internet','Hotel name','Hotel stars','Nr.
rooms','User continent','Member years','Review month','Review weekday']
data=pd.read_csv(url, names=names, header=0, delimiter=';',
error_bad_lines=False)
print(data.shape)

OUT:-

ParserError: Too many columns specified: expected 20 and found 2

P.S:The URL is public and can be accessed


问:
Saiku Mondrian Schema error - parentheses perhaps?
I'm using Mondrian xml schema for Saiku report (Pentaho 7.0) and when defining roles, Saiku throws errors whenever there are parentheses. (Actually from my different combo of testing it's the conclusion I came up with. No solid evidence.)
XML parser doesn't throw errors but when loading data cubes, Saiku doesn't like it.
For example

```<code>  <Role name="ABC-DEF.GHI(JKL)">
    <SchemaGrant access="none">
      <CubeGrant cube="Some Cube" access="all">
        <DimensionGrant dimension="[Measures]" access="all"/>
        <HierarchyGrant hierarchy="Some Hierarchy (with parentheses)" access="none">
        </HierarchyGrant>
      </CubeGrant>
     </SchemaGrant>
   </Role>
</code>```

Did anyone come across this issue?

答:
I agree with @monty_bean. Saiku may not give any feedback about what the error is, but looking at the tomcat pentaho log can give you some clues.
I had a similar problem, in my case a field name was misspelled. Saiku just refused to load the schema, but in the pentaho log the error was clear.

Also, if you try your schema in the "Schema workbench", try to execute an mdx sentence directly from the schema workbench. Error messages are there pretty clear too.

Body:
I'm using Mondrian xml schema for Saiku report (Pentaho 7.0) and when defining roles, Saiku throws errors whenever there are parentheses. (Actually from my different combo of testing it's the conclusion I came up with. No solid evidence.)
XML parser doesn't throw errors but when loading data cubes, Saiku doesn't like it.
For example

  <Role name="ABC-DEF.GHI(JKL)">
    <SchemaGrant access="none">
      <CubeGrant cube="Some Cube" access="all">
        <DimensionGrant dimension="[Measures]" access="all"/>
        <HierarchyGrant hierarchy="Some Hierarchy (with parentheses)" access="none">
        </HierarchyGrant>
      </CubeGrant>
     </SchemaGrant>
   </Role>

Did anyone come across this issue?


问:
bash script to batch truncate filenames in one dir
this question is somewhat unique among others asked.

i have a dir with a bunch of folders and they are named using periods to separate every word.

such as: foo.bar.2011.useless.words

the last two words are always the useless ones, so i would like to truncate starting with the second to last period.

not sure of the wording...

many thanks

答:
If your folders with dots are only one level deep, go with Ignacio's answer.  However, if you have folders that you want to rename that exist in subdirs such as /toplevel/subdir1/foo.bar.baz.blah/ then you'll need to use my find command below.  Unless you have Bash 4.x in which case you can use the shopt -s globstar option.

```<code>find /top/level/dir -type d -name '*.*.*' -exec sh -c 'for arg; do echo mv "$arg" "${arg%.*.*}"; done' _ {} +
</code>```

I added an echo in there so you can do a dry-run without making any changes. Remove the echo if you are satisfied with the output and run it again to make the changes permanent.

Edit
Removed my $tmp var by shamelessly stealing Ignacio's PE

Body:
If your folders with dots are only one level deep, go with Ignacio's answer.  However, if you have folders that you want to rename that exist in subdirs such as /toplevel/subdir1/foo.bar.baz.blah/ then you'll need to use my find command below.  Unless you have Bash 4.x in which case you can use the shopt -s globstar option.

find /top/level/dir -type d -name '*.*.*' -exec sh -c 'for arg; do echo mv "$arg" "${arg%.*.*}"; done' _ {} +

I added an echo in there so you can do a dry-run without making any changes. Remove the echo if you are satisfied with the output and run it again to make the changes permanent.

Edit
Removed my $tmp var by shamelessly stealing Ignacio's PE