问:
Wordpress Override a function from a parent theme
I've installed a theme on my word press that uses Visual Composer. But after installing it I found out that the theme has disabled some element from Visual Composer. After quit some time i found the file that is being executed to remove these elements.

I created a child theme in order to override this function but with no luck.

the original function goes like this:

```<code>if ( ! function_exists('remove-elements-from-vc') ) {

function remove-elements-from-vc() {

    /*** Remove Grid Elements if grid elements disabled */
    vc_remove_element('vc_basic_grid');
    vc_remove_element('vc_media_grid');
    vc_remove_element('vc_masonry_grid');
    vc_remove_element('vc_masonry_media_grid');
    vc_remove_element('vc_icon');
    vc_remove_element('vc_button2');
    vc_remove_element("vc_custom_heading");

    /*** Remove unused parameters from grid elements */
    if (function_exists('vc_remove_param')) {
        vc_remove_param('vc_basic_grid', 'button_style');
        vc_remove_param('vc_basic_grid', 'button_color');
        vc_remove_param('vc_basic_grid', 'button_size');
        vc_remove_param('vc_basic_grid', 'filter_color');
        vc_remove_param('vc_basic_grid', 'filter_style');
        vc_remove_param('vc_media_grid', 'button_style');
        vc_remove_param('vc_media_grid', 'button_color');
        vc_remove_param('vc_media_grid', 'button_size');
        vc_remove_param('vc_media_grid', 'filter_color');
        vc_remove_param('vc_media_grid', 'filter_style');
        vc_remove_param('vc_masonry_grid', 'button_style');
        vc_remove_param('vc_masonry_grid', 'button_color');
        vc_remove_param('vc_masonry_grid', 'button_size');
        vc_remove_param('vc_masonry_grid', 'filter_color');
        vc_remove_param('vc_masonry_grid', 'filter_style');
        vc_remove_param('vc_masonry_media_grid', 'button_style');
        vc_remove_param('vc_masonry_media_grid', 'button_color');
        vc_remove_param('vc_masonry_media_grid', 'button_size');
        vc_remove_param('vc_masonry_media_grid', 'filter_color');
        vc_remove_param('vc_masonry_media_grid', 'filter_style');
        vc_remove_param('vc_basic_grid', 'paging_color');
        vc_remove_param('vc_basic_grid', 'arrows_color');
        vc_remove_param('vc_media_grid', 'paging_color');
        vc_remove_param('vc_media_grid', 'arrows_color');
        vc_remove_param('vc_masonry_grid', 'paging_color');
        vc_remove_param('vc_masonry_grid', 'arrows_color');
        vc_remove_param('vc_masonry_media_grid', 'paging_color');
        vc_remove_param('vc_masonry_media_grid', 'arrows_color');
    }
}

add_action('vc_after_init', 'remove-elements-from-vc');
}
</code>```

And this is what I'm trying to do in my child theme in functions.php:

```<code>add_action( 'vc_after_init', 'undo-remove-elements-from-vc' );
function undo-remove-elements-from-vc(){
    remove_action( 'vc_after_init', 'remove-elements-from-vc');
}
</code>```

the function that is causing this action is in a file called "visual-composer-config.php" and it's being loaded from a sibling file called "load.php"

```<code>if (visual_composer_installed()) {
include_once ELATED_FRAMEWORK_MODULES_ROOT_DIR.'/visualcomposer/visual-composer-functions.php';
include_once ELATED_FRAMEWORK_MODULES_ROOT_DIR.'/visualcomposer/visual-composer-config.php';
}
</code>```

I don't want to edit the original theme codes in case of any theme update later on, the changes will be removed. So i need to find a solution from the Child Theme.

Thanks

答:
Because the function in question is wrapped in if ( ! function_exists('') ) (read: "if this function does not exist") you should be able to declare it before the parent does. This will prevent the code inside the parent function from ever being run.

Note: I replaced your hyphens (-) because I haven't seen the hyphen syntax and went along assuming that is a typo. In my experience the proper syntax to use is underscores (_).

You would add something like this to your child theme's functions.php file:

```<code>function remove_elements_from_vc() {
    return;
}
</code>```

However, your remove_action() should work as well. It's possible you're function is hooking in before the parent theme's function is hooked. You can't remove an action until after it is added. From the codex:

You may need to prioritize the removal of the action to a hook that occurs after the action is added.

You cannot successfully remove the action before it has been added.

You also cannot remove an action after it has been run.

To remove an action the priority must match the priority with with the function was originally added.

If that is the case you could try to add it with a lesser priority:

```<code>add_action( 'vc_after_init', 'undo_remove_elements_from_vc', 20 );

function undo_remove_elements_from_vc(){
remove_action( 'vc_after_init', 'remove_elements_from_vc');
}
</code>```

Body:
I've installed a theme on my word press that uses Visual Composer. But after installing it I found out that the theme has disabled some element from Visual Composer. After quit some time i found the file that is being executed to remove these elements.

I created a child theme in order to override this function but with no luck.

the original function goes like this:

if ( ! function_exists('remove-elements-from-vc') ) {

function remove-elements-from-vc() {

    /*** Remove Grid Elements if grid elements disabled */
    vc_remove_element('vc_basic_grid');
    vc_remove_element('vc_media_grid');
    vc_remove_element('vc_masonry_grid');
    vc_remove_element('vc_masonry_media_grid');
    vc_remove_element('vc_icon');
    vc_remove_element('vc_button2');
    vc_remove_element("vc_custom_heading");

    /*** Remove unused parameters from grid elements */
    if (function_exists('vc_remove_param')) {
        vc_remove_param('vc_basic_grid', 'button_style');
        vc_remove_param('vc_basic_grid', 'button_color');
        vc_remove_param('vc_basic_grid', 'button_size');
        vc_remove_param('vc_basic_grid', 'filter_color');
        vc_remove_param('vc_basic_grid', 'filter_style');
        vc_remove_param('vc_media_grid', 'button_style');
        vc_remove_param('vc_media_grid', 'button_color');
        vc_remove_param('vc_media_grid', 'button_size');
        vc_remove_param('vc_media_grid', 'filter_color');
        vc_remove_param('vc_media_grid', 'filter_style');
        vc_remove_param('vc_masonry_grid', 'button_style');
        vc_remove_param('vc_masonry_grid', 'button_color');
        vc_remove_param('vc_masonry_grid', 'button_size');
        vc_remove_param('vc_masonry_grid', 'filter_color');
        vc_remove_param('vc_masonry_grid', 'filter_style');
        vc_remove_param('vc_masonry_media_grid', 'button_style');
        vc_remove_param('vc_masonry_media_grid', 'button_color');
        vc_remove_param('vc_masonry_media_grid', 'button_size');
        vc_remove_param('vc_masonry_media_grid', 'filter_color');
        vc_remove_param('vc_masonry_media_grid', 'filter_style');
        vc_remove_param('vc_basic_grid', 'paging_color');
        vc_remove_param('vc_basic_grid', 'arrows_color');
        vc_remove_param('vc_media_grid', 'paging_color');
        vc_remove_param('vc_media_grid', 'arrows_color');
        vc_remove_param('vc_masonry_grid', 'paging_color');
        vc_remove_param('vc_masonry_grid', 'arrows_color');
        vc_remove_param('vc_masonry_media_grid', 'paging_color');
        vc_remove_param('vc_masonry_media_grid', 'arrows_color');
    }
}

add_action('vc_after_init', 'remove-elements-from-vc');
}

And this is what I'm trying to do in my child theme in functions.php:

add_action( 'vc_after_init', 'undo-remove-elements-from-vc' );
function undo-remove-elements-from-vc(){
    remove_action( 'vc_after_init', 'remove-elements-from-vc');
}

the function that is causing this action is in a file called "visual-composer-config.php" and it's being loaded from a sibling file called "load.php"

if (visual_composer_installed()) {
include_once ELATED_FRAMEWORK_MODULES_ROOT_DIR.'/visualcomposer/visual-composer-functions.php';
include_once ELATED_FRAMEWORK_MODULES_ROOT_DIR.'/visualcomposer/visual-composer-config.php';
}

I don't want to edit the original theme codes in case of any theme update later on, the changes will be removed. So i need to find a solution from the Child Theme.

Thanks

Body:
Because the function in question is wrapped in if ( ! function_exists('') ) (read: "if this function does not exist") you should be able to declare it before the parent does. This will prevent the code inside the parent function from ever being run.

Note: I replaced your hyphens (-) because I haven't seen the hyphen syntax and went along assuming that is a typo. In my experience the proper syntax to use is underscores (_).

You would add something like this to your child theme's functions.php file:

function remove_elements_from_vc() {
    return;
}

However, your remove_action() should work as well. It's possible you're function is hooking in before the parent theme's function is hooked. You can't remove an action until after it is added. From the codex:

You may need to prioritize the removal of the action to a hook that occurs after the action is added.

You cannot successfully remove the action before it has been added.

You also cannot remove an action after it has been run.

To remove an action the priority must match the priority with with the function was originally added.

If that is the case you could try to add it with a lesser priority:

add_action( 'vc_after_init', 'undo_remove_elements_from_vc', 20 );

function undo_remove_elements_from_vc(){
remove_action( 'vc_after_init', 'remove_elements_from_vc');
}


来源: stackexchange

问:
Why can't we directly print the output of a lambda function/expression directly as a string,list, or tuple?
I am using Python 3. I am trying to write a lambda function/expression and generate a string type output. I am not sure what I am not understanding in this issue.

```<code>Cel = [39.5, 36.5, 37.3, 37.8]
Fer = lambda x: (float(9)/5*x for x in Cel + 32)
print(Fer)
</code>```

prints:

```<code><function <lambda> at 0x7fafc369eea0>
</code>```

But, I want the list of values as:

```<code>[103.1, 97.70, 99.14, 100.03]
</code>```

I then tried map with lambda

```<code>Fer2 = map(lambda x: (float(9)/5)*x + 32, Cel)
print(Fer2) # prints:
<map object at 0x7fafc36b5b38> # still no success

for x in Fer:
    print(x)  # this doesn't work and gives following error
TypeError: 'function' object is not iterable

for x in Fer2:
    print(x) # but this works and prints
             103.10
             97.7
             99.14
             100.039
</code>```

Why can't I get print(Fer or Fer2) simply as a a list of values, like:
[103.1, 97.70, 99.14, 100.03]

How do I solve this within lambda, without writing another def function?

答:
Personally I prefer to use map with a defined function as opposed to lambda

```<code>def func(e):
    return float(((9/5)*e)+32)
</code>```

