问:
How do I convert a derived recursive data type to a base data type?
I have a class called nesteddict derived from collections.defaultdict that hold a nested set of dictionaries:

```<code>import collections

class nesteddict(collections.defaultdict):
    """Nested dictionary structure.

    Based on Stack Overflow question 635483
    """
    def __init__(self):
        collections.defaultdict.__init__(self, nesteddict)
        self.locked = False
</code>```

I would like to be able to perform an operation an instance that converts all of the nesteddict objects to python-native dict objects.

One way to do this is to have a method:

```<code>def todict(self):
    for (key,val) in self.iteritems():
        if isinstance(val,nesteddict):
            val.todict()
            self[key] = dict(val)
    self = dict(self)
</code>```

This is successful at replacing all the inner mapping objects with dict types, but the last statement in the method is obviously not going to work.

Here is an example:

```<code>In [93]: a = pyutils.nesteddict()

In [94]: a[1][1] = 'a'

In [95]: a[1][2] = 'b'

In [96]: a[2][1] = 'c'

In [97]: a[2][2] = 'd'

In [98]: print a
defaultdict(<class 'pyutils.nesteddict'>, {1: defaultdict(<class 'pyutils.nesteddict'>, {1: 'a', 2: 'b'}), 2: defaultdict(<class 'pyutils.nesteddict'>, {1: 'c', 2: 'd'})})

In [99]: a.todict()

In [100]: print a
defaultdict(<class 'pyutils.nesteddict'>, {1: {1: 'a', 2: 'b'}, 2: {1: 'c', 2: 'd'}})
</code>```

Is there a way to do this in python?  Have a method that converts its object to another type?  If not, what is a good alternative to this.  Note that the datatype in practice may be large, so it would be preferable not to just make a copy and then return it.

Thanks!

Uri

答:
The first thing I notice in your code, is that you're modifying (or trying to) the self variable. That variable is just pointing at the current instance of your class. If you reassign it, you're just pointing it at another value, but the previous value pointed by self remains unchanged. This is just how Python works.

So, what you should to is just return the result of the transformation in your method... something like this:

```<code>def anothertodict(self):
    stuff = dict(self)
    for (key,val) in stuff.iteritems():
        if isinstance(val,nesteddict):
            stuff[key] = val.anothertodict()
    return stuff
</code>```

That way, if you do a: print a.anothertodict() you'll get what you're expecting to get.

PS: Why do you need to convert from defaultdict to dict?

Body:
I have a class called nesteddict derived from collections.defaultdict that hold a nested set of dictionaries:

import collections

class nesteddict(collections.defaultdict):
    """Nested dictionary structure.

    Based on Stack Overflow question 635483
    """
    def __init__(self):
        collections.defaultdict.__init__(self, nesteddict)
        self.locked = False

I would like to be able to perform an operation an instance that converts all of the nesteddict objects to python-native dict objects.

One way to do this is to have a method:

def todict(self):
    for (key,val) in self.iteritems():
        if isinstance(val,nesteddict):
            val.todict()
            self[key] = dict(val)
    self = dict(self)

This is successful at replacing all the inner mapping objects with dict types, but the last statement in the method is obviously not going to work.

Here is an example:

In [93]: a = pyutils.nesteddict()

In [94]: a[1][1] = 'a'

In [95]: a[1][2] = 'b'

In [96]: a[2][1] = 'c'

In [97]: a[2][2] = 'd'

In [98]: print a
defaultdict(<class 'pyutils.nesteddict'>, {1: defaultdict(<class 'pyutils.nesteddict'>, {1: 'a', 2: 'b'}), 2: defaultdict(<class 'pyutils.nesteddict'>, {1: 'c', 2: 'd'})})

In [99]: a.todict()

In [100]: print a
defaultdict(<class 'pyutils.nesteddict'>, {1: {1: 'a', 2: 'b'}, 2: {1: 'c', 2: 'd'}})

Is there a way to do this in python?  Have a method that converts its object to another type?  If not, what is a good alternative to this.  Note that the datatype in practice may be large, so it would be preferable not to just make a copy and then return it.

Thanks!

Uri

Body:
The first thing I notice in your code, is that you're modifying (or trying to) the self variable. That variable is just pointing at the current instance of your class. If you reassign it, you're just pointing it at another value, but the previous value pointed by self remains unchanged. This is just how Python works.

So, what you should to is just return the result of the transformation in your method... something like this:

def anothertodict(self):
    stuff = dict(self)
    for (key,val) in stuff.iteritems():
        if isinstance(val,nesteddict):
            stuff[key] = val.anothertodict()
    return stuff

That way, if you do a: print a.anothertodict() you'll get what you're expecting to get.

PS: Why do you need to convert from defaultdict to dict?


来源: stackexchange

问:
Javascript array search and remove string?
I have:

```<code>var array = new Array();
array.push("A");
array.push("B");
array.push("C");
</code>```

I want to be able to do something like:

array.remove("B");

but there is no remove function. How do I accomplish this?

答:
I'm actually updating this thread with a more recent 1-line solution:

```<code>let arr = ['A', 'B', 'C'];
arr = arr.filter(e => e !== 'B'); // will return ['A', 'C']
</code>```

The idea is basically to filter the array by selecting all elements different to the element you want to remove.

Note: will remove all occurrences.

EDIT:

If you want to remove only the first occurence:

```<code>t = ['A', 'B', 'C', 'B'];
t.splice(t.indexOf('B'), 1); // will return ['B'] and t is now equal to ['A', 'C', 'B']
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have:

var array = new Array();
array.push("A");
array.push("B");
array.push("C");

I want to be able to do something like:

array.remove("B");

but there is no remove function. How do I accomplish this?

Body:
I'm actually updating this thread with a more recent 1-line solution:

let arr = ['A', 'B', 'C'];
arr = arr.filter(e => e !== 'B'); // will return ['A', 'C']

The idea is basically to filter the array by selecting all elements different to the element you want to remove.

Note: will remove all occurrences.

EDIT:

If you want to remove only the first occurence:

t = ['A', 'B', 'C', 'B'];
t.splice(t.indexOf('B'), 1); // will return ['B'] and t is now equal to ['A', 'C', 'B']

ContentLicense: CC BY-SA 4.0


问:
Check if the current time has just passed 12 o'clock in BACKGROUND
I want to check if the current time (24 hours or 12 hours am/pm) has just passed 12 o'clock.

I did something like that in a view, but in this case I checked if it was not yet 12 in the morning:

```<code>let date = Date()
let calendar = Calendar.current
let hora = calendar.component(.hour, from: date)
let minutos = calendar.component(.minute, from: date)
if hora < 12 && minutos <= 59 { ... }
</code>```

I don't know if I explained it well... I was wondering if I can check if the time has passed in AppDelegate, always in background, and execute a function when 12 am has passed. It is possible?

答:
Depending on what you're trying to do, Local Notifications might be of use to you:

https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/SchedulingandHandlingLocalNotifications.html#//apple_ref/doc/uid/TP40008194-CH5-SW1

You can schedule them and they will be delivered to the user even when your app is in the background or not running. The user may then launch your app with a particular action on the notification.

Body:
I want to check if the current time (24 hours or 12 hours am/pm) has just passed 12 o'clock.

I did something like that in a view, but in this case I checked if it was not yet 12 in the morning:

let date = Date()
let calendar = Calendar.current
let hora = calendar.component(.hour, from: date)
let minutos = calendar.component(.minute, from: date)
if hora < 12 && minutos <= 59 { ... }

I don't know if I explained it well... I was wondering if I can check if the time has passed in AppDelegate, always in background, and execute a function when 12 am has passed. It is possible?


问:
Screen Locked causing Unable to find explicit activity class have you declared this activity in your AndroidManifest.xml?
I have been getting this error in my application for quite a sometime now at few client devices. I have posted a related question Here but found not useful answer.

After weeks of research and testing, i reproduce this error at development machine.

On login activity, after user insert required credentials and click Login button, I am running a AsyncTask to validate the credentials over the server. In between i am showing ProgressDialog to the user. In case if am locked the device during doInBackground execution using device hardware lock key or it dims by own and lock, PostExecute method throws exception. Following is code snippet of PostExecute. Normally without Locking the device it works well

```<code>if(EveryThing Goes Well)
{
    progressDialogUtil.Dismiss();
    Intent selectBikeActivity = new Intent(getApplicationContext(), SelectBike.class);
    startActivity(selectBikeActivity); // Here Raised Exception
    finish();
}
......
</code>```

StackTrace is

```<code> android.content.ActivityNotFoundException: Unable to find explicit activity class {com.yego.motodriver/com.yego.motodriver.SelectBike}; have you declared this activity in your AndroidManifest.xml?
                                                 at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1805)
                                                 at android.app.Instrumentation.execStartActivity(Instrumentation.java:1523)
                                                 at android.app.Activity.startActivityForResult(Activity.java:3968)
                                                 at android.support.v4.app.BaseFragmentActivityJB.startActivityForResult(BaseFragmentActivityJB.java:50)
                                                 at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:79)
                                                 at android.app.Activity.startActivityForResult(Activity.java:3920)
                                                 at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:859)
                                                 at android.app.Activity.startActivity(Activity.java:4259)
                                                 at android.app.Activity.startActivity(Activity.java:4227)
                                                 at com.yego.motodriver.Login.HandleLoginResponse(Login.java:502)
                                                 at com.yego.motodriver.Login.access$300(Login.java:61)
                                                 at com.yego.motodriver.Login$4.onGRPCTaskCompleted(Login.java:233)
                                                 at com.yego.util.GrpcTask.onPostExecute(GrpcTask.java:297)
                                                 at com.yego.util.GrpcTask.onPostExecute(GrpcTask.java:38)
                                                 at android.os.AsyncTask.finish(AsyncTask.java:651)
                                                 at android.os.AsyncTask.-wrap1(AsyncTask.java)
                                                 at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:668)
                                                 at android.os.Handler.dispatchMessage(Handler.java:111)
                                                 at android.os.Looper.loop(Looper.java:207)
                                                 at android.app.ActivityThread.main(ActivityThread.java:5742)
                                                 at java.lang.reflect.Method.invoke(Native Method)
                                                 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
                                                 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)
</code>```

How to avoid this Exception ?

答:
You have not declare your activity in AndroidManifest.xml like :

```<code><activity
        android:name=".SelectBike"
        android:screenOrientation="portrait"
        android:windowSoftInputMode="adjustPan"/>
