问:
How to convert Pandas Dataframe columns of String type to a SET in JSON
I have a pandas dataframe whose each entry in to_json(orient="records") format returns :

```<code>{
    "applicationType": "IMPALA",
    "user": "root",
    "id": "705c64ad",
    "category_2": "{ \"tag\": \"uncategorised\",\"tag_type\":\"uncategorised\" }",
    "category_5": "{ \"tag\": \"HR\",\"tag_type\":\"Management\" }",
    "category_8": "{ \"tag\": \"uncategorised\",\"tag_type\":\"uncategorised\" }"
}
</code>```

If Dataframe is operated using to_dict(orient="records") it returns the following data in Dictionary format :

```<code>{
'applicationType': 'IMPALA',
'user': 'root',
'id': '705c64ad',
'category_2': '{ "tag": "uncategorised","tag_type":"uncategorised" }',
'category_5': '{ "tag": "HR","tag_type":"Management" }',
'category_8': '{ "tag": "uncategorised","tag_type":"uncategorised" }'
}
</code>```

I want to process the above data to produce a JSON that should be a SET having unique entries in a tag called "category" for all "category_*" columns of dataframe as follows

```<code>{
    "applicationType": "IMPALA",
    "user": "root",
    "id": "705c64ad",
    "category": [{ "tag": "uncategorised","tag_type":"uncategorised" }, { "tag": "HR","tag_type":"Management" }]
}
</code>```

答:
Try this:

```<code>import json
json_data = '''{
  "applicationType": "IMPALA",
  "user": "root",
  "id": "705c64ad",
  "category_2": {
    "tag": "uncategorised",
    "tag_type": "uncategorised"
  },
  "category_5": {
    "tag": "HR",
    "tag_type": "Management"
  },
  "category_8": {
    "tag": "uncategorised",
    "tag_type": "uncategorised"
  }
}'''
data = json.loads(json_data)

res = {x: data[x] for x in data if 'category' not in x}
res['category'] = [dict(y) for y in {tuple(data[x].items()) for x in data if 'category' in x}]
print(res)
</code>```

Output:

```<code>{'applicationType': 'IMPALA', 'user': 'root', 'id': '705c64ad', 'category': [{'tag': 'uncategorised', 'tag_type': 'uncategorised'}, {'tag': 'HR', 'tag_type': 'Management'}]}
</code>```

Body:
I have a pandas dataframe whose each entry in to_json(orient="records") format returns :

{
    "applicationType": "IMPALA",
    "user": "root",
    "id": "705c64ad",
    "category_2": "{ \"tag\": \"uncategorised\",\"tag_type\":\"uncategorised\" }",
    "category_5": "{ \"tag\": \"HR\",\"tag_type\":\"Management\" }",
    "category_8": "{ \"tag\": \"uncategorised\",\"tag_type\":\"uncategorised\" }"
}

If Dataframe is operated using to_dict(orient="records") it returns the following data in Dictionary format :

{
'applicationType': 'IMPALA',
'user': 'root',
'id': '705c64ad',
'category_2': '{ "tag": "uncategorised","tag_type":"uncategorised" }',
'category_5': '{ "tag": "HR","tag_type":"Management" }',
'category_8': '{ "tag": "uncategorised","tag_type":"uncategorised" }'
}

I want to process the above data to produce a JSON that should be a SET having unique entries in a tag called "category" for all "category_*" columns of dataframe as follows

{
    "applicationType": "IMPALA",
    "user": "root",
    "id": "705c64ad",
    "category": [{ "tag": "uncategorised","tag_type":"uncategorised" }, { "tag": "HR","tag_type":"Management" }]
}

Body:
Try this:

import json
json_data = '''{
  "applicationType": "IMPALA",
  "user": "root",
  "id": "705c64ad",
  "category_2": {
    "tag": "uncategorised",
    "tag_type": "uncategorised"
  },
  "category_5": {
    "tag": "HR",
    "tag_type": "Management"
  },
  "category_8": {
    "tag": "uncategorised",
    "tag_type": "uncategorised"
  }
}'''
data = json.loads(json_data)

res = {x: data[x] for x in data if 'category' not in x}
res['category'] = [dict(y) for y in {tuple(data[x].items()) for x in data if 'category' in x}]
print(res)

Output:

{'applicationType': 'IMPALA', 'user': 'root', 'id': '705c64ad', 'category': [{'tag': 'uncategorised', 'tag_type': 'uncategorised'}, {'tag': 'HR', 'tag_type': 'Management'}]}


来源: stackexchange

问:
Material Date Range Picker selection color formatting
When you select two date in the range picker the in-between dates get highlighted. How do i change the color of the in-between dates?

答:
You can define a style as:

```<code>  <style name="MaterialCalendarTheme_RangeFill" parent="ThemeOverlay.MaterialComponents.MaterialCalendar">
    <item name="materialCalendarStyle">@style/MyMaterialCalendar</item>
  </style>
  <style name="MyMaterialCalendar"  parent="Widget.MaterialComponents.MaterialCalendar">
    <item name="rangeFillColor">@color/my_calendar_range</item>
  </style>
</code>```

with this selector:

```<code><selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:alpha="..." android:color="@color/...."/>
</selector>
</code>```

Then in your code:

```<code>MaterialDatePicker.Builder<Pair<Long, Long>> builderRange =
        MaterialDatePicker.Builder.dateRangePicker();
builderRange.setTheme(R.style.MaterialCalendarTheme_RangeFill);
</code>```

If you want to change totally the color only in the MaterialDatePicker you can also use something like:

```<code>  <style name="MaterialCalendarTheme_RangeFill" parent="ThemeOverlay.MaterialComponents.MaterialCalendar">
    <item name="colorPrimary">@color/....</item>
  </style>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
You can define a style as:

  <style name="MaterialCalendarTheme_RangeFill" parent="ThemeOverlay.MaterialComponents.MaterialCalendar">
    <item name="materialCalendarStyle">@style/MyMaterialCalendar</item>
  </style>
  <style name="MyMaterialCalendar"  parent="Widget.MaterialComponents.MaterialCalendar">
    <item name="rangeFillColor">@color/my_calendar_range</item>
  </style>

with this selector:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:alpha="..." android:color="@color/...."/>
</selector>

Then in your code:

MaterialDatePicker.Builder<Pair<Long, Long>> builderRange =
        MaterialDatePicker.Builder.dateRangePicker();
builderRange.setTheme(R.style.MaterialCalendarTheme_RangeFill);

If you want to change totally the color only in the MaterialDatePicker you can also use something like:

  <style name="MaterialCalendarTheme_RangeFill" parent="ThemeOverlay.MaterialComponents.MaterialCalendar">
    <item name="colorPrimary">@color/....</item>
  </style>


问:
Get the array of objects from query parameters in javascript
I'm trying to parse the array from the url query parameters. The url is as below which contains the array of emp objects specified in query parameters

```<code>http://localhost:8080/list?emp[0].id=21&emp[0].name=john&emp[1].id=22&emp[1].name=tom
</code>```

Can someone please help me with the function that will parse such query params(with some ReGEX maybe) and returns the array as below

```<code>[{id:'21',name:'john'},{id:'22',name:'tom'}]
</code>```

Note: There could be any number of emp objects mentioned in the query params, for example purpose I've just added two.
I've looked for similar solutions but none of them seems to return the array which has its objects specified in the query params with the index value. So please don't mark the question as duplicate

Edit: I've written the below function which works for fetching simple query params but doesn't work for array of objects specified in query param as above.

```<code>export const getQueryParamByName = (name, url) => {
    if (!url) url = window.location.href;
    name = name.replace(/[[\]]/g, '\\$&');
    const regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)');
    const results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, ' '));
}
</code>```

答:
I tried to create a generic function to handle the layed problem:

```<code>var url = '?person[0].name=Jack&person[0].id=1&person[1].name=Jonathan&note=book';

function removeFirstChar (string) {
  var tmp = string.split('');
  tmp.splice(0 , 1);
  return tmp.join('');
}

function parse (url) {
  url = removeFirstChar(url);
  var queryParamsArray = url.split('&');

  var object = {};
  for (var i = 0; i < queryParamsArray.length; i++) {
    var queryParamArray = queryParamsArray[i].split('=');
    var re = /\[(\d*)\]/;

    if (re.test(queryParamArray[0])) {
      var reString = /\w+/g;
      var base = (((queryParamArray[0].split('.'))[0]).match(reString))[0];
      var property = (queryParamArray[0].split('.'))[1];

      if (!object[base]) {
        object[base] = [];
      }

      const urlParts = re.exec(queryParamArray[0]);
      const index = urlParts[1];

      if (object[base][index]) {
        object[base][index][property] = queryParamArray[1];
      } else {
        object[base][index] = {
          [property]: queryParamArray[1]
        }
      }
    } else {
      object[queryParamArray[0]] = queryParamArray[1];
    }
  }

  return object;
}
</code>```

It will create an object with all the properties from the query string, the example query string provided will generate the following object:

```<code>{
    person: [
        {
            name: 'Jack',
            id: '1'
        },
        {
            name: 'Jonathan'
        }
    ],
    note: 'book'
}
</code>```

Body:
I'm trying to parse the array from the url query parameters. The url is as below which contains the array of emp objects specified in query parameters

http://localhost:8080/list?emp[0].id=21&emp[0].name=john&emp[1].id=22&emp[1].name=tom

Can someone please help me with the function that will parse such query params(with some ReGEX maybe) and returns the array as below

[{id:'21',name:'john'},{id:'22',name:'tom'}]

Note: There could be any number of emp objects mentioned in the query params, for example purpose I've just added two.
I've looked for similar solutions but none of them seems to return the array which has its objects specified in the query params with the index value. So please don't mark the question as duplicate

Edit: I've written the below function which works for fetching simple query params but doesn't work for array of objects specified in query param as above.

export const getQueryParamByName = (name, url) => {
    if (!url) url = window.location.href;
    name = name.replace(/[[\]]/g, '\\$&');
    const regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)');
    const results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, ' '));
}

Body:
I tried to create a generic function to handle the layed problem:

var url = '?person[0].name=Jack&person[0].id=1&person[1].name=Jonathan&note=book';

function removeFirstChar (string) {
  var tmp = string.split('');
  tmp.splice(0 , 1);
  return tmp.join('');
}

function parse (url) {
  url = removeFirstChar(url);
  var queryParamsArray = url.split('&');

  var object = {};
  for (var i = 0; i < queryParamsArray.length; i++) {
    var queryParamArray = queryParamsArray[i].split('=');
    var re = /\[(\d*)\]/;

    if (re.test(queryParamArray[0])) {
      var reString = /\w+/g;
      var base = (((queryParamArray[0].split('.'))[0]).match(reString))[0];
      var property = (queryParamArray[0].split('.'))[1];

      if (!object[base]) {
        object[base] = [];
      }

      const urlParts = re.exec(queryParamArray[0]);
      const index = urlParts[1];

      if (object[base][index]) {
        object[base][index][property] = queryParamArray[1];
      } else {
        object[base][index] = {
          [property]: queryParamArray[1]
        }
      }
    } else {
      object[queryParamArray[0]] = queryParamArray[1];
    }
  }

  return object;
}

It will create an object with all the properties from the query string, the example query string provided will generate the following object:

{
    person: [
        {
            name: 'Jack',
            id: '1'
        },
        {
            name: 'Jonathan'
        }
    ],
    note: 'book'
}


问:
How to get the state of the mouse through JavaScript
I want to get whether the current mouse is pressed, such as the right button.

I know that you can use mousedown to maintain a variable to determine whether it has been pressed.

But when mouseup on a disabled element, there is no way to set state to up, which leads to subsequent state errors.

Is there an api to help me get the current mouse state?

example

  <button disabled>disabled</button>
```