Also if you want to create a list or tuple with map() in Python 3 you have to put list( or tuple( before map()

```<code>Cel = [39.5, 36.5, 37.3, 37.8]
Fer = list(map(func,Cel))
print (Fer)
</code>```

Also it seems like list comprehension is faster in this case (probably because Cel is short, over long lists and many function calls map would be slightly faster I think):

```<code>import time
Cel = [39.5, 36.5, 37.3, 37.8]

def func(e):
    return float(((9/5)*e)+32)

st = time.time()
for i in range(1000000):
    Fer = [32+float(9)/5*x for x in Cel]
end = time.time()
print ('COMP TIME: '+str(end-st))

st = time.time()
for i in range(1000000):
    Fer = list(map(func,Cel))
end = time.time()
print ('MAP TIME: '+str(end-st))
</code>```

Results:

```<code>COMP TIME: 1.8918001651763916
MAP TIME: 2.031294584274292
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am using Python 3. I am trying to write a lambda function/expression and generate a string type output. I am not sure what I am not understanding in this issue.

Cel = [39.5, 36.5, 37.3, 37.8]
Fer = lambda x: (float(9)/5*x for x in Cel + 32)
print(Fer)

prints:

<function <lambda> at 0x7fafc369eea0>

But, I want the list of values as:

[103.1, 97.70, 99.14, 100.03]

I then tried map with lambda

Fer2 = map(lambda x: (float(9)/5)*x + 32, Cel)
print(Fer2) # prints:
<map object at 0x7fafc36b5b38> # still no success

for x in Fer:
    print(x)  # this doesn't work and gives following error
TypeError: 'function' object is not iterable

for x in Fer2:
    print(x) # but this works and prints
             103.10
             97.7
             99.14
             100.039

Why can't I get print(Fer or Fer2) simply as a a list of values, like:
[103.1, 97.70, 99.14, 100.03]

How do I solve this within lambda, without writing another def function?

Body:
Personally I prefer to use map with a defined function as opposed to lambda

def func(e):
    return float(((9/5)*e)+32)

Also if you want to create a list or tuple with map() in Python 3 you have to put list( or tuple( before map()

Cel = [39.5, 36.5, 37.3, 37.8]
Fer = list(map(func,Cel))
print (Fer)

Also it seems like list comprehension is faster in this case (probably because Cel is short, over long lists and many function calls map would be slightly faster I think):

import time
Cel = [39.5, 36.5, 37.3, 37.8]

def func(e):
    return float(((9/5)*e)+32)

st = time.time()
for i in range(1000000):
    Fer = [32+float(9)/5*x for x in Cel]
end = time.time()
print ('COMP TIME: '+str(end-st))

st = time.time()
for i in range(1000000):
    Fer = list(map(func,Cel))
end = time.time()
print ('MAP TIME: '+str(end-st))

Results:

COMP TIME: 1.8918001651763916
MAP TIME: 2.031294584274292

ContentLicense: CC BY-SA 3.0


问:
Convert String to numeric vector
I have a function which takes a vector of zeros and ones for example:

```<code>foo(c(1,1,1,0,1,1))
</code>```

But in some cases, there are more then 100 numbers and I have to add all commas manually. Is there any predefined function to convert a string to such a vector? Something like this:

```<code>foo(unknown_function("111011"))
</code>```

答:
We can use paste

```<code>foo <- function(vec){
   paste(vec, collapse="")
  }

foo(c(1,1,1,0,1,1))
#[1] "111011"
</code>```

If we need to do the reverse

```<code>foo1 <- function(str1){
      as.integer(unlist(strsplit(str1, "")))
  }
res <- foo1("111011")
res
#[1] 1 1 1 0 1 1
</code>```

Or may be the OP meant

```<code>dput(res)
</code>```

Title: Convert String to numeric vector

Body:
I have a function which takes a vector of zeros and ones for example:

foo(c(1,1,1,0,1,1))

But in some cases, there are more then 100 numbers and I have to add all commas manually. Is there any predefined function to convert a string to such a vector? Something like this:

foo(unknown_function("111011"))

Body:
We can use paste

foo <- function(vec){
   paste(vec, collapse="")
  }

foo(c(1,1,1,0,1,1))
#[1] "111011"

If we need to do the reverse

foo1 <- function(str1){
      as.integer(unlist(strsplit(str1, "")))
  }
res <- foo1("111011")
res
#[1] 1 1 1 0 1 1

Or may be the OP meant

dput(res)


问:
How to filter all the fields in react?
How to filter all the fields in react?
I have written a code which only filters specified fields.

```<code> let filteredContacts=this.props.contacts.filter(
         (contact)=>{
           return contact.name.indexOf(this.state.search)!==-1;
         }
       );
</code>```

the above code only returns filtered names...but i want to filter name,age,city work.

this is the data file:

```<code>export default function(){
  return [{
    key: 1,
    name: 'Steve',
    city: 'Paris',
  }, {
    key: 2,
    name: 'Tim',
    city: 'London',
  }, {
    key: 3,
    name: 'Stella',
    city: 'Bankok',
  }, {
    key: 4,
    name: 'John',
    city: 'Paris',
  }];
}
</code>```

i want to create a search bar which which filters all the fields suppose if i search john then the list of john should be displayed and if i search paris then all the entries which have paris should be displayed..So the code which i have written only searches for name as i have specified name..i want to search the inputed data to search all the fields.

答:
The filter criteria can be the indexOf on Object.values() like below but it will only give a complete match

var data = [{
    key: 1,
    name: 'Steve',
    city: 'Paris',
  }, {
    key: 2,
    name: 'Tim',
    city: 'London',
  }, {
    key: 3,
    name: 'Stella',
    city: 'Bankok',
  }, {
    key: 4,
    name: 'John',
    city: 'Paris',
  }];

  var value = 'Paris'
  var newData = data.filter((obj) => {
      return Object.values(obj).indexOf(value) > -1
  })
  console.log(newData)```

Title: How to filter all the fields in react?

Body:
How to filter all the fields in react?
I have written a code which only filters specified fields.

 let filteredContacts=this.props.contacts.filter(
         (contact)=>{
           return contact.name.indexOf(this.state.search)!==-1;
         }
       );

the above code only returns filtered names...but i want to filter name,age,city work.

this is the data file:

export default function(){
  return [{
    key: 1,
    name: 'Steve',
    city: 'Paris',
  }, {
    key: 2,
    name: 'Tim',
    city: 'London',
  }, {
    key: 3,
    name: 'Stella',
    city: 'Bankok',
  }, {
    key: 4,
    name: 'John',
    city: 'Paris',
  }];
}

i want to create a search bar which which filters all the fields suppose if i search john then the list of john should be displayed and if i search paris then all the entries which have paris should be displayed..So the code which i have written only searches for name as i have specified name..i want to search the inputed data to search all the fields.


问:
How to set that all Lable foreground is White in Window?
Follow method is invalid,I dont want to set color by ergodic. How to set by style:</p>

```<code>Style styleLable = new System.Windows.Style(typeof(Label));
styleLable.Setters.Add(new Setter(Label.ForegroundProperty, "White"));
this.Resources.Add("", styleLable);
this.UpdateLayout();
</code>```

答:
You can try something like this:

```<code><Style TargetType="{x:Type Label}" x:Key="LabelBase">
<Setter Property="Foreground" Value="White"/>
    <Setter Property="Template">
    <Setter.Value>

    <ControlTemplate TargetType="{x:Type Label}">
    <Grid>
    <Border x:Name="Rectangle_MouseOver"BorderThickness="1" Background="{x:Null}" CornerRadius="4" Height="Auto">
        <ContentPresenter x:Name="Content" Margin="4,0,4,0"/>
    </Border>
    </Grid>
    <ControlTemplate.Triggers>
        <Trigger/>
    </ControlTemplate.Triggers>
    </ControlTemplate>
    </Setter.Value>
</Setter>
</code>```

Body:
Follow method is invalid,I dont want to set color by ergodic. How to set by style:

Style styleLable = new System.Windows.Style(typeof(Label));
styleLable.Setters.Add(new Setter(Label.ForegroundProperty, "White"));
this.Resources.Add("", styleLable);
this.UpdateLayout();

Body:
You can try something like this:

<Style TargetType="{x:Type Label}" x:Key="LabelBase">
<Setter Property="Foreground" Value="White"/>
    <Setter Property="Template">
    <Setter.Value>

    <ControlTemplate TargetType="{x:Type Label}">
    <Grid>
    <Border x:Name="Rectangle_MouseOver"BorderThickness="1" Background="{x:Null}" CornerRadius="4" Height="Auto">
        <ContentPresenter x:Name="Content" Margin="4,0,4,0"/>
    </Border>
    </Grid>
    <ControlTemplate.Triggers>
        <Trigger/>
    </ControlTemplate.Triggers>
    </ControlTemplate>
    </Setter.Value>
</Setter>

ContentLicense: CC BY-SA 2.5


问:
Return string from rpgle program
I want to return string from rpgle program.

```<code>/free
return 'this is simple text';
/end-free
</code>```

Can any please give me code snippet for this.

答:
A program object must return values via parameters. If you want to return a value with the RETURN op code, you need to use a sub-procedure. A sub-procedure can be contained in a program object or a service program object. If you want to share the sub-procedure with multiple programs, you should use a service program. This is how you would define the sub-procedure for use within a service program:

```<code>dcl-proc MyProcedure Export;
  dcl-pi *n Varchar(25);
  end-pi;

  return 'this is simple text';
end-proc;
</code>```

If you are just defining the sub-procedure within a program, you need to omit the Export keyword.

To call the sub-procedure you then use something like this:

```<code>dcl-s string     Varchar(25);

string = MyProcedure();
</code>```

To return a value from a Program

If you really want to return a value from a program you have to do it with parameters like this:

```<code>ctl-opt DftActGrp(*No) ActGrp(*Caller)
        Main(MyProgram);

dcl-proc MyProgram;
  dcl-pi *n;
    string        Varchar(25);
  end-pi;

  string = 'this is a simple string';
  return;
end-proc;
</code>```

To call the program you would use something like this:

```<code>dcl-s string      Varchar(25);

dcl-pr MyProgram ExtPgm('MYPROGRAM');
  str          Varchar(25);
end-pr;

MyProgram(string);
</code>```

Title: Return string from rpgle program

Body:
I want to return string from rpgle program.

/free
return 'this is simple text';
/end-free

Can any please give me code snippet for this.

Body:
A program object must return values via parameters. If you want to return a value with the RETURN op code, you need to use a sub-procedure. A sub-procedure can be contained in a program object or a service program object. If you want to share the sub-procedure with multiple programs, you should use a service program. This is how you would define the sub-procedure for use within a service program:

dcl-proc MyProcedure Export;
  dcl-pi *n Varchar(25);
  end-pi;

  return 'this is simple text';
end-proc;

If you are just defining the sub-procedure within a program, you need to omit the Export keyword.

To call the sub-procedure you then use something like this:

dcl-s string     Varchar(25);

string = MyProcedure();

To return a value from a Program

If you really want to return a value from a program you have to do it with parameters like this:

ctl-opt DftActGrp(*No) ActGrp(*Caller)
        Main(MyProgram);

dcl-proc MyProgram;
  dcl-pi *n;
    string        Varchar(25);
  end-pi;

  string = 'this is a simple string';
  return;
end-proc;

To call the program you would use something like this:

dcl-s string      Varchar(25);

dcl-pr MyProgram ExtPgm('MYPROGRAM');
  str          Varchar(25);
end-pr;

MyProgram(string);


问:
Jupyter Notebook: Import .ipynb file and access it's method in other .ipynb file giving error
I am fairly new to Jupyter Notebook. I have played around with it for a while. But this was my first time trying to import another notebook into my main class.

For reference, I am using Anaconda 4.3.1 and Python v2.7.

I am trying to replicate what I did in my python project to jupyter notebooks. It requires importing other .ipynb files (translated from the original .py files) into it to use relevant methods as desired.

For this, I followed the directions as given on Jupyter Nbviewer Steps Link which I found through my preliminary search on the following stack Question. It gave me some idea but didn't help me after one stage.

I will walk you through the steps I took and the sample program I tried.

Created a small .ipynb file abc.ipynb as follows

```<code>def prt_n(str):
    print(str)
if __name__ == '__main__':
    prt_n("in abc")
</code>```

Created an .ipynb file to import Jupyter Notebook from the Jupyter link given above. Say, importer.ipynb.

Run importer.ipynb

import abc

str="Hello Me"

Test step abc.__name__ results in abc as output.

abc.prt_n(str) throws following error

*---------------------------------------------------------------------------

```<code>AttributeError                            Traceback (most recent call last)
<ipython-input-9-2fb88a43c9e5> in <module>()
</code>```

----> 1 abc.prt_n(str)
AttributeError: 'module' object has no attribute 'prt_n'*

I was hoping that the answer will be Hello Me.

Later, I want to actually create a myMain.ipynb file and in that I want to include 2-3 such notebooks and call their methods with required parameters.

One such example can be a file efg.ipynb as follows:

import abc
a="Hello Notebook"
abc.prt_n(a)

I also want to make sure if there is any other way to do this?

Note: I have already checked sys.executable and sys.path. Both have the same python path value.

Any sort of help is welcome!

答:
**

Link to sample files on Drive

**

Ok. So, after some struggle and looking around on Internet, and finally found a solution that worked for my sample case.

Firstly, this is the stackoverflow question that was the most helpful to me. Mohideen and Tyhela's answer was the actual solution and not the one with most number of votes.

So, what I did was, I made a folder by the name module and placed all my .ipynb files there. Plus, I created an __init__.py file in that module  by using touch __init__.py command such that the import can register it as a valid module. Those guys have given a detailed explanation for it which seems legit.

Then from my working directory I ran the following commands:

```<code>str = "Hello Me"
import test.abc as tabc
tabc.prt_n(str)
</code>```

that gave me Hello Me in the output.

And for,

```<code>`import test.efg as tefg`
</code>```

I got

importing Jupyter notebook from test/efg.ipynb
Hello Note

As my desired output.

I hope this will be of help to others who land up on similar problem.

If you have a better approach then I will appreciate if you can share that with me.

Thank you :)

Body:
I am fairly new to Jupyter Notebook. I have played around with it for a while. But this was my first time trying to import another notebook into my main class.

For reference, I am using Anaconda 4.3.1 and Python v2.7.

I am trying to replicate what I did in my python project to jupyter notebooks. It requires importing other .ipynb files (translated from the original .py files) into it to use relevant methods as desired.

For this, I followed the directions as given on Jupyter Nbviewer Steps Link which I found through my preliminary search on the following stack Question. It gave me some idea but didn't help me after one stage.

I will walk you through the steps I took and the sample program I tried.

Created a small .ipynb file abc.ipynb as follows

def prt_n(str):
    print(str)
if __name__ == '__main__':
    prt_n("in abc")

Created an .ipynb file to import Jupyter Notebook from the Jupyter link given above. Say, importer.ipynb.

Run importer.ipynb

import abc

str="Hello Me"

Test step abc.__name__ results in abc as output.

abc.prt_n(str) throws following error

*---------------------------------------------------------------------------

AttributeError                            Traceback (most recent call last)
<ipython-input-9-2fb88a43c9e5> in <module>()

----> 1 abc.prt_n(str)
AttributeError: 'module' object has no attribute 'prt_n'*

I was hoping that the answer will be Hello Me.

Later, I want to actually create a myMain.ipynb file and in that I want to include 2-3 such notebooks and call their methods with required parameters.

One such example can be a file efg.ipynb as follows:

import abc
a="Hello Notebook"
abc.prt_n(a)

I also want to make sure if there is any other way to do this?

Note: I have already checked sys.executable and sys.path. Both have the same python path value.

Any sort of help is welcome!

Body:
**

Link to sample files on Drive

**

Ok. So, after some struggle and looking around on Internet, and finally found a solution that worked for my sample case.

Firstly, this is the stackoverflow question that was the most helpful to me. Mohideen and Tyhela's answer was the actual solution and not the one with most number of votes.

So, what I did was, I made a folder by the name module and placed all my .ipynb files there. Plus, I created an __init__.py file in that module  by using touch __init__.py command such that the import can register it as a valid module. Those guys have given a detailed explanation for it which seems legit.

Then from my working directory I ran the following commands:

str = "Hello Me"
import test.abc as tabc
tabc.prt_n(str)

that gave me Hello Me in the output.

And for,

`import test.efg as tefg`

I got

importing Jupyter notebook from test/efg.ipynb
Hello Note

As my desired output.

I hope this will be of help to others who land up on similar problem.

If you have a better approach then I will appreciate if you can share that with me.

Thank you :)


