问:
problem in handling one-to-many and many-to-one mapping
the problem is when i add sous_categorie for a categorie that already exists an exception appears

java.sql.SQLIntegrityConstraintViolationException: Le champ 'id_cat' ne peut être vide (null)

i used postman for testing the API

```<code>{
"id_Cat": "1274d819-ca54-455b-b69f-07a3f8b345c0",
"souCatName": "hospitals"
}
</code>```

Class DBCategorie

```<code>@Entity
@Table(name = "categorie")
public class DBCategorie {
@Id
@GeneratedValue(generator = "uuid2")
@GenericGenerator(name = "uuid2", strategy = "uuid2")
private String idCat;

private String catName;

@OneToMany(mappedBy = "categorie")
private List<DBSousCategorie> souscategorie;

public DBCategorie() {
}
//getters& setter

public DBCategorie(String idCat, String catName, List<DBSousCategorie> souscategorie) {
    super();
    this.idCat = idCat;
    this.catName = catName;
    this.souscategorie = souscategorie;
}

public DBCategorie(String idCat, String catName) {
    this.idCat = idCat;
    this.catName = catName;
}
</code>```

class DBSousCategorie

```<code>@Entity
@Table(name = "souscategorie")
public class DBSousCategorie {
@Id
@GeneratedValue(generator = "uuid2")
@GenericGenerator(name = "uuid2", strategy = "uuid2")
private String idSouCat;

private String souCatName;

@ManyToOne(cascade=CascadeType.ALL)
@JoinColumn(name="id_Cat")
private DBCategorie categorie;

@OneToMany(mappedBy = "souscategorie")
private List<DBFile> files;

public DBSousCategorie() {
}

//Getters & Setters

public DBSousCategorie(String idSouCat, String souCatName, DBCategorie categorie) {
    super();
    this.idSouCat = idSouCat;
    this.souCatName = souCatName;
    this.categorie = categorie;
}
</code>```

答:
Did you set the parent categorie object to sous_category before persisting ?

```<code>dbSousCategory.setCategory(categorie);
subCategoryService.save(dbSousCategory);
</code>```

And to avoid recursion use @JsonIgnore to ignore the parent category.

```<code>@Entity
@Table(name = "souscategorie")
public class DBSousCategorie {
@Id
@GeneratedValue(generator = "uuid2")
@GenericGenerator(name = "uuid2", strategy = "uuid2")
private String idSouCat;

private String souCatName;

@ManyToOne(cascade=CascadeType.ALL)
@JoinColumn(name="id_Cat")
@JsonIgnore
private DBCategorie categorie;

@OneToMany(mappedBy = "souscategorie")
private List<DBFile> files;

public DBSousCategorie() {
}

//Getters & Setters

public DBSousCategorie(String idSouCat, String souCatName, DBCategorie categorie) {
    super();
    this.idSouCat = idSouCat;
    this.souCatName = souCatName;
    this.categorie = categorie;
}
</code>```

Body:
the problem is when i add sous_categorie for a categorie that already exists an exception appears

java.sql.SQLIntegrityConstraintViolationException: Le champ 'id_cat' ne peut être vide (null)

i used postman for testing the API

{
"id_Cat": "1274d819-ca54-455b-b69f-07a3f8b345c0",
"souCatName": "hospitals"
}

Class DBCategorie

@Entity
@Table(name = "categorie")
public class DBCategorie {
@Id
@GeneratedValue(generator = "uuid2")
@GenericGenerator(name = "uuid2", strategy = "uuid2")
private String idCat;

private String catName;

@OneToMany(mappedBy = "categorie")
private List<DBSousCategorie> souscategorie;

public DBCategorie() {
}
//getters& setter

public DBCategorie(String idCat, String catName, List<DBSousCategorie> souscategorie) {
    super();
    this.idCat = idCat;
    this.catName = catName;
    this.souscategorie = souscategorie;
}

public DBCategorie(String idCat, String catName) {
    this.idCat = idCat;
    this.catName = catName;
}

class DBSousCategorie

@Entity
@Table(name = "souscategorie")
public class DBSousCategorie {
@Id
@GeneratedValue(generator = "uuid2")
@GenericGenerator(name = "uuid2", strategy = "uuid2")
private String idSouCat;

private String souCatName;

@ManyToOne(cascade=CascadeType.ALL)
@JoinColumn(name="id_Cat")
private DBCategorie categorie;

@OneToMany(mappedBy = "souscategorie")
private List<DBFile> files;

public DBSousCategorie() {
}

//Getters & Setters

public DBSousCategorie(String idSouCat, String souCatName, DBCategorie categorie) {
    super();
    this.idSouCat = idSouCat;
    this.souCatName = souCatName;
    this.categorie = categorie;
}

Body:
Did you set the parent categorie object to sous_category before persisting ?

dbSousCategory.setCategory(categorie);
subCategoryService.save(dbSousCategory);

And to avoid recursion use @JsonIgnore to ignore the parent category.

@Entity
@Table(name = "souscategorie")
public class DBSousCategorie {
@Id
@GeneratedValue(generator = "uuid2")
@GenericGenerator(name = "uuid2", strategy = "uuid2")
private String idSouCat;

private String souCatName;

@ManyToOne(cascade=CascadeType.ALL)
@JoinColumn(name="id_Cat")
@JsonIgnore
private DBCategorie categorie;

@OneToMany(mappedBy = "souscategorie")
private List<DBFile> files;

public DBSousCategorie() {
}

//Getters & Setters

public DBSousCategorie(String idSouCat, String souCatName, DBCategorie categorie) {
    super();
    this.idSouCat = idSouCat;
    this.souCatName = souCatName;
    this.categorie = categorie;
}


来源: stackexchange

问:
Android Kotlin app RecyclerView Showing Nothing, Adapter Not Working, No errors
I'm trying an Api with a simple MVP Kotlin app and I do everything for it, I receive the list of coins in the Adapter but when I do a Log in bind() It doesn't show to me any error and app runs well but without any item.
I have a similar app with the same code but it works well so I don't know what to do. I bring you my code, thanks!

MainActivity:

```<code>class MainActivity : AppCompatActivity(),
    CoinsView {

    lateinit var presenter: MainPresenter
    lateinit var numAdapter: MainAdapter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val remoteRepository = RemoteRepoCalls(RetrofitFactory.getCoinApi())

        presenter = MainPresenter(
            this,
            remoteRepository
        )

        recyclerViewMain.layoutManager = LinearLayoutManager(this)
        recyclerViewMain.setHasFixedSize(true)

        numAdapter = MainAdapter()
        recyclerViewMain.adapter = numAdapter

        presenter.getMonedas("3")
    }

    override fun showData(result: List<Coins>) {
        //numAdapter.getData(result)
        numAdapter.getData(result)
    }
}
</code>```

MainAdapter:

```<code>class MainAdapter: RecyclerView.Adapter<MainAdapter.ViewHolder>() {

    var listNums : List<Coins> = listOf<Coins>()

    fun getData(list: List<Coins>) {
        listNums = list
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MainAdapter.ViewHolder {
        return ViewHolder.from(parent)
    }

    //Tamaño lista
    override fun getItemCount(): Int = listNums.size

    //Nos pasa cada dato de la lista segun posicion
    override fun onBindViewHolder(holder: MainAdapter.ViewHolder, position: Int) {
        holder.bind(listNums[position])
    }

    //Rellena la vista con cada dato
    class ViewHolder private constructor(view: View): RecyclerView.ViewHolder(view) {
        private val coinNames = view.findViewById<TextView>(R.id.coinName)
        private val coinSymbol = view.findViewById<TextView>(R.id.coinSymbol)
        //private val imageItem1 = view.findViewById<ImageView>(R.id.imageItem)

        fun bind(coinss : Coins) {
            coinNames.text = coinss.name
            coinSymbol.text = coinss.symbol
            //Picasso.get().load(coinss.thumbnail).into(imageItem1)
        }

        companion object {
            fun from(parent: ViewGroup): ViewHolder {
                val view = LayoutInflater.from(parent.context).inflate(R.layout.item, parent, false)
                return ViewHolder(view)
            }
        }
    }

}
</code>```

MainPresenter:

```<code>class MainPresenter(
    private val view: CoinsView,
    private val remoteRepository: RemoteRepository,
    private val mainDispatcher: CoroutineDispatcher = Dispatchers.Main,
    private val ioDispatcher: CoroutineDispatcher = Dispatchers.IO
) {
    fun getMonedas(limite: String) {
        CoroutineScope(ioDispatcher).launch {

            var resultado = remoteRepository.getCoins(limite)

            withContext(mainDispatcher) {
                view.showData(resultado)

            }
        }
    }
}
interface CoinsView {
    fun showData(result : List<Coins>)
}
</code>```

CoinRanking.kt:

```<code>interface CoinRanking {
    @GET("coins")
    suspend fun getAll(): Response <EveryData>
}

object RetrofitFactory {

    const val BASE_URL = "https://api.coinranking.com/v1/public/"

    fun getCoinApi(): CoinRanking {
        return Retrofit.Builder()
            .baseUrl(BASE_URL)
            .addConverterFactory(MoshiConverterFactory.create())
            .build().create(CoinRanking::class.java)
    }
}
</code>```

Coins Model:

```<code>data class Coins (
    var symbol: String,
    var name: String,
    var iconUrl: String,
    var price: String
)
</code>```

AppPhoto: Under tittle should show the recycler with coins items

答: Did you try calling the notifyDataSetChanged() after updating the list in the adapter? Seems the adapter is not refreshed.</p>

ContentLicense: CC BY-SA 4.0

Body:
I'm trying an Api with a simple MVP Kotlin app and I do everything for it, I receive the list of coins in the Adapter but when I do a Log in bind() It doesn't show to me any error and app runs well but without any item.
I have a similar app with the same code but it works well so I don't know what to do. I bring you my code, thanks!

MainActivity:

class MainActivity : AppCompatActivity(),
    CoinsView {

    lateinit var presenter: MainPresenter
    lateinit var numAdapter: MainAdapter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val remoteRepository = RemoteRepoCalls(RetrofitFactory.getCoinApi())

        presenter = MainPresenter(
            this,
            remoteRepository
        )

        recyclerViewMain.layoutManager = LinearLayoutManager(this)
        recyclerViewMain.setHasFixedSize(true)

        numAdapter = MainAdapter()
        recyclerViewMain.adapter = numAdapter

        presenter.getMonedas("3")
    }

    override fun showData(result: List<Coins>) {
        //numAdapter.getData(result)
        numAdapter.getData(result)
    }
}

MainAdapter:

class MainAdapter: RecyclerView.Adapter<MainAdapter.ViewHolder>() {

    var listNums : List<Coins> = listOf<Coins>()

