text:
Q: iOS - pros and cons of using vector asset than png In my recent project, our team had decided using vector image asset with pdf format.
What pros and cons of using vector than normal png?
If I have three different image size for one image, 30x30, 75x75, 123x123. In this case, will Xcode generate all of them? Or generate only one png?
If I set a "Preserve vector data" option and using single scale, does iOS generate png images on runtime? Does it works with dynamic size view?


text:
Q: binary_search, find_if and  std::find_if takes a predicate in one of it's overloaded function. Binders make it possible to write EqualityComparators for user-defined types and use them either for dynamic comparison or static comparison.
In contrast the binary search functions of the standard library take a comparator and a const T& to the value that should be used for comparison. This feels inconsistent to me and could possibly more inefficient as the comparator has to be called with both arguments every time instead of having the constant argument bound to it. While it could be possible to implement std::binary_search in a way to use std::bind this would require all comparators to inherit from std::binary_function. Most code I've seen doesn't do that.
Is there a possible benefit from letting comparators inherit from std::binary_function when using it with algorithms that take a const T& as a value instead of letting me use the binders? Is there a reason for not providing predicate overloads in those functions?

A: A single-argument predicate version of std::binary_search wouldn't be able to complete in O(log n) time.
Consider the old game "guess the letter I'm thinking of". You could ask: "Is it A?" "Is it B?".. and so on until you reached the letter. That's a linear, or O(n), algorithm. But smarter would be to ask "Is it before M?" "Is it before G?" "Is it before I?" and so on until you get to the letter in question. That's a logarithmic, or O(log n), algorithm.
This is what std::binary_search does, and to do this in needs to be able to distinguish three conditions:

*

*Candidate C is the searched-for item X

*Candidate C is greater than X

*Candidate C is less than X

A one-argument predicate P(x) says only "x has property P" or "x doesn't have property P". You can't get three results from this boolean function.
A comparator (say, <) lets you get three results by calculating C < X and also X < C. Then you have three possibilities:

*

*!(C < X) && !(X < C) C is equal to X

*C < X && !(X < C) C is less than X

*!(C < X) && X < C C is greater than X

Note that both X and C get bound to both parameters of < at different times, which is why you can't just bind X to one argument of < and use that.
Edit: thanks to jpalecek for reminding me binary_search uses <, not <=.
Edit edit: thanks to Rob Kennedy for clarification.

A: They are completely different algorithms: find_if looks linearly for the first item for which the predicate is true, binary_search takes advantage that the range is sorted to test in logarithmic time if a given value is in it.
The predicate for binary_search specifies the function according to which the range is ordered (you'd most likely want to use the same predicate you used for sorting it).
You can't take advantage of the sortedness to search for a value satisfying some completely unrelated predicate (you'd have to use find_if anyway). Note however, that with a sorted range you can do more than just test for existence with lower_bound, upper_bound and equal_range.

The question, what is the purpose of std::binary_function is an interesting one.
All it does is provide typedefs for result_type, first_argument_type and second_argument_type. These would allow the users, given a functor as a template argument, to find out and use these types, e.g
template <class T, class BinaryFunction>
void foo(const T& a, const T& b, BinaryFunction f)
{
     //declare a variable to store the result of the function call
     typename BinaryFunction::result_type result = f(a, b);
     //...
 }

However, I think the only place where they are used in the standard library is creating other functor wrappers like bind1st, bind2nd, not1, not2. (If they were used for other purposes, people would yell at you any time you used a function as a functor since it would be an unportable thing to do.)
For example, binary_negate might be implemented as (GCC):
template<typename _Predicate>
class binary_negate
: public binary_function<typename _Predicate::first_argument_type,
             typename _Predicate::second_argument_type, bool>
{
protected:
  _Predicate _M_pred;

public:
  explicit
  binary_negate(const _Predicate& __x) : _M_pred(__x) { }

  bool
  operator()(const typename _Predicate::first_argument_type& __x,
     const typename _Predicate::second_argument_type& __y) const
  { return !_M_pred(__x, __y); }
};

Of course, operator() could perhaps just be a template, in which case those typedefs would be unnecessary (any downsides?). There are probably also metaprogramming techniques to find out what the argument types are without requiring the user to typedef them explicitly. I suppose it would somewhat get into the way with the power that C++0x gives - e.g when I'd like to implement a negator for a function of any arity with variadic templates...
(IMO the C++98 functors are a bit too inflexible and primitive compared for example to std::tr1::bind and std::tr1::mem_fn, but probably at the time compiler support for metaprogramming techniques required to make those work was not that good, and perhaps the techniques were still being discovered.)

A: This is a misunderstanding of the Functor concept in C++.
It has nothing to do with inheritance. The property that makes an object a functor (eligible for passing to any of the algorithms) is validity of the expression object(x) or object(x, y), respectively, regardless whether it is a function pointer or an object with overloaded function call operator. Definitely not inheritance from anything. The same applies for std::bind.
The use of binary functors as comparators comes from the fact that comparators (eg. std::less) are binary functors and it's good to be able to use them directly.
IMHO there would be no gain in providing or using the predicate version you propose (after all, it takes just passing one reference). There would be no (performance) gain in using binders, because it does the same thing as the algorithm (bind would pass the extra argument in lieu of the algorithm).

redpajama_set_name: RedPajamaStackExchange


text:
Q: Unmonitored (X.X.X.X:3306) Error in MEM tool We're seeing "Unmonitored (X.X.X.11:3306)" error in MEM tool due to below command executed on wrong Master server.
Can anyone suggest how to fix this issue without restarting the Master server.
ON Master X.X.X.10 :-
CHANGE MASTER TO MASTER_HOST='X.X.X.11', MASTER_USER='mysql',
MASTER_PASSWORD='paswd', MASTER_PORT=3306, MASTER_LOG_FILE='mysql-bin.00XXXX',
MASTER_LOG_POS=61001479 ;

In the Replication Group, we're seeing this Unmonitored (X.X.X.11:3306) error & two red circles apart from the normal Master (X.X.X.10:3306) & Slave (X.X.X.20:3306) information.
How to remove the errored red circles & Unmonitored (X.X.X.11:3306) error.

A: Issue is resolved when I execute the below command on the Master server and then restarted the MySQL Monitoring agent.
mysql> change master to Master_Host='';
ERROR 1210 (HY000): Incorrect arguments to MASTER_HOST

mysql> change master to Master_Host=' ';
Query OK, 0 rows affected (0.23 sec)

My MySQL version is : 5.5.8
Best,
Srinivas


text:
Q: WordPress custom post type URL rewriting with custom field values I can't seem to get this to work how I want it to, but here's basically what I want to do:
I have a page called "album". This has all of the photo albums on that page. Then you click an album to go to the photo gallery for that album. I have a custom template for this page set, so all of the different albums will use this template. From here, I want to be able to click on an image and take it to the single image view. Because the photo gallery page is a custom post type, when I go to the single image, I have a file called "single-gallery.php" which then should display and then gather the image data to display it.
This is all working, however I want to keep the URL a certain way throughout this. I have almost got it how I want it, however the issue I am having is that I need to rewrite the URL in the gallery custom post type and use a custom field value in the URL to indicate which album this is.
For registering my "gallery" custom post type, I have this to rewrite my URL:
'rewrite' => array('slug'=>'album/%albumName%','with_front' => true),
Then in the gallery page template I use php to replace %albumName% with the current album.
$photoPermalink = str_replace('%albumName%', $albumName, $photoPermalink);
The problem is that I guess WordPress has to index the permalinks, and it's indexing the %albumName%, so when I change it with PHP it gets broken.
Is there a way to do this?

A: You need to use wordpress's own filters to do this. At least to do it correctly without causing issues in other areas of your wordpress install later.
https://wordpress.stackexchange.com/questions/39500/how-to-create-a-permalink-structure-with-custom-taxonomies-and-custom-post-types
That actually shows you how to create custom permalink structures for custom post types.


text:
Q: Separate and loop string object javascript How can I loop over this in javascript
var car = "{"Uber","Lyft"}"
I would want to loop over every string in car. So Uber and Lyft in this case. The end goal is to convert this to a Json Object so {text1: Uber, text2: Lyft}

A: Replace the first { with [, the last } with ], then you can use JSON.parse() to get an array that you can loop over.

var car = '{"Uber","Lyft"}';
var json = '[' + car.substr(1, car.length-2) + ']';
var array = JSON.parse(json);
console.log(array);


text:
Q: AWS Cognito federated user login not allowing to sign in as different user after log out I am able to logout and login but there is 1 particular scenario which I am not able to achieve.
Scenario:-

*

*User logs in using federated social login (Google), using hosted UI directly.

*Now the user clicks on logout it directs it to AWS Cognito logout URL

https://xxxxxxx.auth.us-east-2.amazoncognito.com/logout?
response_type=token&client_id=xxxxxxxxx&logout_uri=https://abc/logout.html

it logs out the user success and successfully redirects the user to logout page as mentioned in URL.

*

*Now when the user tries to log in again by a different account, he is forced to use his previous google login only.

I want to have such functionality that user can log out and log in again if he wants then he can log in with the same account or with different depend on choice.
The important point to note is I can't use AWS-Amplify or any javascript framework, only plain javascript.

A: The reason you are always forced to log in with the same user seems to be that the /logout? endpoint only logs out the user on Cognito, but Cognito does not communicate to Google that it should log you out of your device. Thus, every time you sign back in and the Google Authentication screen is launched Google still remembers the device and sees that you're still logged in. As a result, the redirect URI is triggered without you ever being prompted to choose a new account.
I'm running into the same issues on a React Native project, but have yet to find any evidence that Cognito offers an endpoint to force it to also sign you out of the Identity provider (i.e. Google).
PS: Here's another stackoverflow discussion with more info: AWS Cognito - How to force select account when signing in with Google
One of the responses in that thread mentions calling Google's logout endpoint directly as part of the signout flow. It's definitely not pretty, but since you're using plain Javascript it might be a sufficient solution.
If you find a cleaner solution please make sure to share it, as I'd be interested to hear what you find :)

A: Well, I got it working but I don't think so its an issue but a kind of behaviour that every developer should know who is trying to integrate google login in the there application. Here are the few scenarios I am have checked and their respective behaviour.
My AWS Cognito Login URL
https://xxxxxxx.auth.us-east-2.amazoncognito.com/oauth2/authorize?
identity_provider=Google&redirect_uri=https://xxxxxx/login.html&response_type=TOKEN
&client_id=xxxxxxxxxxxxxxxxx&scope=phone%20email%20openid%20profile

My AWS Cognito Log out URL
https://xxxxxxxxx.auth.us-east-2.amazoncognito.com/logout?
client_id=xxxxxxxxxxxxxxxxxxxx
&logout_uri=https://xxxxxxxxxxxxx/logout.html

By using the above URL when I log out, I don't get logged out from chrome browser.
This behaviour is an issue for many people
So when your chrome browser has only 1 account logged in, at that time AWS Cognito google login won't redirect to a page where you can select the different user, because you have only single user through which it gets logged indirectly.
Found out how we can show multiple logins:-  So if you want another user to log in then he needs to first sign in chrome browser, and when he clicks on google login from the website at that time he will be able to select user, as in chrome we have now 2 users logged in google, from where he can select which user want to use for access.
I won't be accepting this as an answer because it's not how everyone want this behaviour, will wait for few days if someone can suggest better way.
I think so, for now, we have to go with this.