问:
How to focus next feald on next is clicked in react native?
Hi i am trying to focus next input field( Which is extended from parent ) while next(in android keyboard) is clicked android keyboard closes and not focusing the next field.

I tried some of the codes like onSubmitEditing= this.refs.passwordFeald.focus() its not working and i am little confused about naming component if some one explains it also be better

the following is my current code

```<code>export default class InputBox extends Component {
    focusNextField = (nextField) => { this.refs[nextField].focus(); };

    render(){
        return(
            <TextInput
                style = {style.input}
                underlineColorAndroid='rgba(255,255,255,0.7)'
                placeholderTextColor = "rgba(255,255,255,0.6)"
                placeholder = {this.props.placeholder}
                secureTextEntry={this.props.typePassword}
                returnKeyType = {this.props.returnKeyType}
                ref = {this.props.inputRef}
                focusNextField = {() => this.focusNextField(this.props.onSubmitEditing)}
            />
        )
    }
}

export default class Login extends Component {

  render(){
    return(
      <View style={[styles.container, commonStyle.background]}>
        <View style={[headerContStyle.topContainer]}>
          <MainHeading/>
        </View>
        <View style={[formStyle.container]}>
          <InputBox
            placeholder = "Email or username"
            returnKeyType = "next"
            inputRef = {el => this.usenameFeald = el}
            onSubmitEditing= 'passwordFeald'
          />
          <InputBox
            placeholder = "Password"
            secureTextEntery = {"true"}
            returnKeyType = "go"
            inputRef = {el => this.passwordFeald = el}
            typePassword = {true}
          />
          <CommonButton
              title = "Login"
          />
          <CommonButton
              title = "Sign Up"
          />
          <ForgotPassword />
        </View>
      </View>
    )
  }
}
</code>```

答:
Ref the document about TextInput here.

You can see the example focus the next TextInput at the class BlurOnSubmitExample.
At your project, I suggest you change the properties like this on the first input:

```<code><InputBox
  placeholder="Email or username"
  returnKeyType="next"
  onSubmitEditing={() => this.nextInput.focus()}
 />
</code>```

And the second one:

```<code><InputBox
  placeholder="Password"
  returnKeyType="next"
  inputRef={(nextInput) => this.nextInput = nextInput}
 />
</code>```

On the InputBox component, we send the ref to the parent component:

```<code>ref={(nextInput) => {this.props.inputRef && this.props.inputRef(nextInput)}}
{ ...this.props }
</code>```

onSubmitEditing will call when the user press the enter key and this will focus the second TextInput.

Body:
Hi i am trying to focus next input field( Which is extended from parent ) while next(in android keyboard) is clicked android keyboard closes and not focusing the next field.

I tried some of the codes like onSubmitEditing= this.refs.passwordFeald.focus() its not working and i am little confused about naming component if some one explains it also be better

the following is my current code

export default class InputBox extends Component {
    focusNextField = (nextField) => { this.refs[nextField].focus(); };

    render(){
        return(
            <TextInput
                style = {style.input}
                underlineColorAndroid='rgba(255,255,255,0.7)'
                placeholderTextColor = "rgba(255,255,255,0.6)"
                placeholder = {this.props.placeholder}
                secureTextEntry={this.props.typePassword}
                returnKeyType = {this.props.returnKeyType}
                ref = {this.props.inputRef}
                focusNextField = {() => this.focusNextField(this.props.onSubmitEditing)}
            />
        )
    }
}

export default class Login extends Component {

  render(){
    return(
      <View style={[styles.container, commonStyle.background]}>
        <View style={[headerContStyle.topContainer]}>
          <MainHeading/>
        </View>
        <View style={[formStyle.container]}>
          <InputBox
            placeholder = "Email or username"
            returnKeyType = "next"
            inputRef = {el => this.usenameFeald = el}
            onSubmitEditing= 'passwordFeald'
          />
          <InputBox
            placeholder = "Password"
            secureTextEntery = {"true"}
            returnKeyType = "go"
            inputRef = {el => this.passwordFeald = el}
            typePassword = {true}
          />
          <CommonButton
              title = "Login"
          />
          <CommonButton
              title = "Sign Up"
          />
          <ForgotPassword />
        </View>
      </View>
    )
  }
}

Body:
Ref the document about TextInput here.

You can see the example focus the next TextInput at the class BlurOnSubmitExample.
At your project, I suggest you change the properties like this on the first input:

<InputBox
  placeholder="Email or username"
  returnKeyType="next"
  onSubmitEditing={() => this.nextInput.focus()}
 />

And the second one:

<InputBox
  placeholder="Password"
  returnKeyType="next"
  inputRef={(nextInput) => this.nextInput = nextInput}
 />

On the InputBox component, we send the ref to the parent component:

ref={(nextInput) => {this.props.inputRef && this.props.inputRef(nextInput)}}
{ ...this.props }

onSubmitEditing will call when the user press the enter key and this will focus the second TextInput.


问:
Loading url with pdf in monodroid webview
Im trying to load an url in a webview. The url links to a pdf file on the website. I want to display this pdf file in the webview. For some reason I only see a white screen and the pdf is not loading.

Here is code:

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.Webkit;

namespace TrackandTrace.Droid
{
    [Activity (Label = "PodActivity")]
    public class PodActivity : Activity
    {
        public string PodUrl { get; set; }

        protected override void OnCreate (Bundle bundle)
        {
            base.OnCreate (bundle);
            SetContentView (Resource.Layout.PodLayout);

            var PodWebView = FindViewById<WebView> (Resource.Id.webViewPod);
            PodUrl = Intent.GetStringExtra ("PodUrlString" ?? "No Pod Data available");

            PodWebView.Settings.AllowFileAccess = true;
            PodWebView.Settings.JavaScriptEnabled = true;
            PodWebView.Settings.BuiltInZoomControls = true;
            PodWebView.LoadData (PodUrl);

            PodWebView.SetWebViewClient (new PodWebViewClient ());

            // Create your application here
        }

