问:
how to find date range between two dates in days format using linq c#
I have a requirement for generating report in form of 15 days,30 days,45 days.
I have to compare the list data which is coming from db with current date.example if difference is 5days. It is less than 15,so i should send to 15 days ,if >15 i should send to greater than 15etc.How to write linq query for this.can any one help on this please</p>

答:
I'm not sure that can be possible to make this in only one query.
But, I can propose you another solution.
Instead of one query, you can use one query for every case.
In order to compare date difference, you can use SqlFunctions Class.
For this, you should use :

```<code>   using System.Data.Objects.SqlClient;
</code>```

Here is the query for 5 days with an imaginary table and fields :

```<code>      var lstDiff5 = (from ro in dc.Commandes where
                   SqlFunctions.DateDiff("DD", ro.Cmd_PromisDate, DateTime.Now) <= 5
                   select ro).ToList();
</code>```

The DateDiff Function takes the date part (DD for days), the start date and the end date. In my case the start date is the current date.
And for 15 days :

```<code>                var lstDiff15 = (from ro in dc.Commandes where
                   SqlFunctions.DateDiff("DD", ro.Cmd_PromisDate, DateTime.Now) > 5 &&
                   SqlFunctions.DateDiff("DD", ro.Cmd_PromisDate, DateTime.Now) >= 15
                          select ro).ToList();
</code>```

You can change the operators > et >= depending your need.

At the end, you can fill your report using all of your lists or you can merge your lists into a new list in order to bind your report to your final list.

Body:
I'm not sure that can be possible to make this in only one query.
But, I can propose you another solution.
Instead of one query, you can use one query for every case.
In order to compare date difference, you can use SqlFunctions Class.
For this, you should use :

   using System.Data.Objects.SqlClient;

Here is the query for 5 days with an imaginary table and fields :

      var lstDiff5 = (from ro in dc.Commandes where
                   SqlFunctions.DateDiff("DD", ro.Cmd_PromisDate, DateTime.Now) <= 5
                   select ro).ToList();

The DateDiff Function takes the date part (DD for days), the start date and the end date. In my case the start date is the current date.
And for 15 days :

                var lstDiff15 = (from ro in dc.Commandes where
                   SqlFunctions.DateDiff("DD", ro.Cmd_PromisDate, DateTime.Now) > 5 &&
                   SqlFunctions.DateDiff("DD", ro.Cmd_PromisDate, DateTime.Now) >= 15
                          select ro).ToList();

You can change the operators > et >= depending your need.

At the end, you can fill your report using all of your lists or you can merge your lists into a new list in order to bind your report to your final list.


来源: stackexchange

问:
How to export Core Data entity to a CSV file
I'd like to be able to export my Core Data entity to a CSV file, to save application's data. I googled but found nothing.

My app uses only one entity with five attributes. These attributes are all strings except one that is a decimal number (with a comma or a point). How can I export this entity with all the attributes?

答:
You have to create a method to do this kind of operation, like this:

```<code>NSString *separator = @", ";
NSString *cvs = @"";
for (NSObject *object in arrayOfObject) {
        cvs = [NSString stringWithFormat:@"%@%@%@%@%@\n", cvs, [object att1], separator, [object att2], separator, [object att3]...];
}
//If you want to store in a file the CVS
[cvs writeToFile:pathToFile atomically:YES];
</code>```

I suggest you to try to avoid the "appending" system that I'm using, this kind of operation generate leaks in memory.
Instead of a stringWithFormat that rewrite the same var, use this method that has been very well written:
Shortcuts in Objective-C to concatenate NSStrings

You can also take a look at this library: https://github.com/davedelong/CHCSVParser
I never used it, but it looks very helpful for write/read CVS files.

ContentLicense: CC BY-SA 3.0

Body:
You have to create a method to do this kind of operation, like this:

NSString *separator = @", ";
NSString *cvs = @"";
for (NSObject *object in arrayOfObject) {
        cvs = [NSString stringWithFormat:@"%@%@%@%@%@\n", cvs, [object att1], separator, [object att2], separator, [object att3]...];
}
//If you want to store in a file the CVS
[cvs writeToFile:pathToFile atomically:YES];

I suggest you to try to avoid the "appending" system that I'm using, this kind of operation generate leaks in memory.
Instead of a stringWithFormat that rewrite the same var, use this method that has been very well written:
Shortcuts in Objective-C to concatenate NSStrings

You can also take a look at this library: https://github.com/davedelong/CHCSVParser
I never used it, but it looks very helpful for write/read CVS files.

ContentLicense: CC BY-SA 2.5


问:
"Waiting for device to come online". Running Android emulator from Android Studio
I'm having a problem where my emulator cannot start and I get this message "waiting for device to come online". Try to quit the emulator but cannot quit until some time. This keeps happening to me with the same emulator. Any idea how to solve this? Thank you.</p>

答:
Already answered in "waiting for target device to come online" in Android Studio 2.3

locate lib64 folder.Since i am running ubuntu 64 bit. In my case, its located under ~/Android/Sdk/emulator/lib64.

In terminal, Navigate to the ~/Android/Sdk/emulator/lib64 folder ,then run the following commands:

// Double Check to see if these are available

$ sudo apt-get install lib64stdc++6:i386

$ sudo apt-get install mesa-utils

// then move the libstdc++ file inside the folder libstdc++.bak

$ mv libstdc++/ libstdc++.bak

// And execute below command

$ ln -s /usr/lib64/libstdc++.so.6 libstdc++


问:
Select first row after goup
I have the below query which return the name of a class which is less than 20 and if there is no class less than 20 it adds a new one. the problem is that when I delete a user from the class which was full than this query returns two row.
I need to get only the first row that returns.</p>

```<code>SELECT exam_venue AS venue
  FROM application
 WHERE class_level = 1
   AND rownumber = 1
 GROUP
    BY venue
HAVING COUNT(id) < 20
</code>```

答:
An easy way can be the following :::</p>

```<code>SELECT TOP 1 exam_venue AS venue, COUNT(id)
FROM application
WHERE class_level = 1
GROUP BY venue
HAVING COUNT(id) < 20
</code>```

Title: Select first row after goup

Body:
I have the below query which return the name of a class which is less than 20 and if there is no class less than 20 it adds a new one. the problem is that when I delete a user from the class which was full than this query returns two row.
I need to get only the first row that returns.

SELECT exam_venue AS venue
  FROM application
 WHERE class_level = 1
   AND rownumber = 1
 GROUP
    BY venue
HAVING COUNT(id) < 20

Body:
An easy way can be the following :::

SELECT TOP 1 exam_venue AS venue, COUNT(id)
FROM application
WHERE class_level = 1
GROUP BY venue
HAVING COUNT(id) < 20


问:
Linq in from ObservableCollection in ObservableCollection
I am tring to get the value "thisValueIwant". Is there any possibility to get this value so easy? Or Maybe there is another solution for these 2 ObservableCollection</p>

```<code>public class Foo
{
    public int number { get; set; }
    public ObservableCollection<FooInFoo> Details { get; set; }
}

public class FooInFoo
{
    public string thisValueIwant { get; set; }
}

public class TestClass
{
    public void Test()
    {
        ObservableCollection<Foo> FooCollection = new ObservableCollection<Foo>();

        FooCollection.Add(new Foo{
            number =1,
            Details = new ObservableCollection<FooInFoo>{ new FooInFoo {thisValueIwant = "very important string"}}
        });

        string x = (from f in FooCollection
                    where f.number == 1
                    select ???)
    }
}
</code>```

答:
An ObservableCollection<T> is a Collection<T> which implements IEnumerable<T>. Therefore the fact that your FooCollection is an observable collection is not important, you can regard it as a sequence of Foo, an IEnumerable<Foo> and equally an IEnumerable<FooInFoo>

Your code will be like (sorry, I only know how to write in Method format)
In baby steps:

```<code>IEnumerable<Foo> AllFooWithNumber1 = FooCollection
   .Where(foo => foo.Number == 1);
</code>```

If you are certain there is exactly one continue with:

```<code>Foo fooWithNumber1 = AllFooWithNumber1.Single();
</code>```

Consider using SingleOrDefault if you are not certain that there is one.

Once you have the Foo that you want, you can select the Details:

```<code>IEnumerable<FooInFoo> detailsOfFooWithNumber1 = fooWithNumber1.Details;
FooInFoo detailIWant = detailsOfFooWithNumber1
   .Where(detail => some expression that uses detail...)
   .SingleOrDefault();

string thisValueIWant = defailtIWant.thisValueIWant;
</code>```

Or in one statement:

```<code>string thisValueIWant = FooCollection
   .Where(foo => foo.Number == 1)
   .Single()
   .Details
   .Where(detail => ...)
   .Single()
   .thisValueIWant;
</code>```

Problems might arise if you are not certain there is one Single element.

If you want to check foo.Number for a given value AND all details for some predicate, consider using Enumerable.SelectMany. This is used whenever you have sequences of sequences (arrays within arrays). With SelectMany you enumerate over all these inner arrays as if it was one array:

```<code>IEnumerable<string> valuesIWant = FooCollection
    .Where(foo => foo.Number == 1)
    .SelectMany(foo => foo.Details)
    // now you have one sequence of all FooInFoo that are Details within
    // Foo objects with Number 1
    .Where(detail => expression that selects the FooInFoo you want)
    .Select(detail => detail.thisValueIWant);
</code>```

Body:
I am tring to get the value "thisValueIwant". Is there any possibility to get this value so easy? Or Maybe there is another solution for these 2 ObservableCollection

public class Foo
{
    public int number { get; set; }
    public ObservableCollection<FooInFoo> Details { get; set; }
}

public class FooInFoo
{
    public string thisValueIwant { get; set; }
}

public class TestClass
{
    public void Test()
    {
        ObservableCollection<Foo> FooCollection = new ObservableCollection<Foo>();

        FooCollection.Add(new Foo{
            number =1,
            Details = new ObservableCollection<FooInFoo>{ new FooInFoo {thisValueIwant = "very important string"}}
        });

        string x = (from f in FooCollection
                    where f.number == 1
                    select ???)
    }
}

Body:
An ObservableCollection<T> is a Collection<T> which implements IEnumerable<T>. Therefore the fact that your FooCollection is an observable collection is not important, you can regard it as a sequence of Foo, an IEnumerable<Foo> and equally an IEnumerable<FooInFoo>

Your code will be like (sorry, I only know how to write in Method format)
In baby steps:

IEnumerable<Foo> AllFooWithNumber1 = FooCollection
   .Where(foo => foo.Number == 1);

If you are certain there is exactly one continue with:

Foo fooWithNumber1 = AllFooWithNumber1.Single();

Consider using SingleOrDefault if you are not certain that there is one.

Once you have the Foo that you want, you can select the Details:

IEnumerable<FooInFoo> detailsOfFooWithNumber1 = fooWithNumber1.Details;
FooInFoo detailIWant = detailsOfFooWithNumber1
   .Where(detail => some expression that uses detail...)
   .SingleOrDefault();

string thisValueIWant = defailtIWant.thisValueIWant;

Or in one statement:

string thisValueIWant = FooCollection
   .Where(foo => foo.Number == 1)
   .Single()
   .Details
   .Where(detail => ...)
   .Single()
   .thisValueIWant;

Problems might arise if you are not certain there is one Single element.

If you want to check foo.Number for a given value AND all details for some predicate, consider using Enumerable.SelectMany. This is used whenever you have sequences of sequences (arrays within arrays). With SelectMany you enumerate over all these inner arrays as if it was one array:

IEnumerable<string> valuesIWant = FooCollection
    .Where(foo => foo.Number == 1)
    .SelectMany(foo => foo.Details)
    // now you have one sequence of all FooInFoo that are Details within
    // Foo objects with Number 1
    .Where(detail => expression that selects the FooInFoo you want)
    .Select(detail => detail.thisValueIWant);


问:
What is the equivalent of location.replace() for Angular
What is the equivalent of location.replace() for Angular
to change the path without linkbutton</p>