text:
Q: How to include multiple values under a section in inifile I am trying to create a puppet manifest using inifile. This would be for a configuration file where I need to have the following format.
[safe]
    directory = /home/foo
    directory = /home/test
    directory = /home/something

I know that there is a way to use directory1, and directory2 but I was wondering if there is a way to do it without changing the directory since it needs that specific attribute. This implementation is meant for puppet manifest.
Also, I was thinking puppetlabs/inifile module but if there is another option to achieve this would be great too.
Thanks for the help in advance
So far, I have an implementation like:
ini_setting { 'procedure cache size':
  ensure         => present,
  path           => '/var/lib/somethning/test.config',
  section        => 'safe',
  setting        => 'directory',
  value          => '/home/foo',
  indent_char    => "\t",
}

This is for each directory. The purpose for this implementation is to address the new git configuration for safe.repository in the recent update. My understanding is that for multiple directories, it adds a new value as directory = <directory> I don't believe that it likes directories separate by commas.

A: First I thought about file_line, but this is not idempotent for multi-line settings (you get problems when you run again). You can try:
Sample puppet code dir.pp
$safe_directories="directory = /home/foo
directory = /home/test
directory = /home/something"

notice "Testing\n${safe_directories}"

file { "/tmp/result.ini":
  ensure => present,
  content => template('/tmp/layout.erb'),
}

notice "Check /tmp/result.ini"

Sample template /tmp/layout.erb
[unsafe]
  directory=/unsafe
[safe]
  <%=@safe_directories%>
  otherfield=secure
[header3]
  nothing = here

Now run command from commandline
puppet apply dir.pp


text:
Q: Can overwrite Bootstrap CSS for some elements but not others? I have the following elements I have applied the Bootstrap btn and default-btn classes to:
<input class="btn btn-default add-to-cart-btn" type="submit" name="addcart" value="Add to Cart" />

Enquire

My CSS selectors look like:
.add-to-cart-btn, .enquire-btn {
//CSS
}

However, only the add-to-cart-btn CSS overwrties the Bootstrap CSS.
Would anyone know why this is or if/why Bootstrap has issues with overwriting styles on divs?

A: Your CSS must be more  specific than the css you are trying to overload.
Your are doing .add-to-cart-btn, .enquire-btn.
So bootstrap might be doing "div.enquire-btn". This is more specific than your CSS.
To overload it div.enquire-btn.

A: I would try making two different classes.
.add-to-cart-btn {...}

.enquire-btn {...}

A: Your first issue is that for your input class you've spelt "btn-default" incorrectly. So the bootstrap.css for that class isn't being used, which is why your custom code is working for that and not the other.
Without seeing the rest of your document, I can only assume that your custom css is being loaded before the bootstrap stylesheet which is why that is receiving preference. Try making your custom selectors more specific by adding the btn class to them.
eg;
.btn.add-to-cart-btn, .btn.enquire-btn {
  //CSS
}

A: This is quite strange. But I will try to do this instead to see if it's working or not.
input.add-to-cart-btn, div.enquire-btn {
  /* Your Style Here */
}


text:
Q: ctrl click class in Eclipse shows binary / jar instead of source Using Eclipse
Version: Helios Service Release 2
Build id: 20110218-0911
with Android plugin. I have an Android project "AndroidUtil" that is marked as a "library" project for my main Android application.  When I ctrl + click the name of a class defined in AndroidUtil, I am taken to the binary / jar version of that class instead of the source file.  How can I make it take me to the source instead?

A: When you control-click and it displays the class file editor in the editor pane, you should see an "Attach Source" button. Click that and point it to the library project in your workspace.

A: For those with a newer version of the SDK, it might help to check out the workaround in this thread http://code.google.com/p/android/issues/detail?id=23685


text:
Q: Reading file in Icarus Verilog I have a file data.txt that has 1200 lines, each representing a 16 bit binary string  such as the following.
"0001111111000000"
I'm trying to write a testbench using Icarus Verilog that reads in each line of the file and sends each line to a .v file that will run some simple if statements on each line of the file (a simple classification algorithm).
My code is below.
// Verilog test bench for generate.v
`timescale 1ns/100ps
`include "generate.v"

module generate_tb;

$display('running test bench')

   integer               data_file    ; // file handler
   integer               scan_file    ; // file handler
   logic   signed [21:0] captured_data;
   `define NULL 0

   initial begin
      $dumpfile("generate.vcd");
      $dumpvars(0, generate_tb);

      data_file = $fopen("./data.txt", "r");
      if (data_file == `NULL) begin
         $display("data_file handle was NULL");
         $finish;
      end
   end

   always @(posedge clk) begin
      scan_file = $fscanf(data_file, "%b\n", captured_data);
      if (!$feof(data_file)) begin
         generate the_circuit(output, captured_data); // HERE
      end
   end

   $finish;
   endmodule

and my generate.v file:
module generate(actual_class, data_row);

   output actual_class;
   input  data_row;

   wire stby_flag ;
   wire       [0:15] vect;

   reg [0:1] classe;

   assign vect = data_row;

   always  @(posedge clk) begin
        if (vect[3] == 0) begin
            classe = 2'b10;
        end

        if (vect[11] == 0) begin
            classe = 2'b01;
        end

        if (vect[8] == 1 &&  vect[4] + vect[5] + vect[6] + vect[7] >= 3) begin
            classe = 2'b00;
        end

        if (vect[0] + vect[1] + vect[2] + vect[3] + vect[4] + vect[5] + vect[6] + vect[7] + vect[8] + vect[9] + vect[10] + vect[11] + vect[12] + vect[13] + vect[14] + vect[15] <= 1) begin
        classe = 2'b11;
    end

end

assign actual_class = classe;

endmodule

I am stuck on this part of the code. I'm not sure how I can call the generate.v file for each line of the file.
if (!$feof(data_file)) begin
             generate the_circuit(output, captured_data); // HERE
end

A better way to do this would be to save my data into and use $readmemb but I'm hoping to do it this way.
Any advice is much appreciated.

A: To start off: it is a very bad idea to name your module after a reserved word 'generate'.

I'm not sure how I can call the generate.v

It is a module, not a function. You can not 'call' a module.
You read each line from the file and assign it to a input variable of the module. Make sure you wait long enough before reading the next line for your module (and all subsequent triggered modules) to finish processing the input. You can wait a number of clock cycles or use a 'ready' signal.

A better way to do this would be..

Maybe. If your pattern gets very big you need a big memory.


text:
Q: WebClient - The remote server returned an error: (403) Forbidden Opening a public page from browser works fine.
Downloading same page using WebClient throws - (403) Forbidden.
What is going on here ?
Here is quick copy/paste example (used on console app) to specific page on web:
try
{
    WebClient webClient = new WebClient();
    string content = webClient.DownloadString("http://he.wikisource.org/wiki/%D7%A9%D7%95%D7%9C%D7%97%D7%9F_%D7%A2%D7%A8%D7%95%D7%9A_%D7%90%D7%95%D7%A8%D7%97_%D7%97%D7%99%D7%99%D7%9D_%D7%90_%D7%90");
}
catch (Exception ex)
{
    throw;
}

A: I've just tried it with Fiddler running to see the response and it returns the following notice with the status code.

Scripts should use an informative
  User-Agent string with contact
  information, or they may be IP-blocked
  without notice.

This works.
    WebClient webClient = new WebClient();
    webClient.Headers.Add("user-agent", "Only a test!");

    string content = webClient.DownloadString("http://he.wikisource.org/wiki/%D7%A9%D7%95%D7%9C%D7%97%D7%9F_%D7%A2%D7%A8%D7%95%D7%9A_%D7%90%D7%95%D7%A8%D7%97_%D7%97%D7%99%D7%99%D7%9D_%D7%90_%D7%90");

A: Check if the server, you are trying to access is set up to use improved TLS protocol.
Make sure to add this to Global.asax.cs
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;


text:
Q: Remove specific regions from fo file in xsl-fo I have a xsl-fo file defined as below ,
<?xml version="1.0" encoding="utf-8" ?>
<fo:root xmlns:fo="http://www.w3.org/1999/XSL/Format">
  <fo:layout-master-set>
    <fo:simple-page-master master-name="master">
      <fo:region-body margin-bottom="0.5in" margin-top="0.9in" margin-left="35pt"/>
      <fo:region-before region-name="xsl-region-before" extent="0.9in"/>
      <fo:region-after region-name="xsl-region-after" extent="0.5in"/>
    </fo:simple-page-master>
  </fo:layout-master-set>
  <fo:page-sequence master-reference="master">

    <fo:static-content flow-name="xsl-region-before">
    Some not needed things will be here
    </fo:static-content>

    <fo:static-content flow-name="xsl-region-after">

    Some not needed things will be here

    </fo:static-content>

    <fo:flow flow-name="xsl-region-body">
      <fo:block font-size="10pt" xmlns:fo="http://www.w3.org/1999/XSL/Format">
  <fo:table table-layout="fixed" space-after="0pt" border-collapse="separate" border-separation="0pt">
// This is the content that I need
  </fo:table>
</fo:block>
      <fo:block id="end"/>
    </fo:flow>
  </fo:page-sequence>
</fo:root>

Is there any way I can remove some regions that are defined in this fo that I do not need for processing ? What I am trying to do is remove the <fo:static-content flow-name="xsl-region-after"> and <fo:static-content flow-name="xsl-region-before"> competely from this . How can I do that . Would really appreciate some help

A: Assuming that you have an XSLT processor available, you can use a stylesheet that is an identity template plus a higher-priority template that drops the elements that you don't want:
<xsl:stylesheet
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    version="2.0"
    xmlns:fo="http://www.w3.org/1999/XSL/Format">

<xsl:template match="fo:static-content" />

<!-- Identity template. -->
<xsl:template match="@* | node()" mode="#all">
  <xsl:copy>
    <xsl:apply-templates select="@* | node()" mode="#current"/>
  </xsl:copy>
</xsl:template>

</xsl:stylesheet>


text:
Q: problem when trying to use terraform remote mirrors on artifactory I am trying to work together with some colleagues on setting up a static mirror on artifactory to avoid doing so many remote pulls from the remote repository.
I read this articles and I thought I was all set but I'm still failing and I wanted to know if I could get some hints.
https://www.terraform.io/internals/provider-network-mirror-protocol
https://www.terraform.io/cli/config/config-file#network_mirror
So I have defined the mirror and I can see some plugins in it

And then I configured it in my configs:
provider_installation {
    network_mirror {
        url = "https://registry.sits.abc.net/virtual-generic-terraform-cp/"
    }
}

(UPDATE first issue was the missing trialing /)
However when I do my terraform init I am getting problems with accessing the providers.
$ terraform init

Initializing the backend...