<pre class="lang-js prettyprint-override"><code>    let state = 'up'
    document.addEventListener('mousedown', () => {
      state = 'down'
      console.log('mouseDown')
    })
    document.addEventListener('mouseup', () => {
      state = 'up'
      console.log('mouseup')
    })
    document.addEventListener('mousemove', () => {
      console.log('mousemove',state)
    })
</code>```

答:
according to the the HTML Spec
A form control that is disabled must prevent any click events that are queued on the user interaction task source from being dispatched on the element.

So you can hack the behaviour using Capturing pointer events
give your button an id ex: "mybutton"

```<code>button=document.getElementById('mybutton')
button.addEventListener('click',()=>{
console.log('click')
})

button.addEventListener('pointerdown', event => {
    console.log('down')

});

button.addEventListener('pointerup', event => {
  console.log('up')
});
</code>```

OR remove the disabled attribute and use css pointer-events: none this will prevent the button from responding and also you will still be able to get the mouse events

Body:
I want to get whether the current mouse is pressed, such as the right button.

I know that you can use mousedown to maintain a variable to determine whether it has been pressed.

But when mouseup on a disabled element, there is no way to set state to up, which leads to subsequent state errors.

Is there an api to help me get the current mouse state?

example

  <button disabled>disabled</button>

    let state = 'up'
    document.addEventListener('mousedown', () => {
      state = 'down'
      console.log('mouseDown')
    })
    document.addEventListener('mouseup', () => {
      state = 'up'
      console.log('mouseup')
    })
    document.addEventListener('mousemove', () => {
      console.log('mousemove',state)
    })

Body:
according to the the HTML Spec
A form control that is disabled must prevent any click events that are queued on the user interaction task source from being dispatched on the element.

So you can hack the behaviour using Capturing pointer events
give your button an id ex: "mybutton"

button=document.getElementById('mybutton')
button.addEventListener('click',()=>{
console.log('click')
})

button.addEventListener('pointerdown', event => {
    console.log('down')

});

button.addEventListener('pointerup', event => {
  console.log('up')
});

OR remove the disabled attribute and use css pointer-events: none this will prevent the button from responding and also you will still be able to get the mouse events


问:
NSTableview with RXSwift and RxCocoa for OSX
How do I populate the NSTableview with an array using reactive framework?
In iOS for UITableview:

```<code>self.viewModel.arrayElements.asObservable()
        .observeOn(MainScheduler.instance)
        .bind(to: detailsTableView.rx.items(cellIdentifier: "comment", cellType: UITableViewCell.self)){
            (row,element,cell) in
                 cell.addSubview(cellView)
        }.addDisposableTo(disposeBag)
</code>```

how can i achieve the same for NSTableView

答:
I ran into a similar need, and solved it with a BehaviorRelay (using RxSwift 5).

The BehaviorRelay acts as a mediator so it's possible to use regular NSTableViewDataSource and NSTableViewDelegate protocols

The important part is the self.detailsTableView.reloadData() statement which tells the tableview to reload the data, it is not triggered automatically.

Something like this:

var disposeBag = DisposeBag()
var tableDataRelay = BehaviorRelay(value: [Element]())

func viewDidLoad() {
    viewModel.arrayElements.asObservable()
        .observeOn(MainScheduler.instance)
        .bind(to: tableDataRelay).disposed(by: disposeBag)

    tableDataRelay
        .observeOn(MainScheduler.instance)
        .subscribe({ [weak self] evt in
            self.detailsTableView.reloadData()
        }).disposed(by: disposeBag)
}

func numberOfRows(in tableView: NSTableView) -> Int {
    return tableDataRelay.value.count
}

func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
    let element = tableDataRelay.value[row]
    let cellView = tableView.makeView(withIdentifier: tableColumn!.identifier, owner: nil) as? NSTableCellView

    cellView?.textField?.stringValue = element.comment
    return cellView
}

```

ContentLicense: CC BY-SA 3.0

Body:
How do I populate the NSTableview with an array using reactive framework?
In iOS for UITableview:

self.viewModel.arrayElements.asObservable()
        .observeOn(MainScheduler.instance)
        .bind(to: detailsTableView.rx.items(cellIdentifier: "comment", cellType: UITableViewCell.self)){
            (row,element,cell) in
                 cell.addSubview(cellView)
        }.addDisposableTo(disposeBag)

how can i achieve the same for NSTableView


问:
How to hide/disable TabLayouts when items on navigation drawer is clicked?
I am very new to android development and hence, I am not able to solve my problems via help from other internet resources. Using Youtube videos, I am designing an app that uses both NavigationDrawer and TabLayout, and all the TabLayout items and navigation drawer items use fragments. My problem is that when I clicked on items in navigation drawers, the app still displays TabLayout's fragments instead of displaying the fragment corresponding to the clicked item from `NavigationDrawer. Please help me with this. I have included code and even an image below. Thanks a lot.