答:
you can use navigate :)</p>

```<code>   constructor(private router: Router,private service: HeroService){}
   replace(hero: Hero) {
        this.router.navigate(['/hero', hero.id]);
   }
</code>```

Body:
you can use navigate :)

   constructor(private router: Router,private service: HeroService){}
   replace(hero: Hero) {
        this.router.navigate(['/hero', hero.id]);
   }


问:
Custom layout is not showing in a android app?
I have a created custom layout but it is not working. When I use include the layout instead of set com.samsung.android.app.spage.CustomView.WeatherStateView it is working ok. I found some answers like use the <merge> tag but it not working too, please help me:

weather_state_layout.xml

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/weather_state_main_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<TextView
    android:id="@+id/current_location"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="current location" />

<include layout="@layout/detail_info_frag_hourly_content" /></LinearLayout>
</code>```

WeatherStateView.java

```<code>public class WeatherStateView extends LinearLayout implements View.OnClickListener{
    private static final String TAG = "WeatherStateView";
    private TextView mCurrentLocation;
    private Context mContext;

    public WeatherStateView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public WeatherStateView(Context context) {
        super(context);
    }

    public WeatherStateView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initialize(context);
    }

    private void initialize(Context context) {
        mContext = context;
        LayoutInflater.from(context).inflate(R.layout.weather_state_layout, this);

        mCurrentLocation = (TextView) findViewById(R.id.current_location);
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int w = MeasureSpec.getSize(widthMeasureSpec);
        int h = MeasureSpec.getSize(heightMeasureSpec);

        int size = Math.min(w, h);
        setMeasuredDimension(size, size);
    }
}
</code>```

in main_layout.xml

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".WeatherModule.WeatherViewStateFragment">

    <CustomView.WeatherStateView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/weather_state_main_layout"
        android:orientation="vertical"
    />
</code>```

答:
You can use something like that
Simply give the cast to the view of included layout and then get it.</p>

```<code>View test1View = findViewById(R.id.yourincludedlayoutid);
TextView t1 = (TextView) test1View.findViewById(R.id.emiscode);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a created custom layout but it is not working. When I use include the layout instead of set com.samsung.android.app.spage.CustomView.WeatherStateView it is working ok. I found some answers like use the <merge> tag but it not working too, please help me:

weather_state_layout.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/weather_state_main_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<TextView
    android:id="@+id/current_location"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="current location" />

<include layout="@layout/detail_info_frag_hourly_content" /></LinearLayout>

WeatherStateView.java

public class WeatherStateView extends LinearLayout implements View.OnClickListener{
    private static final String TAG = "WeatherStateView";
    private TextView mCurrentLocation;
    private Context mContext;

    public WeatherStateView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public WeatherStateView(Context context) {
        super(context);
    }

    public WeatherStateView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initialize(context);
    }

    private void initialize(Context context) {
        mContext = context;
        LayoutInflater.from(context).inflate(R.layout.weather_state_layout, this);

        mCurrentLocation = (TextView) findViewById(R.id.current_location);
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int w = MeasureSpec.getSize(widthMeasureSpec);
        int h = MeasureSpec.getSize(heightMeasureSpec);

        int size = Math.min(w, h);
        setMeasuredDimension(size, size);
    }
}

in main_layout.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".WeatherModule.WeatherViewStateFragment">

    <CustomView.WeatherStateView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/weather_state_main_layout"
        android:orientation="vertical"
    />

Body:
You can use something like that
Simply give the cast to the view of included layout and then get it.

View test1View = findViewById(R.id.yourincludedlayoutid);
TextView t1 = (TextView) test1View.findViewById(R.id.emiscode);


问:
SQL Server design
I am trying to build a c# application with visual studio. One of my design problems is this:

A costumer creates a request(For some service), which will be stored on a "Requests Table" in the database.

Every company can make a "bid", where it will give the service for price X.

The student will then look at each request and choose the one which suits him best.

Thus, every "bid" needs to keep the Company name, and the bid price.

How can i store the "bids" on an SQL server?
I thought of creating a Table for each request which stores the bids, but it seems to take a lot of space.

Thanks!

答:
since you are new to sql serversDatabase Normalization forms

you should be aware of normalization forms and rest will be ok in terms of db design

Title: SQL Server design


问:
JMS and AMQP - RabbitMQ
I am trying to understand what JMS and how it is connected to AMQP terminology.
I know JMS is an API and AMQP is a protocol.

Here are my assumptions (and questions as well)

RabbitMQ uses AMQP protocol (rather implements AMQP protocol)

Java clients need to use AMQP protocol client libraries to connect / use RabbitMQ

Where does JMS API come into play here? JMS API should use AMQP client libraries to connect to RabbitMQ?

Usually we use JMS to connect Message brokers like RabbitMQ, ActiveMQ, etc. Then what is the default protocol used here instead of AMQP?

Some of the above may be dumb. :-) But trying to wrap my head around it.

答:
Where does JMS API come into play here? JMS API should use AMQP client libraries to connect to RabbitMQ?

JMS is an API, so some JMS API's are implemented over the AMQP protocol (like Apache QPID JMS) while most JMS APIs use other protocols. If the version of the AMQP protocol is the same, such a client should be able to communicate with another AMQP client.

Usually we use JMS to connect Message brokers like RabbitMQ, ActiveMQ, etc. Then what is the default protocol used here instead of AMQP?

It depends on your configuration of that JMS API. For ActiveMQ, it could be AMQP but by default it is 'openwire'

Title: JMS and AMQP - RabbitMQ


问:
JQuery modal dialog form that send data over https
I have already working modal login dialog. The problem is that if the origin page is loaded via http I still want to pass credentials to server via https. And of course I want to do with as little rewriting of working code as it can be.

I cannot use JSONP for my case because login data is passed to server via POST AJAX request.

Any ideas?

答:
The Same Origin Policy makes this impossible (at least in browsers which don't support cross domain XHR, which is enough).

(And since the host document is served over HTTP it is subject to interception and alteration on the wire, which would make the data vulnerable even if it was transported over SSL)


问:
Add value in Object Ionic 2
I have an Object:

```<code>public countriesSignup = [{
    name: 'countries',
    options: [
        {text: 'Customer', value: '1'},
    ]
}];
</code>```

My Final Object must be:

```<code>countriesSignup = [{
    name: 'countries',
    options: [
        {text: 'Customer', value: '1'},
        {text: 'Contractor', value: '2'},
    ]
}];
</code>```

How i can add from Controller? I try this:

```<code>this.countriesSignup['options'] = [{text: 'Contractor', value: '2'}] ;
</code>```

答:
You can directly use .push since options is an array

```<code>this.countriesSignup[0].options.push({text: 'Contractor', value: '2'});
</code>```

Title: Add value in Object Ionic 2

Body:
I have an Object:

public countriesSignup = [{
    name: 'countries',
    options: [
        {text: 'Customer', value: '1'},
    ]
}];

My Final Object must be:

countriesSignup = [{
    name: 'countries',
    options: [
        {text: 'Customer', value: '1'},
        {text: 'Contractor', value: '2'},
    ]
}];

How i can add from Controller? I try this:

this.countriesSignup['options'] = [{text: 'Contractor', value: '2'}] ;

Body:
You can directly use .push since options is an array

this.countriesSignup[0].options.push({text: 'Contractor', value: '2'});


问:
Routing Conflict in Codeigniter application with other assets in root folder
Hi I have Codeigniter Web App.

I am Facing conflict between my route and an asset(Image or some file) with exact name as my route name.

My asset is opening in browser when i am trying to access my route. I know the solution can be achieved with htaccess but i simply not getting it.

Any help would be appreciated.

Check my Folder Structure Below:

```<code>Root
 - application
 - system
 - assets
   event.png
   list.html
</code>```

.htaccess:

```<code>RewriteEngine On
Options -Indexes
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ http://%1/$1 [R]
</code>```

My route is www.example.com/event/event-name

I am facing issue here.

答:
Find and replace usages of event.png, and rename it!

OR, reconfigure your route. You can use regex to ensure your route doesn't accept a .png in it. See here https://www.codeigniter.com/userguide3/general/routing.html

Body:
Hi I have Codeigniter Web App.

I am Facing conflict between my route and an asset(Image or some file) with exact name as my route name.

My asset is opening in browser when i am trying to access my route. I know the solution can be achieved with htaccess but i simply not getting it.

Any help would be appreciated.

Check my Folder Structure Below:

Root
 - application
 - system
 - assets
   event.png
   list.html

.htaccess:

RewriteEngine On
Options -Indexes
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ http://%1/$1 [R]

My route is www.example.com/event/event-name

I am facing issue here.


问:
Openvswitch change header field
I want add new field openvswitch pattern. My openvswitch (/var/log/openvswitch/ovs-vswitch.log) looking like follow ;

```<code>2017-05-21T18:00:06.572Z|00105|rconn|WARN|s2<->tcp:192.168.29.87:6633: connection failed (Network is unreachable)
2017-05-21T18:00:07.572Z|00106|stream_tcp|ERR|tcp:192.168.29.87:6633: connect: Network is unreachable
2017-05-21T18:00:07.572Z|00107|rconn|WARN|s1<->tcp:192.168.29.87:6633: connection failed (Network is unreachable)
2017-05-21T18:00:07.572Z|00108|stream_tcp|ERR|tcp:192.168.29.87:6633: connect: Network is unreachable
2017-05-21T18:00:07.572Z|00109|rconn|WARN|s2<->tcp:192.168.29.87:6633: connection failed (Network is unreachable)
2017-05-21T18:00:08.248Z|00110|bridge|WARN|could not open network device s1-eth2 (No such device)
2017-05-21T18:00:08.257Z|00111|bridge|WARN|could not open network device s1-eth1 (No such device)
</code>```

I want to add switchID  this file. Can I make that? Otherwise  this is impossible.

Have a good day everybody.

答:
what it's your meaning about openvswitch header?

for your log about, the error is about the port is not present,
you must add port to bridge that you make,

example:
the output of ifconfig is : enp3s0 and enp3s1
you want to add those port to ovs bridge

```<code>ovs-vsctl --may-exist add-br ovs-br #add ovs bridge name ovs-br
ovs-vsctl --may-exist add-port ovs-br enp3s0 #add enp3s0 to ovs-br
ovs-vsctl --may-exist add-port ovs-br enp3s1
</code>```

Title: Openvswitch change header field

Body:
I want add new field openvswitch pattern. My openvswitch (/var/log/openvswitch/ovs-vswitch.log) looking like follow ;

2017-05-21T18:00:06.572Z|00105|rconn|WARN|s2<->tcp:192.168.29.87:6633: connection failed (Network is unreachable)
2017-05-21T18:00:07.572Z|00106|stream_tcp|ERR|tcp:192.168.29.87:6633: connect: Network is unreachable
2017-05-21T18:00:07.572Z|00107|rconn|WARN|s1<->tcp:192.168.29.87:6633: connection failed (Network is unreachable)
2017-05-21T18:00:07.572Z|00108|stream_tcp|ERR|tcp:192.168.29.87:6633: connect: Network is unreachable
2017-05-21T18:00:07.572Z|00109|rconn|WARN|s2<->tcp:192.168.29.87:6633: connection failed (Network is unreachable)
2017-05-21T18:00:08.248Z|00110|bridge|WARN|could not open network device s1-eth2 (No such device)
2017-05-21T18:00:08.257Z|00111|bridge|WARN|could not open network device s1-eth1 (No such device)

I want to add switchID  this file. Can I make that? Otherwise  this is impossible.

Have a good day everybody.

Body:
what it's your meaning about openvswitch header?

for your log about, the error is about the port is not present,
you must add port to bridge that you make,

example:
the output of ifconfig is : enp3s0 and enp3s1
you want to add those port to ovs bridge

ovs-vsctl --may-exist add-br ovs-br #add ovs bridge name ovs-br
ovs-vsctl --may-exist add-port ovs-br enp3s0 #add enp3s0 to ovs-br
ovs-vsctl --may-exist add-port ovs-br enp3s1


问:
How to hide a navigation bar from first ViewController in Swift?
How can I hide a navigation bar from first ViewController or a particular ViewController in swift?

I used the following code in viewDidLoad():

```<code>override func viewDidLoad() {
    super.viewDidLoad()
    self.navigationController?.isNavigationBarHidden = true
}
</code>```

and also on viewWillAppear:

```<code>override func viewWillAppear(animated: Bool) {
    self.navigationController?.isNavigationBarHidden = true
}
</code>```

Both methods hide the navigation controller from all ViewControllers.

答:
You can do it from the window controller (Swift3)</p>

```<code>class WindowController: NSWindowController {

    override func windowDidLoad() {
        super.windowDidLoad()

        window?.titleVisibility = .hidden
    }
}
</code>```

Body:
How can I hide a navigation bar from first ViewController or a particular ViewController in swift?

I used the following code in viewDidLoad():

override func viewDidLoad() {
    super.viewDidLoad()
    self.navigationController?.isNavigationBarHidden = true
}

and also on viewWillAppear:

override func viewWillAppear(animated: Bool) {
    self.navigationController?.isNavigationBarHidden = true
}

Both methods hide the navigation controller from all ViewControllers.

Body:
You can do it from the window controller (Swift3)

class WindowController: NSWindowController {

    override func windowDidLoad() {
        super.windowDidLoad()

        window?.titleVisibility = .hidden
    }
}


问:
rails respond_to in controller rescue block
respond_to not working inside controller rescue block:

```<code>def create
  respond_to do | format |
    format.json { render json: SomeManager.new(some_params).json }
    format.html do
      SomeManager.new(some_params)
      render :new, notice: 'it worked'
    end
  end
