text:
Q: Set Current State of Spring StateMachine I am starting to use Spring Statemachine and I am having some trouble managing the state of my objects.
My Statemachine is of type StateMachine.
My business object, Shipment, has an enum property (state) of type ShipmentState, which should hold the state-machine state of the episode. Here is my desired workflow:

*

*Load a Shipment from the database.

*Set the current state of the Statemachine from the ShipmentState that
is in that Shipment instance.

*Send an event to the Statemachine.

*Get the resultant state from the Statemachine (post event) and set
the ShipmentState in my Shipmentinstance.

*Save the Shipment instance.

The problem is: How do I set the current state of an existing StateMachine?
My current approach is this one: For every event, create a new StateMachine instance (using a StateMachineBuilder) specifying the initial state according to a Shipment instance. For example:
@Service
public class StateMachineServiceImpl implements IStateMachineService {

    @Autowired
    private IShipmentService shipmentService;

    @Override
    public StateMachine<ShipmentState, ShipmentEvent> getShipmentStateMachine(Shipment aShipment) throws Exception {

        Builder<ShipmentState, ShipmentEvent> builder = StateMachineBuilder.builder();

        builder.configureStates().withStates()
            .state(ShipmentState.S1)
            .state(ShipmentState.S2)
            .state(ShipmentState.S3)
            .initial(shipmentService.getState())
            .end(ShipmentState.S4);

        builder.configureTransitions().withExternal().source(ShipmentState.S1).target(ShipmentState.S1)
                .event(ShipmentEvent.S3).action(shipmentService.updateAction()).and().withExternal()
                .source(ShipmentState.S1).target(ShipmentState.S2).event(ShipmentEvent.S3)
                .action(shipmentService.finalizeAction()).and().withExternal().source(ShipmentState.S3)
                .target(ShipmentEvent.S4).action(shipmentService.closeAction()).event(ShipmentEvent.S5);

        return builder.build();
    }

}

What do you think of my approach?

A: There is no issue with the approach. You can reset the state machine to particular state using the below code.
stateMachine.getStateMachineAccessor().doWithAllRegions(access -> access
          .resetStateMachine(new DefaultStateMachineContext<>(state, null, null,null)));

You can pass the arguments to the DefaultStateMachineContext according to your use case.


text:
Q: Multiple inputs and outputs in C++ I have a code that is written in C++17 takes values x and y as inputs and give some value as output.   I want to change it to take as many inputs ( x and y values) and give outputs. What changes needed to be done in the code
what is happening in the code is : with some x and y coordinates it finds the coordinate number.
int main(void) {
    const std::vector<Tile> tiles{ Tile(0),Tile(1),Tile(2),Tile(3) };

    // Test values
      const double  x{ 3700 };  // want to  add multiple entries here
      const double  y{ 11261 };  // want to  add multiple entries here

    // Check cell number
    for (const Tile& tile : tiles) {
        if (const auto [isInTile, cellNumber] = tile.getCellNumber(x, y); isInTile) {
            std::cout << "\nCellnumber: " << cellNumber << "\n:)\n\n\n\n\n\n";

        }
    }

    return 0;
}

I have tried many changes but always end in some error also I am new to c++ my primary language is python.

A: If you want multiple input values, then put x,y into a vector, like you did with tiles:
    // Test values
    const std::vector<std::pair<double, double>> test_values = {
        { 3700, 11261 },
        { 2500, 10000 },
        { 1000, 5000 }
    };

    // Check cell number
    for (const Tile& tile : tiles) {
        for (const auto [x,y] : test_values) {
            if (const auto [isInTile, cellNumber] = tile.getCellNumber(x, y); isInTile) {
                std::cout << "\nCellnumber: " << cellNumber << "\n:)\n\n\n\n\n\n";
            }
        }
    }

redpajama_set_name: RedPajamaStackExchange


text:
Q: Parse JSON to custom 'tree-like' file structure I have a folder/file system of custom classes, where Folders can have childs of either Folders or Files. Files cannot have children. When I have added folders and files, I would like to save the structure to be able to restore it. Right now i store the structure as a JSON string and my problem is how to parse it back to the custom classes.
A JSON string could look like:
{
  "name": "Root",
  "type": "Folder",
  "img": null,
  "checked": false,
  "children": [
    {
      "name": "Folder1",
      "type": "Folder",
      "img": "img/folder.png",
      "checked": false,
      "children": [

      ]
    },
    {
      "name": "Desert.jpg",
      "type": "image/jpeg",
      "img": "img/file.png",
      "checked": false,
      "data": {
        "lastModifiedDate": "2009-07-14T05:32:31.000Z",
        "size": 845941
      }
    }
  ]
}

Where children with type ==='Folder' is of my custom Folder class and type !== 'Folder' is an object of my custom File class.
How should i parse this JSON to be able to create new custom objects and store them in my file structure?
I have tried to do this, but i get stuck at the first level. I'm not that good at recursion which I suppose that I should do.
My code so far that works when there is only files/folders in the root and no subfolders/subfiles
function importJson(json){
    var jsonObj = JSON.parse(json);
    //This line needs to be fixed when/if recursion?
    var currentFolder = rootFolder; //a global variable which is my rootFolder

    for(var i = 0, obj = jsonObj.children; i < obj.length; i++){
        if(obj[i].type === 'Folder'){
            var folder = new Folder(obj[i].name, 'Folder');
            folder.img = obj[i].img;
            currentFolder.add(folder);
            console.log('A folder, check for children?');
        }
        else{
            var file = new File(obj[i].name, obj[i].type);
            file.data = obj[i].data;
            file.img = obj[i].img;
            currentFolder.add(file);
            console.log('a file');
        }
    }
}

A: You will need to use recursion. Have your method accept the parsed JSON as a parameter instead of parsing it in the function, then when you need to check for children in a folder, simply call your method again with the folder you want to parse, in this case obj[i].


text:
Q: How to not escape characters when using pandas styles If I want to add html inside a normal dataframe, I can do
df.to_html(escape=False)

To ensure special characters are not escaped.
On the other hand if I want to use styles, I do
df.style.background_gradient(cmap='Blues').render()

How can I have both?
The render method seem to accept escape=False, but it doesn't do anything.
Additionally, my requirements are such that I would like to:

*

*have the gradient be applied on the original df

*be able to change some individual cells afterwards (specifically, I would like to make some cells clickable by surrounding them with ...
Anyone knows how to do this?
EDIT
Here is an example
import pandas as pd
df = pd.DataFrame([{'i': i*i } for i in range(10)])
df['clickable'] = df['i'].apply(lambda i: f"""Click for {i}""")
df.style.background_gradient(cmap='PuBu')

In the example above, I managed to get the 'clickable' column to be clickable. But I would like the 'i' column to be clickable too, while retaining its style.

A: I might be wrong, but it seems what you are looking for is something like this:
import pandas as pd
df = pd.DataFrame([{'i': i*i } for i in range(10)])
df.style.background_gradient(cmap='PuBu').format("""Click for {0}""", subset=['i'])

This way apply allows you to apply gradients based on values and format allows you to tell styler how you want to render values (everywhere or in specific columns using subset).


text:
Q: How to extend a list by overwriting the common values list1=[{"status":1, "s_count":100}, {"status":2, "s_count":20}]
list2=[{"status":1, "s_count":0}, {"status":3, "s_count":30}]

list1.extend(list2) gives
[{"status":1, "s_count":100}, {"status":2, "s_count":20}, {"status":1,
    "s_count":0}, {"status":3, "s_count":30}]

what I want is,
[{"status":1, "s_count":0}, {"status":2, "s_count":20}, {"status":3, "s_count":30}]

A: 1) Consider using a dictionary instead of a list.
2) If you insist on using a list:
helper = []
for i in range(0,len(list1)):
  for item in list2:
     if item['status'] == list1[i]['status']:
         list1[i]['s_count'] = item['s_count']
         helper.add(item)
for item in helper:
    list2.remove(item)
list1.extend(list2)

This is inefficient, so try to do 1 if possible.


text:
Q: Load panorama from assets folder or URL I have been using Xamarin.GooglePlayServices.Panorama 60.1142.0-rc1 package in order to show a simple fullscreen panorama activity. The following code successfuly starts panorama activity from fragment:
public async void OnConnected(Bundle connectionHint)
{
    Android.Net.Uri uri = Android.Net.Uri.Parse("android.resource://" + Activity.PackageName + "/" + Resource.Raw.pano1);
    var panoramaResult = await Android.Gms.Panorama.PanoramaClass.PanoramaApi.LoadPanoramaInfoAsync( googleApiClient, uri);

    if(panoramaResult.Status.IsSuccess)
    {
        if(panoramaResult.ViewerIntent != null)
        {
            StartActivity(panoramaResult.ViewerIntent);
        }
        else
        {
            Activity.RunOnUiThread(() => {
                Toast.MakeText(Activity, "WTF?!", ToastLength.Short).Show();
            });
        }
    }
}

However, if i try to load the same panorama jpg from assets or URL, like this:
Android.Net.Uri uri = Android.Net.Uri.Parse("file:///android_asset/panorama/pano1.jpg");

or like this:
Android.Net.Uri uri = Android.Net.Uri.Parse("https://raw.githubusercontent.com/xzs424/RBCPrototypeChallenge/master/PanoramaSampleActivity/res/raw/pano1.jpg");

panoramaResult.ViewerIntent is null, and there is no activity to start. Documentation says that ViewerIntent should be null if image is not Google panorama, but all three parts of the code use the same image, only it's in different places. So, is there a way to load panorama image from any place other than raw folder in resources? Note that I also tried latest stable Xamarin.GooglePlayServices.Panorama, which at the time of writing was 42.1021.1, without luck.


text:
Q: Solving advanced complex inequalities $|z − 2| + |z + 2| ≤ 2$
I've tried solving it like this:
$|x+iy - 2| + |x+iy + 2| \le 2\\
|x - 2 + iy| + |x + 2 + iy| \le 2\\
\sqrt{(x-2)^2+(y)^2} + \sqrt{(x+2)^2+(y)^2} \le 2\\
\sqrt{(x-2)^2+(y)^2} \le 2 - \sqrt{(x+2)^2+(y)^2}\\
\sqrt{x^2 - 4x + 4 + y^2} \le 2 - \sqrt{x^2 + 4x + 4 + y^2}\\
x^2 - 4x +4 + y^2 \le 4 - 4\sqrt{x^2 + 4x + 4 + y^2} + x^2 + 4x + 4 + y^2\\
-8x \le 4 - 4\sqrt{x^2 + 4x + 4 + y^2}\\
-2x \le 1 - \sqrt{x^2 + 4x + 4 + y^2}\\
-2x - 1\le\sqrt{x^2 + 4x + 4 + y^2}\\
4x^2+4x + 1 \le x^2 + 4x + 4 + y^2\\
3x^2-y^2 \le 3$
Which seems to be incorrect, what am I doing incorrectly in my procedure? Is my logic correct?

A: Solve the inequality geometrically.
Since $|z-w|$ is the distance between the points representing $z$ and $w$, the inequality $$|z − 2| + |z + 2| ≤ 2$$ can be interpreted as:
The sum of distances from $z$ to $2$ and from $z$ to $-2$ is smaller than $2.$
Put on $x$-axis $-2$ and $2$ and various points $z$ in the plane .... wherever is $z\in \mathbb{C},$ the sum of distances to $2$ and $-2$ is at least $4,$ obtained when $z\in [-2,2].$