        private class PodWebViewClient : WebViewClient
        {
            public override bool ShouldOverrideUrlLoading (WebView view, string url)
            {
                view.LoadUrl (url);
                return true;
            }
        }
    }
}
</code>```

答:
you have to add this link to your pdf link or just tape the same code below

```<code>WebView webview = FindViewById<WebView>(Resource.Id.webView1);
        urlPdf = ("example of url");
        WebSettings settings = webview.Settings;
        settings.JavaScriptEnabled = true;
        webview.LoadUrl("http://drive.google.com/viewerng/viewer?embedded=true&url=" + urlPdf);
</code>```

and it's important to add this link before urlPDF "http://drive.google.com/viewerng/viewer?embedded=true&url="

Body:
Im trying to load an url in a webview. The url links to a pdf file on the website. I want to display this pdf file in the webview. For some reason I only see a white screen and the pdf is not loading.

Here is code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.Webkit;

namespace TrackandTrace.Droid
{
    [Activity (Label = "PodActivity")]
    public class PodActivity : Activity
    {
        public string PodUrl { get; set; }

        protected override void OnCreate (Bundle bundle)
        {
            base.OnCreate (bundle);
            SetContentView (Resource.Layout.PodLayout);

            var PodWebView = FindViewById<WebView> (Resource.Id.webViewPod);
            PodUrl = Intent.GetStringExtra ("PodUrlString" ?? "No Pod Data available");

            PodWebView.Settings.AllowFileAccess = true;
            PodWebView.Settings.JavaScriptEnabled = true;
            PodWebView.Settings.BuiltInZoomControls = true;
            PodWebView.LoadData (PodUrl);

            PodWebView.SetWebViewClient (new PodWebViewClient ());

            // Create your application here
        }

        private class PodWebViewClient : WebViewClient
        {
            public override bool ShouldOverrideUrlLoading (WebView view, string url)
            {
                view.LoadUrl (url);
                return true;
            }
        }
    }
}

Body:
you have to add this link to your pdf link or just tape the same code below

WebView webview = FindViewById<WebView>(Resource.Id.webView1);
        urlPdf = ("example of url");
        WebSettings settings = webview.Settings;
        settings.JavaScriptEnabled = true;
        webview.LoadUrl("http://drive.google.com/viewerng/viewer?embedded=true&url=" + urlPdf);

and it's important to add this link before urlPDF "http://drive.google.com/viewerng/viewer?embedded=true&url="


答:
I don't think you want to be doing this at all. Instead, good.gkey should be a foreign key to goods_category.id. If the insertion order is important, you can add an insert_date date field to the goods table.

From there you can run all sorts of queries, with the added bonus of having referential integrity on your tables.

Title: MYSQL - how to a second unique string key?

Body:
Here is my goods table.

+----------------------+---------------+------+-----+---------+-------+
| Field                | Type          | Null | Key | Default | Extra |
+----------------------+---------------+------+-----+---------+-------+
| ID                   | decimal(18,0) | NO   | PRI |         |       |
| gkey                 | varchar(255)  | YES  | MUL | NULL    |       |
| GOODS                | decimal(18,0) | YES  | MUL | NULL    |       |

Column ID is auto-increment.
GOODS is the id of a goods category.
Here is the goods category table.

+-------+---------------------+
| ID    | NAME                |
+-------+---------------------+
| 1     | book                |
| 2     | phone               |
+-------+---------------------+

My question is in goods table I need the gkey is also an unique key with prefix-id(here id is started from 1.) Like BOOK-1,BOOK-2....PHONE-1,PHONE-2... when insert a new goods record into goods table.
Like that:

+--------------------+---------------+------+-----+---------+-------+
| ID                 | GKEY          |GOODS | PRI | COUNTRY | Extra |
+--------------------+---------------+------+-----+---------+-------+
| 1                  | BOOK-1        | 1    | 10  |         |       |
| 2                  | PHONE-1       | 2    | 12  |         |       |
| 3                  | BOOK-2        | 1    | 13  |         |       |
| 4                  | BOOK-3        | 1    | 10  |         |       |
| 5                  | PHONE-2       | 2    | 10  |         |       |
| 6                  | PHONE-3       | 2    | 20  |         |       |
+--------------------+---------------+------+-----+---------+-------+

How to get that GKEY in PHP+MYSQL?

thanks.


问:
Get open activity of the foreground app
I need to get the current Activity of the foreground App. I tried following this answer and later used this library(because the first solution only worked from Lollipop), and them indeed worked well telling the foreground app's package name, but I need to know what activity is open.</p>

答:
Hey @Capitan Luzzatto,

Pre LOLLIPOP(API 21) we can get list of running apps from ActivityManager

But From LOLLIPOP we should get only from UsageStatsManager

First you need 2 permissions to read the tasks

```<code><uses-permission android:name="android.permission.GET_TASKS" />
<uses-permission android:name="android.permission.PACKAGE_USAGE_STATS" />
</code>```

And you should check first the user API level is 21 or more if yes you should get access for usage access settings like below

```<code>if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP && !mIsChecked) {
        if (getUsageStatsList(getActivity()).isEmpty()) {

            Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS);
            startActivity(intent);
        }
 }
</code>```

to get Usage stats list

```<code>    public static List<UsageStats> getUsageStatsList(Context context){
    UsageStatsManager usm = (UsageStatsManager) context.getSystemService("usagestats");
    Calendar calendar = Calendar.getInstance();
    long endTime = calendar.getTimeInMillis();
    calendar.add(Calendar.DATE, -1);
    long startTime = calendar.getTimeInMillis();

    List<UsageStats> usageStatsList = usm.queryUsageStats(UsageStatsManager.INTERVAL_DAILY,startTime,endTime);

    return usageStatsList;
}
</code>```

Finally you can get the latest Foreground app using the following method

```<code>public String getRecentApps(Context context) {
    String topPackageName = "";

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        UsageStatsManager mUsageStatsManager = (UsageStatsManager) context.getSystemService(Context.USAGE_STATS_SERVICE);

        long time = System.currentTimeMillis();

        UsageEvents usageEvents = mUsageStatsManager.queryEvents(time - 1000 * 30, System.currentTimeMillis() + (10 * 1000));
        UsageEvents.Event event = new UsageEvents.Event();
        while (usageEvents.hasNextEvent()) {
            usageEvents.getNextEvent(event);
        }

        if (event != null && !TextUtils.isEmpty(event.getPackageName()) && event.getEventType() == UsageEvents.Event.MOVE_TO_FOREGROUND) {
            if (AndroidUtils.isRecentActivity(event.getClassName())) {
                return event.getClassName();
            }
            return event.getPackageName();
        } else {
            topPackageName = "";
        }
    } else {
        ActivityManager am = (ActivityManager) context.getSystemService(context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
        ComponentName componentInfo = taskInfo.get(0).topActivity;

        if (AndroidUtils.isRecentActivity(componentInfo.getClassName())) {
            return componentInfo.getClassName();
        }

        topPackageName = componentInfo.getPackageName();
    }

    return topPackageName;
}
</code>```

To get Foreground activity use the method like this

```<code>public String getRecentActivity(Context context) {
    String topActivityName = "";

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        UsageStatsManager mUsageStatsManager = (UsageStatsManager) context.getSystemService(Context.USAGE_STATS_SERVICE);

        long time = System.currentTimeMillis();

        UsageEvents usageEvents = mUsageStatsManager.queryEvents(time - 1000 * 30, System.currentTimeMillis() + (10 * 1000));
        UsageEvents.Event event = new UsageEvents.Event();
        while (usageEvents.hasNextEvent()) {
            usageEvents.getNextEvent(event);
        }

        if (event != null && !TextUtils.isEmpty(event.getPackageName()) && event.getEventType() == UsageEvents.Event.MOVE_TO_FOREGROUND) {
            return event.getClassName();
        } else {
            topActivityName = "";
        }
    } else {
        ActivityManager am = (ActivityManager) context.getSystemService(context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
        ComponentName componentInfo = taskInfo.get(0).topActivity;

        topActivityName = componentInfo.getClassName();
    }

    return topActivityName;
}
</code>```

AndroidUtils.java - To get the device recent screen in Hack way, Maybe we should investigate more on this, Not sure it will work on all device, but it works on almost all devices

```<code>public class AndroidUtils {
    private static final String RECENT_ACTIVITY;

    static {
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
            RECENT_ACTIVITY = "com.android.systemui.recents.RecentsActivity";
        } else if (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN_MR1) {
            RECENT_ACTIVITY = "com.android.systemui.recent.RecentsActivity";
        } else {
            RECENT_ACTIVITY = "com.android.internal.policy.impl.RecentApplicationDialog";
        }
    }

    /**
     * To get the Device recent screen activity
     *
     * @param className
     * @return activity
     */
    public static boolean isRecentActivity(String className) {
        if (RECENT_ACTIVITY.equalsIgnoreCase(className)) {
            return true;
        }

        return false;
    }
}
</code>```

Title: Get open activity of the foreground app

Body:
Hey @Capitan Luzzatto,

Pre LOLLIPOP(API 21) we can get list of running apps from ActivityManager

But From LOLLIPOP we should get only from UsageStatsManager

First you need 2 permissions to read the tasks

<uses-permission android:name="android.permission.GET_TASKS" />
<uses-permission android:name="android.permission.PACKAGE_USAGE_STATS" />

And you should check first the user API level is 21 or more if yes you should get access for usage access settings like below

if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP && !mIsChecked) {
        if (getUsageStatsList(getActivity()).isEmpty()) {

            Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS);
            startActivity(intent);
        }
 }

to get Usage stats list

    public static List<UsageStats> getUsageStatsList(Context context){
    UsageStatsManager usm = (UsageStatsManager) context.getSystemService("usagestats");
    Calendar calendar = Calendar.getInstance();
    long endTime = calendar.getTimeInMillis();
    calendar.add(Calendar.DATE, -1);
    long startTime = calendar.getTimeInMillis();

    List<UsageStats> usageStatsList = usm.queryUsageStats(UsageStatsManager.INTERVAL_DAILY,startTime,endTime);

    return usageStatsList;
}

Finally you can get the latest Foreground app using the following method

public String getRecentApps(Context context) {
    String topPackageName = "";

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        UsageStatsManager mUsageStatsManager = (UsageStatsManager) context.getSystemService(Context.USAGE_STATS_SERVICE);

        long time = System.currentTimeMillis();

        UsageEvents usageEvents = mUsageStatsManager.queryEvents(time - 1000 * 30, System.currentTimeMillis() + (10 * 1000));
        UsageEvents.Event event = new UsageEvents.Event();
        while (usageEvents.hasNextEvent()) {
            usageEvents.getNextEvent(event);
        }

        if (event != null && !TextUtils.isEmpty(event.getPackageName()) && event.getEventType() == UsageEvents.Event.MOVE_TO_FOREGROUND) {
            if (AndroidUtils.isRecentActivity(event.getClassName())) {
                return event.getClassName();
            }
            return event.getPackageName();
        } else {
            topPackageName = "";
        }
    } else {
        ActivityManager am = (ActivityManager) context.getSystemService(context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
        ComponentName componentInfo = taskInfo.get(0).topActivity;

        if (AndroidUtils.isRecentActivity(componentInfo.getClassName())) {
            return componentInfo.getClassName();
        }

        topPackageName = componentInfo.getPackageName();
    }

    return topPackageName;
}

To get Foreground activity use the method like this

public String getRecentActivity(Context context) {
    String topActivityName = "";

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        UsageStatsManager mUsageStatsManager = (UsageStatsManager) context.getSystemService(Context.USAGE_STATS_SERVICE);

        long time = System.currentTimeMillis();

        UsageEvents usageEvents = mUsageStatsManager.queryEvents(time - 1000 * 30, System.currentTimeMillis() + (10 * 1000));
        UsageEvents.Event event = new UsageEvents.Event();
        while (usageEvents.hasNextEvent()) {
            usageEvents.getNextEvent(event);
        }

        if (event != null && !TextUtils.isEmpty(event.getPackageName()) && event.getEventType() == UsageEvents.Event.MOVE_TO_FOREGROUND) {
            return event.getClassName();
        } else {
            topActivityName = "";
        }
    } else {
        ActivityManager am = (ActivityManager) context.getSystemService(context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
        ComponentName componentInfo = taskInfo.get(0).topActivity;

        topActivityName = componentInfo.getClassName();
    }

    return topActivityName;
}

AndroidUtils.java - To get the device recent screen in Hack way, Maybe we should investigate more on this, Not sure it will work on all device, but it works on almost all devices

public class AndroidUtils {
    private static final String RECENT_ACTIVITY;

    static {
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
            RECENT_ACTIVITY = "com.android.systemui.recents.RecentsActivity";
        } else if (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN_MR1) {
            RECENT_ACTIVITY = "com.android.systemui.recent.RecentsActivity";
        } else {
            RECENT_ACTIVITY = "com.android.internal.policy.impl.RecentApplicationDialog";
        }
    }

    /**
     * To get the Device recent screen activity
     *
     * @param className
     * @return activity
     */
    public static boolean isRecentActivity(String className) {
        if (RECENT_ACTIVITY.equalsIgnoreCase(className)) {
            return true;
        }

        return false;
    }
}


问:
UIImageJPEGRepresentation returns nil when file at specified path is deleted in Swift?
I'm completely confused as to how UIImageJPEGRepresentation is related to a file's path in the Documents directory.

Basically, when I delete a file from a file path, and then call UIImageJPEGRepresentation on a UIImage, it returns nil, but if the file path is not deleted, UIImageJPEGRepresentation returns the data representation of the image.

Here's my sample code to demonstrate what I mean:

```<code>func functionA()
{
    if imagePaths_ARRAY.isEmpty == false
    {
        for pathToDelete in imagePaths_ARRAY
        {
            if fileManager.fileExists(atPath: pathToDelete)
            {
                do
                {
                    try fileManager.removeItem(atPath: pathToDelete)
                }
                catch let error as NSError
                {
                    print(error.localizedDescription)
                }
            }
            else
            {
                print("ERROR")
            }
        }

        imagePaths_ARRAY.removeAll()
    }

    print(images_ARRAY)

    for image in images_ARRAY
    {
        print(image)

        if let imageData = UIImageJPEGRepresentation(image, 0.5)
        {
            print("RETURN GOOD")
            let imageName = getImageName()

            let imagePath = getDirectoryPath().appending("/" + imageName)

            let success = fileManager.createFile(atPath: imagePath, contents: imageData, attributes: nil)

            if success == true
            {
                imagePaths_ARRAY.append(imagePath)
            }
        }
        else
        {
            print("RETURN NIL")
        }

    }
}
</code>```

The very FIRST time functionA is called, imagePaths_ARRAY is empty so the inside block of code does not execute. I loop through an array of UIImages and for each image, I call UIImageJPEGRepresentation to convert it to a Data object to write to file, and I add the imagePath to my imagePaths_ARRAY array to be used elsewhere in my code.

For each image, I see a log of RETURN GOOD and all the images are written to file.

However, when functionA is called the SECOND time,imagePaths_ARRAY is not empty, so I delete all the files from the paths in imagePaths_ARRAY.

But when UIImageJPEGRepresentation is called on the image again, it returns nil?

I am completely confused as to why because each image in images_ARRAY gives me a valid UIImage:

```<code>[<UIImage: 0x600000085280> size {4288, 2848} orientation 0 scale 1.000000]
</code>```

As mentioned in the first sentence, I like to know how removing a file using removeItem causes UIImageJPEGRepresentation to return nil?

UPDATE: when I replace UIImageJPEGRepresentation with UIImagePNGRepresentation instead, the image is compressed just fine. I'm completely confused!

答:
Seems like something else must be going on in your code.

I just gave it a try, and with the following code I can tap the button repeatedly and every time through I get success:

```<code>//
//  TestViewController.swift
//