    fun getData(list: List<Coins>) {
        listNums = list
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MainAdapter.ViewHolder {
        return ViewHolder.from(parent)
    }

    //Tamaño lista
    override fun getItemCount(): Int = listNums.size

    //Nos pasa cada dato de la lista segun posicion
    override fun onBindViewHolder(holder: MainAdapter.ViewHolder, position: Int) {
        holder.bind(listNums[position])
    }

    //Rellena la vista con cada dato
    class ViewHolder private constructor(view: View): RecyclerView.ViewHolder(view) {
        private val coinNames = view.findViewById<TextView>(R.id.coinName)
        private val coinSymbol = view.findViewById<TextView>(R.id.coinSymbol)
        //private val imageItem1 = view.findViewById<ImageView>(R.id.imageItem)

        fun bind(coinss : Coins) {
            coinNames.text = coinss.name
            coinSymbol.text = coinss.symbol
            //Picasso.get().load(coinss.thumbnail).into(imageItem1)
        }

        companion object {
            fun from(parent: ViewGroup): ViewHolder {
                val view = LayoutInflater.from(parent.context).inflate(R.layout.item, parent, false)
                return ViewHolder(view)
            }
        }
    }

}

MainPresenter:

class MainPresenter(
    private val view: CoinsView,
    private val remoteRepository: RemoteRepository,
    private val mainDispatcher: CoroutineDispatcher = Dispatchers.Main,
    private val ioDispatcher: CoroutineDispatcher = Dispatchers.IO
) {
    fun getMonedas(limite: String) {
        CoroutineScope(ioDispatcher).launch {

            var resultado = remoteRepository.getCoins(limite)

            withContext(mainDispatcher) {
                view.showData(resultado)

            }
        }
    }
}
interface CoinsView {
    fun showData(result : List<Coins>)
}

CoinRanking.kt:

interface CoinRanking {
    @GET("coins")
    suspend fun getAll(): Response <EveryData>
}

object RetrofitFactory {

    const val BASE_URL = "https://api.coinranking.com/v1/public/"