Initializing provider plugins...
- Finding hashicorp/aws versions matching "~> 3.0"...
- Finding latest version of hashicorp/random...
â•·
│ Error: Failed to query available provider packages
│
│ Could not retrieve the list of available versions for provider
│ hashicorp/aws: host registry.sits.abc.net rejected the given
│ authentication credentials
╵

â•·
│ Error: Failed to query available provider packages
│
│ Could not retrieve the list of available versions for provider
│ hashicorp/random: failed to query provider mirror
│ https://registry.sits.abc.net/virtual-generic-terraform-cp/ for
│ registry.terraform.io/hashicorp/random: invalid response content from
│ mirror server: invalid character '<' looking for beginning of value
╵

I have the provide in my code defined as I normally do it.
terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 3.0"
    }
  }
}

By looking at the log I wonder if I need to define the provider in a different way now that I'm trying to use a mirror?
Any tips are welcomed it's very likely I'm doing something wrong on my side since I recently started exploring terraform


text:
Q: C#, usage of custom exceptions I need to make a short premise: I am a software architect with more than 20 years of experience, not a junior asking directions. This is not to say "I know it all" (quite the contrary in fact) but just to give context and state that I have come across a legitimate doubt about something I thought was common knowledge and best practice and have done so for all this time.
I am working on different projects for different clients. I always check method's parameters for not being null and for other non valid states. A common precondition check you can find in my code is:
if (param == null) { throw new ArgumentNullException(nameof(param)); }

or
this.myField = myParam ?? throw new ArgumentNullException(nameof(myParam));

Also bear in mind that I use exceptions sparingly, I do not do user input validation with exceptions, I just use them to check and/or signal invalid states in the code, thus programming errors. It's extremely rare to find a try/catch block in my code at all.
One of my clients just asked me, without much margin to debate, to replace any similar occurrence with the use of custom exceptions. Meaning I am to define a CustomerNameArgumentNullException, CustomerNameFileNotFoundException, etc. and use those wherever I would use a standard exception.
Now I will comply, I have no right to debate the client request, but their lead programmer was pretty strong about this point on how this is the right way to go, that using default exceptions makes code less readable and also that custom exceptions make more easy to see what-is-what in Azure Application Insights. I tried to point out that he has the fully qualified name of the method that raised the exception so he can know which program, in which assembly and namespace and such but again, there was not much room to debate and it was not my place to do so.
So I've been wondering if he's actually right and I've been doing exceptions wrong all this time. If anyone has some more insight and/or some material I can read about that supports this theory.
Thanks.

A: While normally I'd suggest that a question like this should be closed as opinion-based, in this case there's really clear guidance from Microsoft:

Use the predefined .NET exception types
Introduce a new exception class only when a predefined one doesn't apply. For example:

*

*Throw an InvalidOperationException exception if a property set or method call is not appropriate given the object's current state.

*Throw an ArgumentException exception or one of the predefined classes that derive from ArgumentException if invalid parameters are passed.

In other words, your customer is asking you to go against guidance from the platform authors.
You may not be able to change the customer's mind to follow the guidance, but you can be confident that your approach is the recommended one, and their approach goes against that.
Following conventions like this is particularly important in Open Source projects - it's one thing to decide that you'll have your own conventions when only your team will work with the code, but if an application uses 10 different Open Source libraries, each of which has decided to create its own conventions, that's a nightmare.

A: There are two sides of the coin. Sure MS recommends this
Using custom exceptions gives you some advantages and disadvantages.
Advantages:

*

*Abstraction

*You can log telemetry data before you raise an exception. If not for custom exceptions, you'd have to catch an exception, log data and re-throw.

*Customizing exception and error handling as needed by the app/services, etc

Disadvantages:

*

*Telemetry data will have no stack trace if you are throwing custom exceptions.

*Code maintenance and rigorous testing

There are various other things that come into picture, but catching an exception, logging metrics and then re-throwing (to preserve stack trace) the same exception is expensive.
Just my thoughts.


text:
Q: Replace some of a matched string in javascript I'm working on a grid layout function. I'm about 1/2 way there and have hit a wall.
I am using a string and running a single RegExp function per box I'm placing in the grid to determine where it will fit (based on number of rows/columns it occupies). This works successfully. Demonstration:
function findSpace(columns, rows){
    var totalColumns = 4;
    var grid = "11002100020000200002";
    //1 represents occupied space, 0 empty space, and 2 a new line
    var reg = RegExp("(0{" + columns + "})(([0-2]{" + (totalColumns - columns + 1) + "})0{"+columns+"}){" + (rows-1) + "}");
    var i = grid.search(reg);
    return i.index;
}

Returns the index of the match, letting me know where in my grid this box will fall. See fiddle.
I fall short trying to replace the "0"s with "1"s. Doing grid.replace(reg, "1") of course replaces everything from the beginning of the match to the end with a single "1". I need to replace just the "0"s that will be occupied for row and column, each with a "1", and not any of the characters matched between.
This is an exercise in doing things differently. Yes, I could do this with an array data structure. What fun is that? I'm not looking for a "don't do it this way do it the way everyone else does" answer, I'm trying to determine the most efficient way to solve my scenario.
Thanks!

A: The String#replace method might be the ticket. If you pass a regular expression and a function as the second parameter, you can dynamically manipulate each match.
Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace


text:
Q: Using SetGlobalSpanCostCoefficient lead to worse routes in OR-tools VRP I'm using OR-tools VRP to create delivery routes. I have distance as a dimension, a dimension to constrain the number of delivery points per route and my code is very similar to the guide shared in https://developers.google.com/optimization/routing/vrp
The issue I have is that when using SetGlobalSpanCostCoefficient as below, the resulting routes have very short distances from the depot to the first delivery point and from the last delivery point to the depot, but instead, the distances between delivery points is high. Instead, when not using this SetGlobalSpanCostCoefficient the routes have very low distances between delivery points but the distance from and to the depot are higher.
distance_dimension = routing.GetDimensionOrDie(dimension_name)
distance_dimension.SetGlobalSpanCostCoefficient(100)

Also, when not using the span cost, the sum of the distances of all routes is lower. Based on the metrics and how the routes look in a map, I think that not using the span cost is better. See the routes on the images below, first not using the span cost and second using it.