rescue => e
  respond_to do | format |
    format.json { render json: {error: 'did not work because reasons'}.to_json, status: :forbidden }
    format.html { render :new, alert: 'did not work because reasons' }
  end
end
</code>```

^ Controller for API which can respond to API json uploads, or manual uploads using UI.

答:
For better readability, use begin .. rescue like this instead:

```<code>def create
  respond_to do | format |
    begin
      format.json { render json: SomeManager.new(some_params).json }
      format.html do
        SomeManager.new(some_params)
        render :new, notice: 'it worked'
      end
    rescue => e
      format.json { render json: {error: 'did not work because reasons'}.to_json, status: :forbidden }
      format.html { render :new, alert: 'did not work because reasons' }
    end
  end
end
</code>```

I think it shall work.

Body:
respond_to not working inside controller rescue block:

def create
  respond_to do | format |
    format.json { render json: SomeManager.new(some_params).json }
    format.html do
      SomeManager.new(some_params)
      render :new, notice: 'it worked'
    end
  end
rescue => e
  respond_to do | format |
    format.json { render json: {error: 'did not work because reasons'}.to_json, status: :forbidden }
    format.html { render :new, alert: 'did not work because reasons' }
  end
end

^ Controller for API which can respond to API json uploads, or manual uploads using UI.

Body:
For better readability, use begin .. rescue like this instead:

def create
  respond_to do | format |
    begin
      format.json { render json: SomeManager.new(some_params).json }
      format.html do
        SomeManager.new(some_params)
        render :new, notice: 'it worked'
      end
    rescue => e
      format.json { render json: {error: 'did not work because reasons'}.to_json, status: :forbidden }
      format.html { render :new, alert: 'did not work because reasons' }
    end
  end
end

I think it shall work.


问:
How to speed up the display of a slider on wordpress?
I create a website that contains many sliders using revolution slider on wordpress. The problem that when I access to my website, the display of the sliders is very slow. How can I fix them to will be displayed in the same time as the website? </p>

答: You need to give more information. It  could  be  your  slider,  it could be your images..... First thing i would do is compress you images. Do you need the sliders executing on page load,  if not turn them off and  use directional arrows. If that doesn't work run a Javascript minimmisation test, and if needs be find a plugin with GREAT reviews and minimise your site. Be sure to back up your site first though. Sliders will slow down your website bottom line. After you do all that run a speed test on your website and make sure its below 3.3 secs if you want  to  be found in search engines.</p>


问:
How can I change the token format of ReplaceTokens filter in gradle?
I have tokens in the file in a bash format looking something like this:

```<code>PASSWORD=$PASSWORD
</code>```

How can I change ReplaceTokens filter so that it would respect the bash format?

```<code>copy{
  into something
  from somethingelse
  filter(ReplaceTokens, tokens: [PASSWORD:'123456'])
}
</code>```

答:
The solution is to use expand property of a copy task:

https://docs.gradle.org/3.4/dsl/org.gradle.api.tasks.Copy.html#org.gradle.api.tasks.Copy:expand(java.util.Map)

```<code>task copyProductionConfig(type: Copy) {
  from 'source'
  include 'config.properties'
  into 'build/war/WEB-INF/config'
  expand([
    databaseHostname: 'db.company.com',
    version: versionId,
    buildNumber: (int)(Math.random() * 1000),
    date: new Date()
  ])
}
</code>```

Body:
I have tokens in the file in a bash format looking something like this:

PASSWORD=$PASSWORD

How can I change ReplaceTokens filter so that it would respect the bash format?

copy{
  into something
  from somethingelse
  filter(ReplaceTokens, tokens: [PASSWORD:'123456'])
}

Body:
The solution is to use expand property of a copy task:

https://docs.gradle.org/3.4/dsl/org.gradle.api.tasks.Copy.html#org.gradle.api.tasks.Copy:expand(java.util.Map)

task copyProductionConfig(type: Copy) {
  from 'source'
  include 'config.properties'
  into 'build/war/WEB-INF/config'
  expand([
    databaseHostname: 'db.company.com',
    version: versionId,
    buildNumber: (int)(Math.random() * 1000),
    date: new Date()
  ])
}


问:
"Percent" Style Formatting in Excel-VBA
Have n sheets which have been selected and I am trying to apply the "percent' style to all for a range of cell selection.
However only the  first sheet gets formatted. Other formatting styles that I am using work perfectly on all sheets. Only "percent" seems to be working only in the first sheet! Is there a specific reason for this? Pasting my Code snippet below: Thanks in advance for your help</p>

```<code>Range(Cells(143, 2), Cells(146, MarketRangeColumn + 10)).Select
Selection.Style = "Percent"
Range(Cells(100, 2), Cells(142, MarketRangeColumn + 10)).Select
Selection.Style = "Comma"
Selection.numberformat = "_(* #,##0.0_);_(* (#,##0.0);_(* ""-""??_);_(@_)"
Selection.numberformat = "_(* #,##0_);_(* (#,##0);_(* ""-""??_);_(@_)"
</code>```

答: If you have multiple sheets selected, applying a Style only affects the cells on the active sheet. Applying a NumberFormat will affect all sheets, so you should use that rather than the Style, or loop through each sheet.</p>

Title: "Percent" Style Formatting in Excel-VBA

Body:
Have n sheets which have been selected and I am trying to apply the "percent' style to all for a range of cell selection.
However only the  first sheet gets formatted. Other formatting styles that I am using work perfectly on all sheets. Only "percent" seems to be working only in the first sheet! Is there a specific reason for this? Pasting my Code snippet below: Thanks in advance for your help

Range(Cells(143, 2), Cells(146, MarketRangeColumn + 10)).Select
Selection.Style = "Percent"
Range(Cells(100, 2), Cells(142, MarketRangeColumn + 10)).Select
Selection.Style = "Comma"
Selection.numberformat = "_(* #,##0.0_);_(* (#,##0.0);_(* ""-""??_);_(@_)"
Selection.numberformat = "_(* #,##0_);_(* (#,##0);_(* ""-""??_);_(@_)"


问:
How to create SQL multiple count count query by date?
I have a query that selects counts group by department.

```<code>select department, count(*) group by department
</code>```

This returns two columns data result. I wonder if select cout, count by today and count by this month same query.

```<code>Department  Total  Today  ThisMonth
AAA         40     8      23
BBB         20     6      11
</code>```

答:
```<code>select
  department,
  count(*) as total,
  count(*) filter (where datecolumn = current_date) as count_for_today,
  count(*) filter (where date_trunc('month', datecolumn) = date_trunc('month', current_date)) as count_for_month
from
  your_table
group by
  department
</code>```

FILTER clause

date_trunc function

Body:
I have a query that selects counts group by department.

select department, count(*) group by department

This returns two columns data result. I wonder if select cout, count by today and count by this month same query.

Department  Total  Today  ThisMonth
AAA         40     8      23
BBB         20     6      11

Body:
select
  department,
  count(*) as total,
  count(*) filter (where datecolumn = current_date) as count_for_today,
  count(*) filter (where date_trunc('month', datecolumn) = date_trunc('month', current_date)) as count_for_month
from
  your_table
group by
  department

FILTER clause

date_trunc function


问:
which data structure should I use in java to store duplicate values?
Which is the best data structure to store duplicate values in java? And how easy is to retrieve values from it!?

thanks
EDIT #1 I am reading contents from 1000 files, and I want to put each files content as tokens in some data structure. I used Hashtable but i am not able to view many words when I am doing that. thats why I want a data structure which can store the duplicate values.

答: theres lack of info to properly answer this qn.. but anyway, hashmaps could do the trick. retrieval of values can be done in constant time on average..</p>


问:
QCombobox write "HELLO" when press backspace
i want intercept signal when i press on a Qcombobox->linEdit(), key Backpace and clear all text.
I have seen on web and i write this code, but it dont work. It seem that keypressevent function not is invoked.. Some tips???</p>

```<code> MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent), ui(new Ui::MainWindow)
    {
        ui->setupUi(this);
        ui->comboBox->addItem("11");
        ui->comboBox->addItem("21");
        ui->comboBox->addItem("32");
        ui->comboBox->addItem("41");
        ui->comboBox->addItem("54");
    }

bool MainWindow::eventFilter(QObject *obj, QEvent *event)
{
  if (obj == ui->comboBox) {
     if (event->type() == QEvent::KeyPress) {
         QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event);
         qDebug()<<"Ciao";
         if (keyEvent->key() == Qt::Key_Backspace)
         {
             ui->comboBox->clearEditText();
             return true;
         }
  }
     // pass the event on to the parent class
     return QMainWindow::eventFilter(obj, event);
}
}
MainWindow::~MainWindow()
{
    delete ui;
}
</code>```

Body:
i want intercept signal when i press on a Qcombobox->linEdit(), key Backpace and clear all text.
I have seen on web and i write this code, but it dont work. It seem that keypressevent function not is invoked.. Some tips???

 MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent), ui(new Ui::MainWindow)
    {
        ui->setupUi(this);
        ui->comboBox->addItem("11");
        ui->comboBox->addItem("21");
        ui->comboBox->addItem("32");
        ui->comboBox->addItem("41");
        ui->comboBox->addItem("54");
    }

bool MainWindow::eventFilter(QObject *obj, QEvent *event)
{
  if (obj == ui->comboBox) {
     if (event->type() == QEvent::KeyPress) {
         QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event);
         qDebug()<<"Ciao";
         if (keyEvent->key() == Qt::Key_Backspace)
         {
             ui->comboBox->clearEditText();
             return true;
         }
  }
     // pass the event on to the parent class
     return QMainWindow::eventFilter(obj, event);
}
}
MainWindow::~MainWindow()
{
    delete ui;
}

Body: Add ui->comboBox->installEventFilter(this);


问:
When writing to the Windows Event Log, is it possible to create a custom link text for URLs?
I'm just using the vanilla EventLog.WriteEntry method:

```<code>        EventLog.WriteEntry(EVENT_SOURCE, message, EventLogEntryType.Error, id);
</code>```

Here's how the message shows up in the Event Log, with the links in the parenthesis working just fine, but it's ugly:

Example 1:

Please contact us via email (mailto:some@example.com) or online (http://example.com).

Here's how the message shows up in the Event Log, with the HTML "markup", doesn't even handle it:

Example 2:

```<code>Please contact us via <a href="mailto:some@example.com">email</a> or <a href="http://example.com">online</a>.
</code>```

This is how I would like the message to show up, but with "email" and "online" as the link texts:

Example 3:

Please contact us via email or online.

I've tried the ... HTML tags with no success.

答: Not supported as far as I know.  If the ugly way is giving you clickable links, just stick with that.</p>

Body:
I'm just using the vanilla EventLog.WriteEntry method:

        EventLog.WriteEntry(EVENT_SOURCE, message, EventLogEntryType.Error, id);

Here's how the message shows up in the Event Log, with the links in the parenthesis working just fine, but it's ugly:

Example 1:

Please contact us via email (mailto:some@example.com) or online (http://example.com).

Here's how the message shows up in the Event Log, with the HTML "markup", doesn't even handle it:

Example 2:

Please contact us via email or online.

This is how I would like the message to show up, but with "email" and "online" as the link texts:

Example 3:

Please contact us via email or online.

I've tried the ... HTML tags with no success.


问:
Getting error while calling one sendOTP API using PHP
I am getting  error while calling one API using PHP.

Error:

```<code>Warning: include(): http:// wrapper is disabled in the server configuration by allow_url_include=0 in /opt/lampp/htdocs/test/otp.php on line 8