</code>```

Body:
I have been getting this error in my application for quite a sometime now at few client devices. I have posted a related question Here but found not useful answer.

After weeks of research and testing, i reproduce this error at development machine.

On login activity, after user insert required credentials and click Login button, I am running a AsyncTask to validate the credentials over the server. In between i am showing ProgressDialog to the user. In case if am locked the device during doInBackground execution using device hardware lock key or it dims by own and lock, PostExecute method throws exception. Following is code snippet of PostExecute. Normally without Locking the device it works well

if(EveryThing Goes Well)
{
    progressDialogUtil.Dismiss();
    Intent selectBikeActivity = new Intent(getApplicationContext(), SelectBike.class);
    startActivity(selectBikeActivity); // Here Raised Exception
    finish();
}
......

StackTrace is

 android.content.ActivityNotFoundException: Unable to find explicit activity class {com.yego.motodriver/com.yego.motodriver.SelectBike}; have you declared this activity in your AndroidManifest.xml?
                                                 at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1805)
                                                 at android.app.Instrumentation.execStartActivity(Instrumentation.java:1523)
                                                 at android.app.Activity.startActivityForResult(Activity.java:3968)
                                                 at android.support.v4.app.BaseFragmentActivityJB.startActivityForResult(BaseFragmentActivityJB.java:50)
                                                 at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:79)
                                                 at android.app.Activity.startActivityForResult(Activity.java:3920)
                                                 at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:859)
                                                 at android.app.Activity.startActivity(Activity.java:4259)
                                                 at android.app.Activity.startActivity(Activity.java:4227)
                                                 at com.yego.motodriver.Login.HandleLoginResponse(Login.java:502)
                                                 at com.yego.motodriver.Login.access$300(Login.java:61)
                                                 at com.yego.motodriver.Login$4.onGRPCTaskCompleted(Login.java:233)
                                                 at com.yego.util.GrpcTask.onPostExecute(GrpcTask.java:297)
                                                 at com.yego.util.GrpcTask.onPostExecute(GrpcTask.java:38)
                                                 at android.os.AsyncTask.finish(AsyncTask.java:651)
                                                 at android.os.AsyncTask.-wrap1(AsyncTask.java)
                                                 at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:668)
                                                 at android.os.Handler.dispatchMessage(Handler.java:111)
                                                 at android.os.Looper.loop(Looper.java:207)
                                                 at android.app.ActivityThread.main(ActivityThread.java:5742)
                                                 at java.lang.reflect.Method.invoke(Native Method)
                                                 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
                                                 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)

How to avoid this Exception ?

Body:
You have not declare your activity in AndroidManifest.xml like :

<activity
        android:name=".SelectBike"
        android:screenOrientation="portrait"
        android:windowSoftInputMode="adjustPan"/>


问:
Combine 2 lists, combinations between 2 lists but not within a list
I have

```<code>list1 <- c("A","B","C")
</code>```

and

```<code>list2 <- c(1,2,3)
</code>```

And I want a joined list:

```<code>list3 = c("A_1", "B_2", "C_3").
</code>```

I've looked everywhere but cannot find the answer.
I've tried mapply, combn, permn... All did not work. Any help is appreciated!

答:
We can do this with paste.  The input datasets are vectors

```<code>v1 <- paste(list1, list2, sep = "_")
dput(v1)
#c("A_1", "B_2", "C_3")
</code>```

But, if they are list elements and wanted a vector as output

```<code>paste(unlist(list1), unlist(list2), sep = "_")
</code>```

Body:
I have

list1 <- c("A","B","C")

and

list2 <- c(1,2,3)

And I want a joined list:

list3 = c("A_1", "B_2", "C_3").

I've looked everywhere but cannot find the answer.
I've tried mapply, combn, permn... All did not work. Any help is appreciated!

Body:
We can do this with paste.  The input datasets are vectors

v1 <- paste(list1, list2, sep = "_")
dput(v1)
#c("A_1", "B_2", "C_3")

But, if they are list elements and wanted a vector as output

paste(unlist(list1), unlist(list2), sep = "_")


问:
Can you or How can you make custom functions MongoDB like db.mydbname.customFunction()?
I'd like to know if you could write custom functions in MongoDB similar to a stored procedure for queries?</p>

答:
There is a special system collection named system.js that can store JavaScript functions for reuse.

NOTE:

Do not store application logic in the database. There are performance
  limitations to running JavaScript inside of MongoDB. Application code
  also is typically most effective when it shares version control with
  the application itself.

See The Reference.


问:
Display Shortcode on wordpress page
I want to display Shortcode on my WordPress documentation page.

```<code>[example parameter="something"]
</code>```

But it was executing the shortcode on my page. Instead of executing it just want to display the shortcode on my page.

Thanks in advance.

答:
Try this code :

```<code>echo do_shortcode( '[example parameter="something"]' );
</code>```

Hope it will work Properlly

Title: Display Shortcode on wordpress page

Body:
I want to display Shortcode on my WordPress documentation page.

[example parameter="something"]

But it was executing the shortcode on my page. Instead of executing it just want to display the shortcode on my page.

Thanks in advance.

Body:
Try this code :

echo do_shortcode( '[example parameter="something"]' );

Hope it will work Properlly


问:
Java libraries for converting between character encodings
The problem I am looking to solve is converting between unicode storage types. As I understand it, one character in UTF-8 can be represented by 1 to 4 bytes of data whereas a character in UTF-16 can be represented in 1-2, two bytes blocks of data. This variable length means it's a pain to convert between the two and produce something that is sensible in the english language. </p>

<p>What I am looking for is a library that would let me specify a language or locale, and a storage mechanism (utf-8 etc.) and have it produce a more sensible result. Am I dreaming in the clouds?  </p>

答: You mean like java.io.Reader/Writer or java.nio.charset?</p>

ContentLicense: CC BY-SA 2.5

Body:
The problem I am looking to solve is converting between unicode storage types. As I understand it, one character in UTF-8 can be represented by 1 to 4 bytes of data whereas a character in UTF-16 can be represented in 1-2, two bytes blocks of data. This variable length means it's a pain to convert between the two and produce something that is sensible in the english language.

What I am looking for is a library that would let me specify a language or locale, and a storage mechanism (utf-8 etc.) and have it produce a more sensible result. Am I dreaming in the clouds?


问:
Switching from tensorflow on python 3.6 to python 3.5
This is my first question on stackoverflow, please bear with me as I will do my best to provide as much info as possible.

I have a windows 10, 6-bit processor.  My end goal is to use keras within spyder.  The first thing I did was update python to 3.6 and install tensorflow, which seemed to work.  When I attempted to get keras, however, it wasn't working, and I read that keras worked on python 3.5.  I successfully installed keras on python 3.5, which automatically installed theano as the backend.

But now I have two spyder environments, one running off of python 3.5, one off of 3.6.  The 3.5 reads keras but doesn't go through with any modules because it cannot find tensorflow.  The 3.6 can read tensorflow, but cannot find keras.

Please let me know what you would recommend.  Thank you!

答:
I had some issues with my tensorflow's installation too.
I personnaly used anaconda to solve the problem.
After installing anaconda (Maybe uninstall the old one if you already have one), launch an anaconda prompt and input conda create -n tensorflow python=3.5, afther that, you must activate it with activate tensorflow.
Once it's done, you have to install tensorflow on your python 3.5.
For that, use:

pip install --ignore-installed --upgrade https://storage.googleapis.com/tensorflow/windows/cpu/tensorflow-1.2.0rc1-cp35-cp35m-win_amd64.whl
for cpu version

pip install --ignore-installed --upgrade https://storage.googleapis.com/tensorflow/windows/gpu/tensorflow_gpu-1.2.0rc1-cp35-cp35m-win_amd64.whl for gpu version

You now have the r1.2 version of tensorflow.

Then, just use pip install keras and keras will be installed.

Now, all you have to do is launch anaconda navigator, select tensorflow on the scrolling menu and launch spyder/jupyter.
You can now use Keras with a tensorflow backend in Python 3.5

Hope it helped someone ! (It take me so much time to find it by myself)


问:
Ignore the first row when running the macro
I have the below macro to transfer data from one sheet to another. However I need the first row to be the date (date modified) so I need the macro to ignore the top row. I've looked online but can't seem to find the solution?

```<code>Sub HistoricMD()

    ActiveSheet.Range("K7:K15").Copy
    Sheets("Historic MD").Range("IV1").End(xlToLeft).Offset(1, 1).PasteSpecial xlValues
    Application.CutCopyMode = False