text:
Q: mysql gem issue on bundle install I have a rails app. When I do bundle install, I am getting

Make sure that gem install mysql2 -v '0.4.4' succeeds before bundling.

I am getting below error

E: Unable to locate package libmysqlclient-devgem E: Unable to locate
  package install E: Unable to locate package mysql2

When I do sudo apt-get install libmysqlclient-dev
I get below error.

The following packages have unmet dependencies: libmysqlclient-dev :
  Depends: libmysqlclient18 (= 5.5.49-0ubuntu0.14.04.1) but
  10.0.25+maria-1~trusty is to be installed E: Unable to correct problems, you have held broken packages.

I am not sure what's wrong. Please help.


text:
Q: CIDR range for --master-ipv4-cidr in GKE private cluster Note:
There is an existing stackoverflow post which discuss about --master-ipv4-cidr, but it doesn't discuss about the topic which I am asking in the question.
Please don't mark this as duplicate.
Problem description
I am creating private clusters in GKE and got confused with the --master-ipv4-cidr range. This link, mentions that --master-ipv4-cidr needed CIDR in RFC 1918 range.
"--master-ipv4-cidr 172.16.0.0/28 specifies an RFC 1918 range for the master. This setting is permanent for this cluster."

Since valid RFC 1918 ranges are
 10.0.0.0        -   10.255.255.255  (10/8 prefix)
 172.16.0.0      -   172.31.255.255  (172.16/12 prefix)
 192.168.0.0     -   192.168.255.255 (192.168/16 prefix)

So I tried to create private cluster with following values:
  --master-ipv4-cidr "172.17.0.0/28"
  --cluster-ipv4-cidr "172.16.128.0/17"
  --services-ipv4-cidr "192.168.1.0/24"

Since 172.17.0.0/28 is also from RFC 1918 range I thought that cluster will come up. But it resulted in error as mentioned below
172.17.0.0/16 is a reserved GKE IP range and cannot be used for the 'master-ipv4-cidr'.
Then I changed --master-ipv4-cidr to example given in link and cluster created successfully. Below are the successful case values.
  --master-ipv4-cidr "172.16.0.16/28"
  --cluster-ipv4-cidr "172.16.128.0/17"
  --services-ipv4-cidr "192.168.1.0/24"

Now my question are

*

*Does --master-ipv4-cidr expects CIDR in 172.16.0.0/28 only and it cannot accept any other range from 10/8 or 192.168/16 or any other range for example 172.17.0.0/28 which I provided earlier?

*With an existing cluster  --master-ipv4-cidr  of 172.16.0.0/28, if I create another cluster in same VPC what should be the --master-ipv4-cidr value?
Because creating another cluster with same --master-ipv4-cidr 172.16.0.0/28 fails with below error which is quite expected.

Google Compute Engine: An IP range in the peer network (172.16.0.16/28) overlaps with an IP range (172.16.0.16/28) in an active peer (gke-c2a126697c6fee94c2b8-1e18-f2ff-peer) of the local network.
  and thats expected because 172.16.0.16/28 already exist in an existing cluster in same vpc to which its getting peered.

*I am thinking to manage my cluster pods from 172.16.0.0 range and services from 192.168.0.0 range of RFC 1918 and not use 10/8 network to avoid conflict with existing office network.
Since 172.16/12 is a superset of 172.16.0.0/28. How do you make sure that they are separated from each other?

Apologies for asking many question here, but I am just trying to keep the entire context at same place.

A: I will answer your questions as follows:

*

*172.17.0.0 cannot be used because this is for Docker.

*You can use any of the following CIDRs 10.0.0.0 – 10.255.255.255, 172.16.0.0 – 172.31.255.255, 192.168.0.0 – 192.168.255.255 except 172.16 and 172.17. Also this must be /28

*Supersets or Subnets are not possible therefore you will have to choose a different CIDR range
You can read about the Restrictions and Limitations in the following Google Public doc


text:
Q: Search Issues Green Star On my SharePoint I have items in waterfall type order the items come in are approved or rejected and moved to a Completed or Rejected folder/library. All seems to be working well. However, Ive noticed that some of the items in the Completed folder/library have green stars next to them, to me this indicates they are new or have been updated in someway. The issue Im running into, is that when I attempt to search for these items it gives me a link to the main library that they are in, but doesnt show the link to the completed folder/library, and when I click on the link it gives me a page that says something went wrong. I can search for other items without the green star in the Completed folder/library, just the search for the ones with the star causes this issue. Please help if possible.

A: Well, if the items move to a new list or library, then they are new to that list or library, so having the green "new" star is not surprising, it is what we would expect.  As far as the search goes, it sounds like the search crawl is not happening soon enough after the items get moved, so the search index is not updated with the items new location, which is why it gives you the old location.  And then of course when you try to go to the old location, the item is no longer there, and so therefore "something went wrong" when trying to access the item in the old location.


text:
Q: What is the English verb/phrase/expression for cheating customers with an inaccurate scale? In the town where I live, many street vendors actively cheat customers by using an inaccurate scale.  As a result, people receive less than what they ought to.
For example, if you buy five apples, which actually weigh 2 kg on a standard scale, the false readout might show 3 kg or higher. As a result you pay for 3 kg worth of apples, but you get only 2 kg or even less.
It's called "扼称" in my mother tongue, which means "to play trick with a tampered scale to take advantage of customers". An example:

Jack was back home from shopping at the market where he just bought several apples that weighed 3 kg. But when weighing it with his own scale, it showed only 2 kg. Realizing that he had been cheated, he told his brother: "I just got ____ by that sneaky vendor! I'm going after him now."

Is there an idiomatic verb/phrase/expression for this in English? (It doesn't necessarily fit the sentence structure, that's just a suggestion.)
Edit: Someone suggested 'rip off', is that a idiomatic phrase to describe that behavior?

A: Fleecing is a word that is often used in journalism.
Fleece:

Obtain a great deal of money from (someone), typically by overcharging or swindling them.

e.g. The city's cab drivers are notorious for fixing fares and fleecing tourists.
Your sentence could be

I just got fleeced by that sneaky vendor! I'm going after him now.

A: I would use 'Chiseling' here. It's not overly common depending on your part of the world but it is one word and accurate.

to cheat or swindle (someone): He chiseled me out of fifty dollars.

or

to get (something) by cheating or trickery: He chiseled fifty dollars
  out of me.

This is normally used in the context of slight cheating not outright cheating.

A: All of these common English phrases could express your situation:

*

*Pull a fast one

*

*Usage over time

*Use Example

*(1)Take someone for a ride / (2)take him for a ride / (3)take her for a ride / (4)take them for a ride

*

*(1)Usage over time / (2)Usage over time / (3)Usage over time / (4)Usage over time

*Use Example

*(1)Short-change / (2)short change

*

*(1)Usage over time / (2)Usage over time; be careful of this one's earlier entries; 1888 was the earliest I saw where it's used in this context

*Use Example

*Fudge the numbers

*

*Usage over time

*Use Example

*Swindled

*

*Usage over time

*Use Example

In regards to thumb on the scale, I won't argue its validity or general use, only state that I have not observed its usage in conversation to any recollection. That being said, I think it is self-evident when used and requires no further explanation, nor a history of usage to be considered valid.
All of these alternatives provided above are common in conversational English in America. Fudge the numbers is probably the least used in a modern context but should still be understood by native speakers.

For American English, I can also vouch for:
fleeced, by Himabindu Boddupall
duped, by justin
shorted, by Yorik
Dupe can often but not exclusively hold the connotation that the deception was a substitution.

A: A more generic term that covers situations of minor swindling is diddle:

*

*informal with object Cheat or swindle (someone) so as to deprive them of something.
  'he thought he'd been diddled out of his change'
1.1 Deliberately falsify.
  'he diddled his income tax returns'
-- oxforddictionaries.com

Example: Many of my local street vendors diddle the scales.

A: I'm not sure if this is exactly right, but there is the expression "to put your thumb on the scale", meaning that you manually push the scale down while weighing something, to make it seem heavier than it actually is.
The meaning has broadened out from the original "grocer's shop" context to apply to any situation where someone in charge of making a measurement deliberately makes the measurement incorrect, in order to gain some kind of advantage.
http://idioms.thefreedictionary.com/thumb+on+the+scale

*

*A method of deception or manipulation that creates an unfair advantage for the swindler, likened to a merchant holding a thumb on
the scale when weighing goods for sale, therefore increasing the
weight and price.
You have to suspect that the casinos have their thumb on the scale when it comes to the slot machines. There's no way you're getting
fair odds.

