text:
Q: Executing spring cloud task based on event into messaging source (i.e. RabbitMQ, Kafka) I am new in Learning of Spring cloud Task and SCDF so asking this.
I wand to execute my SCT based on an event (say a message is posted into Rabbit MQ), so I am think it can be done in two ways:

*

*Create a source which polls message from RabbitMQ and sends the data to stream, now create a sink which reads data from stream and as soon as data comes to sink (from source stream) Task will be launched.
create steam producer --definition "rabbitproducer | streamconsumer (This is @TaskEnabled)"

Not sure if this is possible?

*Other way could be to use task launcher. Here task launcher will be configured with a stream and a listener will be polling message from rabbitMQ. so when a message is received then trigger will initiate the process and tasklauncher will launch the task. But here not sure how will i get the message data into my task? Do I have to add the data into TaskLaunchRequest?
create stream mystream --definition "rabbitmsgtrigger --uri:my task | joblauncher"

A: Launching a Task by an upstream event is already supported and there are few approaches to it - please review the reference guide (and the sample) for more details.

A: Here is the complete explanation about my question's answer. Here Sabby has helped me a lot for resolving my issue.
Problem: I was not able to trigger my task using tasklauncher/task-sink. In the log also I was not getting correct details and I even did not know how to set to set log level correctly.
Solution: With the help of Sabby and documentations provided on SCT site I could resolve this and have moved ahead in my POC work. Below are the detailed steps I did.

*

*Started my SCDF with postgresql database by referring to the property file and setting log level change as
--logging.level.org.springframework.cloud=DEBUG
--spring.config.location=file://scdf.properties

*Imported apps from bitly.
app import --uri [stream applications link][1]

*Registered task sink app
app register --name task-sink --type sink --uri file://tasksink-1.1.0.BUILD-SNAPSHOT.jar

*Created stream as:
stream create mytasklaunchertest --definition "triggertask --triggertask.uri=https://my-archiva/myproject-scdf-task1/0.0.1-SNAPSHOT/myproject-scdf-task1-0.0.1-20160916.143611-1.jar --trigger.fixed-delay=5 | task-sink"

*Deployed Stream:
stream deploy foo --properties "app.triggertask.spring.rabbitmq.host=host,app.triggertask.spring.rabbitmq.username=user,app.triggertask.spring.rabbitmq.password=pass,app.triggertask.spring.rabbitmq.port=5672,app.triggertask.spring.rabbitmq.virtual-host=xxx"


text:
Q: How do I change the color of my Dock on Mac I am digging deep into my Mac's files to try and find how to change the color of my mac's dock. I have been able to change little things like the separator, indicator light, trash can, finder icon, etc. But I cannot find the file where the color of the actual Dock is.
I used this code to immediately go to the Dock folder
/System/Library/CoreServices/Dock.app/Contents/Resources
If you want a picture please ask and I'll edit a good one so you get the idea.

A: As far as I know, there's no image that you can change to change the background of the Dock. However, you can give the image to DockMod which will let you change the background.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Erro ao inserir dados no JPA import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
// pode usar para alterar o nome da tabela la no banco
//@Table(name = "")
public class Usuario {

    @Id
    @GeneratedValue
    private Long id;
    @Column(name= "login_usu")
    private String login;
    private String senha;

    public void mostrar() {
        System.out.printf("Id: %-5d Login: %-30s Senha: %-20s \n", id, login, senha);
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getLogin() {
        return login;
    }

    public void setLogin(String login) {
        this.login = login;
    }

    public String getSenha() {
        return senha;
    }

    public void setSenha(String senha) {
        this.senha = senha;
    }

}

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

public class ConnectionFactory {

    private static EntityManagerFactory emf = Persistence.createEntityManagerFactory("aula09");
    public static EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

}

import javax.persistence.EntityManager;

public class Principal {

    public static void main(String[] args) {

        Usuario u = new Usuario();
        u.setLogin("aaaaaaa@gmail.com");
        u.setSenha("senha123");

        EntityManager em = ConnectionFactory.getEntityManager();
        em.getTransaction().begin();
        em.persist(u);
        em.getTransaction();
        em.close();

    }
}

Quando mando rodar, tudo é criado porém não são inseridas as informações no banco de dados.

A: Partindo do princípio que as suas configurações no persistence.xml estão corretas, faça o seguinte:

*

*"Anote" seu atributo senha com @Column(name="NOME_DA_COLUNA")

*Na linha em seguida do método persist(u), chame o método commit() com: em.getTransaction().commit();
No final ficará assim (resumidamente):
@Entity
public class Usuario {

    @Id
    @GeneratedValue
    private Long id;

    @Column(name= "login_usu")
    private String login;

    @Column(name="NOME_DA_COLUNA")
    private String senha;

    //getters e setters

}

public class Principal {

    public static void main(String[] args) {

        Usuario u = new Usuario();
        u.setLogin("aaaaaaa@gmail.com");
        u.setSenha("senha123");

        EntityManager em = ConnectionFactory.getEntityManager();
        em.getTransaction().begin();
        em.persist(u);
        em.getTransaction().commit();
        em.close();
    }
}


text:
Q: how to add price discount percentage by a category in zen cart? I know that there is an option for the special price for a specific product But I want to set the discount price percentage for a category so that discount price will be applied automatically for each product in that specific category.
Is there any option in zen cart or any module for this?
Please help.

A: This is done in Zen Cart using "Salemaker".  See admin->catalog->SaleMaker.


text:
Q: upgrade to newer version manage categories not showing in admin menu upgrading to newer version now we do not have the manage categories in the menu I tried hard to find where I should insert or change anything for example adminhtml.xml or config.xml
I thought maybe some modules made this to happen but I disabled all modules and still I cannot see it in the menu the magento upgrade version is from 12 to 13
is there anyone experiencing the same?

A: I found the problem my self it was from :
app/code/core/Enterprise/catalogEvent/etc/adminhtml.xml

the menu structure is in XMl and we can find tag of <categories> by clicking the folder in eclipse and search in selected resources
the categories tag was disabled
something like this:
<categories>
<disabled>1<disabled>

so I just deleted it


text:
Q: Command That Doesn't Exist const Discord = require("discord.js");
module.exports.run = async (bot, message, args) => {
    if (!message.member.hasPermission("MANAGE_GUILD")) return message.reply("You don't have enough permission");

    let contSend = args.splice(1).join(' ');

    let chanSendFind = message.mentions.channels.first() ? message.mentions.channels.first().id : true;

    if (chanSendFind === true) return message.reply(`you need to specify a channel to send this message in. {prefix}send #<channel_name> <content>`);
    if (!contSend) return message.reply('I can\'t send an empty message.');

    bot.channels.get(chanSendFind).send(contSend)
        .then(() => message.react(`✅`))
        .catch(console.error);
}

(node:4) UnhandledPromiseRejectionWarning: TypeError: bot.channels.get is not a function

2020-08-03T09:46:19.027003+00:00 app[worker.1]:     at Object.module.exports.run (/app/commands/send.js:12:18)

2020-08-03T09:46:19.027012+00:00 app[worker.1]:     at Client.<anonymous> (/app/bot.js:39:21)

2020-08-03T09:46:19.027012+00:00 app[worker.1]:     at Client.emit (events.js:327:22)

2020-08-03T09:46:19.027013+00:00 app[worker.1]:     at MessageCreateAction.handle (/app/node_modules/discord.js/src/client/actions/MessageCreate.js:31:14)

2020-08-03T09:46:19.027014+00:00 app[worker.1]:     at Object.module.exports [as MESSAGE_CREATE] (/app/node_modules/discord.js/src/client/websocket/handlers/MESSAGE_CREATE.js:4:32)

2020-08-03T09:46:19.027015+00:00 app[worker.1]:     at WebSocketManager.handlePacket (/app/node_modules/discord.js/src/client/websocket/WebSocketManager.js:386:31)

2020-08-03T09:46:19.027015+00:00 app[worker.1]:     at WebSocketShard.onPacket (/app/node_modules/discord.js/src/client/websocket/WebSocketShard.js:436:22)

2020-08-03T09:46:19.027015+00:00 app[worker.1]:     at WebSocketShard.onMessage (/app/node_modules/discord.js/src/client/websocket/WebSocketShard.js:293:10)

2020-08-03T09:46:19.027017+00:00 app[worker.1]:     at WebSocket.onMessage (/app/node_modules/ws/lib/event-target.js:125:16)

2020-08-03T09:46:19.027017+00:00 app[worker.1]:     at WebSocket.emit (events.js:315:20)

2020-08-03T09:46:19.027107+00:00 app[worker.1]: (node:4) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)

2020-08-03T09:46:19.027180+00:00 app[worker.1]: (node:4) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

My bot is erroring the send command with this error I don't know why please help.

A: You need to add in cache:
bot.channels.cache.get(chanSendFind).send(contSend)
    .then(() => message.react(`✅`))
    .catch(console.error);

For more information, please read the Discord.js migration guide or check the Discord.js docs.


text:
Q: Induced map between polynomial rings. This might be a highly trivial question since I've just encountered category theory for a short time. Let $A$ be a commutative ring with identity and consider the polynomial ring $A[x]$ as the free $A$-algebra generated by a single element $x$. If we consider the construction of $A[x]$, then for any ring homomorphism $h: A\to B$ we have a naturally induced algebra homomorphism $h^*:A[x]\to B[x]$ defined by $$h^*(\sum\limits_{i=0}^n a_ix^i)=\sum\limits_{i=0}^n h(a_i)x^i.$$ Moreover if $h: A\to B$ preserves units,(that is, $h(u)$ is a unit in $B$ if $u$ is a unit in $A$) then $h^*$ also preserves units.
The above statements are not just useless information. For example consider the following proposition in elementary commutative ring theory;

Let $A$ be a commutative ring with identity. If the polynomial $f=\sum\limits_{i=0}^n a_ix^i$ is a unit in $A[x]$ then $a_0$ is a unit in $A$ and $a_1,...,a_n$ are nilpotent elements in $A$.

We utilize the claims from the first paragraph to reduce the proposition to integral domains. For every prime ideal $\mathfrak{p}\subset A$ consider the unit-preserving canonical homomorphism $h: A\to A/\mathfrak{p}$. Assume the proposition is true for integral domains $A/\mathfrak{p}$. Since the induced map $h^*: A[x]\to (A/\mathfrak{p})[x]$ preserves units, all coefficients for $h^*(f)$ except for the constant term are $0$ in $A/\mathfrak{p}$ and thus coefficients $a_1,...,a_n$ for $f$ belong to every prime ideal of $A$, which means that $a_1,...,a_n$ are all nilpotent elements. $a_0$ is easily seen to be a unit in $A$.
After all the above informations, I have two questions:

*