Warning: include(http://api.msg91.com/api/sendotp.php?authkey="15529*************"&mobile="9937229853"&message="Your verification code is:1111"&sender="Subhrajyoti"&otp="1111"): failed to open stream: no suitable wrapper could be found in /opt/lampp/htdocs/test/otp.php on line 8

Warning: include(): Failed opening 'http://api.msg91.com/api/sendotp.php?authkey="15529*************"&mobile="9937229853"&message="Your verification code is:1111"&sender="Subhrajyoti"&otp="1111"' for inclusion (include_path='.:/opt/lampp/lib/php') in /opt/lampp/htdocs/test/otp.php on line 8
</code>```

Here is my code:

```<code>$authkey="15529*************";
$mobile=9937229853;
$code=1111;
$message="Your verification code is:".$code;
$sender="Subhrajyoti";
$otp=1111;
include ('http://api.msg91.com/api/sendotp.php?authkey="'.$authkey.'"&mobile="'.$mobile.'"&message="'.$message.'"&sender="'.$sender.'"&otp="'.$otp.'"');
</code>```

Here I am trying to send OTP but getting those message. Here I need to send OTP and get the response.

答:
you can use CURL or file_get_contents.

```<code>$response = file_get_contents('http://api.msg91.com/api/sendotp.php?authkey="'.$authkey.'"&mobile="'.$mobile.'"&message="'.$message.'"&sender="'.$sender.'"&otp="'.$otp.'"');
$response = json_decode($response);
</code>```

or
using cURL:

```<code>$ch = curl_init();
$data=array('authkey'=>$authkey,'mobile'=>$mobile,'message'=>$message);//all parameter
curl_setopt($ch, CURLOPT_URL, 'http://api.msg91.com/api/sendotp.php');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$result = curl_exec($ch);
print_r($result);
curl_close($ch);
</code>```

Body:
I am getting  error while calling one API using PHP.

Error:

Warning: include(): http:// wrapper is disabled in the server configuration by allow_url_include=0 in /opt/lampp/htdocs/test/otp.php on line 8

Warning: include(http://api.msg91.com/api/sendotp.php?authkey="15529*************"&mobile="9937229853"&message="Your verification code is:1111"&sender="Subhrajyoti"&otp="1111"): failed to open stream: no suitable wrapper could be found in /opt/lampp/htdocs/test/otp.php on line 8

Warning: include(): Failed opening 'http://api.msg91.com/api/sendotp.php?authkey="15529*************"&mobile="9937229853"&message="Your verification code is:1111"&sender="Subhrajyoti"&otp="1111"' for inclusion (include_path='.:/opt/lampp/lib/php') in /opt/lampp/htdocs/test/otp.php on line 8

Here is my code:

$authkey="15529*************";
$mobile=9937229853;
$code=1111;
$message="Your verification code is:".$code;
$sender="Subhrajyoti";
$otp=1111;
include ('http://api.msg91.com/api/sendotp.php?authkey="'.$authkey.'"&mobile="'.$mobile.'"&message="'.$message.'"&sender="'.$sender.'"&otp="'.$otp.'"');

Here I am trying to send OTP but getting those message. Here I need to send OTP and get the response.

Body:
you can use CURL or file_get_contents.

$response = file_get_contents('http://api.msg91.com/api/sendotp.php?authkey="'.$authkey.'"&mobile="'.$mobile.'"&message="'.$message.'"&sender="'.$sender.'"&otp="'.$otp.'"');
$response = json_decode($response);

or
using cURL:

$ch = curl_init();
$data=array('authkey'=>$authkey,'mobile'=>$mobile,'message'=>$message);//all parameter
curl_setopt($ch, CURLOPT_URL, 'http://api.msg91.com/api/sendotp.php');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$result = curl_exec($ch);
print_r($result);
curl_close($ch);


问:
Create Angular 2 component library without inline styles
I red this article about creating Angular 2 component library, and it uses inline styles. Is there a way to create a lib without inline styles in Angular 2?

Also I saw this, but there is no word about styles, css.

My problem is, I want to create a complex component with multiple components in it and I use SASS also.

答:
If you want to use external HTML templates and CSS styles (or even SCSS styles) you might inline them first before NGC compilation by using Gulp and 'gulp-inline-ng2-template' plugin.

Here is how you npm scripts may look like in package.json:

```<code>{
  "scripts": {
    ...
    "build:esm": "gulp inline-templates && npm run ngcompile",
    "ngcompile": "node_modules/.bin/ngc -p tsconfig-aot.json",
    ...
  }
}
</code>```

Then gulpfile.js would look like.

```<code>const gulp = require('gulp');
const sass = require('node-sass');
const inlineTemplates = require('gulp-inline-ng2-template');

/**
 * Inline templates configuration.
 * @see  https://github.com/ludohenin/gulp-inline-ng2-template
 */
const INLINE_TEMPLATES = {
  SRC: './src/**/*.ts',
  DIST: './tmp/src-inlined',
  CONFIG: {
    base: '/src',
    target: 'es6',
    useRelativePaths: true,
    styleProcessor: compileSass
  }
};

/**
 * Inline external HTML and SCSS templates into Angular component files.
 * @see: https://github.com/ludohenin/gulp-inline-ng2-template
 */
gulp.task('inline-templates', () => {
  return gulp.src(INLINE_TEMPLATES.SRC)
    .pipe(inlineTemplates(INLINE_TEMPLATES.CONFIG))
    .pipe(gulp.dest(INLINE_TEMPLATES.DIST));
});

/**
 * Compile SASS to CSS.
 * @see https://github.com/ludohenin/gulp-inline-ng2-template
 * @see https://github.com/sass/node-sass
 */
function compileSass(path, ext, file, callback) {
  let compiledCss = sass.renderSync({
    data: file,
    outputStyle: 'compressed',
  });
  callback(null, compiledCss.css);
}
</code>```

This approach is utilized by angular-library-seed. You may look there for full integration example.

Body:
If you want to use external HTML templates and CSS styles (or even SCSS styles) you might inline them first before NGC compilation by using Gulp and 'gulp-inline-ng2-template' plugin.

Here is how you npm scripts may look like in package.json:

{
  "scripts": {
    ...
    "build:esm": "gulp inline-templates && npm run ngcompile",
    "ngcompile": "node_modules/.bin/ngc -p tsconfig-aot.json",
    ...
  }
}

Then gulpfile.js would look like.

const gulp = require('gulp');
const sass = require('node-sass');
const inlineTemplates = require('gulp-inline-ng2-template');

/**
 * Inline templates configuration.
 * @see  https://github.com/ludohenin/gulp-inline-ng2-template
 */
const INLINE_TEMPLATES = {
  SRC: './src/**/*.ts',
  DIST: './tmp/src-inlined',
  CONFIG: {
    base: '/src',
    target: 'es6',
    useRelativePaths: true,
    styleProcessor: compileSass
  }
};

/**
 * Inline external HTML and SCSS templates into Angular component files.
 * @see: https://github.com/ludohenin/gulp-inline-ng2-template
 */
gulp.task('inline-templates', () => {
  return gulp.src(INLINE_TEMPLATES.SRC)
    .pipe(inlineTemplates(INLINE_TEMPLATES.CONFIG))
    .pipe(gulp.dest(INLINE_TEMPLATES.DIST));
});

/**
 * Compile SASS to CSS.
 * @see https://github.com/ludohenin/gulp-inline-ng2-template
 * @see https://github.com/sass/node-sass
 */
function compileSass(path, ext, file, callback) {
  let compiledCss = sass.renderSync({
    data: file,
    outputStyle: 'compressed',
  });
  callback(null, compiledCss.css);
}

This approach is utilized by angular-library-seed. You may look there for full integration example.


问:
Count child nodes of a JSON response using groovy in soapui
I have a JSON response due to security reasons I had to take a screenshot and post it here.

I need to find number of available itineraryPrice available. Each curly braces refers to a separate itinerary, how to I count those tags in a groovy script step.

Method I have tried

```<code>def holder = groovyUtils.getXmlHolder( "air-search#ResponseAsXml" )
def xpath = "//*:search/*:itineraryPrice"
def numberOfRecommendations = holder["count(//*:search/*:itineraryPrice)"]
log.info "Total no of recommendations : "+numberOfRecommendations
</code>```

But I got the output as 1 :(

Kindly help ! Please refer screenshot as well.

答:
```<code>def json = '''{
"pos":"...",
"search":{
  "uri":"...",
  "itineraryPrice":[
    {"a":1},
    {"a":22},
    {"a":333},
    {"a":4},
    {"a":56}
  ]
}
}'''

json = new groovy.json.JsonSlurper().parseText(json)
def count = json.search.itineraryPrice.size()
</code>```

output: 5

Body:
I have a JSON response due to security reasons I had to take a screenshot and post it here.

I need to find number of available itineraryPrice available. Each curly braces refers to a separate itinerary, how to I count those tags in a groovy script step.

Method I have tried

def holder = groovyUtils.getXmlHolder( "air-search#ResponseAsXml" )
def xpath = "//*:search/*:itineraryPrice"
def numberOfRecommendations = holder["count(//*:search/*:itineraryPrice)"]
log.info "Total no of recommendations : "+numberOfRecommendations

But I got the output as 1 :(

Kindly help ! Please refer screenshot as well.

Body:
def json = '''{
"pos":"...",
"search":{
  "uri":"...",
  "itineraryPrice":[
    {"a":1},
    {"a":22},
    {"a":333},
    {"a":4},
    {"a":56}
  ]
}
}'''

json = new groovy.json.JsonSlurper().parseText(json)
def count = json.search.itineraryPrice.size()

output: 5


问:
How can i share a variable value between 2 components in angular 2
I am playing around with angular2. I have created 1 component using angular cli called appmenu.

appmenu.html as follows:

```<code><ul>
  <li (click)="menuitem1()">Menu Item 1</li>
  <li>Menu Item 2</li>
  <li>Menu Item 3</li>
</ul>
</code>```

i wish to fetch the value of testvariable on app.component.html, but i dont know what should i do in my app.component.ts

appmenu.ts as follows

```<code>   import { Component, OnInit } from '@angular/core';
import { Injectable } from '@angular/core';

@Component({
  providers: [AppMenuService], // GIVING ERROR HERE
  selector: 'app-appmenu',
  templateUrl: './appmenu.component.html',
  styleUrls: ['./appmenu.component.css']
})
export class AppmenuComponent implements OnInit {
public testvariable = "1st";
public data: any;
 // constructor(private sharedData: AppMenuService) { }

  ngOnInit() {
   // this.data = this.sharedData.data;
   // console.log(this.data);
  }

  menuitem1(){
    console.log("Menu item 1 clicked");
  }

}
</code>```

appmenu.service.ts

```<code>import { Injectable } from '@angular/core';

@Injectable()
export class AppMenuService{
public data: any;
    constructor() {
        this.data = 'Lorem ipsum dolor sit.';
    }
}
</code>```

Getting error on appmenu.component.ts here -> providers: [AppMenuService] , it says cannot find name AppMenuService

答:
You can use the @ViewChild annotation for this in your parent component:

```<code>@ViewChild(AppmenuComponent) appComponent: AppmenuComponent;
</code>```

https://angular.io/docs/ts/latest/cookbook/component-communication.html

Body:
I am playing around with angular2. I have created 1 component using angular cli called appmenu.

appmenu.html as follows:

Menu Item 1

Menu Item 2

Menu Item 3

i wish to fetch the value of testvariable on app.component.html, but i dont know what should i do in my app.component.ts

appmenu.ts as follows

   import { Component, OnInit } from '@angular/core';
import { Injectable } from '@angular/core';

@Component({
  providers: [AppMenuService], // GIVING ERROR HERE
  selector: 'app-appmenu',
  templateUrl: './appmenu.component.html',
  styleUrls: ['./appmenu.component.css']
})
export class AppmenuComponent implements OnInit {
public testvariable = "1st";
public data: any;
 // constructor(private sharedData: AppMenuService) { }

  ngOnInit() {
   // this.data = this.sharedData.data;
   // console.log(this.data);
  }

  menuitem1(){
    console.log("Menu item 1 clicked");
  }

}

appmenu.service.ts

import { Injectable } from '@angular/core';

@Injectable()
export class AppMenuService{
public data: any;
    constructor() {
        this.data = 'Lorem ipsum dolor sit.';
    }
}

Getting error on appmenu.component.ts here -> providers: [AppMenuService] , it says cannot find name AppMenuService

Body:
You can use the @ViewChild annotation for this in your parent component:

@ViewChild(AppmenuComponent) appComponent: AppmenuComponent;

https://angular.io/docs/ts/latest/cookbook/component-communication.html


问:
Unset Session for Particular Page not in whole Project?

Is it Possible to Unset $_SESSION['success'] for only one page?

not in whole website

答:
I dont know this will help you
For example: "sample.php"  page you unset
Start of page just assign the session value to one variable and unset that session</p>

```<code><?php
 session_start();
 $session_fav = $_SESSION["favanimal"];
 unset($_SESSION['favanimal']);
?>

page contents here

<?php
 /*At end of the page take that variable which assigned at start of the page*/
 /* again set the session here*/
 $_SESSION["favanimal"] = $session_fav;
?>
</code>```

Body:
I dont know this will help you
For example: "sample.php"  page you unset
Start of page just assign the session value to one variable and unset that session

<?php
 session_start();
 $session_fav = $_SESSION["favanimal"];
 unset($_SESSION['favanimal']);
?>

page contents here

<?php
 /*At end of the page take that variable which assigned at start of the page*/
 /* again set the session here*/
 $_SESSION["favanimal"] = $session_fav;
?>


问:
c# delete excel sheets using for loop
I am trying to delete excel sheets using for loop except selected sheet by User using Dropdown menu in asp.net web application. So, I have written a code in c#.

```<code>int index = DropDownList1.SelectedIndex;
int max = DropDownList1.Items.Count;
int i=3;
for (i=1; i <= max; i++)
{
    if (i != index+1)
    {
        Excel.Worksheet worksheets = (Excel.Worksheet)xlWorkBook.Sheets[i];
        worksheets.Delete();
    }

}
</code>```

And I am getting an error like this -

System.Runtime.InteropServices.COMException: 'Invalid index.
  (Exception from HRESULT: 0x8002000B (DISP_E_BADINDEX))'

答:
I don't know but anyhow when I reversed the loop, It started working.</p>

```<code>for (i=max; i > 0; i--)
{
    if (i != index+1)
    {
         Excel.Worksheet worksheets = (Excel.Worksheet)xlWorkBook.Sheets[i];
         worksheets.Delete();
    }

}
</code>```

Title: c# delete excel sheets using for loop

Body:
I am trying to delete excel sheets using for loop except selected sheet by User using Dropdown menu in asp.net web application. So, I have written a code in c#.

int index = DropDownList1.SelectedIndex;
int max = DropDownList1.Items.Count;
int i=3;
for (i=1; i <= max; i++)
{
    if (i != index+1)
    {
        Excel.Worksheet worksheets = (Excel.Worksheet)xlWorkBook.Sheets[i];
        worksheets.Delete();
    }

}

And I am getting an error like this -

System.Runtime.InteropServices.COMException: 'Invalid index.
  (Exception from HRESULT: 0x8002000B (DISP_E_BADINDEX))'

Body:
I don't know but anyhow when I reversed the loop, It started working.

for (i=max; i > 0; i--)
{
    if (i != index+1)
    {
         Excel.Worksheet worksheets = (Excel.Worksheet)xlWorkBook.Sheets[i];
         worksheets.Delete();
    }

}


问:
ASP.NET MVC Dictionary<string,string> output in view
Controller / C#:

```<code>public Action GetData()
{
    ViewBag.InputData = new Dictionary<string, string>
    {
         ["Name"] = "Simon Lin",
         ["Age"] = "18"
    };
    return View();
}
</code>```

View / HTML:

```<code>@foreach (var keyValuePair in (ViewBag.InputData as Dictionary<string, string>))
{
     <input type="text" name=@keyValuePair.Key value="" placeholder=@keyValuePair.Value />
}
</code>```

But in the result, first input's placeholder only show "Simon", Final HTML:

```<code><input type="text" name="Name" value="" placeholder="Simon" Lin="">
</code>```

答:
Enclosed Name and Placeholder in quotes   </p>

```<code>@foreach (var keyValuePair in (ViewBag.InputData as Dictionary<string, string>))
{
   <input type="text" name="@keyValuePair.Key" value=""
 placeholder="@keyValuePair.Value"/>
}
</code>```

Body:
Controller / C#:

public Action GetData()
{
    ViewBag.InputData = new Dictionary<string, string>
    {
         ["Name"] = "Simon Lin",
         ["Age"] = "18"
    };
    return View();
}

View / HTML:

@foreach (var keyValuePair in (ViewBag.InputData as Dictionary<string, string>))
{
     <input type="text" name=@keyValuePair.Key value="" placeholder=@keyValuePair.Value />
}

But in the result, first input's placeholder only show "Simon", Final HTML:

<input type="text" name="Name" value="" placeholder="Simon" Lin="">

Body:
Enclosed Name and Placeholder in quotes

@foreach (var keyValuePair in (ViewBag.InputData as Dictionary<string, string>))
{
   <input type="text" name="@keyValuePair.Key" value=""
 placeholder="@keyValuePair.Value"/>
}


问:
What's the best way to create a 24 hour countdown that resets once it hits a certain time in the day?
I want to an "order withing x amount of hours for next day delivery". I'm guessing the best way would be JS? but I'm not good at it to pick apart and edit anything I've found so far

My problem is that all of the ones I find are set to specific dates such as June 5th 2018 12:00.

Basically I want it to be set to 17:00 and if it's 15:30, I wan't the timer to say "order withing 1 hours 30 minutes for next day delivery" and then start from 23 hours 59 minutes once the time hits 17:01.

答:
Create a timestamp for arrival and a timestamp based upon the absolute distance to arrival, and use the latter for countdown:

//Order timestamps
var arrived = new Date();
arrived.setHours(15);
arrived.setMinutes(0);
arrived.setSeconds(0);
arrived.setTime(arrived.getTime() + 86400000);
//Drawing example
var arriveNode = document.body.appendChild(document.createElement("p"));
arriveNode.innerHTML = "Arrives in: ";
var arriveNodeTime = arriveNode.appendChild(document.createElement("b"));
setInterval(function() {
  var d = new Date(Math.abs(Date.now() - arrived.getTime()));
  arriveNodeTime.innerHTML = d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
}, 100);```


问:
Matching values for a list in python
Beginner question:  I am trying to evaluate whether two values in a row match.

```<code>a = ['sl','sl','cr','cl']
</code>```

This is my current code:

```<code>while (j+1) < len(a):
    if a[j] == a[j+1]:
        num = num + 1
    else:
        num = num
</code>```

However, when I do it this way it doesn't count the first value in the list - this is due to (j+1), however, if I remove it, get an error telling me my index is out of range - any advice would be appreciated.

答:
There are a few things you should improve in your code.
First, loop over enumerate(list) to easily compare items in the list.
Second, IndexError can be used to quit the loop after the last index is reached.
Here an --easy-to-read-- example.

```<code>for i,item in enumerate(a):
    try:
        if item = a[i+1]:
            print(item, 'and', a[i+1], 'are the same')
            #increment your counter here
    except IndexError:
        break
</code>```

Title: Matching values for a list in python

Body:
Beginner question:  I am trying to evaluate whether two values in a row match.

a = ['sl','sl','cr','cl']

This is my current code:

while (j+1) < len(a):
    if a[j] == a[j+1]:
        num = num + 1
    else:
        num = num

However, when I do it this way it doesn't count the first value in the list - this is due to (j+1), however, if I remove it, get an error telling me my index is out of range - any advice would be appreciated.

Body:
There are a few things you should improve in your code.
First, loop over enumerate(list) to easily compare items in the list.
Second, IndexError can be used to quit the loop after the last index is reached.
Here an --easy-to-read-- example.

for i,item in enumerate(a):
    try:
        if item = a[i+1]:
            print(item, 'and', a[i+1], 'are the same')
            #increment your counter here
    except IndexError:
        break


问:
Redis cluster instance consumes more memory than a standalone instance?
In our redis cluster,

A master node (redis 3.2.7 with jemalloc 3.6.0, installed using yum, yellow line) used 2.240G of memory

A slave node (redis 3.2.7 with jemalloc 3.6.0, installed using yum, cyan line) used 1.735G of memory

A slave node (redis 3.2.9 with jemalloc 4.0.3, compiled from source, orange line) used 1.531G of memory

A standalone slave (redis 3.2.9 with jemalloc 4.0.3, compiled from source, green line) used 1.008G of memory

Using a newer version of memory allocator saves about 12% of memory. That's easy to understand. But what makes a 50% more memory usage in the case of a cluster slave node than that of a standalone instance?

答:
Redis cluster uses an internal table, mapping each key in the cluster to its designated slot, which adds an overhead.

And the more keys you have, the bigger the overhead. So especially if you have many many small keys, this is very noticeable, and even slows down saving and loading data to/from RDB.

In redis 4.0 the data structure holding these keys has been optimized to reduce memory and increase speed. For reference - https://github.com/antirez/redis/issues/3800


问:
Assigning class to current image/slide
I am using fancybox 3 and need to assign a class to the current open slide

So far I have tried this, but unsuccesfully:

```<code>$("[data-fancybox]").fancybox({
        afterMove: function( instance, slide ) {

            //tried this but none is working
            $(this).addClass("active");
            slide.addClass("active");
            $(slide).addClass("active");
        }
});
</code>```

How can I assign a class to the current opened image? Do I have to use $(slide) or slide instead of $(this)?

答: The DOM element containing your content would be slide.$slide

Title: Assigning class to current image/slide

Body:
I am using fancybox 3 and need to assign a class to the current open slide

So far I have tried this, but unsuccesfully:

$("[data-fancybox]").fancybox({
        afterMove: function( instance, slide ) {

            //tried this but none is working
            $(this).addClass("active");
            slide.addClass("active");
            $(slide).addClass("active");
        }
});

How can I assign a class to the current opened image? Do I have to use $(slide) or slide instead of $(this)?


问:
Email validation, using if else statements wont allow it to continue checking if there was an error with the first if?
I have:

```<code>if(isset($_POST['submit'])) {
    if (empty($name)) {
        echo'<span class="error">ERROR: Missing Name </span><br/>';
    } else if(empty($phone) || empty($email)) {
        echo'<span class="error">ERROR: You must insert a phone number or email</span><br/>';
    } else if(!preg_match('/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}/', $email)) {
        echo'<span class="error">ERROR: Please Insert a valid Email</span><br/>';
    }  else {
        mail( "anEmail@hotmail.com", "Monthly Specials Email",
            "Name: $name
            Email: $email
            Phone Number: $phone
            Comment: $comment", "From: $email" );
        echo'<span id="valid">Message has been sent</span><br/>';
    }
}
</code>```

How else could I check for all of those issues without using else if?
When I use else if, it checks through the first if statement, if there is an issue with it it will not continue going through the other if statements following that one.

Any ideas? Thank you

答:
you can use try...catch statements for error checking like this.
whenever you encounter a condition where an error should be generated, you can use throw new Exception clause.

Body:
I have:

if(isset($_POST['submit'])) {
    if (empty($name)) {
        echo'ERROR: Missing Name
';
    } else if(empty($phone) || empty($email)) {
        echo'ERROR: You must insert a phone number or email
';
    } else if(!preg_match('/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}/', $email)) {
        echo'ERROR: Please Insert a valid Email
';
    }  else {
        mail( "anEmail@hotmail.com", "Monthly Specials Email",
            "Name: $name
            Email: $email
            Phone Number: $phone
            Comment: $comment", "From: $email" );
        echo'Message has been sent
';
    }
}

How else could I check for all of those issues without using else if?
When I use else if, it checks through the first if statement, if there is an issue with it it will not continue going through the other if statements following that one.

Any ideas? Thank you


问:
find data in json data in Javascript
I want to fetch some data from json file in Javascript

I have json data like this :

```<code>var bib = {
"AnthesGarcia-HernandezEtAl2016": {
    "author": "C. Anthes and R. J. Garcia-Hernandez and M. Wiedemann and D. Kranzlmuller",
    "booktitle": "2016 IEEE Aerospace Conference",
    "doi": "10.1109/AERO.2016.7500674",
    "file": "AnthesGarcia-HernandezEtAl2016.pdf:AnthesGarcia-HernandezEtAl2016.pdf:PDF",
    "keywords": "virtual reality, survey, aerospace",
},
"Bastos2014": {
    "author": "Bastos, Ricardo S",
    "file": "Bastos2014.pdf:Bastos2014.pdf:PDF",
    "institution": "DTIC Document",
    "keywords": "maritime, military, submarine, training, simulator, virtual reality, web, webgl, navy"

},
"Baum1994": {
    "author": "Baum, David R",
    "keywords": "patent, virtual reality, gestures, aviation, training, head-mounted-display, HMD, gloves",

}
</code>```

how can I fetch data like this in js:

```<code>    var keywords = {
    "keywords-name": { // keywords-name as example : virtual reality
        "repeat": "??"

    },
    "keywords-name2": {
       "repeat": "??"
       },
    "keywords-name3": {
       "repeat": "??"
}, ...
</code>```

I don't know how to do this in javascript..

答:
u can try this:

```<code>alert(keywords.keywords-name)
</code>```

should get the value.

Title: find data in json data in Javascript

Body:
I want to fetch some data from json file in Javascript

I have json data like this :

var bib = {
"AnthesGarcia-HernandezEtAl2016": {
    "author": "C. Anthes and R. J. Garcia-Hernandez and M. Wiedemann and D. Kranzlmuller",
    "booktitle": "2016 IEEE Aerospace Conference",
    "doi": "10.1109/AERO.2016.7500674",
    "file": "AnthesGarcia-HernandezEtAl2016.pdf:AnthesGarcia-HernandezEtAl2016.pdf:PDF",
    "keywords": "virtual reality, survey, aerospace",
},
"Bastos2014": {
    "author": "Bastos, Ricardo S",
    "file": "Bastos2014.pdf:Bastos2014.pdf:PDF",
    "institution": "DTIC Document",
    "keywords": "maritime, military, submarine, training, simulator, virtual reality, web, webgl, navy"

},
"Baum1994": {
    "author": "Baum, David R",
    "keywords": "patent, virtual reality, gestures, aviation, training, head-mounted-display, HMD, gloves",

}

how can I fetch data like this in js:

    var keywords = {
    "keywords-name": { // keywords-name as example : virtual reality
        "repeat": "??"

    },
    "keywords-name2": {
       "repeat": "??"
       },
    "keywords-name3": {
       "repeat": "??"
}, ...

I don't know how to do this in javascript..

Body:
u can try this:

alert(keywords.keywords-name)

should get the value.


问:
What happens if I send integers to a BigQuery field "string"?
One of the columns I send (in my code) to BigQuery is integers. I added the columns to BigQuery and I was too fast and added them as type string.

Will they be automatically converted? Or will the data be totally corrupted (= I cannot trust at all the resulting string)?

答: Actually BigQuery converted automatically the integers that I have sent it to string, so my table populates ok</p>


问:
sending GET Variable In ECHO META REFRESH
if i write this:

```<code>echo '<meta http-equiv="refresh" content="0;URL=https://en.wikipedia.org/wiki/.$_GET['w']"/>';
</code>```

error message: Parse error: syntax error, unexpected 'w' (T_STRING),
  expecting ',' or ';' in
  /storage/ssd3/084/1533084/public_html/wikiscript2.php on line 12

if i change 'w' to "w"

i get to wiki page but the title is like this.and ofcourse its a file not available there.

```<code>https://en.wikipedia.org/wiki/.$_GET[
</code>```

what i am doing wrong here.Please help me.

i am trying to send echo meta refresh to the file like this.......echo '<meta http-equiv="refresh" content="0;URL=https://en.wikipedia.org/wiki/.$_GET['w']"  />'; it doesnt work this way.

答:
You need to take your variable outside of the single quotes, like this:</p>

```<code> '<meta http-equiv="refresh" content="0;URL=https://en.wikipedia.org/wiki/'.$_GET['w'].'"/>';
</code>```

Body:
if i write this:

echo '<meta http-equiv="refresh" content="0;URL=https://en.wikipedia.org/wiki/.$_GET['w']"/>';

error message: Parse error: syntax error, unexpected 'w' (T_STRING),
  expecting ',' or ';' in
  /storage/ssd3/084/1533084/public_html/wikiscript2.php on line 12

if i change 'w' to "w"

i get to wiki page but the title is like this.and ofcourse its a file not available there.

https://en.wikipedia.org/wiki/.$_GET[

what i am doing wrong here.Please help me.

i am trying to send echo meta refresh to the file like this.......echo '<meta http-equiv="refresh" content="0;URL=https://en.wikipedia.org/wiki/.$_GET['w']"  />'; it doesnt work this way.

Body:
You need to take your variable outside of the single quotes, like this:

 '<meta http-equiv="refresh" content="0;URL=https://en.wikipedia.org/wiki/'.$_GET['w'].'"/>';


问:
Fresh install tensorflow
I installed tensorflow using pip earlier (CPU only version). It was showing me some warnings whenever I used to work with it. Now I tried to install the GPU version. Now when I import tensorflow, it gives a bunch of errors.

So I wanted to know if there was a way to completely delete tensorflow from Ubuntu and then reinstall it later?

答:
pip packages can be uninstalled pip uninstall tensorflow. Make sure you are uninstalling it from the environment of concern (if applicable).The pip output will inform you of it's successful removal. This should be enough to remove tensorflow from your system. You can then pip install tensorflow --ignore-installed to reinstall. The --ignore-install flag should overwrite tensorflow if you're concerned it was not successfully removed.

Please note that if you tried to install tensorflow GPU version that you will need to uninstall using tensorflow-gpu isntead of tensorflow. Same for re-installing.

Regarding your other issues, I suggest you open a fresh question for your errors. There's a good chance you weren't receiving errors but just the standard info messages from Tensorflow-GPU.

Title: Fresh install tensorflow


问:
Recently updated R / RStudio, rJava could not be loaded.
I recently updated R to 3.4 and RStudio to its RStudio v1.0.143 Preview so that it's compatible with the image updates & plots for R, but now I'm having an issue with rJava when trying to load it or packages that require it. It's as follows:

```<code>Loading required package: rJava
Error: package or namespace load failed for ‘rJava’:
 .onLoad failed in loadNamespace() for 'rJava', details:
 call: dyn.load(file, DLLpath = DLLpath, ...)
  error: unable to load shared object '/Library/Frameworks/R.framework/Versions/3.4/Resources/library/rJava/libs/rJava.so': dlopen(/Library/Frameworks/R.framework/Versions/3.4/Resources/library/rJava/libs/rJava.so, 6): Library not loaded: @rpath/libjvm.dylib
Referenced from:
 /Library/Frameworks/R.framework/Versions/3.4/Resources/library/rJava/libs/rJava.so
  Reason: image not found
Error: package ‘rJava’ could not be loaded
</code>```

I am presently running MacOSX 10.12.4 Sierra

Any help on how to fix this is great appreciated.

答:
rJava, R, Java and macOS is a mess.

What you can do is to try rebuild rJava from the sources.

Make sure to reconfigure Java. Due to the fact javareconf makes lots of strong assumptions when it comes to macOS and JAVA (one of these is, that whenever you have "Home" word, in JAVA_HOME variable, it will assume you want to use System wide Java - not quite good idea), you need to:

create "artificial" Home inside JDK, e.g.

cd /Library/Java/JavaVirtualMachines/jdk1.8.0_11.jdk/Contents
ln -s Home RHome

export RHome as JAVA_HOME

export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_11.jdk/Contents/RHome

Run javareconf with loots of switches that will make gcc with JNI based code compilation

```<code>`sudo R CMD javareconf JAVA_HOME=${JAVA_HOME} JAVA=${JAVA_HOME/bin/java JAVAC=${JAVA_HOME}/bin/javac JAVAH=${JAVA_HOME}/bin/javah JAR=${JAVA_HOME}/bin/jar JAVA_LD_LIBRARY_PATH=${JAVA_HOME}/jre/lib/server JAVA_CPPFLAGS="-I${JAVA_HOME}/include -I${JAVA_HOME}/include/darwin"`
</code>```

Download rJava package and try to rebuild it manually (outside R)

https://cran.r-project.org/web/packages/rJava/index.html

```<code>> curl https://cran.r-project.org/src/contrib/rJava_0.9-8.tar.gz -o rJava_0.9-8.tar.gz
> tar zxf rJava_0.9-8.tar.gz
> cd rJava
> ./configure
</code>```

if it passes, start R (in the same console where you have set env)

```<code>> install.packages("rJava", type="source")
</code>```

Note that with messy Java installations (Apple's JREs, Oracle's JDKs) you might need to play with setting up Java env propperly in a first place. It might be you will need some "dirty" hacks where you link javac, javah and jar from JDK inside JRE. You will know when you need to do it once ./configure complains about missing commands.

It also might be needed to update file

```<code>`/usr/libexec/java_home`/../Info.plist
</code>```

and make sure your JVM can handle JNI. You need to change:

```<code><key>JVMCapabilities</key>
<array>
  <string>CommandLine</string>
</array>
</code>```

to

```<code><key>JVMCapabilities</key>
<array>
  <string>CommandLine</string>
  <string>JNI</string>
</array>
</code>```

After some struggle, you might get it working fine. However, it's really system dependent. A lot depends on what version of R you have, whether you have JDK installed or not and what is your default JVM.

Note!

rJava requires XQuartz for compilation, make sure to install it as well

https://www.xquartz.org

Body:
I recently updated R to 3.4 and RStudio to its RStudio v1.0.143 Preview so that it's compatible with the image updates & plots for R, but now I'm having an issue with rJava when trying to load it or packages that require it. It's as follows:

Loading required package: rJava
Error: package or namespace load failed for ‘rJava’:
 .onLoad failed in loadNamespace() for 'rJava', details:
 call: dyn.load(file, DLLpath = DLLpath, ...)
  error: unable to load shared object '/Library/Frameworks/R.framework/Versions/3.4/Resources/library/rJava/libs/rJava.so': dlopen(/Library/Frameworks/R.framework/Versions/3.4/Resources/library/rJava/libs/rJava.so, 6): Library not loaded: @rpath/libjvm.dylib
Referenced from:
 /Library/Frameworks/R.framework/Versions/3.4/Resources/library/rJava/libs/rJava.so
  Reason: image not found
Error: package ‘rJava’ could not be loaded

I am presently running MacOSX 10.12.4 Sierra

Any help on how to fix this is great appreciated.

Body:
rJava, R, Java and macOS is a mess.

What you can do is to try rebuild rJava from the sources.

Make sure to reconfigure Java. Due to the fact javareconf makes lots of strong assumptions when it comes to macOS and JAVA (one of these is, that whenever you have "Home" word, in JAVA_HOME variable, it will assume you want to use System wide Java - not quite good idea), you need to:

create "artificial" Home inside JDK, e.g.

cd /Library/Java/JavaVirtualMachines/jdk1.8.0_11.jdk/Contents
ln -s Home RHome

export RHome as JAVA_HOME

export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_11.jdk/Contents/RHome

Run javareconf with loots of switches that will make gcc with JNI based code compilation

`sudo R CMD javareconf JAVA_HOME=${JAVA_HOME} JAVA=${JAVA_HOME/bin/java JAVAC=${JAVA_HOME}/bin/javac JAVAH=${JAVA_HOME}/bin/javah JAR=${JAVA_HOME}/bin/jar JAVA_LD_LIBRARY_PATH=${JAVA_HOME}/jre/lib/server JAVA_CPPFLAGS="-I${JAVA_HOME}/include -I${JAVA_HOME}/include/darwin"`

Download rJava package and try to rebuild it manually (outside R)

https://cran.r-project.org/web/packages/rJava/index.html

> curl https://cran.r-project.org/src/contrib/rJava_0.9-8.tar.gz -o rJava_0.9-8.tar.gz
> tar zxf rJava_0.9-8.tar.gz
> cd rJava
> ./configure

if it passes, start R (in the same console where you have set env)

> install.packages("rJava", type="source")

Note that with messy Java installations (Apple's JREs, Oracle's JDKs) you might need to play with setting up Java env propperly in a first place. It might be you will need some "dirty" hacks where you link javac, javah and jar from JDK inside JRE. You will know when you need to do it once ./configure complains about missing commands.

It also might be needed to update file

`/usr/libexec/java_home`/../Info.plist

and make sure your JVM can handle JNI. You need to change:

<key>JVMCapabilities</key>
<array>
  <string>CommandLine</string>
</array>

to

<key>JVMCapabilities</key>
<array>
  <string>CommandLine</string>
  <string>JNI</string>
</array>

After some struggle, you might get it working fine. However, it's really system dependent. A lot depends on what version of R you have, whether you have JDK installed or not and what is your default JVM.

Note!

rJava requires XQuartz for compilation, make sure to install it as well

https://www.xquartz.org


问:
Call JavaScript function inside SVG from Surrounding HTML
I've created a little page just as this one here:

```<code><!DOCTYPE html>
<html>
  <head>
     <title>Test</title>
     <script type="text/javascript">
     function test() {
        executeAnimation();
     }
     </script>
  </head>
  <body>
     <h1>Tester</h1>
     <embed src="test.svg" type="image/svg+xml" />
     <hr />
     <input type='button' value='Test' onclick='test()' />
  </body>
</html>
</code>```

The test.svg looks like this:

```<code><?xml version="1.0" ?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 20010904//EN"
 "http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd">
<svg id="testSvgId" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="950" height="900">
     <title>Title</title>
     <desc>Desc</desc>
     <defs>
          <script type="text/javascript">
          <![CDATA[
          function executeAnimation () {
              document.getElementById('anim').beginElement();
          }
          ]]>
          </script>
     </defs>
     <ellipse cx="500" cy="1090" rx="600" ry="0" fill="rgb(94,114,54)">
          <animate id="anim" attributeType="XML" attributeName="ry" begin="indefinite" dur="2s" from="0" to="350" fill="freeze" />
     </ellipse>
</svg>
</code>```

As you can see, I want to call from JavaScript in the HTML page the function executeAnimation() which is defined insite the SVG image. This actually does not work.

I also tried this:

```<code><svg onload='onloadFunction()'...>
...
function onloadFunction() {
    alert('i am loading');
    window.executeAnimation = executeAnimation();
}
</code>```

This was suggested in another forum, but this did also not work (window.executeAnimation was undefined from outside).

What would be the real correct way to do this?

Body:
I've created a little page just as this one here:

<!DOCTYPE html>

     <title>Test</title>

Tester

     <embed src="test.svg" type="image/svg+xml" />

     <input type='button' value='Test' onclick='test()' />

The test.svg looks like this:

<?xml version="1.0" ?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 20010904//EN"
 "http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd">
<svg id="testSvgId" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="950" height="900">
     <title>Title</title>
     <desc>Desc</desc>
     <defs>

     </defs>
     <ellipse cx="500" cy="1090" rx="600" ry="0" fill="rgb(94,114,54)">
          <animate id="anim" attributeType="XML" attributeName="ry" begin="indefinite" dur="2s" from="0" to="350" fill="freeze" />
     </ellipse>
</svg>

As you can see, I want to call from JavaScript in the HTML page the function executeAnimation() which is defined insite the SVG image. This actually does not work.

I also tried this:

<svg onload='onloadFunction()'...>
...
function onloadFunction() {
    alert('i am loading');
    window.executeAnimation = executeAnimation();
}

This was suggested in another forum, but this did also not work (window.executeAnimation was undefined from outside).

What would be the real correct way to do this?

Body:
Without seeing the source of your .svg, it's impossible to answer specifically...

Check this out: https://codepen.io/lambdacreatives/pen/uygzk

HTML

<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="77px" height="77px" viewBox="0 0 77 77" enable-background="new 0 0 77 77" xml:space="preserve">
  <g>
    <path id="d" fill="#ffffff" d="M49.045,61.112c2.549-1.198,4.867-2.798,6.857-4.743L36.83,13.587c-2.862,0.186-5.602,0.826-8.124,1.899
    l6.448,14.465l-15.12,25.387c1.866,2.038,4.044,3.785,6.489,5.118L39.236,39.11L49.045,61.112z"/>

    <path id="circle" fill="#ffffff" d="M38.457,67.2c-15.852,0-28.701-12.848-28.701-28.701c0-15.851,12.85-28.697,28.701-28.697
    c5.773,0,11.137,1.72,15.639,4.653l4.605-7.702c-6.049-3.873-13.114-5.998-20.359-5.998C17.531,0.754,0.6,17.687,0.6,38.499
    c0,20.813,16.932,37.746,37.742,37.746c8.438,0,16.48-2.773,23.061-7.865l-3.809-8.533C52.514,64.405,45.818,67.2,38.457,67.2z">
        <animateTransform
               xlink:href="#circle"
               attributeName="transform"
               attributeType="XML"
               id="ani-circle"
               type="rotate"
               from="0 38.501500725746155 38.4994986653327945"
               to="360 38.501500725746155 38.4994986653327945"
               dur="0.3s"
              begin="click"
               repeatCount="1"
               fill="freeze" />

    </path>
  </g>
</svg>
<br><br>
<button id="trigger">Trigger Animation</button>

CSS

body {
  background-color: black;
  text-align: center;
}

svg {
  height: 100%;
  width: 200px;
  path {
    fill: white;
  }
}

JS

$( "#trigger" ).click(function() {
  document.getElementById("ani-circle").beginElement();
});

If you can't work it out from that, post the source of your .svg and I'll knock up a specific answer for you.


问:
Owin 3rd party login with Google or Facebook redirect failed (/Account/ExternalLoginCallback not working) C# MVC
When we test our program in local server the 3rd party login works fine, but that's not the case when we publish it onto the actual server. When we use 3rd party login on actual server, it didn't work.

So far what we know is our server provider is using https while our IIS server setting is using http. Could this be the cause? If not, any idea what's the problem we are encountering?

Here is the URL when we are entering account on Facebook 3rd party login page:

```<code>https://www.facebook.com/login.php?skip_api_login=1&api_key=569249369941462&signed_next=1&next=https%3A%2F%2Fwww.facebook.com%2Fv2.8%2Fdialog%2Foauth%3Fredirect_uri%3Dhttp%253A%252F%252Fwww.ipce.com.tw%252Fsignin-facebook%26state%3DwXOgKtgLeatXfqXP-Cv-Rc5EJu7AYiWQyqyN4bqtWfgZr6ncxzc9uerpXv4uSKZoSUQpWwO5AUt2YksiIP3q05GhjVUoT94kMZD5E57a2PgMaJT8oSrXh1K9lrH3g88DF0M2jtGX-DWJl-UJ66g_neu5xx1pGsIc3NBvblBjQfWM_rR6Vt8qB16GTCMqxSsQXhH4UXRDuQY5eBLSUKS7W0SRJMzDNClgMRT-VTZ7Gvv4oYTEAXnFG6qmh41o-xT5%26scope%3Demail%26response_type%3Dcode%26client_id%3D569249369941462%26ret%3Dlogin%26logger_id%3D2a07ffc7-acf8-ad97-0b9f-b45dcff38b39&cancel_url=http%3A%2F%2Fwww.ipce.com.tw%2Fsignin-facebook%3Ferror%3Daccess_denied%26error_code%3D200%26error_description%3DPermissions%2Berror%26error_reason%3Duser_denied%26state%3DwXOgKtgLeatXfqXP-Cv-Rc5EJu7AYiWQyqyN4bqtWfgZr6ncxzc9uerpXv4uSKZoSUQpWwO5AUt2YksiIP3q05GhjVUoT94kMZD5E57a2PgMaJT8oSrXh1K9lrH3g88DF0M2jtGX-DWJl-UJ66g_neu5xx1pGsIc3NBvblBjQfWM_rR6Vt8qB16GTCMqxSsQXhH4UXRDuQY5eBLSUKS7W0SRJMzDNClgMRT-VTZ7Gvv4oYTEAXnFG6qmh41o-xT5%23_%3D_&display=page&locale=zh_TW&logger_id=2a07ffc7-acf8-ad97-0b9f-b45dcff38b39
</code>```

and this is the URL after we login, back to our home page but /Account/ExternalLoginCallback is not called

```<code>https://www.ipce.com.tw/?code=AQAUdHG-r1AxBOy1xkVm4sklkq-tBKn-9c_PAYqqpZmwiseTcKWAnTRJkoyeoZkiwReg_x7VSnMymQiWgqp0ZdnhlH1ypijH-FSyaca5BDCMJUS04x05CNVjrN5HvuRXdVJkv2OHwzqkTSWvkwC6S58nrRckIjroKjjGDqaWvldOt_0g8nFe_ZvLovj_hbdQs5SPE4M97CpPrm0ExudeEddEo1zn29RIMabS204kF445Hn73X90RTy7WpIqAINpcIIwK4XeAQMcoqoBQinaVRyjrNxjvKoAEXqBPBKKkdJn7u3bx94rFZXqHGGMJ6uth0rBSpDPJgtq0M1XMmYXfESjS&state=wXOgKtgLeatXfqXP-Cv-Rc5EJu7AYiWQyqyN4bqtWfgZr6ncxzc9uerpXv4uSKZoSUQpWwO5AUt2YksiIP3q05GhjVUoT94kMZD5E57a2PgMaJT8oSrXh1K9lrH3g88DF0M2jtGX-DWJl-UJ66g_neu5xx1pGsIc3NBvblBjQfWM_rR6Vt8qB16GTCMqxSsQXhH4UXRDuQY5eBLSUKS7W0SRJMzDNClgMRT-VTZ7Gvv4oYTEAXnFG6qmh41o-xT5#/_=_
</code>```

I tried forcing http to https, but a server error 500 happened, I can't figure another way to fix the problem.

somebody help me please

Try 1

I set localhost server Route like this:

```<code>routes.MapRoute(
     name: "SigninFacebook",
     url: "signin-facebook",
     defaults: new { controller = "Member", action = "ExternalLoginCallback" }
);
</code>```

It works! but it responded HTTP ERROR 500.

I tried applying the setting to actual server, well, nothing happened.
It still redirect to our home page, and ExternalLoginCallback still not called.
I doubt our actual server didn't get to signin-facebook Route.

答:
I suppose it happens because you provide redirect_uri=localhost.

This parameter is used to redirect the browser page after successful 3rd party login to provide a auth code from Facebook to your server.

It works in your test environment because your webserver is local so browser can perform redirect to localhost.

But in production environment the real domain name should be used instead of localhost.

Body:
When we test our program in local server the 3rd party login works fine, but that's not the case when we publish it onto the actual server. When we use 3rd party login on actual server, it didn't work.

So far what we know is our server provider is using https while our IIS server setting is using http. Could this be the cause? If not, any idea what's the problem we are encountering?

Here is the URL when we are entering account on Facebook 3rd party login page:

https://www.facebook.com/login.php?skip_api_login=1&api_key=569249369941462&signed_next=1&next=https%3A%2F%2Fwww.facebook.com%2Fv2.8%2Fdialog%2Foauth%3Fredirect_uri%3Dhttp%253A%252F%252Fwww.ipce.com.tw%252Fsignin-facebook%26state%3DwXOgKtgLeatXfqXP-Cv-Rc5EJu7AYiWQyqyN4bqtWfgZr6ncxzc9uerpXv4uSKZoSUQpWwO5AUt2YksiIP3q05GhjVUoT94kMZD5E57a2PgMaJT8oSrXh1K9lrH3g88DF0M2jtGX-DWJl-UJ66g_neu5xx1pGsIc3NBvblBjQfWM_rR6Vt8qB16GTCMqxSsQXhH4UXRDuQY5eBLSUKS7W0SRJMzDNClgMRT-VTZ7Gvv4oYTEAXnFG6qmh41o-xT5%26scope%3Demail%26response_type%3Dcode%26client_id%3D569249369941462%26ret%3Dlogin%26logger_id%3D2a07ffc7-acf8-ad97-0b9f-b45dcff38b39&cancel_url=http%3A%2F%2Fwww.ipce.com.tw%2Fsignin-facebook%3Ferror%3Daccess_denied%26error_code%3D200%26error_description%3DPermissions%2Berror%26error_reason%3Duser_denied%26state%3DwXOgKtgLeatXfqXP-Cv-Rc5EJu7AYiWQyqyN4bqtWfgZr6ncxzc9uerpXv4uSKZoSUQpWwO5AUt2YksiIP3q05GhjVUoT94kMZD5E57a2PgMaJT8oSrXh1K9lrH3g88DF0M2jtGX-DWJl-UJ66g_neu5xx1pGsIc3NBvblBjQfWM_rR6Vt8qB16GTCMqxSsQXhH4UXRDuQY5eBLSUKS7W0SRJMzDNClgMRT-VTZ7Gvv4oYTEAXnFG6qmh41o-xT5%23_%3D_&display=page&locale=zh_TW&logger_id=2a07ffc7-acf8-ad97-0b9f-b45dcff38b39

and this is the URL after we login, back to our home page but /Account/ExternalLoginCallback is not called

https://www.ipce.com.tw/?code=AQAUdHG-r1AxBOy1xkVm4sklkq-tBKn-9c_PAYqqpZmwiseTcKWAnTRJkoyeoZkiwReg_x7VSnMymQiWgqp0ZdnhlH1ypijH-FSyaca5BDCMJUS04x05CNVjrN5HvuRXdVJkv2OHwzqkTSWvkwC6S58nrRckIjroKjjGDqaWvldOt_0g8nFe_ZvLovj_hbdQs5SPE4M97CpPrm0ExudeEddEo1zn29RIMabS204kF445Hn73X90RTy7WpIqAINpcIIwK4XeAQMcoqoBQinaVRyjrNxjvKoAEXqBPBKKkdJn7u3bx94rFZXqHGGMJ6uth0rBSpDPJgtq0M1XMmYXfESjS&state=wXOgKtgLeatXfqXP-Cv-Rc5EJu7AYiWQyqyN4bqtWfgZr6ncxzc9uerpXv4uSKZoSUQpWwO5AUt2YksiIP3q05GhjVUoT94kMZD5E57a2PgMaJT8oSrXh1K9lrH3g88DF0M2jtGX-DWJl-UJ66g_neu5xx1pGsIc3NBvblBjQfWM_rR6Vt8qB16GTCMqxSsQXhH4UXRDuQY5eBLSUKS7W0SRJMzDNClgMRT-VTZ7Gvv4oYTEAXnFG6qmh41o-xT5#/_=_

I tried forcing http to https, but a server error 500 happened, I can't figure another way to fix the problem.

somebody help me please

Try 1

I set localhost server Route like this:

routes.MapRoute(
     name: "SigninFacebook",
     url: "signin-facebook",
     defaults: new { controller = "Member", action = "ExternalLoginCallback" }
);

It works! but it responded HTTP ERROR 500.

I tried applying the setting to actual server, well, nothing happened.
It still redirect to our home page, and ExternalLoginCallback still not called.
I doubt our actual server didn't get to signin-facebook Route.


问:
Profiling VBA code for microsoft word
I have some legacy code that uses VBA to parse a word document and build some XML output;

Needless to say it runs like a dog but I was interested in profiling it to see where it's breaking down and maybe if there are some options to make it faster.

I don't want to try anything until I can start measuring my results so profiling is a must - I've done a little searching around but can't find anything that would do this job easily. There was one tool by brentwood? that requires modifying your code but it didn't work and I ran outa time.

Anyone know anything simple that works?

Update: The code base is about 20 or so files, each with at least 100 methods - manually adding in start/end calls for each method just isn't appropriate - especially removing them all afterwards - I was actually thinking about doing some form of REGEX to solve this issue and another to remove them all after but its just a little too intrusive but may be the only solution. I've found some nice timing code on here earlier so the timing part of it isn't an issue.

答:
About that "Now" function (above, svinto) ...

I've used the "Timer" function (in Excel VBA), which returns a Single.
It seems to work just fine.  Larry

OwnerDisplayName: widgisoft

Title: Profiling VBA code for microsoft word

LastEditorDisplayName: widgisoft

OwnerDisplayName: Larry


问:
why GUID uniqueidentifier show value slightly different
We have an user table which the userId is an uniqueidentifier type in Sybase database. The value we put in is a GUID value from our C# application. When we look at the table via Sybase tool, the value shows as 3835FD60-ACDE-4345-99AB-54263E9A07AE. When we copy/paste that field to a text file, it shows as 0x3835fd60acde434599ab54263e9a07ae. When we access that field using  odbc (in python) generates the (Hex) string as
3835FD60ACDE434599AB54263E9A07AE.

Why it shows differently?
thanks

答:
Typically, UUID/GUID values are stored as a 128 bit integer, so any of the display formats are valid.  The formatted display that we are used to when we are referring to a UUID or GUID is just a transformation of that 128-bit integer into a convenient string format.

In Python, you should be able to pass the value to the uuid.UUID class in order to get a UUID object that you can then format in the customary way.


问:
Handle triple condition with *ngIf else
I would like to suggest establishments to the user based on its location.

I must handle to cases:

The user granted the geolocation service

The user did not granted the geolocation service

I want to display a loading message while I am both checking if the geolocation service is granted and (if yes) while looking out for the establishments.

I tried something like this:

```<code><div *ngIf="(suggestedPlaces$ | async) || clocationAvailable !== undefined; else loading" >
      <div *ngFor="let place of suggestedPlaces$ | async">
        <ion-card (click)="onSuggestedPlaceSelected(place)">
          <!--<ion-img width="2OO" height="200" src="{{place.photo}}">
        </ion-img>-->
          <ion-card-content>
            <ion-card-title>
              {{place.name}} - {{place.rating}}
            </ion-card-title>
            <p>
              {{place.vicinity}}
            </p>
          </ion-card-content>
        </ion-card>
      </div>
    </div>

    <div #loading padding text-center>
        <ion-spinner></ion-spinner>
        <p>
          Chargement...
        </p>
    </div>

    <div *ngIf="clocationAvailable === false" class="message-box message-box-alert">
      <ion-row>
          <ion-col col-1>
            <ion-icon name="alert"></ion-icon>
          </ion-col>
          <ion-col>
            Could not geolocate you
          </ion-col>
        </ion-row>
    </div>
</code>```

In my controller I wrote the following:

```<code>clocationAvailable: boolean;

ionViewDidLoad() {
    // Start to geolocate the user in order to suggest accurate places
    this.geolocation.getCurrentPosition().then((resp) => {
      // resp.coords.latitude
      // resp.coords.longitude
      console.log('Location ', resp);

      // Trigger searchSuggestionsForSport()
      // Will populate the suggestedPlaces$ variable
      this.clocationAvailable = true;
      this.searchSuggestionsForSport(this.sport);

    }).catch((error) => {
      console.log('Error getting location', error);

      // Set clocationAvailable to false which means that the user could not be geolocated (certainly because not granted)
      // This is used in view to display a message
      this.clocationAvailable = false;
    });
  }
</code>```

My problem is, when I catch the geolocation error and that I set the clocationAvailable to false, my error message is well displayed but the spinner remains.

How could I handle this ?

答:
You could use variable for visibility of loader.

```<code><div *ngIf="loadingInProgress" #loading padding text-center></div>
</code>```

controller

```<code>loadingInProgress: boolean = true; //loading in the begining

ionViewDidLoad() {
//stuff as before
.catch((error) => {
    console.log('Error getting location', error);

    this.loadingInProgress = false; //Changed visibility
});
</code>```

}

Edit

if you want to use else statement you need to use ng-template

```<code><ng-template #loading>
    <div padding text-center>
        <ion-spinner></ion-spinner>
        <p>
            Chargement...
        </p>
    </div>
</ng-template>
</code>```

Title: Handle triple condition with *ngIf else

Body:
I would like to suggest establishments to the user based on its location.

I must handle to cases:

The user granted the geolocation service

The user did not granted the geolocation service

I want to display a loading message while I am both checking if the geolocation service is granted and (if yes) while looking out for the establishments.

I tried something like this:

        <ion-card (click)="onSuggestedPlaceSelected(place)">

          <ion-card-content>
            <ion-card-title>
              {{place.name}} - {{place.rating}}
            </ion-card-title>

              {{place.vicinity}}

          </ion-card-content>
        </ion-card>

        <ion-spinner></ion-spinner>

          Chargement...

      <ion-row>
          <ion-col col-1>
            <ion-icon name="alert"></ion-icon>
          </ion-col>
          <ion-col>
            Could not geolocate you
          </ion-col>
        </ion-row>

In my controller I wrote the following:

clocationAvailable: boolean;

ionViewDidLoad() {
    // Start to geolocate the user in order to suggest accurate places
    this.geolocation.getCurrentPosition().then((resp) => {
      // resp.coords.latitude
      // resp.coords.longitude
      console.log('Location ', resp);

      // Trigger searchSuggestionsForSport()
      // Will populate the suggestedPlaces$ variable
      this.clocationAvailable = true;
      this.searchSuggestionsForSport(this.sport);

    }).catch((error) => {
      console.log('Error getting location', error);

      // Set clocationAvailable to false which means that the user could not be geolocated (certainly because not granted)
      // This is used in view to display a message
      this.clocationAvailable = false;
    });
  }

My problem is, when I catch the geolocation error and that I set the clocationAvailable to false, my error message is well displayed but the spinner remains.

How could I handle this ?

Body:
You could use variable for visibility of loader.

<div *ngIf="loadingInProgress" #loading padding text-center></div>

controller

loadingInProgress: boolean = true; //loading in the begining

ionViewDidLoad() {
//stuff as before
.catch((error) => {
    console.log('Error getting location', error);

    this.loadingInProgress = false; //Changed visibility
});

}

Edit

if you want to use else statement you need to use ng-template

<ng-template #loading>
    <div padding text-center>
        <ion-spinner></ion-spinner>
        <p>
            Chargement...
        </p>
    </div>
</ng-template>