End Sub
</code>```

On another note I've just added

```<code>=IF(B2 >0,NOW(),"")
</code>```

to get the date modified, any other better solutions would be good!

Thank you :)

答:
Can't you just change this:

```<code>Sheets("Historic MD").Range("IV1").End(xlToLeft).Offset(1, 1).PasteSpecial xlValues
</code>```

To this:

```<code>Sheets("Historic MD").Range("IV2").End(xlToLeft).Offset(1, 1).PasteSpecial xlValues
</code>```

Body:
I have the below macro to transfer data from one sheet to another. However I need the first row to be the date (date modified) so I need the macro to ignore the top row. I've looked online but can't seem to find the solution?

Sub HistoricMD()

    ActiveSheet.Range("K7:K15").Copy
    Sheets("Historic MD").Range("IV1").End(xlToLeft).Offset(1, 1).PasteSpecial xlValues
    Application.CutCopyMode = False

End Sub

On another note I've just added

=IF(B2 >0,NOW(),"")

to get the date modified, any other better solutions would be good!

Thank you :)

Body:
Can't you just change this:

Sheets("Historic MD").Range("IV1").End(xlToLeft).Offset(1, 1).PasteSpecial xlValues

To this:

Sheets("Historic MD").Range("IV2").End(xlToLeft).Offset(1, 1).PasteSpecial xlValues


问:
How can I set up rule for selectable FullCalendar
I am trying to set up a rule for selectable attribute. The rule should be like this:
 selectable attribute is true for future weeks, otherwise false
However, I could not find how can I check dates in calendar option. I tried some ways but javascript does not accept these ways. Here is my current option. Any helps ?

```<code>$(document).ready(function () {

        $('#calendar').fullCalendar({
        //some options
        //some options

            selectable: true,
            selectHelper: true,

            select: function (start, end) {
                var title = loadRequired("ff8081815c776701015c7788151d06b4",
                    "activity",
                    "@Session["token"].ToString()");
                var eventData;
                if (title) {
                    eventData = {
                        title: title,
                        start: start,
                        end: end
                    };
                    $('#calendar').fullCalendar('renderEvent', eventData, true); // stick? = true
                }
                $('#calendar').fullCalendar('unselect');
            },
     });
</code>```

});

答:
I could be mistaken but because selectable is just a bool and doesn't accept a callback I don't think there is a nice way of doing this. I would probably set it to true and then catch it in the select callback.

In the select callback you could check if the selected date is in the future and if it is just call unselect and return from the function.

Body:
I am trying to set up a rule for selectable attribute. The rule should be like this:
 selectable attribute is true for future weeks, otherwise false
However, I could not find how can I check dates in calendar option. I tried some ways but javascript does not accept these ways. Here is my current option. Any helps ?

$(document).ready(function () {

        $('#calendar').fullCalendar({
        //some options
        //some options

            selectable: true,
            selectHelper: true,

            select: function (start, end) {
                var title = loadRequired("ff8081815c776701015c7788151d06b4",
                    "activity",
                    "@Session["token"].ToString()");
                var eventData;
                if (title) {
                    eventData = {
                        title: title,
                        start: start,
                        end: end
                    };
                    $('#calendar').fullCalendar('renderEvent', eventData, true); // stick? = true
                }
                $('#calendar').fullCalendar('unselect');
            },
     });

});


问:
Ruby on rails, delayed job :run_at variable
I am running a job which send data to a rest api.

After the completion of all those requests, I need a 10 minute delay then a method will be called which will process on those sent requests.

```<code>def self.batch_task(batch_params)
    # a very long code
    Batch.delay.check_requests
end
</code>```

My second method is check_requests

```<code>def self.check_requests
   puts 'hello darkness'
end

def check_requests
   self.check_requests
end
</code>```

at the end, i am calling handle_asynchronously

```<code>handle_asynchronously :batch_task
handle_asynchronously :check_requests, :run_at => Proc.new { 10.minutes.from_now }
</code>```

Batch_task runs correctly followed by check_reqeusts, but I am not getting any the 10-minute delay before the function check_requests.
My rake job is working fine. I also see the hello_darkness output in the console of rake jobs.

答:
Try using the delay like below in the batch_task method

```<code>def self.batch_task(batch_params)
  # a very long code
  Batch.delay(run_at: 10.minutes.from_now).check_requests
end

handle_asynchronously :batch_task
handle_asynchronously :check_requests
</code>```

Body:
I am running a job which send data to a rest api.

After the completion of all those requests, I need a 10 minute delay then a method will be called which will process on those sent requests.

def self.batch_task(batch_params)
    # a very long code
    Batch.delay.check_requests
end

My second method is check_requests

def self.check_requests
   puts 'hello darkness'
end

def check_requests
   self.check_requests
end

at the end, i am calling handle_asynchronously

handle_asynchronously :batch_task
handle_asynchronously :check_requests, :run_at => Proc.new { 10.minutes.from_now }

Batch_task runs correctly followed by check_reqeusts, but I am not getting any the 10-minute delay before the function check_requests.
My rake job is working fine. I also see the hello_darkness output in the console of rake jobs.

Body:
Try using the delay like below in the batch_task method

def self.batch_task(batch_params)
  # a very long code
  Batch.delay(run_at: 10.minutes.from_now).check_requests
end

handle_asynchronously :batch_task
handle_asynchronously :check_requests


问:
Create a Dynamic Angular Directive
I have a html snippet that I'm now having to duplicate a lot which brings me to my question as I'd like to make the html snippet into a directive that can be reused.
I'd like to transform the snippet below into a directive.

```<code>  <a href="#"
    ng-click="vm.orderBy ='UserName'; reverseSort = !reverseSort">
                                    User Name
                                    <span ng-show="vm.orderBy == 'UserName'">
                                        <span ng-show="!reverseSort"><i class="fa fa-sort-alpha-asc"></i></span>
                                        <span ng-show="reverseSort"><i class="fa fa-sort-alpha-desc"></i></span>
                                    </span>
    </a>
</code>```

What I'd  like is a directive that allows me to pass any  string property to the orderBy field which would make it dynamic.
so something like <my-directive sort = 'Username'></my-directive>
I have  vm.orderBy = '' initialised in my main controller.

答:
I was able to sort this after all.

```<code>.directive("myDirective", function () {

        return {
            scope:{prop:'@'},
            templateUrl:'/templates/Sorter.html'

        }

    });
</code>```

and the html  like this.

```<code><my-directive prop="UserName"></my-directive>
</code>```

Title: Create a Dynamic Angular Directive

Body:
I have a html snippet that I'm now having to duplicate a lot which brings me to my question as I'd like to make the html snippet into a directive that can be reused.
I'd like to transform the snippet below into a directive.

                                    User Name

What I'd  like is a directive that allows me to pass any  string property to the orderBy field which would make it dynamic.
so something like <my-directive sort = 'Username'></my-directive>
I have  vm.orderBy = '' initialised in my main controller.

Body:
I was able to sort this after all.

.directive("myDirective", function () {

        return {
            scope:{prop:'@'},
            templateUrl:'/templates/Sorter.html'

        }

    });

and the html  like this.

<my-directive prop="UserName"></my-directive>


问:
the simcardio is not available in java 1.7?
I am trying to work the Java smartcardio API but I can not find its classes in Java 1.7.  At this page stands it is in JSR 268 which was released on 11 Dec, 2006
https://docs.oracle.com/javase/7/docs/jre/api/security/smartcardio/spec/
Do someone know the reason why I can not import the ATR classes? Do I have to import the api? if yes where can I find the jar?

答: What worked for me is the following:

Body: What worked for me is the following:


问:
JS hover negative space between items
So I have a container with a grid of items and I want to be able to detect hover between rows. Not the individual items.

Its important to remember that the number of items, in the container and per row, will change.

My container of items currently looks like this

```<code><div class="container">
    <div class="hover-placeholder"></div>
    <div class="row">
        <!-- Start : Items -->
            <div class="col-md-3">...</div>
            <div class="col-md-3">...</div>
            <div class="col-md-3">...</div>
            <div class="col-md-3">...</div>
            ...
            <div class="col-md-3">...</div>
        <!-- End : Items -->
    </div>
</div>
</code>```

Preferably I DO NOT want to put a placeholder element every 4th item. Mainly because on smaller screens the number of items per row will reduce. This is why in my example above I have a single placeholder outside the grid that I want to transform: translateY(..) to the position between the hovered rows.

This is what I have currently: https://jsfiddle.net/0t8c0h4m/

Its nowhere near the result I am after but I have got to the point where I am overthinking it and getting stuck.

Any help would be great!

UPDATE

The goal for this functionality is when the user hovers the negative space, the .hover-placeholder will translate to that position and become visible. And when clicked will add a permanent separator between the rows.

SUCCESS!

I have solved my issue! Thank you all for your help.

Here is my solution: https://jsfiddle.net/0t8c0h4m/9/

答:
So I have come up with a solution to show dividers between each row using CSS. I just have been overthinking this issue.

I have added a dividing element after each item and with css nth-child() I can show specific dividers at each break point.

I have also added the grouping functionality I was aiming for.

Updated example: https://jsfiddle.net/0t8c0h4m/9/

Title: JS hover negative space between items

Body:
So I have a container with a grid of items and I want to be able to detect hover between rows. Not the individual items.

Its important to remember that the number of items, in the container and per row, will change.

My container of items currently looks like this

...

...

...

...

            ...

...

Preferably I DO NOT want to put a placeholder element every 4th item. Mainly because on smaller screens the number of items per row will reduce. This is why in my example above I have a single placeholder outside the grid that I want to transform: translateY(..) to the position between the hovered rows.

This is what I have currently: https://jsfiddle.net/0t8c0h4m/

Its nowhere near the result I am after but I have got to the point where I am overthinking it and getting stuck.

Any help would be great!

UPDATE

The goal for this functionality is when the user hovers the negative space, the .hover-placeholder will translate to that position and become visible. And when clicked will add a permanent separator between the rows.

SUCCESS!

I have solved my issue! Thank you all for your help.

Here is my solution: https://jsfiddle.net/0t8c0h4m/9/


问:
Write Once, Test Everywhere - Selenium and Python's unittest on desktop and mobile
I'm working with Selenium and Python's unittest and I'm creating test cases for desktop, tablet and mobile websites. However, it's not ideal to have three test cases that test on same things.

At the moment, I put self.driver.set_window_size(1366, 768) in the desktop's test method and self.driver.set_window_size(414, 736) in the mobile's test method. So I have two test methods that do the same job mostly.

I am looking for some ways to encapsulate the set_window_size() and to have one test method, maybe with the if loop to test on some elements that may only appear on mobile or desktop websites.

答:
Refactor to place common code into a separate method.

```<code>class Mytest(unittest.TestCase):

    def do_test(self):
        # your actual test code

    def test_something_mobile(self):
        self.driver.set_window_size(1366, 768)
        self.do_test()

    def test_something_mobile(self):
        self.driver.set_window_size(414, 768)
        self.do_test()
</code>```

the above code assumes that the driver is initialized elsewhere typically done in __init__

Body:
Refactor to place common code into a separate method.

class Mytest(unittest.TestCase):

    def do_test(self):
        # your actual test code

    def test_something_mobile(self):
        self.driver.set_window_size(1366, 768)
        self.do_test()

    def test_something_mobile(self):
        self.driver.set_window_size(414, 768)
        self.do_test()

the above code assumes that the driver is initialized elsewhere typically done in __init__


问:
PHP / MySQL - Search query
I need help making a search query for comments (it's for a WordPress site).

the comments are retrieved this way- if user is logged in:

```<code>       $comments = $wpdb->get_results($wpdb->prepare("
       SELECT * FROM $wpdb->comments WHERE comment_post_ID = %d
       AND (comment_approved = '1' OR (user_id = %d AND comment_approved = '0'))
       ORDER BY comment_date_gmt", $post->ID, $user_ID));
</code>```

if not:

```<code>       $comments = $wpdb->get_results($wpdb->prepare("
       SELECT * FROM $wpdb->comments WHERE comment_post_ID = %d
       AND (comment_approved = '1' OR (comment_author = %s
         AND comment_author_email = %s AND comment_approved = '0'))
       ORDER BY comment_date_gmt",
       $post->ID, wp_specialchars_decode($comment_author,ENT_QUOTES),
       $comment_author_email));
</code>```

so I how can I filter comments that contain a specific search string, like $_GET['search_query'] ?

this is WP's database structure. The search string I'm looking for is in comment_content

答:
You can put them all in an array and use array_search:

http://il2.php.net/manual/en/function.array-search.php

You can also use wp google search query widge. i used it before and
it's great:

http://www.lautr.com/wp-google-search-query-widget-wordpress-plugin

Title: PHP / MySQL - Search query

Body:
I need help making a search query for comments (it's for a WordPress site).

the comments are retrieved this way- if user is logged in:

       $comments = $wpdb->get_results($wpdb->prepare("
       SELECT * FROM $wpdb->comments WHERE comment_post_ID = %d
       AND (comment_approved = '1' OR (user_id = %d AND comment_approved = '0'))
       ORDER BY comment_date_gmt", $post->ID, $user_ID));

if not:

       $comments = $wpdb->get_results($wpdb->prepare("
       SELECT * FROM $wpdb->comments WHERE comment_post_ID = %d
       AND (comment_approved = '1' OR (comment_author = %s
         AND comment_author_email = %s AND comment_approved = '0'))
       ORDER BY comment_date_gmt",
       $post->ID, wp_specialchars_decode($comment_author,ENT_QUOTES),
       $comment_author_email));

so I how can I filter comments that contain a specific search string, like $_GET['search_query'] ?

this is WP's database structure. The search string I'm looking for is in comment_content


问:
Pass a value to an on-click function
I have this API that I'm currently using to output a short URL or URL generator. Is there a way to pass the output to an on-click function.

The first script shows the API running

```<code>  var base_url      = window.location.origin,
      hash_bang     = "/#/sign-up?referral=",
      login         = "login",
      api_key       = "api_key";

  function get_short_url(login, api_key, func, value) {
      var value = document.getElementById('input-refcode').value;

      $.getJSON(
          "https://api-ssl.bitly.com//v3/shorten?callback=?",
          {
              "format": "json",
              "apiKey": api_key,
              "login": login,
              "longUrl": base_url + hash_bang + value
          },

          function(response)
          {
              func(response.data.url);
          }
      );
  }
</code>```

Second is a script that shares a text via Twitter using on-click

```<code>  $('#twitter').on('click', function() {
      win = window.open('https://twitter.com/intent/tweet?text=Get Free Rides at Electric Studio! Sign up to purchase your first timer package! After your first ride, you get 1 ride on us!', '_blank');
      win.focus();

  });
</code>```

Is there a way to get the output from the first function get_short_url then bind it in a on-click like this for example

```<code>  $('#twitter').on('click', get_short_url(login, api_key, function(short_url)) {
      win = window.open('https://twitter.com/intent/tweet?text=Get Free Rides at Electric Studio! Sign up to purchase your first timer package! After your first ride, you get 1 ride on us!' + short_url, '_blank');
      win.focus();
  });
</code>```

I tried this solution but the browser flagged the function as a pop-up

```<code>  $('#twitter').on('click', function() {

     var base_url          = window.location.origin,
         hash_bang_twitter = "/%23/sign-up?referral=",
         referral_code      = document.getElementById('input-refcode').value;

       get_short_url(login, api_key, function(short_url) {
           win = window.open('https://twitter.com/intent/tweet?text=Get Free Rides at Electric Studio! Sign up ' + short_url + ' to purchase your first timer package! After your first ride, you get 1 ride on us!' + ' https://www.electricstudio.ph/', '_blank');
           win.focus();
       });
  });
</code>```

答:
There is no need to, you can simply wrap</p>

```<code>$('#twitter').on('click', function() {

    get_short_url(login, api_key, function(short_url) {

        win = ...
        win.focus();

    });

});
</code>```

Title: Pass a value to an on-click function

Body:
I have this API that I'm currently using to output a short URL or URL generator. Is there a way to pass the output to an on-click function.

The first script shows the API running

  var base_url      = window.location.origin,
      hash_bang     = "/#/sign-up?referral=",
      login         = "login",
      api_key       = "api_key";

  function get_short_url(login, api_key, func, value) {
      var value = document.getElementById('input-refcode').value;

      $.getJSON(
          "https://api-ssl.bitly.com//v3/shorten?callback=?",
          {
              "format": "json",
              "apiKey": api_key,
              "login": login,
              "longUrl": base_url + hash_bang + value
          },

          function(response)
          {
              func(response.data.url);
          }
      );
  }

Second is a script that shares a text via Twitter using on-click

  $('#twitter').on('click', function() {
      win = window.open('https://twitter.com/intent/tweet?text=Get Free Rides at Electric Studio! Sign up to purchase your first timer package! After your first ride, you get 1 ride on us!', '_blank');
      win.focus();

  });

Is there a way to get the output from the first function get_short_url then bind it in a on-click like this for example

  $('#twitter').on('click', get_short_url(login, api_key, function(short_url)) {
      win = window.open('https://twitter.com/intent/tweet?text=Get Free Rides at Electric Studio! Sign up to purchase your first timer package! After your first ride, you get 1 ride on us!' + short_url, '_blank');
      win.focus();
  });

I tried this solution but the browser flagged the function as a pop-up

  $('#twitter').on('click', function() {

     var base_url          = window.location.origin,
         hash_bang_twitter = "/%23/sign-up?referral=",
         referral_code      = document.getElementById('input-refcode').value;

       get_short_url(login, api_key, function(short_url) {
           win = window.open('https://twitter.com/intent/tweet?text=Get Free Rides at Electric Studio! Sign up ' + short_url + ' to purchase your first timer package! After your first ride, you get 1 ride on us!' + ' https://www.electricstudio.ph/', '_blank');
           win.focus();
       });
  });

Body:
There is no need to, you can simply wrap

$('#twitter').on('click', function() {

    get_short_url(login, api_key, function(short_url) {

        win = ...
        win.focus();

    });

});


问:
connection between 2 docker containers using docker compose
I have a 2 docker containers "restorecms_facade_1" (facade service) and "restorecms_identity_1" (identity service) running on same bridge "restorecms_default".

I have specified the host name as 'hostname: identity-srv' for identity service image in my docker compose file

The facade service has 5000 port exposed and it accepts my graphQL request.
This facade service will delegate the request to identity service ( dns name 'identity-srv') running on port 50051 but the request is currently timing out on facade service.

My docker container and bride network details are below.

I cannot even ping from facade service to identity service (but the other way around is possible).

Am I missing something here or do I need to add anything on facade service so that the connection goes through to identity service ?

Docker ps:

```<code>akumar@client3 /restore $ docker ps
CONTAINER ID        IMAGE                               COMMAND                  CREATED             STATUS                    PORTS                                                NAMES
4a8854ce4876        xxx/facade-srv          "node lib/index.js"      41 minutes ago      Up 41 minutes             0.0.0.0:5000->5000/tcp                               restorecms_facade_1
00f1f00ae2a6        xxx/identity-srv        "node service.js"        41 minutes ago      Up 41 minutes (healthy)   0.0.0.0:50051->50051/tcp                             restorecms_identity_1
</code>```

Docker inspect:

```<code>akumar@client3 /restore/identity-srv-TypeScript $ docker inspect restorecms_default
[
    {
        "Name": "restorecms_default",
        "Id": "102358eab67884f7d39b78fd0bcf1050499d3dc667eddab5e15086633185837d",
        "Created": "2017-06-08T10:40:59.672964582+02:00",
        "Scope": "local",
        "Driver": "bridge",
        "EnableIPv6": false,
        "IPAM": {
            "Driver": "default",
            "Options": null,
            "Config": [
                {
                    "Subnet": "172.18.0.0/16",
                    "Gateway": "172.18.0.1"
                }
            ]
        },
        "Internal": false,
        "Attachable": true,
        "Ingress": false,
        "Containers": {
            "00f1f00ae2a64f489a530a63a9fb57711618d5e67769b739db514b5f20b73d36": {
                "Name": "restorecms_identity_1",
                "EndpointID": "d005cdff65479817bf769e4b60a18769c40d9d9cae396f3c735c2e497d6e08a4",
                "MacAddress": "02:42:ac:12:00:09",
                "IPv4Address": "172.18.0.9/16",
                "IPv6Address": ""
            },
            "4a8854ce487698149072c224378f697e9309e32649f6010d2d8c4cc4f0bb3f42": {
                "Name": "restorecms_facade_1",
                "EndpointID": "2509c8e1444d27cbe8a3188412fcbfb1aab103ec2366c22f3ad614c684ef87ab",
                "MacAddress": "02:42:ac:12:00:0a",
                "IPv4Address": "172.18.0.10/16",
                "IPv6Address": ""
            }
        },
        "Options": {},
        "Labels": {
            "com.docker.compose.network": "default",
            "com.docker.compose.project": "restorecms"
        }
    }
]
</code>```

Hostnames and ping:

```<code>root@identity-srv:/# cat /etc/hostname
identity-srv

root@identity-srv:/# ping 4a8854ce4876
PING 4a8854ce4876 (172.18.0.10): 48 data bytes
56 bytes from 172.18.0.10: icmp_seq=0 ttl=64 time=0.241 ms
56 bytes from 172.18.0.10: icmp_seq=1 ttl=64 time=0.149 ms
56 bytes from 172.18.0.10: icmp_seq=2 ttl=64 time=0.165 ms
^C--- 4a8854ce4876 ping statistics ---
3 packets transmitted, 3 packets received, 0% packet loss
round-trip min/avg/max/stddev = 0.149/0.185/0.241/0.040 ms

root@4a8854ce4876:/# cat /etc/hostname
4a8854ce4876

root@4a8854ce4876:/# ping identity-srv
ping: unknown host
</code>```

My current docker-compose.yml (for identity and facade service) config are below:

```<code>identity:
    hostname: identity-srv
    image: xxx/identity-srv
    ports:
      - "50051:50051"
    depends_on:
      arangodb:
        condition: service_healthy
    links:
      - arangodb
      - kafka
    healthcheck:
      test: "exit 0"

  # Facade service
  facade:
    image: xxx/facade-srv
    ports:
      - "5000:5000"
    depends_on:
      identity:
        condition: service_healthy
      #resource:
      #  condition: service_healthy
    links:
      - identity
      - kafka
      - elasticsearch
      - arangodb
      - redis
</code>```

答:
Hostname only sets hostname "inside" the container. If you want to ping it from another one you need to use alias (default to service name) which you used in your links section.

ping identity

if you want use identity-srv you can use links this way:

...
links:
 - identity:identity-srv
...

Body:
I have a 2 docker containers "restorecms_facade_1" (facade service) and "restorecms_identity_1" (identity service) running on same bridge "restorecms_default".

I have specified the host name as 'hostname: identity-srv' for identity service image in my docker compose file

The facade service has 5000 port exposed and it accepts my graphQL request.
This facade service will delegate the request to identity service ( dns name 'identity-srv') running on port 50051 but the request is currently timing out on facade service.

My docker container and bride network details are below.

I cannot even ping from facade service to identity service (but the other way around is possible).

Am I missing something here or do I need to add anything on facade service so that the connection goes through to identity service ?

Docker ps:

akumar@client3 /restore $ docker ps
CONTAINER ID        IMAGE                               COMMAND                  CREATED             STATUS                    PORTS                                                NAMES
4a8854ce4876        xxx/facade-srv          "node lib/index.js"      41 minutes ago      Up 41 minutes             0.0.0.0:5000->5000/tcp                               restorecms_facade_1
00f1f00ae2a6        xxx/identity-srv        "node service.js"        41 minutes ago      Up 41 minutes (healthy)   0.0.0.0:50051->50051/tcp                             restorecms_identity_1

Docker inspect:

akumar@client3 /restore/identity-srv-TypeScript $ docker inspect restorecms_default
[
    {
        "Name": "restorecms_default",
        "Id": "102358eab67884f7d39b78fd0bcf1050499d3dc667eddab5e15086633185837d",
        "Created": "2017-06-08T10:40:59.672964582+02:00",
        "Scope": "local",
        "Driver": "bridge",
        "EnableIPv6": false,
        "IPAM": {
            "Driver": "default",
            "Options": null,
            "Config": [
                {
                    "Subnet": "172.18.0.0/16",
                    "Gateway": "172.18.0.1"
                }
            ]
        },
        "Internal": false,
        "Attachable": true,
        "Ingress": false,
        "Containers": {
            "00f1f00ae2a64f489a530a63a9fb57711618d5e67769b739db514b5f20b73d36": {
                "Name": "restorecms_identity_1",
                "EndpointID": "d005cdff65479817bf769e4b60a18769c40d9d9cae396f3c735c2e497d6e08a4",
                "MacAddress": "02:42:ac:12:00:09",
                "IPv4Address": "172.18.0.9/16",
                "IPv6Address": ""
            },
            "4a8854ce487698149072c224378f697e9309e32649f6010d2d8c4cc4f0bb3f42": {
                "Name": "restorecms_facade_1",
                "EndpointID": "2509c8e1444d27cbe8a3188412fcbfb1aab103ec2366c22f3ad614c684ef87ab",
                "MacAddress": "02:42:ac:12:00:0a",
                "IPv4Address": "172.18.0.10/16",
                "IPv6Address": ""
            }
        },
        "Options": {},
        "Labels": {
            "com.docker.compose.network": "default",
            "com.docker.compose.project": "restorecms"
        }
    }
]

Hostnames and ping:

root@identity-srv:/# cat /etc/hostname
identity-srv

root@identity-srv:/# ping 4a8854ce4876
PING 4a8854ce4876 (172.18.0.10): 48 data bytes
56 bytes from 172.18.0.10: icmp_seq=0 ttl=64 time=0.241 ms
56 bytes from 172.18.0.10: icmp_seq=1 ttl=64 time=0.149 ms
56 bytes from 172.18.0.10: icmp_seq=2 ttl=64 time=0.165 ms
^C--- 4a8854ce4876 ping statistics ---
3 packets transmitted, 3 packets received, 0% packet loss
round-trip min/avg/max/stddev = 0.149/0.185/0.241/0.040 ms

root@4a8854ce4876:/# cat /etc/hostname
4a8854ce4876

root@4a8854ce4876:/# ping identity-srv
ping: unknown host

My current docker-compose.yml (for identity and facade service) config are below:

identity:
    hostname: identity-srv
    image: xxx/identity-srv
    ports:
      - "50051:50051"
    depends_on:
      arangodb:
        condition: service_healthy
    links:
      - arangodb
      - kafka
    healthcheck:
      test: "exit 0"

  # Facade service
  facade:
    image: xxx/facade-srv
    ports:
      - "5000:5000"
    depends_on:
      identity:
        condition: service_healthy
      #resource:
      #  condition: service_healthy
    links:
      - identity
      - kafka
      - elasticsearch
      - arangodb
      - redis


答:
You can do either/both of these:

1) In the "select" callback, check the start/end dates. If they're before the date that you want to allow, then don't continue to process the code, just return false.

2) You could also set the validRange property so that events can't even be dragged onto the areas you choose to exclude: https://fullcalendar.io/docs/current_date/validRange/

Title: How can I set up rule for selectable FullCalendar


问:
How to automatically moving my cursor to div?
i'am trying to figure out, how to automatically moving my cursor to div? For example i clicked the green box then my cursor immediately moving to the white div.

i've trying to use jQuery .focus(); but it seems doesn't work.

答: You can't move your cursor with javascript. If its a focus-able element then you can transfer the focus to that element but can't move your cursor. </p>


问:
How to find the sum of items and create new object dynamically?
How can i model an object similar to target object from following data?If there any shorthands exists in ES6, Then it would be more suitable.

The data sample contains the information of people and the items they  collected.The people Max and Carol has collected the same stones with different values.If this occurs, this should be pushed as a new item in our target object.

Sample data

```<code>let people = [{
  "id": 1,                        // Person Id
  "name": "John",                 // Name of person
  "date": "2017-5-27",            // Date
  "totalAssets": 500,             // Sum of total (gems collected)
  "gems": [{                      // Gems collected from forest
    "total": 500,           // totalCollected * value
    "value": 100,           // Value of one gem (Ruby = 100)
    "totalCollected": 5,    // Total number
    "gemName": "Ruby",      // Gem name
    "gemCode": "GEM001"     // Gem code
  }]
}, {
  "id": 2,
  "name": "Max",
  "date": "2017-5-28",
  "totalAssets": 1300, // TotalAssets = Emerald.total + Moonstone.total
  "gems": [{
    "total": 900,
    "value": 150,
    "totalCollected": 6,
    "gemName": "Emerald",
    "gemCode": "GEM002"
  }, {
    "total": 400,
    "value": 250,
    "totalCollected": 2,
    "gemName": "Moonstone",
    "gemCode": "GEM003"
  }]
}, {
  "id": 3,
  "name": "Carol",
  "date": "2017-5-29",
  "totalAssets": 2900,
  "gems": [{
      "total": 1500,
      "value": 150,
      "totalCollected": 10,
      "gemName": "Emerald",
      "gemCode": "GEM002"
    }, {
      "total": 1000,
      "value": 200,
      "totalCollected": 5,
      "gemName": "Moonstone",
      "gemCode": "GEM003"
    },
    {
      "total": 400,
      "value": 100,
      "totalCollected": 4,
      "gemName": "Ruby",
      "gemCode": "GEM001"
    }
  ]
}]
</code>```

Compute total

```<code>computeTotal = () => {   //Mock target object function
 // Return target object

   "totalAssets": 4800, //Total assets of all people
   "gemsValueTotal":[{
     "gemName": "Ruby",
     "value": 100,
     "totalC0llected":9,
     "total": 900,
   },
   {
     "gemName": "Emerald",
     "value": 150,
     "totalC0llected":16,
     "total": 2400,
   },
   {
     "gemName": "MoonStone",
     "value": 200,
     "totalC0llected":5,
     "total": 1000,
   },
   {
     "gemName": "MoonStone", // Value changed so push as new item in object
     "value": 250,
     "totalC0llected":2,
     "total": 500,
   }
   ]
}
</code>```

I found some solution in this manner.

```<code> aggregateGems(data) {
   this.rows = [];
   let totalCollected = 0;
   let totalvalue = 0;
   return data.filter((item) => {
       item.gems.map(d => {
        let model: any = {};
        let totalAssets: number = 0;
        totalCollected += parseInt(d.totalCollected);
        totalvalue += parseInt(d.total);
        model.gemname = d.gemName;
        model.value = d.value;
        model.totalCollected = totalCollected;
        model.totalValue = totalValue;
        this.rows.push(model);
        debugger
       });
     },
   );
 }
</code>```

答:
You can do it using the Array.reduce function, in cooperation with the Array.forEach function.

```<code>// this will save the indexes of the gemNames and value in the output array (so you don't have to search for the index all of the time)
let gemNameValueIndex = {};
// this will reduce the people array in a new object, receiving the new object and the next person on each iteration
let totals = people.reduce( (current, person) => {

  // and for each person we need to iterate the gems
  person.gems.forEach( gem => {
    // each gem increases the total value
    current.totalAssets += gem.total;
    let key = gem.gemName + gem.value;
    let idx;
    if ((idx = gemNameValueIndex[key]) === undefined) {
      // no matching gem found, so add the index
      current.gemsValueTotal.push( {
        gemName: gem.gemName,
        value: gem.value,
        totalCollected: gem.totalCollected,
        total: gem.total
      } );
      // mark the index so it can be looked up for next iterations
      gemNameValueIndex[key] = current.gemsValueTotal.length - 1;
      return;
    }
    // update the already found index with the new totals
    current.gemsValueTotal[idx].totalCollected += gem.totalCollected;
    current.gemsValueTotal[idx].total += gem.total;
  });

  return current;
}, { totalAssets: 0, gemsValueTotal: [] } );
</code>```

Your totals object will now contain the data you were looking for (you can try it out in the snippet below).

The gemNameValueIndex will contain the gems per value as a key and the index in the resulting total object (but that object is only there to avoid looping all added gems in the gemsValueTotal to find the index based on gemName and value per gem that we need to compare)

let people = [{
  "id": 1,                        // Person Id
  "name": "John",                 // Name of person
  "date": "2017-5-27",            // Date
  "totalAssets": 500,             // Sum of total (gems collected)
  "gems": [{                      // Gems collected from forest
    "total": 500,           // totalCollected * value
    "value": 100,           // Value of one gem (Ruby = 100)
    "totalCollected": 5,    // Total number
    "gemName": "Ruby",      // Gem name
    "gemCode": "GEM001"     // Gem code
  }]
}, {
  "id": 2,
  "name": "Max",
  "date": "2017-5-28",
  "totalAssets": 1300, // TotalAssets = Emerald.total + Moonstone.total
  "gems": [{
    "total": 900,
    "value": 150,
    "totalCollected": 6,
    "gemName": "Emerald",
    "gemCode": "GEM002"
  }, {
    "total": 400,
    "value": 250,
    "totalCollected": 2,
    "gemName": "Moonstone",
    "gemCode": "GEM003"
  }]
}, {
  "id": 3,
  "name": "Carol",
  "date": "2017-5-29",
  "totalAssets": 2900,
  "gems": [{
      "total": 1500,
      "value": 150,
      "totalCollected": 10,
      "gemName": "Emerald",
      "gemCode": "GEM002"
    }, {
      "total": 1000,
      "value": 200,
      "totalCollected": 5,
      "gemName": "Moonstone",
      "gemCode": "GEM003"
    },
    {
      "total": 400,
      "value": 100,
      "totalCollected": 4,
      "gemName": "Ruby",
      "gemCode": "GEM001"
    }
  ]
}];

// this will save the indexes of the gemNames and value in the output array (so you don't have to search for the index all of the time)
let gemNameValueIndex = {};
// this will reduce the people array in a new object, receiving the new object and the next person on each iteration
let totals = people.reduce( (current, person) => {

  // and for each person we need to iterate the gems
  person.gems.forEach( gem => {
    // each gem increases the total value
    current.totalAssets += gem.total;
    let key = gem.gemName + gem.value;
    let idx;
    if ((idx = gemNameValueIndex[key]) === undefined) {
      // no matching gem found, so add the index
      current.gemsValueTotal.push( {
        gemName: gem.gemName,
        value: gem.value,
        totalCollected: gem.totalCollected,
        total: gem.total
      } );
      // mark the index so it can be looked up for next iterations
      gemNameValueIndex[key] = current.gemsValueTotal.length - 1;
      return;
    }
    // update the already found index with the new totals
    current.gemsValueTotal[idx].totalCollected += gem.totalCollected;
    current.gemsValueTotal[idx].total += gem.total;
  });

  return current;
}, { totalAssets: 0, gemsValueTotal: [] } );

console.log( totals );```

Body:
How can i model an object similar to target object from following data?If there any shorthands exists in ES6, Then it would be more suitable.

The data sample contains the information of people and the items they  collected.The people Max and Carol has collected the same stones with different values.If this occurs, this should be pushed as a new item in our target object.

Sample data

let people = [{
  "id": 1,                        // Person Id
  "name": "John",                 // Name of person
  "date": "2017-5-27",            // Date
  "totalAssets": 500,             // Sum of total (gems collected)
  "gems": [{                      // Gems collected from forest
    "total": 500,           // totalCollected * value
    "value": 100,           // Value of one gem (Ruby = 100)
    "totalCollected": 5,    // Total number
    "gemName": "Ruby",      // Gem name
    "gemCode": "GEM001"     // Gem code
  }]
}, {
  "id": 2,
  "name": "Max",
  "date": "2017-5-28",
  "totalAssets": 1300, // TotalAssets = Emerald.total + Moonstone.total
  "gems": [{
    "total": 900,
    "value": 150,
    "totalCollected": 6,
    "gemName": "Emerald",
    "gemCode": "GEM002"
  }, {
    "total": 400,
    "value": 250,
    "totalCollected": 2,
    "gemName": "Moonstone",
    "gemCode": "GEM003"
  }]
}, {
  "id": 3,
  "name": "Carol",
  "date": "2017-5-29",
  "totalAssets": 2900,
  "gems": [{
      "total": 1500,
      "value": 150,
      "totalCollected": 10,
      "gemName": "Emerald",
      "gemCode": "GEM002"
    }, {
      "total": 1000,
      "value": 200,
      "totalCollected": 5,
      "gemName": "Moonstone",
      "gemCode": "GEM003"
    },
    {
      "total": 400,
      "value": 100,
      "totalCollected": 4,
      "gemName": "Ruby",
      "gemCode": "GEM001"
    }
  ]
}]

Compute total

computeTotal = () => {   //Mock target object function
 // Return target object

   "totalAssets": 4800, //Total assets of all people
   "gemsValueTotal":[{
     "gemName": "Ruby",
     "value": 100,
     "totalC0llected":9,
     "total": 900,
   },
   {
     "gemName": "Emerald",
     "value": 150,
     "totalC0llected":16,
     "total": 2400,
   },
   {
     "gemName": "MoonStone",
     "value": 200,
     "totalC0llected":5,
     "total": 1000,
   },
   {
     "gemName": "MoonStone", // Value changed so push as new item in object
     "value": 250,
     "totalC0llected":2,
     "total": 500,
   }
   ]
}

I found some solution in this manner.

 aggregateGems(data) {
   this.rows = [];
   let totalCollected = 0;
   let totalvalue = 0;
   return data.filter((item) => {
       item.gems.map(d => {
        let model: any = {};
        let totalAssets: number = 0;
        totalCollected += parseInt(d.totalCollected);
        totalvalue += parseInt(d.total);
        model.gemname = d.gemName;
        model.value = d.value;
        model.totalCollected = totalCollected;
        model.totalValue = totalValue;
        this.rows.push(model);
        debugger
       });
     },
   );
 }

Body:
You can do it using the Array.reduce function, in cooperation with the Array.forEach function.

// this will save the indexes of the gemNames and value in the output array (so you don't have to search for the index all of the time)
let gemNameValueIndex = {};
// this will reduce the people array in a new object, receiving the new object and the next person on each iteration
let totals = people.reduce( (current, person) => {

  // and for each person we need to iterate the gems
  person.gems.forEach( gem => {
    // each gem increases the total value
    current.totalAssets += gem.total;
    let key = gem.gemName + gem.value;
    let idx;
    if ((idx = gemNameValueIndex[key]) === undefined) {
      // no matching gem found, so add the index
      current.gemsValueTotal.push( {
        gemName: gem.gemName,
        value: gem.value,
        totalCollected: gem.totalCollected,
        total: gem.total
      } );
      // mark the index so it can be looked up for next iterations
      gemNameValueIndex[key] = current.gemsValueTotal.length - 1;
      return;
    }
    // update the already found index with the new totals
    current.gemsValueTotal[idx].totalCollected += gem.totalCollected;
    current.gemsValueTotal[idx].total += gem.total;
  });

  return current;
}, { totalAssets: 0, gemsValueTotal: [] } );

Your totals object will now contain the data you were looking for (you can try it out in the snippet below).

The gemNameValueIndex will contain the gems per value as a key and the index in the resulting total object (but that object is only there to avoid looping all added gems in the gemsValueTotal to find the index based on gemName and value per gem that we need to compare)

let people = [{
  "id": 1,                        // Person Id
  "name": "John",                 // Name of person
  "date": "2017-5-27",            // Date
  "totalAssets": 500,             // Sum of total (gems collected)
  "gems": [{                      // Gems collected from forest
    "total": 500,           // totalCollected * value
    "value": 100,           // Value of one gem (Ruby = 100)
    "totalCollected": 5,    // Total number
    "gemName": "Ruby",      // Gem name
    "gemCode": "GEM001"     // Gem code
  }]
}, {
  "id": 2,
  "name": "Max",
  "date": "2017-5-28",
  "totalAssets": 1300, // TotalAssets = Emerald.total + Moonstone.total
  "gems": [{
    "total": 900,
    "value": 150,
    "totalCollected": 6,
    "gemName": "Emerald",
    "gemCode": "GEM002"
  }, {
    "total": 400,
    "value": 250,
    "totalCollected": 2,
    "gemName": "Moonstone",
    "gemCode": "GEM003"
  }]
}, {
  "id": 3,
  "name": "Carol",
  "date": "2017-5-29",
  "totalAssets": 2900,
  "gems": [{
      "total": 1500,
      "value": 150,
      "totalCollected": 10,
      "gemName": "Emerald",
      "gemCode": "GEM002"
    }, {
      "total": 1000,
      "value": 200,
      "totalCollected": 5,
      "gemName": "Moonstone",
      "gemCode": "GEM003"
    },
    {
      "total": 400,
      "value": 100,
      "totalCollected": 4,
      "gemName": "Ruby",
      "gemCode": "GEM001"
    }
  ]
}];

// this will save the indexes of the gemNames and value in the output array (so you don't have to search for the index all of the time)
let gemNameValueIndex = {};
// this will reduce the people array in a new object, receiving the new object and the next person on each iteration
let totals = people.reduce( (current, person) => {

  // and for each person we need to iterate the gems
  person.gems.forEach( gem => {
    // each gem increases the total value
    current.totalAssets += gem.total;
    let key = gem.gemName + gem.value;
    let idx;
    if ((idx = gemNameValueIndex[key]) === undefined) {
      // no matching gem found, so add the index
      current.gemsValueTotal.push( {
        gemName: gem.gemName,
        value: gem.value,
        totalCollected: gem.totalCollected,
        total: gem.total
      } );
      // mark the index so it can be looked up for next iterations
      gemNameValueIndex[key] = current.gemsValueTotal.length - 1;
      return;
    }
    // update the already found index with the new totals
    current.gemsValueTotal[idx].totalCollected += gem.totalCollected;
    current.gemsValueTotal[idx].total += gem.total;
  });

  return current;
}, { totalAssets: 0, gemsValueTotal: [] } );

console.log( totals );


问:
Remove text line in XML file C# .NET
i need to write app to remove specific text line in very large XML file (about 3,5 GB).

I wrote this code:

```<code>    string directoryPath;

    OpenFileDialog ofd = new OpenFileDialog();

    private void button1_Click(object sender, EventArgs e)
    {
        ofd.Filter = "XML|*.xml";
        if (ofd.ShowDialog() == DialogResult.OK)
        {
            directoryPath = Path.GetDirectoryName(ofd.FileName);
            textBox2.Text = directoryPath;
            textBox1.Text = ofd.SafeFileName;
        }
    }

    private void Replace()
    {
        StreamReader readerFile = new StreamReader(ofd.FileName, System.Text.Encoding.UTF8);

        while (!readerFile.EndOfStream)
        {
            string stringReplaced;
            string replaceResult = textBox2.Text + "\\" + "replace_results";
            Directory.CreateDirectory(replaceResult);
            StreamWriter writerFile = new StreamWriter(replaceResult + "\\" + textBox1.Text, true);
            StringBuilder sb = new StringBuilder();
            char[] buff = new char[10 * 1024 * 1024];
            int xx = readerFile.ReadBlock(buff, 0, buff.Length);
            sb.Append(buff);
            stringReplaced = sb.ToString();
            stringReplaced = stringReplaced.Replace("line to remove", string.Empty);
            writerFile.WriteLine(stringReplaced);
            writerFile.Close();
            writerFile.Dispose();
            stringReplaced = null;
            sb = null;
        }

        readerFile.Close();
        readerFile.Dispose();
    }

    private void button2_Click(object sender, EventArgs e)
    {
        if (!backgroundWorker1.IsBusy)
        {
            backgroundWorker1.RunWorkerAsync();
            toolStripStatusLabel1.Text = "Replacing in progress...";
        }
    }

    private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
        try
        {
            Replace();
            toolStripStatusLabel1.Text = "Replacing complete!";
        }
        catch
        {
            toolStripStatusLabel1.Text = "Error! Replacing aborted!";
        }
    }
}
</code>```

it works, but not as well because new file (after remove lines) is bigger than original file and at the end of new file are added some junk (lots of dots), screenshot:

https://images81.fotosik.pl/615/873833aa0e23b36f.jpg

How i can fix my code to make new file the same as old file, only without specific lines?

答:
I trying do this by XmlTextReader but i have system.xml.xmlexception during read my file, screenshot: https://images82.fotosik.pl/622/d98b35587b0befa4.jpg

Code:

```<code>XmlTextReader xmlReader = new XmlTextReader(ofd.FileName);
XmlDocument doc = new XmlDocument();
doc.Load(xmlReader);
</code>```

Title: Remove text line in XML file C# .NET

Body:
i need to write app to remove specific text line in very large XML file (about 3,5 GB).

I wrote this code:

    string directoryPath;

    OpenFileDialog ofd = new OpenFileDialog();

    private void button1_Click(object sender, EventArgs e)
    {
        ofd.Filter = "XML|*.xml";
        if (ofd.ShowDialog() == DialogResult.OK)
        {
            directoryPath = Path.GetDirectoryName(ofd.FileName);
            textBox2.Text = directoryPath;
            textBox1.Text = ofd.SafeFileName;
        }
    }

    private void Replace()
    {
        StreamReader readerFile = new StreamReader(ofd.FileName, System.Text.Encoding.UTF8);

        while (!readerFile.EndOfStream)
        {
            string stringReplaced;
            string replaceResult = textBox2.Text + "\\" + "replace_results";
            Directory.CreateDirectory(replaceResult);
            StreamWriter writerFile = new StreamWriter(replaceResult + "\\" + textBox1.Text, true);
            StringBuilder sb = new StringBuilder();
            char[] buff = new char[10 * 1024 * 1024];
            int xx = readerFile.ReadBlock(buff, 0, buff.Length);
            sb.Append(buff);
            stringReplaced = sb.ToString();
            stringReplaced = stringReplaced.Replace("line to remove", string.Empty);
            writerFile.WriteLine(stringReplaced);
            writerFile.Close();
            writerFile.Dispose();
            stringReplaced = null;
            sb = null;
        }

        readerFile.Close();
        readerFile.Dispose();
    }

    private void button2_Click(object sender, EventArgs e)
    {
        if (!backgroundWorker1.IsBusy)
        {
            backgroundWorker1.RunWorkerAsync();
            toolStripStatusLabel1.Text = "Replacing in progress...";
        }
    }

    private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
        try
        {
            Replace();
            toolStripStatusLabel1.Text = "Replacing complete!";
        }
        catch
        {
            toolStripStatusLabel1.Text = "Error! Replacing aborted!";
        }
    }
}

it works, but not as well because new file (after remove lines) is bigger than original file and at the end of new file are added some junk (lots of dots), screenshot:

https://images81.fotosik.pl/615/873833aa0e23b36f.jpg

How i can fix my code to make new file the same as old file, only without specific lines?

Body:
I trying do this by XmlTextReader but i have system.xml.xmlexception during read my file, screenshot: https://images82.fotosik.pl/622/d98b35587b0befa4.jpg

Code:

XmlTextReader xmlReader = new XmlTextReader(ofd.FileName);
XmlDocument doc = new XmlDocument();
doc.Load(xmlReader);


问:
How do I transform/fork a Kafka stream and send it over to a specific topic?
I am Trying to transform the string value obtained in my original stream "textlines" into JSONObject Messages using the function "mapValues" into newStream. Then stream whatever I get in newStream onto a topic called "testoutput". But everytime a message actually goes through the transformation block I get a NullPointerException with errors pointing only into kafka stream libraries. Have no idea what is going on :((

P.S. When I fork/create a new kafka stream from the original stream, does the new stream belong to the original builder? Since I need builder to create the KafkaStreams Object and start streaming I am not sure if I need to do something else with the new stream other than just specifying where its going .to("topic")

```<code>//Testing a Kafka Stream Application
public class testStream {

public static void main(String[] args) throws Exception {
    //Configurations
    Properties props = new Properties();
    props.put(StreamsConfig.APPLICATION_ID_CONFIG, "streams-teststream");
    props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "xxxxxxxxxxxx:xxxx");
    props.put(StreamsConfig.KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass().getName());
    props.put(StreamsConfig.VALUE_SERDE_CLASS_CONFIG, Serdes.String().getClass().getName());
    props.put(StreamsConfig.TIMESTAMP_EXTRACTOR_CLASS_CONFIG, WallclockTimestampExtractor.class);
    props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "latest");

    //Building Stream
    KStreamBuilder builder = new KStreamBuilder();
    KStream<String, String> textlines = builder.stream("mytest2");

    //Printout The Inputs just for testing purposes
    textlines.foreach(new ForeachAction<String, String>(){
        public void apply(String key, String value){
            for(int y=0; y<value.length(); y++){
                System.out.print(value.charAt(y));
            }
            System.out.print("\n");
        }
    });

    //Transform String Records to JSON Objects
    KStream<String, JSONObject> newStream = textlines.mapValues(new ValueMapper<String,JSONObject>(){
        @Override
        public JSONObject apply(String value) {

            JSONObject jsnobj = new JSONObject();

            //If the first 4 letters of the message is "xxxx" then parse it to a
            //JSON Object, otherwise create a dummy
            if(value.substring(0, 4).equals("xxxx")){
                jsnobj.put("Header_Title", value.substring(0, 4));
                jsnobj.put("Data_Part", value.substring(4));
            }else{
                jsnobj.put("Header_Title", "Not xxxx");
                jsnobj.put("Data_Part", "None");
            }
            return jsnobj;
        }
    });

    //Specify target
    newStream.to("testoutput");

    //Off you go
    KafkaStreams streams=new KafkaStreams(builder, props);
    streams.start();

  }
}
</code>```

答:
From what I can tell your problem is this line:

```<code>newStream.to("testoutput");
</code>```

newStream has the type KStream<String, JSONObject>.

However, your application is configured to use, by default, a String serde to serialize/deserialize record keys and record values:

```<code>props.put(StreamsConfig.KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass().getName());
props.put(StreamsConfig.VALUE_SERDE_CLASS_CONFIG, Serdes.String().getClass().getName());
</code>```

This means that, when you do not provide explicit serdes in the to() call, Kafka Streams will attempt to write your newStream as KStream<String, String> (rather than KStream<String, JSONObject>) back to Kafka.

What you need to do is to provide explicit serdes in the to() call:

```<code>// Sth like this
newStream.to(Serdes.String(), myJsonSerde, "testoutput");
</code>```

Unfortunately, Kafka doesn't include an out-of-the-box JSON serde yet (it's planned).  Fortunately, you can look at (and copy) the example JSON serde included in Kafka's own demo applications for the Kafka Streams API: https://github.com/apache/kafka/tree/trunk/streams/examples/src/main/java/org/apache/kafka/streams/examples/pageview

Body:
I am Trying to transform the string value obtained in my original stream "textlines" into JSONObject Messages using the function "mapValues" into newStream. Then stream whatever I get in newStream onto a topic called "testoutput". But everytime a message actually goes through the transformation block I get a NullPointerException with errors pointing only into kafka stream libraries. Have no idea what is going on :((

P.S. When I fork/create a new kafka stream from the original stream, does the new stream belong to the original builder? Since I need builder to create the KafkaStreams Object and start streaming I am not sure if I need to do something else with the new stream other than just specifying where its going .to("topic")

//Testing a Kafka Stream Application
public class testStream {

public static void main(String[] args) throws Exception {
    //Configurations
    Properties props = new Properties();
    props.put(StreamsConfig.APPLICATION_ID_CONFIG, "streams-teststream");
    props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "xxxxxxxxxxxx:xxxx");
    props.put(StreamsConfig.KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass().getName());
    props.put(StreamsConfig.VALUE_SERDE_CLASS_CONFIG, Serdes.String().getClass().getName());
    props.put(StreamsConfig.TIMESTAMP_EXTRACTOR_CLASS_CONFIG, WallclockTimestampExtractor.class);
    props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "latest");

    //Building Stream
    KStreamBuilder builder = new KStreamBuilder();
    KStream<String, String> textlines = builder.stream("mytest2");

    //Printout The Inputs just for testing purposes
    textlines.foreach(new ForeachAction<String, String>(){
        public void apply(String key, String value){
            for(int y=0; y<value.length(); y++){
                System.out.print(value.charAt(y));
            }
            System.out.print("\n");
        }
    });

    //Transform String Records to JSON Objects
    KStream<String, JSONObject> newStream = textlines.mapValues(new ValueMapper<String,JSONObject>(){
        @Override
        public JSONObject apply(String value) {

            JSONObject jsnobj = new JSONObject();

            //If the first 4 letters of the message is "xxxx" then parse it to a
            //JSON Object, otherwise create a dummy
            if(value.substring(0, 4).equals("xxxx")){
                jsnobj.put("Header_Title", value.substring(0, 4));
                jsnobj.put("Data_Part", value.substring(4));
            }else{
                jsnobj.put("Header_Title", "Not xxxx");
                jsnobj.put("Data_Part", "None");
            }
            return jsnobj;
        }
    });

    //Specify target
    newStream.to("testoutput");

    //Off you go
    KafkaStreams streams=new KafkaStreams(builder, props);
    streams.start();

  }
}

Body:
From what I can tell your problem is this line:

newStream.to("testoutput");

newStream has the type KStream<String, JSONObject>.

However, your application is configured to use, by default, a String serde to serialize/deserialize record keys and record values:

props.put(StreamsConfig.KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass().getName());
props.put(StreamsConfig.VALUE_SERDE_CLASS_CONFIG, Serdes.String().getClass().getName());

This means that, when you do not provide explicit serdes in the to() call, Kafka Streams will attempt to write your newStream as KStream<String, String> (rather than KStream<String, JSONObject>) back to Kafka.

What you need to do is to provide explicit serdes in the to() call:

// Sth like this
newStream.to(Serdes.String(), myJsonSerde, "testoutput");

Unfortunately, Kafka doesn't include an out-of-the-box JSON serde yet (it's planned).  Fortunately, you can look at (and copy) the example JSON serde included in Kafka's own demo applications for the Kafka Streams API: https://github.com/apache/kafka/tree/trunk/streams/examples/src/main/java/org/apache/kafka/streams/examples/pageview


问:
FancyBox iFrame body background-color
Hey everyone I'm trying to change the body background-color of the body in the iFrame generated by FancyBox.

It currently looks like this:

Of course this is not what I want, so this is why I'm trying to change the background color to something like transparent.

答:
You can set/change background color for element containing iframe and iframe element itself -

```<code>.fancybox-slide--iframe .fancybox-content,
.fancybox-slide--iframe iframe {
    background: #fff;
}
</code>```

But for iframed page - you have to set it within the page.

Title: FancyBox iFrame body background-color

Body:
You can set/change background color for element containing iframe and iframe element itself -

.fancybox-slide--iframe .fancybox-content,
.fancybox-slide--iframe iframe {
    background: #fff;
}

But for iframed page - you have to set it within the page.


问:
How do I pass an array of Pointers to a structure and allocate the members
ok, heres my code.  I'm trying to pass an array of pointers to a structure to a function.
I need to dynamically allocate each structure and put a pointer to that structure in the array.
When I malloc the second time thru it gets a heap error.
HELP</p>

```<code>#define MAXSTRUCTS 50
#define MAXBUFF 100

typedef struct {
 char fullName[41];
 char address[41];
 char cityState[41];
 char zipcode[11];
} Persons;

int readData(Persons *structPtrs[]);

int main(void) {

     int totalStructs;
     Persons *structPtrs[MAXSTRUCTS];
     totalStructs = 0;
     structPtrs[0] = NULL;
     totalStructs = readData(structPtrs);
}

int readData(Persons *strptr[]) {

    int tStructs = 0;
    int recs;
    char inRecord[MAXBUFF];
    Persons *tmpPtr;
    tStructs = 0;
    for (recs=0; recs < MAXSTRUCTS; recs++) {
        if (gets(inRecord) != NULL) {
           strptr[recs] = (Persons *)malloc( sizeof(Persons));
           tmpPtr = strptr[recs];
           strncpy(tmpPtr->fullName,inRecord,MAXBUFF);
           gets(inRecord);
           strncpy(tmpPtr->address,inRecord,MAXBUFF);
           gets(inRecord);
           strncpy(tmpPtr->cityState,inRecord,MAXBUFF);
           gets(inRecord);
           strncpy(tmpPtr->zipcode,inRecord,MAXBUFF);
           strptr[recs] = tmpPtr;
           tStructs++;
        }
        else {
             if ( recs = 0 ) {
                exit (0);
             }
             recs=MAXSTRUCTS;
        }
    }
    return(tStructs);
}
</code>```

答:
You are doing everything right in regard of passing an array of pointers and allocating memory. What leading to a heap corruption is incorrect usage of strncpy function. The arrays where you are trying to copy data to are slightly smaller than MAXBUFF in all cases. To fix this, you have to specify the size of destination array instead of MAXBUFF. For example, instead of:

```<code>strncpy(tmpPtr->fullName,inRecord,MAXBUFF);
</code>```

... do (assuming that buffer is already filled with \0 symbols):

```<code>strncpy(tmpPtr->fullName,inRecord, sizeof(tmpPtr->fullName) - 1);
</code>```

Also, using gets function is not recommended as well as it could easily lead to buffer overruns. Try using fgets instead.

Here is your modified example that works:

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

#define MAXSTRUCTS 2
#define MAXBUFF 100

typedef struct {
  char fullName[41];
  char address[41];
  char cityState[41];
  char zipcode[11];
} Persons;

int readData(Persons *structPtrs[]);

int main ()
{
  int totalStructs;
  int recs;
  Persons *structPtrs[MAXSTRUCTS];
  totalStructs = 0;
  structPtrs[0] = NULL;
  totalStructs = readData(structPtrs);
  for(recs = 0; recs < totalStructs; ++recs) {
    printf ("Record #%d - %s\n", recs + 1, structPtrs[recs]->fullName);
  }
  return 0;
}

int readData(Persons *strptr[])
{
  int tStructs = 0;
  int recs;
  char inRecord[MAXBUFF];
  Persons *tmpPtr;
  tStructs = 0;
  for (recs=0; recs < MAXSTRUCTS; ++recs) {
    memset (inRecord, 0, sizeof(inRecord));
    if (fgets(inRecord, sizeof (inRecord) - 1, stdin))
      {
      strptr[recs] = (Persons *)malloc(sizeof(Persons));
      tmpPtr = strptr[recs];
      memset (tmpPtr, 0, sizeof(Persons));
      strncpy(tmpPtr->fullName,inRecord,sizeof(tmpPtr->fullName) - 1);
      fgets(inRecord, sizeof (inRecord) - 1, stdin);
      strncpy(tmpPtr->address,inRecord,sizeof(tmpPtr->address) - 1);
      fgets(inRecord, sizeof (inRecord) - 1, stdin);
      strncpy(tmpPtr->cityState,inRecord, sizeof(tmpPtr->cityState) - 1);
      fgets(inRecord, sizeof (inRecord) - 1, stdin);
      strncpy(tmpPtr->zipcode,inRecord, sizeof (tmpPtr->zipcode) - 1);
      strptr[recs] = tmpPtr;
      tStructs++;
    } else {
      if ( recs = 0 ) {
    exit (0);
      }
      recs=MAXSTRUCTS;
    }
  }
  return(tStructs);
}
</code>```

Body:
ok, heres my code.  I'm trying to pass an array of pointers to a structure to a function.
I need to dynamically allocate each structure and put a pointer to that structure in the array.
When I malloc the second time thru it gets a heap error.
HELP

#define MAXSTRUCTS 50
#define MAXBUFF 100

typedef struct {
 char fullName[41];
 char address[41];
 char cityState[41];
 char zipcode[11];
} Persons;

int readData(Persons *structPtrs[]);

int main(void) {

     int totalStructs;
     Persons *structPtrs[MAXSTRUCTS];
     totalStructs = 0;
     structPtrs[0] = NULL;
     totalStructs = readData(structPtrs);
}

int readData(Persons *strptr[]) {

    int tStructs = 0;
    int recs;
    char inRecord[MAXBUFF];
    Persons *tmpPtr;
    tStructs = 0;
    for (recs=0; recs < MAXSTRUCTS; recs++) {
        if (gets(inRecord) != NULL) {
           strptr[recs] = (Persons *)malloc( sizeof(Persons));
           tmpPtr = strptr[recs];
           strncpy(tmpPtr->fullName,inRecord,MAXBUFF);
           gets(inRecord);
           strncpy(tmpPtr->address,inRecord,MAXBUFF);
           gets(inRecord);
           strncpy(tmpPtr->cityState,inRecord,MAXBUFF);
           gets(inRecord);
           strncpy(tmpPtr->zipcode,inRecord,MAXBUFF);
           strptr[recs] = tmpPtr;
           tStructs++;
        }
        else {
             if ( recs = 0 ) {
                exit (0);
             }
             recs=MAXSTRUCTS;
        }
    }
    return(tStructs);
}

Body:
You are doing everything right in regard of passing an array of pointers and allocating memory. What leading to a heap corruption is incorrect usage of strncpy function. The arrays where you are trying to copy data to are slightly smaller than MAXBUFF in all cases. To fix this, you have to specify the size of destination array instead of MAXBUFF. For example, instead of:

strncpy(tmpPtr->fullName,inRecord,MAXBUFF);

... do (assuming that buffer is already filled with \0 symbols):

strncpy(tmpPtr->fullName,inRecord, sizeof(tmpPtr->fullName) - 1);

Also, using gets function is not recommended as well as it could easily lead to buffer overruns. Try using fgets instead.

Here is your modified example that works:

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#define MAXSTRUCTS 2
#define MAXBUFF 100

typedef struct {
  char fullName[41];
  char address[41];
  char cityState[41];
  char zipcode[11];
} Persons;

int readData(Persons *structPtrs[]);

int main ()
{
  int totalStructs;
  int recs;
  Persons *structPtrs[MAXSTRUCTS];
  totalStructs = 0;
  structPtrs[0] = NULL;
  totalStructs = readData(structPtrs);
  for(recs = 0; recs < totalStructs; ++recs) {
    printf ("Record #%d - %s\n", recs + 1, structPtrs[recs]->fullName);
  }
  return 0;
}

int readData(Persons *strptr[])
{
  int tStructs = 0;
  int recs;
  char inRecord[MAXBUFF];
  Persons *tmpPtr;
  tStructs = 0;
  for (recs=0; recs < MAXSTRUCTS; ++recs) {
    memset (inRecord, 0, sizeof(inRecord));
    if (fgets(inRecord, sizeof (inRecord) - 1, stdin))
      {
      strptr[recs] = (Persons *)malloc(sizeof(Persons));
      tmpPtr = strptr[recs];
      memset (tmpPtr, 0, sizeof(Persons));
      strncpy(tmpPtr->fullName,inRecord,sizeof(tmpPtr->fullName) - 1);
      fgets(inRecord, sizeof (inRecord) - 1, stdin);
      strncpy(tmpPtr->address,inRecord,sizeof(tmpPtr->address) - 1);
      fgets(inRecord, sizeof (inRecord) - 1, stdin);
      strncpy(tmpPtr->cityState,inRecord, sizeof(tmpPtr->cityState) - 1);
      fgets(inRecord, sizeof (inRecord) - 1, stdin);
      strncpy(tmpPtr->zipcode,inRecord, sizeof (tmpPtr->zipcode) - 1);
      strptr[recs] = tmpPtr;
      tStructs++;
    } else {
      if ( recs = 0 ) {
    exit (0);
      }
      recs=MAXSTRUCTS;
    }
  }
  return(tStructs);
}


问:
two big table join slow
this is a simple select query:

```<code>SELECT *
  from (select * from ods_rfx_prod where dt = '2017-06-07') p
  left join (select * from ods_rfx_prod_ext where dt = '2017-06-07') pt
    on p.prod_id = pt.prod_id
</code>```

two table (ods_rfx_prod,ods_rfx_prod_ext) all partitioned by 'dt' and stored as RCFile.

table p contains 3000w columns,table pt contains 3500w columns.
p.prod_id  and pt.prod_id has no null and blanks record.

it runs nearly for 40min~50min.
i don't know how to optimize it.

答:
You can try many different combinations to check if the performance increases.

1) As you have a where condition , check if the column is indexed

2) Since it is a date column you can create partitions on it

3) As you are joining on productID you can try to sort the data on productID and then apply the join

4) You can also try to create buckets by hashing the productID, so that the query can take advantage of map side join

Title: two big table join slow

Body:
this is a simple select query:

SELECT *
  from (select * from ods_rfx_prod where dt = '2017-06-07') p
  left join (select * from ods_rfx_prod_ext where dt = '2017-06-07') pt
    on p.prod_id = pt.prod_id

two table (ods_rfx_prod,ods_rfx_prod_ext) all partitioned by 'dt' and stored as RCFile.

table p contains 3000w columns,table pt contains 3500w columns.
p.prod_id  and pt.prod_id has no null and blanks record.

it runs nearly for 40min~50min.
i don't know how to optimize it.


问:
Contivo mapping analyst, mutliple integer to targer.
I am little bit stuck with contivo mapping analyst 5.6
issue is that I could not find any function to multiple some source value with another integer value.
Example

```<code>If Source exists
Move Source * 3 to Target
Else
Move -1 to target
EndIf
</code>```

Thanks

答:
You can use Compute method for contivo:

```<code>If Source exists
compute target = Source * 3
Else
Move -1 to target
EndIf
</code>```

Body:
I am little bit stuck with contivo mapping analyst 5.6
issue is that I could not find any function to multiple some source value with another integer value.
Example

If Source exists
Move Source * 3 to Target
Else
Move -1 to target
EndIf

Thanks

Body:
You can use Compute method for contivo:

If Source exists
compute target = Source * 3
Else
Move -1 to target
EndIf


问:
Automatically set = and IS in Python psycopg2 sql module
I have this snippet in Python using psycopg2:

```<code>spam = None
command = sql.SQL("= {}").format(sql.Literal(spam))
</code>```

Mogrifying the command gives "= NULL", which gives no results when included in the SQL query, since the query needs "IS NULL" to work.

(If spam is not None, but for example "eggs", "= 'eggs'" will work fine for the query.)

Is there a way to automatically switch between "IS" and "=" in the mogrified command, depending on whether the following argument is None or not None?

Thanks!

答:
No, but you can use is distinct from instead of = to include nulls in the comparison.

https://www.postgresql.org/docs/current/static/functions-comparison.html

Body:
I have this snippet in Python using psycopg2:

spam = None
command = sql.SQL("= {}").format(sql.Literal(spam))

Mogrifying the command gives "= NULL", which gives no results when included in the SQL query, since the query needs "IS NULL" to work.

(If spam is not None, but for example "eggs", "= 'eggs'" will work fine for the query.)

Is there a way to automatically switch between "IS" and "=" in the mogrified command, depending on whether the following argument is None or not None?

Thanks!


问:
choosing the order of prints in pthreads
I have some threads working on an array, and each of them sorts their part, in parallel with the others. I have a global array of pthread_t, in which i sort the id of each thread. Here is the part I can't figure out: After a thread is done with sorting I want it to print something, but the order must be from threads[MAX] to threads[0]. How do I do this? I tried to understand how to use pthread_cond_wait() and pthread_cond_signal() but I'm not even sure if this is what I need to do my job.

Essentially what I want is, my threads to work in parallel until they reach to a specific point, in which I want them to continue in a specific order.

答:
It is possible. I understand what's the reasoning behind such uni task. Nice one, I appreciate it, in some wicked manner. The algorithm is simple, however if you put something like that in a solution of real life problem you would be dommed. To put it simply: all threads, after doing their main job (sorting) must wait on barrier. When all of them reach the barrier, they wait on a separate entity and you need to trigger first one, then second, then another.

So, you need to find how to implement the barrier, every thread would wait on unless the last one reach it.

And hint for triggering: you need to trigger all of them at once. But only designed one would really process, and others would go back to waiting on the entity. (edit: it could be done in a better manner, but guess it for  yourself).

Do your work, do your research, show us some code, then you will receive some more detailed help.

BTW, there was some questions regarding to conditional variables in last 24 hours here on stack overflow. Go, look for them. You can find some explanation and some ideas to use in your task.