My concern is that if I'm not using the span cost, I don't know if the solver is optimizing the routes or it just creates a greedy solution (I'm using PATH_CHEAPEST_ARC as first solution strategy). Can someone explain why I'm getting these routes in both cases and tell me if the routes I'm getting when not using the span are optimal?

A: In both cases you'll always have the arc cost added to the objective, the global span cost coefficient add an EXTRA cost being coeff * (max_end - min_start)
note: When using a coefficient of 100 it just makes this cost the dominant factor...
First the solver try to create an initial solution using the first strategy heuristic.
Then if local search is enable, solution may be improved drastically
-> do you enable local search ?
    search_parameters.local_search_metaheuristic = (
        routing_enums_pb2.LocalSearchMetaheuristic.GUIDED_LOCAL_SEARCH)
    search_parameters.log_search = True
    search_parameters.time_limit.FromSeconds(20)


text:
Q: How to pass variable to tile (tiles library) I handle templates of my application using tiles library.
tile.xml:
<definition name="template1" template="/WEB-INF/template/default/template1.jsp">
   ...
    <put-attribute name="menu" value="/WEB-INF/template/default/menu.jsp" />
   ...
</definition>

template1.jsp
<html>
    <body>
        ...
        <tiles:insertAttribute name="menu" />
        <tiles:insertAttribute name="menu" />
        ...
    </body>
</html>

As you can see I have to insert to tiles "menu". Since I have to dinamically print different menu inside "menu.jsp", how can I send 2 different variables to the 2 different tiles "menu"?
To be clearer
   <html>
        <body>
            ...
            <tiles:insertAttribute name="menu" /> <--- here I should pass a variable called menu1
            <tiles:insertAttribute name="menu" /> <--- here I should pass a variable called menu2
            ...
        </body>
    </html>

Thanks everybody

A: You need to have two templates
<definition name="template1" template="/WEB-INF/template/default/template1.jsp">
   ...
    <put-attribute name="menu" value="/WEB-INF/template/default/menu1.jsp" />
   ...
</definition>

<definition name="template2" template="/WEB-INF/template/default/template1.jsp">
   ...
    <put-attribute name="menu" value="/WEB-INF/template/default/menu2.jsp" />
   ...
</definition>

<html>
    <body>
        ...
        <tiles:insertAttribute name="menu" />
        ...
    </body>
</html>

Update
You can use this approach too
<definition name="menu1" template="menu.jsp">
   ...
  <put name="header.tile" value="headerMenu1.jsp" />
   ...
</definition>

<definition name="menu2" template="menu.jsp">
   ...
  <put name="header.tile" value="headerMenu2.jsp" />
   ...
</definition>

In the menu.jsp
<tiles:insert attribute="header.tile" />


text:
Q: How to forced cancel BeginExecuteXmlReader() executing What is the best way to forced cancel query executing which has been started via BeginExecuteXmlReader() method of SqlCommand class on some timeout?
Tnank you.


text:
Q: I would like the MIN - MAX from each month and every site_id First Table: site_map_pae
id |  site_id   | site_name |  off_id
1    213140951       Med         3
2    213140952     Vedmed        3

Second Table: electric
id |        timeIn           | energy  |  site_id
1     2022-07-07 07:20:35        150     213140951
2     2022-07-07 10:46:23        155     213140952
3     2022-07-09 18:37:23        160     213140951
4     2022-08-01 14:46:23        170     213140951
5     2022-08-03 19:46:23        180     213140952
6     2022-08-06 20:46:23        190     213140952
7     2022-08-09 13:37:23        200     213140951

***the results that I would like to achieved is like this.
id |        timeIn           | result_energy
1     2022-07-09 18:37:23          10
2     2022-08-09 13:37:23          40

this is my query. I would like SQL Inner join via off_id = "3" on table site_map_pae.
`
SELECT Max(DISTINCT energy)-MIN(DISTINCT energy) as result_energy, max(timeIn) as timeIn
FROM Electric.site_map_pae AS t1
INNER JOIN Electric.electric AS t2
ON t1.site_id = t2.site_id
WHERE t1.off_id = "3"
AND t2.timeIn BETWEEN '2022-01-01 00:00:00' and '2022-12-31 23:59:59'

`
my results:

     id |  result_energy |      timeIn
      1      50.00         2022-08-09 13:37:23

A: You have no grouping in your query so it just shows 1 row.
Since you want it for each month, each site_id then you need to group by month and site_id.
MONTH(timeIn) will get the month from the timeIn field.
SELECT Max(DISTINCT energy)-MIN(DISTINCT energy) as result_energy,MONTH(timeIn) as timeIn_month, t1.site_id
FROM Electric.site_map_pae AS t1
INNER JOIN Electric.electric AS t2
ON t1.site_id = t2.site_id
WHERE t1.off_id = "3"
AND t2.timeIn BETWEEN '2022-01-01 00:00:00' and '2022-12-31 23:59:59'
GROUP BY MONTH(timeIn), t1.site_id

Something like this, hope it helps.


text:
Q: Custom Mix Task to generate ex files I'm currently trying to write a mix task that automates the scaffolding of an Elm app in a phoenix (v1.3) project. It's generating all the elm files / js script to add, installing node and elm modules correctly. I'm also generating an elm_view.ex and elm_controller.ex that takes the name of the current otp_app, and it outputs the files correctly like below:
defmodule PipeDream.Web.ElmController do
  use PipeDream.Web, :controller

  def index(conn, _params) do
    render conn, "index.html"
  end
end

However, when I start the server with mix phx.server I get an error: "module PipeDream.Web.ElmController is not available". I've found that when I go to these files and save them the module gets picked up correctly (similar error with the elm_view.ex).
Could this be something to do with how I'm rendering the controller and view templates? The templates look like this:
defmodule <%= @app_name %>.Web.ElmController do
  use <%= @app_name %>.Web, :controller

  def index(conn, _params) do
    render conn, "index.html"
  end
end

and I'm using EEx.eval_string(template_string, assigns: [app_name: app]) to add the app module name and then writing the file with Mix.Generator.create_file
Would be super grateful for any help or suggestions!

A: Since there are many comments above, I decided to post a [hacky but yet working] solution as an answer for the future visitors.
There is some kind of file creation time issue when Elixir/Mix try to cache/check the dependencies. While the sledgehammer solution proposed by Steve Pallen (rm -rf deps && rm -rf _build && mix do deps.get, deps.compile, compile) should work always, there might be a more handy hack: call File.touch/2 on newly generated files to enforce Mix to recompile them.
Also, as a sidenote, I would suggest to use Mix.Generator.embed_template/2 to compile and embed template, rather than generic EEx.eval_string to clarity the intent.


text:
Q: How do I hide a range of rows by getting the start and end row values from user input cells? I have a sheet of 1,000 plus rows.
I'm trying to hide all rows that match the values I input into cells A1 (the starting row in the range), and cell A2 (the end row in the range).
Sub Macro1()
'
' Hide rows when row numbers are between the values in cell A1 and Cell A2.
'
'   Range("A1:A15").Select 'Trying to modify this so that I get values from Cells A1 and A2.
    Rows(Range("A1").Value:Range("A2").Value).Select ' This is my failed attempt.
    Selection.EntireRow.Hidden = True
    Range("A1").Select
End Sub

A: Based on my comment, I'm going to assume you want to hide the rows (inclusive) between the two values you specify in A1 and A2.
You'll need to clean it up to make sure the correct sheet is having this applied to it.  Right now, it works on the active sheet.
I've also assumed that if you change the numbers, you want to unhide all of the previously hidden rows.
Public Sub HideRows()
    Dim lngRowFrom As Long, lngRowTo As Long, objSheet As Worksheet

    Set objSheet = ActiveSheet

    With objSheet
        On Error GoTo ErrorCatchNotNumeric

        lngRowFrom = .Range("A1").Value
        lngRowTo = .Range("A2").Value

        On Error GoTo 0

        If lngRowFrom > .Rows.Count Or lngRowFrom < 1 Then GoTo ErrorCatchNotNumeric
        If lngRowTo > .Rows.Count Or lngRowTo < 1 Then GoTo ErrorCatchNotNumeric

        If lngRowFrom > lngRowTo Then
            MsgBox "Your ""From"" row is greater than your ""To"" row.", vbCritical, "Error"
        Else
            .Rows.Hidden = False
            .Rows(lngRowFrom & ":" & lngRowTo).EntireRow.Hidden = True
        End If
    End With

    Exit Sub

ErrorCatchNotNumeric:
    MsgBox "The values you supplied are not valid!", vbInformation, "Error"

End Sub

Adapt it as you see fit.


text:
Q: Conditional Probability Concept Question The organizers of a cycling competition know that about 8% of the racers use steroids. They decided to employ a test that will help them identify steroid-users. The following is known about the test: When a person uses steroids, the person will test positive 96% of the time; on the other hand, when a person does not use steroids, the person will test positive only 9% of the time. The test seems reasonable enough to the organizers. The one last thing they want to find out is this: Suppose a cyclist does test positive, what is the probability that the cyclist is really a steroid-user.
S be the event that a randomly selected cyclist is a steroid-user and P be the event that a randomly selected cyclist tests positive.
***My questions is Can someone please translate and explain P(P|S) and P(S|P) ?

A: We are given that $P(S)=0.08$ (hence $P(\neg S)=0.92$), $P(P|S)=0.96$ and $P(P|\neg S)=0.09$.
What we want to knwo is $P(S|P)$.
Note that $P(S\cap P)=P(S|P)\cdot P(P)$ as well as $P(S\cap P)=P(P|S)\cdot P(S)$, therefore
$$ P(S|P) = \frac{P(P|S)\cdot P(S)}{P(P)}.$$
Thus we first need $P(P)$, which we get from $P(P)=P(P|S)P(S)+P(P|\neg S)P(\neg S)$. At last now all is reduced to given values.

A: $\Pr(P|S)$ is the probability that the person tests positive, given that she uses steroids. We are told explicitly that this is $0.96$.
$\Pr(S|P)$ is the probability she is a steroid user, given that she tests positive. That is what we are asked to find.  Informally, if we confine attention to the people who test positive, $\Pr(S|P)$ measures the proportion of them that really are steroid users.
Since the problem says that the proportion of steroid users is not high (sure!), many of the positives will be false positives.  Thus I would expect that $\Pr(S|P)$ will not be very high: the test is not as good as it looks on first sight.
For computing, there are two ways I would suggest, the first very informal and probably not acceptable to your grader, and the second more formal.
$(1)$: Imagine $1000$ cyclists. About how many of them will test positive? About how many of these will be steroid users?  Divide the second number by the first, since $\Pr(S|P)$ asks us to confine attention to the subpopulation of people who tested positive.
$(2)$: Use the defining formula
$$\Pr(S|P)=\frac{S\cap P}{\Pr(P)}.$$
The two numbers on the right are not hard to compute. I can give further help if they pose difficulty.

A: Here is a relatively plain English explanation for Bayesian statistics.
Here, you have an evidence which says a user tested positive and the hypothesis you want to test against is whether steroids were used.
P(H | E) = P(E|H) x P(H) / [ P(E|H) x P(H) + P(E|~H) x P(~H) ]
from your numbers, P(H) = 8% so P(~H) = 92%, P(E|H) = 96% and P(E|~H) = 9%. Plug in all these numbers and you get ~ 48% which is quite low.


text:
Q: Perspective trigonometry I was thinking of a question for a while now.
R1 is radius of small circle, R2 is radius of large.
The small circle is actually the base of a right cylinder and the big circle is the top.
So in reality R1=R2. Given that R2=k*R1, k is some proportion, in the picture
is there a way to determine the height of the cylinder?
I came to this question because originally I was thinking if there is a way to figure out the distance from observer A to B with a camera. You essentially move the camera upwards perpendicular to ground by x meter at the same time detecting by how much observer B moved (just like the cylinder question distance B moved is simply how it looks like on 2D).
Thanks ahead of time.

A: If $V$ is the viewpoint, then it must be aligned with the cylinder axis (dashed line in the diagram below), which in turn is perpendicular to the view plane $\pi$. If $v$ is the distance between $V$ and $\pi$ and $d$ is the distance between $\pi$ and the front base of the cylinder, then by similar triangles we have:
$$
R_2:R=v:(v+d),
\quad\hbox{and}\quad
R_1:R=v:(v+d+h).
$$
By dividing the first equation by the second we obtain:
$$
R_1:R_2=(v+d+h):(v+d).
$$
To solve for $h$ you then need to know $d+v$.


text:
Q: How to test Material2 snack-bar? I have a project on Angular 5 and I encountered with following issue. I have a
component ComponentWithSnackBar which triggers displaying of a snack-bar:
showSnackBar() {
  this.snackBar.open('Message text', 'Close', {
    duration: 5000,
    verticalPosition: 'top',
  });
}

It works as expected. But I have no ideas how I can test it. I try to write test:
describe('ComponentWithSnackBar', () => {
  let snackBar: MatSnackBar;
  let overlayContainer: OverlayContainer;
  let overlayContainerElement: HTMLElement;

  function createComponent<T>(component: Type<T>, providers: Provider[] = [], declarations: any[] = []): ComponentFixture<T> {
    TestBed.configureTestingModule({
      imports: [AppModule, RouterTestingModule, NoopAnimationsModule],
      declarations: declarations,
      schemas: [CUSTOM_ELEMENTS_SCHEMA],
      providers,
    }).compileComponents();

    inject([MatSnackBar, OverlayContainer], (sb: MatSnackBar, oc: OverlayContainer) => {
      snackBar = sb;
      overlayContainer = oc;
      overlayContainerElement = oc.getContainerElement();
    })();

    return TestBed.createComponent<T>(component);
  }

  it(`Should display snack-bar`, fakeAsync(() => {
    const fixture = createComponent(ComponentWithSnackBar);
    const component: ComponentWithSnackBar = fixture.debugElement.componentInstance;

    fixture.detectChanges();
    const button = fixture.debugElement.query(By.css('button')); //button which triggers method showSnackBar
    button.triggerEventHandler('click', null);
    fixture.detectChanges();
    flush();

    const messageElement = overlayContainerElement.querySelector('snack-bar-container');
    expect(messageElement.textContent).toContain('Message text');
  }));
});

As a result I get error

TypeError: Cannot read property 'textContent' of null

What I do wrong? Thanks for advance!

A: The following worked for me:
describe('MyComponent', () => {
  let component: MyComponent;
  let fixture: ComponentFixture<MyComponent>;
  let element: any;
  let overlayContainer: OverlayContainer;
  let overlayContainerElement: HTMLElement;
  let snackBar: MatSnackBar;

....

beforeEach(() => {
    fixture = TestBed.createComponent(MyComponent);
    component = fixture.componentInstance;
    element = fixture.nativeElement;
    fixture.detectChanges();
  });

beforeEach(inject([MatSnackBar, OverlayContainer],
    (sb: MatSnackBar, oc: OverlayContainer) => {
      snackBar = sb;
      overlayContainer = oc;
      overlayContainerElement = oc.getContainerElement();
    }));

....

 it('should show my success message', () => {

   const containerElement = overlayContainerElement.querySelector('simple-snack-bar');

   expect(containerElement.textContent).toContain('My success text');
 });

A: I decided do not test fact of displaying of snack-bar, but only fact of call method snackBar.open() with correct arguments:
expect(snackBarSpy.open.calls.count()).toEqual(1);
expect(snackBarSpy.open.calls.first().args).toEqual([message, 'Close', {duration: 5000, verticalPosition: 'top'}]);

A: I ran into a similar issue when trying to test a component with a material dialog. I didn't find the solution but I figured I'd share what I do know:
If you put a breakpoint on the test when running and inspect the scope, the overlayContainerElement (which is the div with the class cdk-overlay-container) has no child nodes.
Also if you add the following to the end of the test before the expect statement:
console.log("overlay wrapper", document.getElementsByClassName('cdk-global-overlay-wrapper')[0]);
// and or
console.log("snackbar text", document.getElementsByClassName('snack-bar-container')[0]); // or whatever class you gave this item

They both log undefined.
My theory is that Angular change detection does not get run on the components that are involved with displaying material parts such as the dialog or snackbar which is why they are empty/not showing during the test.
Can you also share the code for the ComponentWithSnackBar?

A: const mockSnackbar = jasmine.createSpyObj(['open']);

it('test desc'()=>{
    component.showSnackBar()
        expect(mockSnackbar.open).tohavebeencalled();
        expect(mockSnackbar.open).tohavebeencalledwith('Message text',
            'Close', {
                duration: 5000,
                verticalPosition: 'top',
            });
})


text:
Q: iterate replacing elements with the most frequently occurring element in a data frame I am a novice at R programming and try to use it for my data handling.
I am trying to create new data frame by replacing some elements with the most frequently occurring element in my data frame.
My original data frame is like this :
df:
id | first_name | last_name | info_1 |infor_2
---|------------|-----------|--------|-------
 1 |  Hillary   |  Clinton  |    2   |  3
 1 |  Hillary   |  Clinton  |    10  |  2
 2 |  Donald    |  Trump    |    5   |  6
 2 |  Donald    |  Trump    |    3   |  8
 4 |  Hillary   |  Clinton  |    9   |  5
 3 |  Bernie    |  Sanders  |    5   |  0
 3 |  Donald    |  Trump    |    4   |  9
 3 |  Bernie    |  Sanders  |    24  |  9
 6 |  Bernie    |  Sanders  |    24  |  9

The new data frame should look like this:
new_df:
id | first_name | last_name | info_1 |infor_2
---|------------|-----------|--------|-------
 1 |  Hillary   |  Clinton  |    2   |  3
 1 |  Hillary   |  Clinton  |    10  |  2
 2 |  Donald    |  Trump    |    5   |  6
 2 |  Donald    |  Trump    |    3   |  8
 1 |  Hillary   |  Clinton  |    9   |  5
 3 |  Bernie    |  Sanders  |    5   |  0
 2 |  Donald    |  Trump    |    4   |  9
 3 |  Bernie    |  Sanders  |    24  |  9
 3 |  Bernie    |  Sanders  |    24  |  9

As you can see in the first data frame, "1" is the most frequently occurring id for Hillary Clionton, but there appears "4" on the 5th row. So, I want to replace all id for Hillary Clinton by "1". This operation should be applied for all others name (Bernie Sanders and Donald Trump).
To my understanding, it can be done by "if" and "for", but I couldn't find clear solution.
Any help would appreciate!
Joseph

A: using this great custom mode function:
Mode <- function(x) {
    ux <- unique(x)
    ux[which.max(tabulate(match(x, ux)))]
}

then library(dplyr):
library(dplyr)
df %>% group_by(last_name) %>% mutate(id = Mode(id))

Source: local data frame [9 x 5]
Groups: last_name [3]

     id first_name last_name info1 info2
  <int>      <chr>     <chr> <int> <int>
1     1    Hillary   Clinton     2     3
2     1    Hillary   Clinton    10     2
3     2     Donald     Trump     5     6
4     2     Donald     Trump     3     7
5     1    Hillary   Clinton     4    11
6     3     Bernie   Sanders     3     2
7     2     Donald     Trump     5     6
8     3     Bernie   Sanders    24     8
9     3     Bernie   Sanders    12    11

A: This can be achieved by using factor on the last name:
df$id <- as.integer(factor(df$last_name, levels=c("Clinton", "Trump", "Sanders")))

df
  id first_name last_name info1 info2
1  1    Hillary   Clinton     2     3
2  1    Hillary   Clinton    10     2
3  2     Donald     Trump     5     6
4  2     Donald     Trump     3     7
5  1    Hillary   Clinton     4    11
6  3     Bernie   Sanders     3     2
7  2     Donald     Trump     5     6
8  3     Bernie   Sanders    24     8
9  3     Bernie   Sanders    12    11

To change the ID order, simply change the order that you feed to the levels argument of factor.


text: Q: number of maximizers Suppose f(x) is continuous in x∈X, where X is compact. Let T(x):=argmaxf(x) be the set of maximum of f(x), where the maxf(x) is bounded. Then under what condition the set T(x) cannot contain infinitely many distinct points? Here x' and x'' are said to be distinct if there is no path in T(x) connecting x' and x''. I know that the bounded variation is sufficient (or piecewise monotone), but can we have even more general conditions? Thank you!


text:
Q: How to get the Unix Timestamp for one month in the future given a date Suppose I pull a field from the database, a timestamp field.
How do I get the Unix Timestamp, 1 month in the future, from that timestamp field?
My brain is a bit tired, so I need a bit of a re-jogging.

A: I would use the strtotime() function, to add +1 month to your timestamp :
$future = strtotime('+1 month', $current_time);

With strtotime(), you don't have to think yourself about stuff like "some month avec 30 days, and others have 31", or "february sometimes has 28 days and sometimes 29".
After all, adding one month to a date is a bit harder that adding 30*24*3600 seconds...

You could also work with the DateTime class, and methods such as DateTime::modify() or DateTime::add().

A: $newDate = strtotime('+1 month',$startDate);

Using strtotime() you can pass it '+1 month' to add a context sensitive month.

A: Wouldn't
strtotime('+1 month', $value_from_db);

work?

A: Depends on the database.

*

*MySQL has TIMESTAMPADD

*Postgre lets you just add INTERVAL 1 MONTH.

*Oracle... is annoying. But you can find out how to do that here.

(Don't know the others, sorry)
Of course there is also strtotime('+1 month', $current_time); in PHP. Of course, strtotime is so incredibly easy you might consider it cheating ;-).

A: How about something like:
tm *currTime = localtime(timestamp);

currTime->tm_mon++;

timestamp = mktime(currTime);


text:
Q: Why is it getting slower and slower each time I call the formatted() method of the Decimal type in Swift? I needed to separate integers into 3-digit numbers and looked into the formatted() method of the Decimal type.
Calling the formatted() method of type Decimal 100,000 times each for a random integer gradually degrades performance.
I would like to know why this happens.
import Foundation

/// https://stackoverflow.com/a/56381954
func calculateTime(block : (() -> Void)) {
  let start = DispatchTime.now()
  block()
  let end = DispatchTime.now()
  let nanoTime = end.uptimeNanoseconds - start.uptimeNanoseconds
  let timeInterval = Double(nanoTime) / 1_000_000_000
  print("Time: \(timeInterval) seconds")
}

calculateTime { for _ in 0...100_000 { _ = Decimal(Int.random(in: 0...Int.max)).formatted() } }
calculateTime { for _ in 0...100_000 { _ = Decimal(Int.random(in: 0...Int.max)).formatted() } }
calculateTime { for _ in 0...100_000 { _ = Decimal(Int.random(in: 0...Int.max)).formatted() } }
calculateTime { for _ in 0...100_000 { _ = Decimal(Int.random(in: 0...Int.max)).formatted() } }
calculateTime { for _ in 0...100_000 { _ = Decimal(Int.random(in: 0...Int.max)).formatted() } }
calculateTime { for _ in 0...100_000 { _ = Decimal(Int.random(in: 0...Int.max)).formatted() } }
calculateTime { for _ in 0...100_000 { _ = Decimal(Int.random(in: 0...Int.max)).formatted() } }
calculateTime { for _ in 0...100_000 { _ = Decimal(Int.random(in: 0...Int.max)).formatted() } }

Time: 0.9492465 seconds
Time: 3.29213125 seconds
Time: 7.988363667 seconds
Time: 15.165178292 seconds
Time: 17.305036583 seconds
Time: 25.0114935 seconds
Time: 35.746310417 seconds
Time: 47.024551125 seconds

A: While matt and Martin R are correct, they didn't actually point to the culprit. When you use the "Memory Object" Debugger, while the functions are executing, you will see this very interesting graph:

So, the function formatted() causes a LOT of allocations, mainly objects of type NSAutoLocale.
This hints to further issues: since evaluating a locale requires to access a file where the locale is actually read from, you may also experience very slow performance.
So, if you want to speed it up, too, you should explicitly use a pre-configured locale object, which you allocate once, and only once, which you then use as a parameter to format the string.
Edit:
In order to prove my hypothesis, I created an equivalent statement and compared that with your original:
Your original code:
calculateTime { for _ in 0...100_000 { _ = Decimal(Int.random(in: 0...Int.max)).formatted() } }

Time: 9.674371748 seconds
The equivalent code using a single locale:
let locale = Locale()
calculateTime { for _ in 0...100_000 { _ = NSDecimalNumber(
    value: Int.random(in: 0...Int.max))
    .description(withLocale: locale)
} }

Time: 0.210493037 seconds
AND without any further modifications, calling the improved statement repeatedly, you get this:
Time: 0.224133942 seconds
Time: 0.238930039 seconds
Time: 0.214735965 seconds
Time: 0.220390686 seconds
Time: 0.212360066 seconds
Time: 0.207630215 seconds
Time: 0.205125154 seconds

...

A: It's a Heisenbug: you are causing the slowdown yourself by straining memory with your test harness. Change your test lines to:
calculateTime { for _ in 0...100_000 { autoreleasepool { _ = Decimal(Int.random(in: 0...Int.max)).formatted() } } }
calculateTime { for _ in 0...100_000 { autoreleasepool { _ = Decimal(Int.random(in: 0...Int.max)).formatted() } } }
calculateTime { for _ in 0...100_000 { autoreleasepool { _ = Decimal(Int.random(in: 0...Int.max)).formatted() } } }
// ... and so on

A: Your formatter uses auto-released strings. By the time of your last call there are already 700,000 auto released strings in an auto release pool. That will slow you down.
Plus the formatting will produce lots of auto-released formattting objects, making it worse.


text:
Q: How to monkey patch a ruby class inside a method I am unable to monkey patch a class inside a method body.
Within a method definition,
I am trying to use a class in two ways:
1] Create an instance and use the orignal definition of a method in the class I am using
2] Monkey patch (pverride) a method in the class and now use an instance with the new method definition.
Basically I would be using both of the above instances of a class in my program.
The challenge is the method I am overriding gets called during initialization so I have to override it before I create the instance of the class.
Here is a small mock-up:
class A

  def initialize
   do_something
  end

  def do something
     #implementation
  end

end

Now , I want to use A in the same method twice , but once by using a modified version of do_something
This is how I am trying to do it:
def my_method

  orig_instance = A.new

  #patch the class
  Class A          # ERROR: CLASS DEF IN METHOD BODY
   class << self
     alias_method :old_do_something, :do_something

     def self.do_something
        # new implementation
     end
  end

  new_instance = A.new

  #restore method
   class << self
     alias_method :do_something,:old_do_something

     def self.do_something
        # new implementation
     end
  end

end # end of method

I get the (ERROR: CLASS DEF IN METHOD BODY) where I try to monkey patch the class, since I am trying to change the class inside of a method.
How do I achieve monkey patching the class in a method ?
Thanks

A: Instead of using class Clazz; blabla; end to reopen Clazz and monkey patch it, you can use Module#class_eval, Module#instance_eval and some other meta-programming utilities/methods to do the same trick. And because that block accepted by these methods doesn't create new binding scopes, it is more convenient in meta-programming practice.
def my_method
  puts ">> creating orig_instance"
  orig_instance = A.new

  puts ">> dump orig_instance"
  orig_instance.do_something

  new_do_something = lambda do
    puts "Modified A#do_something"
  end

  # monkey patch class A so that the modified version of do_something get called
  # during initialization of new_instance
  A.class_eval do
    alias_method :old_do_something, :do_something
    define_method :do_something, new_do_something
  end

  puts ">> creating new_instance"
  new_instance = A.new

  puts ">> dump before do_something gets restored"
  new_instance.do_something
  orig_instance.do_something

  # add singleton method for the special instance
  # so that the instance always calls the modified do_something
  new_instance_singleton = class << new_instance; self end
  new_instance_singleton.send :define_method, :do_something, new_do_something

  # restore the modified do_something
  # so that orig_instance and all other instances (except new_instance) have the original definition
  A.class_eval do
    alias_method :do_something, :old_do_something
  end
  puts ">> dump for final result"
  new_instance.do_something
  orig_instance.do_something
end

And the following is the output of my_method call:
>> creating orig_instance
Original A#do_something
>> dump orig_instance
Original A#do_something
>> creating new_instance
Modified A#do_something
>> dump before do_something gets restored
Modified A#do_something
Modified A#do_something
>> dump for final result
Modified A#do_something
Original A#do_something


text:
Q: 3045 : The Currency field is missing I'm getting following error in salesforce integration with sagepay test environment. I'm using 'AES128' Algorithm.
This transaction attempt has failed. We are unable to redirect you back to the web store from which you were purchasing. The details of the failure are given below.

Status: MALFORMED

Status Detail:  3045 : The Currency field is missing.

My Source System is Salesforce. We are using AES128 Crypto algorithm.
Blob stringToEncrypt = Blob.valueOf('VendorTxCode=Vtest&Amount=10&Currency=GBP&Description=test description&SuccessURL=https://ap1.salesforce.com/a01&FailureURL=https://ap1.salesforce.com/a01&BillingSurname=Ravi&BillingFirstnames=test ravi&BillingAddress1=BillAddressLine1&BillingCity=Atlanta&BillingPostCode=30004&BillingCountry=US&DeliverySurname=test&DeliveryFirstnames=Fnames&DeliveryAddress1=test&DeliveryCity=Atlanta&DeliveryPostCode=3004&DeliveryCountry=US');

Blob cryptoKey = Blob.valueOf('key');
Blob encryption = Crypto.encrypt('AES128', cryptoKey, cryptoKey, stringToEncrypt);

Thanks in Advance.

A: Have you checked the padding is PCKS#5? Error 3045 (currency) is the first to crop up when the encryption is wrong....


text:
Q: ExtJS 6. Use data from 1st store in 2nd store constructor There are 2 stores. I need data from 1st store in 2nd store constructor. How can it be done?

A: This would be rather easy, but useless.
To achieve what you want you have to create store2 from the load() event of store1, and you may not bind the store to any component before said load event.
Ext.define('MyApp.store.Store1',{
    ...
    listeners:{
        load:function(store, records) {
            var store2 = Ext.getStore("store2") || Ext.create('MyApp.store.Store2',{
                store1data: records
            });
            Ext.getCmp("someCombobox").bindStore(store2); // you would have to use ext-empty-store on the combobox before, or else it may trigger store creation too early
        }

BUT this is not good programming style nor does it serve any real purpose. Normally you would want to call some function for store2 again whenever store1 gets new data. There is nearly nothing you have to do during store construction, that cannot be done afterwards using reconfigure or other store methods. (notable exception: you have to decide during construction whether it is an array store or a json store or a tree store).
So for instance you can define a method on store2 and call that just after store1 has been reloaded:
store2.someFunction = function(store1Records) {
    var store2 = this;
    Ext.each(store1Records,function(record) {
        store2.getProxy().setExtraParam(record.get("paramName"),record.get("paramValue"));
    });
    store2.load();
}

store1.on('load',function(store, records) {
    store2.someFunction(records);
});


text:
Q: TTStyledTextLabel I'm trying to get this control to work with a hypertext link with not much success.  I have looked at TTCalaog and tried to replecate but does not work.
I have this working as far as displaying the hypertext link but it does not fire.
TTStyledTextLabel* label = [[[TTStyledTextLabel alloc] initWithFrame:CGRectMake(5, 0, 315, 175)] autorelease];
NSString* labelText = @"This should work";
label.text = [TTStyledText textFromXHTML:labelText lineBreaks:NO URLs:YES];
[self.view addSubview:label];
I thing I am missing the point here perhaps with the placement of the google url?  I have seen a post on this forum that makes use of custom-uri://some/url that is then set up in TTURLMap and TTNavigator, but I need to open a url from the hypertext in a webview so I need the url to run a method in my class that creates my webview controller etc.
I have tried to cusomise TTURLMap to work without a TTNavigator but completely pickled?
Any help gratefullt appreciated ;-)
Thanks

A: I've just found myself a solution to catch the clicked URL on a TTStyledTextLabel. I hope this could help in your case too.
This's what I have done.
1. Create TTNavigator
    TTNavigator *navigator = [TTNavigator navigator];
    navigator.persistenceMode = TTNavigatorPersistenceModeNone;
    navigator.delegate = self;

2. Create TTNavigatorDelegate
As you assigned self as delegate of the navigator object. Therefore, please remember to add  protocol in the header file .h before you continue.
In the implementation, create this method
    - (BOOL) navigator:(TTBaseNavigator *)navigator shouldOpenURL:(NSURL *)URL {
        // Now you can catch the clicked URL, and can do whatever with it
        // For Example: In my case, I take the query of the URL
        // If no query is available, let the app open the URL in Safari
        // If there's query, get its value and process within the app

        NSString *query = URL.query;

        if (query == nil) {
            return YES;
        } else {
            // process the query
        }
    }

I hope this helps! Please vote for me if this helps to solve your issue!
Best Regards,
Thang


text:
Q: React Native App Working in Development, 'Error: 'undefined' is not a function' in Production I have completed an app that builds on both Android and iOS. It works as expected when I build the app from the CLI or when I build it via XCode / Android Studio. However, on TestFlight, it gets errors that simply do NOT exist when I build it locally. These errors only appear on TestFlight, and thus I have little to no idea on how to go finding them down or even resolving them. Does anyone have better expertise in this area?

A: I'm not sure how common an issue this is-- I've never heard of it before to be honest, but the components that were not working were components that utilized ({props}) in a component. For example, any component wthat utilized the following declarations did NOT work
function Example({props}){
   // stuff
}

// OR //

const Example = ({props}) => {
    // stuff
}

all of the values inside of props were unreadable. I fixed this by simply moving EVERYTHING into a recoil state instead and that mitigated any errors. For example...
navigation.navigate("path",{prop1: value})

// AND //

return (<Example prop={value} prop={value})

would not work unless the prop was a single value-- a string, an int, a bool, these would work. Objects and Arrays did NOT properly carry over.
Hope this helps someone in the future.


text:
Q: pfgplots plot in degrees Everywhere on the web, and in this forum, tells me pfgplot plots trig functions in degrees, which is what I'm after.
Here is the code for my graph:
\begin{figure}[H]
    \centering
    \begin{tikzpicture}
    \begin{axis}[
    domain=1:20000,
    xmode=log,
    xlabel=Frequency (Hz),
    ylabel=Phase shift (\degree),
    ]
    \addplot[mark=none, samples=100, red] function {atan(-2*pi*0.001*x)};
    \end{axis}
    \end{tikzpicture}
    \caption{Transfer function with multiple values of $RC$}
\end{figure}

And the result, which as you can see, is in radians (otherwise it would stretch to minus 90).

How can I plot in degrees?

A: When you use \addplot [...] function {...} it uses gnuplot on the terminal, which uses radians for trigonometric functions, as noted in Section 4.3.5 of the pgfplots manual.
To use the pgf computation engine, remove the word function (or replace it with expression):
\documentclass{standalone}
\usepackage{pgfplots,siunitx}
\pgfplotsset{compat=1.11}

\begin{document}
    \begin{tikzpicture}
    \begin{axis}[
    domain=1:20000,
    xmode=log,
    xlabel=Frequency (\si{\hertz}),
    ylabel=Phase shift (\si{\degree}),
    ]
    \addplot[mark=none, samples=100, red] {atan(-2*pi*0.001*x)};
    \end{axis}
    \end{tikzpicture}
\end{document}


text:
Q: different aspects (linestrings) in one kml file I want present different aspects on the same path (so different linestrings) in one kml file.
Does the KML format support hierarchical structure of objects:
Document
  Aspect1
    Aspect1_1
      LineString1
      LineString2
    Aspekt1_2
      LineString1
  Aspect2
  ...
Document

So I need to have many aspects in one file.
UPD: What about many LineStrings with different LineStyles within one Placemark?

A: I am not sure what you mean by an aspect. However, this might be useful. Give the containing Folder or Document a ListStyle with listItemType of radioFolder:
https://developers.google.com/kml/documentation/kmlreference#liststyle
Which then displays your options in the left pane as radio buttons, so only one can be selected at a time. Then create different Placemarks with a LineString displayed in some way different from the others.


text:
Q: automatic and dynamic countdown timer android I want to make a countdown timer that is automatically triggered by time.
Let's say for example the countdown should automatically start at 12:00:00 AM and ends at 11:59:59 PM. The problem is if ever the fragment will be destoyed or the application is terminated, how will my countdown timer automatically counts the time left before the timer ends when the view is created again?

A: Don't worry about the start time.  Just define the end time.
Whenever your fragment that shows the countdown is displayed, compute the timer display based on the difference between the current time and the end time.
When the fragment becomes invisible, you don't have to do anything because the end time stays the same.  Just worry about updating the timer display when the fragment is visible.


text:
Q: Htaccess - Change domain based on language param I need help with a htaccess rewrite. Been asking Google for a while now...
I want this url:
http://www.examplenorwegian.no/sv/(wildcard)

To rewrite to:
http://www.exampleswedish.se/sv/(wildcard)

It is the /sv/ part that is the key in this. So if the case is other way around, it will rewrite to norwegian url.
Could not get this to work:
RewriteCond %{HTTP_HOST} ^www.examplenorwegian\.no/sv/$ [NC]
RewriteRule ^(.*)$ http://www.exampleswedish.se/sv/$1 [R=301,L]

A: The %{HTTP_HOST} variable only contains the hostname, no path information. The Path information must be matched in the rule's regex pattern or against the %{REQUEST_URI} variable:
RewriteCond %{HTTP_HOST} ^www.examplenorwegian\.no$ [NC]
RewriteRule ^sv/(.*)$ http://www.exampleswedish.se/sv/$1 [R=301,L]


text:
Q: why interface comes like eth1@if11 in network namespace? I attached an end of the Veth with separate network namespace. But I noticed that "@if11" is automatically added with my created Veth. Can anyone please explain it what is this?

A: if11 means that the other end of the veth pair has the internal InterFace number 11, but as it isn't present in this network namespace, it has no name. So this name is used as a replacement.
If you create a veth pair in a single namespace (or the main namespace), you'll see name1@name2 instead.


text:
Q: What symmetric cypher to use for encrypting messages? I haven't a clue about encryption at all. But I need it. How?
Say you have a system of nodes communicating with each other on a network via asynchronous messages. The nodes do not maintain session information about other nodes (this is a design restriction).
Say you want to make sure only your nodes can read the messages being sent. I believe encryption is the sollution to that.
Since the nodes are not maintaining a session and communication must work in a stateless, connectionless fashion, I am guessing that asymmetric encryption is ruled out.
So here is what I would like to do:

*

*messages are sent as UDP datagrams

*each message contains a timestamp to make messages differ (counter replay attacks)

*each message is encrypted with a shared secret symmetric key and sent over the network

*other end can decrypt with shared secret symmetric key

Keys can obviously be compromised by compromising any single node. At the same time, in this scenario, access to any single compromised node reveals all interesting information anyway, so the key is not the weakest link.
What cypher should I use for this encryption? What key length?
I would prefer to use something supported by ezPyCrypto.
Assuming, as most point out, I go with AES. What modes should I be using?
I couldn't figure out how to do it with ezPyCrypto, PyCrypto seems to be hung on a moderator swap and googles keyczar does not explain how to set this up - I fear if I don't just get it, then I run a risk of introducing insecurity. So barebones would be better. This guy claims to have a nice module for AES in python, but he also asserts that this is his first python project - Allthough he is probably loads smarter than I, maybe he got tripped up?
EDIT: I moved the search for the python implementation to another question to stop clobber...

A: Your first thought should be channel security - either SSL/TLS, or IPSec.
Admittedly, these both have a certain amount of setup overhead, IPSec more than SSL/TLS, especially when it comes to PKI etc. - but it more than pays for itself in simplicity of development, reliability, security, and more. Just make sure you're using strong cipher suites, as appropriate to the protocol.
If neither SSL/TLS or IPSec fits your scenario/environment, your next choice should be AES (aka Rijndael).
Use keys at least 256 bits long, if you want you can go longer.
Keys should be randomly generated, by a cryptographically secure random number generator (and not a simple rnd() call).
Set the cipher mode to CBC.
Use PKCS7 padding.
Generate a unique, crypto-random Initialization Vector (IV).
Don't forget to properly protect and manage your keys, and maybe consider periodic key rotations.
Depending on your data, you may want to also implement a keyed hash, to provide for message integrity - use SHA-256 for hashing.
There are also rare situations where you may want to go with a stream cipher, but thats usually more complicated and I would recommend you avoid it your first time out.
Now, I'm not familiar ezpycrypto (or really python in general), and cant really state that it supports all this; but everything here is pretty standard and recommended best practice, if your crypto library doesnt support it, I would suggest finding one that does ;-).

A:
I haven't a clue about encryption at all. But I need it. How?

DANGER! If you don't know much about cryptography, don't try to implement it yourself.  Cryptography is hard to get right.  There are many, many different ways to break the security of a cryptographic system beyond actually cracking the key (which is usually very hard).
If you just slap a cipher on your streaming data, without careful key management and other understanding of the subtleties of cryptographic systems, you will likely open yourself up to all kinds of vulnerabilities. For example, the scheme you describe will be vulnerable to man-in-the-middle attacks without some specific plan for key distribution among the nodes, and may be vulnerable to chosen-plaintext and/or known-plaintext attacks depending on how your distributed system communicates with the outside world, and the exact choice of cipher and mode of operation.
So... you will have to read up on crypto in general before you can use it securely.

A: Assuming the use of symmetric crypto, then AES should be your default choice, unless you have a good very reason to select otherwise.
There was a long, involved competition to select AES, and the winner was carefully chosen. Even Bruce Schneier, crypto god, has said that the AES winner is a better choice than the algorithm (TwoFish) that he submitted to the competition.

A: AES 256 is generally the preferred choice, but depending on your location (or your customers' location) you may have legal constraints, and will be forced to use something weaker.
Also note that you should use a random IV for each communication and pass it along with the message (this will also save the need for a timestamp).
If possible, try not to depend on the algorithm, and pass the algorithm along with the message. The node will then look at the header, and decide on the algorithm that will be used for decryption. That way you can easily switch algorithms when a certain deployment calls for it.

A: I'd probably go for AES.

A: Asymmetric encryption would work in this scenario as well.  Simply have each node publish it's public key.  Any node that wants to communicate with that node need only encrypt the message with that node's public key.  One advantage of using asymmetric keys is that it becomes easier to change and distribute keys -- since the public keys can be distributed openly, each node need only update it's public-private key pair and republish. You don't need some protocol for the entire network (or each node pair) to agree on a new symmetric key.

A: Why not create a VPN among the nodes that must communicate securely?
Then, you don't have to bother coding up your own security solution, and you're not restricted to a static, shared key (which, if compromised, will allow all captured traffic to be decrypted after the fact).


text:
Q: What does min-height: 100% do when nothing has an explicit height? My university website has a strange issue on Opera 12.xx only (as far as I'm aware) where all the content is ludicrously spaced out, with giant sections of empty space separating all the sections.
When I inspected the CSS, I noticed several containers had the property min-height: 100% going up to and including html and body, but no intervening parent had an explicitly defined height. My guess is that Opera recursed all the way up the DOM tree and, since it got to the top, made all of these at least 100% of the viewport height.
Based on my understanding of CSS, this seems like what should be happening. My question(s), then:

*

*Is it what's supposed to be happening, or am I misunderstanding something?

*If so, why does this issue only affect Opera 12? (Opera 15 is immune because it uses Webkit, I know. I mean, why does Webkit display it normally?)

*What is the point of all these min-height declarations? There doesn't seem (again, in my understanding) to be an answer to 100% of what, and isn't this forcing the elements marked to base their height on their parent's content, rather than their own? What's the sense in that?

I was told by one of the university webmasters that it had to be this way because this site employs responsive design, and while I admit I don't fully understand what all that buzzword has come to mean, I don't understand what that has to do with it.

A: When in doubt, consult the spec:

If the height of the containing block is not specified explicitly (i.e., it depends on content height), and this element is not absolutely positioned, the percentage value is treated as '0' (for 'min-height') or 'none' (for 'max-height').

Opera's behavior isn't consistent with what the spec outlines, so it's a browser bug.


text:
Q: How to remove a single object from Array Properties in React Js? I have a state like:
const initialFieldValue={
...............

photos:[]
.........

}

const [state, setState] = useState(initialFieldValue);

Then I was pushing some object one by one through onClick function like that:
const handlePush=()=>{
     state.photos.push({
        fieldId: Math.random(),
        file: file , /// from upload file
      });
    }
}

Now I want to remove those object one by one onClick function like
const handleRemove=(fieldId )=>{
    const tableDoc = [...state.photos];
    tableDoc.splice(
      tableDoc.findIndex(value => value.fieldId === fieldId),
      1,
    );
    state.photos = tableDoc;
}

A: Solution:
Change this line
state.photos = tableDoc;

to
setState({...state, photos: tableDoc});

Refactor code:
const newPhotos = state.photos.filter(value => value.fieldId !== fieldId);
setState(prevState => ({...prevState, photos: ...newPhotos }));

Note:

*

*Don't mutate data in React Js: The same as handleRemove method, you shouldn't mutate data directly, please do something like this in handlePush
const newPhoto = {fieldId: Math.random(),file: file};
setState(prevState => ({...prevState, photos: [...prevState.photos, newPhoto]}));

*Keep in mind that, from reactjs.org docs say that:

Unlike the setState() method found in class components, useState does
not automatically merge update objects. You can replicate this
behavior by combining the function updater form with object spread
syntax:

setState(prevState => {
  // Object.assign would also work
  return {...prevState, ...updatedValues};
});

A: In addition to the above solution, You can try all in a single line (no need to spread, findIndex, and splice)
setState({...state, photos: state.photos.filter(value => value.fieldId !== fieldId)});

A: Thanks Everyone for trying to solution for me . Everyone is right. but I can modification like that:
//Old
const handlePush=()=>{
     state.photos.push({
        fieldId: Math.random(),
        file: file , /// from upload file
      });
    }
}

//New

handleChange =()=>{
setState({
      ...state,
      photos: [...state.photos, {
        fieldId: Math.random(),
        file: file , /// from upload file
      }],
    });
}

then Remove function:
//old
const handleRemove=(fieldId )=>{
    const tableDoc = [...state.photos];
    tableDoc.splice(
      tableDoc.findIndex(value => value.fieldId === fieldId),
      1,
    );
    state.photos = tableDoc;
}
//New
  const handlePhotoRemove = fieldId => {
    const tabPhotos = [...state.photos];
    tabPhotos.splice(
      tabPhotos.findIndex(value => value.fieldId === fieldId ),
      1,
    );
    setState({
      ...state,
      photos: tabPhotos,
    });
  };

It is successfully done!!
thanks. Plz tell me if have any easy solutions


text:
Q: trouble with URL encoding in mod_rewrite So I am making a kind of proxy type thing and I need to encode all the get query using my .htaccess file. Basically I want to silently redirect:
http://example.com/p/external.php?foo=bar

to:
http://example.com/proxy.php?path=external.php%3Ffoo=bar

except that that doesn't seem to be the case with the following line of code:
RewriteRule ^p/(.*)$ /proxy.php?path=$1

I've tried using the B flag and the NE flag but neither seem to make a diference, anything before the ? is been passed on but nothing else.

A: Have your generic rule like this with B flag:
RewriteCond %{THE_REQUEST} \s/+p/[^?]+\?([^\s]+) [NC]
RewriteRule ^p/(.+?)\.php$ /proxy.php?path=$1.php\%3F%1 [L,NC,B]

This will rewrite /p/external.php?foo=bar&abc=123 to /proxy.php with
_SERVER["QUERY_STRING"]=path=external.php%3Ffoo%3dbar%26abc%3d123

A: You need to include the %{QUERY_STRING} variable:
RewriteCond %{QUERY_STRING} ^(.*)&(.*)$
RewriteRule ^p/ %{REQUEST_URI}?%1\%26%2[L,NE]

RewriteRule ^p/(.*)$ /proxy.php?path=$1\%3F%{QUERY_STRING}

Because it's not part of the rule's pattern match, and won't be captured by the (.*).


text:
Q: How can I print more than one fields resulting from a query? I am trying to learn how to use the database/sql package with go-sql-driver. I wrote the following simple program and it works, but I could not figure out how to print more than one fields.
The database wiki1 has three fields, id, title and body. I query for "title1" which is one of the values but I want to print the values for "title" and "body". How do I this?
package main

import (
    "database/sql"
    "fmt"
    _ "github.com/go-sql-driver/mysql"
)

func main() {

    db, err := sql.Open("mysql", "root:Password1@/wiki1")
    if err != nil {
        fmt.Println(err)
        return
    }
    defer db.Close()

    st, err := db.Prepare("SELECT title FROM page WHERE title=?")
    if err != nil {
        fmt.Println(err)
    }
    rows, err := st.Query("title1")
    if err != nil {
        fmt.Println(err)
    }

    for rows.Next() {
        var title, body string
        if err := rows.Scan(&title); err != nil {
            fmt.Println(err)
        }

        fmt.Printf("%s\n", title)
    }
    if err := rows.Err(); err != nil {
        fmt.Println(err)
    }
}

A: To read the body and the title instead of just the title, first change the statement.
Change
st, err := db.Prepare("SELECT title FROM page WHERE title=?")

to
st, err := db.Prepare("SELECT body, title FROM page WHERE title=?")

Then change the reading. Change
    var title, body string
    if err := rows.Scan(&title); err != nil {
        fmt.Println(err)
    }

to
    var title, body string
    if err := rows.Scan(&body, &title); err != nil {
        fmt.Println(err)
    }

This reads both columns.
To print the fields, you can do
fmt.Printf("title: %s\nbody: %s\n", title, body)

You'll find more details regarding querying using database/sql, read this related question.


text:
Q: svnant - parent dir in server is not a working copy I want to checkout project, get the revision number, build jar with that number in menifest, on the server with a web interface. There are some other minor steps in the whole process, but that's the main goal. everything in the build script is working fine locally, but I always get stuck when it is done on the server. when I try to use svnant  task on the project I checked out, it's telling me the parent dir is not a working copy, so I tried  a copy first, then  the whole project again into that  copy, it's still telling me that the parent dir (the first  edition) is not a working copy.
what sould I do?
p.s. I have tried all possible combination of , , , . none of them worked. can anyone else get the  in svnant work? I always get error as following:
java.lang.NullPointerException
        at org.tigris.subversion.svnant.commands.WcVersion.getWorkingCopySumary(Unknown Source)
        at org.tigris.subversion.svnant.commands.WcVersion.execute(Unknown Source)
        at org.tigris.subversion.svnant.commands.SvnCommand.executeCommand(Unknown Source)
        at org.tigris.subversion.svnant.SvnTask.execute(Unknown Source)
        at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:288)
        at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
        at java.lang.reflect.Method.invoke(Method.java:597)
        at org.apache.tools.ant.dispatch.DispatchUtils.execute(DispatchUtils.java:106)
..........
can anyone help with either question?
Thank you

A: Please, check that you have the same version of SVN installed on server and on client (svn --version).
Also, I would like to recall you that svnant is binding to SVN 1.5 and if on server side you have 1.6 version, you can get similar behavior.
How to resolve the issue: switch your script from javahl to svnkit. I.e. add svnkit jars to your classpath and add to all svnant related commands appropriate hint:
javahl="false" svnkit="true"


text:
Q: How can $V$ be a vector space over the field of real numbers when it is explicitly defined as being over the field of complex numbers? Let $V = \{(a_1, a_2, ..., a_n): a_i \in \mathbb{C}$ for $ i = 1, 2, .., n\}$; so $V$ is a vector space over $\mathbb{R}$. Is V a vector space over the field of real numbers with the operations of coordinatewise addition and multiplication?
The solution says,

Yes. All the conditions are preserved when the field is the real
  numbers.

I don't understand how $V$ can be a vector space over $\mathbb{R}$? $V$ itself is specified as being over the field of complex numbers ($V = \{(a_1, a_2, ..., a_n): a_i \in \mathbb{C}$), so how can the question then claim that $V$ is a vector space over the real numbers?
I would greatly appreciate it if someone could please take the time to clarify my misunderstanding.

A: Check the definition of a vector space over a field, for example on Wikipedia: https://en.wikipedia.org/wiki/Vector_space#Definition
Being over $\mathbb{R}$ means that vectors can be multiplied by real numbers and you get again a vector in $V$. This is certainly true in your example since complex numbers multiplied by real numbers are again complex numbers.


text:
Q: How to change path for data storage for elasticsearch I have gone into my elasticsearch.yml and changed "path.data:" to the path where I want to store the data. Now when I start the elasticsearch service, the localhost:9200 would not work anymore. If I kept "path.data:" line commented out, localhost:9200 would work fine. I am on a centos 6 machine and I installed elasticsearch through yum. Thanks in advance.

A: I figured out the solution. I had created the folder using the root folder, so elasticsearch did not have permissions to make changes to the folder where the new data would be stored in. IF you have any issues like this, make sure you have changed your permissions for the newly created folder.


text:
Q: How can I add elements to parent classes? I have following inheritance chain:
class Derivation : public std::vector<Symbol> {
};

class Alternatives : public std::vector<Derivation> { };

class Production : public std::pair<NonTerminal, Alternatives> {
    int order = 0;
};

class Productions : public std::vector<Production> { };

class Grammar {

    Productions productions;

};

How can I access parent classes to add elements to them?
Or is there maybe even a way to do something like this directly?
productions.production[3].alternatives.push_back(std::vector<Symbol>())

Maybe a little contrived:
productions::parents.last.push_back(std::vector<Symbol()>


text:
Q: Do these sentences have the same meaning? 1) "That is what I said." 2) "I said it, too." The following sentences seem to have the same meaning?
1-"That is what I said."
2-"I said it, too."
For instance;
The boss says to an employee: You should not smoke here. It is forbidden.
The assistant of the boss who is together with the boss and is not happy about the employee says to the boss:
1- That is what I said.
2- I said it, too.**
Do both sentences completely have the same meaning? If yes, which one do you think is more idiomatic?

A: It would help if you'd add more context to the question, because these look like replies.  What was the statement they were replying to?
Let's invent some examples.

Example 1:
Statement: "Why did we go to this movie? Mission Impossible would have been better."
Reply: "That is what I said!"

Example 2:
Statement: To pass through this gate, you must say the password. Why haven't you spoken it?
Reply, person 1: I said it.
Reply, person 2: I said it, too.  We both said it.

Here, you cannot switch the two replies. They are each quite different.
So the final answer is: they don't have the same meaning.

Note: you might be imagining a different "Example 3" where both of your statements fit equally well.  And, that's possible also.

A: The two example sentences from the question:

(1) That is what I said.
(2) I said it, too.

have similar meanings. They might be called related or overlapping meanings. There are situations or contexts in which either would work, and others in which only one would work. Both are likely to be replies, or parts of an exchange of dialog, and so the earlier parts of any such dialog are key to whether the sentences are appropriate and just what meaning they carry.
The answer by user Sam gave two example scenarios. Then the OP, user yunus gave a third. Let's look at number 3 again, slightly modified:

Boss:  You should not smoke here, Jones. It is not allowed.
Assistant manager: That's what I said.

Here sentence (1) means that the assistant manager had already given the same instruction to Jones, and implies that Jones did not follow it.  A variant on (2) could be used instead:

Boss:  You should not smoke here, Jones. It is not allowed.
Assistant manager: I said that too.

Note that "I said it too." does not work here. But (1) and the modified (2) carry much the same meaning here. Also, other statements are a bit more likely here, such as:

*

*I said that yesterday.

*I told you that before, Jones.

*I already mentioned that to Jones.

Let's explore some other scenarios.
Scenario 4:

Boss: Did you tell Jones that shje could use the computer lab?
Assistant manager: Yes, that's what I said.

Here sentence (1) is appropriate, but (2) simply does not fit.
Scenario 5:

Boss: Did you give Jones written instructions to log out of the computer lab every time?
Assistant manager: Yes. I said it, too.

Here (2) is appropriate, but (1) does not fit.
Scenario 6:

Jones: Dis you say to shut off the red valve, and leave the green one open?
Assistant manager: That's what I said.

Here again (1) works and (2) simply does not work at all.
Note that the contracted version of (1), which might be called (1A) "That's what I said" always caries much the same meaning as the original (1) which uses "that is". (1A) is slightly less formal, and far more common.


text:
Q: JPEG baseline standard VS progressive: compression cost We are JPEG-compressing a large quantity of images on the fly.
This is a server-side process to interactively prepare images to be sent to the clients' browsers.
Using progressive compression would improve the user experience.
I know that this compression requires more computation for decompression, but that's not an issue.
I'd like to know if progressive compression is more costly too and how much (without running my own serie of tests and benchmarks).

A: If you're compressing on the fly, then baseline will allow you to stream compressed data to the client even before you finish downloading and converting rest of the image. This will let you reduce latency. OTOH to compress progressive JPEG you need to download entire source image first.
For small images like thumbnails or avatars it won't matter either way.
For large images… it depends on compressor, number of progressive scans, and image sizes. Cost could be negligible compared to optimized baseline, or could be doubled compared to one-pass streaming encoder.

A: After running benchmarks I noticed that generating a JPEG requires an amount of cpu time that is roughly proportional to the number of progressive scans
What I stated in my question...

Using progressive compression would improve the user experience

is actually false since most browsers show the image only when completely loaded by the client.


text:
Q: Cannot execute SSIS package from vb6 I am trying to execute a simple SSIS package from vb6 application.
I can execute the same package from c#.
This is my code in vb6:
  pkgLocation = "c:\Package.dtsx"
  Set dtsApp = New Application

  Set package = dtsApp.LoadPackage(pkgLocation, True, Nothing)
  Set pkgContainer = package

  pkgResults = package.Execute

  If (pkgResults = 0) Then
   MsgBox "Success"
  Else
    MsgBox "Fail"
  End If

In my log file, I see this error:
The Execute method on the task returned error code 0x80131621 (Mixed mode assembly is built against version 'v2.0.50727' of the runtime and cannot be loaded in the 4.0 runtime without additional configuration information.). The Execute method must succeed, and indicate the result using an "out" parameter.
I my c# program I have to add an App.config file to resolve the same error:
<?xml version="1.0"?>
  <configuration>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
  </startup>
</configuration>

But How can I do the same from vb6 application?
Edit 1:
In my vb6 project I am using this references:
C:\Program Files (x86)\Microsoft SQL Server\120\DTS\Binn\DTS.DLL  - Microsoft DTS Runtime 1.0
C:\Program Files (x86)\Microsoft SQL Server\120\DTS\Binn\MsDtsSrvrUtil.dll - Dts Server 9.0 Type Library
The SSIS package was made with : Sql Server Data Tools for Visual Studio 2013
Thanks for your help.

A: I found the solution in this post Using app.config with Interop Controls
In short : If my VB6 exe es called VB6.exe , I  need to put in the same directory as the file VB6.exe the App.config file but renamed VB6.exe.config

A: Your version of calling the object is older/newer than the version you are trying to open it seems.
You need to reference the correct version object in your app under project/references.


text:
Q: C++ constexpr boolean vs macro I have been reading about using constexpr instead of using macros for better safety, as macros can lead to undefined behavior. However, if I have the code in the following example, is it okay to do this, and just use preprocessor if statements (#if), or should I change the macros to constexpr bool.
Here is what I wanted to do:
#if NDEBUG
#define ENABLE_VALIDATION_LAYERS 0
#else
#define ENABLE_VALIDATION_LAYERS 1
#endif

vs
#if NDEBUG
constexpr bool enable_validation_layers = false;
#else
constexpr bool enable_validation_layers = true;
#endif

Code usage right now looks like this:
//if validation layers are not enabled, the validation support does not need to be checked
#if ENABLE_VALIDATION_LAYERS
        if (!CheckValidationLayerSupport()) //function that returns a bool to check if validation layers are supported
        {
            throw std::runtime_error("validation layers requested, but not available!");
        }
#endif