    fun getCoinApi(): CoinRanking {
        return Retrofit.Builder()
            .baseUrl(BASE_URL)
            .addConverterFactory(MoshiConverterFactory.create())
            .build().create(CoinRanking::class.java)
    }
}

Coins Model:

data class Coins (
    var symbol: String,
    var name: String,
    var iconUrl: String,
    var price: String
)

AppPhoto: Under tittle should show the recycler with coins items


问:
Confusion with Linux Logrotate
There is a linux mongo instance wherein the mongo logrotation has been set:

/etc/logrotate.d/mongodb

```<code>/var/log/mongodb/mongod.log {
   rotate 7
   daily
   size 500M
   copytruncate
   missingok
   create 0600 mongodb mongodb
   dateext
   delaycompress
   compress
}
</code>```

But the /etc/logrotate.conf file has the following configuration:

```<code>weekly

su root syslog

rotate 4

create

include /etc/logrotate.d

/var/log/wtmp {
    missingok
    monthly
    create 0664 root utmp
    rotate 1
}

/var/log/btmp {
    missingok
    monthly
    create 0660 root utmp
    rotate 1
}
</code>```

The question here is, will the mongo logrotation happen daily as specified in /etc/logrotate.d/mongodb or will it happen weekly as it has been specified in /etc/logrotate.conf ?

Also how do I know/ensure if the logrotation is actually happening, through cron ?

答:
logrotate must be run by cron. On Ubuntu 18.04 cron runs logrotate daily, see /etc/crontab and /etc/cron.daily. You can also run it manually.

Global weekly is the default, /etc/logrotate.d/mongodb overrides it with daily.

Title: Confusion with Linux Logrotate

Body:
There is a linux mongo instance wherein the mongo logrotation has been set:

/etc/logrotate.d/mongodb

/var/log/mongodb/mongod.log {
   rotate 7
   daily
   size 500M
   copytruncate
   missingok
   create 0600 mongodb mongodb
   dateext
   delaycompress
   compress
}

But the /etc/logrotate.conf file has the following configuration:

weekly

su root syslog

rotate 4

create

include /etc/logrotate.d

/var/log/wtmp {
    missingok
    monthly
    create 0664 root utmp
    rotate 1
}

/var/log/btmp {
    missingok
    monthly
    create 0660 root utmp
    rotate 1
}

The question here is, will the mongo logrotation happen daily as specified in /etc/logrotate.d/mongodb or will it happen weekly as it has been specified in /etc/logrotate.conf ?

Also how do I know/ensure if the logrotation is actually happening, through cron ?


问:
Repeat and Double elements in lists in Prolog
how can I write two predicates that are described below.

1) Define the double(X,Y) predicate, which is true if the list Y contains each of the elements X
repeated twice. Example: double([a,b],[a,a,b,b]) is true.

2) Define the predicate repeat(X,Y,N), which is true if the list Y contains each of the elements X
repeated N times. For example, for the question repeat([a,b],[a,a,a,b,b,b],3), Prolog answers true.

Could you give me the example of those predicates?

答:
If you have repeat/3 you have double/2.

and thus:

```<code>multiple(X,N,R) :-
    length(R,N),maplist(=(X),R).
repeat(Li,Lo,N) :-
    maplist({N}/[Xi,Xo]>>multiple(Xi,N,Xo),Li,Nested),flatten(Nested,Lo).
</code>```

But it doesn't run backwards due to the flatten/2 I think. Can that be improved?

Body:
If you have repeat/3 you have double/2.

and thus:

multiple(X,N,R) :-
    length(R,N),maplist(=(X),R).
repeat(Li,Lo,N) :-
    maplist({N}/[Xi,Xo]>>multiple(Xi,N,Xo),Li,Nested),flatten(Nested,Lo).

But it doesn't run backwards due to the flatten/2 I think. Can that be improved?


问:
ArrayList value show the column and related values in angular table

var ArrayList = [{ Width: "3" }, { Width: "3.9" }, { Width: "4.4" },
{ Width: "2" }, { Width: "2.5" }, { Width: "1.625" }, { Width: null },
{ VoltageToleranceMax: null }, { ThresholdVoltage: null },
{ ThresholdVoltage: "2.55/2.88" }, { ThresholdVoltage: "1.2" },
{ ThresholdVoltage: "1.665" }, { ThresholdVoltage: "3.3" }]
```

<p>Above array, list convert separate column</p>

<p>My Result:</p>

```Width | Threshold Voltage-Nom

3     |  2.55/2.88
3.9   |  1.2
4.4   |  1.665
2     |  3.3
2.5
1.625
```

convert the Array List to HTML table show in column and values

答:
Please make sure the object follows the naming convention to avoid exception Unexpected identifier. As you can not take a key like 'Threshold Voltage'. It should be ThresholdVoltage.

I have changed the array and follow the code to get your result.

```<code>var ArrayList = [ {Width: "3"}, {Width: "3.9"}, {Width: "4.4"},
   {Width: "2"}, {Width: "2.5"}, {Width: "1.625"}, {Width: null},
   {VoltageToleranceMax: null}, {ThresholdVoltage: null},
   {ThresholdVoltage: "2.55/2.88"}, {ThresholdVoltage: "1.2"},
   {ThresholdVoltage: "1.665"}, {ThresholdVoltage: "3.3"} ]

var widthNotFiltered  = ArrayList.map((res)=>{
  if(res.Width) {
    return res.Width;
  }
  return null;
});

var widthFiltered = widthNotFiltered.filter(function (el) {
   return el != null;
});

console.log(widthFiltered);
["3", "3.9", "4.4", "2", "2.5", "1.625"]
</code>```

Likewise, get for Threshold Voltage-Nom

```<code>var thresholdNotFiltered  = ArrayList.map((res)=>{
  if(res.ThresholdVoltage) {
    return res.ThresholdVoltage;
  }
  return null;
});

var thresholdFiltered = thresholdNotFiltered.filter(function (el) {
   return el != null;
});

console.log(thresholdFiltered);
["2.55/2.88", "1.2", "1.665", "3.3"]
</code>```

Body:
var ArrayList = [{ Width: "3" }, { Width: "3.9" }, { Width: "4.4" },
{ Width: "2" }, { Width: "2.5" }, { Width: "1.625" }, { Width: null },
{ VoltageToleranceMax: null }, { ThresholdVoltage: null },
{ ThresholdVoltage: "2.55/2.88" }, { ThresholdVoltage: "1.2" },
{ ThresholdVoltage: "1.665" }, { ThresholdVoltage: "3.3" }]

Above array, list convert separate column

My Result:

Width | Threshold Voltage-Nom

3     |  2.55/2.88
3.9   |  1.2
4.4   |  1.665
2     |  3.3
2.5
1.625

convert the Array List to HTML table show in column and values

Body:
Please make sure the object follows the naming convention to avoid exception Unexpected identifier. As you can not take a key like 'Threshold Voltage'. It should be ThresholdVoltage.

I have changed the array and follow the code to get your result.

var ArrayList = [ {Width: "3"}, {Width: "3.9"}, {Width: "4.4"},
   {Width: "2"}, {Width: "2.5"}, {Width: "1.625"}, {Width: null},
   {VoltageToleranceMax: null}, {ThresholdVoltage: null},
   {ThresholdVoltage: "2.55/2.88"}, {ThresholdVoltage: "1.2"},
   {ThresholdVoltage: "1.665"}, {ThresholdVoltage: "3.3"} ]

var widthNotFiltered  = ArrayList.map((res)=>{
  if(res.Width) {
    return res.Width;
  }
  return null;
});

var widthFiltered = widthNotFiltered.filter(function (el) {
   return el != null;
});

console.log(widthFiltered);
["3", "3.9", "4.4", "2", "2.5", "1.625"]

Likewise, get for Threshold Voltage-Nom

var thresholdNotFiltered  = ArrayList.map((res)=>{
  if(res.ThresholdVoltage) {
    return res.ThresholdVoltage;
  }
  return null;
});

var thresholdFiltered = thresholdNotFiltered.filter(function (el) {
   return el != null;
});

console.log(thresholdFiltered);
["2.55/2.88", "1.2", "1.665", "3.3"]


问:
Error: <toHaveBeenCalled> : Expected a spy, but got Function in Jamsine
I'm new to Unit testing in Angular using Jasmine and Karma. I've written a spec file but I'm getting an error. Let me first show what I've done so far. I've created a custom component:

TimeselectorComponent

```<code>startRange = moment('12-01-01');
endRange = moment ('12-12-01');

modes= ['Calendar Year', 'Year-to-date', 'Rolling Year', 'Custom'];

date = new Date();
currentYear = this.date.getFullYear(); // or simply currentYear = 2020;

@ViewChild('primaryMonthPicker') primaryMonthPicker: MonthpickerComponent; // a child component

primaryDropDown(startRange, endRange) {
    if (this.primaryMode === this.modes[0]) {
        this.initCalendarYear(this.primaryMonthPicker, this.currentYear);
    } else if (this.primaryMode === this.modes[1]) {
        this.initYearToDate(this.primaryMonthPicker, this.currentYear);
    } else if (this.primaryMode === this.modes[2]) {
        this.initRollingYear(this.primaryMonthPicker, this.currentYear);
    }
}
</code>```

In the above code MonthpickerComponent is another custom component which is the only child component of TimeselectorComponent.

I just want to check when primaryDropDown is called then initCalendarYear should also be called. Here's the spec file:

```<code>import { TestBed, ComponentFixture, async } from '@angular/core/testing';
import { TimeselectorComponent } from './timeselector.component';
...

describe('TimeselectorComponent', () => {
    let fixture: ComponentFixture<TimeselectorComponent>;

    @Component({
        selector: 'app-monthpicker',
        template: '<div></div>'
    })
    class FakeMonthpickerComponent {
        // methods of MonthpickerComponent
    }

    let MODES = [];

    beforeEach(async(() => {
        MODES = ['Calendar Year', 'Year-to-date', 'Rolling Year', 'Custom'];
        TestBed.configureTestingModule({
            declarations: [FakeMonthpickerComponent, TimeselectorComponent],
            schemas: [NO_ERRORS_SCHEMA]
        }).compileComponents();
    }));

    beforeEach(() => {
        fixture = TestBed.createComponent(TimeselectorComponent);
    });

    // other test cases that are passing

    // need help with this test case
    it('should call initCalendarYear when primaryDropDown is called', () => {
      const startRange=moment('2020-01-01');
      const endRange= moment('2020-12-01');
      spyOn(fixture.componentInstance, 'initCalendarYear');
      fixture.componentInstance.primaryMode=MODES[0];
      fixture.componentInstance.primaryDropDown(startRange, endRange);
     expect(fixture.componentInstance.initCalendarYear).toHaveBeenCalled();
  });
});
</code>```

But I'm getting this error:

I have to test whether correct method is called for associated if-else statement. Please help me.

Here's the stackblitz.

答:
Add a spy like this

```<code>spyOn(fixture.componentInstance, 'initCalendarYear');
</code>```

Change the last line by this

```<code>expect(fixture.componentInstance.initCalendarYear).toHaveBeenCalled();
</code>```

So your final test case should look like this

```<code>it('should call initCalendarYear when primaryDropDown is called', () => {
        const startRange=moment('2020-01-01');
        const endRange= moment('2020-12-01');
        fixture.componentInstance.primaryMode = MODES[0];
        spyOn(fixture.componentInstance, 'initCalendarYear');
        fixture.componentInstance.primaryDropDown(startRange, endRange);

  expect(fixture.componentInstance.initCalendarYear).toHaveBeenCalled();
 });
</code>```

Body:
I'm new to Unit testing in Angular using Jasmine and Karma. I've written a spec file but I'm getting an error. Let me first show what I've done so far. I've created a custom component:

TimeselectorComponent

startRange = moment('12-01-01');
endRange = moment ('12-12-01');

modes= ['Calendar Year', 'Year-to-date', 'Rolling Year', 'Custom'];

date = new Date();
currentYear = this.date.getFullYear(); // or simply currentYear = 2020;

@ViewChild('primaryMonthPicker') primaryMonthPicker: MonthpickerComponent; // a child component

primaryDropDown(startRange, endRange) {
    if (this.primaryMode === this.modes[0]) {
        this.initCalendarYear(this.primaryMonthPicker, this.currentYear);
    } else if (this.primaryMode === this.modes[1]) {
        this.initYearToDate(this.primaryMonthPicker, this.currentYear);
    } else if (this.primaryMode === this.modes[2]) {
        this.initRollingYear(this.primaryMonthPicker, this.currentYear);
    }
}

In the above code MonthpickerComponent is another custom component which is the only child component of TimeselectorComponent.

I just want to check when primaryDropDown is called then initCalendarYear should also be called. Here's the spec file:

import { TestBed, ComponentFixture, async } from '@angular/core/testing';
import { TimeselectorComponent } from './timeselector.component';
...

describe('TimeselectorComponent', () => {
    let fixture: ComponentFixture<TimeselectorComponent>;

    @Component({
        selector: 'app-monthpicker',
        template: '

'
    })
    class FakeMonthpickerComponent {
        // methods of MonthpickerComponent
    }

    let MODES = [];

    beforeEach(async(() => {
        MODES = ['Calendar Year', 'Year-to-date', 'Rolling Year', 'Custom'];
        TestBed.configureTestingModule({
            declarations: [FakeMonthpickerComponent, TimeselectorComponent],
            schemas: [NO_ERRORS_SCHEMA]
        }).compileComponents();
    }));

    beforeEach(() => {
        fixture = TestBed.createComponent(TimeselectorComponent);
    });

    // other test cases that are passing

    // need help with this test case
    it('should call initCalendarYear when primaryDropDown is called', () => {
      const startRange=moment('2020-01-01');
      const endRange= moment('2020-12-01');
      spyOn(fixture.componentInstance, 'initCalendarYear');
      fixture.componentInstance.primaryMode=MODES[0];
      fixture.componentInstance.primaryDropDown(startRange, endRange);
     expect(fixture.componentInstance.initCalendarYear).toHaveBeenCalled();
  });
});

But I'm getting this error:

I have to test whether correct method is called for associated if-else statement. Please help me.

Here's the stackblitz.

Body:
Add a spy like this

spyOn(fixture.componentInstance, 'initCalendarYear');

Change the last line by this

expect(fixture.componentInstance.initCalendarYear).toHaveBeenCalled();

So your final test case should look like this

it('should call initCalendarYear when primaryDropDown is called', () => {
        const startRange=moment('2020-01-01');
        const endRange= moment('2020-12-01');
        fixture.componentInstance.primaryMode = MODES[0];
        spyOn(fixture.componentInstance, 'initCalendarYear');
        fixture.componentInstance.primaryDropDown(startRange, endRange);

  expect(fixture.componentInstance.initCalendarYear).toHaveBeenCalled();
 });


问:
Javascript empty validation not working before sending to database
For some reason my JavaScript validation function is not working before sending the info to the database, I tried my best to fix it but it just wont work here is my code:

<form name="myForm" action="connectform.php" onsubmit="return validateForm()" method="POST" required>

Contact Me

      First Name :
      <input type="text" name="firstName" id="firstName" placeholder="Enter Your First Name">

      Last Name :
      <input type="text" name="lastName"  placeholder="Enter Your Last Name">

      Email
      <input type="email" name="email" id="email" placeholder="Enter Your Email">

      Message :
      <input type="text" name="info" id="info">

    <input type="submit" id='validate' class="btn" />

</form>
```

<p>and here is my javascript code (i only did it once for testing it for the first name):</p>

<pre class="lang-js prettyprint-override"><code><script>
  function validateForm() {
    var x = document.forms["myForm"]["firstName"].value;
    if (x==null || x=="") {
      alert("First name must be filled out");
      return false;
    }
</script>
</code>```

Here is my PHP code:

<?php
  $firstName = $_POST['firstName'];
  $lastName = $_POST['lastName'];
  $email = $_POST['email'];
  $info = $_POST['info'];

  //Database Connection
  $conn = new mysqli('localhost', 'root', '', 'webpage_project');

  if ($conn->connect_error) {
      echo "$conn->connect_error";
  die("Connection Failed : ". $conn->connect_error);
  }
  else{
      $stmt = $conn->prepare("insert into contactme(firstName, lastName, email, info) values (?, ?, ?, ?)");
      $stmt->bind_param("ssss", $firstName, $lastName, $email, $info);
  $execval = $stmt->execute();
      $echo'Sent Sucessfully';
  $stmt->close();
  $conn->close();
  }
?>
```

答:
Your script is missing a curly bracket }, this should fix it:

```

Body:
For some reason my JavaScript validation function is not working before sending the info to the database, I tried my best to fix it but it just wont work here is my code:

<form name="myForm" action="connectform.php" onsubmit="return validateForm()" method="POST" required>

Contact Me

      First Name :
      <input type="text" name="firstName" id="firstName" placeholder="Enter Your First Name">

      Last Name :
      <input type="text" name="lastName"  placeholder="Enter Your Last Name">

      Email
      <input type="email" name="email" id="email" placeholder="Enter Your Email">

      Message :
      <input type="text" name="info" id="info">

    <input type="submit" id='validate' class="btn" />

</form>

and here is my javascript code (i only did it once for testing it for the first name):

Here is my PHP code:

<?php
  $firstName = $_POST['firstName'];
  $lastName = $_POST['lastName'];
  $email = $_POST['email'];
  $info = $_POST['info'];

  //Database Connection
  $conn = new mysqli('localhost', 'root', '', 'webpage_project');

  if ($conn->connect_error) {
      echo "$conn->connect_error";
  die("Connection Failed : ". $conn->connect_error);
  }
  else{
      $stmt = $conn->prepare("insert into contactme(firstName, lastName, email, info) values (?, ?, ?, ?)");
      $stmt->bind_param("ssss", $firstName, $lastName, $email, $info);
  $execval = $stmt->execute();
      $echo'Sent Sucessfully';
  $stmt->close();
  $conn->close();
  }
?>

Body:
Your script is missing a curly bracket }, this should fix it:

<script>
  function validateForm() {
    var x = document.forms["myForm"]["firstName"].value;
    if (x==null || x=="") {
      alert("First name must be filled out");
      return false;
    }
  }
</script>


问:
Problem with alias in join statiment
I have problem with following query:

```<code>SELECT
    g_contac.contid, g_contac.name, g_contac.email, f_sync.foreign_key,
    (
        SELECT COUNT(g_cpers.cpersid)
        FROM g_cpers
        WHERE g_cpers.contid = g_contac.contid
    ) AS employee_count
FROM f_sync
    FULL OUTER JOIN g_contac ON
    (
        g_contac.contid = f_sync.external_id AND
        model = case when f_sync.employee_count = 0 then 'PRIVATE' else 'COMPANY' end
    )
WHERE model = 'COMPANY' or model = 'PRIVATE' OR model IS null
</code>```

When I execute it, I get error:

Invalid column name 'employee_count'.

How to solve this problem?

答:
Can you try this one:</p>

```<code>SELECT
    gt.contid, gt.name, gt.email, f_sync.foreign_key,
    gt.employee_count
FROM f_sync
    FULL OUTER JOIN
    (   SELECT
            g_contac.contid, g_contac.name, g_contac.email,
            (
                SELECT COUNT(g_cpers.cpersid)
                FROM g_cpers
                WHERE g_cpers.contid = g_contac.contid
            ) AS employee_count
        FROM g_contac
    )  AS gt ON
    (
        gt.contid = f_sync.external_id AND
        model = case when gt.employee_count = 0 then 'PRIVATE' else 'COMPANY' end
    )
</code>```

ContentLicense: CC BY-SA 3.0

Title: Problem with alias in join statiment

Body:
I have problem with following query:

SELECT
    g_contac.contid, g_contac.name, g_contac.email, f_sync.foreign_key,
    (
        SELECT COUNT(g_cpers.cpersid)
        FROM g_cpers
        WHERE g_cpers.contid = g_contac.contid
    ) AS employee_count
FROM f_sync
    FULL OUTER JOIN g_contac ON
    (
        g_contac.contid = f_sync.external_id AND
        model = case when f_sync.employee_count = 0 then 'PRIVATE' else 'COMPANY' end
    )
WHERE model = 'COMPANY' or model = 'PRIVATE' OR model IS null

When I execute it, I get error:

Invalid column name 'employee_count'.

How to solve this problem?

Body:
Can you try this one:

SELECT
    gt.contid, gt.name, gt.email, f_sync.foreign_key,
    gt.employee_count
FROM f_sync
    FULL OUTER JOIN
    (   SELECT
            g_contac.contid, g_contac.name, g_contac.email,
            (
                SELECT COUNT(g_cpers.cpersid)
                FROM g_cpers
                WHERE g_cpers.contid = g_contac.contid
            ) AS employee_count
        FROM g_contac
    )  AS gt ON
    (
        gt.contid = f_sync.external_id AND
        model = case when gt.employee_count = 0 then 'PRIVATE' else 'COMPANY' end
    )


问:
dijkstras algorithm doesn't find the actual shortest path
I am trying to implement dijkstras algorithm  in python using three dictionaries. However, I am not getting the true shortest path to Piano from Book. My implementation doesn't update the parent of Piano even after a shorter path to it from node Drum set.

Here is my output:
parents-{'Poster': 'Book',
 'Rare LP': 'Book',
 'Piano': 'Bass guitar',
 'Bass guitar': 'Rare LP',
 'Drum set': 'Rare LP'}
processed-['Poster', 'Rare LP', 'Bass guitar', 'Drum set', 'Piano']
costs-{'Poster': 0, 'Rare LP': 5, 'Bass guitar': 15, 'Drum set': 20, 'Piano': 20}

Desired_result-
parents-{'Poster': 'Book',
 'Rare LP': 'Book',
 'Piano': 'Drum set',
 'Bass guitar': 'Rare LP',
 'Drum set': 'Rare LP'}
costs-{'Poster': 0, 'Rare LP': 5, 'Bass guitar': 15, 'Drum set': 20, 'Piano': 10}

Here is my implementation-

```<code>import math
# the graph
graph = {'Book':{'Poster':0, 'Rare LP':5}, 'Poster':{'Bass guitar':30, 'Drum set':35},
         'Rare LP':{'Bass guitar':15, 'Drum set':20}, 'Bass guitar':{'Piano':20},
         'Drum set':{'Piano':10},'Piano':{}}

# the costs table
costs = {'Poster':0, 'Rare LP':5, 'Bass guitar':math.inf, 'Drum set':math.inf, 'Piano':math.inf}

# the parents table
parents = {'Poster':'Book', 'Rare LP':'Book', 'Piano':''}

processed = []

def find_lowest_cost_node(costs):
    lowest_cost = math.inf
    lowest_cost_node = None
    # Go through each node.
    for node in costs:
        cost = costs[node]
        # If it's the lowest cost so far and hasn't been processed yet...
        if cost < lowest_cost and node not in processed:
            # ... set it as the new lowest-cost node.
            lowest_cost = cost
            lowest_cost_node = node
    return lowest_cost_node

# Run till all nodes are processed
while len(processed) < len(graph)-1:
    lowest_cost_node = find_lowest_cost_node(costs)