*Can be obtain the definition for the induced map $h^*$ without looking at the construction? Note that this works in general for any free object: There is a functor from a concrete category $(C, F)$ to the category of free objects generated by one(or any positive integer $n$?) element. Intuitively it is just defined by mapping an element in an object $O\in C$ to itself, but in the content of free objects, and maps a homomorphism in $(C, F)$ to its induced homomorphism between free objects.

*Note that for many propositions like above in commutative algebra we are able to obtain both "global" and "local" proofs.(For example the "local" version of proof to the above proposition is just listing inductively cancel out the elements.) Is there a general explanation for why this phenomenon happens? I think mostly it is because we can nicely obtain a "global" characterization for the set of special elements. For example the set of units in a commutative ring with identity is the complement of the union of all its maximal ideals, the nilradical is the intersection of all its prime ideals, etc.


text:
Q: Android strings.xml length Is there a way to get the number of strings in my strings.xml or to check if all strings are available in the selected language?

A: I don't think there is something in the public api. You can try with reflection since  from strings.xml  the R.string class is generated..
try this:
Field[] f = R.string.class.getDeclaredFields();

A: I don't think your approach is the best. If you are going to provide multiple languages, then probably the best way to store these in android is as alternative resources (see http://developer.android.com/guide/topics/resources/providing-resources.html and http://developer.android.com/guide/topics/resources/localization.html).
If you are going to do that, than you should be having translated resources of everything you need, so there isn't a question of partly translated content.
I think you'd be better off using a 3rd party crowd-sourced translation service and just prompt your users to that service for any languages that aren't yet ready to be included. Look at crowdin for an example of such a service. I know Friendcaster, for example, used this service to translate to multiple languages and it worked very well (e.g. https://crowdin.com/project/f-plus).


text:
Q: chrome.runtime.onConnect.addListener() doesn't work on initial chrome tab UPDATE
It now seems like it's only happening in the first case I described, when the Extensions tab is reloaded and a new tab is opened. Possible bug?

I'm setting up a chrome extension with a background.js page and a content-script.js.
The two communicate with each other via a port. The way it works now, the port gets intialized  in the background everytime a tab gets activated or updated and the content-script listens to it via chrome.runtime.onConnect.addListener() (which returns the port).
This works fine. Except in two (similar) cases:

*

*When the extension gets reloaded in the Tools>Extensions page and a new tab is created.

*On the new tab page after Chrome is shutdown and restarted.

I'm have some logs that show that in these cases, background.js does initialize the port... but the content script isn't receiving it for some reason.
These are the basics of what i'm doing:
background.js
// When a tab gets activated
chrome.tabs.onActivated.addListener(function(tab) {
    port = chrome.tabs.connect(tab.tabId, { name: "fh-ext-messenger" });
    console.log(port)
    initPortListener(port);
});

// When a tab is updated
chrome.tabs.onUpdated.addListener(function(tab) {
    port = chrome.tabs.connect(tab, { name: "fh-ext-messenger" });
    console.log(port)
    initPortListener(port);
});

content.js
chrome.runtime.onConnect.addListener(function(port) {
    console.log(port);
    // ...
}

Any ideas on why this doesn't work on an initial tab?

A: Content scripts are always attached to your extension. Anytime your extension is reloaded or deactivated that content script will be removed from all the tabs that it was active on.
Reloading the extension doesn't make it become active again you need to reload that particular tab.
I have also noticed that reloading the extension page reloads all extensions and shoudl explain why your previously active content scripts are not longer active.


text:
Q: Combining 2 linq queries - group and join I have 2 separate tables in my Db for Customers and their related Ethnicity. The customers table holds foreign key Id for the ethnicity. I would like to create a Linq query that shows the total of each ethnicity for reporting purposes. For example something like...
 +------------+------------------+
 |  Ethnicity | Customer Count   |
 +------------+------------------+
 |  White     |   100            |
 +------------+------------------+
 |  Black     |   50             |
 +------------+------------------+
 |  Chinese   |   20             |
 +------------+------------------+ etc...

So far I have the following two LINQ queries:
var customers = repository.GetAll<Customer>();
var ethnicities = repository.GetAll<Ethnicity>();

var query1 = customers.GroupBy(c => c.EthnicityId).Select(g => new { Key = g.Key, Count = g.Count() });

query 1 shows totals but with ethnicity ID instead of text (EthnicityType).
var query2 = from c in customers
             join e in ethnicities on c.EthnicityId equals e.Id
             where (c.EthnicityId == e.Id)
             select new { Ethnicity = e.EthnicityType, Count = ??? };

query 2 joins the two tables but how to group this so that I get the Total instead of individual records? Hope this makes sense, would appreciate help on this.

A: var query2 = query1.Join(ethnicities, x => x.Key,
                                      y => EthnicityId,
                                   (x, y) => new { Ethnicity = y.EthnicityType,
                                                      Count = x.Count });

A: There are quite a few ways to do what you want but if the number of ethnicities is small you can simply create a lookup table on the client side and use it to map ID's to descriptive names:
var customers = repository.GetAll<Customer>();
var ethnicities = repository.GetAll<Ethnicity>().ToDictionary(e => e.Id);

var query1 = customers
  .GroupBy(c => c.EthnicityId)
  .Select(g => new { Key = ethnicities[g.Key], Count = g.Count() };

ToDictionary(e => e.Id) is used to create a dictionary mapping ID's to names and the dictionary is then used to look up the name using ethnicities[g.Key].

A: I think this might work:
var query2 =
    from e in ethnicities
    join c in customers on e.Id equals c.EnthnicityId
    into g
    where g.Any()
    select new { Ethnicity = g.First(), Count = g.Count() };


text:
Q: How to delete all image placeholder powerpoint with vsto powerpoint I'm try making an Add-in for PowerPoint 2019.  I want to delete only images on a slide in PowerPoint. im make button on ribbon when im click button all image deleted.
 Sub DeleteAllPictures()
On Error Resume Next
    Dim PPSlide As Slide
    For Each PPSlide In ActivePresentation.Slides
 PPSlide.Shapes.Placeholders(1).Delete
        PPSlide.Shapes.Placeholders(2).Delete
        PPSlide.Shapes.Placeholders(3).Delete
        PPSlide.Shapes.Placeholders(4).Delete
        PPSlide.Shapes.Placeholders(5).Delete
        PPSlide.Shapes.Placeholders(6).Delete
        PPSlide.Shapes.Placeholders(7).Delete
        PPSlide.Shapes.Placeholders(8).Delete
        PPSlide.Shapes.Placeholders(9).Delete
        PPSlide.Shapes.Placeholders(10).Delete
            Next
End Sub

previously I removed all image using vba macro and it works.
Being a newbie for vsto, I don't know where and how to delete all images. Any kind of assistance will be appreciated. Sorry for my bad English.

A: The Shapes property of the Slide class returns a Shapes collection that represents all the elements that have been placed or inserted on the specified slide, slide master, or range of slides. The Shapes.Placeholders property returns a Placeholders collection that represents the collection of all the placeholders on a slide.
Try to use the following code:
Sub DeleteAllPictures()
On Error Resume Next
    Dim PPSlide As Slide
    For Each PPSlide In ActivePresentation.Slides
        Dim PPShapes as powerPoint.Shapes = PPSlide.Shapes
        For Each PPPlaceholder In PPShapes.Placeholders
          PPPlaceholder.Delete
        Next
    Next
End Sub


text:
Q: Android Game Dev: Input handling I'm programming my first Android Game ever and I'm trying to figure out the best way to handle inputs.
Should I handle inputs outright or put them in a queue of some sort and handle them with an updateInputs() method?
Also, where should I put the code for handling inputs? Should it be inside my SurfaceView object or inside of the thread that handles drawing and physics?
Thanks!

A: I would put them in a queue but execute them right away, incase the processing takes longer then expected you can keep track of what the user has done. As for handling the imputs, i would put it in the surface view, but thats just my general opinion. Im sure there are better ways.
Good luck, I would like to play your game when you finish


text:
Q: Swap button image when state changes I am testing a change of button states however I am having several difficulties.
I am trying to set an image for the buttons when they are in a natural state (pause). When I click the button on a line, a dropdown opens and I want to click on start on that line, the button changes the image set in the Start state. My problem is that none of the images appear, does anyone know what I may be doing wrong?
Thank you!
html
<button id="button-basic" dropdownToggle aria-controls="dropdown-basic">

  </button>

Start

Stop

A: Change your button section as follows,
I have also added height and width attribute for better viewing of image.
<button id="button-basic" dropdownToggle aria-controls="dropdown-basic">

</button>


text:
Q: How was this records/fanout logic derived for the "no statistics" case in MySQL's Query Planner? In the MySQL Server 5.7 source code, the formula records = (x * (b-a) + a*c-b)/(c-1) is used in the query planner to calculate the number of records when key distribution statistics are not available.
Where is this formula coming from, how was it derived, or why is this specific formula the formula that's being used?  Does it have an established theoretical underpinning, and if so, what is its basis?
https://github.com/mysql/mysql-server/blob/5.7/sql/sql_planner.cc#L529
          Assume that the first key part matches 1% of the file
          and that the whole key matches 10 (duplicates) or 1
          (unique) records.
          Assume also that more key matches proportionally more
          records
          This gives the formula:
          records = (x * (b-a) + a*c-b)/(c-1)
          b = records matched by whole key
          a = records matched by first key part (1% of all records?)
          c = number of key parts in key
          x = used key parts (1 <= x <= c)

A: If you have absolutely no data about your problem, you are forced to do an estimate.
The general form of that formula is explained in the comments:

*

*if we use just one keycolumn (x) of a multicolumn index (with c columns), we get a rows (1% of total rows). So for x=1, the result is a by definition.

*if we know the value for every keycolumn of a multicolumn index, we get the number of rows per whole key (b); so for x=c, we get b rows (which is 1 or 10) by definition.

*in between (if we use keyvalues for more than 1 key column, but not all), for each additional known keyvalue, we can exclude some additional rows: we have a-b rows that will not belong to the case where we know our full key (which would have b rows), and by definition they shall be excluded proportionally to the ratio of usable keycolumns ((x-1)/(c-1)).

*The -1 in (x-1)/(c-1) is just a shift (you could just use different variable names), since we only need to count the additional columns, but c and x is the count including the first column. (In a time series, you would call the parameter for the first column t=0, and the -1 does exactly that).

So in conclusion we get a - (a-b) * (x-1)/(c-1) (a for the first key column minus the rows we proportionally exclude). This is (if you transform that expression a bit) exactly the formula given. A quick sanity check: For x=1 (x-1=0), the second term is 0 and we get a, as defined by the first condition; for x=c, we get a-(a-b)=b as defined by the second condition.
It is not unreasonable to make this ansatz using these assumptions, but you can probably find a different formula that makes as much sense. To argue that it is better would be a harder task though.
Then there is the matter of choosing the values (b=10 and 1% in this case). You can obviously choose any value. For doing this without any reliable data except a gut feeling, there is a concept called the Fermi estimate:

The estimation technique is named after physicist Enrico Fermi as he was known for his ability to make good approximate calculations with little or no
  actual data.

You basically choose just the order of magnite (1, 1000000, 1/100) for your input parameters, and you get a reasonable order of magnitude for your result.
So how many rows do you expect a non-unique key to cover? It's more than 1, otherwise you would make it a unique key, but is it more like 2, 10 or 100? 10 is probably a good guess (it covers value from about 3 to 30 in that estimate). So although this numbers could have come from a 2 year worldwide survey about key distribution, estimated values in powers of 10 are usually derived in a fashion like that. If you want to be absolutely certain, ask the developer.
And the obligatory xkcd for this kind of topics: What-if? Paint the Earth


text:
Q: Why data doesn't show in activity of android? Data of MaterialSpinner doesn't show before the user presses the spinner. But Date of MaterialSpinner shows while the user is pressing the spinner. After selected, it doesn't show in MaterialSpinner.
MainActivity.java
spn_menu = (MaterialSpinner) findViewById(R.id.spn_menu);
spn_menu.setAdapter(new ItemSpinnerAdapter(this, foods));

ItemSpinnerAdapter.java
public class ItemSpinnerAdapter extends BaseAdapter {

    private Context context;
    private List<Food> food_list;

    public ItemSpinnerAdapter(Context context, List<Food> food_list) {
        this.context = context;
        this.food_list = food_list;
    }

    public int getCount() {
        return food_list.size();
    }

    public Food getItem(int position) {
        return food_list.get(position);
    }

    public long getItemId(int position) {
        return position;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        TextView tv = (TextView) convertView;
        if (tv == null) {
            tv = (TextView) LayoutInflater.from(context).inflate(R.layout.custom_spinner_item, parent, false);
        }
        tv.setText(getItem(position).getName());
        return tv;
    }
}


text:
Q: Communication between multiple users of one extension I am planning on building an chrome extension that would allow 2+ users communication on different devices. Basically one user would fill out the textarea and send encrypted (if needed) message and the other user would receive it and decrypt.
I am wondering if there's an API that would allow for such communication. (I'm pretty sure neither broadcast channels or chrome.runtime.messages doesn't work in this scenario.).


text:
Q: How to split an array of nested Angular forms in a child component? error I can't split the form into two components, it works fine, there are no errors in one component. It works in both)))) but there are errors in the console, and I can't find an answer on how to fix them.
there is an array of filter formgroups, it must contain an array of value formgroups.
Parent form array component:

import { AfterContentChecked, ChangeDetectionStrategy, ChangeDetectorRef, Component, OnInit } from '@angular/core';

import { FormArray, FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';

@Component({
    selector: 'app-filters',
    styleUrls: ['./el-input.scss'],
    templateUrl: './el-input.html',
    changeDetection: ChangeDetectionStrategy.OnPush,
})
export class ElInputComponent implements OnInit, AfterContentChecked {
    form!: FormGroup;

    constructor(
        private cdr: ChangeDetectorRef,
        private fb: FormBuilder,
    ) {
    }

    ngAfterContentChecked(): void {
        this.cdr.detectChanges();
    }

    ngOnInit(): void {
        this.form = this.fb.group({
            filters: this.fb.array([]),
        });
    }

    filters(): FormArray {
        return this.form.get('filters') as FormArray;
    }

    newFilter(): FormGroup {
        return this.fb.group({
            labelRU: new FormControl<string | null>(null, [Validators.required]),
            labelUA: new FormControl<string | null>(null, [Validators.required]),
            orderIndex: new FormControl<number | null>(null),
            dynamicProperty: this.fb.array([]),
        });
    }

    addFilter(): void {
        this.filters().push(this.newFilter());
    }

    removeFilter(index: number): void {
        this.filters().removeAt(index);
    }

    onSubmit(): void {
        // console.log(this.form.value);
    }
}

Angular Nested FormArray

<form (ngSubmit)="onSubmit()" [formGroup]="form">

                {{filterIndex}} labelRU :
                <input formControlName="labelRU" type="text"/>
                labelUA:
                <input formControlName="labelUA" type="text"/>

                <button (click)="removeFilter(filterIndex)">Remove</button>
                <app-dynamic-property-form-array [filterIndex]="filterIndex"
                                                 [form]="form"></app-dynamic-property-form-array>

        <button (click)="addFilter()" type="button">Add filter</button>

</form>

Children form array component:

import { AfterContentChecked, ChangeDetectionStrategy, ChangeDetectorRef, Component, Input, OnInit } from '@angular/core';

import { FormArray, FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';

@Component({
    selector: 'app-dynamic-property-form-array',
    styleUrls: ['./dynamic-property.scss'],
    templateUrl: './dynamic-property.html',
    changeDetection: ChangeDetectionStrategy.OnPush,
})
export class DynamicPropertyComponent implements OnInit, AfterContentChecked {
    @Input() form!: FormGroup;

    @Input() filterIndex!: number;

    constructor(
        private cdr: ChangeDetectorRef,
        private fb: FormBuilder,
    ) {
    }

    ngAfterContentChecked(): void {
        this.cdr.detectChanges();
    }

    ngOnInit(): void {
    }

    public filters(): FormArray {
        return this.form.get('filters') as FormArray;
    }

    public dynamicProperty(index: number): FormArray {
        return this.filters()
            .at(index)
            .get('dynamicProperty') as FormArray;
    }

    public addDynamicProperty(index: number): void {
        this.dynamicProperty(index).push(this.newDynamicProperty());
    }

    public removeDynamicProperty(filterIndex: number, dynamicPropertyIndex: number): void {
        this.dynamicProperty(filterIndex).removeAt(dynamicPropertyIndex);
    }

    private newDynamicProperty(): FormGroup {
        return this.fb.group({
            nameRU: new FormControl<string | null>(null, [Validators.required]),
            nameUA: new FormControl<string | null>(null, [Validators.required]),
            orderIndex: new FormControl<number | null>(null),
        });
    }
}

 Dynamic FormArray

                        {{dynamicIndex}} nameRU :
                        <input formControlName="nameRU" type="text"/>
                        nameUA:
                        <input formControlName="nameUA" type="text"/>

                        <button (click)="removeDynamicProperty(filterIndex,dynamicIndex)">
                            Remove
                        </button>

    <button (click)="addDynamicProperty(filterIndex)" type="button">
        Add DynamicProperty
    </button>

But in the console I get two errors


text:
Q: Cross domain HttpWebRequest return 403 forbidden I have 2 sites that sits on 2 domains. I need to send information from one site to the other.
I checked that the asmx is reachable running unit test but when I run my code from the second domain I get a 403 forbidden response.
The code is extremely simple:
     try
     {
        var webRequest = (HttpWebRequest)WebRequest.Create("http://www.blahblahblah.com/Services/ChatNotification.asmx?fromId=" + 525808 + "&toId=" + 525808);
        var webResponse = webRequest.GetResponse();
        var stream = webResponse.GetResponseStream();
    }
    catch(WebException ex)
    {
         var response = (HttpWebResponse)ex.Response;
    }


text:
Q: How to generate a bootstrap popover using javascript with dynamic location The page that I am creating has several canvas elements which are made into piecharts. I would like to make it so that if I click on a particular section of a piechart, a popover is generated next to it with information about that particular section.
**So my specific question is: ** How can I generate a popover at a specific x and y location on the page? For example, if I was to calculate that the top right corner of the clicked section was at x: 295, y: 400, how would I place the popover that is generated at that position? Javascript or Jquery is fine

A: Create a div with style:
<div id="popover"> content </div>

#popover{
    position: absolute;
//    left: <x>px;
//    top: <y>px;
    display: inline-block;
    height: 100px;
    width: 100px;
}

On click set left and right for #popover and show the element.


text:
Q: Laravel Scout does not respect Algolia's order I try to use Laravel Scout with Algolia as my search engine.
I use it like this
MyModel::search('my query')->paginate()->pluck('id');

Problem is, Algolia returns the correct order let's say some records with ids 3, 1, 2 but when Laravel fetches the records on the database, the ids are like 1, 2, 3 (ordered by id).
Am I using Scout wrong?

A: Regarding the issue #341 on the scout repository, it seems to be a scout problem being investigated.
EDIT
The issue is now fixed as of PR #369 ( version > 7.0)

A: You have to edit vendor file in your laravel project:
vendor/laravel/scout/src/Searchable.php

and edit return statement of getScoutModelsByIds() function into:
    $ids_ordered = implode(',', $ids);

    return $query->whereIn(
        $this->getScoutKeyName(), $ids
    )->orderByRaw(DB::raw("FIELD(id, $ids_ordered)"))->get();


text:
Q: Selenium.WebDriver.ChromeDriver Slow on initial launch Initial launching of the Chrome driver is taking 35 seconds on average everything works fine just can't speed up the launch time. Using Selenium.WebDriver.ChromeDriver Version 2.35, NuGet by Jsakamoto. Additional nuget packages are Selenium.support 3.9.1 and selenium.webdriver 3.9.1 by Selenium Committers. How can I speed up the initial launching of the ChromeDriver?
  [TestMethod, TestCategory("DriverSpeed"), TestCategory("GUI")]
        public void SpeedingUpOption()
        {
            Stopwatch time = new Stopwatch();
            time.Start();
            ChromeOptions options = new ChromeOptions();

            // Tried many options nothing helped

            IWebDriver driver = new ChromeDriver(options);
            driver.Navigate().GoToUrl("http://www.google.com");
            time.Stop();
            IWebElement searchBox = driver.FindElement(By.Name("q"));
            searchBox.SendKeys("ChromeDriver Slow");
            driver.Dispose();
        }


text:
Q: How can I use SVG to background on website? I want to use adobe illustrator to make an svg background for my website. When I export the svg image from illustrator it has white borders and then the image won't cover the whole width of my site.. I am loosing it, so please help!
Thanks!
Screenshot of what it looks like when exported (colors are also distorted:

A: If you used the SVG actually as a background and not as an image I expect that you also have used CSS. Asuming your image does not include the white borders, you could use this:
.your-selector {
    background-image: url('your image');
    width: 100%;
    height: 100%;
    background-size: 100% 100%;
    background-position: 0 0;
    background-repeat: no-repeat;
}

If your SVG does contain the white borders and you don't want to change your SVGyou can change the value of your background-size: ..% ..% to values that make the SVG fit.


text:
Q: Can't register the class AdaptiveCardsBinding.iOS.ACOHostConfig when the dynamic registrar has been linked away I am creating a Xamarin.iOS binding library for AdaptiveCards. It works correctly on iOS simulator. However, when running on a real iOS device I get the following error: Can't register the class AdaptiveCardsBinding.iOS.ACOHostConfig when the dynamic registrar has been linked away.
I have read this documentation about linker behaviour and tried the following solutions:

*

*Set linker behaviour to Don't Link in the referencing iOS app. This works but is not efficient/desired

*Preferred solution: Preserve code by adding the following attribute on the ACOHostConfig class: [Preserve (AllMembers = true)] This does not fix the problem.

*Add mtouch arguments: --linkskip=AdaptiveCardsBinding.iOS. Doesn't work either.

Any ideas on how to fix this?

A: So as the error indicates, the dynamic registrar has been linked away. This default behavior can be overridden by passing --optimize=[+|-]remove-dynamic-registrar to mtouch
Solution: Add the following mtouch argument: --optimize=-remove-dynamic-registrar


text:
Q: How to make Laravel Vite copy static assets versioned to build folder I'm experimenting with Laravel Vite but can't seem to figure out how to have the build command move static assets. Instead, it embeds the images "in" the css file trough base64.
So far I've figured out that you need to reference your images relative to the source .css / .scss file.
Like so in /resources/app.css;
.arrow {
  background-image: url('../img/icons/arrow.png');
}

When I run npm run build the end result is a css file containing the image as a base64;
.arrow {
  background-image: url(data:image/png;base64,xxxxxxxxxxxxxxxxxxxx);
}

My desired end result, however, would be that Vite would copy and version that exact image into /public/build/assets/img/icons/arrow.xxxxxxxxxx.png and the processed css would be;
.arrow {
  background-image: url('/build/assets/img/icons/arrow.xxxxxxxxxx.png);
}

A: Figured it out.
Turns out it's actually a feature where Vite inlines images < 4kb by default. The setting can be overwritten by defining build.assetsInlineLimit
export default defineConfig({
    build: {
        assetsInlineLimit: 0,
    },
    plugins: [
        laravel([
            'resources/css/app.scss',
        ]),
    ],
});

As stated in the docs;

Assets smaller in bytes than the assetsInlineLimit option will be inlined as base64 data URLs.

https://vitejs.dev/guide/assets.html
https://vitejs.dev/config/build-options.html#build-assetsinlinelimit


text:
Q: IE problem: keyboard interaction with checkbox I have an HTML table, and each row has a checkbox for selecting or deselecting its row.  Whenever a checkbox changes value, I need to add or remove highlighting to the row and also ensure that the page's submit button is only enabled when at least one row is selected and disabled otherwise.
The checkbox event handler is defined by the following function:
function getCheckboxCallback() {
  return function () {
    var parentRow = getParentRow(this);
    if (!parentRow) {
      return;  // No parent row found; abort
    }

    // Adjust the appearance of the row
    setSelected(parentRow, this.checked);

    // Count the number of selected table rows, and disable the submit
    // button whenever no rows are selected
    enforceInvariants();

    return true;
  };
}

Elsewhere in the same module, the checkboxes are given the event handlers:
checkbox.onchange = getCheckboxCallback();
checkbox.onclick = getCheckboxCallback();  // alleged IE fix

I'm working in Windows XP, and everything works fine in both Firefox 3 and Opera 9.  However, IE 7 does not handle keyboard interaction well (mouse interaction works fine).
The problem is that if a checkbox has the focus and I hit the spacebar, the checkbox doesn't get checked -- instead it gets half checked (it has the same shadowed appearance that it would get immediately after a mousedown).  I have to press the spacebar a second time to actually check the box.  Similarly, it requires two key presses to uncheck it.  Oddly enough, if I hold down the spacebar for a few moments, then a single press works as expected.
Can anyone explain what is going on here?  Is there something I'm doing wrong in the JavaScript code that is causing this behavior?  How can I fix this?

A: Unfortunately, IE handles onchange differently than other browsers. IE interprets it to mean "on blur after change". Note that while this isn't very useful, it is technically correct according to the spec: "The onchange event occurs when a control loses the input focus and its value has been modified since gaining focus"
You can try using the IE-only event "onpropertychange".
Reference: http://lhorie.blogspot.com/2007/04/fixing-ie7-onchange-bug-on-checkboxes.html


text:
Q: Static view holder vs Adapter reference I have recycler view adapter and I keep the id of selected view holder in the adapter and to access the selection field I have two options :
1- make view holder class not status which I read it's bad
2- add a reference for the adapter in the view holder
what should I do for better memory performance and why?

A: You can add to the ViewHolder the data itself. Let's say you have a recycler view that displays a list of User's data, you can add to the ViewHolder the field user (ie var user: User? = null), and then when you bind the view holder you can set the value (ie holder.user = list.get(position) ). Then when you click on a button you can access that member.


text:
Q: US SMS transactional notification opt-out requirements This is probably on the borderline of being a programming question, but this is really about technology choice at the end of the day.
I am trying to work out what functionality the system should support in the USA, distributing receipt notifications for payments via email and SMS, regarding SMS opt-out. Is it mandatory that for transactional SMSs the user should be able to 'unsubscribe from all communications'? To stress: this is ONLY transactional SMSs (receipts)

A: Twilio developer evangelist here.
If you're considering this because you are building a service using Twilio, then you need not worry about building this functionality. Twilio handles opt out messages for you.
If you are only delivering transactional SMS messages and think that opt outs should not apply, I encourage you to get in touch with Twilio support to discuss this in more detail.


text:
Q: Automatically Create a Work Item on new Pull Request We would like to have task created when on new Pull Request .
What I would like to do is:

*

*Find User Story Pull Request Review in Current Sprint

*If not exist, create it.

*Create Task Review Pull Request X under previous story.

That feature doesn't seem to exists in Azure DevOps. Even simply creating a task on new pull request...
The Only way I can think of is through a Service Hook with a custom Web hook.
Can you guide me through this?

Edit
We are currently reviewing a solution using Zapier but we cannot perform exactly what is described above, and it's a paid subscription

A: You can force users to link pull request to an existing work item with Branch policies. this would not create a work item for them, but it would block them from creating a PR unless they link it to an existing work item. I think this is the only thing you can do out of the box.

A: I use custom app and run it through the task scheduler. Rest Api methods:

*

*View active pull requests. In my case, I use a service comment (like "Review task is created") in pull request. If I did not find it, I`ll create a task, link it to PR and add the service comment.

*Create task and link it to pull request.

Here is the sample project: Create and View Pull Requests


text:
Q: P/Invoke declarations should not be safe-critical My code imports following native methods:

*

*DeleteObject, GetFontData and SelectObject from gdi32.dll

*GetDC and ReleaseDC from user32.dll

I want to run the code in full and medium trust environments (I am fine with exceptions being thrown when these imported methods are indirectly used in medium trust environments).
When I run Code Analysis on the code I get warnings like:

CA5122 P/Invoke declarations should not be safe-critical.
P/Invoke method 'GdiFont.DeleteObject(IntPtr)' is marked
  safe-critical. Since P/Invokes may only be called by critical code,
  this declaration should either be marked as security critical, or have
  its annotation removed entirely to avoid being misleading.

Could someone explain me (in layman terms) what does this warning really mean?
I tried putting these imports in static SafeNativeMethods class as internal static methods but this doesn't make the warnings go away.
I didn't try to put them in NativeMethods because after reading this article I am unsure that it's the right way to go because I don't want my code to be completely unusable in medium trust environments (I think this will be the consequence of moving imports to NativeMethods).
Honestly, I am pretty much confused about the real meaning of the warning and consequences of different options to suppressing it.
Could someone shed some light on all this?
EDIT:
My code target .NET 2.0 framework.
Assembly is marked with
[assembly: AllowPartiallyTrustedCallers]

Methods are declared like this:
[DllImport("gdi32")]
internal static extern int DeleteObject(HANDLE hObject);

A: This is most likely an occurrence of this bug Bogus CA5122 warning about P/Invoke declarations should not be safe-critical, which manifests itself with pre-NET4 assemblies.


text:
Q: Rotors in graphs and rank polynomial (Tutte polynomial) I
am studying the $Rank$ $polynomial$ through matroid theory. I have seen that the rank polynomial doesn't determine the graph. In fact, as the the cycle matroid of a graph can distinguish the graph only if it is  $3-$connected, one can choose two different graphs (not $3-$connected) that have the same cycle matroid and therefore the same rank polynomial.
Moreover, it can be shown that there are also 3-connected graphs, non isomorphic (also the cycle matroid are not isomorphic because 3-connected graphs are distinguished by the cycle matroid). This can be seen using $rotors$ (if anyone is interested, it is in Godsil-Royle, page 363). This is seen creating two graphs (with the same number of edges and vertex) and a bijective map between the edges that preserves $size$ and $rank$. Unfortunately, I don't understand why such a map is not an isomorphism of a matroid. Can someone tell me what I am missing?

A: I might be wrong, but I think there is something strange in the idea of the proof that I read in the book of Godsil and Royle. I believe that it is more clear the proof of Tutte written in "Codichromatic graphs, J. Combinatorial Theory Ser. B 16 (1974), 168–174". The Tutte's idea seems a little bit different, but after making some small changes it is satisfying.


text:
Q: text overflow ellipsis: avoid word break In my webpage I have a div with fixed width and using the following css:
width: 200px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;

The ellipsis is working, the problem is that it cuts the final word, and I wanted it to put the ellipsis (...) in the final of a full word.
For instance, if I have the text: "stackoverflow is the best", and if it need to be cutted near the end, I want it to display "stackoverflow is the ..." instead of "stackoverflow is the be..."

A: I'm afraid it's impossible. There was once text-overflow: ellipsis-word, which would do just this, but it was not implemented in browsers and it was removed from CSS3 drafts.

A: Of course it's possible. (If you're willing to change your markup a bit.)
https://jsfiddle.net/warphLcr/

  stackoverflow is the best

A: There's a jQuery plugin that does this, called dotdotdot.
It also works for multi-line text, and adapts responsively if the text reflows e.g. if the screen size changes. It also includes smart truncation of pathnames e.g. http://example.com/some/long/.../path.html

Be aware of the possibility of width-based timing issues in cases where the width changes or becomes unavailable in ways the plugin might not expect, such as if the text is initially hidden or if it changes font (e.g. loading web fonts on some browsers). Might require re-applying or being applied after such changes.
But 99% of the time, the plugin seems fast and robust.

A: If you want to display one line of text that would end in ellipsis, like a news ticker for example, just do:
p { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }


text:
Q: Expected a real got "1,000.00" I am trying to use scan() to read in a very large data set that has variables beginning on different rows. One column contains numbers, some of which are simply 20, others are 1,000.00. My code to read this data in looks like:
largedata<-scan(paste0(folder,df.txt),
            what=list("","","",0,"","","",""),
            skip=20,sep="\t",quote="",dec=".")

But my larger numbers, in the thousands, are not cooperating. I included the dec="." to try to eliminate the problem, but I am still getting this error:
Error in scan(file, what, nmax, sep, dec, quote, skip, nlines, na.strings,  :
  scan() expected 'a real', got '1,000.00'

If I just make my numeric column to be character with all the others, my data set reads in fine, but when I convert to data.frame, everything turns into a factor, and when converting the factor to numeric, my numeric values of 1,000.00 and above all become NA. Is there a way that I can read in numbers that have both commas and decimals in this format? I cannot think of another way to read in my data other than using scan().


text:
Q: Is there any way to improve Phaser 2 Game performance? I am using Phaser 2 in my game. When I open the game initially it works fine, with 55 to 60 fps, however after some time it slows to fps below 30. This is the url of game: http://139.59.91.216:8082/ .
Game Area
game = new Phaser.Game(1366, 778, Phaser.AUTO, null);
game.state.add('Game', Game);
game.state.start('Game');
glowFilter = new Phaser.Filter.Glow(game);

In the game's update function I am doing this:
update: function () {
    // to update the stcik lenght
    for (var i = self.game.snakes.length - 1; i >= 0; i--) {
        self.game.snakes[i].updateStick();
    }
    // to update the FoodGroup
    for (var i = this.foodGroup.children.length - 1; i >= 0; i--) {
        var f = this.foodGroup.children[i];
        f.food.update();
    }

    updateAndSendData(self); // to send the data to server from client side
},

Can anyone suggest how I can improve the performance of the game?


text:
Q: AttributeError: 'function' object has no attribute 'name' I have an issue with Flask. Here's my code. I got the error
AttributeError: 'function' object has no attribute 'name'
from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://postgres:1351996@localhost:5432/example'

db = SQLAlchemy(app)

class Person(db.Model):
    __tablename__ = 'persons'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(), nullable=False)

db.create_all()

@app.route('/')
def index():
    person = Person.query.first
    return 'Hello ' + person.name

if __name__ == '__main__':
    app.run(debug=True)

I used app.run(debug=True) because I got another error when trying to run app using FLASK_APP=app.py, flask run and I don't know why this error appears to me!

A: you're not actually executing the query. your index function should be
@app.route('/')
def index():
    person = Person.query.first()
    return 'Hello ' + person.name

Note the parentheses after the .first


text:
Q: rxjs subscription calls a function that returns a promise, need Promise.each style scheduling I'm trying to read JSON from a file, filter out stuff I don't want and possibly map and flatten the JSON elements, and then for each filtered JSON line in the file call a function that returns a promise.  (Basically tail -f from a bunyan produced file).  Additional Requirement:  I want the pacing to be based on how fast the functions resolve the promise (output pacing, one element at a time, like Promise.each)
Sounds like a great use for RXJS and promises, right?  Well, except that all the examples out there are for promises that produce observable streams, not streams that have subscribers who call functions that return promises.
The available schedulers for RXJS don't seem to have an output-based single concurrency pacing equivalent to Promise.each (I tried flatMapWithMaxConcurrent)
In this code, update returns a promise.  The promises are resolved once I fixed a library bug, but the console output is out of order, and the promises are resolved in what appears to be a highly concurrent manner.  The promises actually take 5 seconds to resolve, I would expect to a see a console message about every 5 seconds.  Instead there's one delay of 5 seconds and a bunch of messages, meaning I think that many messages were run concurrently.
The library I created has Bluebird promises from the ground up, I can't rewrite it without removing promises from all my code.   Kinda getting tempted, this is my second all nighter hunting down unresolved promises. I know how I'd write this in "C"...
function tailMyFile(filename, ocu, oce) {
    var handle = new Tail(filename);

    handle.bunyan().filter(function (x) {
        if ("descr" in x &&  "units" in x && "value" in x && "time" in x)  {
            return true;
        }
    })
    .subscribe (
        function(x) {
            if (x.descr == "enter") {
                MyPromisifiedLib.update(oce, x.value, "").done(function() {
                    console.log("updated enter value");
                })
            } else if ("push" in x) {
                MyPromisifiedLib.update(ocu, x.value, "push").done(function() {
                    console.log("updated with push");
                })
            } else {
                MyPromisifiedLib.update(ocu, x.value, "").done(function() {
                    console.log("updated value");
                })
            }
        },
        function(err) {
            console.error("err leaked through to subscriber");
            log.error("err leaked through to subscriber");
        },
        function() { log.info("Completed") }
    );
}


text:
Q: Sharding and Transactions with MySQL With sharding, how can you maintain a reliable transaction across multiple database servers?
For example, if I had a table named AccountLedger on one database server (MySQL instance)  and a table named User on another database server, is it possible to run a transaction across both database instances that will both reliably commit, or rollback on failure?
Example transaction:
AccountLedger database server:
START TRANSACTION;
INSERT INTO AccountLedger SET
    UserID = @UserID,
    Date = @Date,
    Debit = @Debit,
    Balance = @Balance;

User database server:
START TRANSACTION;
UPDATE User SET
    Balance = @Balance
WHERE UserID = @UserID;

AccountLedger database server:
COMMIT;

User database server:
COMMIT; -- What happens if the COMMIT fails here (power goes out or whatever)

I've read a quite a lot about sharding, but I can't seem to find any information on using  transactions with sharding. Can someone point me in the right direction?

A: It is possible to do this with distributed transactions. They are supported by the InnoDB storage engine. You will find more information about them and about the syntax of the commands in the MySQL documentation: XA Transactions
I advise against using them directly. If consistency is the most requirements for ypur application, then use a transaction monitor that can take care of it. Java EE does that for you.
However, if availability is more important than consistency, you should avoid distributed transactions. The CAP theorem explains why.

A: You can implement cross shard serializable transaction on the client side if each shard supports per key linearizability and compare and set (which is true for MySQL). This approach is used in Google's Percolator and in the CockroachDB but nothing prevents you from using it with MySQL.
I've created a step-by-step visualization of such transactions. I hope it will help you to understand them.
If you're fine with read committed isolation level then it makes sense to take a look on RAMP transactions by Peter Bailis. They also can be implemented in the sharded MySQL environment.

A: Disclaimer: I work for ScaleBase (http://www.scalebase.com), a provider of a complete solution for sharding
We at ScaleBase give the choice to use the use of XA Transactions in InnoDB, although we found out they can be performance costly... And exactly at the places you need your database to be the fastest (massive inserts etc.). So we also enable "our version of 2-phase-commit" which is faster and may be considered very close to XA in terms of consistency, and may just be enough for the trade-off... This "our version" includes a quick "are you available" query such as SELECT version() to all participating databases, and then committing them. This is addition to other mechanisms we have in our "ScaleBase database traffic controller" are enough for most of our customers (and those who don't - still get to choose full XA).


text:
Q: Print number in front of every line of a file I have made a phone book and the function to add users.  I want it to have numbers in front of every line, but I get the wrong number in front of each line. I have added code that prints out the numbers but it gives a big number that is the same on every line. I want it to print like this:
1 John Doe
2 Johnny Doe
3 Max Doe

Right now, it prints this instead:
1878003873 John Doe
1878003873 Johnny Doe
1878003873 Max Doe

I don't know where that number comes from.
void addContact()
{
    string Fname, Lname, Address, Contact, list, name, Fname2, Lname2, Address2, Contact2;
    int counter, number;
    cout << "Enter First Name: ";
    getline(cin, Fname);
    cout << "Enter Last Name: ";
    getline(cin, Lname);
    cout << "Enter Address: ";
    getline(cin, Address);
    cout << "Enter Contact Number: ";
    getline(cin, Contact);

    ifstream asd("number.txt");
    while (asd >> counter >> Fname2 >> Lname2 >> Address2 >> Contact2)
    {
        number = counter;
    }
    ofstream adb("number.txt", ios::app);
    number = number + 1;
    adb << number << " " << Fname << " " << Lname
        << " " << Address << " " << Contact << endl;
}

A: Suppose that you are adding your first user. What do you think that value of number is going to be then?
ifstream asd("number.txt");
while (asd >> counter >> Fname2 >> Lname2 >> Address2 >> Contact2)
{
    number = counter;
}

Because it is your first user then while loop is never entered, so number is never initialised. Hence the garbage numbers you see. Once the first garbage number is there, then the code correctly adds one to each following number.
To fix just add this so that number always gets an initial value.
int counter, number = 0;

Not what you asked about but I think you should close your input file before you try to write the new user
ifstream asd("number.txt");
while (asd >> counter >> Fname2 >> Lname2 >> Address2 >> Contact2)
{
    number = counter;
}
asd.close(); // stop reading and close the input file
ofstream adb("number.txt", ios::app);
...

Having a reading and a writing stream open simultaneously on the same file is not a good idea, even if it does seem to work in this case.


text:
Q: Extending abstract classes in c# I am a Java developer and I have noticed some differences in extending abstract classes in c# as opposed to Java. I was wondering how a c# developer would achived the following.
1) Covarience
public abstract class A {
   public abstract List<B> List();
}
public class BList : List<B> {
}
public abstract class C : A {
   public abstract BList List();
}

So in the above hierarchy, there is covarience in C where it returns a type compatible with what A returns. However this gives me an error in Visual Studio. Is there a way to specify a covarient return type in c#?
2) Adding a setter to a property
public abstract class A {
   public abstract String Name { get; }
}
public abstract class B : A {
   public abstract String Name { get; set }
}

Here the compiler complains of hiding. Any suggestions?
Please do not suggest using interfaces unless that is the ONLY way to do this.

A: Somehow I don't understand your Intention. Why don't you solve it like this ?
public class BList : List<T> where T : B {} same =  public class BList : List<B> {}

public class C : A
{
    public override List<B> Liste()
    {
        return new BList();
    }
}

About your second Question :
What you want to do there is bad design in my eyes. You can use the keyword virtual on both and ignore the warnings, but why do you want to do something like this ?
public abstract class A
{
    public virtual string Name { get; protected set; }

}

public abstract class B : A
{
    public virtual string Name { get; set;}
}

A: Neither of these is supported in C#.  Covariant returns are also not supported in the underlying runtime (the CLR).
It appears that it may be possible to do something along the lines of your property example on the CLR, but not in C#.  Under the hood, a property essentially consists of a name, the property type, and references to the getter and setter methods (as applicable), which are typically named get_<Property> and set_<Property> (but which are not required to follow that convention in non-CLS-compliant classes).  It is possible to create a property in a base class which has only a getter, and then another property in the derived class with the same name and getter, but which has its own setter.  However, I don't know that any .NET languages allow such a definition.


text:
Q: Need to display author's email id in the "Edit post" field in wp dashboard. How do I do this? I have created a custom post type & have enabled frontend posting for the same.
I need the Edit post page to display the original author's email id. I already have "post author" displayed, but that just gives the name & username of the author. How do I go about doing this?

A: Probably you use get_post on edit page with query object. You can simply use $post->post_author on edit page. For example;
$editableid = get_query_var('id');
$postedit = get_post($editableid);
$author_id = $postedit->post_author; //Always return author ID value.

<input type="hidden" name="post_author" value="<?php echo $author_id;?>" />

I hope this code piece helps you.
EDIT : For email you use the_author_meta with your $author_id value.


text:
Q: Linux opencv independent installation : not found in CMake I am creating an object tracking program which rely on OpenCV. Thus I want to be able to test it with different versions of OpenCV but I have linking errors.
I installed the last version of OpenCV (a69b435c928f422fb5f99c02cf2dcae57dcf820a) in the following folder : /usr/local/opencv/opencv-trunk instead of the usual /usr/local.
Then I followed also the official tutorial to use OpenCV with CMake in Linux, but I had the following "normal" error :
CMake Error at CMakeLists.txt:11 (find_package):
  By not providing "FindOpenCV.cmake" in CMAKE_MODULE_PATH this project has asked CMake to find a package configuration file provided by "OpenCV", but CMake did not find one.

  Could not find a package configuration file provided by "OpenCV" with any of the following names:

    OpenCVConfig.cmake
    opencv-config.cmake

  Add the installation prefix of "OpenCV" to CMAKE_PREFIX_PATH or set "OpenCV_DIR" to a directory containing one of the above files.  If "OpenCV" provides a separate development package or SDK, be sure it has been installed.

-- Configuring incomplete, errors occurred!

So I did what was suggested and added the following line in my CMakeLists.txt :
# Find independently installed OpenCV libraries
set(OpenCV_DIR "/usr/local/opencv/opencv-trunk/share/OpenCV")

This is the complete CMakeLists.txt file :
# Find independently installed OpenCV libraries
set(OpenCV_DIR "/usr/local/opencv/opencv-trunk/share/OpenCV")

cmake_minimum_required(VERSION 2.8)
project( DisplayImage )
add_executable( DisplayImage DisplayImage.cpp )

find_package( OpenCV REQUIRED )
include_directories( ${OpenCV_INCLUDE_DIRS} )
target_link_libraries( DisplayImage ${OpenCV_LIBS} )

Now I have the following error and I don't find how to deal with it.
CMake Error at CMakeLists.txt:12 (find_package):
  Found package configuration file:

    /usr/local/opencv/opencv-trunk/share/OpenCV/OpenCVConfig.cmake

  but it set OpenCV_FOUND to FALSE so package "OpenCV" is considered to be NOT FOUND.

-- Configuring incomplete, errors occurred!

If you have already faced that issue in such context your solutions are welcomed ;)

A: If you are running IntelliJ or any other IDE, just try re-building CMake cache (or just remove your build directory and run cmake utility again).
I believe this is not the best practice - to set the configuration variable like OpenCV_DIR hard-coded in the CMakeLists.txt. Try setting it manually, as an environment variable to the cmake utility:
OpenCV_DIR=/usr/local/Cellar/opencv3/3.1.0_2/share/OpenCV/ cmake ..

or set your IDE to make this for you:


text:
Q: Regexp on C# not finding all matches of CDATA I'm trying to match:
<script type="text/javascript">
//<![CDATA[
if (typeof(Sys) === 'undefined') throw new Error('ASP.NET Ajax client-side framework failed to load.');
//]]>
</script>

AND
<script type="text/javascript">
//<![CDATA[
var theForm = document.forms['aspnetForm'];
if (!theForm) {
    theForm = document.aspnetForm;
}
function __doPostBack(eventTarget, eventArgument) {
    if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
        theForm.__EVENTTARGET.value = eventTarget;
        theForm.__EVENTARGUMENT.value = eventArgument;
        theForm.submit();
    }
}
//]]>
</script>

I'm using:
regex = new Regex(@"\<script(.*)type=(.*)text/javascript(.*)\>(.*)\/\/\<\!\[CDATA\[(?<text>(.*))\/\/\]\]\>(.*)\<\/script\>", RegexOptions.IgnoreCase | RegexOptions.Singleline);

foreach (Match match in regex.Matches(html))
{

}

but it only finds the first match. It doesn't find the second. Can't for the life of me see why?

A: The regex is too greedy at the 6th group, (.*)\<\/script\>*. I added lazy behavior to all the (.*) groups, and here is a fixed regex:
(?s)\<script(.*?)type=(.*?)text/javascript(.*?)\>(.*?)\/\/\<\!\[CDATA\[(?<text>(.*?))\/\/\]\]\>(.*?)\<\/script\>
So, if you run the regex on your concatenated inputs, you will get 2 matches, and your CDATA will be in .Groups[5].Value.


text:
Q: Correct way to use !is_null() There is an example in PHP Object-Oriented Solutions that seems to be flawed, if I understand is_null properly.
The sample code in the book is as follows:
if (!is_null($required) && !is_array($required)) {
throw new Exception('The names of required fields must be an array, even if only one field is required.');
}

This code is supposed to test that a var $required is not NULL and is an array.  To my understanding, is_null() returns TRUE if the variable is not set or is NULL.  So, does it make sense to negate is_null() in that example if you're trying to throw an exception when the variable is not set, NULL, or is not an array?  The only way an exception is thrown is if (true && true) is satisfied.

A: FROM: http://www.php.net/manual/en/language.types.null.php

A variable is considered to be null if:
it has been assigned the constant NULL.
it has not been set to any value yet.
it has been unset().

<?php
if(is_null($obj)){
    echo 'is null';
}

While $obj is considered NULL because it hasn't been registered yet, it will still throw a Notice: undefined ...
The correct use for your if statement should first check to see if the variable exists then check to see if it is an array.
if (!isset($required) || !is_array($required)) {}
-or-
if (empty($required) || !is_array($required)) {}
The nice thing about is_array() is the fact that if $required IS NULL then it's not an array and will pass the if clause.
isset() and empty() will both ensure that the variable exists. Failure to pass either of these methods will quit the if statement and no errors will be returned.

A: I appreciate all the feedback, but somehow I think part of my question was not addressed.  The fact that the variable is being tested with a Logical AND, means that both statements must be TRUE for the Exception in the if clause to run.
But, I don't think the use of !is_null($required) is correct.  The sample code from the book was testing for a variable to contain an array with one to many values.  Even if it has one value, the $required variable (for other reasons) still must be declared as an array with a single value.  So, if $required hold's a value of (int) 5, an Exception should be thrown. If the $required variable is not declared/instantiated, an Exception should be thrown.  If the $required variable holds NULL, an Exception should be thrown.  Here is where the logic of this sample code fails.  Using the online php command line that @Calimero posted, this logic fails when $required is set to NULL.
Instead of using !is_null($required) , is_null($required) without the negation should have been used since is_null returns TRUE if the value of $required is indeed NULL.  So, if you negate is_null() when the $required value happens to be NULL, that part of the logical AND operation becomes FALSE, therefore the Exception never gets run at all because the logical AND operation requires both statements to be TRUE for the logic to jump into the curly braces.  Which is precisely what the if clause was supposed to catch in the first place. The sample code was supposed to catch the $required variable not being set and not being of an array type.
And as I mentioned in a comment, isset() probably wasn't used because isset will return TRUE even if the $required variable is an empty string, a string with a space, an empty array, etc.
Someone please confirm I'm not talking stupid.  LOL.
Take a look at this: (http://3v4l.org/QpVXq)

A: **Is_null**
The is_null is php construct language and  can be used to test whether a variable is set to null.
   $myVariable = null;
    is_null($myVariable); // this returns true,because it is set to null

$myVariable = 10;
is_null($myVariable); // this returns false, cuz it is assigned to value

If the variable does not exist is_null will also return true,
but with an error notice as it is not supposed
 to be used with uninitialized variables.

 //returns true and also notice with (undefined variable notice)

    is_null($myNewVariable);// true (undefined variable notice)

A: If the code is part of a function, it could be that the function allows for null values, but if the value is passed and it's not an array, then an exception must be thrown. If the code is not part of a function, it may be just demonstrating how to detect if a value is an array only if it isn't null, thus allowing null values.


text:
Q: jQuery UI .sortable very jumpy I'm using nested sortables to create a UI editor. Basically similar to portlets I guess. The user picks up widgets or widget holders and can move them around the screen, then it saves. They are really jumpy and don't like to stick into certain spots. It almost seems like they prefer to be dragged top-down. I've tried adding padding to the holder and the widgets and it doesn't seem to make it any better. Does anyone know of a really good method of making this crap more accurate? I've tried almost everything I can find....I understand the issue (mostly), I just can't figure out a fix. One problem is when it snaps into a spot, something moves and sometimes what moves makes the layout change drastically and the placeholder jumps back and forth trying to settle. I don't understand why I can't get it to go to the top of a holder though...Here's my js:
  $(".widget_holder").sortable({
        distance: 30,
        revert: true,
        items: ".widget",
        opacity: .8,
        scroll: true,
        scrollSensitivity: 100,
        scrollSpeed: 100,
        handle: ".move_widget",
        dropOnEmpty: true,
        tolerance: "pointer",
        cursorAt: { top:0, left: 0 },
        start: function(e, ui){
        $(".widget_holder", ui.item).hide();
        $('.widget').addClass("drag_padding");
        $(".widget_holder" ).addClass("holder_hover").addClass("drag_padding").sortable("refresh");
        },
        update: function(e, ui){
        if(this === ui.item.parent()[0]) {
        updateByHolder();
        }
        },
        stop: function(e, ui){
        $(".widget_holder", ui.item).show();
        $('.widget').removeClass("drag_padding");
        $(".widget_holder" ).removeClass("holder_hover").removeClass("drag_padding");
        }
   }).sortable(
       "option", "connectWith", '.widget_holder'
    );

A: Try getting rid of tolerance: "pointer", or replace it with tolerance: "intersect",
Having pointer as the tolerance options makes the whole list very jumpy!

A: What about overflow: auto; to the parent (ul, #element_id, etc)?


text:
Q: Is there any other security/performance issue of XAMPP for production on windows server except those listed in official FAQ? Usually I prefer using Linux CentOS / Ubuntu for production server. However currently I got a customer who don't want to pay extra for hosting. In return he provides a server running windows server 2003. To save setting time, I would like to see if it is safe to use XAMPP as production server.
After some Google searches, many people says that it is not recommended, but usually with no reason given. The only exception is the official Q&A section, stating that there are the following security issue:

*

*The MySQL administrator (root) has no password.

*The MySQL daemon is accessible via network.

*ProFTPD uses the password "lampp" for user "daemon".

*PhpMyAdmin is accessible via network.

*The XAMPP demopage is accessible via network.

*The default users of Mercury and FileZilla are known.

So, if I am not installing ProFTPD and Mercury during XAMPP installation, setting a password for MySQL root account and set up a firewall that only allow public access on port 80, it seems that all 6 problems are solved?
If so, except the security issue listed above, are there any other security / performance issue that I should not be using XAMPP for production?

A: I think your approach is correct.
The most important points are to create a root password and configure the .htaccess file.
There are also guides how to make XAMPP more secure.


text:
Q: How can change sender email Address?
I made Trigger Flow and Schedule Flow using Email Alert using with email template.
Addly, I want change sender email address, so use custom email in Flow Action, add the sender email, but still cannot change email address.
how can i change sender's email address?
Regards, CKJ

A: Consider using the 'Flow Core Action: Send Email' action node in your Flow. You can specify the sender, just be sure to check you org-wide addresses.
https://help.salesforce.com/s/articleView?id=sf.flow_ref_elements_actions_sendemail.htm&type=5


text:
Q: Git Remove Directory in Github I made a mistakes and now I can't fix it.
I have pushed an useless directory in my github repository, then I deleted it and repush the new version of my project. The problem is that the directory is still here in github WebUI but not when I pull (already up to date, and my local project doesn't have the useless directory).
This is a screenshot of my github web interface

The dir is l3miage-bdsi-G01
Thanks

A: it seems what you have there is a git submodule
This question may help you: How do I remove a submodule?

A: Try to remove commit and push it to repo with -f command line option. This way is not good becouse somebody may be alredy make work from before pushed commits but this command remove that.
Try to do:
git checkout master
git reset --hard commit
git push --force origin master:master

If there is no help. Possible git repo broken some how. It is rare case seems impossible. If git repo broken it is need to delete repo and recreate and push again.

A: Try cloning the project and see if that directory is there in cloned project or not.
If the directory is not in cloned project then it must not be in git either.
If the directory is still there then delete directory using 'git rm -r directory_name' command.
In either case, add that directory to .gitignore file to make sure this directory is not pushed.

A: I don't know how I solved this problem but it's okay.
I have just git rm the folder, git commit and push.
but I have reset lot of think before with lot of commands so I don't realy know the solution (I did this commands before whitout success).


text:
Q: Add dynamic form validation callback to field I am using formValidation.io and need to dynamically add a callback type validator within a class so that it can use a class property. The issue is that I initially pass my validator options into a super call that has some form validation procedures. But this means I do not have initial access to class properties.
So to do this I was trying to use updateOption but it definitely does not begin to validate this.
class MyForm extends Form {

  var validatorOptions = {
    fields: {
      phoneNumber: {
        validators: {
          regexp: {
            regexp: Regexp.phone,
            message: "Please enter a valid phone number"
          }
        }
      }
    }
  };

  super({
    validator: {
      options: validatorOptions
    }
  });
  var self = this;

  this._cachedPhoneNumbers = [];

  var phoneValidatorCallback = {
    message: "This number is already in use",
    callback: function(value, validator, $field) {
      if ($.inArray(value, self._cachedPhoneNumbers) > -1)
        return false;
      return true;
    }
  }

  // ref to validator is definitely valid!
  this.validator.updateOption('phone', 'callback', 'callback', phoneValidatorCallback);

}

A: Here is the answer. I simply misused the function.
class MyForm extends Form {

  var validatorOptions = {
    fields: {
      phoneNumber: {
        validators: {
          regexp: {
            regexp: Regexp.phone,
            message: "Please enter a valid phone number"
          },
          callback: {
            message: 'This number is in use',
            callback: function() {
              return true;
            }
          }
        }
      }
    }
  };

  super({
    validator: {
      options: validatorOptions
    }
  });
  var self = this;

  this._cachedPhoneNumbers = [];

  function phoneValidatorCallback(value, validator, $field) {
    if ($.inArray(value, self._cachedPhoneNumbers) > -1)
      return false;
    return true;
  }

  // ref to validator is definitely valid!
  this.validator.updateOption('phone', 'callback', 'callback', phoneValidatorCallback);

}


text:
Q: Setting a counter to the value of a reference I have a use case description, something along the lines of:
\begin{enumerate}
    \item User does X.
    \item User does Y. \label{y}
    \item User does Z. \label{z}
\end{enumerate}

Then there is an alternative path that deviates from action Y. It is shown in a different list. I would like to start that list with the value of the Y item above (in this case, the second list would start at 2). I tried:
\begin{enumerate}
    \setcounter{enumi}{\ref{y}}\addtocounter{enumi}{-1}
    \item User does Y2.
    \item Continue with Z (\ref{z}).
\end{enumerate}

However, this only works when the index has been made already. Otherwise, I get:
! Missing number, treated as zero.

What is the correct way to do this?

A: You could use refcount (as egreg already proposed) in conjunction with the enumitem package and its start=... feature (no need to use \setcounter{enumi}{...} explicitly then.
\documentclass{article}

\usepackage{refcount}
\usepackage{enumitem}
\begin{document}

\begin{enumerate}
    \item User does X.
    \item User does Y. \label{y}
    \item User does Z. \label{z}
\end{enumerate}

\begin{enumerate}[start={\getrefnumber{y}}]
%    \setcounter{enumi}{\ref{y}}\addtocounter{enumi}{-1}
    \item User does Y2.
    \item Continue with Z (\ref{z}).
\end{enumerate}

\end{document}


text:
Q: accessing subtrees in jSON file Hi all I hope you can help me with this one. My JSON file is structured like this:
[{
   {
    "link": {
       "title": "Applications"
    },
    "has_children": true,
    "subtree": [{
        "link": {
        "title": "Projects"
       },
       "subtree": [{
          "link": {
             "title": "WORK\/NEW YORK",
          }
       }]
     }]
   }
}]

Basically its a nav menu and it should be like this:

Application => Projects => WORK/NEW YORK

I am iterating through the whole JSON file to get all the first objects. I have managed to access the first object and display "Application" with this code:
for (var i = 0; i < list.length; i++) {
    var _title = (list[i].link.title);
    console.log(_title);
    buildingMenuContent(_title);
}

Now, I wanna iterate through the first array index [0] and access its subtree first index[0] and finally the last subtree and its index[0] so i can be able to display:

Application => Projects => WORK/NEW YORK

I used this code which got me to application => Projects but it did not iterate to get all of the first objects:
 for (var i = 0; i < list.length; i++) {
         if (list[i].has_children) {
            for (var n = 0; n < list[i].subtree.length; n++) {
            var _subtitle = (list[i].subtree[n].link.title);
         }
       }
    }
 }

I dont know if I clarified this but i need loop through this array. I used a recursive for loop but it was too complicated to use it to manipulate the DOM after.

A: As a general advice, keep the schema of the objects/nodes in the JSON similar if you want to recursively iterate over them. It'll make your code easy and generic.
Doing it manually for every level is not recommended as others have said. What if another level comes up in the form of 4th subtree? 5th subtree? Would you keep writing code for that? I don't think so. It's better to come up with a recursive solution for such cases. To do this, the objects should have a similar structure so you can iterate over them, treating every object/node independently.
// Menu JSON structure
var menuList = [
    {
        "link": { "title": "Applications" },
        "has_children": true,
        "subtree": [
            {
                "link": { "title": "Projects" },
                "subtree": [
                    {
                        "link": { "title": "WORK\/NEW YORK" }
                    }
                ]
            }
        ]
    },
    {
        "link": { "title": "Operations" },
        "has_children": true,
        "subtree": [
            {
                "link": { "title": "Projects" },
                "subtree": [
                    {
                        "link": { "title": "WORK\/DALLAS" }
                    }
                ]
            }
        ]
    }
];

function printTree(list, isTopLevel) {
    let path = '';

    // Iterate all the nodes in the provided list array
    for ( var i = 0; i < list.length; ++i ) {
        path += list[i].link.title;

        // Process subtree if present
        // This condition can also be based on `has_children` property but since that isn't present across all nodes, I've used `subtree`
        if ( list[i].subtree && list[i].subtree.length > 0 ) {
            path += '=>'; // Add => only if current node has subtrees
            path += printTree(list[i].subtree, false); // Recursively add the subtree paths
        }

        // Only needed to insert new line after every parent node path has been added
        // Not really necessary
        if ( isTopLevel )
            path += '\n';
    }
    return path; // Return the path constructed at every node level
}

console.log(printTree(menuList, true));

// Output:
// Applications=>Projects=>WORK/NEW YORK
// Operations=>Projects=>WORK/DALLAS

Notice the use of subtree property which is present across all nodes/objects. It can be used to detect recursive case as it's present across all nodes.

A: first your inputs are wrong !!! syntax error ,
second recursion  is only way because u dont know how level u must go down
var q =[
 {
    "link": {
        "title": "Applications"
            },
    "has_children": true,
    "subtree": [{
            "link": {
                "title": "Projects"
            },
            "subtree": [{
                    "link": {
                        "title": "WORK\/NEW YORK",
                            }}]
                     }]
  }]

function find_child(json)
//a function move down until error happen (last level of json)
  {
      result ="" // this varible hold result
    try // just to avoid if!!! at last level of json it will go to catch and end this loop
    {
        if(json.link.title) // check this field is in json ?
            result += json.link.title
        result += "=>" +find_child( json.subtree[0]) /* call again with {
        "link": {
            "title": "Projects"
        },
        "subtree": [{
                "link": {
                    "title": "WORK\/NEW YORK",
                        }}]
                 } and second type with nex child at forth time it cause error and return*/

    }
    catch (e)
    {
    }
    return result
  }

  print(find_child(q[0],""))

result = Applications=>Projects=>WORK/NEW YORK

A: let tree = {}; //your parsed JSON here

const loopTree = (tree, subTreePropName, resultAccumulator) => {
  if (tree) {
    if (tree[subTreePropName]) {
      resultAccumulator += tree[subTreePropName].map((subtree) => loopTree(subtree, subTreePropName, resultAccumulator));
    }
    return resultAccumulator + tree.link.title;
  }
  return '';
}

let result = loopTree(tree, 'subtree', '');

I did not test this, but it should work... Explanation of how loopTree works:
if (tree) check if the function was called with an undefined item. In case this is false (or null, or undefined - means this was called with an empty object), return an empty string. Otherwise, let's loop the tree!
if (tree[subTreePropName]) checks if the current tree we are visiting has a subtree property. If not, it's a leaf. Return resultAccumulator + own text. Otherwise, it's a branch, let's loop it!
resultAccumulator += tree[...].map(...) this is the heart of the recursion. It says - for each item in the current tree's subtree, loop it and add to our result its result.
return resultAccumulator + tree.link.title; is the line closing the recursion. It returns current result + own title.
let result = loopTree(tree, 'subtree', '') is where we effectively execute the loop. We're saying, loop the tree tree, looking for childs in the property named 'subtreee', and add the results of each item to an empty string. The final result is set to the result variable.
Does this make sense?
Is this what you need, or did I miss some conditional somewhere?
If you want to take this one step further, you can pass an additional processValues value in the function to map specific tree items... EX:
let processValues = (treeItem) => {
  return treeItem.link.title
}

And then
let tree = {}; //your parsed JSON here

const loopTree = (tree, subTreePropName, resultAccumulator, itemMapper) => {
  if (tree) {
    if (tree[subTreePropName]) {
      resultAccumulator += tree[subTreePropName].map((subtree) => loopTree(subtree, subTreePropName, resultAccumulator, itemMapper));
    }
    return resultAccumulator + itemMapper(tree);
  }
  return '';
}

let result = loopTree(tree, 'subtree', '', processValues);

This will allow to pass a function as the 4th argument. This function should receive a tree item, and return its related value.
This way you can add all your conditional and operations in that processValues function, and the loop stays clean.


text:
Q: 'reinterpret_cast': cannot convert from 'overloaded-function' to 'intptr_t' with boost.dll I am working on plugin system using Boost.dll
#include <boost/config.hpp>
#include <boost/dll/alias.hpp>
#include <memory>

class base {
public:
  base(){};
  ~base(){};
  template <typename T>
  static std::shared_ptr<base> create() {
    return std::make_shared<T>();
  }
  virtual void do1() = 0;
};

class derived : public base {
public:
  derived(){};
  ~derived(){};
  virtual void do1() override {}
};

BOOST_DLL_ALIAS(base::create<derived>, // <-- this function is exported with...
                create_plugin          // <-- ...this alias name
)

// auto a = base::create<derived>();

When I trying use factory method inside BOOST_DLL_ALIAS macro getting error like below.

cl /c /ID:\Download\Compressed\boost_1_67_0 a.cpp

Microsoft (R) C/C++ Optimizing Compiler Version 19.12.25834 for x86

Copyright (C) Microsoft Corporation.  All rights reserved.

a.cpp

a.cpp(27): error C2440: 'reinterpret_cast': cannot convert from 'overloaded-function' to 'intptr_t'

a.cpp(27): note: Context does not allow for disambiguation of overloaded function

Without BOOST_DLL_ALIAS macro when calling factory method (as shown in last commented line), it get compiled fine.

A: // this really does nothing:
template<class R, class...Args>
R(*to_fptr( R(*f)(Args...) ))(Args...) {
    return f;
}
// except avoid the bug in MSVC:
BOOST_DLL_ALIAS(to_fptr(base::create<derived>),
            create_plugin
)

that should fix it.
MSVC seems to break when you try to cast from the name of a template function to a intptr_t.  This is a bug.
The above workaround changes it from directly dealing with the name of a template function to just a function pointer.  By breaking the overload resolution and the cast to intptr_t apart, MSVC no longer chokes.
You could probably also do:
template<class T>
T identity( T t ) { return std::move(t); }

instead of to_fptr.
to_fptr is a function that takes a function pointer and returns it.  The syntax to return a function pointer from a function is a bit ridiculous, which is why it is hard to read.

A: This should do the trick:
BOOST_DLL_ALIAS(std::function<std::shared_ptr<base>(void)>(base::create<derived>), // <-- this function is exported with...
    create_plugin          // <-- ...this alias name
)

Indeed it seems MSVC has a bug here, as there should be no problem taking such an expression base::create<derived> and treating it directly as a function pointer. So instead, we "feed it a function pointer" ourselves using the magic of std::function.
I've chosen to use std::function as it involves no writing of any kind of wrapping code and relies directly on intent-delivering standard c++ code.
And of course don't forget to #include <functional> : )

A: Inspired by this tangentially related answer, I found another solution:
const void * create_plugin =
    reinterpret_cast<const void*>(
        reinterpret_cast<std::intptr_t>(
            reinterpret_cast<std::decay_t<decltype(&base::create<derived>)> >(
                &base::create<derived>
            )
        )
    );

https://godbolt.org/z/NVGz_0


text:
Q: Software to create board pinout diagram What software is used to create this (very cool) pinout diagram?

A: This is most likely done in a graphic design program.
It is not "cool" because the actual data is not available for use in any convenient way.
Pinouts should be presented in tabular form, excel-style, that can be copy-pasted in bulk easily, for example into the Altium tabular pinout editor, or into code. When the only pinout available is a graphic file, or a pdf where the table can't be cleanly copy-pasted, you have to do everything by hand, which is error-prone.
Many manufacturers provide pinouts for high pin count devices like microcontrollers in spreadsheet format. Then it's very simple to import in CAD to make a symbol, or make another column with the function name you'll assign to each pin, and convert the whole thing into #defines to import in your code without any chance of error. That saves a lot of time.

A: Relevant previous SE question:
Program to draw pinouts (and easily visualize pin's multiplexed functions)
Lots of ideas are mentioned, but in particular there is this video which demonstrates how such a diagram is made in Inkscape:
Feather Diagram Walk-Through for Adafruit
https://www.youtube.com/watch?v=ndVs1UvK6AE


text:
Q: Concate two dataframes in pandas I have two dataframe and try to join them but failed, can you please help me.
dataframe 1
      0
0     0
1  -100

...

20  400
21  500

dataframe 2
               Rate
Date
2015-04-01      NaN
2015-04-02 -0.00346
2015-04-03  0.00323

...

2015-04-29  0.00296
2015-04-30  0.00878

I want to join them to be:
Rate          0
Date
2015-04-01      NaN      0
2015-04-02 -0.00346   -100
2015-04-03  0.00323      0

...

2015-04-29  0.00296    400
2015-04-30  0.00878    500

but using this
concate = pd.concat([dataframe1, dataframe2], axis=1, join_axes=[dataframe1.index])
print gabung

I got this:
               Rate   0
Date
2015-04-01      NaN NaN
2015-04-02 -0.00346 NaN
2015-04-03  0.00323 NaN

...

2015-04-29  0.00296 NaN
2015-04-30  0.00878 NaN

How to fix the code so get me the result I want. Thank you

A: you could just do
dataframe2['values'] = dataframe1[0].values

So just insert a column to the second data frame, since this is the one you want to keep the index of. I just chose 'values' as an arbitrary name for the column in the result but you can put anything you lie there.

A: Concatination denotes two lists being put after each other, like this:
df1 = pd.DataFrame({"data":[1,2,3]})
df2 = pd.DataFrame({"data":[4,5,6]})
pd.concat([df1, df2])
    data
0   1
1   2
2   3
0   4
1   5
2   6

Merging (Joining) would need a key to join on.
df1 = pd.DataFrame({"data1":[1,2,3], "key":["John", "Janice", "Jake"]})
df2 = pd.DataFrame({"data2":[4,5,6], "key":["John", "Janice", "Jake"]})
pd.merge(left=df1, right=df2, on="key")
    data1   key     data2
0   1   John    4
1   2   Janice  5
2   3   Jake    6

Adding a new column to an existing dataframe is simple assignment:
df1 = pd.DataFrame({"data":[1,2,3]})
df2 = pd.DataFrame({"data":[4,5,6]})
df1['data2'] = df2['data']
    data    data2
0   1   4
1   2   5
2   3   6


text:
Q: remove Quotation marks in IEEE bibliography I am using jot.cls (journal of operator theory) which doesn't allow to use natbib package.
How can I remove quotation marks from titles in references? I am using \bibliographystyle{IEEEtranS}.


text:
Q: How to trigger .fail handlers from promise .then handler tl;dr what can I do within a function that is part of a .then() chain to immediately trigger any .fail() handlers? (Using jQuery 1.9.1)
Long version:
I have a bunch of tests and and test-prep tasks to perform, but some are expensive, so I wish to perform them all sequentially. I wrote this:
$.when( gatherEasyData() )            // collect into for test #1
 .then( failIfDataBad )               // test #1

 .then( makeRestCall )                // fetch info for test #2
 .then( extractRestPayload )          // prepare info for test #2
 .then( failIfPayload1Unacceptable )  // test #2, based on REST info

 .then( makeHarderRestCall )          // fetch info for test #3
 .then( extractRestPayload )          // prepare info for test #3
 .then( failIfPayload2Unacceptable )  // test #3, based on expensive REST info

 .then( action1 )                     // success case!

 .fail( action2) ;                    // failure case :(

The idea is that if any test fails, or any of the test-prep work fails, I want to skip the more expensive tasks and jump right to the fail handler.
Also, by relying on then to chain these guys together, none of the actual functions need to be promise-aware; they can focus on whatever contract is appropriate for their task, and they can pass data down the line as needed. E.g.: failIfDataBad (AKA Test #1) will receive a deep hash of config that was created by gatherEasyData, and the function only needs to inspect the hash and return its verdict. So, every function on the list returns data or a boolean.
I've discovered that none of my failure cases actual trigger the .fail. The REST calls are made using $.ajax, and when those come back with HTTP error codes, action 2 is invoked instead of action 1. But none of my custom tests seem capable of short-circuiting the resulting steps.
My question: what must I do within failIfDataBad to cause execution to skip to the .fail handler at the bottom?
Consider that this is the current implementation of failIfDataBad:
function failIfDataBad(data) {
    if(!data) return false; // should trigger .fail
    if(data.prop1 === true) return false; // should trigger .fail

    if(data.prop2 > 500) return false; // should trigger .fail

    return true; // should permit next .then
}

I have tried (without success):

*

*throw

*return false

*not returning

Any help is appreciated.

A: All you have to do is return a rejected promise.
All of your steps should be returning promises if they're doing any asynchronous actions.
var success1 = function () {
    return $.Deferred(function (d){ return d.resolve();}).promise();
};
var success2 = function () {return $.Deferred(function (d){ return d.resolve();}).promise();};
var success3 = function () {return $.Deferred(function (d){ return d.resolve();}).promise();};
var fail = function () {
    return $.Deferred(function (d){ return d.reject();}).promise();
};
var success4 = function () {return $.Deferred(function (d){ return d.resolve();}).promise();};

success1()
    .then(success2)
    .then(success3)
    .then(fail)
    .then(success4)
    .done(function() {
        console.log("Successful. :(");
    })
    .fail(function () {
        console.log("Failure. :)"); // this one happens
    });

success1-4 are simply returning resolved promises while fail returns a rejected promise.
http://jsfiddle.net/43Mr8/