The abovementioned image.

    public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
    private DrawerLayout drawer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //following gives toolbar and navigation bar can be viewed by sliding L-R
        Toolbar toolbar = findViewById(R.id.toolbar_main);
        setSupportActionBar(toolbar);
        //attach sectionpageadapter to viewpager
        SectionPagerAdapter pagerAdapter = new SectionPagerAdapter(getSupportFragmentManager());
        ViewPager pager = findViewById(R.id.pager);
        pager.setAdapter(pagerAdapter);

        //attach viewpager to tablayout
        TabLayout tabLayout = findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(pager);

        //following to give hamburger sign to navigation drawer
        drawer = findViewById(R.id.drawer_layout);

        //references to listen to click events on navigation views
        NavigationView navigationView = findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        //following for hamburger sign to rotate when slide from L-R
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer,toolbar,
                R.string.navigation_drawer_open,R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();

        //below is our default fragment which will be shown on create, without any clicks
        //if statement so that it wont reload on rotation or resume of the device
        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                    new HomeFragment()).commit();
            navigationView.setCheckedItem(R.id.nav_home);
        }
    }

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
        switch (menuItem.getItemId()){
            case R.id.nav_home:
            getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                    new HomeFragment()).commit();
            break;
            case R.id.nav_myaccount:
                getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                        new AccountFragment()).commit();
                break;
            case R.id.nav_mymessages:
                getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                        new MessageFragment()).commit();
                break;
            case R.id.nav_mysongs:
                getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                        new MySongFragment()).commit();
                break;
            case R.id.nav_mystores:
                getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                        new StoreFragment()).commit();
                break;
        }
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    @Override
    //following for closing navagation bar instead of leaving activity immediately  when you press back button
    public void onBackPressed() {
        if(drawer.isDrawerOpen(GravityCompat.START)){
            drawer.closeDrawer(GravityCompat.START);
        }else {
            super.onBackPressed();
        }
    }
    private class SectionPagerAdapter extends FragmentPagerAdapter{
        public SectionPagerAdapter(FragmentManager fm){
            super(fm,BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
        }

        @Override
        public int getCount() {
            return 4;
        }

        @NonNull
        @Override
        public Fragment getItem(int position) {
            switch (position){
                case 0:
                    return new HomeFragment();
                case 1:
                    return new FragmentArtists();
                case 2:
                    return new FragmentAlbum();
                case 3:
                    return new FragmentPlaylists();
            }
            return null;
        }

        @Nullable
        @Override
        public CharSequence getPageTitle(int position) {
            switch (position){
                case 0:
                    return getResources().getText(R.string.home_tab);
                case 1:
                    return getResources().getText(R.string.artist_tab);
                case 2:
                    return getResources().getText(R.string.album_tab);
                case 3:
                    return getResources().getText(R.string.playlist_tab);
            }
            return null;
        }
    }
}
```

答:
you have the provision to set the visibility of the layout elements to visible,invisible and gone. Programatically you can do this by

```<code>ViewPager.setVisibility(View.GONE);
TabLayout.setVisibility(View.GONE);
</code>```

and also you can show the FrameLayout that you are using to inflate the FrameLayout container.

FrameLayout.setVisibility(View.VISIBLE);

And start with having the FrameLayout set to gone in the XML attribute.

```<code>android:visibility="gone"
</code>```

I hope it helps.

Body:
you have the provision to set the visibility of the layout elements to visible,invisible and gone. Programatically you can do this by

ViewPager.setVisibility(View.GONE);
TabLayout.setVisibility(View.GONE);

and also you can show the FrameLayout that you are using to inflate the FrameLayout container.

FrameLayout.setVisibility(View.VISIBLE);

And start with having the FrameLayout set to gone in the XML attribute.

android:visibility="gone"

I hope it helps.


问:
How to name excel files as the names of the data frames in a list in R
I have a large list with more than 100 data frames in it. For simplification I show a list with three data frames (dummy data). I would like to write each data frame into an excel file by using openxlsx. I already created a loop, in which each data frame becomes on excel file, but I want to name each excel file as the name of the data frame. How can I get each excel file named as the data frame in the list??
So DF1 should become DF1.xlsx. DF2 should become DF2.xlsx. DF should become DF3.xlsx.But at the moment each excel file is name 1,2 or 3.
My loop:

```<code>for (i in (1:3)) {write.xlsx(listDF[i],file=paste(i,".xlsx"))}
</code>```

```<code># dummy data
listDF <- list(
  DF1 = data.frame(
    sample = c("TGX", "TGX", "TGX", "TGX"),
    RC = c(0, 1, 2, 3),
    medRC = c(0, 3, 4, 0),
    RC.norm = c(0, 3, 3, 3),
    medRC.norm = c(0, 3, 3, 3)
  ),
  DF2 = data.frame(
    sample = c("TBF", "TBF", "TBF", "TBF"),
    RC = c(2, 1, 2, 3),
    medRC = c(4, 3, 4, 0),
    RC.norm = c(1, 3, 3, 3),
    medRC.norm = c(0, 3, 3, 3)
  ),
  DF3 = data.frame(
    sample = c("TZW", "TZW", "TZW", "TZW"),
    RC = c(4, 3, 2, 3),
    medRC = c(1, 3, 2, 0),
    RC.norm = c(1, 1, 1, 1),
    medRC.norm = c(0, 7, 5, 3)
  )
</code>```

```<code>    listDF

    # $DF1
    #   sample  RC medRC RC.norm medRC.norm
    # 1  TGX    0     0       0          0
    # 2  TGX    1     3       3          3
    # 3  TGX    2     4       3          3
    # 4  TGX    3     0       3          3

    # $DF2
    #   sample RC medRC RC.norm medRC.norm
    # 1  TBF   2     4       1       0
    # 3  TBF   1     3       3       3
    # 4  TBF   2     4       3       3
    # 5  TBF   3     0       3       3

    # $DF3
    #   sample  RC medRC RC.norm medRC.norm
    # 1  TZW    4     1       1          0
    # 2  TZW    3     3       1          7
    # 3  TZW    2     2       1          5
    # 4  TZW    3     0       1          3
</code>```

答:
To retrieve names from a list in R you can run:

```<code>df_names <- names(listDF)
</code>```

Then you can use them in your loop:

```<code>for (i in (1:length(listDF))) {
  write.xlsx(listDF[[i]],
             file = paste0(df_names[i], ".xlsx"))
}
</code>```

Note that you can refer to your data frames as listDF[[]] (to return a data.frame, not a list, see the documentation) and it's generally better to store files without spaces, so use paste0 instead of paste (see the documentation).

lapply

If you would like to use lapply, it would be probably necessary to write a function like lapply(listDF, function(i) {...}), where i's are your data frames.

Or, probably you can iterate over indexes and get data frames names inside lapply like that:

```<code>lapply(seq_along(listDF),
       function(i) {write.xlsx(listDF[[i]],
                      paste0(names(listDF)[[i]], ".xlsx"))
                   }
)
</code>```

Body:
I have a large list with more than 100 data frames in it. For simplification I show a list with three data frames (dummy data). I would like to write each data frame into an excel file by using openxlsx. I already created a loop, in which each data frame becomes on excel file, but I want to name each excel file as the name of the data frame. How can I get each excel file named as the data frame in the list??
So DF1 should become DF1.xlsx. DF2 should become DF2.xlsx. DF should become DF3.xlsx.But at the moment each excel file is name 1,2 or 3.
My loop:

for (i in (1:3)) {write.xlsx(listDF[i],file=paste(i,".xlsx"))}

# dummy data
listDF <- list(
  DF1 = data.frame(
    sample = c("TGX", "TGX", "TGX", "TGX"),
    RC = c(0, 1, 2, 3),
    medRC = c(0, 3, 4, 0),
    RC.norm = c(0, 3, 3, 3),
    medRC.norm = c(0, 3, 3, 3)
  ),
  DF2 = data.frame(
    sample = c("TBF", "TBF", "TBF", "TBF"),
    RC = c(2, 1, 2, 3),
    medRC = c(4, 3, 4, 0),
    RC.norm = c(1, 3, 3, 3),
    medRC.norm = c(0, 3, 3, 3)
  ),
  DF3 = data.frame(
    sample = c("TZW", "TZW", "TZW", "TZW"),
    RC = c(4, 3, 2, 3),
    medRC = c(1, 3, 2, 0),
    RC.norm = c(1, 1, 1, 1),
    medRC.norm = c(0, 7, 5, 3)
  )

    listDF

    # $DF1
    #   sample  RC medRC RC.norm medRC.norm
    # 1  TGX    0     0       0          0
    # 2  TGX    1     3       3          3
    # 3  TGX    2     4       3          3
    # 4  TGX    3     0       3          3

    # $DF2
    #   sample RC medRC RC.norm medRC.norm
    # 1  TBF   2     4       1       0
    # 3  TBF   1     3       3       3
    # 4  TBF   2     4       3       3
    # 5  TBF   3     0       3       3

    # $DF3
    #   sample  RC medRC RC.norm medRC.norm
    # 1  TZW    4     1       1          0
    # 2  TZW    3     3       1          7
    # 3  TZW    2     2       1          5
    # 4  TZW    3     0       1          3

Body:
To retrieve names from a list in R you can run:

df_names <- names(listDF)

Then you can use them in your loop:

for (i in (1:length(listDF))) {
  write.xlsx(listDF[[i]],
             file = paste0(df_names[i], ".xlsx"))
}

Note that you can refer to your data frames as listDF[[]] (to return a data.frame, not a list, see the documentation) and it's generally better to store files without spaces, so use paste0 instead of paste (see the documentation).

lapply

If you would like to use lapply, it would be probably necessary to write a function like lapply(listDF, function(i) {...}), where i's are your data frames.

Or, probably you can iterate over indexes and get data frames names inside lapply like that:

lapply(seq_along(listDF),
       function(i) {write.xlsx(listDF[[i]],
                      paste0(names(listDF)[[i]], ".xlsx"))
                   }
)


问:
Controlling randomness in Z3
Similar (but somewhat opposite) to this SO question, I do want to expose randomness if possible.
That is, I want the two consecutive queries to provide different results.
Is that possible? Here is my code:

```<code>void oren_example()
{
    int i;

    // context + solver
    context ctx;
    solver solver(ctx);

    // sorts
    sort int_sort     = ctx.int_sort();
    sort seq_int_sort = ctx.seq_sort(int_sort);
    sort bool_sort    = ctx.bool_sort();

    // constants
    expr two   = ctx.int_val(2);
    expr five  = ctx.int_val(5);
    expr four  = ctx.int_val(4);
    expr three = ctx.int_val(3);

    // define State sort
    const char *names[4]={"x","A","b","n"};
    sort sorts[4]={int_sort,seq_int_sort,bool_sort,int_sort};
    func_decl_vector projs(ctx);
    sort state_sort = ctx.tuple_sort("State",4,names,sorts,projs).range();

    // define an arbitrary state sigma
    expr sigma = ctx.constant("sigma",state_sort);

    // define some predicate on the state
    func_decl init = function("init",state_sort,bool_sort);
    solver.add(forall(sigma,
        init(sigma) == (
            ((projs[0](sigma))          == two  ) &&
            ((projs[1](sigma).length()) == three) &&
            ((projs[1](sigma).nth(two)) == five ) &&
            ((projs[3](sigma))          == five ))));

    for (int k=0;k<2;k++)
    {
        // create a snapshot
        solver.push();

        // find an initial state
        solver.add(init(sigma));

        // check sat + get model
        if (solver.check() == sat)
        {
            model m = solver.get_model();
            std::cout << "x = " << m.eval(projs[0](sigma)) << "\n";
            std::cout << "A = " << m.eval(projs[1](sigma)) << "\n";
            std::cout << "b = " << m.eval(projs[2](sigma)) << "\n";
            std::cout << "n = " << m.eval(projs[3](sigma)) << "\n";

            int size = m.eval(projs[1](sigma).length()).get_numeral_int();
            std::vector<int> A;
            for (i=0;i<size;i++)
            {
                A.push_back(
                    m.eval(
                        projs[1](sigma).nth(
                            ctx.int_val(i))).get_numeral_int());
            }
            std::cout << "A = { ";
            for (i=0;i<size;i++)
            {
                std::cout << A[i] << " ";
            }
            std::cout << "}\n";
        }

        // restore snapshot
        solver.pop();
    }
}
</code>```

And the results are the same:

```<code>x = 2
A = (seq.++ (seq.unit 6) (seq.unit 7) (seq.unit 5))
b = false
n = 5
A = { 6 7 5 }
x = 2
A = (seq.++ (seq.unit 6) (seq.unit 7) (seq.unit 5))
b = false
n = 5
A = { 6 7 5 } // ideally this would be different than { 6 7 5 } ...
</code>```

Posted now to GitHub/Z3/issues

答:
This is typically done by adding constraints to outlaw previous models. Note that unless you add new constraints, you will not get a new solution.

If you simply want to rely on randomness after solving from scratch, try setting random seeds used by z3. There are a few of them:

```<code>$ z3 -pd | grep seed
    random_seed (unsigned int) random seed (default: 0)
    seed (unsigned int) random seed. (default: 0)
    spacer.random_seed (unsigned int) Random seed to be used by SMT solver (default: 0)
    random_seed (unsigned int) random seed for the smt solver (default: 0)
    random_seed (unsigned int) random seed (default: 0)
</code>```

whether altering these will give you a significantly different (or different at all) model will depend on your initial set of constraints and which theory solvers come into play.

To set these from the C++ API, use the set_param function. Here's how you'd set them:

```<code>set_param("sat.random_seed", 50);
set_param("smt.random_seed", 50);
</code>```

If you run z3 -pd it'll list all the settings you can give, per module. You can dump it to a file (z3 -pd > settings), then look at the created settings file for names that include seed to find which ones there are. Note that you have to prefix the actual names with the module they are in, as in the above example with sat and smt. You'll also find the module names in the z3 -pd output.

Title: Controlling randomness in Z3

Body:
Similar (but somewhat opposite) to this SO question, I do want to expose randomness if possible.
That is, I want the two consecutive queries to provide different results.
Is that possible? Here is my code:

void oren_example()
{
    int i;

    // context + solver
    context ctx;
    solver solver(ctx);

    // sorts
    sort int_sort     = ctx.int_sort();
    sort seq_int_sort = ctx.seq_sort(int_sort);
    sort bool_sort    = ctx.bool_sort();

    // constants
    expr two   = ctx.int_val(2);
    expr five  = ctx.int_val(5);
    expr four  = ctx.int_val(4);
    expr three = ctx.int_val(3);

    // define State sort
    const char *names[4]={"x","A","b","n"};
    sort sorts[4]={int_sort,seq_int_sort,bool_sort,int_sort};
    func_decl_vector projs(ctx);
    sort state_sort = ctx.tuple_sort("State",4,names,sorts,projs).range();

    // define an arbitrary state sigma
    expr sigma = ctx.constant("sigma",state_sort);

    // define some predicate on the state
    func_decl init = function("init",state_sort,bool_sort);
    solver.add(forall(sigma,
        init(sigma) == (
            ((projs[0](sigma))          == two  ) &&
            ((projs[1](sigma).length()) == three) &&
            ((projs[1](sigma).nth(two)) == five ) &&
            ((projs[3](sigma))          == five ))));

    for (int k=0;k<2;k++)
    {
        // create a snapshot
        solver.push();

        // find an initial state
        solver.add(init(sigma));

        // check sat + get model
        if (solver.check() == sat)
        {
            model m = solver.get_model();
            std::cout << "x = " << m.eval(projs[0](sigma)) << "\n";
            std::cout << "A = " << m.eval(projs[1](sigma)) << "\n";
            std::cout << "b = " << m.eval(projs[2](sigma)) << "\n";
            std::cout << "n = " << m.eval(projs[3](sigma)) << "\n";

            int size = m.eval(projs[1](sigma).length()).get_numeral_int();
            std::vector<int> A;
            for (i=0;i<size;i++)
            {
                A.push_back(
                    m.eval(
                        projs[1](sigma).nth(
                            ctx.int_val(i))).get_numeral_int());
            }
            std::cout << "A = { ";
            for (i=0;i<size;i++)
            {
                std::cout << A[i] << " ";
            }
            std::cout << "}\n";
        }

        // restore snapshot
        solver.pop();
    }
}

And the results are the same:

x = 2
A = (seq.++ (seq.unit 6) (seq.unit 7) (seq.unit 5))
b = false
n = 5
A = { 6 7 5 }
x = 2
A = (seq.++ (seq.unit 6) (seq.unit 7) (seq.unit 5))
b = false
n = 5
A = { 6 7 5 } // ideally this would be different than { 6 7 5 } ...

Posted now to GitHub/Z3/issues

Body:
This is typically done by adding constraints to outlaw previous models. Note that unless you add new constraints, you will not get a new solution.

If you simply want to rely on randomness after solving from scratch, try setting random seeds used by z3. There are a few of them:

$ z3 -pd | grep seed
    random_seed (unsigned int) random seed (default: 0)
    seed (unsigned int) random seed. (default: 0)
    spacer.random_seed (unsigned int) Random seed to be used by SMT solver (default: 0)
    random_seed (unsigned int) random seed for the smt solver (default: 0)
    random_seed (unsigned int) random seed (default: 0)

whether altering these will give you a significantly different (or different at all) model will depend on your initial set of constraints and which theory solvers come into play.

To set these from the C++ API, use the set_param function. Here's how you'd set them:

set_param("sat.random_seed", 50);
set_param("smt.random_seed", 50);

If you run z3 -pd it'll list all the settings you can give, per module. You can dump it to a file (z3 -pd > settings), then look at the created settings file for names that include seed to find which ones there are. Note that you have to prefix the actual names with the module they are in, as in the above example with sat and smt. You'll also find the module names in the z3 -pd output.


问:
How to define volume mounts for logs in Kubernates deployments and access service through public IP?

Question first Part:
Every time I deploy latest service my data is lost so I want to mount
some volume so that my data is not lost and also want to sync same
volume mount to multiple services for data sharing.

Question Second Part:
how could I access service using public IP, It's accessible on local network but not publicly

Here is the deployment file I write:

```<code>apiVersion: apps/v1
kind: Deployment
metadata:
  name: setup
  labels:
    app: setup
spec:
  replicas: 1
  selector:
    matchLabels:
      app: setup
  template:
    metadata:
      labels:
        app: setup
    spec:
      containers:
      - name: setup
        image: esmagic/setup:1.0
        ports:
        - containerPort: 8081
---
apiVersion: v1
kind: Service
metadata:
  name: setup
  labels:
    app: setup
spec:
  ports:
  - name: tcp-8081-8081-setup
    port: 8081
    targetPort: 8081
    protocol: TCP
  selector:
    app: setup
  type: LoadBalancer
  externalIPs:
    - 192.168.1.249
  sessionAffinity: None
  externalTrafficPolicy: Cluster
status:
  loadBalancer: {}
</code>```

答:
Follow this guide for using a volume mount in a pod. Specifically for logging you can write it to a volume and use Fluentd or FluentBit to send the logs to a centralized log aggregator system.

You can use NodePort or LoadBalaancer type service to expose pods outside the cluster.If you are using NodePort then the Kubernetes cluster nodes need to have Public IP. Follow this guide for NodePort.

Body:
Question first Part:
Every time I deploy latest service my data is lost so I want to mount
some volume so that my data is not lost and also want to sync same
volume mount to multiple services for data sharing.

Question Second Part:
how could I access service using public IP, It's accessible on local network but not publicly

Here is the deployment file I write:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: setup
  labels:
    app: setup
spec:
  replicas: 1
  selector:
    matchLabels:
      app: setup
  template:
    metadata:
      labels:
        app: setup
    spec:
      containers:
      - name: setup
        image: esmagic/setup:1.0
        ports:
        - containerPort: 8081
---
apiVersion: v1
kind: Service
metadata:
  name: setup
  labels:
    app: setup
spec:
  ports:
  - name: tcp-8081-8081-setup
    port: 8081
    targetPort: 8081
    protocol: TCP
  selector:
    app: setup
  type: LoadBalancer
  externalIPs:
    - 192.168.1.249
  sessionAffinity: None
  externalTrafficPolicy: Cluster
status:
  loadBalancer: {}


问:
Alpakka Kafka stream never getting terminated
We are using Alpakka Kafka streams for consuming events from Kafka. Here is how the stream is defined as:

```<code>ConsumerSettings<GenericKafkaKey, GenericKafkaMessage> consumerSettings =
    ConsumerSettings
        .create(actorSystem, new KafkaJacksonSerializer<>(GenericKafkaKey.class),
                new KafkaJacksonSerializer<>(GenericKafkaMessage.class))
        .withBootstrapServers(servers).withGroupId(groupId)
        .withClientId(clientId).withProperties(clientConfigs.defaultConsumerConfig());
CommitterSettings committerSettings = CommitterSettings.create(actorSystem)
        .withMaxBatch(20)
        .withMaxInterval(Duration.ofSeconds(30));
Consumer.DrainingControl<Done> control =
    Consumer.committableSource(consumerSettings, Subscriptions.topics(topics))
        .mapAsync(props.getMessageParallelism(), msg ->
                CompletableFuture.supplyAsync(() -> consumeMessage(msg), actorSystem.dispatcher())
                        .thenCompose(param -> CompletableFuture.supplyAsync(() -> msg.committableOffset())))
        .toMat(Committer.sink(committerSettings), Keep.both())
        .mapMaterializedValue(Consumer::createDrainingControl)
        .run(materializer);
</code>```

Here is the piece of code that is shutting down the stream:

```<code>CompletionStage<Done> completionStage = control.drainAndShutdown(actorSystem.dispatcher());
completionStage.toCompletableFuture().join();
</code>```

I tried doing a get too on the completable future. But neither join nor get on future are returning. Have anyone else too faced similar problem? Is there something that I am doing wrong here?

答:
Your usage looks correct and I can't identify anything that would hinder draining.

A common thing to miss with Alpakka Kafka consumers is the stop-timeout which defaults to 30 seconds.
When using the DrainingControl you can safely set it to 0 seconds.

See https://doc.akka.io/docs/alpakka-kafka/current/consumer.html#draining-control

Body:
We are using Alpakka Kafka streams for consuming events from Kafka. Here is how the stream is defined as:

ConsumerSettings<GenericKafkaKey, GenericKafkaMessage> consumerSettings =
    ConsumerSettings
        .create(actorSystem, new KafkaJacksonSerializer<>(GenericKafkaKey.class),
                new KafkaJacksonSerializer<>(GenericKafkaMessage.class))
        .withBootstrapServers(servers).withGroupId(groupId)
        .withClientId(clientId).withProperties(clientConfigs.defaultConsumerConfig());
CommitterSettings committerSettings = CommitterSettings.create(actorSystem)
        .withMaxBatch(20)
        .withMaxInterval(Duration.ofSeconds(30));
Consumer.DrainingControl<Done> control =
    Consumer.committableSource(consumerSettings, Subscriptions.topics(topics))
        .mapAsync(props.getMessageParallelism(), msg ->
                CompletableFuture.supplyAsync(() -> consumeMessage(msg), actorSystem.dispatcher())
                        .thenCompose(param -> CompletableFuture.supplyAsync(() -> msg.committableOffset())))
        .toMat(Committer.sink(committerSettings), Keep.both())
        .mapMaterializedValue(Consumer::createDrainingControl)
        .run(materializer);

Here is the piece of code that is shutting down the stream:

CompletionStage<Done> completionStage = control.drainAndShutdown(actorSystem.dispatcher());
completionStage.toCompletableFuture().join();

I tried doing a get too on the completable future. But neither join nor get on future are returning. Have anyone else too faced similar problem? Is there something that I am doing wrong here?


问:
Cannot install ggplot with conda-forge
I am trying to install ggplot with conda-forge. But it is showing some certain error. Details error message is given below.

```<code>(base) C:\Users\ASUS>conda install -c conda-forge ggplot=0.11.5
</code>```

```<code>Collecting package metadata (current_repodata.json): done
Solving environment: failed with initial frozen solve. Retrying with flexible solve.
Solving environment: failed with repodata from current_repodata.json, will retry with next repodata source.
Collecting package metadata (repodata.json): done
Solving environment: failed with initial frozen solve. Retrying with flexible solve.
Solving environment: -
Found conflicts! Looking for incompatible packages.
This can take several minutes.  Press CTRL-C to abort.
failed
</code>```

```<code>UnsatisfiableError: The following specifications were found
to be incompatible with the existing python installation in your environment:

Specifications:

  - ggplot=0.11.5 -> python[version='2.7.*|3.5.*|3.6.*|3.4.*']

Your python: python=3.7

If python is on the left-most side of the chain, that's the version you've asked for.
When python appears to the right, that indicates that the thing on the left is somehow
not available for the python version you are constrained to. Note that conda will not
change your python version to a different minor version unless you explicitly specify
that.

The following specifications were found to be incompatible with your CUDA driver:

  - feature:/win-64::__cuda==11.0=0
  - feature:|@/win-64::__cuda==11.0=0

Your installed CUDA driver is: 11.0
</code>```

Please help me with any solution.

答:
The development of yhat's ggplot python port stopped in 2016. It seems that it is only compatible with pandas<0.22 which predates python 3.7 and is thus not available for python-3.7 on conda-forge.

The easiest way to use it is to install it into an environment with a python3.6 interpreter.

Title: Cannot install ggplot with conda-forge

Body:
I am trying to install ggplot with conda-forge. But it is showing some certain error. Details error message is given below.

(base) C:\Users\ASUS>conda install -c conda-forge ggplot=0.11.5

Collecting package metadata (current_repodata.json): done
Solving environment: failed with initial frozen solve. Retrying with flexible solve.
Solving environment: failed with repodata from current_repodata.json, will retry with next repodata source.
Collecting package metadata (repodata.json): done
Solving environment: failed with initial frozen solve. Retrying with flexible solve.
Solving environment: -
Found conflicts! Looking for incompatible packages.
This can take several minutes.  Press CTRL-C to abort.
failed

UnsatisfiableError: The following specifications were found
to be incompatible with the existing python installation in your environment:

Specifications:

  - ggplot=0.11.5 -> python[version='2.7.*|3.5.*|3.6.*|3.4.*']

Your python: python=3.7

If python is on the left-most side of the chain, that's the version you've asked for.
When python appears to the right, that indicates that the thing on the left is somehow
not available for the python version you are constrained to. Note that conda will not
change your python version to a different minor version unless you explicitly specify
that.

The following specifications were found to be incompatible with your CUDA driver:

  - feature:/win-64::__cuda==11.0=0
  - feature:|@/win-64::__cuda==11.0=0

Your installed CUDA driver is: 11.0

Please help me with any solution.


问:
Swift: Change a button color once pressed
I'm trying to make a basic app my iPhone. I'm completely new to Xcode and I've had a browse on google and could not find exactly what I'm looking for. I'm trying to make a checklist for my plane.

I've basically got a View controller with several buttons on. And what I want is for the button to change from grey to blue once pressed and stay blue unless pressed again. I have no knowledge of Xcode and Swift language at all so if anyone could help please explain as if you're explaining to a kid.

So far I've managed to get the pages all setup and scrolling working but I just need the buttons to change now.

Thank you in advance,
Ty.

答:
UPDATE SWIFT 5

Remember to also call the color when state is selected

```<code>@IBAction func yourBtnAction(_ sender: UIButton) {

    sender.isSelected = !sender.isSelected
    sender.tintColor = .clear

    if sender.isSelected{
        sender.setTitleColor(.green, for: .selected)
       }
    else{
        sender.setTitleColor(.red, for: .selected)
     }
}
</code>```

Body:
UPDATE SWIFT 5

Remember to also call the color when state is selected

@IBAction func yourBtnAction(_ sender: UIButton) {

    sender.isSelected = !sender.isSelected
    sender.tintColor = .clear

    if sender.isSelected{
        sender.setTitleColor(.green, for: .selected)
       }
    else{
        sender.setTitleColor(.red, for: .selected)
     }
}


问:
PHP Warning: shell_exec(): unable to execute '[command]'
background: I have a PHP script which calls shell_exec. For the moment i just want to test that it works and am running a basic command through it. Separate copies of the same script exist in two separate webapps on the same server. Both apps' anonymous authentication are set to IUSR.

Here is the example code:

```<code>$output = shell_exec('dir 2>&1');
print_r($output);
</code>```

Trying it on one website in IIS gives the desired output. However, on another, it does not capture any output and instead give the below error:

```<code>PHP Warning:  shell_exec(): Unable to execute 'dir 2>&1' in C:\inetpub\webapp\script.php on line 4
</code>```

The only information i could find on this error is from here:

With PHP on Windows, if you get the 'Warning: shell_exec()
  [function.shell-exec]: Unable to execute' error, then you need to
  check the permissions on file 'C:\WINDOWS\system32\cmd.exe'. You need
  read/execute permission on this file.  I would recommend using the
  sysinternals Process Monitor 'procmon.exe' to confirm the user that is
  trying to run 'cmd.exe'. Filter on 'Process Name' is 'php-cgi.exe' and
  'Path' ends with 'cmd.exe'. Look at the event properties for the task
  with the access denied error, and it will show you the 'Impersonating'
  user name.  This is usually the 'Internet Guest Account', often 'NT
  AUTHORITY\IUSR'.

Yet this doesnt seem like a permissions issue. I cannot understand why its working through on website and not another. Anonymous Authentication for both websites are set to IUSR.

also, safe_mode in php.ini is set to off.

Is there anything else i need to check here? Does cmd.exe need explicit read/execute permissions for IUSR?

答: It turns out, for whatever reason, that IUSR was the problem. I cannot exactly know why, but changing Anonymous Authentication of the affected website to use another user it worked. So it is permissions related after all.</p>

Body:
background: I have a PHP script which calls shell_exec. For the moment i just want to test that it works and am running a basic command through it. Separate copies of the same script exist in two separate webapps on the same server. Both apps' anonymous authentication are set to IUSR.

Here is the example code:

$output = shell_exec('dir 2>&1');
print_r($output);

Trying it on one website in IIS gives the desired output. However, on another, it does not capture any output and instead give the below error:

PHP Warning:  shell_exec(): Unable to execute 'dir 2>&1' in C:\inetpub\webapp\script.php on line 4

The only information i could find on this error is from here:

With PHP on Windows, if you get the 'Warning: shell_exec()
  [function.shell-exec]: Unable to execute' error, then you need to
  check the permissions on file 'C:\WINDOWS\system32\cmd.exe'. You need
  read/execute permission on this file.  I would recommend using the
  sysinternals Process Monitor 'procmon.exe' to confirm the user that is
  trying to run 'cmd.exe'. Filter on 'Process Name' is 'php-cgi.exe' and
  'Path' ends with 'cmd.exe'. Look at the event properties for the task
  with the access denied error, and it will show you the 'Impersonating'
  user name.  This is usually the 'Internet Guest Account', often 'NT
  AUTHORITY\IUSR'.

Yet this doesnt seem like a permissions issue. I cannot understand why its working through on website and not another. Anonymous Authentication for both websites are set to IUSR.

also, safe_mode in php.ini is set to off.

Is there anything else i need to check here? Does cmd.exe need explicit read/execute permissions for IUSR?


问:
How to excute code after form validation within Google Tag Manager constrictions?
I need to call a tracking code when a form is submit and after it is validated using Google Tag Manager. I do not have direct access to the site code. I can only execute script from Google Tag Manager.

I've searched the web for an answer, but I could not find something that worked.

I've tried:

```<code>jQuery('#formId').on('submit',function(){
    console.log('test');
})
</code>```

But this prints "test" before the form validates the fields, so if I leave a field blank, it still prints "test".

I've tried different approaches that I found:

```<code>jQuery('#formId').on('submit',function(){
    if (jQuery('#formId').valid()){
     console.log('test');
    }
})
</code>```

or

```<code>jQuery('#formId').on('submit',function(){
    if (jQuery(this).valid()){
     console.log('test');
    }
})
</code>```

or

```<code>jQuery('#formId').on('submit',function(event){
    if (jQuery(event).valid()){
     console.log('test');
    }
})
</code>```

But they all return VM914:2 Uncaught TypeError: jQuery(...).valid is not a function

How can I run a script from Google Tag Manager that runs on formsubmit after the form validation?

答:
The given site (https://www.sportlink.com.br/a-melhor-grama-sintetica/) uses Wordpress.

The contact form in question has the class wpcf7. A web search indicated that the form and its validation logic is implemented by the Wordpress plugin Contact Form 7 (its JavaScript logic is currently available here, compressed by Autoptimize)

Fortunately, Confact Form 7 provides custom events to hook into their validation logic, which are documented here:  https://contactform7.com/dom-events/.

Solution for your question:

jQuery('.wpcf7').on('wpcf7mailsent', function(event) {
    console.log('test');
});
```

Notes:

wpcf7submit was not sufficient in my tests, this fired even for invalid forms

in case of only one contact form, jQuery('.wpcf7') works also (so you don't need to know the #formid, if that's a problem)

Body:
I need to call a tracking code when a form is submit and after it is validated using Google Tag Manager. I do not have direct access to the site code. I can only execute script from Google Tag Manager.

I've searched the web for an answer, but I could not find something that worked.

I've tried:

jQuery('#formId').on('submit',function(){
    console.log('test');
})

But this prints "test" before the form validates the fields, so if I leave a field blank, it still prints "test".

I've tried different approaches that I found:

jQuery('#formId').on('submit',function(){
    if (jQuery('#formId').valid()){
     console.log('test');
    }
})

or

jQuery('#formId').on('submit',function(){
    if (jQuery(this).valid()){
     console.log('test');
    }
})

or

jQuery('#formId').on('submit',function(event){
    if (jQuery(event).valid()){
     console.log('test');
    }
})

But they all return VM914:2 Uncaught TypeError: jQuery(...).valid is not a function

How can I run a script from Google Tag Manager that runs on formsubmit after the form validation?

Body:
The given site (https://www.sportlink.com.br/a-melhor-grama-sintetica/) uses Wordpress.

The contact form in question has the class wpcf7. A web search indicated that the form and its validation logic is implemented by the Wordpress plugin Contact Form 7 (its JavaScript logic is currently available here, compressed by Autoptimize)

Fortunately, Confact Form 7 provides custom events to hook into their validation logic, which are documented here:  https://contactform7.com/dom-events/.

Solution for your question:

jQuery('.wpcf7').on('wpcf7mailsent', function(event) {
    console.log('test');
});

Notes:

wpcf7submit was not sufficient in my tests, this fired even for invalid forms

in case of only one contact form, jQuery('.wpcf7') works also (so you don't need to know the #formid, if that's a problem)


问:
Remove public from url hosted in sub domain in Laravel
I have hosted my Laravel site in sub domain, its url is something like this:

https://mymaindomain.com/subfolder/public/about-us

Now i want to remove the public from url,
my .htaccess file is like:

```<code><IfModule mod_rewrite.c>
    RewriteCond %{HTTPS} !=on
    RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI}/beta [L,R=301]
    RewriteRule ^(.*)$ public/$1 [L]
</IfModule>
</code>```

答:
Move your all files from /public to your root folder / (which mainly your laravel folder).

Now open index.php file and edit 2 lines, as below :

```<code>require __DIR__.'/../vendor/autoload.php';
// changed to
require __DIR__.'/vendor/autoload.php';

$app = require_once __DIR__.'/../bootstrap/app.php';
// changed to
$app = require_once __DIR__.'/bootstrap/app.php';
</code>```

Now add this lines to your .htaccess to prevent access .env from URL :

```<code><Files .env>
order allow,deny
Deny from all
</Files>
</code>```

By this method you can host your laravel app in any kind of shared hosting too.

Hope this helps

Body:
I have hosted my Laravel site in sub domain, its url is something like this:

https://mymaindomain.com/subfolder/public/about-us

Now i want to remove the public from url,
my .htaccess file is like:

<IfModule mod_rewrite.c>
    RewriteCond %{HTTPS} !=on
    RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI}/beta [L,R=301]
    RewriteRule ^(.*)$ public/$1 [L]
</IfModule>

Body:
Move your all files from /public to your root folder / (which mainly your laravel folder).

Now open index.php file and edit 2 lines, as below :

require __DIR__.'/../vendor/autoload.php';
// changed to
require __DIR__.'/vendor/autoload.php';

$app = require_once __DIR__.'/../bootstrap/app.php';
// changed to
$app = require_once __DIR__.'/bootstrap/app.php';

Now add this lines to your .htaccess to prevent access .env from URL :

<Files .env>
order allow,deny
Deny from all
</Files>

By this method you can host your laravel app in any kind of shared hosting too.

Hope this helps


答:
The string shown in the example above looks like a base-64 encoded string.

The base-64 encoded string can be decoded easily using Buffer.from() as shown below.

Working example of decoding base-64 data:

```<code>// File name: decode-demo.js

let input = "eyJzIjoiWlIybnJVcGxVLUlGNnFZcW03cWVmUmo4MVVnIiwidiI6MSwicCI6IntcInVcIjozMDEwMTMzMixcInZcIjoxLFwidXJsXCI6XCJodHRwczpcXFwvXFxcL3Rlc3QudmFuaGV1c2VuaW5kaWEuY29tXFxcL3Jlc2V0cGFzc3dvcmRcXFwvY29udGVudFxcXC9zZWN1cmVfa2V5XFxcL2U5MmUzOWRlMDEwZmQyMTQ0ODg3NTJlODZkZTQ2NmFhXFxcL2lkX2N1c3RvbWVyXFxcLzE2OTM1ODVcXFwvc2VjXFxcLzE1OTA4MjYwMDQuNDU4XFxcL290cFxcXC8yNTgyMDE_dXRtX3NvdXJjZT1QaWdlb25fZm9yZ2V0X3Bhc3N3b3JkJnV0bV9tZWRpdW09ZW1haWwmdXRtX2NhbXBhaWduPWZvcmdldF9wYXNzd29yZFwiLFwiaWRcIjpcIjIzZGZkNDNiOGY1ODRlMmJiYTdjMzcyNGM2ZDgxMTY4XCIsXCJ1cmxfaWRzXCI6W1wiYTk4ZmEwMDgxYTk3ZjY3MGRmNDc3ZTI4MDFlYThlMzIzN2Q4YmQwMlwiXX0ifQ"
let base64Data = Buffer.from(input, 'base64')
console.log("Decoded value: \n" + (base64Data.toString()))
</code>```

Output:

```<code>> node decode-demo.js

Decoded value:

{
    "s": "ZR2nrUplU-IF6qYqm7qefRj81Ug",
    "v": 1,
    "p": {
            "u": 30101332,
            "v": 1,
            "url": "https://test.vanheusenindia.com/....",
            "id": "23dfd43b8f584e2bba7c3724c6d81168",
            "url_ids": ["a98fa0081a97f670df477e2801ea8e3237d8bd02"]
    }
}
</code>```

More information:

https://www.base64decoder.io/node-js/

https://stackabuse.com/encoding-and-decoding-base64-strings-in-node-js/

Title: how to decrpt url parameter in reactjs

Body: i am getting parameter in url as p=eyJzIjoiWlIybnJVcGxVLUlGNnFZcW03cWVmUmo4MVVnIiwidiI6MSwicCI6IntcInVcIjozMDEwMTMzMixcInZcIjoxLFwidXJsXCI6XCJodHRwczpcXFwvXFxcL3Rlc3QudmFuaGV1c2VuaW5kaWEuY29tXFxcL3Jlc2V0cGFzc3dvcmRcXFwvY29udGVudFxcXC9zZWN1cmVfa2V5XFxcL2U5MmUzOWRlMDEwZmQyMTQ0ODg3NTJlODZkZTQ2NmFhXFxcL2lkX2N1c3RvbWVyXFxcLzE2OTM1ODVcXFwvc2VjXFxcLzE1OTA4MjYwMDQuNDU4XFxcL290cFxcXC8yNTgyMDE_dXRtX3NvdXJjZT1QaWdlb25fZm9yZ2V0X3Bhc3N3b3JkJnV0bV9tZWRpdW09ZW1haWwmdXRtX2NhbXBhaWduPWZvcmdldF9wYXNzd29yZFwiLFwiaWRcIjpcIjIzZGZkNDNiOGY1ODRlMmJiYTdjMzcyNGM2ZDgxMTY4XCIsXCJ1cmxfaWRzXCI6W1wiYTk4ZmEwMDgxYTk3ZjY3MGRmNDc3ZTI4MDFlYThlMzIzN2Q4YmQwMlwiXX0ifQ

Body:
The string shown in the example above looks like a base-64 encoded string.

The base-64 encoded string can be decoded easily using Buffer.from() as shown below.

Working example of decoding base-64 data:

// File name: decode-demo.js

let input = "eyJzIjoiWlIybnJVcGxVLUlGNnFZcW03cWVmUmo4MVVnIiwidiI6MSwicCI6IntcInVcIjozMDEwMTMzMixcInZcIjoxLFwidXJsXCI6XCJodHRwczpcXFwvXFxcL3Rlc3QudmFuaGV1c2VuaW5kaWEuY29tXFxcL3Jlc2V0cGFzc3dvcmRcXFwvY29udGVudFxcXC9zZWN1cmVfa2V5XFxcL2U5MmUzOWRlMDEwZmQyMTQ0ODg3NTJlODZkZTQ2NmFhXFxcL2lkX2N1c3RvbWVyXFxcLzE2OTM1ODVcXFwvc2VjXFxcLzE1OTA4MjYwMDQuNDU4XFxcL290cFxcXC8yNTgyMDE_dXRtX3NvdXJjZT1QaWdlb25fZm9yZ2V0X3Bhc3N3b3JkJnV0bV9tZWRpdW09ZW1haWwmdXRtX2NhbXBhaWduPWZvcmdldF9wYXNzd29yZFwiLFwiaWRcIjpcIjIzZGZkNDNiOGY1ODRlMmJiYTdjMzcyNGM2ZDgxMTY4XCIsXCJ1cmxfaWRzXCI6W1wiYTk4ZmEwMDgxYTk3ZjY3MGRmNDc3ZTI4MDFlYThlMzIzN2Q4YmQwMlwiXX0ifQ"
let base64Data = Buffer.from(input, 'base64')
console.log("Decoded value: \n" + (base64Data.toString()))

Output:

> node decode-demo.js

Decoded value:

{
    "s": "ZR2nrUplU-IF6qYqm7qefRj81Ug",
    "v": 1,
    "p": {
            "u": 30101332,
            "v": 1,
            "url": "https://test.vanheusenindia.com/....",
            "id": "23dfd43b8f584e2bba7c3724c6d81168",
            "url_ids": ["a98fa0081a97f670df477e2801ea8e3237d8bd02"]
    }
}

More information:

https://www.base64decoder.io/node-js/

https://stackabuse.com/encoding-and-decoding-base64-strings-in-node-js/


问:
Change responseStatusCode when returning customer Exception object
I built a rest API using Spring Boot, that returns a custom ResponseEntity when an excpetion occurs using a class xxEntity that I created

public class xxEntity<T> {
    private T body;
    private HttpStatus status;
    private int statusCode;
    private xxException error;

    public xxEntity(T body) {
        this.body = body;
        status = HttpStatus.OK;
        this.statusCode = status.value();
    }

    public xxEntity(HttpStatus status, xxException error) {
        this.status = status;
        this.statusCode = status.value();
        this.error = error;
    }
}
```

<p>When there is an exception I return the entity as following:</p>

<pre class="lang-java prettyprint-override"><code>return new xxEntity<>(HttpStatus.NOT_FOUND, new xxException(ex));
</code>```

Where ex is a json containing the Stringfrench message, Stringenglish message and an intinternal error code.

It returns a custom object with the following details:

```<code>{
    "body": null,
    "status": "NOT_FOUND",
    "statusCode": 404,
    "error": {
        "userMessage": {
            "en": "No user found",
            "fr": "Pas d'utilisateur trouvé",
            "errorCode": 10
        }
    }
}
</code>```

Till there everything is working fine, the only issue is that I can return only as status code 200 OK

I actually want to return different status code according to the event that happened so that in the front-end it can be handle easily as an exception without having to write multiple if..else conditions

Example: Actually in the json that I attached the status code is 404 NOT FOUND but when making the request in postman I receive a 200 OK

答:
The best way to do it using a controllerAdvice. This is a class annotated with @ControllerAdvice where you define methods for every exception type you want to manage and the result of that function is the response of the api, I mean an httpstatus along with the bosy you want.

In addition to this solution you can use others like using @ExceptionHandler in error handler methods inside the controller class. But I think the cleanest way is using a ControllerAdvice.

Anyway, here you can find examples of all the ways you can manage exceptions in spring rest APIs

https://www.baeldung.com/exception-handling-for-rest-with-spring

Body:
I built a rest API using Spring Boot, that returns a custom ResponseEntity when an excpetion occurs using a class xxEntity that I created

public class xxEntity<T> {
    private T body;
    private HttpStatus status;
    private int statusCode;
    private xxException error;

    public xxEntity(T body) {
        this.body = body;
        status = HttpStatus.OK;
        this.statusCode = status.value();
    }

    public xxEntity(HttpStatus status, xxException error) {
        this.status = status;
        this.statusCode = status.value();
        this.error = error;
    }
}

When there is an exception I return the entity as following:

return new xxEntity<>(HttpStatus.NOT_FOUND, new xxException(ex));

Where ex is a json containing the Stringfrench message, Stringenglish message and an intinternal error code.

It returns a custom object with the following details:

{
    "body": null,
    "status": "NOT_FOUND",
    "statusCode": 404,
    "error": {
        "userMessage": {
            "en": "No user found",
            "fr": "Pas d'utilisateur trouvé",
            "errorCode": 10
        }
    }
}

Till there everything is working fine, the only issue is that I can return only as status code 200 OK

I actually want to return different status code according to the event that happened so that in the front-end it can be handle easily as an exception without having to write multiple if..else conditions

Example: Actually in the json that I attached the status code is 404 NOT FOUND but when making the request in postman I receive a 200 OK


问:
Sorted a javascript array of objects by an object property
Hay, i have an array of objects and i need to sort them (either DESC or ASC) by a certain property of each object.

Here's the data

```<code>obj1 = new Object;
obj1.date = 1307010000;

obj2 = new Object;
obj2.date = 1306923600;

obj3 = new Object;
obj3.date = 1298974800;

obj4 = new Object;
obj4.date = 1306923600;

obj5 = new Object;
obj5.date = 1307096400;

data = [obj1,obj2,obj3,obj4,obj5];
</code>```

Now, i want to order the data array so that the objects are in order by date.

Can someone help me with this?

答:
You can use a custom sort function:</p>

```<code>function mySort(a,b) {
    return (a.date - b.date);
}
data.sort(mySort);
</code>```

Body:
Hay, i have an array of objects and i need to sort them (either DESC or ASC) by a certain property of each object.

Here's the data

obj1 = new Object;
obj1.date = 1307010000;

obj2 = new Object;
obj2.date = 1306923600;

obj3 = new Object;
obj3.date = 1298974800;

obj4 = new Object;
obj4.date = 1306923600;

obj5 = new Object;
obj5.date = 1307096400;

data = [obj1,obj2,obj3,obj4,obj5];

Now, i want to order the data array so that the objects are in order by date.

Can someone help me with this?

Body:
You can use a custom sort function:

function mySort(a,b) {
    return (a.date - b.date);
}
data.sort(mySort);


问:
[[Prototype]] vs prototype: ..what is the difference? (MyCons.__proto__ === MyCons.prototype) equals FALSE
It seems like there is a difference here...

Let's say we have function MyConstructor() {}

MyConstructor's [[Prototype]] is Function.prototype, not MyConstructor.prototype.

In other (non-standard/"console.log-able") words:

MyConstructor.__ proto__ is not MyConstructor's MyConstructor.prototype

TRY THIS:

```<code>function MyConstructor() {};
(MyConstructor.__proto__ === MyConstructor.prototype); //false?! why?
</code>```

Why is this so? Can someone explain it to me the difference?

答:
Inspired by another answer, and to complete it:</p>

```<code>var obj = {name: 'Ali'};
var arr = [1, 2, 3];
var date = new Date();
var func = function(){console.log('Hi!')};
var arrowFunc = ()=>{};

obj.prototype === undefined;
arr.prototype === undefined;
date.prototype === undefined;
func.prototype != undefined;
func.hasOwnProperty('prototype') === true;
arrowFunc.prototype === undefined;
arrowFunc.hasOwnProperty('prototype') === false;

obj.__proto__ === Object.prototype;
arr.__proto__ === Array.prototype;
date.__proto__ === Date.prototype;
func.__proto__ === Function.prototype;
arrowFunc.__proto__ === Function.prototype;

Array.prototype.__proto__ === Object.prototype;
Date.prototype.__proto__ === Object.prototype;
Function.prototype.__proto__ === Object.prototype;

Object.prototype__proto__ === undefined;

</code>```

Body:
It seems like there is a difference here...

Let's say we have function MyConstructor() {}

MyConstructor's [[Prototype]] is Function.prototype, not MyConstructor.prototype.

In other (non-standard/"console.log-able") words:

MyConstructor.__ proto__ is not MyConstructor's MyConstructor.prototype

TRY THIS:

function MyConstructor() {};
(MyConstructor.__proto__ === MyConstructor.prototype); //false?! why?

Why is this so? Can someone explain it to me the difference?

Body:
Inspired by another answer, and to complete it:

var obj = {name: 'Ali'};
var arr = [1, 2, 3];
var date = new Date();
var func = function(){console.log('Hi!')};
var arrowFunc = ()=>{};

obj.prototype === undefined;
arr.prototype === undefined;
date.prototype === undefined;
func.prototype != undefined;
func.hasOwnProperty('prototype') === true;
arrowFunc.prototype === undefined;
arrowFunc.hasOwnProperty('prototype') === false;

obj.__proto__ === Object.prototype;
arr.__proto__ === Array.prototype;
date.__proto__ === Date.prototype;
func.__proto__ === Function.prototype;
arrowFunc.__proto__ === Function.prototype;

Array.prototype.__proto__ === Object.prototype;
Date.prototype.__proto__ === Object.prototype;
Function.prototype.__proto__ === Object.prototype;

Object.prototype__proto__ === undefined;


问:
No context is current or a function that is not available in the current context when trying to load voa
source:

```<code>import java.nio.FloatBuffer;
import java.util.ArrayList;
import java.util.List;

import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL15;
import org.lwjgl.opengl.GL20;
import org.lwjgl.opengl.GL30;

public class Loader {
    private List<Integer> vaos = new ArrayList<Integer>();
    private List<Integer> vbos = new ArrayList<Integer>();

    public RawModel loadToVAO(float[] positions) {
        int vaoID = createVAO();
        storeDataInAttributeList(0,positions);
        unbindVAO();
        return new RawModel(vaoID,positions.length/3);
    }

    public void cleanUP() {
        for(int vao:vaos) {
            GL30.glDeleteVertexArrays(vao);
        }
        for(int vbo:vbos) {
            GL30.glDeleteVertexArrays(vbo);
        }
    }

    private int createVAO() {
        int vaoID = GL30.glGenVertexArrays();
        vaos.add(vaoID);
        GL30.glBindVertexArray(vaoID);
        return vaoID;
    }

    private void storeDataInAttributeList(int attributeNumber,float[] data) {
        int vaoID = GL15.glGenBuffers();
        vbos.add(vaoID);
        GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, vaoID);
        FloatBuffer buffer = storeDataImFloatBuffer(data);
        GL15.glBufferData(GL15.GL_ARRAY_BUFFER, buffer, GL15.GL_STATIC_DRAW);
        GL20.glVertexAttribPointer(attributeNumber, 3, GL11.GL_FLOAT, false, 0, 0);
        GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0);

    }
    private void unbindVAO(){
        GL30.glBindVertexArray(0);
    }

    private FloatBuffer storeDataImFloatBuffer(float[] data) {
        FloatBuffer buffer = BufferUtils.createFloatBuffer(data.length);
        buffer.put(data);
        buffer.flip();
        return buffer;
    }
}
</code>```

error:

FATAL ERROR in native method: Thread[main,5,main]: No context is current or a function that is not available in the current context was called.
 The JVM will abort execution.
 at org.lwjgl.opengl.GL30C.nglGenVertexArrays(Native Method)
 at org.lwjgl.opengl.GL30C.glGenVertexArrays(GL30C.java:2420)
 at org.lwjgl.opengl.GL30.glGenVertexArrays(GL30.java:2369) at Loader.createVAO(Loader.java:32)
 at Loader.loadToVAO(Loader.java:16) at MainGameLoop.main(MainGameLoop.java:21)
```

答: You have not called glfwMakeContextCurrent(window) or GL.createCapabilities() to actually make the OpenGL context. Add these two lines just after window creation.</p>

Body:
source:

import java.nio.FloatBuffer;
import java.util.ArrayList;
import java.util.List;

import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL15;
import org.lwjgl.opengl.GL20;
import org.lwjgl.opengl.GL30;

public class Loader {
    private List<Integer> vaos = new ArrayList<Integer>();
    private List<Integer> vbos = new ArrayList<Integer>();

    public RawModel loadToVAO(float[] positions) {
        int vaoID = createVAO();
        storeDataInAttributeList(0,positions);
        unbindVAO();
        return new RawModel(vaoID,positions.length/3);
    }

    public void cleanUP() {
        for(int vao:vaos) {
            GL30.glDeleteVertexArrays(vao);
        }
        for(int vbo:vbos) {
            GL30.glDeleteVertexArrays(vbo);
        }
    }

    private int createVAO() {
        int vaoID = GL30.glGenVertexArrays();
        vaos.add(vaoID);
        GL30.glBindVertexArray(vaoID);
        return vaoID;
    }

    private void storeDataInAttributeList(int attributeNumber,float[] data) {
        int vaoID = GL15.glGenBuffers();
        vbos.add(vaoID);
        GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, vaoID);
        FloatBuffer buffer = storeDataImFloatBuffer(data);
        GL15.glBufferData(GL15.GL_ARRAY_BUFFER, buffer, GL15.GL_STATIC_DRAW);
        GL20.glVertexAttribPointer(attributeNumber, 3, GL11.GL_FLOAT, false, 0, 0);
        GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0);

    }
    private void unbindVAO(){
        GL30.glBindVertexArray(0);
    }

    private FloatBuffer storeDataImFloatBuffer(float[] data) {
        FloatBuffer buffer = BufferUtils.createFloatBuffer(data.length);
        buffer.put(data);
        buffer.flip();
        return buffer;
    }
}

error:

FATAL ERROR in native method: Thread[main,5,main]: No context is current or a function that is not available in the current context was called.
 The JVM will abort execution.
 at org.lwjgl.opengl.GL30C.nglGenVertexArrays(Native Method)
 at org.lwjgl.opengl.GL30C.glGenVertexArrays(GL30C.java:2420)
 at org.lwjgl.opengl.GL30.glGenVertexArrays(GL30.java:2369) at Loader.createVAO(Loader.java:32)
 at Loader.loadToVAO(Loader.java:16) at MainGameLoop.main(MainGameLoop.java:21)


问:
JS through2 Arrow function this.push()
I have a problem with lexical binding in JavaScript.
This is my code:

```<code>.pipe(through.obj((url, enc, done)=>{
        if(!url) return done();
        request.head(url, (err, response)=>{
            this.push(url + ' is ' + (err ? 'down' : 'up') + '\n');
            done();
        });
    }))
</code>```

I get this error:

```<code>TypeError: this.push is not a function
</code>```

But when I use es5 function syntax like function(url,enc,done){...}:

```<code>.pipe(through.obj(function(url, enc, done){
        if(!url) return done();
        request.head(url, (err, response)=>{
            this.push(url + ' is ' + (err ? 'down' : 'up') + '\n');
            done();
        });
    }))
</code>```

then my code works well.

In this case, how can I use this.push() with the Arrow Function?
I know about Arrow Function's lexical binding, but I have no idea about using this.

Thanks for reading my text.

答:
Well in the former case, your this is pointing to window object. That's why you're getting the error.

arrow functions  don't provide their own this binding (they retain the this value of the enclosing lexical context)

In arrow functions, this retains the value of the enclosing lexical
  context's this. In global code, it will be set to the global object:

var globalObject = this; var foo = (() => this); console.log(foo() ===
  globalObject); // true

Check this out MDN-this particularly Arrow functions Section

Title: JS through2 Arrow function this.push()

Body:
I have a problem with lexical binding in JavaScript.
This is my code:

.pipe(through.obj((url, enc, done)=>{
        if(!url) return done();
        request.head(url, (err, response)=>{
            this.push(url + ' is ' + (err ? 'down' : 'up') + '\n');
            done();
        });
    }))

I get this error:

TypeError: this.push is not a function

But when I use es5 function syntax like function(url,enc,done){...}:

.pipe(through.obj(function(url, enc, done){
        if(!url) return done();
        request.head(url, (err, response)=>{
            this.push(url + ' is ' + (err ? 'down' : 'up') + '\n');
            done();
        });
    }))

then my code works well.

In this case, how can I use this.push() with the Arrow Function?
I know about Arrow Function's lexical binding, but I have no idea about using this.

Thanks for reading my text.


问:
Java - How to run function synchronously for multiple threads
I must use three instances of the Runnable class named changeCase and only one single instance of the Server class for all three changeCase instances. The process execution needs to run continously, that is why I have used while (true) inside the overridden run method. The process method execution for each Thread is overlapping. How can I solve this issue?

My code:

```<code>package uppercase;

import java.util.Scanner;

class Server {

    void process(String threadName) {

        System.out.println("You are inside the Server " +threadName);

        System.out.println("Enter your sentence");
        Scanner sc1 = new Scanner(System.in);
        String input = sc1.nextLine();

        System.out.println("Press 1 to convert to Uppercase or Press 2 to convert to Lowercase");
        Scanner sc2 = new Scanner(System.in);
        int num = sc2.nextInt();

        switch (num) {
            case 1:
                changetoUpperCase(input);
                break;
            case 2:
                changetoLowerCase(input);
                break;
            default:
                System.out.println("Invalid number given\n\n");
                break;
        }
    }

    void changetoUpperCase(String msg) {

        printMessage(msg.toUpperCase());
    }

    void changetoLowerCase(String msg) {

        printMessage(msg.toLowerCase());
    }

    void printMessage(String msg) {

        System.out.println("[ " +msg+ " ]\n\n");

        try {
            Thread.sleep(1000);
        }catch (Exception e) {
           System.out.println(e.getMessage());
        }
    }
}

class changeCase implements Runnable {

    String threadName;
    Server target;
    Thread t;

    public changeCase(Server c, String s) {

        this.threadName = s;
        this.target = c;
    }

    @Override
    synchronized public void run() {

        while(true) {

            target.process(threadName);
        }

        //target.process(threadName);
    }

}

public class UpperCase {

    public static void main(String[] args) {

        Server s1 = new Server();

        Thread t1 = new Thread(new changeCase(s1, "Thread1"));
        Thread t2 = new Thread(new changeCase(s1, "Thread2"));
        Thread t3 = new Thread(new changeCase(s1, "Thread3"));

        t1.start();
        t2.start();
        t3.start();
    }

}
</code>```

The output I need:

```<code>run:
You are inside the Server Thread1
Enter your sentence
hello world
Press 1 to convert to Uppercase or Press 2 to convert to Lowercase
1
[ HELLO WORLD ]

You are inside the Server Thread3
Enter your sentence
HELLO WORLD
Press 1 to convert to Uppercase or Press 2 to convert to Lowercase
2
[ hello world ]

You are inside the Server Thread2
Enter your sentence
hello world
Press 1 to convert to Uppercase or Press 2 to convert to Lowercase
4
Invalid number given

You are inside the Server Thread3
Enter your sentence
</code>```

The output I am getting:

```<code>run:
You are inside the Server Thread1
Enter your sentence
You are inside the Server Thread2
Enter your sentence
You are inside the Server Thread3
Enter your sentence
</code>```

答:
Declare your method as below and it should work just fine.

```<code>    @Override
    public void run() {

        while(true) {
            synchronized (target)
            {
                target.process(threadName);
                try {
                    target.wait();
                    notifyAll();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

</code>```

Since you do not want to make process() method as synchronized, so I placed synchronized keyword in run() method.

Why it should work just fine :

The synchronised around the process() method call, allows only one Thread to access it at a time.

Passing the target object in synchronized keyword as that is the resource that threads are working on.

Once you have utilised the resource i.e the process() method is executed, need to wait() on the current Thread processing and notifyAll() other threads to take ownership.

Calling target.wait() and not simply wait() because that uis the resource that threads are working on, otherwise it will throw java.lang.IllegalMonitorStateException: current thread is not owner.

Hope it answers your query.

You can go through some resources here.https://www.geeksforgeeks.org/synchronized-in-java/

Body:
I must use three instances of the Runnable class named changeCase and only one single instance of the Server class for all three changeCase instances. The process execution needs to run continously, that is why I have used while (true) inside the overridden run method. The process method execution for each Thread is overlapping. How can I solve this issue?

My code:

package uppercase;

import java.util.Scanner;

class Server {

    void process(String threadName) {

        System.out.println("You are inside the Server " +threadName);

        System.out.println("Enter your sentence");
        Scanner sc1 = new Scanner(System.in);
        String input = sc1.nextLine();

        System.out.println("Press 1 to convert to Uppercase or Press 2 to convert to Lowercase");
        Scanner sc2 = new Scanner(System.in);
        int num = sc2.nextInt();

        switch (num) {
            case 1:
                changetoUpperCase(input);
                break;
            case 2:
                changetoLowerCase(input);
                break;
            default:
                System.out.println("Invalid number given\n\n");
                break;
        }
    }

    void changetoUpperCase(String msg) {

        printMessage(msg.toUpperCase());
    }

    void changetoLowerCase(String msg) {

        printMessage(msg.toLowerCase());
    }

    void printMessage(String msg) {

        System.out.println("[ " +msg+ " ]\n\n");

        try {
            Thread.sleep(1000);
        }catch (Exception e) {
           System.out.println(e.getMessage());
        }
    }
}

class changeCase implements Runnable {

    String threadName;
    Server target;
    Thread t;

    public changeCase(Server c, String s) {

        this.threadName = s;
        this.target = c;
    }

    @Override
    synchronized public void run() {

        while(true) {

            target.process(threadName);
        }

        //target.process(threadName);
    }

}

public class UpperCase {

    public static void main(String[] args) {

        Server s1 = new Server();

        Thread t1 = new Thread(new changeCase(s1, "Thread1"));
        Thread t2 = new Thread(new changeCase(s1, "Thread2"));
        Thread t3 = new Thread(new changeCase(s1, "Thread3"));

        t1.start();
        t2.start();
        t3.start();
    }

}

The output I need:

run:
You are inside the Server Thread1
Enter your sentence
hello world
Press 1 to convert to Uppercase or Press 2 to convert to Lowercase
1
[ HELLO WORLD ]

You are inside the Server Thread3
Enter your sentence
HELLO WORLD
Press 1 to convert to Uppercase or Press 2 to convert to Lowercase
2
[ hello world ]

You are inside the Server Thread2
Enter your sentence
hello world
Press 1 to convert to Uppercase or Press 2 to convert to Lowercase
4
Invalid number given

You are inside the Server Thread3
Enter your sentence

The output I am getting:

run:
You are inside the Server Thread1
Enter your sentence
You are inside the Server Thread2
Enter your sentence
You are inside the Server Thread3
Enter your sentence

Body:
Declare your method as below and it should work just fine.

    @Override
    public void run() {

        while(true) {
            synchronized (target)
            {
                target.process(threadName);
                try {
                    target.wait();
                    notifyAll();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

Since you do not want to make process() method as synchronized, so I placed synchronized keyword in run() method.

Why it should work just fine :

The synchronised around the process() method call, allows only one Thread to access it at a time.

Passing the target object in synchronized keyword as that is the resource that threads are working on.

Once you have utilised the resource i.e the process() method is executed, need to wait() on the current Thread processing and notifyAll() other threads to take ownership.

Calling target.wait() and not simply wait() because that uis the resource that threads are working on, otherwise it will throw java.lang.IllegalMonitorStateException: current thread is not owner.

Hope it answers your query.

You can go through some resources here.https://www.geeksforgeeks.org/synchronized-in-java/


问:
Is 'Bower package management system' is now obsolete? What are the replacement of Bower (static content manager for client-site Web App)?
I am using 'Visual Studio 2019' and doing an 'ASP.NET Core 3.1' project. I was going to use

Bower package management system.

for my project. But then I saw that isn't included in the templates. Then while researching I found out that I can add that manually. And I also saw some saying that 'it is now obsolete and we should not use that'. There is a link:
https://devblogs.microsoft.com/aspnet/what-happened-to-bower/.

So, I need the best suggestion about how to go from here.

Should I set up the dependencies manually of 'Bower package management system' and use it in my project?

Should I install Bootstrap from 'NuGet Package Manager'? As, I was about to install Bootstrap with Bower.

Should I use an alternative of Bower? if 'yes' then suggest some packages similar to that.

Should I install Bower from NuGet? What does that package do?

答:
Should I set up the dependencies manually of 'Bower package management
  system' and use it in my project?

Actually, Since VS2017 and later, ASP.NET Core projects abandoned Bower system. Instead, not only Microsoft but also Bower itself suggests we should use npm Yarn or Webpack.

So if you still use Bower in your new project, you may encounter various compatibility issues, so we do not recommend you to use it in vs2019.

Should I install Bootstrap from 'NuGet Package Manager'? As, I was
  about to install Bootstrap with Bower.

To install Bootstrap in VS 2019 project, nuget is a right way. So what you thought is right.

With nuget, additional parameters can be configured into the project according to the author's needs while installing the package, so using Nuget is more convenient and convenient.

Right-click on your project-->Manage Nuget pacakges--> search Bootstrap and install it.

Should I use an alternative of Bower? if 'yes' then suggest some
  packages similar to that.

Please try to use Yarn, Webpack or Parcel rather than Bower.

Should I install Bower from NuGet? How does that package do?

The Bower package was last released in 2014 and after that, the official has announced to give up that package. It is just left as an outdated product on Nuget.

So you do not need to install that package but to use the new package just as I recommend.


问:
inspect delphi control object without modify source code
I have an Stock program which developed by Delphi,  I want a tools which can read the data from the stock program, for example, the stock price in Delphi grid object.

The Stock program under test is close source, so no chance modify source code which QTP/Robot inspector required.  I cannot tell out which Delphi version it is using, neither the object is a standard delphi control.

So anyone can tell out is it possible to inspect that delphi program object data through other technology ?

thanks in advance.

答:
You can use a tool like Winsight to find out the structure of the program window, and use FindWindow and EnumerateChildWindows to find the controls. Then you can use GetWindowText api to get the text of the control. This will work with most controls, but might not work for all. For instance TLabel control has no handle, but does its drawing itself. It has not handle to get the text from and it won't show up in WinSight. You'll have to OCR the window to get those label texts. :p

But this 'testing' sounds more like 'hacking' or 'controlling' to me, if you don't even know what kind of controls are used and which version of Delphi is used, why are you the one testing this program this way?


问:
Tomcat, mod_jk, Plesk and SSL setup problems
my workers.properties:

```<code>vi /etc/httpd/conf.d/workers.properties
worker.list=worker1
worker.worker1.type=ajp13
worker.worker1.host=localhost
worker.worker1.port=8009
</code>```

my mod_jk.conf

```<code>vi /etc/httpd/conf.d/mod_jk.conf
JkWorkersFile /etc/httpd/conf.d/workers.properties
JkShmFile     /var/log/httpd/mod_jk.shm
JkLogFile     /var/log/httpd/mod_jk.log
JkLogLevel    info
JkLogLevel info
JkLogStampFormat "[%a %b %d %H:%M:%S %Y] "
JkOptions +ForwardKeySize +ForwardURICompat -ForwardDirectories
JkRequestLogFormat "%w %V %T"
</code>```

Added to Tomcat server.xml

```<code><Engine name="Catalina" defaultHost="localhost" jvmRoute="worker1">
<Host name="domain.com" appBase="/opt/tomcat/webapps/">
<Context path="" docBase="domain-dir"/>
<Alias>www.domain.com</Alias>
</Host>
</code>```

added mod_jk entries in plesk domain name as under:

```<code>vi /var/www/vhosts/system/domain.com/conf/vhost.conf
<IfModule mod_jk.c>
JkMount /servlet/* worker1
JkMount /*.jsp worker1
</IfModule>
</code>```

Till here things started towards working but tomcat was redirecting to apache on port 80 whilst its using port 8443 for all hosted domains.

Then I tried to add SSL via java keytool utility and added the following into tomcat server.xml

```<code><Connector port="8445" protocol="org.apache.coyote.http11.Http11NioProtocol"
maxThreads="150" SSLEnabled="true" scheme="https" secure="true"
clientAuth="false" sslProtocol="TLS" keystoreFile="/opt/tomcat/ssl/keytool.jks" keystoreType="JKS" keystorePass="pass"/>
</code>```

The error was ajp cannot be initialized as address is already in use. I think the reason was port 8443 is used by Plesk. Then I changed port 8443 as 8445 and tomcat start working as https but with some error obviously because of self signed certificate.

Still not able to fix the problem(s):

http://domain.com --> working

https://domain.com --> not working

https://domain.com:8445 --> Rendering servlet pages but not pages from http (Apache) on Plesk

Why tomcat working fine with Plesk http pages and not working with
HTTPS pages?

Why tomcat request is not going to https domains of Plesk

Plesk is occupied 8443 port for displaying domains and 443 for devcot.

I don't know where I am making mistake as this 4th day I am clueless and finally decided to get help here in this forum

Please advise

答:
Do you want to Access the application via HTTPS in Apache httpd? If yes then please add all JKmount entry in Apache httpd SSL VirtualHost. </p>

```<code>JkMount /servlet/* worker1
JkMount /*.jsp worker1
</code>```

Body:
my workers.properties:

vi /etc/httpd/conf.d/workers.properties
worker.list=worker1
worker.worker1.type=ajp13
worker.worker1.host=localhost
worker.worker1.port=8009

my mod_jk.conf

vi /etc/httpd/conf.d/mod_jk.conf
JkWorkersFile /etc/httpd/conf.d/workers.properties
JkShmFile     /var/log/httpd/mod_jk.shm
JkLogFile     /var/log/httpd/mod_jk.log
JkLogLevel    info
JkLogLevel info
JkLogStampFormat "[%a %b %d %H:%M:%S %Y] "
JkOptions +ForwardKeySize +ForwardURICompat -ForwardDirectories
JkRequestLogFormat "%w %V %T"

Added to Tomcat server.xml

<Engine name="Catalina" defaultHost="localhost" jvmRoute="worker1">
<Host name="domain.com" appBase="/opt/tomcat/webapps/">
<Context path="" docBase="domain-dir"/>
<Alias>www.domain.com</Alias>
</Host>

added mod_jk entries in plesk domain name as under:

vi /var/www/vhosts/system/domain.com/conf/vhost.conf
<IfModule mod_jk.c>
JkMount /servlet/* worker1
JkMount /*.jsp worker1
</IfModule>

Till here things started towards working but tomcat was redirecting to apache on port 80 whilst its using port 8443 for all hosted domains.

Then I tried to add SSL via java keytool utility and added the following into tomcat server.xml

<Connector port="8445" protocol="org.apache.coyote.http11.Http11NioProtocol"
maxThreads="150" SSLEnabled="true" scheme="https" secure="true"
clientAuth="false" sslProtocol="TLS" keystoreFile="/opt/tomcat/ssl/keytool.jks" keystoreType="JKS" keystorePass="pass"/>

The error was ajp cannot be initialized as address is already in use. I think the reason was port 8443 is used by Plesk. Then I changed port 8443 as 8445 and tomcat start working as https but with some error obviously because of self signed certificate.

Still not able to fix the problem(s):

http://domain.com --> working

https://domain.com --> not working

https://domain.com:8445 --> Rendering servlet pages but not pages from http (Apache) on Plesk

Why tomcat working fine with Plesk http pages and not working with
HTTPS pages?

Why tomcat request is not going to https domains of Plesk

Plesk is occupied 8443 port for displaying domains and 443 for devcot.

I don't know where I am making mistake as this 4th day I am clueless and finally decided to get help here in this forum

Please advise

Body:
Do you want to Access the application via HTTPS in Apache httpd? If yes then please add all JKmount entry in Apache httpd SSL VirtualHost.

JkMount /servlet/* worker1
JkMount /*.jsp worker1


问:
Trying to plot a graph using a list of column names using seaborn
I'm trying to print a grid of seaborn plots by using a list of column names. It is plotting everything on the last plot.

```<code>fig, ax = plt.subplots(2,2, figsize=(10,10), sharex=True)

for aa in listA:
    for j in range(2):
        for i in range(2):
            ax[i][j] = sns.lineplot(x='time', y=aa, data=new_df, color='r')
</code>```

Output plot

答:
One way is to flatten the ax and iterate through them. You can call plt from matplotlib directly:

```<code>import pandas as pd
import matplotlib. pyplot as plt

dates = pd.date_range(start='1/1/2018', periods=10, freq='1D')
listA = [np.random.normal(0,1,10) for i in range(4)]
new_df = pd.DataFrame({'time':dates })

fig, ax = plt.subplots(2,2, figsize=(10,10), sharex=True)
ax = ax.flatten()
for i,aa in enumerate(listA):
    ax[i].plot(new_df['time'], aa, color='r')
    ax[i].set_xticklabels(new_df['time'], rotation = 45, ha="right",fontsize=7)
</code>```

If you really wanna use seaborn, it goes like:

```<code>fig, ax = plt.subplots(2,2, figsize=(10,10), sharex=True)
ax = ax.flatten()
for i,aa in enumerate(listA):
    sns.lineplot(x=new_df['time'], y=aa, color='r',ax=ax[i])
    ax[i].set_xticklabels(new_df['time'], rotation = 45, ha="right",fontsize=7)
</code>```

Body:
I'm trying to print a grid of seaborn plots by using a list of column names. It is plotting everything on the last plot.

fig, ax = plt.subplots(2,2, figsize=(10,10), sharex=True)

for aa in listA:
    for j in range(2):
        for i in range(2):
            ax[i][j] = sns.lineplot(x='time', y=aa, data=new_df, color='r')

Output plot

Body:
One way is to flatten the ax and iterate through them. You can call plt from matplotlib directly:

import pandas as pd
import matplotlib. pyplot as plt

dates = pd.date_range(start='1/1/2018', periods=10, freq='1D')
listA = [np.random.normal(0,1,10) for i in range(4)]
new_df = pd.DataFrame({'time':dates })

fig, ax = plt.subplots(2,2, figsize=(10,10), sharex=True)
ax = ax.flatten()
for i,aa in enumerate(listA):
    ax[i].plot(new_df['time'], aa, color='r')
    ax[i].set_xticklabels(new_df['time'], rotation = 45, ha="right",fontsize=7)

If you really wanna use seaborn, it goes like:

fig, ax = plt.subplots(2,2, figsize=(10,10), sharex=True)
ax = ax.flatten()
for i,aa in enumerate(listA):
    sns.lineplot(x=new_df['time'], y=aa, color='r',ax=ax[i])
    ax[i].set_xticklabels(new_df['time'], rotation = 45, ha="right",fontsize=7)


问:
How to return headers of columns that match a criteria for every row in a pandas dataframe?
I have a pandas dataframe df of the form :

```<code>     Col1      Col2      Col3      Col4

0    True      False     True      False
1    False     False     False     False
2    False     True      False     False
3    True      True      True      True
</code>```

Here True and False are boolean values.

I am trying to generate a new pandas dataframe new_df which should look like:

```<code>     Matched_Cols

0    [Col1, Col3]
1    []
2    [Col2]
3    [Col1, Col2, Col3, Col4]
</code>```

What is the most efficient way to achieve this?

答:
Use:

```<code>df['Matched_Cols'] = df.agg(lambda s: s.index[s].values, axis=1)
</code>```

Result:

```<code>   Col1   Col2   Col3   Col4               Matched_Cols

0   True  False   True  False              [Col1, Col3]
1  False  False  False  False                        []
2  False   True  False  False                    [Col2]
3   True   True   True   True  [Col1, Col2, Col3, Col4]
</code>```

Body:
I have a pandas dataframe df of the form :

     Col1      Col2      Col3      Col4

0    True      False     True      False
1    False     False     False     False
2    False     True      False     False
3    True      True      True      True

Here True and False are boolean values.

I am trying to generate a new pandas dataframe new_df which should look like:

     Matched_Cols

0    [Col1, Col3]
1    []
2    [Col2]
3    [Col1, Col2, Col3, Col4]

What is the most efficient way to achieve this?

Body:
Use:

df['Matched_Cols'] = df.agg(lambda s: s.index[s].values, axis=1)

Result:

   Col1   Col2   Col3   Col4               Matched_Cols

0   True  False   True  False              [Col1, Col3]
1  False  False  False  False                        []
2  False   True  False  False                    [Col2]
3   True   True   True   True  [Col1, Col2, Col3, Col4]