    #Loop through neighbours of the current lowest_cost_node
    for node in graph[lowest_cost_node].keys():

        if costs[node] > costs[lowest_cost_node] + graph[lowest_cost_node][node]:
            costs[node] = graph[lowest_cost_node][node]
            parents[node] = lowest_cost_node
    processed.append(lowest_cost_node)
</code>```

答:
This part looks suspicious:

```<code>if costs[node] > costs[lowest_cost_node] + graph[lowest_cost_node][node]:
        costs[node] = graph[lowest_cost_node][node]
</code>```

The assigned cost does not include the original cost of the node.

Try:

```<code>if costs[node] > costs[lowest_cost_node] + graph[lowest_cost_node][node]:
        costs[node] = costs[lowest_cost_node] + graph[lowest_cost_node][node]
</code>```

Body:
I am trying to implement dijkstras algorithm  in python using three dictionaries. However, I am not getting the true shortest path to Piano from Book. My implementation doesn't update the parent of Piano even after a shorter path to it from node Drum set.

Here is my output:
parents-{'Poster': 'Book',
 'Rare LP': 'Book',
 'Piano': 'Bass guitar',
 'Bass guitar': 'Rare LP',
 'Drum set': 'Rare LP'}
processed-['Poster', 'Rare LP', 'Bass guitar', 'Drum set', 'Piano']
costs-{'Poster': 0, 'Rare LP': 5, 'Bass guitar': 15, 'Drum set': 20, 'Piano': 20}

Desired_result-
parents-{'Poster': 'Book',
 'Rare LP': 'Book',
 'Piano': 'Drum set',
 'Bass guitar': 'Rare LP',
 'Drum set': 'Rare LP'}
costs-{'Poster': 0, 'Rare LP': 5, 'Bass guitar': 15, 'Drum set': 20, 'Piano': 10}

Here is my implementation-

import math
# the graph
graph = {'Book':{'Poster':0, 'Rare LP':5}, 'Poster':{'Bass guitar':30, 'Drum set':35},
         'Rare LP':{'Bass guitar':15, 'Drum set':20}, 'Bass guitar':{'Piano':20},
         'Drum set':{'Piano':10},'Piano':{}}

# the costs table
costs = {'Poster':0, 'Rare LP':5, 'Bass guitar':math.inf, 'Drum set':math.inf, 'Piano':math.inf}

# the parents table
parents = {'Poster':'Book', 'Rare LP':'Book', 'Piano':''}

processed = []

def find_lowest_cost_node(costs):
    lowest_cost = math.inf
    lowest_cost_node = None
    # Go through each node.
    for node in costs:
        cost = costs[node]
        # If it's the lowest cost so far and hasn't been processed yet...
        if cost < lowest_cost and node not in processed:
            # ... set it as the new lowest-cost node.
            lowest_cost = cost
            lowest_cost_node = node
    return lowest_cost_node

# Run till all nodes are processed
while len(processed) < len(graph)-1:
    lowest_cost_node = find_lowest_cost_node(costs)

    #Loop through neighbours of the current lowest_cost_node
    for node in graph[lowest_cost_node].keys():

        if costs[node] > costs[lowest_cost_node] + graph[lowest_cost_node][node]:
            costs[node] = graph[lowest_cost_node][node]
            parents[node] = lowest_cost_node
    processed.append(lowest_cost_node)

Body:
This part looks suspicious:

if costs[node] > costs[lowest_cost_node] + graph[lowest_cost_node][node]:
        costs[node] = graph[lowest_cost_node][node]

The assigned cost does not include the original cost of the node.

Try:

if costs[node] > costs[lowest_cost_node] + graph[lowest_cost_node][node]:
        costs[node] = costs[lowest_cost_node] + graph[lowest_cost_node][node]


问:
How to associate package-info with class in Byte-buddy?
I create package-info of package foo.bar and class foo.bar.BarCl in next code

```<code>public static void main(String[] args) throws ClassNotFoundException, IOException {
        DynamicType.Unloaded<?> make = new ByteBuddy().makePackage("foo.bar").make();
        DynamicType.Loaded<Object> load = new ByteBuddy()
                .subclass(Object.class)
                .name("foo.bar.BarCl")
                .make()
                .include(make)
                .load(Main2.class.getClassLoader(), ClassLoadingStrategy.Default.INJECTION);
        load.saveIn(new File("folder"));
        Class<?> loaded = load.getLoaded();
        System.out.println(loaded.getPackage());
    }
</code>```

Class and package info correctly writing in folder:

```<code>package foo.bar;

interface $$package-info /* Real name is 'package-info' */ {
}

package foo.bar;

public class BarCl {
    public BarCl() {
    }
}
</code>```

But in runtime after injecting this classes i get loaded.getPackage()==null
How i can associate package-info with generated class?

P.S. In real task i need to generate package-info with JAXB annotation @XmlSchema, that specify xml namespace. Without it, classes have naming collisions

答: Packages are class loader respobsibility and not defined by a package-info class. You can define them using the loader DSL.

Body:
I create package-info of package foo.bar and class foo.bar.BarCl in next code

public static void main(String[] args) throws ClassNotFoundException, IOException {
        DynamicType.Unloaded<?> make = new ByteBuddy().makePackage("foo.bar").make();
        DynamicType.Loaded<Object> load = new ByteBuddy()
                .subclass(Object.class)
                .name("foo.bar.BarCl")
                .make()
                .include(make)
                .load(Main2.class.getClassLoader(), ClassLoadingStrategy.Default.INJECTION);
        load.saveIn(new File("folder"));
        Class<?> loaded = load.getLoaded();
        System.out.println(loaded.getPackage());
    }

Class and package info correctly writing in folder:

package foo.bar;

interface $$package-info /* Real name is 'package-info' */ {
}

package foo.bar;

public class BarCl {
    public BarCl() {
    }
}

But in runtime after injecting this classes i get loaded.getPackage()==null
How i can associate package-info with generated class?

P.S. In real task i need to generate package-info with JAXB annotation @XmlSchema, that specify xml namespace. Without it, classes have naming collisions


问:
How to remove all items of an array except first/last n elements in Swift
I had this question and saw that on stack overflow there isn't any information. So wanted to ask and answer in case anyone else has the same question. I found the answer from this medium post https://medium.com/@marcosantadev/arrayslice-in-swift-4e18522ab4e4#convert_slice_array</p>

答:
basically array.dropFirst(n) lets you create an ArraySlice with all elements but the first n elements. But in Swift we cannot assign an ArraySlice to be an array. Therefore, we need to use Array() to convert it into an array and reassign it to the original array

```<code>nodes = Array(nodes.dropFirst(n))
</code>```

This line allows you to get an array that doesn't have the first n elements of iteself

Body:
basically array.dropFirst(n) lets you create an ArraySlice with all elements but the first n elements. But in Swift we cannot assign an ArraySlice to be an array. Therefore, we need to use Array() to convert it into an array and reassign it to the original array

nodes = Array(nodes.dropFirst(n))

This line allows you to get an array that doesn't have the first n elements of iteself


问:
Get substring from twitter source in R
I have a dataframe in which one column is the twitter source, however, right now it looks messy. To clean it I would like to extract only: Twitter for iPhone, Twitter for Android, etc.

So I want to extract all text between ">" and "<"

Thank you

答: You can use the strsplit function and pass it the "<" symbol</p>

Title: Get substring from twitter source in R


问:
Combobox change value of other combobox
I have two comboboxes on an form. Each has the values Yes and No. What I want is when one is changed the other get the opposite (if the first is Yes the other is No).I need to do it with Javascript. I saw this question How to change "selected" value in combobox using JavaScript? but it is applied to only one combobox.

How can I do this?

LE:I need this example to be make with comboboxes. I can not use radio buttons

答:
I created a simple jsFiddle Demo. This is not perfect, just illustrates the idea.

HTML:

```<code><select id="first">
    <option value="0" selected>No</option>
    <option value="1">Yes</option>
</select>

<select id="second">
    <option value="0">No</option>
    <option value="1" selected>Yes</option>
</select>
</code>```

Javascript:

```<code>//find the selects in the DOM
var first = document.getElementById('first');
var second = document.getElementById('second');

//this is the handler function we will run when change event occurs
var handler = function () {
    //inside the handler, "this" should be the select
    //whose change event we are currently handling

    //get the current value and invert it (0 -> 1, 1 -> 0)
    var invertedValue = this.value === '0' ? 1 : 0;

    //check which select's change we are currently handling
    //and set the inverted value as the other select's value
    if (this === first) {
        second.value = invertedValue;
    } else {
        first.value = invertedValue;
    }

};

//add handler function to run on change event on both selects
first.addEventListener('change', handler, false);
second.addEventListener('change', handler, false);
</code>```

Title: Combobox change value of other combobox

Body:
I created a simple jsFiddle Demo. This is not perfect, just illustrates the idea.

HTML:

<select id="first">
    <option value="0" selected>No</option>
    <option value="1">Yes</option>
</select>

<select id="second">
    <option value="0">No</option>
    <option value="1" selected>Yes</option>
</select>

Javascript:

//find the selects in the DOM
var first = document.getElementById('first');
var second = document.getElementById('second');

//this is the handler function we will run when change event occurs
var handler = function () {
    //inside the handler, "this" should be the select
    //whose change event we are currently handling

    //get the current value and invert it (0 -> 1, 1 -> 0)
    var invertedValue = this.value === '0' ? 1 : 0;

    //check which select's change we are currently handling
    //and set the inverted value as the other select's value
    if (this === first) {
        second.value = invertedValue;
    } else {
        first.value = invertedValue;
    }

};

//add handler function to run on change event on both selects
first.addEventListener('change', handler, false);
second.addEventListener('change', handler, false);


问:
How to reduce a string containing the same substring repeated n times to a single instace of the substring
I have strings like 'ageage' or 'feetfeetfeet' or 'cmcmcmcmcm' and would like to reduce these to 'age', 'feet', and 'cm' respectively.

This is an intermediate step in normalization for matching across different data sources of certain classes of data fields that originally also contained numbers. The numeric parts have been removed into a separate string. All the unicode letters have been transliterated to  lowercase ASCII letters with:

public static function transliterate(string $value)
{
    $transliterator = Transliterator::createFromRules(
        ':: Any-Latin; :: Latin-ASCII; :: NFD; :: [:Nonspacing Mark:] Remove; :: Lower(); :: NFC;',
        Transliterator::FORWARD
    );
    return $transliterator->transliterate($value);
}
```

Also note that pluralization doesn't matter because while the examples I've provided are in English the project is normalizing mainly Turkish strings where such words would always be singular.

I expect this can be done with regex. Though I'm not entirely sure how

答:
I assume non regex is ok.

This method loops through half the string and tries to find a substring that if used in a str_replace returns nothing.

If we find that then the know it's a repeating word.

```<code>$str = 'feetfeetfeet';
$return = $str; // return full str if it fails

$len = strlen($str);

for($i = 1; $i < $len/2; $i++){
    $sub = substr($str, 0, $i);
    if(str_replace($sub, "", $str) == ""){
        $return = $sub;
        break;
    }
}

echo $return; //feet
</code>```

Body:
I have strings like 'ageage' or 'feetfeetfeet' or 'cmcmcmcmcm' and would like to reduce these to 'age', 'feet', and 'cm' respectively.

This is an intermediate step in normalization for matching across different data sources of certain classes of data fields that originally also contained numbers. The numeric parts have been removed into a separate string. All the unicode letters have been transliterated to  lowercase ASCII letters with:

public static function transliterate(string $value)
{
    $transliterator = Transliterator::createFromRules(
        ':: Any-Latin; :: Latin-ASCII; :: NFD; :: [:Nonspacing Mark:] Remove; :: Lower(); :: NFC;',
        Transliterator::FORWARD
    );
    return $transliterator->transliterate($value);
}

Also note that pluralization doesn't matter because while the examples I've provided are in English the project is normalizing mainly Turkish strings where such words would always be singular.

I expect this can be done with regex. Though I'm not entirely sure how

Body:
I assume non regex is ok.

This method loops through half the string and tries to find a substring that if used in a str_replace returns nothing.

If we find that then the know it's a repeating word.

$str = 'feetfeetfeet';
$return = $str; // return full str if it fails

$len = strlen($str);

for($i = 1; $i < $len/2; $i++){
    $sub = substr($str, 0, $i);
    if(str_replace($sub, "", $str) == ""){
        $return = $sub;
        break;
    }
}

echo $return; //feet


问:
Merging Data into a long data frame
I am consolidating data to put it into a new data base and I am having some issues with replacing the old columns with the new Foreign Key (FK) variables. I am consolidating all my data into a long format and then cast it again to create the new table structure of the new data model. Due to some name duplicates for generic variables like 'total' and merging some old names into new ones, direct merging does not always work because the names would not match. There are some work arounds that I can use and maybe there are some other conceptual improvements to fix my issues. However, I am generally courious if there is a way to merge and replace a FK into a long data table, like it works for a wide table.

Searching for threads with "merging" or "long" always yields other melting problems, thats why I am asking myself.

I tried creating a generic example using 'mtcars'

```<code>library(data.table)
dt<-data.table(mtcars)
#Create Id to melt the data
dt[,id:=1:.N]
dt_long<-melt(dt, id.vars="id")
#Create a unique sub table for 4 variables of mtcars with a new sub_id
merge_cols<-c("vs","am","gear","carb")
dt_sub<-dt[,..merge_cols]
dt_sub<-unique(dt_sub)
dt_sub[,id_sub:=1:.N]
# Easy to merge with orginal table and delete old columns
dt<-merge(dt,dt_sub, by=merge_cols )
set(dt, , merge_cols, NULL)
#Any way to do this with the long data frame?
setorder(dt_long, id)
dt_long[variable %in% merge_cols,]
dt_sub[vs==0 & am==1 & gear ==4 & carb==4,]
</code>```

For instance the first 4 rows should be replaced by one row with variable "sub_id" and value "4". Just if I were to melt the merged 'dt' from above using the wide original dt. So my final result should look like I melted the wide table after it has been merged with the sub table, but for each four rows of the 'merge_cols' we have one row with 'sub_id'

```<code>dt_final<-melt(dt,  id.vars="id"  )
dt_final[variable=="id_sub"]
</code>```

答:
If I understand correctly (but may be I'm missing the point), the question is how to merge or subset in long format. Perhaps, the OP is looking for something along the following lines.

The first step is to understand that subsetting is equivalent (to some extent) to merging / joining with a lookup table. So,

```<code>library(data.table) # just to highlight that data.table syntax is used here
dt_sub[vs == 0 & am == 1 & gear == 4 & carb == 4, ]
</code>```

returns the same result as

```<code>lut_wide <- data.table(vs = 0, am = 1, gear = 4, carb = 4)
dt_sub[lut_wide, on = names(lut_wide)]
</code>```

```<code>   vs am gear carb id_sub
1:  0  1    4    4      1
</code>```

To do the same in long format, also the lookup table needs to be reshaped:

```<code>lut_long <- melt(lut_wide, measure.vars = names(lut_wide))
</code>```

```<code>   variable value
1:       vs     0
2:       am     1
3:     gear     4
4:     carb     4
</code>```

Alternatively, fread() can be used to create a lookup table in long format from scratch:

```<code>lut_long <- fread(
"variable, value
vs, 0
am, 1
gear, 4
carb, 4")
</code>```

Now, we need to find those ids which fullfil all 4 conditions:

```<code>idx <- dt_long[lut_long, on = .(variable, value)][
  , which(.N == nrow(lut_long)), by = id][, .(id)]
idx
</code>```

```<code>   id
1:  1
2:  2
</code>```

Alternatively, we can write

```<code>idx <- dt_long[lut_long, on = .(variable, value)][
  , .N, by = id][N == nrow(lut_long), .(id)]
</code>```

Finally, idx is used to subset dt_long (by joining):

```<code>dt_long[variable %in% merge_cols, ][idx, on = "id"]
</code>```

```<code>   id variable value
1:  1       vs     0
2:  1       am     1
3:  1     gear     4
4:  1     carb     4
5:  2       vs     0
6:  2       am     1
7:  2     gear     4
8:  2     carb     4
</code>```

Here, only the variables defined in merge_cols are considered.

Apparently, the result contains a duplicate. This can be removed by picking only the first row of idx:

```<code>dt_long[variable %in% merge_cols, ][first(idx), on = "id"]
</code>```

```<code>   id variable value
1:  1       vs     0
2:  1       am     1
3:  1     gear     4
4:  1     carb     4
</code>```

Title: Merging Data into a long data frame

Body:
I am consolidating data to put it into a new data base and I am having some issues with replacing the old columns with the new Foreign Key (FK) variables. I am consolidating all my data into a long format and then cast it again to create the new table structure of the new data model. Due to some name duplicates for generic variables like 'total' and merging some old names into new ones, direct merging does not always work because the names would not match. There are some work arounds that I can use and maybe there are some other conceptual improvements to fix my issues. However, I am generally courious if there is a way to merge and replace a FK into a long data table, like it works for a wide table.

Searching for threads with "merging" or "long" always yields other melting problems, thats why I am asking myself.

I tried creating a generic example using 'mtcars'

library(data.table)
dt<-data.table(mtcars)
#Create Id to melt the data
dt[,id:=1:.N]
dt_long<-melt(dt, id.vars="id")
#Create a unique sub table for 4 variables of mtcars with a new sub_id
merge_cols<-c("vs","am","gear","carb")
dt_sub<-dt[,..merge_cols]
dt_sub<-unique(dt_sub)
dt_sub[,id_sub:=1:.N]
# Easy to merge with orginal table and delete old columns
dt<-merge(dt,dt_sub, by=merge_cols )
set(dt, , merge_cols, NULL)
#Any way to do this with the long data frame?
setorder(dt_long, id)
dt_long[variable %in% merge_cols,]
dt_sub[vs==0 & am==1 & gear ==4 & carb==4,]

For instance the first 4 rows should be replaced by one row with variable "sub_id" and value "4". Just if I were to melt the merged 'dt' from above using the wide original dt. So my final result should look like I melted the wide table after it has been merged with the sub table, but for each four rows of the 'merge_cols' we have one row with 'sub_id'

dt_final<-melt(dt,  id.vars="id"  )
dt_final[variable=="id_sub"]

Body:
If I understand correctly (but may be I'm missing the point), the question is how to merge or subset in long format. Perhaps, the OP is looking for something along the following lines.

The first step is to understand that subsetting is equivalent (to some extent) to merging / joining with a lookup table. So,

library(data.table) # just to highlight that data.table syntax is used here
dt_sub[vs == 0 & am == 1 & gear == 4 & carb == 4, ]

returns the same result as

lut_wide <- data.table(vs = 0, am = 1, gear = 4, carb = 4)
dt_sub[lut_wide, on = names(lut_wide)]

   vs am gear carb id_sub
1:  0  1    4    4      1

To do the same in long format, also the lookup table needs to be reshaped:

lut_long <- melt(lut_wide, measure.vars = names(lut_wide))

   variable value
1:       vs     0
2:       am     1
3:     gear     4
4:     carb     4

Alternatively, fread() can be used to create a lookup table in long format from scratch:

lut_long <- fread(
"variable, value
vs, 0
am, 1
gear, 4
carb, 4")

Now, we need to find those ids which fullfil all 4 conditions:

idx <- dt_long[lut_long, on = .(variable, value)][
  , which(.N == nrow(lut_long)), by = id][, .(id)]
idx

   id
1:  1
2:  2

Alternatively, we can write

idx <- dt_long[lut_long, on = .(variable, value)][
  , .N, by = id][N == nrow(lut_long), .(id)]

Finally, idx is used to subset dt_long (by joining):

dt_long[variable %in% merge_cols, ][idx, on = "id"]

   id variable value
1:  1       vs     0
2:  1       am     1
3:  1     gear     4
4:  1     carb     4
5:  2       vs     0
6:  2       am     1
7:  2     gear     4
8:  2     carb     4

Here, only the variables defined in merge_cols are considered.

Apparently, the result contains a duplicate. This can be removed by picking only the first row of idx:

dt_long[variable %in% merge_cols, ][first(idx), on = "id"]

   id variable value
1:  1       vs     0
2:  1       am     1
3:  1     gear     4
4:  1     carb     4


问:
Map-box Android : Icon Overlapping and SymbolManager OnClickListener
I have got a strange issue when using the symbol manager. When I allow icons overlapping, the click listener of the symbol manager is triggered multiple times. This doesn't occur when I don't set Allow Icon Overlap to true. But I need to show all of the symbols on the map, and each one must open a dialog on click.

Is it a known issue or am I doing something wrong ?

Thanks for your help !

答:
```<code>I too had the same problem. I used the symbolManager.addClickListener within the forloop which triggered the click multiple times.
I resolved it by using the symbolManager.addClickListener inside onMapReady method.

public void onMapReady(@NonNull MapboxMap mapboxMap) {
                    map = mapboxMap;
                    map.setStyle(Style.MAPBOX_STREETS, new Style.OnStyleLoaded() {
                        @Override
                        public void onStyleLoaded(@NonNull Style style) {
                            symbolManager = new SymbolManager(mapView, mapboxMap, style);
//                            symbolManager.setIconAllowOverlap(true);
                            symbolManager.addClickListener(new OnSymbolClickListener() {
                                @Override
                                public void onAnnotationClick(Symbol symbol) {

                                }
                            });
}
                    });
                }
</code>```


问:
Loop over array and create `n` other arrays based on item value in array
Id like to loop over an array of objects which is of unknown length and (some) unknown content and create a new set of enumerated arrays.

I know that the array has a consistent set of key:value pairs, which I'd like to use a reference to chunk out the array.

Here's the example array:

```<code>[{something:test,value:10},{something:example,value:20},{something:test,value:30}]
</code>```

The function should recognize the key 'something' and create a number of arrays based on the variations of the corresponding value, so for example, in this case 2 arrays would result with an object form:

```<code>{
    test: [{something:test,value:10},{something:test,value:30},
    example: [{something:example,value:20}]
}
</code>```

In other words I need to chunk an array based on some items value in the array, rather than size / length.

I have considered / tried using index on values etc to get size parameter, but this seems a like a huge undertaking, and I'm sure there's a faster solution.

Lodash etc do not seem to have something like this in their library.

答:
Object.Keys will allow you to grab all the keys out of each object.
Since some of the content is unknown, then its impossible to know whether all objects have some linking property, like the something prop in your example.

I suppose I'd need another example, with the unknown / variant content. Because it seems like you could loop through the content detect your prop of interest. If you don't know the prop ahead of time and are doing it based on the most common prop, then the Object.keys functions should help you out. I think it would be something like this.

```<code>function enumArrays(arrayObjects){
    let enumArrays = {}
    let keyCounts = {}

    // look at each object and get a count of the keys
    for (let obj of arrayObjects){
        const keys = Object.Keys(obj);
        for (let key of keys){
            if (keyCounts.hasOwnProperty(key)){
                keyCounts[key] += 1;
            } else {
                keyCounts[key] = 1;
            }
        }
    }

    //determine which key to use, there are plenty of ways to do this, but ill go with a basic approach
    let max = 0 // assuming positive integer counts only
    let selectedKey = "";
    for (let keyCount of Object.keys(keyCounts)){
        if (keyCounts[keyCount] > max){
            max = keyCounts[keyCount];
            selectedKey = keyCount
        }
    }

    //we now have our most common key in selected key! We can chunk the original array of Objects by that key
    enumArrays['null'] = [] // its possible that some objects will not have the selected key, so we'll store those objects in a null bucket
    for (let obj of arrayObjects){
        if (obj[selectedKey]){
            //check if prop type has been added yet
            let propType = obj[selectedKey];
            if (!enumArrays.hasOwnProperty(propType)){
                //add an empty array to that propType
                enumArrays[propType] = []
            }
            enumArrays[propType].push(obj)
        } else {
            enumArrays['null'].push(obj)
        }
    }

    return enumArrays
}
</code>```

Body:
Id like to loop over an array of objects which is of unknown length and (some) unknown content and create a new set of enumerated arrays.

I know that the array has a consistent set of key:value pairs, which I'd like to use a reference to chunk out the array.

Here's the example array:

[{something:test,value:10},{something:example,value:20},{something:test,value:30}]

The function should recognize the key 'something' and create a number of arrays based on the variations of the corresponding value, so for example, in this case 2 arrays would result with an object form:

{
    test: [{something:test,value:10},{something:test,value:30},
    example: [{something:example,value:20}]
}

In other words I need to chunk an array based on some items value in the array, rather than size / length.

I have considered / tried using index on values etc to get size parameter, but this seems a like a huge undertaking, and I'm sure there's a faster solution.

Lodash etc do not seem to have something like this in their library.

Body:
Object.Keys will allow you to grab all the keys out of each object.
Since some of the content is unknown, then its impossible to know whether all objects have some linking property, like the something prop in your example.

I suppose I'd need another example, with the unknown / variant content. Because it seems like you could loop through the content detect your prop of interest. If you don't know the prop ahead of time and are doing it based on the most common prop, then the Object.keys functions should help you out. I think it would be something like this.

function enumArrays(arrayObjects){
    let enumArrays = {}
    let keyCounts = {}

    // look at each object and get a count of the keys
    for (let obj of arrayObjects){
        const keys = Object.Keys(obj);
        for (let key of keys){
            if (keyCounts.hasOwnProperty(key)){
                keyCounts[key] += 1;
            } else {
                keyCounts[key] = 1;
            }
        }
    }

    //determine which key to use, there are plenty of ways to do this, but ill go with a basic approach
    let max = 0 // assuming positive integer counts only
    let selectedKey = "";
    for (let keyCount of Object.keys(keyCounts)){
        if (keyCounts[keyCount] > max){
            max = keyCounts[keyCount];
            selectedKey = keyCount
        }
    }

    //we now have our most common key in selected key! We can chunk the original array of Objects by that key
    enumArrays['null'] = [] // its possible that some objects will not have the selected key, so we'll store those objects in a null bucket
    for (let obj of arrayObjects){
        if (obj[selectedKey]){
            //check if prop type has been added yet
            let propType = obj[selectedKey];
            if (!enumArrays.hasOwnProperty(propType)){
                //add an empty array to that propType
                enumArrays[propType] = []
            }
            enumArrays[propType].push(obj)
        } else {
            enumArrays['null'].push(obj)
        }
    }

    return enumArrays
}


问:
MQL4 How to check if last open position in profit
I want to create "Expert advisor" which scaling in\pyramiding\snowballing into trend,

(Another winning position is openning after first one already in breakeven)

Im stuck with function which checks if previous LONG\SHORT open position is already profitable

Seems like my current function always return 1,

```<code>      extern double ProfitForOpenAnother = 30;

      double IsLastLongProfitable(string sy="", int op=OP_BUY) {
      int LastLongProfitable = 0;
      datetime o;
      double   l=-1;
      int      i, k=OrdersTotal();

      if (sy=="0") sy=Symbol();
      for (i=0; i<k; i++) {
        if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) {
          if (OrderSymbol()==sy || sy=="") {
            if (OrderType()==OP_BUY) {
              if (op<0 || OrderType()==op) {
                if (OrderMagicNumber()==Magic) {
                  if (o<OrderOpenTime()) {
                    o=OrderOpenTime();
                    l=OrderProfit();
                    if(l>ProfitForOpenAnother)
                    {
                      LastLongProfitable=1;
                    }
                  }
                }
              }
            }
          }
        }
      }
      return(LastLongProfitable);
    } ```

```

答:
```<code>double profit_buy=0,profit_sell=0;
for(int i=OrdersTotal()-1; i>=0; i--)
  {
   if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==true)
     {
      datetime time_order=OrderOpenTime();
      double profit_order=OrderProfit()-OrderCommission()+OrderSwap();
      if(OrderType()==OP_BUY && time_buy<time_order)
        {
         time_buy=time_order;
         profit_buy=profit_order;
        }
      if(OrderType()==OP_SELL && time_sell<time_order)
        {
         time_sell=time_order;
         profit_sell=profit_order;
        }
     }
  }```
</code>```

Body:
I want to create "Expert advisor" which scaling in\pyramiding\snowballing into trend,

(Another winning position is openning after first one already in breakeven)

Im stuck with function which checks if previous LONG\SHORT open position is already profitable

Seems like my current function always return 1,

      extern double ProfitForOpenAnother = 30;

      double IsLastLongProfitable(string sy="", int op=OP_BUY) {
      int LastLongProfitable = 0;
      datetime o;
      double   l=-1;
      int      i, k=OrdersTotal();

      if (sy=="0") sy=Symbol();
      for (i=0; i<k; i++) {
        if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) {
          if (OrderSymbol()==sy || sy=="") {
            if (OrderType()==OP_BUY) {
              if (op<0 || OrderType()==op) {
                if (OrderMagicNumber()==Magic) {
                  if (o<OrderOpenTime()) {
                    o=OrderOpenTime();
                    l=OrderProfit();
                    if(l>ProfitForOpenAnother)
                    {
                      LastLongProfitable=1;
                    }
                  }
                }
              }
            }
          }
        }
      }
      return(LastLongProfitable);
    } ```


问:
how i can resolve the error Cannot read property 'prenom' of undefined?
I'm developing a user registration page and I'm using angular on the front side and spring boot side back, the problem I get is this error when starting my application:

this is my user class :

```<code>export class User {

   constructor (

    IDENTIFIANT: Number,
    EMPLOI: Number,
    ENTITE: Number,
    LOGIN: string,
    MOTDEPASSE: string,
    NOM: string,
    PRENOM: string,
    STATUT: string,
    DATEEFFET: Date,
    DATEFIN: Date,
    CREELE: Date,
    CREEPAR: Date,
    MOTIFDEDESACTIVATION: string,
    ANNULEPAR: number,
    ANNULELE: Date,
    EMAIL: string,
    CONFIRMATIONMOTDEPASSE: string
   ){}
}
</code>```

and this is my component.html :

```<code><div class="inscription">

    <!-- Default form register -->
    <form class="text-center border border-light p-5">

        <p class="h4 mb-4">Sign up</p>

        <div class="form-row mb-4">
            <div class="col">
                <!-- First name -->
                <input type="text" id="prenom" class="form-control" [(ngModel)]="user.prenom" placeholder="Votre prenom">
            </div>
            <div class="col">
                <!-- Last name -->
                <input type="text" id="nom" class="form-control" [(ngModel)]="user.nom" placeholder="Votre nom">
            </div>
        </div>

        <!-- E-mail -->
        <input type="email" id="email" class="form-control mb-4" [(ngModel)]="user.email" placeholder="Votre email">

        <!-- Login -->
        <input type="text" id="login" class="form-control mb-4" [(ngModel)]="user.login" placeholder="Votre login">

        <!-- Password -->
        <input type="password" id="password" class="form-control" [(ngModel)]="user.motdepasse" placeholder="Votre mot de passe"
            aria-describedby="defaultRegisterFormPasswordHelpBlock">

        <!-- Confirmation mot de passe -->
        <input type="password" id="password-confirmation" class="form-control"
            placeholder="Confirmez votre mot de passe" [(ngModel)]="user.confirmationmotdepasse" aria-describedby="defaultRegisterFormPasswordHelpBlock">

        <!-- Entite -->

            <select class="form-control" id="entite" [(ngModel)]="user.entite">
                <option value="" selected disabled>Votre entité</option>
                <option>1</option>
                <option>2</option>
                <option>3</option>
                <option>4</option>
                <option>5</option>
            </select>

        <!-- Emploi -->

        <select class="form-control" id="emploi" [(ngModel)]="user.emploi">
            <option value="" selected disabled >Votre emploi</option>
            <ul class="list-unstyled navbar-list">

                <li *ngFor="let tempAllEmploi of allEmploi">

                    <option>{{ tempAllEmploi.NOM}}</option>
                </li>
            </ul>

        </select>

        <!-- Sign up button -->
        <button mdbBtn color="info" block="true" class="my-4" type="submit" id="btn-inscription" class="btn-primary btn-lg" (click)="inscriptionts()">Valider</button>

    </form>
    <!-- Default form register -->

</div>
</code>```

focus more on this code :

```<code><input type="text" id="prenom" class="form-control" [(ngModel)]="user.prenom" placeholder="Votre prenom">
</code>```

you can see here that I created the user class which has a "first name" variable and that I used the ngModel with user.prenom in my html code, so I don't see where the error can come from  :/

this is my component.ts :

```<code>import { Component, OnInit } from '@angular/core';
import { User } from 'src/app/model/user';
import { RestapiService } from 'src/app/restapi.service';
import { Emploi } from 'src/app/model/emploi';

@Component({
  selector: 'app-inscription',
  templateUrl: './inscription.component.html',
  styleUrls: ['./inscription.component.css']
})
export class InscriptionComponent implements OnInit {

  allEmploi: Emploi[];
  user: any;
  //user: Users= new Users(0,0,0,"","","","","",new Date("dd-mm-yyyy"),new Date("dd-mm-yyyy"),new Date("dd-mm-yyyy"),new Date("dd-mm-yyyy"),"",0,new Date("dd-mm-yyyy"),"","");

  constructor(private Userservice: RestapiService) { }

  ngOnInit(): void {

    this.getAllEmploi();
  }

  public getAllEmploi(){

    this.Userservice.getEmploi().subscribe(

      data => {
        this.allEmploi=data;
      }
    );
  }

  public inscriptionts(){

    let resp=this.Userservice.inscription(this.user);
    resp.subscribe((data)=> this.user=data);
  }
}
</code>```

and this is my service :

```<code>import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Emploi } from './model/emploi';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class RestapiService {

  url_getAllEmploi="http://localhost:8484/emploi/getall";

  constructor(private http:HttpClient) { }

  public inscription(user) {

    return this.http.post("http://localhost:8484/addUser", user);
  }

  public getEmploi(): Observable<Emploi[]> {

    return this.http.get<Emploi[]>(this.url_getAllEmploi);
  }

  public login(username:string, password:string) {
    const headers = new HttpHeaders({Authorization: 'Basic ' + btoa(username+":"+password)})
    return this.http.get("http://localhost:8484/", {headers, responseType:'text' as 'json'});
  }

  public getUsers() {
    let username="hr";
    let password="hr";
    const headers = new HttpHeaders({Authorization: 'Basic ' + btoa(username+":"+password)});
    return this.http.get("http://localhost:8484/getUsers", {headers});
  }
}
</code>```

can someone help me please ?

答:
The object properties are case sensitive. So they should be accessed like user.PRENOM, user.NOM and so on.

Furthermore, user is an asynchronous variable and might not be initialized by the time you access it in the template. You could wrap the form in an container with *ngIf check

  ...

```

Body:
I'm developing a user registration page and I'm using angular on the front side and spring boot side back, the problem I get is this error when starting my application:

this is my user class :

export class User {

   constructor (

    IDENTIFIANT: Number,
    EMPLOI: Number,
    ENTITE: Number,
    LOGIN: string,
    MOTDEPASSE: string,
    NOM: string,
    PRENOM: string,
    STATUT: string,
    DATEEFFET: Date,
    DATEFIN: Date,
    CREELE: Date,
    CREEPAR: Date,
    MOTIFDEDESACTIVATION: string,
    ANNULEPAR: number,
    ANNULELE: Date,
    EMAIL: string,
    CONFIRMATIONMOTDEPASSE: string
   ){}
}

and this is my component.html :

    <form class="text-center border border-light p-5">

Sign up

                <input type="text" id="prenom" class="form-control" [(ngModel)]="user.prenom" placeholder="Votre prenom">

                <input type="text" id="nom" class="form-control" [(ngModel)]="user.nom" placeholder="Votre nom">

        <input type="email" id="email" class="form-control mb-4" [(ngModel)]="user.email" placeholder="Votre email">

        <input type="text" id="login" class="form-control mb-4" [(ngModel)]="user.login" placeholder="Votre login">

        <input type="password" id="password" class="form-control" [(ngModel)]="user.motdepasse" placeholder="Votre mot de passe"
            aria-describedby="defaultRegisterFormPasswordHelpBlock">

        <input type="password" id="password-confirmation" class="form-control"
            placeholder="Confirmez votre mot de passe" [(ngModel)]="user.confirmationmotdepasse" aria-describedby="defaultRegisterFormPasswordHelpBlock">

            <select class="form-control" id="entite" [(ngModel)]="user.entite">
                <option value="" selected disabled>Votre entité</option>
                <option>1</option>
                <option>2</option>
                <option>3</option>
                <option>4</option>
                <option>5</option>
            </select>

        <select class="form-control" id="emploi" [(ngModel)]="user.emploi">
            <option value="" selected disabled >Votre emploi</option>

                    <option>{{ tempAllEmploi.NOM}}</option>

        </select>

        <button mdbBtn color="info" block="true" class="my-4" type="submit" id="btn-inscription" class="btn-primary btn-lg" (click)="inscriptionts()">Valider</button>

    </form>

focus more on this code :

<input type="text" id="prenom" class="form-control" [(ngModel)]="user.prenom" placeholder="Votre prenom">

you can see here that I created the user class which has a "first name" variable and that I used the ngModel with user.prenom in my html code, so I don't see where the error can come from  :/

this is my component.ts :

import { Component, OnInit } from '@angular/core';
import { User } from 'src/app/model/user';
import { RestapiService } from 'src/app/restapi.service';
import { Emploi } from 'src/app/model/emploi';

@Component({
  selector: 'app-inscription',
  templateUrl: './inscription.component.html',
  styleUrls: ['./inscription.component.css']
})
export class InscriptionComponent implements OnInit {

  allEmploi: Emploi[];
  user: any;
  //user: Users= new Users(0,0,0,"","","","","",new Date("dd-mm-yyyy"),new Date("dd-mm-yyyy"),new Date("dd-mm-yyyy"),new Date("dd-mm-yyyy"),"",0,new Date("dd-mm-yyyy"),"","");

  constructor(private Userservice: RestapiService) { }

  ngOnInit(): void {

    this.getAllEmploi();
  }

  public getAllEmploi(){

    this.Userservice.getEmploi().subscribe(

      data => {
        this.allEmploi=data;
      }
    );
  }

  public inscriptionts(){

    let resp=this.Userservice.inscription(this.user);
    resp.subscribe((data)=> this.user=data);
  }
}

and this is my service :

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Emploi } from './model/emploi';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class RestapiService {

  url_getAllEmploi="http://localhost:8484/emploi/getall";

  constructor(private http:HttpClient) { }

  public inscription(user) {

    return this.http.post("http://localhost:8484/addUser", user);
  }

  public getEmploi(): Observable<Emploi[]> {

    return this.http.get<Emploi[]>(this.url_getAllEmploi);
  }

  public login(username:string, password:string) {
    const headers = new HttpHeaders({Authorization: 'Basic ' + btoa(username+":"+password)})
    return this.http.get("http://localhost:8484/", {headers, responseType:'text' as 'json'});
  }

  public getUsers() {
    let username="hr";
    let password="hr";
    const headers = new HttpHeaders({Authorization: 'Basic ' + btoa(username+":"+password)});
    return this.http.get("http://localhost:8484/getUsers", {headers});
  }
}

can someone help me please ?

Body:
The object properties are case sensitive. So they should be accessed like user.PRENOM, user.NOM and so on.

Furthermore, user is an asynchronous variable and might not be initialized by the time you access it in the template. You could wrap the form in an container with *ngIf check

<div *ngIf="user" class="inscription">
  ...
</div>


问:
Expandable dynamic nested list with objects array
Im struggling with expandable nested array list anyone keen to help me out

https://jsfiddle.net/AccordEuro06/2otnxb9c/3/

```<code>const webfolder = [{
    name: 'Webpage',
    type: 'folder',
    children: [{
            name: 'php',
            type: 'folder',
            children: [{
                    name: 'header.php',
                    type: 'file'
                },
                {
                    name: 'footer.php',
                    type: 'file'
                },
            ]
        },
        {
            name: 'css',
            type: 'folder',
            children: [{
                    name: 'images',
                    type: 'folder',
                    children: [{
                            name: 'logos',
                            type: 'folder',
                            children: [{
                                    name: 'Colored.svg',
                                    type: 'file'
                                },
                                {
                                    name: 'Monochrome.svg',
                                    type: 'file'
                                },
                            ]
                        },
                        {
                            name: 'gallery',
                            type: 'folder',
                            children: [{
                                    name: 'image1.jpg',
                                    type: 'file'
                                },
                                {
                                    name: 'image2.png',
                                    type: 'file'
                                },
                                {
                                    name: 'image3.gif',
                                    type: 'file'
                                },
                                {
                                    name: 'image4.jpeg',
                                    type: 'file'
                                },
                                {
                                    name: 'image5.jpg',
                                    type: 'file'
                                },
                            ]
                        },
                        {
                            name: 'about-us.jpg',
                            type: 'file'
                        },
                    ],
                },
                {
                    name: 'style.css',
                    type: 'file'
                },
            ]
        },
        {
            name: 'javascipt',
            type: 'folder',
            children: [{
                    name: 'script.js',
                    type: 'file'
                },
                {
                    name: 'script2.js',
                    type: 'file'
                },
                {
                    name: 'ajax.js',
                    type: 'file'
                },
                {
                    name: 'jquery.js',
                    type: 'file'
                },
            ]
        },
        {
            name: 'index.html',
            type: 'file'
        }
    ]
}];

function listHtml(children) {
    return '<ul>' + children.map(node =>
            '<li>' + node.name +
            (node.type === 'file' ? '' : listHtml(node.children)) +
            '</li>').join('\n') +
        '</ul>';
}

document.getElementById('expandableTree').innerHTML += listHtml(webfolder);
</code>```

I understand that hide/show on click should be done with css but i ran out of ideas how to add proper classes to branches and leafs

答:
You can use the HTML5  elements:

function listHtml(children) {
    return '
' + children.map(node =>
        `

            ${node.type === 'file'
                ? node.name
                : `
                     ${node.name}
                     ${listHtml(node.children)}
                   `
            }

`
    ).join('\n') + '
';
}