A: The first term that comes to my mind is "jipped" being synonymous with "cheated". Unfortunately a quick bit of research revealed that the more common spelling is "gypped" and that the word is a slur against gypsies and the stereotyped tendency to make easy money off of gullible people.
Not knowing the proper spelling, I never made the connection.
www.dictionary.com
verb (used with or without object), gypped, gypping.
1.Informal: Sometimes Offensive. to defraud or rob by some sharp practice; swindle; cheat.
noun
2.Informal: Sometimes Offensive. a swindle or fraud.
3.Also, gypper [jip-er], gypster. Informal: Sometimes Offensive. a swindler or cheat.
Usage note:
Gyp in the meanings "to swindle" or "a person who swindles" is sometimes perceived as insulting to or by Gypsies, since it stereotypes them as swindlers. However, gyp has apparently never been used as a deliberate ethnic slur, and many people are unaware that it is derived from Gypsy.
I do think it has been used for the type of dishonest transaction described by the OP:
"Jack was back home from shopping at the market where he just bought several apples that weighed 3 kg. But when weighing it with his own scale, it showed only 2 kg. Realizing that he had been cheated, he told his brother: "I just got jipped by that sneaky vendor! I'm going after him now."
(I'm sticking with my original spelling in order to disassociate from the stereotype)

A: One term that comes to mind is skimming.
The meaning references taking the top layer off something, as in skimmed milk, but would be used in this context to refer to swindling someone by withholding a small amount from what you owe them or not giving them quite as much product as they are paying for.
The most obvious example I can think of for it's use is the kind of financial crime as depicted in the original Superman movie, where the bad guy made his fortune by intercepting bank interest payments and diverting a penny from everyone's account into his own. The theft was barely noticeable on a individual level, but made a large amount of money for the thief.

A: The first word that came to my head was "duping".
dupe(verb)
gerund or present participle: duping
deceive; trick.
Ex: "the newspaper was duped into publishing an untrue story"

A: While this one doesn't necessarily imply an inaccurate scale, it implies the transaction is heavily weighted in one sides favor. If this happened to me, I might say the scales were rigged. Example

The pumps at that gas station are rigged, you don't get your money's worth.

This can also be used in other unfair situations

During his campaign the president posited that the election would rigged against him

Rigged (verb) past tense: rigged; past participle: rigged

*

*manage or conduct (something) fraudulently so as to produce a result or situation that is advantageous to a particular person.

*cause an artificial rise or fall in prices in (a market, especially the stock market) with a view to personal profit.

A: How about to give "Short measure"?
Not specifically weight, you see the term used for any deliberately fiddled measurement (Volume, weight, length....).
The OED gives a definition 1 as :

An amount, especially of alcohol, less than that which is declared or
  paid for.
  'coal users in North Yorkshire are being sold short
  measures' 'the most serious crime is short measure on a pint'

A: Short-change:

verb [ T ] also shortchange
1. COMMERCE to give someone back less money than they are owed when they are buying something from you:
The check-out girl short-changed her.

  2. to treat someone unfairly by giving them less than they deserve:
The case alleges that the company shortchanged female employees on opportunities for promotion.

A: There are a few idioms that talk about this, like putting your thumb on the scale — biasing a measurement or a situation in your favor.
However, since you asked for a single word, then more generally the term for this would be swindling or cheating your customers.

A: My grandmother warned of being sold "a pound of thumb" when buying five pounds of meat. I watched the butcher carefully and never saw him doing that. Perhaps my grandmother had better eyes than I did.

A: You might refer to it as using false weights.

false weight noun
a weight as measured on a shop scales which is wrong and so cheats customers
- investorwords.com

This concept can be traced back at least to Biblical times. The following contrasts a false balance with a just weight:

A false balance is an abomination to the Lord, but a just weight is his delight.
- Proverbs 11:1, ESV

Here's an example of the term false weight used in the context of a maths test. The setting indicates that the term is well-established.

A shopkeeper cheats to the extent of 10% while buying and selling, by using false weights. His total gain ...
- Sawaal

A:
Shorted

Merriam Webster

short [transitive verb] 2:  shortchange, cheat

This is a drop-and-go term for your example: "I just got shorted by that sneaky vendor!"
For attestations "in the wild" see for example "shorted my order"

A: To "give short measure" and to "put a thumb on the scale" and to "short change" are all old idioms that can be used literally or figuratively in describing petty commercial frauds..
"Rip off" is a modern idiom that means to "cheat" or to "defraud" but is not specific in how the cheating/defrauding was accomplished.

A: To rig an election; dictionary.com fails pretty hard core on this one. You could also say one is fudging the numbers though that is more of an idiom.

A:
Jack was back home from shopping at the market where he just bought
several apples that weighed 3 kg. But when weighing it with his own
scale, it showed only 2 kg. Realizing that he had been cheated, he
told his brother: "I just got ____ by that sneaky vendor! I'm going
after him now."

To answer the original question!
Here are some words to put in the gap.
scammed
ripped off
swindled
overcharged
Note that these don't specifically refer to weight but, if your brother sees you weighing goods and then you say any of the above, your brother will know from the context what you mean!


text:
Q: C++: Inherit class from template parameter I recently saw the following C++ code-snippet
template <class B>
class A : public B
{
   ...
};

and I am wondering in which setting such a design is good practice?
The way I understand it, is that having the superclass as a template parameter allows users of A to choose a superclass when instantiating an object of A.
But if this is the case, wouldn't it be better to have a common superclass C for all the classes (B) which are used as the template argument and have A extend C ?

A: Sounds like a good candidate for a wrapper class:
class base {
public:
  virtual void f() = 0;
};

class d1 : public base {
public:
  virtual void f() override { ... };
};

class d2 : public base {
public:
  virtual void f() override { ... };
};

template <typename T>
class wrapper : public T {
public:
  virtual void f() override {
    pre_op();
    T::f();
    post_op();
  }

private:
  void pre_op() { ... }
  void post_op() { ... }
}

int main(int, char**) {
  wrapper<d1> w1;
}

For example, the wrapper class can provide synchronized access to the derived classes.

A: It's often used to realize static polymorphism.
Use cases are:

*

*Policy-based design

*Curiously recurring template pattern

*Barton–Nackman trick
In general you have the benefits from dynamic polymorphism, without the extra runtime costs of virtual functions. But it's only useful if the concrete type can be determined at compile time.

A: It is used frequently in the so called "policy-based" design, i.e. you add characteristics to a base class by composition with desired derived classes, see "Modern C++ Design: Generic Programming and Design Patterns Applied" by Andrei Alexandrescu. The instantiated template class from which you derive is called the "policy". Such a design is sometimes better than inheritance, as it allows to combine policies and avoid a combinatorial explosion inevitable in the inheritance-based model.
See for example the following simple code, where RED and BLUE are drawing policies for a Pen:
#include <iostream>
#include <string>

struct RED
{
    std::string getColor()
    {
        return "RED";
    }
};

struct BLUE
{
    std::string getColor()
    {
        return "BLUE";
    }
};

template <typename PolicyClass>
class Pencil: public PolicyClass
{
public:
    void Draw()
    {
        std::cout << "I draw with the color " << PolicyClass::getColor() << std::endl;
    }
};

int main()
{
    Pencil<RED> red_pencil; // Drawing with RED
    red_pencil.Draw();
    Pencil<BLUE> blue_pencil; // Different behaviour now
    blue_pencil.Draw();

    return 0;
}

Can read a bit more here:
http://en.wikipedia.org/wiki/Policy-based_design

A: A place where I use this style was where I need to implement a generic graph library which is both easy to use and also easy to maintain
After a while I came with this design :
ABstract class for GraphContainer,Edge,Node  :
template < class T1,class T2>
class  GraphAbstractContainer
{
public:
    using Node = T1;
    using Edge = T2;
    virtual std::list<Node> getConnectedNodes(const Node& node)const = 0;
    virtual Node addNode(const Node&) = 0;
    //...
};

class  GraphAbstracthNode
{
public:
    virtual uint32_t getId() const = 0;
    virtual void setID(uint32_t id)=0;
    //..
};

template<class T>
class  GraphAbstractEdge
{
public:
    using Node = T;
    //GraphAbstractEdge(){}
    virtual Node  firstNode() const = 0;
    virtual Node   secondNode() const = 0;
    virtual void  setFirstNode(const Node& node)  = 0;
    virtual void  setSecondNode(const Node& node) = 0;
    //...

};

Then I add Adj_List and  Adj Matrix implementation by inheriting directly from template parametrs .
for example My Adj List classess looks some thing like this :
template<class T1 = GraphAbstractContainer<GraphAdjNode,
                   GraphAdjEdge>>
class  GraphAdjListContainer : public T1
{
public:
    using Node = typename T1::Node;
    using Edge = typename T1::Edge;

    //return connected Nodes
    virtual std::list<Node> getConnectedNodes(const Node& node) const
    {
        //..
    }
    //..
  };

};

template<class T>
class  GraphAdjNode : public T
{
public:
    //implementing abstract class methods...
};

template<class T>
class  GraphAdjEdge : public T
{
public:
   //...

};

And also My Graph class inherit directly from template too :
template<class GraphContainer=GraphAdjListContainer<>>
    class   Graph :public  GraphContainer
    {
    public:
        using Node = typename GraphContainer::Node;
        using Edge = typename GraphContainer::Edge;
         //...

}

An advantage for this design pattern is you can simply change the whole class  underlying's stuffs by just inherit from abstract classes and fill the template parametrs.
for example  I define Trie data structure by simply doing this :
class TrieNode :public GraphAdjNode
{
public:
    //...
    std::string word_;
};

class Trie
{
public:
    using Graph = Graph < ecv::GraphAdjListContainer<TrieNode, ecv::GraphAdjListEdge<TrieNode>>>;
    using Node =  Graph::Node;
    using Edge =  Graph::Edge;
    void addWord(wstring word);
    //...
private:
    Graph graph_;
}


text: Q: In SCons, what is the advantage of using Configure() to set variables instead of Environment? In SCons examples, CPPPATH etc. are often set in Configure(). Is there an advantage to doing it there instead of just setting it on Environment() directly?


text:
Q: Stop Pulsate jQuery Effect I am currently using the kilianvalkhof jQUERY pulsate effet.
http://kilianvalkhof.com/jquerypulsate/
My aim is to start the effect on a div when the user clicks on a menu item.
When the user clicks on a different menu item I want the currant active pulsate effect to stop and a new one to start on a different DIV.
I can't seem to find a way to stop the effect.

       <ui>

Name 1

Name 2

      </ui>


text:
Q: Most efficient way to do 22 different builds I'm getting close to finishing my first relatively simple Xcode project (a custom installer) and I need to do 22 builds. Yes that wasn't a typo! What's different on each build is the PRODUCT_NAME, a source file in the bundle Resources folder and a variable that says whether the software is a trial version or not.
From what I've read so far, duplicating the existing target seems to be the way to do it when there are only a couple of builds but is that still true for 22? It seems like an awful lot of work. What I had in mind was a way to change the PRODUCT_NAME, source files that are copied into the Resources folder and the trial mode boolean. But I'm stuck.
thanks

A: My gut response is that 22 different builds that only differ by a single source file is wrong...
Can't the problem be turned around? Include all 22 different versions of your applicaiton in one build and supply 22 different key/license files in the .app folder each unlocking one of the 22 versions.

A: One way that I've accomplished this in the past is to use Localization.  When you use the NSLocalizedString flavored macros, some of them have the ability to specify a tableName (ie, a different strings file than the default).  Then whenever I need a differently branded build, I just create a new .strings file with the appropriate key-value pairs.
I then have a build target that builds the code with the default values, and a second target that takes the built code and copies the appropriate .strings file into its proper location.  This works pretty well and has allowed us to manage many different build flavors.

A: I'd probably write a script that used a .xcodeproj template and sed to generate all the necessary combinations.

A: You might want to check out CMake for maintaining this large number of builds.
Scripting can certainly get the job done, but once the project grows to a significant number of files, or if you find yourself changing the number of builds, changing the script could get hairy.  CMake will let you organize those scripts, so it's at least a bit easier to do the modifications in the future.


text:
Q: XMLELEMENT() function not recognize the value of variable as tag name I am using XMLELEMENT(tagname,value) in the SELECT query. it is not recognize the variable's values. instead of this, it s taking variable name as tag-name.
//ex
l_0_l   := t_array(l_index) || '-ANI-II'; -- runtime value is "A-ANI-II"

SELECT (XMLELEMENT(l_ii, NULL) ||'')
  INTO l_temp
  FROM dual;

dbms_output.put_line(l_temp );

expected output :<A-ANI-II/>
acutal output :<L_II/>

My Question like : How do I supply the tag-name using the variable at runtime?

A: Thanks whoever tryied solution for this question.
Finally, I got resolution for my problem.
"evalname()" has resolved my problem. this method is returning the value of that variable to XMLELEMENT().
SELECT (XMLELEMENT(evalname(l_ii), NULL) ||'')
  INTO l_temp
  FROM dual;

Now, I am getting output like :<A-ANI-II/>


text:
Q: babun won't run python3 on win10 I am building a new Win10 machine.  I have babun installed, and im trying to get python3 running.  Problem is it won't execute.
$ python2 --version
Python 2.7.8
$ python3 --version
$