import UIKit

class TestViewController: UIViewController {

    var imagePaths_ARRAY = [String]()
    var images_ARRAY = [UIImage]()

    let fileManager = FileManager.default

    override func viewDidLoad() {
        super.viewDidLoad()

        let names = ["s1", "s2", "s3"]

        for s in names {
            if let img = UIImage(named: s) {
                images_ARRAY.append(img)
            }
        }
    }

    @IBAction func btnTapped(_ sender: Any) {
        functionA()
    }

    func getDirectoryPath() -> String {
        return NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
    }

    func getImageName() -> String {
        let randomNum:UInt32 = arc4random_uniform(1000000)
        return "randomName_\(randomNum)"
    }

    func functionA()
    {

        print(imagePaths_ARRAY)

        if imagePaths_ARRAY.isEmpty == false
        {
            for pathToDelete in imagePaths_ARRAY
            {
                if fileManager.fileExists(atPath: pathToDelete)
                {
                    do
                    {
                        try fileManager.removeItem(atPath: pathToDelete)
                    }
                    catch let error as NSError
                    {
                        print(error.localizedDescription)
                    }
                }
                else
                {
                    print("ERROR")
                }
            }

            imagePaths_ARRAY.removeAll()
        }

        print(images_ARRAY)

        for image in images_ARRAY
        {
//          print(image)

            if let imageData = UIImageJPEGRepresentation(image, 0.5)
            {
                let imageName = getImageName()

                let imagePath = getDirectoryPath().appending("/" + imageName)

                let success = fileManager.createFile(atPath: imagePath, contents: imageData, attributes: nil)

                if success == true
                {
                    print("RETURN GOOD")
                    imagePaths_ARRAY.append(imagePath)
                }
            }
            else
            {
                print("RETURN NIL")
            }

        }

    }

}
</code>```

Body:
I'm completely confused as to how UIImageJPEGRepresentation is related to a file's path in the Documents directory.

Basically, when I delete a file from a file path, and then call UIImageJPEGRepresentation on a UIImage, it returns nil, but if the file path is not deleted, UIImageJPEGRepresentation returns the data representation of the image.

Here's my sample code to demonstrate what I mean:

func functionA()
{
    if imagePaths_ARRAY.isEmpty == false
    {
        for pathToDelete in imagePaths_ARRAY
        {
            if fileManager.fileExists(atPath: pathToDelete)
            {
                do
                {
                    try fileManager.removeItem(atPath: pathToDelete)
                }
                catch let error as NSError
                {
                    print(error.localizedDescription)
                }
            }
            else
            {
                print("ERROR")
            }
        }

        imagePaths_ARRAY.removeAll()
    }

    print(images_ARRAY)

    for image in images_ARRAY
    {
        print(image)

        if let imageData = UIImageJPEGRepresentation(image, 0.5)
        {
            print("RETURN GOOD")
            let imageName = getImageName()

            let imagePath = getDirectoryPath().appending("/" + imageName)

            let success = fileManager.createFile(atPath: imagePath, contents: imageData, attributes: nil)

            if success == true
            {
                imagePaths_ARRAY.append(imagePath)
            }
        }
        else
        {
            print("RETURN NIL")
        }

    }
}

The very FIRST time functionA is called, imagePaths_ARRAY is empty so the inside block of code does not execute. I loop through an array of UIImages and for each image, I call UIImageJPEGRepresentation to convert it to a Data object to write to file, and I add the imagePath to my imagePaths_ARRAY array to be used elsewhere in my code.

For each image, I see a log of RETURN GOOD and all the images are written to file.

However, when functionA is called the SECOND time,imagePaths_ARRAY is not empty, so I delete all the files from the paths in imagePaths_ARRAY.

But when UIImageJPEGRepresentation is called on the image again, it returns nil?

I am completely confused as to why because each image in images_ARRAY gives me a valid UIImage:

[<UIImage: 0x600000085280> size {4288, 2848} orientation 0 scale 1.000000]

As mentioned in the first sentence, I like to know how removing a file using removeItem causes UIImageJPEGRepresentation to return nil?

UPDATE: when I replace UIImageJPEGRepresentation with UIImagePNGRepresentation instead, the image is compressed just fine. I'm completely confused!

Body:
Seems like something else must be going on in your code.

I just gave it a try, and with the following code I can tap the button repeatedly and every time through I get success:

//
//  TestViewController.swift
//

import UIKit

class TestViewController: UIViewController {

    var imagePaths_ARRAY = [String]()
    var images_ARRAY = [UIImage]()

    let fileManager = FileManager.default

    override func viewDidLoad() {
        super.viewDidLoad()

        let names = ["s1", "s2", "s3"]

        for s in names {
            if let img = UIImage(named: s) {
                images_ARRAY.append(img)
            }
        }
    }

    @IBAction func btnTapped(_ sender: Any) {
        functionA()
    }

    func getDirectoryPath() -> String {
        return NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
    }

    func getImageName() -> String {
        let randomNum:UInt32 = arc4random_uniform(1000000)
        return "randomName_\(randomNum)"
    }

    func functionA()
    {

        print(imagePaths_ARRAY)

        if imagePaths_ARRAY.isEmpty == false
        {
            for pathToDelete in imagePaths_ARRAY
            {
                if fileManager.fileExists(atPath: pathToDelete)
                {
                    do
                    {
                        try fileManager.removeItem(atPath: pathToDelete)
                    }
                    catch let error as NSError
                    {
                        print(error.localizedDescription)
                    }
                }
                else
                {
                    print("ERROR")
                }
            }

            imagePaths_ARRAY.removeAll()
        }

        print(images_ARRAY)

        for image in images_ARRAY
        {
//          print(image)

            if let imageData = UIImageJPEGRepresentation(image, 0.5)
            {
                let imageName = getImageName()

                let imagePath = getDirectoryPath().appending("/" + imageName)

                let success = fileManager.createFile(atPath: imagePath, contents: imageData, attributes: nil)

                if success == true
                {
                    print("RETURN GOOD")
                    imagePaths_ARRAY.append(imagePath)
                }
            }
            else
            {
                print("RETURN NIL")
            }

        }

    }

}


问:
Microsoft Bot transparent authentication
I just started exploring Bot Framework and I case that I wasn't able to find an answer for came in my head.

I want my bot to say something like: "Hi " when the user type hi, hello etc, but at the same time I don't want to prompt the user to sign-in again, because he already did it when accessing the page. How to achieve that when I insert the web chat as iframe?

The user is authenticated using AAD. I found this article, but i wasn't able to make it working, idk why.

Thanks in advance for you answers.

答: For your scenario, you can use the BackChannel mechanism. With this, you can pass messages from/to the WebChat Control from/to your page. And more on your question, maybe you can pass some user data to the WebChat when user is logged.</p>


问:
How do I get the application's directory from my WPF application, at design time?
How do I get the application's directory from my WPF application, at design time? I need to access a resource in my application's current directory at design time, while my XAML is being displayed in the designer. I'm not able to use the solution specified in this question as at design time both System.IO.Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName) and System.Reflection.Assembly.GetExecutingAssembly().Location point to the IDE's location (Visual Studio... Common7 or something).

Upon request to further clarify my goals: I want to access a database table at design time and display a graphic of that data. The design is done in Visual Studio 2008, so what I need is a very specific solution to a very specific problem, and that is getting the assembly directory for my app.

答:
If you are extensively working on WPF designers using adorner etc, please use "Context" property/type

Details:-
In Design time you have instance of modelItem (I assume it, you know it) if not then you can instantiate it in Override implementation of Activate method

// in  DesignAdorner class

```<code>public class DesignAdorner : PrimarySelectionAdornerProvider
{
      protected override void Activate(ModelItem item)
        {
                modelItem = item;
        }
}
</code>```

Now you can access the current application path using following single line code

```<code>string aplicationPathDir = System.IO.Directory.GetParent(modelItem.Context.ToString()).FullName;
</code>```

Let me know, if it does not help you.

Body:
If you are extensively working on WPF designers using adorner etc, please use "Context" property/type

Details:-
In Design time you have instance of modelItem (I assume it, you know it) if not then you can instantiate it in Override implementation of Activate method

// in  DesignAdorner class

public class DesignAdorner : PrimarySelectionAdornerProvider
{
      protected override void Activate(ModelItem item)
        {
                modelItem = item;
        }
}

Now you can access the current application path using following single line code

string aplicationPathDir = System.IO.Directory.GetParent(modelItem.Context.ToString()).FullName;

Let me know, if it does not help you.


问:
Automating infrastructure with packer & terraform on vsphere
With packer I can script up the creation of a template linux box and upload to my vsphere cloud instance as a vmware box. I'd like it to be uploaded or converted to a vsphere template so then I can run terraform on this template to automate the creation of multiple linux based VMs. How can I do this? I currently need to manually right click on the uploaded VM in vsphere and click "Convert to Template" at which point terraform will happily generate and customise multiple instances of the base linux box.

Is there a mechanism with packer/terraform for automating this? If so what is it?

答:
The disk/template section in the terraform file does not only apply to vsphere templates. For example the following will initiate a clone of the BaseLinuxVM in vsphere:</p>

```<code>resource "vsphere_virtual_machine" "my-first-vm" {
 datacenter        = "MyDatacenter"
 cluster = "MyCluster"
 name = "my-first-vm"
 memory = 1024
 vcpu = 1

 disk {
  datastore = "MyDatastore"
  template = "BaseLinuxVM"
 }
 linked_clone = false
 network_interface {
  label = "VM Network"
 }
}
</code>```

Body:
The disk/template section in the terraform file does not only apply to vsphere templates. For example the following will initiate a clone of the BaseLinuxVM in vsphere:

resource "vsphere_virtual_machine" "my-first-vm" {
 datacenter        = "MyDatacenter"
 cluster = "MyCluster"
 name = "my-first-vm"
 memory = 1024
 vcpu = 1

 disk {
  datastore = "MyDatastore"
  template = "BaseLinuxVM"
 }
 linked_clone = false
 network_interface {
  label = "VM Network"
 }
}


问:
PHP range() function in .NET?
I need to generate a list of sequential numbers.  I know Ruby you can do 1..10 or PHP you can do range(1, 10).  Anything like that in .Net already, or do I have to write it?   Thanks.</p>

答: You can use Enumerable.Range()</p>

OwnerDisplayName: Kevin

Title: PHP range() function in .NET?

Body: You can use Enumerable.Range()

OwnerDisplayName: CMS


问:
What is a good name for this state-like monad
This is something of a combination of State and Writer.  I have checked the monad laws.

```<code>newtype M s a = M { runM :: s -> (s,a) }