document.getElementById('expandableTree').innerHTML += listHtml(webfolder);
```

Try it on CodePen

Body:
Im struggling with expandable nested array list anyone keen to help me out

https://jsfiddle.net/AccordEuro06/2otnxb9c/3/

const webfolder = [{
    name: 'Webpage',
    type: 'folder',
    children: [{
            name: 'php',
            type: 'folder',
            children: [{
                    name: 'header.php',
                    type: 'file'
                },
                {
                    name: 'footer.php',
                    type: 'file'
                },
            ]
        },
        {
            name: 'css',
            type: 'folder',
            children: [{
                    name: 'images',
                    type: 'folder',
                    children: [{
                            name: 'logos',
                            type: 'folder',
                            children: [{
                                    name: 'Colored.svg',
                                    type: 'file'
                                },
                                {
                                    name: 'Monochrome.svg',
                                    type: 'file'
                                },
                            ]
                        },
                        {
                            name: 'gallery',
                            type: 'folder',
                            children: [{
                                    name: 'image1.jpg',
                                    type: 'file'
                                },
                                {
                                    name: 'image2.png',
                                    type: 'file'
                                },
                                {
                                    name: 'image3.gif',
                                    type: 'file'
                                },
                                {
                                    name: 'image4.jpeg',
                                    type: 'file'
                                },
                                {
                                    name: 'image5.jpg',
                                    type: 'file'
                                },
                            ]
                        },
                        {
                            name: 'about-us.jpg',
                            type: 'file'
                        },
                    ],
                },
                {
                    name: 'style.css',
                    type: 'file'
                },
            ]
        },
        {
            name: 'javascipt',
            type: 'folder',
            children: [{
                    name: 'script.js',
                    type: 'file'
                },
                {
                    name: 'script2.js',
                    type: 'file'
                },
                {
                    name: 'ajax.js',
                    type: 'file'
                },
                {
                    name: 'jquery.js',
                    type: 'file'
                },
            ]
        },
        {
            name: 'index.html',
            type: 'file'
        }
    ]
}];

function listHtml(children) {
    return '
' + children.map(node =>
            '
' + node.name +
            (node.type === 'file' ? '' : listHtml(node.children)) +
            '
').join('\n') +
        '
';
}

document.getElementById('expandableTree').innerHTML += listHtml(webfolder);

I understand that hide/show on click should be done with css but i ran out of ideas how to add proper classes to branches and leafs

Body:
You can use the HTML5 <details> elements:

function listHtml(children) {
    return '<ul>' + children.map(node =>
        `<li>
            ${node.type === 'file'
                ? node.name
                : `<details>
                     <summary>${node.name}</summary>
                     ${listHtml(node.children)}
                   </details>`
            }
        </li>`
    ).join('\n') + '</ul>';
}

document.getElementById('expandableTree').innerHTML += listHtml(webfolder);

Try it on CodePen


问:
Assigning values to 2D array of pointers in Arduino
I'm working on an arduino project and I've been struggling to find a way how to assign values to 2D array of pointers (if im correct).
I have this array char* numbers[3][4];
I want it to be 4 characters long - for 4 numbers (like a code). But please note that I cannot change the declaration, only change the number of strings.
I have tried assigning the values with strcpy:

```<code>strcpy(*numbers[0], "1234");
strcpy(*numbers[1], "5678");
strcpy(*numbers[2], "9012");
</code>```

After assigning the values, the array should be used as a parameter of a function
void render_numbers(char** numbers, const int index);
which basically prints the 4-digit code on Arduino Serial at the given index.
So I called the function:

```<code>render_numbers(*numbers, 2);
</code>```

My function:

```<code>void render_numbers(char** numbers, const int index){
 Serial.println(numbers[index]);
}
</code>```

So it passes the compiler, but in Serial it only prints unreadable characters (squares, question marks, etc.)

答:
to assign array of strings in c do the following:

```<code>const char* numbers[]={"1234","5678","9012"};
</code>```

to declare array of strings each has 4 chars:

```<code>char numbers[3][4];
</code>```

so
numbers[1] ==> char* // pointer to first char
numbers[1][2] ==> char // the char value

to Declare 2D array of pointers

```<code>const char* numbers[][] = {{"1234","5678"},{"1234","1111"}};
</code>```

NOTE: strcpy copys source string to destination including null term char so it require 5 chars to store 4.

```<code>char numbers[3][5];
strcpy(numbers[1],"1234");
Serial.println(numbers[1]);
</code>```

Body:
I'm working on an arduino project and I've been struggling to find a way how to assign values to 2D array of pointers (if im correct).
I have this array char* numbers[3][4];
I want it to be 4 characters long - for 4 numbers (like a code). But please note that I cannot change the declaration, only change the number of strings.
I have tried assigning the values with strcpy:

strcpy(*numbers[0], "1234");
strcpy(*numbers[1], "5678");
strcpy(*numbers[2], "9012");

After assigning the values, the array should be used as a parameter of a function
void render_numbers(char** numbers, const int index);
which basically prints the 4-digit code on Arduino Serial at the given index.
So I called the function:

render_numbers(*numbers, 2);

My function:

void render_numbers(char** numbers, const int index){
 Serial.println(numbers[index]);
}

So it passes the compiler, but in Serial it only prints unreadable characters (squares, question marks, etc.)

Body:
to assign array of strings in c do the following:

const char* numbers[]={"1234","5678","9012"};

to declare array of strings each has 4 chars:

char numbers[3][4];

so
numbers[1] ==> char* // pointer to first char
numbers[1][2] ==> char // the char value

to Declare 2D array of pointers

const char* numbers[][] = {{"1234","5678"},{"1234","1111"}};

NOTE: strcpy copys source string to destination including null term char so it require 5 chars to store 4.

char numbers[3][5];
strcpy(numbers[1],"1234");
Serial.println(numbers[1]);


问:
C++ Multithreading - algorithm alternative of merge sort with threads
I have written a merge sort algorithm that sort array with integer data.

Now I need to write another sorting algorithm again with multithread concepts -phthread, which again sorting array with integer data.

My task background:
I have 2 child processes which sorting(with different algorithms) one integer array and first completed task print result and parent kill another process. I had done everything just need to implement 2nd algorithm logic

Please tell me which algorithm I have to use and give me an example implementation

Thank you in advance

答:
One portable option is to use Intel Parallel STL. It is compatible with C++11 and implements parallel std::sort.

C++17 parallel algorithms in GNU C++ standard library and gcc-9 delegate to Intel Parallel STL.


问:
Cannot match region between Google App Engine & VPC Network
I am setting a private connection between my project's Google App Engine and Compute engine with a serverless VPC network. The region of the GAE is set in northamerica-northeast1 (which can't be changed as described in the documentation), so I am trying to set up the VPC connector to be in the same region, following this guide.

When creating a new serverless VPC connector, it looks like there is no region selection for northamerica-northeast1, as shown in the screenshot. Is there a way to set up the connector to this region already set by app engine? At this point the last thing I want to do is start an entirely new project just to re-setup app engine and other applications on GCP.

I have seen some responses in the past about getting whitelisted to be given access to specific requests such as this, but again, I do not know how to go about that process either, if that is my best option.

答: After getting in touch with a helpful Google support rep, this specific region is indeed not supported by VPC networks. My best (and really only) option was to set up a new project, with a new region and match my VPC network to the new region, and then migrate/copy any datasets and apps I was using from the old project to the new.  </p>