any ideas what would cause this?  or how to debug it?
output of debugging.  It looks like everything is noise, but im not sure.
[506] user@nsa_surveillance_01433:~ $ strace /usr/bin/python3 --version
strace.exe: error creating process C:\Users\user\.babun\cygwin\bin\python3, (error 5)
[507] user@nsa_surveillance_01433:~ $ cygcheck python3
cygcheck: track_down: could not find api-ms-win-core-rtlsupport-l1-2-0.dll
cygcheck: track_down: could not find api-ms-win-eventing-provider-l1-1-0.dll
cygcheck: track_down: could not find api-ms-win-core-processthreads-l1-1-3.dll
cygcheck: track_down: could not find api-ms-win-core-processthreads-l1-1-2.dll
cygcheck: track_down: could not find api-ms-win-core-registry-l1-1-0.dll
cygcheck: track_down: could not find api-ms-win-core-heap-l1-2-0.dll
cygcheck: track_down: could not find api-ms-win-core-heap-l2-1-0.dll
cygcheck: track_down: could not find api-ms-win-core-memory-l1-1-2.dll
cygcheck: track_down: could not find api-ms-win-core-enclave-l1-1-0.dll
cygcheck: track_down: could not find api-ms-win-core-handle-l1-1-0.dll
cygcheck: track_down: could not find api-ms-win-core-synch-l1-2-0.dll
cygcheck: track_down: could not find api-ms-win-core-synch-l1-2-1.dll
cygcheck: track_down: could not find api-ms-win-core-file-l1-2-1.dll
cygcheck: track_down: could not find api-ms-win-core-file-l1-2-2.dll
cygcheck: track_down: could not find api-ms-win-core-delayload-l1-1-1.dll
cygcheck: track_down: could not find api-ms-win-core-io-l1-1-1.dll
cygcheck: track_down: could not find api-ms-win-core-job-l1-1-0.dll
cygcheck: track_down: could not find api-ms-win-core-threadpool-legacy-l1-1-0.dll
cygcheck: track_down: could not find api-ms-win-core-threadpool-private-l1-1-0.dll
cygcheck: track_down: could not find api-ms-win-core-libraryloader-l1-2-2.dll
cygcheck: track_down: could not find api-ms-win-core-libraryloader-l1-2-0.dll
cygcheck: track_down: could not find api-ms-win-core-libraryloader-l2-1-0.dll
cygcheck: track_down: could not find api-ms-win-core-namedpipe-l1-2-2.dll
cygcheck: track_down: could not find api-ms-win-core-namedpipe-l1-2-0.dll
cygcheck: track_down: could not find api-ms-win-core-datetime-l1-1-1.dll
cygcheck: track_down: could not find api-ms-win-core-datetime-l1-1-2.dll
cygcheck: track_down: could not find api-ms-win-core-sysinfo-l1-2-1.dll
cygcheck: track_down: could not find api-ms-win-core-sysinfo-l1-2-3.dll
cygcheck: track_down: could not find api-ms-win-core-timezone-l1-1-0.dll
cygcheck: track_down: could not find api-ms-win-core-localization-l1-2-1.dll
cygcheck: track_down: could not find api-ms-win-core-localization-private-l1-1-0.dll
cygcheck: track_down: could not find api-ms-win-core-processsnapshot-l1-1-0.dll
cygcheck: track_down: could not find api-ms-win-core-processenvironment-l1-2-0.dll
cygcheck: track_down: could not find api-ms-win-core-string-l1-1-0.dll
cygcheck: track_down: could not find api-ms-win-core-debug-l1-1-1.dll
cygcheck: track_down: could not find api-ms-win-core-errorhandling-l1-1-1.dll
cygcheck: track_down: could not find api-ms-win-core-errorhandling-l1-1-3.dll
cygcheck: track_down: could not find api-ms-win-core-fibers-l1-1-1.dll
cygcheck: track_down: could not find api-ms-win-core-profile-l1-1-0.dll
cygcheck: track_down: could not find api-ms-win-security-base-l1-2-0.dll
cygcheck: track_down: could not find api-ms-win-core-comm-l1-1-0.dll
cygcheck: track_down: could not find api-ms-win-core-wow64-l1-1-1.dll
cygcheck: track_down: could not find api-ms-win-core-wow64-l1-1-0.dll
cygcheck: track_down: could not find api-ms-win-core-realtime-l1-1-0.dll
cygcheck: track_down: could not find api-ms-win-core-processtopology-l1-2-0.dll
cygcheck: track_down: could not find api-ms-win-core-namespace-l1-1-0.dll
cygcheck: track_down: could not find api-ms-win-core-file-l2-1-2.dll
cygcheck: track_down: could not find api-ms-win-core-file-l2-1-1.dll
cygcheck: track_down: could not find api-ms-win-core-xstate-l2-1-0.dll
cygcheck: track_down: could not find api-ms-win-core-localization-l2-1-0.dll
cygcheck: track_down: could not find api-ms-win-core-normalization-l1-1-0.dll
cygcheck: track_down: could not find api-ms-win-core-fibers-l2-1-1.dll
cygcheck: track_down: could not find api-ms-win-core-sidebyside-l1-1-0.dll
cygcheck: track_down: could not find api-ms-win-core-appcompat-l1-1-1.dll
cygcheck: track_down: could not find api-ms-win-coreFound: C:\Users\user\.babun\cygwin\bin\python3
Found: C:\Users\user\.babun\cygwin\bin\python3
 -> C:\Users\user\.babun\cygwin\bin\python3.6m.exe
C:\Users\user\.babun\cygwin\bin\python3.6m.exe
  C:\Users\user\.babun\cygwin\bin\libpython3.6m.dll
    C:\Users\user\.babun\cygwin\bin\cygwin1.dll
      C:\windows\system32\KERNEL32.dll
        C:\windows\system32\ntdll.dll
        C:\windows\system32\KERNELBASE.dll
    C:\Users\user\.babun\cygwin\bin\cygintl-8.dll
      C:\Users\user\.babun\cygwin\bin\cygiconv-2.dll
    C:\Users\user\.babun\cygwin\bin\cyggcc_s-1.dll
-windowserrorreporting-l1-1-0.dll
cygcheck: track_down: could not find api-ms-win-core-console-l1-1-0.dll
cygcheck: track_down: could not find api-ms-win-core-console-l2-1-0.dll
cygcheck: track_down: could not find api-ms-win-core-psapi-l1-1-0.dll
cygcheck: track_down: could not find api-ms-win-core-psapi-ansi-l1-1-0.dll
cygcheck: track_down: could not find api-ms-win-security-appcontainer-l1-1-0.dll
cygcheck: track_down: could not find api-ms-win-eventing-provider-l1-1-0.dll


text:
Q: webkit animation not working, # before @ in css The site where I want my animation to work adds #user-space before any of my  tags. So, my animation looks like this:
   #user-space @-webkit-keyframes animation-name {
 from {
   style definition ["Before"-state]
 }
 to {
   style definition ["After"-state]
 }

And that #user-space declaration is breaking the css statement and animation is not working. Is there any way, to do that otherwise? For exaple put my keyframes insine      -webkit-animation: animation-name 1.1s ease infinite; like
webkit-animation:  from {
       style definition ["Before"-state]
     }
     to {
       style definition ["After"-state]
     } 1.1s ease infinite; like

A: The solution I see is to get around your problem and do it with javascript.
Simply add a new style in your html file (in the header) and add the @-webkit-keyframes animation inside.
There is a thread which explains it well (see accepted solution): Set the webkit-keyframes from/to parameter with JavaScript


text:
Q: How to upload modified file without reloading website I have a case as follow:
Step 1: Open pop-up, upload file -> Success.
Step 2: Edit file just uploaded.
Step 3: without reload website, reopen pop-up.
Step 4: select file just edited to upload.
Expected result: Upload success.
Actual result  : upload error: Data format of the uploaded file is not EXCEL file.