instance (Monoid s) => Monad (M s) where
    return = M . const . (mempty,)
    m >>= f = M $ \s ->
        let (s' ,x) = runM m s
            (s'',y) = runM (f x) (s `mappend` s')
        in (s' `mappend` s'', y)
</code>```

StateWriter seems kinda lame.

答: Maybe call SW (Statefull Writer), I think short names are rather intuitive and save some typing.

Body:
This is something of a combination of State and Writer.  I have checked the monad laws.

newtype M s a = M { runM :: s -> (s,a) }

instance (Monoid s) => Monad (M s) where
    return = M . const . (mempty,)
    m >>= f = M $ \s ->
        let (s' ,x) = runM m s
            (s'',y) = runM (f x) (s `mappend` s')
        in (s' `mappend` s'', y)

StateWriter seems kinda lame.


问:
What happens if a thread re-assigns a variable in java?
I want to know if the following (contrived) example is thread safe:

```<code>public class SpringSingleton
{

    private MyObject _myObject = new MyObject("hello");

    public void useObject()
    {
        _myObject.doSomethingCool();
    }

    public void changeObject()
    {
        _myObject = new MyObject("goodbye");
    }

    public static void main(String[] args)
    {
        // Have multiple threads, some using and some changing the object
    }

}
</code>```

My main question is: what will happen when one thread tries to call useObject() at the same time another thread tries to call changeObject()?

答:
If one thread tries to call useObject() at the same time another thread tries to call changeObject(), then the behavior is non-deterministic, the thread calling useObject() might see the old or the new value.

Whether or not it is "safe" depends on what behavior you desire.

It might not matter to your code which value it sees, in a short period of time.

Body:
I want to know if the following (contrived) example is thread safe:

public class SpringSingleton
{

    private MyObject _myObject = new MyObject("hello");

    public void useObject()
    {
        _myObject.doSomethingCool();
    }

    public void changeObject()
    {
        _myObject = new MyObject("goodbye");
    }

    public static void main(String[] args)
    {
        // Have multiple threads, some using and some changing the object
    }

}

My main question is: what will happen when one thread tries to call useObject() at the same time another thread tries to call changeObject()?


问:
Start Background Task using ASP.Net Core Middleware
I'm attempting to run an asynchronous task when loading a page in ASP.Net Core, i.e., I want the task to run as soon as the user routes to the page but for the page to be displayed before the task has completed. It seems that with ASP.Net core you use middleware to perform such tasks. So I attempted to add the following to Startup.cs

```<code>public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IServiceProvider serviceProvider)
        {

// Other configurations here
app.Use(async (context, next) =>
            {
                if (context.Request.Path.Value.Contains("PageWithAsyncTask"))
                {
                    var serviceWithAsyncTask = serviceProvider.GetService<IMyService>();
                    await serviceWithAsyncTask .DoAsync();
                }
                await next.Invoke();
            });

app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });

}
</code>```

The problem with the above is that there is a delay in the page loading until DoAsync has complete since we don't call next.Invoke() until DoAsync is complete. How do I correctly implement the above such that next.Invoke() is called immediately after I've got DoAsync running?

答: Have a look at HangFire for managing background processing, works great in .Net Core: https://www.hangfire.io/</p>

Body:
I'm attempting to run an asynchronous task when loading a page in ASP.Net Core, i.e., I want the task to run as soon as the user routes to the page but for the page to be displayed before the task has completed. It seems that with ASP.Net core you use middleware to perform such tasks. So I attempted to add the following to Startup.cs

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IServiceProvider serviceProvider)
        {

// Other configurations here
app.Use(async (context, next) =>
            {
                if (context.Request.Path.Value.Contains("PageWithAsyncTask"))
                {
                    var serviceWithAsyncTask = serviceProvider.GetService<IMyService>();
                    await serviceWithAsyncTask .DoAsync();
                }
                await next.Invoke();
            });

app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });

}

The problem with the above is that there is a delay in the page loading until DoAsync has complete since we don't call next.Invoke() until DoAsync is complete. How do I correctly implement the above such that next.Invoke() is called immediately after I've got DoAsync running?


问:
Keras fit_generator producing exception: output of generator should be a tuple(x, y, sample_weight) or (x, y). Found: [[[[ 0.86666673
I am trying to build an autoencoder for non MNIST, non Imagenet data.  Using  https://blog.keras.io/building-autoencoders-in-keras.html as my base.  However, am getting the following error.

```<code>**Exception: output of generator should be a tuple (x, y, sample_weight) or (x, y). Found: [[[[ 0.86666673  0.86666673  0.86666673 ...,  0.62352943  0.627451
     0.63137257]
   [ 0.86666673  0.86666673  0.86666673 ...,  0.63137257  0.627451
     0.627451  ]
   [ 0.86666673  0.86666673  0.86666673 ...,  0.63137257  0.627451
     0.62352943]
   ...,**
</code>```

Since this is an autoencoder, in my datagenerator, used class mode=None.  My code is as follows.

```<code>from keras.layers import Input, Dense, Convolution2D, MaxPooling2D,   UpSampling2D,Activation, Dropout, Flatten
from keras.models import Model,Sequential
from keras.preprocessing.image import ImageDataGenerator
import numpy as np
import os
import h5py

img_width=140
img_height=140
train_data_dir=r'SitePhotos\train'
valid_data_dir=r'SitePhotos\validation'
input_img = Input(batch_shape=(32,3, img_width, img_width))

x = Convolution2D(16, 3, 3, activation='relu', border_mode='same')(input_img)
x = MaxPooling2D((2, 2), border_mode='same')(x)
x = Convolution2D(8, 3, 3, activation='relu', border_mode='same')(x)
x = MaxPooling2D((2, 2), border_mode='same')(x)
x = Convolution2D(8, 3, 3, activation='relu', border_mode='same')(x)
encoded = MaxPooling2D((2, 2), border_mode='same')(x)

# at this point the representation is (8, 4, 4) i.e. 128-dimensional

x = Convolution2D(8, 3, 3, activation='relu', border_mode='same')(encoded)
x = UpSampling2D((2, 2))(x)
x = Convolution2D(8, 3, 3, activation='relu', border_mode='same')(x)
x = UpSampling2D((2, 2))(x)
x = Convolution2D(16, 3, 3, activation='relu')(x)
x = UpSampling2D((2, 2))(x)
decoded = Convolution2D(1, 3, 3, activation='sigmoid', border_mode='same')(x)

autoencoder = Model(input_img, decoded)
autoencoder.compile(optimizer='adadelta', loss='mse')

valid_datagen = ImageDataGenerator(rescale=1./255)
train_datagen = ImageDataGenerator(rescale=1./255)

train_generator = train_datagen.flow_from_directory(
        train_data_dir,
        target_size=(img_width, img_height),
        batch_size=32,
        class_mode=None,
        shuffle=True)

valid_generator = valid_datagen.flow_from_directory(
        valid_data_dir,
        target_size=(img_width, img_height),
        batch_size=32,
        class_mode=None,
        shuffle=True)

autoencoder.fit_generator(train_generator,
                nb_epoch=50,
                validation_data=valid_generator,
                samples_per_epoch=113,
                nb_val_samples=32
                )
</code>```

答:
The real solution lies in this Keras issue apparently by @skottapa.

https://github.com/fchollet/keras/issues/4260

rodgzilla provided an updated ImageDataGenerator that adds a class_mode='input' that solves the problem.

The nice thing is that you can backport the modification to older Keras versions. A slightly modified image module can be downloaded here:

https://gist.github.com/gsdefender/293db0987a800cf1b103b7777966f8af

Body:
I am trying to build an autoencoder for non MNIST, non Imagenet data.  Using  https://blog.keras.io/building-autoencoders-in-keras.html as my base.  However, am getting the following error.

**Exception: output of generator should be a tuple (x, y, sample_weight) or (x, y). Found: [[[[ 0.86666673  0.86666673  0.86666673 ...,  0.62352943  0.627451
     0.63137257]
   [ 0.86666673  0.86666673  0.86666673 ...,  0.63137257  0.627451
     0.627451  ]
   [ 0.86666673  0.86666673  0.86666673 ...,  0.63137257  0.627451
     0.62352943]
   ...,**

Since this is an autoencoder, in my datagenerator, used class mode=None.  My code is as follows.

from keras.layers import Input, Dense, Convolution2D, MaxPooling2D,   UpSampling2D,Activation, Dropout, Flatten
from keras.models import Model,Sequential
from keras.preprocessing.image import ImageDataGenerator
import numpy as np
import os
import h5py

img_width=140
img_height=140
train_data_dir=r'SitePhotos\train'
valid_data_dir=r'SitePhotos\validation'
input_img = Input(batch_shape=(32,3, img_width, img_width))

x = Convolution2D(16, 3, 3, activation='relu', border_mode='same')(input_img)
x = MaxPooling2D((2, 2), border_mode='same')(x)
x = Convolution2D(8, 3, 3, activation='relu', border_mode='same')(x)
x = MaxPooling2D((2, 2), border_mode='same')(x)
x = Convolution2D(8, 3, 3, activation='relu', border_mode='same')(x)
encoded = MaxPooling2D((2, 2), border_mode='same')(x)

# at this point the representation is (8, 4, 4) i.e. 128-dimensional

x = Convolution2D(8, 3, 3, activation='relu', border_mode='same')(encoded)
x = UpSampling2D((2, 2))(x)
x = Convolution2D(8, 3, 3, activation='relu', border_mode='same')(x)
x = UpSampling2D((2, 2))(x)
x = Convolution2D(16, 3, 3, activation='relu')(x)
x = UpSampling2D((2, 2))(x)
decoded = Convolution2D(1, 3, 3, activation='sigmoid', border_mode='same')(x)

autoencoder = Model(input_img, decoded)
autoencoder.compile(optimizer='adadelta', loss='mse')

valid_datagen = ImageDataGenerator(rescale=1./255)
train_datagen = ImageDataGenerator(rescale=1./255)

train_generator = train_datagen.flow_from_directory(
        train_data_dir,
        target_size=(img_width, img_height),
        batch_size=32,
        class_mode=None,
        shuffle=True)

valid_generator = valid_datagen.flow_from_directory(
        valid_data_dir,
        target_size=(img_width, img_height),
        batch_size=32,
        class_mode=None,
        shuffle=True)

autoencoder.fit_generator(train_generator,
                nb_epoch=50,
                validation_data=valid_generator,
                samples_per_epoch=113,
                nb_val_samples=32
                )


问:
how to select date in sql query
I added a lot of values in SQLite. How do I write query for searching dates earlier than today ?</p>

答:
Further details are available in the sqlite documentation ... but the following should be the sort of thing you're after.

```<code>SELECT columnA, columnB
FROM tableX
WHERE dateColumn < date('now')
</code>```

If this doesn't help, you should look to post more details of your tables, related code, etc..

Title: how to select date in sql query

Body:
Further details are available in the sqlite documentation ... but the following should be the sort of thing you're after.

SELECT columnA, columnB
FROM tableX
WHERE dateColumn < date('now')

If this doesn't help, you should look to post more details of your tables, related code, etc..


问:
Command "npm run tsc" does not work in an offline machine - trying to compile node_modules libraries
I want to execute the following commands in an offline machine (A) but the seconds point does not work:

npm install

npm run tsc

We have a machine (A) that contains my TypeScript APP and another machine (B) that acts as Artifactory (contains all the npm dependencies).

The problem here:

I cannot connect the machine A to B due to proxy restrictions.

My idea was to install my TypeScript APP into another machine (C) that does not have proxy restrictions doing the following "steps" into machine C (machines A and C has the same Operative System):

"npm install" (download the dependencies)

"npm run tsc" (to verify everyting compile)

TAR the folder "node_modules"

Copy the TAR from machine C to A

Untar "node_module.tar" as "node_module" folder

The problem here is after executing "npm run tsc" into machine A there are a lot of "node_modules" ERRORs and I don't understand why. I share with you three example of hundreds of them:

```<code>node_modules/rxjs/Scheduler.d.ts(53,67): error TS1109: Expression expected.
node_modules/rxjs/Scheduler.d.ts(53,83): error TS1109: Expression expected.
node_modules/rxjs/Scheduler.d.ts(53,86): error TS1005: ';' expected.
</code>```

FYI - I could change the machine A to be online temporary and "npm install" + "npm run tsc" worked properly. Then, I think there is something bad in the previous "steps".

Info about my installations:

```<code>bash-4.2# npm -v
3.10.10
bash-4.2# node -v
v6.9.5
bash-4.2# tsc -v
Version 1.8.10
</code>```

Many thanks!

答:
I finally found the issue in "node_modules" folder.

It turns out that:

When I created the TAR file, the compressed files were not export with the "Linux links" to other files.

This issue happened into the folder "node_modules/.bin". This folder contains "Linux links" to other files that belong to "node_modules" subfolders.

In my case, there is a link named as "node_modules/.bin/tsc that was not exported with link inside the TAR.

On the other hand, after uncompressing the TAR, the referenced file "node_modules/typescript/bin/tsc" was copied without execution permission (644).

Although the Linux link was fixed, the execution permission was disabled, then I have to change the permissions to 755.

Then, the steps to fix it were the following (inside "node_modules") folder:

rm .bin/tsc

ln -s ../typescript/bin/tsc tsc

chmod 744 typescript/bin/tsc

Cheers,
Paco.

Body:
I want to execute the following commands in an offline machine (A) but the seconds point does not work:

npm install

npm run tsc

We have a machine (A) that contains my TypeScript APP and another machine (B) that acts as Artifactory (contains all the npm dependencies).

The problem here:

I cannot connect the machine A to B due to proxy restrictions.

My idea was to install my TypeScript APP into another machine (C) that does not have proxy restrictions doing the following "steps" into machine C (machines A and C has the same Operative System):

"npm install" (download the dependencies)

"npm run tsc" (to verify everyting compile)

TAR the folder "node_modules"

Copy the TAR from machine C to A

Untar "node_module.tar" as "node_module" folder

The problem here is after executing "npm run tsc" into machine A there are a lot of "node_modules" ERRORs and I don't understand why. I share with you three example of hundreds of them:

node_modules/rxjs/Scheduler.d.ts(53,67): error TS1109: Expression expected.
node_modules/rxjs/Scheduler.d.ts(53,83): error TS1109: Expression expected.
node_modules/rxjs/Scheduler.d.ts(53,86): error TS1005: ';' expected.

FYI - I could change the machine A to be online temporary and "npm install" + "npm run tsc" worked properly. Then, I think there is something bad in the previous "steps".

Info about my installations:

bash-4.2# npm -v
3.10.10
bash-4.2# node -v
v6.9.5
bash-4.2# tsc -v
Version 1.8.10

Many thanks!


问:
How to iterate over Table in Jquery to change the content
I have this fiddle

where I have an input type with two buttons + and - , I want to add the value of the input to all the units value in the table .

JS Fiddle

The JQuery looks like thi s

```<code>$(".commission").TouchSpin({
  min: 0,
  max: 2,
  step: 0.0001,
  decimals: 4,
  boostat: 5,
  maxboostedstep: 10,
  buttondown_class: 'btn btn-white',
  buttonup_class: 'btn btn-white'
});
$(".commission").on('touchspin.on.startupspin', function() {
  var table = $(this).parent().parent().parent().prev().find('table');
  console.log(table.rows);
})
</code>```

and the HTML you can see in the fiddle itself

答:
I've updated your Fiddle with the following code:

```<code>$(".commission").on('touchspin.on.stopspin', function() {
  var cells = $(this).parent().parent().parent().parent().find('table.cust-tbl td');
  for (var i = 0; i < cells.length; i++) {
    var $cell = cells.eq(i);
    var num = $cell.data('num');
    if (num === undefined || num == null) {
      num = $cell.text().match(/[\d.]+/);
      if (num) {
        $cell.data('num', num[0]);
      }
    }
    num = +$cell.data('num');
    if (num) {
      num += (+$(this).val());
      $cell.text($cell.text().replace(/[\d.]+/, num.toFixed(4)));
    }
  }
});
</code>```

This code stores the original values in a data attribute of the cells, and adds the value to that.

Also changed the event to stopspin, so that it fires when done selecting value (up or down).

Added rounding to 4 decimals .toFixed(4).

Body:
I have this fiddle

where I have an input type with two buttons + and - , I want to add the value of the input to all the units value in the table .

JS Fiddle

The JQuery looks like thi s

$(".commission").TouchSpin({
  min: 0,
  max: 2,
  step: 0.0001,
  decimals: 4,
  boostat: 5,
  maxboostedstep: 10,
  buttondown_class: 'btn btn-white',
  buttonup_class: 'btn btn-white'
});
$(".commission").on('touchspin.on.startupspin', function() {
  var table = $(this).parent().parent().parent().prev().find('table');
  console.log(table.rows);
})

and the HTML you can see in the fiddle itself

Body:
I've updated your Fiddle with the following code:

$(".commission").on('touchspin.on.stopspin', function() {
  var cells = $(this).parent().parent().parent().parent().find('table.cust-tbl td');
  for (var i = 0; i < cells.length; i++) {
    var $cell = cells.eq(i);
    var num = $cell.data('num');
    if (num === undefined || num == null) {
      num = $cell.text().match(/[\d.]+/);
      if (num) {
        $cell.data('num', num[0]);
      }
    }
    num = +$cell.data('num');
    if (num) {
      num += (+$(this).val());
      $cell.text($cell.text().replace(/[\d.]+/, num.toFixed(4)));
    }
  }
});

This code stores the original values in a data attribute of the cells, and adds the value to that.

Also changed the event to stopspin, so that it fires when done selecting value (up or down).

Added rounding to 4 decimals .toFixed(4).


问:
Random weighted selection then remove weight
I have no reputation for a comment on @PeterLawrey's
 answer:Random weighted selection in Java. It is good. But now I call next() get a result as A and want to remove weight for A from map to avoid to get A again. How can I deal with it?

答:
You can simply change this line, in PeterLawrey's solution

```<code>public E next() {
    double value = random.nextDouble() * total;
    return map.higherEntry(value).getValue();
}
</code>```

to

```<code>public E next() {
    double value = random.nextDouble() * total--;
    return map.remove(higherKey(value));
}
</code>```

cause remove() returns the associated value after removing

Alternatively, if you need to remove elements after choosing you can use another solution. Add all the elements into a 'LinkedList', each element must be added as many times as it weight is, then use Collections.shuffle() which, according to JavaDoc

Randomly permutes the specified list using a default source of randomness.  All permutations occur with approximately equal likelihood.

Finally, get and remove elements using pop() or removeFirst()

```<code>Map<String, Integer> map = new HashMap<String, Integer>() {{
    put("Five", 5);
    put("Four", 4);
    put("Three", 3);
    put("Two", 2);
    put("One", 1);
}};

LinkedList<String> list = new LinkedList<>();

for (Map.Entry<String, Integer> entry : map.entrySet()) {
    for (int i = 0; i < entry.getValue(); i++) {
        list.add(entry.getKey());
    }
}

Collections.shuffle(list);

System.out.println("Size: " + list.size());
int size = list.size();
for (int i = 0; i < size; i++) {
    System.out.println(list.pop());
}

System.out.println("Size: " + list.size());
</code>```

Body:
You can simply change this line, in PeterLawrey's solution

public E next() {
    double value = random.nextDouble() * total;
    return map.higherEntry(value).getValue();
}

to

public E next() {
    double value = random.nextDouble() * total--;
    return map.remove(higherKey(value));
}

cause remove() returns the associated value after removing

Alternatively, if you need to remove elements after choosing you can use another solution. Add all the elements into a 'LinkedList', each element must be added as many times as it weight is, then use Collections.shuffle() which, according to JavaDoc

Randomly permutes the specified list using a default source of randomness.  All permutations occur with approximately equal likelihood.

Finally, get and remove elements using pop() or removeFirst()

Map<String, Integer> map = new HashMap<String, Integer>() {{
    put("Five", 5);
    put("Four", 4);
    put("Three", 3);
    put("Two", 2);
    put("One", 1);
}};

LinkedList<String> list = new LinkedList<>();

for (Map.Entry<String, Integer> entry : map.entrySet()) {
    for (int i = 0; i < entry.getValue(); i++) {
        list.add(entry.getKey());
    }
}

Collections.shuffle(list);

System.out.println("Size: " + list.size());
int size = list.size();
for (int i = 0; i < size; i++) {
    System.out.println(list.pop());
}

System.out.println("Size: " + list.size());


问:
Bootstrap popover position when container moves
I have used 4 bootstrap popovers on trigger focus. At a time only one popover display.

On click on anchor tag parent container moves to left but popover stay on its place and it does not move with container.

How i can move popover with container. Please suggest.

答:
You have to provide some code snippets so I can further help you but here is what I suggest:

Only use one popover as it easier to maintain the position and visibility of one popover instead of 4. Make this popover globally available.

Create a custom event handler to update your popover. The popover should listen to the event and the anchor tag parent container should throw the event whenever it moves. Such that the popover can update its position.


问:
Building a docker image (.NET Core) and uploading it to Google Container Engine?
I have an ASP.NET Core app in Visual Studio 2017 with added Docker support and I have created a free trial on Google Container Engine to see if I can host this app as a container. But I'm really totally confused by just about everything...

First of all, I just need to understand how to build the image on my Windows machine (if that is even how it should be done? or should it always be built on the server side?), and then how to deploy it? I also have Docker for Windows installed, if that is needed.

I did run this command (in the folder with my dockerfile) because I figured it was perhaps what I should do:

```<code>docker build -t myapp:v1 .
</code>```

It was successful but I have no idea where the resulting image went? I can't find any new files created that looks to be the image.

And then how do I deploy this to Google?

In the docs, I read this:

```<code>gcloud docker -- push gcr.io/${PROJECT_ID}/hello-node:v1
</code>```

What does that translate to for me? I'm running a Cloud Shell in Chrome. Can I use that to push the image from my local drive?

答:
If you build your image locally, you should check all images on your machine:

```<code>docker images
</code>```

See https://docs.docker.com/engine/reference/commandline/images/ for details

THen you have to tag your image properly

```<code>docker tag 0e5574283393 gcr.io/${PROJECT_ID}/hello-node:v1
</code>```

See https://docs.docker.com/engine/reference/commandline/tag/#extended-description for more detals.
If you list now your images, you'll have two with different tags but the same UUID. NOw you should be able to push it to GKE.

Body:
I have an ASP.NET Core app in Visual Studio 2017 with added Docker support and I have created a free trial on Google Container Engine to see if I can host this app as a container. But I'm really totally confused by just about everything...

First of all, I just need to understand how to build the image on my Windows machine (if that is even how it should be done? or should it always be built on the server side?), and then how to deploy it? I also have Docker for Windows installed, if that is needed.

I did run this command (in the folder with my dockerfile) because I figured it was perhaps what I should do:

docker build -t myapp:v1 .

It was successful but I have no idea where the resulting image went? I can't find any new files created that looks to be the image.

And then how do I deploy this to Google?

In the docs, I read this:

gcloud docker -- push gcr.io/${PROJECT_ID}/hello-node:v1

What does that translate to for me? I'm running a Cloud Shell in Chrome. Can I use that to push the image from my local drive?

Body:
If you build your image locally, you should check all images on your machine:

docker images

See https://docs.docker.com/engine/reference/commandline/images/ for details

THen you have to tag your image properly

docker tag 0e5574283393 gcr.io/${PROJECT_ID}/hello-node:v1

See https://docs.docker.com/engine/reference/commandline/tag/#extended-description for more detals.
If you list now your images, you'll have two with different tags but the same UUID. NOw you should be able to push it to GKE.


问:
Angular material mdMenu onclose scrolls page to top in firefox
I am having a simple angular material app having mdMenu at bottom of the page. On selecting an option, page scrolls to top.
This happens on firefox only (Tested on ver. 52.0.2).

Using angular ver. 1.6.4
Using angular-material ver 1.1.3

Plnkr

```<code><body>
<div style="height:1000px">This is top</div>
    <md-menu md-position-mode="target-right target">
        <md-button aria-label="Open demo menu" class="md-raised md-primary" ng-click="$mdOpenMenu($event)">
            Menu
        </md-button>
        <md-menu-content width="2">
            <md-menu-item>
                <md-button>
                    <div>
                        <p flex>
                            Option </p>
                    </div>
                </md-button>
            </md-menu-item>
        </md-menu-content>
    </md-menu>
</body>
</code>```

答:
```<code> angular.module('yourModule',[]).config( ['$anchorScrollProvider',
        function($anchorScrollProvider) {
            $anchorScrollProvider.disableAutoScrolling();
        }]
    );
</code>```

I resolved the problem by disabling the auto scroll. Be sure to clear the browser cache to ensure its working.

Body:
I am having a simple angular material app having mdMenu at bottom of the page. On selecting an option, page scrolls to top.
This happens on firefox only (Tested on ver. 52.0.2).

Using angular ver. 1.6.4
Using angular-material ver 1.1.3

Plnkr

This is top

    <md-menu md-position-mode="target-right target">
        <md-button aria-label="Open demo menu" class="md-raised md-primary" ng-click="$mdOpenMenu($event)">
            Menu
        </md-button>
        <md-menu-content width="2">
            <md-menu-item>
                <md-button>

                            Option

                </md-button>
            </md-menu-item>
        </md-menu-content>
    </md-menu>

Body:
 angular.module('yourModule',[]).config( ['$anchorScrollProvider',
        function($anchorScrollProvider) {
            $anchorScrollProvider.disableAutoScrolling();
        }]
    );

I resolved the problem by disabling the auto scroll. Be sure to clear the browser cache to ensure its working.


问:
Having trouble manipulating axis.text (ggplot2)
I saw an graphic on reddit and have been working on recreating it.  However I am having trouble configuring the axis.text into a more legible format and was wondering what some possible solutions might be.

The code that I have come up with so far is:

```<code>    library(ggplot2)
    library(forcats)

    airlines <- c('Delta', 'American', 'Spirit', 'JetBlue', 'Alaska', 'United', 'Southwest')

    market_cap <- c(37100000000,25300000000, 3400000000, 7000000000, 9000000000, 21000000000, 25800000000)

    airline_industry <- data.frame(airlines, market_cap)

    ggplot(airline_industry, aes(fct_reorder(airlines, market_cap), market_cap)) +
    geom_bar(stat = "identity") +
    labs(title = "Biggest US Airline Companies by Market Cap", y = 'Market Capitalization (USD)') +
    coord_flip() +
    theme(axis.title.y = element_blank()) +
    scale_x_discrete(labels = c('10000000000' = '10B', '20000000000' = '20B', '30000000000' = '30B'))
</code>```

So the problem I am having is that my breaks along the x axis manually lists out 10, 20, & 30 billion in digit form, which looks messy.  I am trying to figure out how to represent the breaks with 10B, 20B, and 30B.  Similar to the example to the reddit example that was shared above.  scale_x_discrete doesn't appear to be working.  What would be the correct way to get the result I want?

答:
You can use:

```<code>scale_y_continuous(breaks = c(0, 1e10, 2e10, 3e10), labels = c('0B', '10B', '20B', '30B'))
</code>```

A bit confusing perhaps to use a y scale here, but that is due to coord_flip; your original aesthetic mapping is market_cap -> y.

Then note that that axis is continuous, not discrete.

Finally, you also need to supply a label for 0, since that is a break as well. It's always good to supply both the breaks and labels. You shouldn't supply the breaks as a character vector, as it is a continuous scale.

Body:
I saw an graphic on reddit and have been working on recreating it.  However I am having trouble configuring the axis.text into a more legible format and was wondering what some possible solutions might be.

The code that I have come up with so far is:

    library(ggplot2)
    library(forcats)

    airlines <- c('Delta', 'American', 'Spirit', 'JetBlue', 'Alaska', 'United', 'Southwest')

    market_cap <- c(37100000000,25300000000, 3400000000, 7000000000, 9000000000, 21000000000, 25800000000)

    airline_industry <- data.frame(airlines, market_cap)

    ggplot(airline_industry, aes(fct_reorder(airlines, market_cap), market_cap)) +
    geom_bar(stat = "identity") +
    labs(title = "Biggest US Airline Companies by Market Cap", y = 'Market Capitalization (USD)') +
    coord_flip() +
    theme(axis.title.y = element_blank()) +
    scale_x_discrete(labels = c('10000000000' = '10B', '20000000000' = '20B', '30000000000' = '30B'))

So the problem I am having is that my breaks along the x axis manually lists out 10, 20, & 30 billion in digit form, which looks messy.  I am trying to figure out how to represent the breaks with 10B, 20B, and 30B.  Similar to the example to the reddit example that was shared above.  scale_x_discrete doesn't appear to be working.  What would be the correct way to get the result I want?

Body:
You can use:

scale_y_continuous(breaks = c(0, 1e10, 2e10, 3e10), labels = c('0B', '10B', '20B', '30B'))

A bit confusing perhaps to use a y scale here, but that is due to coord_flip; your original aesthetic mapping is market_cap -> y.

Then note that that axis is continuous, not discrete.

Finally, you also need to supply a label for 0, since that is a break as well. It's always good to supply both the breaks and labels. You shouldn't supply the breaks as a character vector, as it is a continuous scale.