How i can fix it??
This is my code
Code js
    function handlerUploadFile() {
      var form = $(''#uploadFile_action')[@];
      var data = new FormData(form);
      loading_ajax();
      $.ajax({
            type: "POST",
            enctype: 'multipart / form - data ',
            url: '../sac0@12/uploadFile.action',
            data: data,
            processData: false,
            contentType: false,
            cache: false,
            timeout: 620000,
            success: function(data, status, xhr) {
              close_loading_ajax(
              };
              var messageld = "";
              var ct = xhr.getResponseHeader('content - type ') || °";
                if (ct.indexOf('html') > -1) {
                  showNotifyDialog("fileNotFormatExcel");
                  return; +
                  if (ct.indexOf('json') > -1) {
                    var obj = JSON.parse(data);
                    if (obj.result == "SUCCESS") {
                      showNotifyDialog("fileUploadSuccess") $("#myModalUpload").css("
                        display", "none ")};
                        $('#itemDetails')
                      }.empty(); loadContent(limit, offset, transactionId, scrollTop);
                    }
                    else {
                      if (obj.code == "EA-0003") {
                        messageId = "EA-0003";
                        contentConfirm = mesSystem[messageId];
                        alert(contentConfirm);
                      } else if (obj.code == "ERROR_PLT_ID_LENGTH") {
                        messageId = "ERROR_PLT_ID_LENGTH";
                        contentConfirm = mesSystem[messageId];
                        alert(contentConfirm);
                      } else {
                        alert("Data format of the uploaded file is not correct.");
                      }
                    }
                  }
                },
                error: function(e) {
                  close_loading_ajax();
                  alert("Data format of the uploaded file is not EXCEL file.");
                }
              });
          }

code jsp
<form id="uploadFile_action" name="uploadFile_action" method="post" enctype="multipart/form-data">

Upload File:

<input type="hidden" name="confirm" value="false" id="uploadFile_action_confirm" />
<input type="file" name="file" accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel" class="input-file" value="" id="uploadFile_action_file" />
<button tabindex="0" for="my-file" class="input-file-trigger" value="Browse">Browse</button>

<input type="submit" name="upload" class="btn btn-primary btn-danger textWhite" id="uploadFile_action_0" style="height: 34px" value="Upload" />
<input type="button" value="Back" class="cancelButton">

<s:hidden name="transactionId"></s:hidden>
</form>


text:
Q: Text to be sent as a clickable link to telegram from Windows device I am trying to send a text message to telegram using python. Text message is basically a Windows command:
mstsc.exe /v:10.20.30.40

I want this text to act a one-click openable text from telegram. Is this possible?
I tried and it is appearing as a broken link. Example given below.

A: No, this is not possible, Telegram Bot API only support a small set of urls, like t.me and the normal http(s)://, any custom format can't be passed a clickable link.
Source: (Still) Can't find any source in the Telegram docs, however, I've asked this a few months ago to the Telegram Bot Support, I wanted to send a clickable tel: link, they replied with:

Hi, at the moment only http/https links will be supported.

The closest you can come to mimic this, is by using backticks to make it copy to your clipboard when you press it:
How to make that when you click on the text it was copied pytelegrambotapi


text:
Q: Google Appengine - How to Tail Logs in Terminal? I am looking for a similar functionality like:
heroku logs --tail
but for Google Appengine. Does anyone know of its existence?

A: gcloud app logs tail is now in generally available!
https://cloud.google.com/sdk/gcloud/reference/app/logs/tail

A: Have you seen gcloud preview app logs read?
https://cloud.google.com/sdk/gcloud/reference/preview/app/logs/


text:
Q: Fourier transform of an integral I am preparing for an exam. I found this problem:

I am trying to use the properties then use a pre-transformed function from the table but I couldn't find one.
I saw a solution on the web:

I think he has a mistake since he forgot the \$t\$'s (each \$\tau\$ should be \$t\$).
Is he right or am I missing something?

A: Tsin(aT+b) cannot be integrated from T=minus infinity, because the integral function contains summed term Tcos(aT+b). It doesn't get eliminated.  It's undefined (as a limit value) at T=minus infinite. So, the formula of x(t) doesn't define a function. The starting point is impossible and the rest is meaningless.
It's possible that by applying different Fourier transform rules one gets a formula which contains delta function or its higher powers. I haven't tried it. It seems to need something like a derivative of the delta function which is two gears beyond classical analysis. The delta function alone becomes from the point frequency. Its derivative becomes from multiplying the sine by T in Tsin(aT+B). It's presented in Fourier transform collections like this:

The formula is taken from this website http://fourier.eng.hmc.edu/e101/lectures/handout3/node2.html
Another formula for the symbol game can be found from the same collection. It's this:


text:
Q: Bounding this integral I'm trying to get a  lower bound for $$\int_0^{\pi n} \left|\frac{\sin x}{x}\right|dx$$ and if I can show that it's greater than $$\sum_{k=1}^{n}\frac{1}{k\pi}\int_0^\pi\sin x\, dx$$ then I can conclude what I want. What confuses me is the denominator. This is likely very simple and I am missing something "obvious."

A: If you replace the denominator with something bigger, then you get something smaller (since everything in your problem is positive).
So for instance, you could replace $x$ with $k \pi$ whenever $(k-1) \pi \leq x \leq k \pi$, for $k=1,2,\dots,n$. Then you get a lower bound of
$$\sum_{k=1}^n \int_{k \pi}^{(k+1) \pi} \frac{|\sin(x)|}{k \pi} dx = \sum_{k=1}^n \frac{1}{k \pi} \int_0^\pi \sin(x) dx.$$
In the last step, we exploit the fact that the integral of sine over the upper semicircle has the same magnitude as the integral over the lower semicircle.


text:
Q: Server configuration for allowing custom domains to point to my saas app by just changing their nameservers to my own I have successfully built a saas application that allow its users to add custom domain names, my question is how do i configure my server for it to allow users point their domain name to my saas app by just changing their domain name servers to my saas app name servers eg. ns1.saasapp.com,ns2.saasapp.com my stack is Nginx php and mysql.

A: Your customers should not have to change their Nameserver records. Instead, have them create a CNAME record pointing to the FQDN of your application and then ensure that your application is configured to properly serve requests with a host header that matches whatever name the customer created.


text:
Q: How to change color on One particular pageBlockSection? I have Change the color using CSS. But i want change the color on one particular pageblocksection. How can i do that. I tried several methods, but does not work. Thanks
    <apex:pageBlockSection title="Add Batch 3" collapsible="true" columns="1" id="section1">
        <apex:pageBlock >
            //Stuff
        </apex:pageBlcok>
    </apex:pageBlockSection

**CSS**

     html .brandTertiaryBgr {
            background-color:  #1A1A56!important;
            color: #FFFFFF!important;
            font-weight:bold;
            font-size:14px;
            margin-bottom:20px;}

By using above css code I would be able to change colours in all my pageblockSections. I used below method to change color, It does not work either`.
<apex:pageBlockSection title="Add Batch 3" collapsible="true" columns="1" id="redSection">
    <apex:pageBlock >
        //Stuff
    </apex:pageBlcok>
<script>colorPageBlock(document.getElementById("{!$Component.redSection}"), "red");</script>
</apex:pageBlockSection

JavaScript
<script>
function colorPageBlock(pageblock, color) {
if (pageblock != null) pageblock.firstChild.style.cssText = "background-color: " + color + ";";

}
</script>

Is there any otherway I can Change my pageBlockSection Color? Only for one. Thanks

A: Wrapping the apex:pageBlockSection in an element that a CSS class can be added to works:
<apex:page>

<style>
.custom1 {
    background-color: red !important;
}
.custom3 {
    background-color: green !important;
}
</style>

<apex:pageBlock>
    <apex:outputPanel layout="block" styleClass="custom1">
        <apex:pageBlockSection title="Section 1">
            Content 1
        </apex:pageBlockSection>
    </apex:outputPanel>
    <apex:outputPanel layout="block">
        <apex:pageBlockSection title="Section 2">
            Content 2
        </apex:pageBlockSection>
    </apex:outputPanel>
    <apex:outputPanel layout="block" styleClass="custom3">
        <apex:pageBlockSection title="Section 3">
            Content 3
        </apex:pageBlockSection>
    </apex:outputPanel>
</apex:pageBlock>

</apex:page>

producing this output:

PS
To style the headers you can make use of a CSS descendant selector:
<style>
.custom1 .pbSubheader {
    background-color: red !important;
}
.custom3 .pbSubheader {
    background-color: green !important;
}
</style>

where pbSubheader is a class applied by the Visualforce framework to the header.


text:
Q: Reading variable number of columns in pandas I have a poorly formatted delimited file, in which the there are errors with the delimiter, so it sometimes appears that there are an inconsistent number of columns in different rows.
When I run
pd.read_csv('patentHeader.txt', sep="|", header=0)

the process dies with this error:

CParserError: Error tokenizing data. C error: Expected 9 fields in line 1034558, saw 15

Is there a way to have pandas skip these lines and continuing? Or put differently, is there some way to make read_csv be more flexible about how many columns it encounters?

A: Try this.
pd.read_csv('patentHeader.txt', sep="|", header=0, error_bad_lines=False)

error_bad_lines: if False then any lines causing an error will be skipped bad lines, and it will be reported once the reading process is done.


text:
Q: Rails API How to add errors in exception and continue In my Rails project I created service object which get params and save Model. I want to handle exception there when e.g. one of the params is not valid. My service object looks like that:
class ModelSaver
  include ActiveModel::Validations

  attr_reader :model

  def initialize(params)
    @params = params
  end

  def errors
    @model.errors
  end

  def save_model
    @model ||= Model.new(params)

    @model.name = nil
    @model.save!

  rescue ActiveRecord::RecordNotSaved, ActiveRecord::RecordInvalid => error
    @model.errors.add(:base, error.to_s)
    false
  end

  private

  attr_reader :params
end

In Model name can't be nil, so when in example I try to @model.name = nil then service object go to rescure and exit from save_model. Can I somehow continue and add next errors from @model.save! (if there any) after exception from @model.name = nil?

A: Unsure what are you trying to achieve but I assume you've just removed all the business logic from the model and left only the bare minimum in that code sample.
I'd suggest instead of calling save! just call save and check if the object is valid. If it's not continue to do what you want to do or add additional errors, if it's valid then do something else.
Example of how that might look like:
  def save_model
    @model ||= Model.new(params)

    @model.name = nil
    @model.save

    return true if @model.valid?

    @model.add(:name, :invalid, message: "can't be nil")
    ... some code
  end

But instead of that, I'd suggest adding a custom validator instead of trying to  reinvent the wheel here you have a guide on how to use it: https://guides.rubyonrails.org/active_record_validations.html#performing-custom-validations


text:
Q: Symfony - how to autowire abstract class in services.yaml I have 4 classes which extend an abstract class. I also have event listener in which I use that abstract class because I implemented chain of responsibility design pattern. Now I have a problem because I don't know how to define abstract class in services.yaml file.
  Services\AbstractClass:
  abstract: true
  autowire: true
  arguments:
        - '@Services\AbstractClass'
Services\Service1:
  parent: Services\AbstractClass
  arguments: - '@Services\AbstractClass'
EventListener\MyEventListener:
  arguments:
    - '@annotations.cached_reader'
    - '@Services\AbstractClass'
  tags:
    - { name: kernel.event_listener, event: kernel.request, method: onKernelRequest }

When I try this I get an error: The definition "EventListener\MyEventListener" has a reference to an abstract definition "Services\AbstractClass". Abstract definitions cannot be the target of references.

A: You can't instantiate an abstract class so set an abstract class in any argument has no sense. And has you are configuring services with parents, the children should have autowire: true and autoconfigure: false in order to work proprely. Your service.yaml should look something like this
Services\AbstractClass:
  abstract: true

Services\Service1:
  parent: Services\AbstractClass
  autowire: true
  autoconfigure: false

EventListener\MyEventListener:
  arguments:
    - '@annotations.cached_reader'
    - '@Services\Service1'
  tags:
    - { name: kernel.event_listener, event: kernel.request, method: onKernelRequest }


text:
Q: Build Procedure My company is putting auto build and deploy procedure in place. What we are doing now is checking out source code from svn and specify the source folder in Ant script. Is it the right way? Can we omit the exporting process and build directly from SVN?
Another question is to do with versioning. At the moment, we are creating a tag whenever there is a release and then use the tag number to name the build product, which will be shipped to a client's site. I've done search on the Internet and here and it seems the correct way to name a product is like this: x.y.z.revision. However, our company is quite small and the client always want quick changes and releases. I would like to know what the drawbacks of only using tag number to name the product?  And what would be the best approach for small companies like us?
Thankyou,
Sarah

A: Sounds like you're doing it the correct way - checking out and building from Ant. You can't build directly 'inside' the SVN repository - you need to checkout somewhere and build from within the working copy.  Each time a change is made you need to update the working copy and then build.
The only thing I would suggest is looking at tools that do this for you anatomically, rather that you having to do it yourself. There are some tool out there that automate this process (Continuum, TeamCity, Bamboo) ranging from free to paid.
If you're not using a continuous integration tool already you might find benefits to your daily development as well.  If you are currently using it, you might be surprised to discover how they can be used to control releases and nightly builds as well as instant feedback and testing.
As for product version numbers, there is no definitive correct way to approach this.  Generally speaking build numbers are an internal reference only, and version numbers are a marketing thing.
Major.Minor.Revision format seems popular, and helps differentiate the degree of change.  Depending on the frequency of your changes this might suffice, but you might find your revision number getting high quickly.
This Wikipedia article talks about a number of differing approaches to version numbers.


text:
Q: Fetching from GraphQL using Class Components in React i have a project to make using Class components in React JS. I have to fetch data from GraphQL endpoint and display it on the front end. It is my first time both with Class components and with GQL. I cannot wrap my head around fetching data and managing component state with it without useQuery hook. I need help, I searched for solutions, tried implementing them but nothing seems to fit.
I would appreciate some advice!


text:
Q: R creating function with For and While I am trying to create a function in which i can calculate the sum of na's of each column.I tried to use for and while arguments but the result i get is always 0.This is what i tried:
sum_na <- function(x){
  for (i in 1:ncol(x)){
    while (i<ncol(x)){
      u=sum(is.na(x[i]))
      return(u)
            i=i+1
    }
  }
}

Any suggestion to a noob like me would be appreciated!


text:
Q: How to get eSIM phone number from the device? I want to get an eSIM phone number from the device.
I am using the SubscriptionInfo class to get the phone number but it always returns null.
SubscriptionManager subscriptionMgr = SubscriptionManager.from(context);
SubscriptionInfo subscriptionInfo = subscriptionMgr.getActiveSubscriptionInfoForSimSlotIndex(simIndex);

String phoneNumber = subscriptionInfo.getNumber()

I also give the permission in the Manifest file:
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>

A: You must to check if permission is granted.
public void getSIMNumber() {
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP_MR1) {
        SubscriptionManager subscriptionManager = SubscriptionManager.from(mContext.getApplicationContext());
        //TODO check if permission is Granted

        List<SubscriptionInfo> subsInfoList = subscriptionManager.getActiveSubscriptionInfoList();

        Log.d("Test", "Current list = " + subsInfoList);

        for (SubscriptionInfo subscriptionInfo : subsInfoList) {

            String number = subscriptionInfo.getNumber();

            Log.d("Test", " Number is  " + number);
        }
    }

}


text:
Q: ReactJS: Transferring Props I'm in the midst of doing up a realtime dashboard application in ReactJS for monitoring sensors. I'm using AutobahnJS + Websockets on PHP to stream data.
This is an abstraction of my dashboard in component view.
Abstraction of dashboard in component view
Main.jsx:
class Main extends React.Component {
constructor(props) {
    super(props)
}

componentDidMount() {
    $(document).foundation();

    var that = this;

    var conn = new ab.Session('ws://xx.xxx.xxx.xx', function() {
        conn.subscribe('', function(topic, data) {
            console.log(data);
            that.setState({
               result: data
            });
        });
    }, function() {
        console.warn('WebSocket connection closed');
    }, {'skipSubprotocolCheck': true});
}
render() {

    return (

                        <SensorDetails/>

                                {this.props.children}

    );
}
};

module.exports = Main;

What is the proper way to pass props from Main.jsx to BuildingList.jsx? I have tried replacing:
{this.props.children}

with
<Dashboard data={this.state.result}/>

This works but i'm unable to access my links e.g. Account Settings. My react-router is set up as such:
<Router history={hashHistory}>
  <Route path="/dashboard" component={Main} >
      <Route path="/about" component={About} onEnter={requireLogin}/>
      <Route path="/examples" component={Examples} onEnter={requireLogin}/>
      <Route path="/accountSettings" component={AccountSettings} onEnter={requireLogin}/>
      <IndexRoute component={Dashboard}/>
  </Route>
  <Route path="/" component={Login} onEnter={redirectIfLoggedIn}/>
</Router>

How would I fix this problem? thanks.

A: There are a couple of ways to handle this.
One method you can use is to render your children inside of Main.jsx like so. Passing two props to your children (state and updateState).
{React.Children.map(this.props.children, (child) => {
    return React.cloneElement(child, {
        state: this.state,
        updateState: (state) => this.setState(state)
    });
}}

From your child component you can update the state of Main.jsx by calling this.
this.props.updateState({prop: 'value'})

I don't think this is the best way of doing things in React. I prefer to take the event approach. I'll usually have something like the following to listen for and update "globally available state".
Inside of Main.jsx
componentDidMount() {
    App.Event.on('state.update', (state = {}) => this.setState(state));
}

App.Event is a simple event system that you can invoke by firing events like so.
App.Event.fire('state.change', {prop: 'value'});

A: Well, React is designed to pass props from up to down..
It makes Data-Management really hard, because you can have a lot of components which needs the same data.
So its better to use some kind of Flux Architecture, (e.g. Redux)
Or a simpler Data Layer like Mobx.
You should take a look at each because they are very different, but designed to help you with data management, (specially) in React


text:
Q: subscript operator postfix The C++ standard defines the expression using subscripts as a postfix expression. AFAIK, this operator always takes two arguments (the first is the pointer to T and the other is the enum or integral type). Hence it should qualify as a binary operator.
However MSDN and IBM does not list it as a binary operator.
So the question is, what is subscript operator? Is it unary or binary? For sure, it is not unary as it is not mentioned in $5.3 (at least straigt away).
What does it mean when the Standard mentions it's usage in the context of postfix expression?

A: I'd tend to agree with you in that operator[] is a binary operator in the strictest sense, since it does take two arguments: a (possibly implicit) reference to an object, and a value of some other type (not necessarily enumerated or integral). However, since it is a bracketing operator, you might say that the sequence of tokens [x], where x might be any valid subscript-expression, qualifies as a postfix unary operator in an abstract sense; think currying.
Also, you cannot overload a global operator[](const C&, size_t), for example. The compiler complains that operator[] must be a nonstatic member function.

A: You are correct that operator[] is a binary operator but it is special in that it must also be a member function.
Similar to operator()
You can read up on postfix expressions here
I just found an interesting article about operator[] and postfix expression, here

A: I think it's the context that [] is used in that counts. Section 5.2.1 the symbol [] is used in the context of a postfix expression that is 'is identical (by definition) to *((E1)+(E2))'. In this context, [] isn't an operator. In section 13.5.5 its used to mean the subscripting operator. In this case it's an operator that takes one argument. For example, if I wrote:
 x = a[2];

It's not necessarily the case that the above statement evaluates to:
x = *(a + 2);

because 'a' might be an object. If a is an object type then in this context, [] is used as an subscript operator.
Anyway that's the best explanation I can derive from the standard that resolves apparent contradictions.

A: If you take a close look to http://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B it will explain you that standard C++ recognize operator[] to be a binary operator, as you said.
Operator[] is, generally speaking, binary, and, despite there is the possibility to make it unary, it should always be used as binary inside a class, even because it has no sense outside a class.
It is well explained in the link I provided you...
Notice that sometimes many programmers overload operators without think too much about what they are doing, sometimes overloading them in an incorrect manner; the compiler is ease is this and accept it, but, probably, it was not the correct way to overload that operator.
Following guides like the one I provided you, is a good way to do things in the correct manner.
So, always beware examples where operators are overloaded without a good practice (out of standard), refer, first to the standard methods, and use those examples that are compliant to them.


text:
Q: ASP.NET MVC for developing widget based portals How suitable is ASP.NET MVC for developing anything like
http://www.google.com/ig?
I haven't seen or failed to find any examples yet. Does the MVC approach imply that the user interface is not supposed to look like that?

A: Check out http://aspspider.info/lakkakula/local.aspx, it is Web 2.0 Portal developed using Asp.Net MVC 1.0, Microsoft Ajax Client Templates and jQuery with drag and drop widget personalization much like google.com/ig.

A: MVC is quite suitable for such a UI.  Your main controller can render with a list of the widgets the user has defined, or an ajax call to a method returning a JsonResult can be used... this can generate the wrappers client-side calling for each partial vie for the corresponding controls.  I would think that MVC would simplify things quite a bit.
MVC + jQueryUI would be about all you'd need...

A: I guess a little bit more clarification, what exactly do you mean by "suitable"?
One method might be for each available "widgit" to be a controller, and then you can use jQuery (or whatever you want) to call the specified method and render.  The page would then have a series of "lists" (which you can store in the DB) against the user and you can simply order those lists to display the relevant widgits in the correct order.
Obviously, that's a VERY large simplification....

A: See the tutorial Developing Web 2.0 Portal using ASP.NET MVC, Microsoft Ajax Client Templates and jQuery with drag and drop widget personalization.


text:
Q: Confusion in longitude range, why do they start at 80? In one of our notes in the university, there's a paragraph about latitude and longitude that tell us this:

Geographic coordinates are the earth's latitude and longitude system,
ranging from 90 degrees south to 90 degrees north in latitude and 80
degrees west to 180 degrees east in longitude

I understand the part for the latitude, since every diagram labels -90S to 90N. But, why do they define for latitude as: 80 degrees west to 180 degrees east in longitude. As far as I understand latitudes also start from 0 to (-/+)180. So, why does it seem like they're somehow omitting a 10 degress of range?

A: I think it is a typo and should correctly read like this:
"Geographic coordinates are the earth's latitude and longitude system, ranging from 90 degrees south to 90 degrees north in latitude and 180 degrees west to 180 degrees east in longitude"
Please note,

The 180th meridian is one of the shames of geospatial technology. The story goes that given the rules of

*

*LineStrings and Polygons are represented as collections of positions

*Positions should be within -180° and 180° longitude and -90° and 90° latitude
It is simply impossible to tell the difference between a line that goes from -179° around the world to 179°, or one that just hops over the 180th meridian. That's one problem with Cartesian coordinates on a sphere.

For further information see The 180th Meridian.


text:
Q: How to group together tuples with the same element at a certain index? I Have a list of tuples like:
a = [('a', 'a', 'z', 'a'), ('b', 'b', 'z', 'b'), ('c', 'c', 'c', 'c')] #... and many more

I need to cut all tuples from the list, where items with index [2] is identical
and write them to other variable.
In the end I should have:
a = [('c', 'c', 'c', 'c')]
b = [('a', 'a', 'z', 'a'), ('b', 'b', 'z', 'b')]

How can I implement this in Python?

A: Try itertools groupby:
from itertools import groupby

k = sorted(k, key= lambda x: x[2]) # if elements are not in order
for grp,key in groupby(k, lambda x: x[2]):
    print(f'group is {grp} is with value {list(key)}')

result:
group is z is with value [('a', 'a', 'z', 'a'), ('b', 'b', 'z', 'b')]
group is c is with value [('c', 'c', 'c', 'c')]

A: Create a mapping of the tuples according to the item at index 2. For convenience, it is possible to use a defaultdict of type list:
from collections import defaultdict

a = [('a','a','z','a'), ('b','b','z','b'), ('c','c','c','c')]

res = defaultdict(list)
for tup in a:
    res[tup[2]].append(tup)

print(res)

Will give:
{'z': [('a', 'a', 'z', 'a'), ('b', 'b', 'z', 'b')],
 'c': [('c', 'c', 'c', 'c')]}


text:
Q: How to finalise a threadvar string to prevent a leak? This is not a major leak, but more of a would be nice to tidy I think, but I have found that my Delphi XE code can leak a String. This is because it is defined as a threadvar as it needs to be, but when the thread terminates, it is apparently not tidying up such variables.
Is there a way for me to manually tidy a string on termination of the thread? Do I just assign an empty string to it, or set it to nil or something?

A: Assign an empty string to it, set it to nil or call Finalize() on it. They are all equivalent and they will deallocate the storage thus removing your memory leak.

In response to Marco's comment, the documentation is explicit on this:

Dynamic variables that are ordinarily
  managed by the compiler (long strings,
  wide strings, dynamic arrays,
  variants, and interfaces) can be
  declared with threadvar, but the
  compiler does not automatically free
  the heap-allocated memory created by
  each thread of execution. If you use
  these data types in thread variables,
  it is your responsibility to dispose
  of their memory from within the
  thread, before the thread terminates.
  For example:
threadvar
  S: AnsiString;

S := 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  ...
S := ;  // free the memory used by S

Rather bizarrely the documentation contains a clear error in the final line which should read S := nil;
It is of course easy to see for yourself that thread local variables are not disposed automatically:
program LeakMe;

{$APPTYPE CONSOLE}

threadvar
  s: string;

begin
  ReportMemoryLeaksOnShutdown := True;
  s := 'Leak me';
end.

A: Some other small solution - you can use ShortString instead of String here (or any other kind of fixed length array), then memory leak disappear


text:
Q: Update attachBaseContext in MainActivity.java from a fragment How can I update attachBaseContext in MainActivity from a fragment? E.g.
MyFragment.java
String chosenLanguage = "en";

public void updateLanguage(String chosenLanguage) {
    //...Update MyContextWrapper.wrap(newBase, chosenLanguage) here
}

MainActivity.java (Following succesfully calls a java class and changes app language)
@Override
protected void attachBaseContext(Context newBase) {
    super.attachBaseContext(MyContextWrapper.wrap(newBase,"en"));
}

A: You need to restart activity to run 'attachBaseContext' again.
In your fragment run:
Intent intent= new Intent(getContext(), MainActivity.class);
startActivity(intent);


text:
Q: How to take backup of git from one server to another I have gitolite setup on one one of my server and it has lots of git repositories. So i decided to take a back up of all these and found this about git bundle. And based on it created the below script
#!/bin/bash
projects_dir=/home/bean/git/
backup_base_dir=/home/bean/gitbackup/

test -d ${backup_base_dir} || mkdir -p ${backup_base_dir}
pushd $projects_dir

for repo in `find $projects_dir -type d -name .git`; do
    cd $repo/..
    this_repo=`basename $PWD`
    git bundle create ${backup_base_dir}/${this_repo}.bundle --all
    cd -
done
popd

cd $backup_base_dir
rsync  -r . username@ip_address:/home/bean1/git_2nd_backup

In the above script 1st i am taking a backup of the repository in the same machine but in different folder as mentioned in the script backup_base_dir=/home/bean/gitbackup/ and then using rsync taking the backup in another machine/server. So my question is, is there any way to avoid the backing up in the same machine and i can directly backup to another server/machine. Just wanted to eliminate the backing up in same machine and wanted to backup directly to server machine.
Both the machines/servers are Ubuntu 16

A: For GitHub, this works:
for repo in $(/usr/local/bin/curl -s -u <username>:<api-key> "https://api.github.com/user/repos?per_page=100&type=owner" |
    /usr/local/bin/jq -r '.[] | .ssh_url')
do
   /usr/local/bin/git clone --mirror ${repo}
done

To follow the same approach you will need to expose as-as service a list of all your repositories, here I created something small in go that hopefully could help you as a start point:
https://gist.github.com/nbari/c98225144dcdd8c3c1466f6af733c73a
package main

import (
    "encoding/json"
    "fmt"
    "log"
    "net/http"
    "os"
    "os/exec"
    "path/filepath"

    "github.com/nbari/violetear"
)

type Repos struct {
    Remotes []string
}

func findRemotes(w http.ResponseWriter, r *http.Request) {
    files, _ := filepath.Glob("*")
    repos := &Repos{}
    for _, f := range files {
        fi, err := os.Stat(f)
        if err != nil {
            fmt.Println(err)
            continue
        }
        if fi.Mode().IsDir() {
            out, err := exec.Command("git",
                fmt.Sprintf("--git-dir=%s/.git", f),
                "remote",
                "get-url",
                "--push",
                "--all",
                "origin").Output()
            if err != nil {
                log.Println(err)
                continue
            }
            if len(out) > 0 {
                repos.Remotes = append(repos.Remotes, strings.TrimSpace(fmt.Sprintf("%s", out)))
            }
        }
    }
    if err := json.NewEncoder(w).Encode(repos); err != nil {
        log.Println(err)
    }
}

func main() {
    router := violetear.New()
    router.HandleFunc("*", findRemotes)
    log.Fatal(http.ListenAndServe(":8080", router))
}

Basically, will scan all directories from where you run the code on your server and try to find the git remotes returning in a JSON format a list of all remotes found.
From your backup server later you could just use the same approach used for Github and backup without duplication.
In this case, you could use it like this:
for repo in $(curl -s your-server:8080 | jq -r '.[][]')
do
   /usr/local/bin/git clone --mirror ${repo}
done


text:
Q: SSH commands stopped working after updating Magento to 2.4.0 After updating Magento to 2.4.0, When doing any SSH command, it shows Constant name is expected.
I found the issue is coming from the file vendor/magento/framework/Data/Argument/Interpreter/Constant.php.
So I added a line print_r($data);exit; in the following if condition
if (!isset($data['value']) || !defined($data['value']).
Then when I do Magento SSH commands, it showing the following error:
Array
(
  [name] => code
  [value] => Magento\Braintree\Model\Ui\ConfigProvider::CODE
)

Any help greatly appreciated.


text:
Q: Connection to remote Hadoop Cluster (CDP) through Linux server I'm new to PySpark and I want to connect remote Hadoop Cluster (CDP) through Linux server by using spark-submit command.
Any help would be appreciated.
I need spark-submit command to connect remote CDP.

A: You can use Apache Livy to submit remote jobs to a CDP cluster. Here is detailed info on how to install and use Livy to submit jobs :
After downloading and unzipping Livy you should add following lines in livy.conf file. Then start livy service.
livy.spark.master = yarn
livy.spark.deploy-mode = cluster

You can find examples of how to create a spark submit script on following links:

*

*https://community.cloudera.com/t5/Community-Articles/Submit-a-Spark-Job-to-CDP-Data-Hub-using-the-Livy-REST-API/ta-p/322481

*https://livy.apache.org/examples/


text:
Q: Why is File.ReadAllBytes result different than when using File.ReadAllText? I have a text file (UTF-8 encoding) with contents "test". I try to get the byte array from this file and convert to string, but it contains one strange character. I use the following code:
var path = @"C:\Users\Tester\Desktop\test\test.txt"; // UTF-8

var bytes = File.ReadAllBytes(path);
var contents1 = Encoding.UTF8.GetString(bytes);

var contents2 = File.ReadAllText(path);

Console.WriteLine(contents1); // result is "?test"
Console.WriteLine(contents2); // result is "test"

conents1 is different than contents2 - why?

A: As explained in ReadAllText's documentation:

This method attempts to automatically detect the encoding of a file based on the presence of byte order marks. Encoding formats UTF-8 and UTF-32 (both big-endian and little-endian) can be detected.

So the file contains BOM (Byte order mark), and ReadAllText method correctly interprets it, while the first method just reads plain bytes, without interpreting them at all.
Encoding.GetString says that it only:

decodes all the bytes in the specified byte array into a string

(emphasis mine). Which is of course not entirely conclusive, but your example shows that this is to be taken literally.

A: You are probably seeing the Unicode BOM (byte order mark) at the beginning of the file.  File.ReadAllText knows how to strip this off, but Encoding.UTF8 does not.

A: It's the UTF8 encoding prefix string. It marks the file as UTF8 encoded. ReadAllText doesn't return it because it's a parsing instruction.


text:
Q: Is SqlServer or NoSql more cost efficient when scaling horizontally RDBMS are traditionally better for vertical scaling since it's harder to do horizontal scaling. As a result NoSql databases are cheaper since they can more easily scale horizontally.
However in recent times RDBMS are horizontally scalable - although they might be harder to do.
So here is my question(s)
I assume it is still cheaper to horizontally scale an relational db than it is to scale it vertically, but still not as efficient as scaling for NoSQL. True or False?
Secondly, are there some ratios that explains the Vertical/Horizontal scaling costs for relational systems and NoSql systems. (I can imagine these change depending on availability - but I only want to know rough estimates as I am not making a business decision - I am just learning about it)

A: Cost of horizontal scalability is mostly a function of hardware provisioning and server hosting, and much removed from the software used for a database system, in my opinion. Yes, NoSQL databases are meant to be able to horizontally scale more easily but that doesn't necessarily mean more cheaply.
In fact, I believe in a lot of cases there's an inverse relationship between cost and ease of implementation. For example, there's so many database systems in existence currently, I don't doubt for every easy to implement horizontally scaling modern NoSQL database system, there's a cheaper horizontally scaling relational database system - at the tradeoff that it's likely a harder to achieve goal in such system (less well implemented, tested, and less commonplace, etc).
"I assume it is still cheaper to horizontally scale an relational db than it is to scale it vertically" - I don't believe this to generally be true either (in the context of a relational database). Horizontal scaling typically involves multiple servers, which means more hardware provisioning (Disk, Memory, and CPU all at once) than vertically scaling a single server, since usually further provisioning is needed as a result of not all resources being exhausted at one time, rather a particular resource topping out instead.
"Secondly, are there some ratios that explains the Vertical/Horizontal scaling costs for relational systems and NoSql systems." - Unfortunately I don't think you'll be able to find an answer to that, being that's just too broad of a question with too many variables, such as the many choices of how to provision a server, the OS used, if it's cloud (with the many options available), off-site, or locally hosted and maintained, etc.
To come to a practical answer here, you'd have to analyze the cost efficiency vs ease of implementation of two particular database systems, in practice. So, you're better off deciding on an actual relational database system and a NoSQL database system that you'd be interested in using. Then decide on the hardware you would need to provision behind both systems for the same workload and example data, and server hosting option you'd want to use in both cases. Once you've gotten that far in practice, you can start effectively comparing the cost differences.

A: At any point in time the server hardware with the best price/performance will have a certain number of compute cores and a certain amount of memory.
Horizontal scaling is only less expensive than vertical scaling for workloads that require more resources than can be provided by that server.
Currently that's something like 48 compute cores and 500GB of RAM, which can handle database workloads of several terabytes and several thousand requests per second.


text:
Q: Any way to get all WordPress Versions dynamically ? Rest API or something? I'm looking for a dynamic way to get the information about WordPress releases.
https://wordpress.org/download/releases/
Last move for me is to scrape this page on a cron but i really wanna avoid doing that.


text:
Q: Programmatically add menu item/link to Drupal menu? I have a Drupal Menu which I created through the interface. I wish to add an entry which says
Hi, John Doe
Where "John Doe" is a link to the User's profile page.  I would like to do this programmatically or if it can be done through the interface then that would be great.

A: You cannot add HTML-ified items to the menu. Menu-items are always wrapped in an anchor tag and will filter out HTML. Changing this behaviour is technically possible, but will cause a lot of unknown side-effects.
What you want, is either a simple theme override, or a custom block (potentially without a title and with some other bullets).
You can create a block with hook_block or by simply typing the HTML, with some PHP into a new block, using the PHP-input filter. This last option is quick, but is discouraged by many people for performance and "good practices" reasons: you should not store php in your database.
EDIT: After comment about "just the name":
To insert "just the name" you simply need to create module with a hook_menu.
global $user;
$items['path/%uid'] = array(
  'title'            => $user->name,
  'description'      => 'description',
  'page callback'    => 'drupal_get_form', //Fill in the callback here: function that renders the page content.
  'page arguments'   => array(''),
  'access callback'  => '',
  'access arguments' => array(''),
  'weight'           => 0,
  'menu_name'        => 'Navigation',
  'type'             => MENU_NORMAL_ITEM,
);

Is about what you want.


text:
Q: Performance of xml path I have a query below:
select col1,
       col2,
       .
       .
       .
       coln
  from table1
  left join table2
  on some condition
  .
  .
  left  join tablen
  on some condition
  left join (
              select t1.col1,
              (
                select t2.col2 + ';' as [data()]
                  from SomeTable t2
                 where t2.col1 = t1.col1
                 for xml path('')
              ) value
              from SomeTable t1
              group by t1.Col1
            )MyTable
         on some condition

The above query will return about 4000 rows. The inline select statement using xml path will also result in about 4000 records.
I wish to know if there will be any performance impact with this query due to the use of xml path.
Thanks in advance.

A: Unless and untill you have proper indexes on the all joining columns in left join and proper covering indexes in select list of columns,there wont be any performance issue here.


text:
Q: How to save csv file in mongodb using node.js? I found an example, how to save a csv file, but I got an error, do you know how to fix it? Also, please let me know if it is possible to save it in another way.
csv-save.js
const mongodb = require("mongodb").MongoClient;
const csvtojson = require("csvtojson");

// let url = "mongodb://username:password@localhost:27017/";
let url = "mongodb://test1:1234@localhost:27017/";

csvtojson()
  .fromFile("bezkoder.csv")
  .then(csvData => {
    console.log(csvData);

    mongodb.connect(
      url,
      { useNewUrlParser: true, useUnifiedTopology: true },
      (err, client) => {
        if (err) throw err;

        client
          .db("cro")
          .collection("cro1")
          .insertMany(csvData, (err, res) => {
            if (err) throw err;

            console.log(`Inserted: ${res.insertedCount} rows`);
            client.close();
          });
      }
    );
  });

bezkoder.csv
id,name,description,createdAt
1,Node.js,JavaScript runtime environment,2019-09-03
2,Vue.js,JavaScript Framework for building UI,2019-09-06
3,Angular.js,Platform for building mobile & desktop web app,2019-09-09

Error content
(MongoError: Authentication failed.)

A: If you are getting "Error content (MongoError: Authentication failed.)" then you have an authentication error that you need to resolve before you can connect to your database.


text:
Q: Access private API from a domain hosted in AWS I'm trying to make private AWS lambda call made through API gateway and I don't find the right answer on the internet, probably because I'm a beginner in AWS website management.
The closest source I found was this amazon documentation: https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-private-api-test-invoke-url.html
I'm using the serverless framework and here is an example of a function setup
provider:
  name: aws
  runtime: nodejs8.10
  memorySize: 128
  environment:
    MONGODB_URL: ....
    MONGODB_USER: ....
    MONGODB_PWD:....
  vpc:
    securityGroupIds:
      - ....
    subnetIds:
      - ....
      - ....

functions:
  addGameTemplate:
    handler: game.create
    events:
      - http:
          method: put
          path: games
          cors: true
          private: true

The url is also hosted on route53.
Any guidance will be appreciated!

A: If I understand your problem right you want to call a private API Gateway in your VPC from Lambda, correct?
To do that you'll need to execute the lambda in the VPC, otherwise it won't have access to the private VPC resources.
Check this out: Configuring a Lambda Function to Access Resources in an Amazon VPC. Most notably you'll have to give it the VPC ID and a list of subnets where it should execute.

As clarified in the comments what you're actually looking for is restricting access to your API Gateway and only permit access from your VPC. To do that create / update your API Gateway Security Group to only permit access from your VPC address range (or from wherever you want to restrict the access to).
Hope that helps :)


text:
Q: Group with a given presentation, finite or infinite? Consider the group with following presentation,
$$G=\langle s,t : s^2=1, (st)^{3}=1\rangle$$
Is this group finite or infinite?
I tried to manipulate the relations and could only get $(ts)^3=1$. I don't know how to proceed further. Any hints?

A: Hint: Instead of taking $s$ and $t$ as generators, take $s$ and $st$ as generators.  How else can you describe the group then?
More details are hidden below.

 Writing $u=st$, we have $G=\langle s,u\mid s^2=1, u^3=1\rangle$.  But this just means that $G$ is the free product of a cyclic group of order $2$ (generated by $s$) and a cyclic group of order $3$ (generated by $u$).  In particular, $G$ is infinite, because for instance there are infinitely many distinct reduced words of the form $sususu\dots$.


text:
Q: applying javascript vertical center to multiple divs After hours of trying to sort this out by myself i feel the need to turn to someone who knows better than me. I have a function that centers a child div within a parent div. It all works the only problem is the child div changes in size so i need a way of applying this function to every div individually.
here is my code
HTML

short text in here

some text in here more text here that is longer. This is longer

CSS
.outer{background:#eee;height:150px;width:150px;margin-bottom:20px;}
.inner{width:130px;padding:10px;text-align:center;}

JAVASCRIPT
$(document).ready(function(){
var inner = $('.inner'),
ht = inner.height();

inner.css({'position':'absolute','top':'50%','margin':-ht/2+'px 0 0 0'});
});

http://jsfiddle.net/AMNVY/

A: Does this work for you?
All i did was edit the css:
.outer{
    background:#eee;
    height:150px;
    width:150px;
    margin-bottom:20px;
    display: table;
}
.inner{
    width:130px;
    padding:10px;
    text-align: center;
    vertical-align: middle;
    display: table-cell;

}
no need for js...

A: If you still need javascript here is my solution... You could use this bind to get height everytime it changes, then you should be able to create an algorithm to manage css.
JS:
$('#inner').bind('getheight', function() {
    $('#inner').height();
});


text:
Q: Stackage LTS announces How can I know that a new Stackage LTS was released? I couldn't find this information in Stackage home page nor in this FAQ section on Github.

A: My personal favorite is using the RSS feeds, e.g.

*

*https://www.stackage.org/feed (all snapshots)

*https://www.stackage.org/feed/lts (all LTS snapshots)

*https://www.stackage.org/feed/lts-11 (all LTS-11 snapshots)

Bonus is that you'll get to see the differences between each successive snapshot. Alternatively, you could watch the LTS Haskell Git repo:

*

*https://www.stackage.org/feed/lts-11


text:
Q: AChartEngine set background and margin transparent I would like to set the background black square to transparent but the result is like this.
_renderer.setApplyBackgroundColor(true);
_renderer.setBackgroundColor(Color.TRANSPARENT);
_renderer.setMargins(new int[]{0,0,0,0});
_renderer.setMarginsColor(Color.TRANSPARENT);

I want to set the graph part a little smaller to have the axis text some space. I don't want the black things... how to set it to be transparent.
Anther question, how to use the xml to set the view. I am now using an linear layout in the xml, and then use linearlayer.addView(view) to add the view that returned by the achartengine: ChartFactory.getBarChartView(...) but if I define a view in the xml, how to directly set the view's content the bar content. I mean not using the dynamic addView in my code, but set the view using xml. Thanks.

A: -> I am not sure if you looked at AChartEngine transparent background  question. It talks about similar issue:
According to it, You can try:
setMarginsColor(Color.argb(0x00, 0x01, 0x01, 0x01));

-> If it does not work you may try to create the activity with transparent background and may also give it a dialog look if you want:
Android: how to create a transparent dialog-themed activity
How do I create a transparent Activity on Android?
Hope this helps.

A: If you want to set transparent background color, you can try:
renderer.setMarginsColor(Color.argb(0x00, 0xff, 0x00, 0x00));

It just be work for me!


text:
Q: Conditionally Enable Button on TreeNode focus I have the following TreeView structure:

I want to enable the button1 button ("download file(s)") only when the Scan_XX or File_XX levels in the hierarchy are selected.

A: The AfterSelect event is a good place for your code.
If you're only concerned with the text of the node, how about this slightly shorter code:
private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
{
    button1.Enabled
       = (e.Node.Text.StartsWith("Scan_") || e.Node.Text.StartsWith("File_"));
}

A: I ended up using this:
 private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {

            if (e.Node.Level == 3 || e.Node.Level == 4)
            {
              button1.Enabled = true;
            }
            else {
              button1.Enabled = false;
            }

        }


text:
Q: Is it possible to mark a method as explicitly used in C#? I have a method that is accessed by NUnit only with its name via reflection, and I can't use nameof() because this is a TestCaseSource accessing test data in a static method in a derived class (the input data and [SetUp] are different for each derived class, but the execution of the test is the same). This method doesn't need to be public/protected for NUnit to work, so for minimizing unwanted access I would like to set it to private, however, if I set it as private then I get a warning that the method is unused.
Is there a way to mark a method as explicitly used? Perhaps an attribute, or a preprocessor directive, that can tell the analyzer that this method is used?


text:
Q: How to prove this complex Inequality $$\left|\sum_{i=0}^\infty\gamma^ir_i-\left(\sum_{i=0}^{n-1}\gamma^ir_i+{\gamma^nr_n \over 1-\gamma}\right)\right|\ge\left|\sum_{i=0}^\infty\gamma^ir_i-\left(\sum_{i=0}^{k-1}\gamma^ir_i+{\gamma^kr_k \over 1-\gamma}\right)\right|$$
where $\gamma$ is a constant, $0<\gamma<1$, $n<k<\infty$, $r_i \in \mathbb{R}$ and $\sum_{i=0}^\infty\gamma^ir_i < \infty$.
I'm trying to show that as long $k$ becomes larger the error between the true sequence $\gamma^0r_0+\gamma^1r_1+...$ and the estimated one $\sum_{i=0}^{k-1}\gamma^ir_i+{\gamma^kr_k \over 1-\gamma}$ becomes smaller.
See that all remaining terms is truncated using only one sample $r_k$ with the term ${\gamma^kr_k \over 1-\gamma}$. Additionally, if possible, I would like to know how much $r_k$, the last sampled $r$, can differ from the future values $r_{k+1}, r_{k+2},...$ to hold this inequality.
I simplified the above inequality to
$\left|\sum^\infty_{i=n}\gamma^i(r_i-r_n)\right|\geq\left|\sum^\infty_{i=k}\gamma^i(r_i-r_k)\right|$, removed the absolute by squaring both side of the inequality and I get $$\sum_{i=n+1}^k\gamma^i(r_i-r_n)^2\geq{\gamma^{k+1}(r_k^2-r_n^2)\over1-\gamma}$$
In the limit as $k\rightarrow\infty$ the right side of the inequality is $0$ and the left side is the squaring sum which will be a number greater or equal to zero, so the inequality becomes true as $k\rightarrow\infty$.
and what for $k < \infty$, e.g., $k = 1+n$, $k = 2+n$, $k = 3+n$...
let state that $r_i$ is a variable sampled from normal distribution where the mean is $\mu$ and the standard deviation is $\sigma$.
What now?


text:
Q: How edit the amounts from a "budgetImport" record in suitscript2.0? I have made a suitelet that groups accounts, but I need to save the results in the budget account lines, I do a record load of "budgetImport", but it does not return the sublist with the amounts, does anyone know how it can be edited from code? ?
      var recordExample = record.load({
                    type: 'budgetImport',
                    id: 396,
                    isDynamic: true
                });

                recordExample.setSublistValue({
                    sublistId: 'budget',
                    fieldId: 'amount_10_',
                    line: 0,
                    value: 310001.00
                });
                var save = recordExample.save()

I have tried this but it seems to be not a sublist but a 'lineFields'


text:
Q: Sell only for a state or region in Magento 2 I'm looking for help, I need to leave the state fixed in the shipping and billing in magento 2.

A: Go to Admin > Stores > Configuration > General > Country Options > Allow Countries
Default Country: A Selected country will display as default country in drop down.
Allow Countries: Selected countries will display in the country drop down options.
Hope this helps!


text:
Q: Meteor CORS android 4.1.2 I'm getting this error when I try to upload a file using android 4.1.2:
XMLHttpRequest cannot load http://bucket.storage.aws.net/. Origin http://meteor.local is not allowed by Access-Control-Allow-Origin.

The application works perfectly on android 4.4+. Does anyone know how to fix this problem for older versions of android?
Thanks.