text:
Q: Android maven-publish generated pom file has incorrect dependency information for local project dependencies I've got a library (Lib1) that depends on several other libraries (Lib2 and Lib3) that I build from source alongside Lib1.  All three are published as artifacts, with artifact ids my-artifact-lib1, my-artifact-lib2, and my-artifact-lib3 respectively.  When I publish the artifacts via the maven-publish plugin, I wind up with a dependencies element in the pom file like the following:
<dependencies>
  <dependency>
    <groupId>org.my.group</groupId>
    <artifactId>Lib2</artifactId>
    <version>unspecified</version>
    <scope>runtime</scope>
  </dependency>
  <dependency>
    <groupId>org.my.group</groupId>
    <artifactId>Lib3</artifactId>
    <version>unspecified</version>
    <scope>runtime</scope>
  </dependency>
</dependencies>

The unspecified versions can be fixed by placing a version property in an allprojects{} block in the project level build.gradle, but the bigger problem is that the artifact ids don't match the publish data:
Lib1Publication(MavenPublication) {
  from components.release
  groupId "org.my.group"
  artifactId "my-artifact-lib1"
  version "${version_major}.${version_minor}."+getPatchVersion()
}
Lib2Publication(MavenPublication) {
  from components.release
  groupId "org.my.group"
  artifactId "my-artifact-lib2"
  version "${version_major}.${version_minor}."+getPatchVersion()
}
Lib3Publication(MavenPublication) {
  from components.release
  groupId "org.my.group"
  artifactId "my-artifact-lib3"
  version "${version_major}.${version_minor}."+getPatchVersion()
}

This creates a problem where any client trying to use my-artifact-lib1 as a dependency and requiring my-artifact-lib2 and my-artifact-lib3 as transitive dependencies winds up searching for artifact ids Lib2 and Lib3 instead and finding nothing.
Module level build.gradle of Lib1 with the project dependencies on the other two modules is as follows:
dependencies {
  implementation project(path: ':Lib2')
  implementation project(path: ':Lib3')
}

How can I get the generated transitive dependencies for my-artifact-lib1 to use the correct artifact ids for project dependencies, rather than their module names?

A: I have a similar structure and at least for me the following changes work:
I have ensured, that the subproject-name matches exactly the desired final library name. So in your example I have changed the project Lib1 into my-artifact-lib1.
Regarding version and group the solution seems to be, that in the root build.gradle the definition allprojects has to be included like
allprojects {
    group "org.my.group"
    version "${version_major}.${version_minor}."+getPatchVersion()
}

at least in my environment this works


text:
Q: filter by data and calculate average vuejs I have a table in firebase named products and one of its params is product, productivity and etc.,
Now I want to filter this table by product (they can contain many different products) and retrieve an average of productivity.
This is how far I can get without any errors I know that somewhere I have to filter data and pass argument but couldn't get an answer. I am using Pinia and VUEJS 3 and trying to get result with getters
getters: {
getAve:(state) => {
      let sum = 0
      state.orders.forEach(  (order)  =>  sum += (order.productivity)  )
      return sum / state.orders.length
    },
}

later on I am using v-for where in template I would pass {{ getAve(order.product)}}
p.s. I am new to vuejs and codding.

A: This is the answer I was looking for, maybe someone else will need. I use this method in my componenet:
const averageProd = (id) => {
  let average = [];
for (var i = 0; i < storeOrders.orders.length; i++) {
    if (storeOrders.orders[i].product === id) {
        average.push(storeOrders.orders[i]);
    }}
    return average.reduce((sum, item) => sum + item.productivity, 0) / average.length

}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Error installing R packages (R 3.4.4), asks for usethis when already installed I'm having the following problem:
When I try to install any R package, at first it downloads the package just fine into a temporal location, and then the following error message appears:
Error: package 'usethis' required by 'devtools' could not be found
Execution halted
Warning in install.packages :
installation of package 'lattice' had non-zero exit status
The wierd part of this is that package usethis is installed and loaded.
Any advise on what can be happening here? I'm a lost there..


text:
Q: Super keyword in Ruby What is the super for in this code?
def initialize options = {}, &block
  @filter = options.delete(:filter) || 1
  super
end

As far as I know it's like calling the function recursively, right?

A: no... super calls the method of the parent class, if it exists. Also, as @EnabrenTane pointed out, it passes all the arguments to the parent class method as well.

A: super calls a parent method of the same name, with the same arguments. It's very useful to use for inherited classes.
Here's an example:
class Foo
  def baz(str)
    p 'parent with ' + str
  end
end

class Bar < Foo
  def baz(str)
    super
    p 'child with ' + str
  end
end

Bar.new.baz('test') # => 'parent with test' \ 'child with test'

There's no limit to how many times you can call super, so it's possible to use it with multiple inherited classes, like this:
class Foo
  def gazonk(str)
    p 'parent with ' + str
  end
end

class Bar < Foo
  def gazonk(str)
    super
    p 'child with ' + str
  end
end

class Baz < Bar
  def gazonk(str)
    super
    p 'grandchild with ' + str
  end
end

Baz.new.gazonk('test') # => 'parent with test' \ 'child with test' \ 'grandchild with test'

If there's no parent method of the same name, however, Ruby raises an exception:
class Foo; end

class Bar < Foo
  def baz(str)
    super
    p 'child with ' + str
  end
end

Bar.new.baz('test') # => NoMethodError: super: no superclass method 'baz'

A: The super keyword can be used to call a method of the same name in the superclass of the class making the call.
It passes all the arguments to parent class method.
super is not same as super()
class Foo
  def show
   puts "Foo#show"
  end
end

class Bar < Foo
  def show(text)
   super

   puts text
  end
end

Bar.new.show("Hello Ruby")

ArgumentError: wrong number of arguments (1 for 0)
super(without parentheses) within subclass will call parent method with exactly same arguments that were passed to original method (so super inside Bar#show becomes super("Hello Ruby") and causing error because parent method does not takes any argument)

A: I know this is late but:
super method calls the parent class method.
for example:
class A
  def a
    # do stuff for A
  end
end

class B < A
  def a
    # do some stuff specific to B
    super
    # or use super() if you don't want super to pass on any args that method a might have had
    # super/super() can also be called first
    # it should be noted that some design patterns call for avoiding this construct
    # as it creates a tight coupling between the classes.  If you control both
    # classes, it's not as big a deal, but if the superclass is outside your control
    # it could change, w/o you knowing.  This is pretty much composition vs inheritance
  end
end

If it is not enough then you can study further from here

A: Bonus:
module Bar
    def self.included base
        base.extend ClassMethods
    end

    module ClassMethods
        def bar
            "bar in Bar"
        end
    end
end

class Foo
    include Bar
    class << self
        def bar
            super
        end
    end
end

puts Foo.bar # => "bar in Bar"

A: Super in a method of a class , say test_method, is used to call another method  with same name i.e test_method of a parent class.
The code written above and below the super keyword will be executed normally and the whole bunch of code action of the method of super class will be included at the place of super keyword.


text:
Q: Derivation of non-arbitrage-free Black and Scholes equation I am well aware of how the ordinary Black and Scholes equation is derived, under the assumption of an arbitrage free portfolio, $V=G-hS$. Here $S$ is the price of the underlying and $G$ is the option price. Suppose now that the portfolio is stochastic, and follows the process
$$(1): dV=rVdt+f(V,t)VdW,$$
where $r$ is a constant parameter. The change of the portfolio also satisfies $dV=dG-h \cdot dS$. In the standard Black and Scholes, we have $h = \partial G/\partial S$. Assuming that the underlying follows a GBM, we have
$$dS = \mu S dt + \sigma SdW,$$
where $\mu$ and $\sigma$ are constant parameters. Itô's lemma then provides
$$dG = \left(\frac{\partial G}{\partial t}+\mu S\frac{\partial G}{\partial S}+\frac{1}{2}\sigma^2S^2\frac{\partial G^2}{\partial S^2} \right)dt + \sigma S\frac{\partial G}{\partial S}dW,$$
so that
$$(2): dV=dG-hdS = \left(\frac{\partial G}{\partial t}+\mu S\left(\frac{\partial G}{\partial S}-h\right)+\frac{1}{2}\sigma^2S^2\frac{\partial G^2}{\partial S^2} \right)dt + \sigma S\left(\frac{\partial G}{\partial S}-h\right)dW $$
Matching 1) and 2), we see that we must have the following implicit relation for $h$ $$(3): f(G-hS,t)(G-hS)=\sigma S \left(\frac{\partial G}{\partial S}-h\right). $$
In the standard Black and Scholes we would have $f=0$, thus recovering $h = \frac{\partial G}{\partial S}$. If $f$ only depends on its second argument ($t$), then 3) can also easily be solved for $h$, yielding $$(5):h =\frac{Gf(t)-\sigma S \frac{\partial G}{\partial S}}{S(f(t)-\sigma)}, \ f \ \mathrm{independent \ of} \ V$$
Combining 1) and 2) would then give the Black and Scholes like equation $$(6):\frac{\partial G}{\partial t}+\mu S\frac{\partial G}{\partial S}+\frac{1}{2}\sigma^2S^2\frac{\partial G^2}{\partial S^2}+(r-\mu)\frac{Gf(t)-\sigma S \frac{\partial G}{\partial S}}{f(t)-\sigma}-rG=0, \ f \ \mathrm{independent \ of} \ V  $$
However, what could we do if $f$ is not independent of $V$?


text:
Q: Rails not getting params from HTTP request I'm trying to POST the following data to a Rails server (running on WebRick) from Android.
<?xml version='1.0' encoding='UTF-8' standalone='yes' ?>
<data>
  <email>email.test@name.com</email>
  <password>APassw0rd</password>
  <remember_me>1</remember_me>
</data>

Now, the funny thing is that these data never show up in the params field in the controller.
Webrick does not output any parsing error. (And I guess it would post an error if it received a POST with no data attached:
Started POST "/users/sign_in.xml" for 192.168.1.94 at 2012-12-14 17:33:20 +0100
Processing by Users::SessionController#create as XML
Completed 500 Internal Server Error in 22643ms

I also found no trace of the data in the request.env variable. Actually, I see no HTTP_BODY in the dump fields. How can one see the raw body of the request? Would webrick really not complain if it received a POST with no attached data?

A: request.env would show the data as an IO object so you wouldn't be able to see your xml directly.
request.raw_post should return the raw data.
For rails to try and parse your xml into the params hash directly you need to set the content type of the request to application/xml. The 'processing as xml' stuff means that rails will try to render an xml response and doesn't necessarily have any bearing on the format of the posted data


text: Q: How to put phone on silent mode in react native? react-native-ringer mode is not working for me it gives error (you are not using expo) react-native-ringer mode is not working for me it gives error (you are not using expo)


text:
Q: when i choose photo from gallery or take a picture from camera my photo is rotating? im choosing a photo from gallery or taking a picture from camera and when it sets to an ImageView it's getting rotate , how can i fix it to become without rotate ?
 public void setNewImage() {

    new android.app.AlertDialog.Builder(getActivity())

            .setPositiveButton("camera", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    Intent takePicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    getActivity().startActivityForResult(takePicture, 0);
                }
            })

            .setNegativeButton("gallery", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    Intent pickPhoto = new Intent(Intent.ACTION_PICK,
                            MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    getActivity().startActivityForResult(pickPhoto, 1);
                }
            })

            .show();
}

and here im setting the image to imageview :
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    super.onActivityResult(requestCode, resultCode, data);
    switch (requestCode) {
        case 0:
            if (resultCode == RESULT_OK && data != null && data.getData() != null) {
                Uri filePath = data.getData();
                try {
                    //Getting the Bitmap from Gallery
                    bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);

                    //Setting the Bitmap to ImageView
                    NewpostFragment.post_image.setImageBitmap(bitmap);
                } catch (IOException e) {
                    e.printStackTrace();
                }

               /* Uri picUri = data.getData();
                filePath = getPath(picUri);
                img.setImageURI(picUri);*/

            }

            break;

        case 1:
            if (resultCode == RESULT_OK && data != null && data.getData() != null) {
                /*Uri picUri = data.getData();

                filePath = getPath(picUri);

                img.setImageURI(picUri);*/

                Uri filePath = data.getData();
                try {
                    //Getting the Bitmap from Gallery
                    bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
                    //Setting the Bitmap to ImageView
                    NewpostFragment.post_image.setImageBitmap(bitmap);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            break;
    }
}

A: First, ACTION_IMAGE_CAPTURE will not give you a Uri via getData() in onActivityResult(). While some buggy camera apps may do that, most will not. Your choices are:

*

*Provide EXTRA_OUTPUT on the ACTION_IMAGE_CAPTURE Intent, in which case the photo should be stored in the location identified by the Uri that you put into EXTRA_OUTPUT, or

*Do not provide EXTRA_OUTPUT, and use getParcelableExtra("data") to get a thumbnail from the camera app
See this sample app for using ACTION_IMAGE_CAPTURE with EXTRA_OUTPUT.
In terms of orientation, if you go down the EXTRA_OUTPUT path, you can use android.support.media.ExifInterface to find out the orientation of the photo, then do something to rotate the image to match (e.g., rotate the ImageView).
See this sample app for using ExifInterface (though I am using a different implementation than android.support.media.ExifInterface).


text:
Q: Pulling Celery Beat arguments from a database Is there a way to give celery beat a callable that will return the arguments to pass to the message?  I would like to be able to pull data from the database to construct the arguments to pass to the celery queue.
What I would like to do would be something like this:
CELERYBEAT_SCHEDULE = {
    'every-minut1': {
        'task': 'some_task',
        'schedule': timedelta(hours=1),
        'args': some_function_that_returns_a_tuple()
    },
}

Currently I have one machine adding messages to the queue and a different machine taking the messages off of the queue and processing them.  The machine that is adding the messages to the queue is hard coding it's arguments, but I would like for it to pull that info out of the database.
The only solution I can think of currently is for the machine that is adding messages to the queue to to run celery itself.  It would have a separate queue to run a command that adds messages to the original queue for the processing server.  This seems overly complicated and it seems like there should be a simpler solution.


text:
Q: You have earned the "xxx" badge back button bug Browser: Chrome
When the bar at the top of the page appears when you earn a badge, and you then navigate to another page (I clicked on the recent icon), then go back, the bar reappears each time.

A: I doubt that this is browser-specific. I suspect that the source initially delivered to the browser already contains the badge information, so when the source is reloaded from the cache it will show it again.
An AJAX call to get badge information would solve this but I suspect it would be a significant traffic hit (in terms of number of requests, not actual bandwidth).

A: That notice bar often sticks in the top of the browser until you click it away by the X or hit the link it shows up with.
If you navigate to another page, but don't click it away, it will keep on with the gentle reminder.
It's like when you check out the site for the first time, you'll see the bar. Click it away with the X and it won't show again unless you clear your cookies.


text:
Q: Access instance variable of dumped headers (iOS) I want to know the value of "_lastNotificationReceivedBundleIdentifier" which is an instance variable of a class. The header is dumped from iOS springboard app.
@interface SBRemoteNotificationServer : NSObject <APSConnectionDelegate> {
    NSMutableDictionary* _bundleIdentifiersToClients;
    NSMutableDictionary* _environmentsToConnections;
    unsigned _lastPlayedAlertSound;
    NSString* _lastNotificationReceivedBundleIdentifier;
}

but the following code does not work:
%hook SBRemoteNotificationServer
-(void)noteApplicationFinishedLaunching:(id)launching{
    NSLog(@"identifier=%@",_lastNotificationReceivedBundleIdentifier);
    %orig;
}
%end

and the compiler error is:
error: '_lastNotificationReceivedBundleIdentifier' was not declared in this scope

How do I access and log this NSString?

A: You could probably use the objective-c runtime capabilities and take a look at the method object_getInstanceVariable(the_object, "_lastNotificationReceivedBundleIdentifier", (void**)&yourPointer);

A: Another solution to try is:
[self valueForKey:@"lastNotificationReceivedBundleIdentifier"];

where self is the parent object and lastNotificationReceivedBundleIdentifier is the variable name. eg same as self.lastNotificationReceivedBundleIdentifier.


text:
Q: Finding discrepancies in distances between random variable samples There are $N$ independent and unknown points $p_i$, $q_i \in \mathbb{R}^3$, $i \in [1, N]$. I want to find if the pairwise squared Euclidean distance of each $i$ pair is the same for all of them, or if any of them is significatively different. It is to say, is $\|p_i - q_i\|^2_2$ always the same, with some small margin of error?
I cannot observe any $p_i$, $q_i$ points, just a single estimate of them (denoted $\bar{p}_i$ and $\bar{q}_i$) that I assume are drawn from normal distributions: $P_i \sim \mathcal{N}(p_i, \Sigma_{p_i})$ and $Q_i \sim \mathcal{N}(q_i, \Sigma_{q_i})$. The covariances are known.
I can model the difference of each observation with a normal distribution $D_i \sim \mathcal{N}(\bar{p}_i - \bar{q}_i, \Sigma_{p_i} + \Sigma_{q_i})$. I am not very sure how I can go from here.
The squared distance should be given by $D_i^t D_i$. I think it is the distribution
$$ (\bar{p}_i - \bar{q}_i)^t (\Sigma_{p_i} + \Sigma_{q_i})^{-1}(\bar{p}_i - \bar{q}_i) \sim \chi^2_3.$$
Is this correct?
If it is, then I have $N$ values drawn from $\chi^2_3$. Can I do a $\chi^2$-test on them to find if all of them agree for some probability?


text:
Q: Vim's "hit-enter" mode. Using ; of `:map ; :` without clearing displayed contents. Do any maps work from hit-enter mode? Reading :help hit-enter, it seems the only way to continue writing commands without redrawing clearing the screen, is to start a command with :.
But there we read:
-> Press ':' or any other Normal mode command character to start that command.

Why doesn't nnoremap ; : apply? (What are "other Normal mode command character[s]"?) I'd like to quickly start a new command without losing the displayed contents from the previous command. I'd also like to be able to use the leader key without losing the displayed contents.
For instance, try ;ls<Ret>, then ; or your <leader> key.
It's not that bad, I can use : after, just wondering if I could get more control in hit-enter-mode.

A: nnoremap gb :ls<CR>:b<Space>

Is the "canonical" way to do what you want.


text:
Q: Enable Cors in Web Api Core 1.1 I need to enable Cross Origins Resource Sharing in my Web Api .Net Core, but nothing happens, I never have the Access-Control-Allow-Origin in the request header.
Here is Startup.cs config :
 public void ConfigureServices(IServiceCollection services)
    {

        services.AddCors(options => options.AddPolicy("AllowAll", p => p.AllowAnyOrigin()
                                                                .AllowAnyMethod()
                                                                 .AllowAnyHeader()));
        services.AddMvc();

        services.Configure<IISOptions>(options =>
        {
            options.AutomaticAuthentication = true;
        });
    }

 public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();
        app.UseCors("AllowAll");
        ConfigureAuth(app);
        app.UseMvc();
    }

Here is the response Header
Header

A:
You can configure CORS in Startup class  in the ConfigureServices method

public void ConfigureServices(IServiceCollection services)
.         {
.             services.AddCors(options =>
.             {
.                 options.AddPolicy("CorsPolicy",
.                builder => builder.AllowAnyOrigin()
.                .AllowAnyMethod()
.                .AllowAnyHeader()
.                .AllowCredentials());
.             });
.         }

apply it to every request

    public void Configure(IApplicationBuilder app)
{
app.UseCors("MyPolicy");
}

you can apply on Controller or Method Also e.g add attribute

 [EnableCors("MyPolicy")]

`


text:
Q: Erlang binary to lower case performance My goal is to speed up performance of ASCII-only binary converting to lower case. I do not need any languages other than English. I've wrote and compare some variants:
Binary comprehension:
binary_comprehension(Binary) ->
    << <<if
             C >= $A andalso C =< $Z -> C - $A + $a;
             true -> C
         end >>
       || <<C>> <= Binary >>.

List comprehension:
list_comprehension(Binary) ->
    L = binary_to_list(Binary),
    Lower =
        [if
             C >= $A andalso C =< $Z -> C - $A + $a;
             true -> C
         end || C <- L],
    list_to_binary(Lower).

And regular string:lowercase.
And surprisingly list comprehension beat all others:
1> timer:tc(fun() -> lists:foreach(fun(_) -> tolower:list_comprehension(<<"QWEQWEIQEKQHWKEHKQWHEKQHWKEQWEKHQWLKL">>) end, L100000) end).
{267603,ok}

2> timer:tc(fun() -> lists:foreach(fun(_) -> tolower:binary_comprehension(<<"QWEQWEIQEKQHWKEHKQWHEKQHWKEQWEKHQWLKL">>) end, L100000) end).
{324383,ok}

3> timer:tc(fun() -> lists:foreach(fun(_) -> string:lowercase(<<"QWEQWEIQEKQHWKEHKQWHEKQHWKEQWEKHQWLKL">>) end, L100000) end).
{319819,ok}

Any ideas why double list conversion + comprehension is much faster than just binary transformation?
Maybe you know more powerful optimisation?
Update:
I also found that list-of-char version of string is also fast:
string_lowercase(Binary) ->
    L = binary_to_list(Binary),
    Lower = string:lowercase(L),
    list_to_binary(Lower).

Run:
39> timer:tc(fun() -> lists:foreach(fun(_) -> tolower:string_to_lower(<<"QWEQWEIQEKQHWKEHKQWHEKQHWKEQWEKHQWLKL">>) end, L100000) end).
{277766,ok}

A: I made some modification of the code and changed test case. Test changes is not mandatory but I personally like more this way:
-module(tolower).
-compile(export_all).

u2l(C) when C >= $A andalso C =< $Z -> C + 32;
u2l(C) -> C.

binary_comprehension(Binary) ->
  << << (u2l(C)) >> || <<C>> <= Binary >>.

list_comprehension(Binary) ->
  list_to_binary([u2l(C) || C <- binary_to_list(Binary)]).

list_recur(Binary) -> list_recur(binary_to_list(Binary), []).

list_recur([], Result) -> lists:reverse(Result);
list_recur([C | Tail], Result) when C >= $A andalso C =< $Z ->
  list_recur(Tail, [(C + 32) | Result]);
list_recur([C | Tail], Result) ->
  list_recur(Tail, [C | Result]).

string_to_lower(Binary) ->
  list_to_binary(string:lowercase(binary_to_list(Binary))).

test() ->
  L100000 = lists:seq(1, 100000),
  TL0 = <<"QWEQWEIQEKQHWKEHKQWHEKQHWKEQWEKHQWLKL">>,
  TL = binary:copy(TL0, 100000),
  {R0, _} = timer:tc(fun() -> lists:foreach(fun(_) -> tolower:binary_comprehension(TL0) end, L100000) end),
  {R1, _} = timer:tc(tolower, binary_comprehension, [TL]),
  {R2, _} = timer:tc(tolower, list_comprehension, [TL]),
  {R3, _} = timer:tc(tolower, list_recur, [TL]),
  {R4, _} = timer:tc(string, lowercase, [TL]),
  {R5, _} = timer:tc(tolower, string_to_lower, [TL]),
  io:format("~n1.binary_comprehension = ~10w~n2.binary_comprehension = ~10w~n3.  list_comprehension = ~10w~n4.          list_recur = ~10w~n5.           lowercase = ~10w~n6.     string_to_lower = ~10w~n",
  [R0,R1,R2,R3,R4,R5]).

Erlang shell shows that elapsed time not consistent due to concurrent nature of system. But the best time is for binary_comprehension as expected.
62> c(tolower).
tolower.erl:2: Warning: export_all flag enabled - all functions will be exported
{ok,tolower}
63> l(tolower).
{module,tolower}
64> tolower:test().

1.binary_comprehension =     109000
2.binary_comprehension =      94000
3.  list_comprehension =     312001
4.          list_recur =     344001
5.           lowercase =     469002
6.     string_to_lower =     218000
ok
65> tolower:test().

1.binary_comprehension =     140998
2.binary_comprehension =      93999
3.  list_comprehension =     327994
4.          list_recur =     296996
5.           lowercase =     155997
6.     string_to_lower =     280996
ok
66> tolower:test().

1.binary_comprehension =     124998
2.binary_comprehension =      93998
3.  list_comprehension =     327995
4.          list_recur =     296995
5.           lowercase =     452993
6.     string_to_lower =     202997
ok
67> tolower:test().

1.binary_comprehension =     125000
2.binary_comprehension =      94000
3.  list_comprehension =     312000
4.          list_recur =     282000
5.           lowercase =     171000
6.     string_to_lower =     266000
ok

Time on line 5 is different of time on line 6 because when you invoke string:lowercase/1 with binary argument it processed as utf8 sequence. When you invoke string:lowercase/1 with string argument utf8 processing is avoided. See code of string.erl from OTP for details.


text:
Q: Xcode 7.3 SDK iOS 9.3, XCTest UI unit tests failing I have been using XCTest UI unit tests in my app, it worked great with Xcode 7.2. with base SDK iOS 9.2, but as soon as I tried to run them with Xcode 7.3, with bas SDK iOS 9.3, all of them are failing.
After looking at the issue, it seems that after the app launches, it tries to tap on the buttons a little too fast, note that at this point I can assert for the existence of the button with a simple NSPredicate, and it does in fact exist, the engine finds it, but when it tries the tap, despite not failing in the logs, the method for the IBAction does NOT get called.
I created a brand new project to test this issue, first I simply created a single view application, no navigation controller involved, with a single UIButton, and hooked up the IBAction to the view controller, then simply added this UI unit test:
    func testExample()
{
    XCUIApplication().buttons["Button"].tap()
}

And set a breakpoint in the IBAction method on my view controller, it got called. Then I decided to make my UIViewController with the button the root view controller of a UINavigationController, ran the same test, and now the tap does not work!. If I add a simple delay such as:
    func testExample()
{
    sleep(1)
    XCUIApplication().buttons["Button"].tap()
}

Then the button tap happens, and the executions stops on the IBAction breakpoint, If I run this code without the sleep in Xcode 7.2. it also gets called. There seems to be a definite problem with Xcode 7.3 or rather iOS Base SDK 9.3, with XCTest UI testing, I know i can simply add sleep at setUp for all test cases, and they work, however this is a big hack, surprisingly I could not find any topics online with this issue, anyone else experiencing the same and has a good work around for it?
It seems to work as long as you wait more than 0.3 seconds, that is
NSThread.sleepForTimeInterval(0.4) // works
NSThread.sleepForTimeInterval(0.3) // Does not work

Curiously enough the animation for a view controller push is 0.35 seconds, note that I am not pushing anything, but simply adding the view controller as the root view controller, but just found that apparent relation interesting.


text:
Q: Is there a way to redirect CNAME www.mywebsite.com to https://www.mywebsite.com with ovh and heroku I am hosting my nodejs app in heroku and my domain name is in OVH.
I managed to create a subdomain www and a CNAME record that points to my heroku app. It is working fine and SSL is also working fine from heroku.
I added a redirection from all subdomains to https://www.mywebsite.com and everything is working fine.
My problem is when i type www.mywebsite.com, there is no redirection and no SSL.
How can i redirect www.mywebsite.com to https://www.mywebsite.com ?
Thanks !

A: Unfortunately, No.
DNS maps domain names onto IP addresses, that is, it tells the client that example.com points to 12.34.56.78. HTTP vs. HTTPS is a matter of picking a port, and using the right protocol, and this is negotiated directly between client and server; DNS lookup has already happened before that.
If you want to redirect all plain-http traffic to https, you have to do it on the web server, not the DNS server.
In your situation, you could do this in node.js.
There tons of examples online for node's built-in http server or for frameworks like express. I'd recommend this solution.
But there are also solutions like Cloudflare.
They offer you a DNS Service and a proxy, which can handle such HTTP to HTTPS redirection and they even let you use their own SSL Certificate, so you don't need to buy (or let's encrypt) a SSL Certificate on your own, for example.


text:
Q: $http calculate download time I have this function which calculates the time it takes to download a text file (3MB in size) from my server. It works fine for just one request but if I try to run say, 10 of these at once the time the call spend waiting for a response from the server is included in loadTime. Is there any way I can get a trigger when the actual download starts?
Here is my function
function getLargeData() {
    var loadTime = 0;
    var dlSpeed = 0;
    var promise = $q.defer();
    var startTime = new Date();
    $networkSvc.getLargeData()
        .success(function (data) {
            loadTime = new Date() - startTime;
            dlSpeed = 3 / (loadTime / 1000);
            var ret = { loadTime: loadTime, dlSpeed: dlSpeed };
            promise.resolve(ret);
            return promise.promise;
        })
        .error(function() {
            $scope.message = "Error - could not contact server.";
        });
    return promise.promise;
}

A: The promise then can have third argument, which is notification function that can be notified from deferred object, before finish.
.then(   function() {
$log.log('success');  },
null,
 $log.log );

And there is possible function to resolve.
   function resolveProgress() {
    for (var i=0; i<=10; i++) {
    deferred.notify(i);
    if (i>=100) { deferred.resolve() };
    }; }


text:
Q: DateTime::createFromFormat is returning false even though it shouldn't I am trying to make sure a date is a valid date, it is like so 07/24/2015 - 07/24/2015
This is my code to make sure it's value
//split the start and end date in to 2 and compare both to a real date to make sure they're valid
        $newdate = explode("-", $start);

        //echo 1;
        //make sure date 2 is set
        if(!isset($newdate[1])): Session::set('error', 13); return false; endif;

        //check if newdate 0 and 1 are real dates
        $date1 = DateTime::createFromFormat('m-d-Y', str_replace("/","-",$newdate[0]));
        $date2 = DateTime::createFromFormat('m-d-Y', str_replace("/","-",$newdate[1]));

        echo date("m-d-Y").'<br/>';
        echo str_replace("/","-",$newdate[0]);

        var_dump($date1);
        var_dump($date2);
        //not valid dates
        if($date1 == false || $date2 == false): Session::set('error',13); return false; endif;

I have tried it with, and without str_replace, I have compared the date("m-d-Y"); to my $newdate with str_replace and they match perfect, but I am still getting a (bool)false with my dates even though they're valid

A: I would start by fixing the explode to be on ' - ', since '-' is leaving extra spaces at the beginning and end of your date strings. That will fix it. Shown here: https://eval.in/404554
Next, you don't need to bother with str_replace on them.
$dates = '07/24/2015 - 07/24/2015';
$newdate = explode(" - ", $dates);

$date1 = DateTime::createFromFormat('m/d/Y', $newdate[0]);
$date2 = DateTime::createFromFormat('m/d/Y', $newdate[1]);

Valid dates: https://eval.in/404555


text:
Q: React. How redux-persist rehydrate after login? if the user fills out the form for a long time, the token can expire. When the user logs in again, needing to download the data. If it's the wrong user, delete it.
now it work Example:
1 persist/PERSIST
2 persist/REHYDRATE auth
3 persist/REHYDRATE root
4 request isAuth account: true
5 request getAuth account: {userId: 1}
this load root in state before auth and save account: true
How I can rehydrate root after authorization? or back to initial root after another user login?
Store:
  const initialize = (initialState?: IRootState, middlewares = []) => {
  const store = createStore(reducerPersist, initialState, composeEnhancers(applyMiddleware(...defaultMiddlewares, ...middlewares)));
  const persistor = persistStore(store, null, () => {});
  return { store, persistor };
};

rootReducer
const authTransform = createTransform(
  (inboundState: IAccount) => ({ userId: inboundState.userId }),
  (outboundState: IAccount) => (outboundState),
  { whitelist: ['account'] }
);

const authConfig = {
  key: 'auth',
  storage,
  stateReconciler: autoMergeLevel2,
  whitelist: ['account'],
  transforms: [authTransform]
};

const rootReducer = combineReducers<IRootState>({
  authentication: persistReducer<AuthenticationState>(authConfig, authentication),
  locale,
... +50 another reducers

my persist-reducer
export const ACTION_TYPES = {
  RESET: 'persist/RESET'
};

const persistConfig = {
  key: 'root',
  storage,
  whitelist: [
    'formBlockState',
    'formCommentBlockState'
  ],
 stateReconciler: autoMergeLevel2
};
const rootReducer = (state: IRootState, action) => {
  if (action.type === ACTION_TYPES.RESET) {
    persistConfig.whitelist.forEach(key => state[key] = undefined);
  }
  return reducer(state, action);
};
const reducerPersist = persistReducer<IRootState>(persistConfig, rootReducer);

export default reducerPersist;

export const clearPersist = () => ({
  type: ACTION_TYPES.RESET
});

app
const { store, persistor } = initStore();

const rootEl = document.getElementById('root');

const render = Component =>
  ReactDOM.render(
    <ErrorBoundary>
      <AppContainer>
        <Provider store={store}>
          <PersistGate loading={null} persistor={persistor}>
              <Component />
          </PersistGate>
        </Provider>
      </AppContainer>
    </ErrorBoundary>,
    rootEl
  );

render(AppComponent);
in AppComponent
  componentDidMount() {
    this.loadData();
  }

      async loadData() {
        await this.props.isUserAuthenticated();
        if (this.props.isAuthenticated) {
          await this.props.getSession();
          await this.props.getProfile();
          ...

this.props.isUserAuthenticated - return state.account - true // replace persist:auth
this.props.getSession - return state.account.userId // old userId - clear
initial state set in reducers in combineReducer
if I write
  if (action.type === ACTION_TYPES.RESET) {
    state = undefined);
  }
  return reducer(state, action);

I have error in components get field state
How I can rehydrate root after authorization? or back to initial root after another user login?


text:
Q: File/symbol dependency graph visualisation for C/C++ I am well aware of Doxygen's ability to visualise the function call graph and file-level include dependency graph. I'm interested in a tool to give a visual overview of a whole project's file-level dependencies in a single graph. The nodes of the graph would be modules/objects, e.g. Foo.cpp/hpp files would considered a single entity and be a single node "Foo". Doxygen's include dependency graph only shows the include chain of a single file, as far as I'm aware.
It would seem the two ways to do this would be:

*

*Symbol dependencies of the object files - so this tool would take the compiled object files as input.

*Include dependencies, but each node is the combined source and header file, rather than just the headers. This tool would take the source files as input, and relies on A.cpp having a corresponding A.hpp in a findable location. This method would result in some extra dependency edges for non-symbol dependencies, as well as unnecessary include dependencies.
Is there such a tool that does this, preferably free?

A: You can try CppDepend, it takes as input the source code and gives you the possibility to have advanced dependency graphs using our code query language to filter what you want to be in the graph.


text:
Q: nl2br doesn't work with text from the database I try this:
echo nl2br($row['content']);

But what I get is:

Hello everybody\n Good luck!

Why doesn't it convert the \n? the database is storing data as UTF-8.
In addition, I check it with a test string, and found out that if the string is with double quotes it doesn't work too.. I mean:
echo nl2br("Hello everybody\n Good luck");

A: It should work but if you wish you can try str_replace("\n","
") instead of nl2br.

A: The issue is that the text is being stored with an additional slash in your database. Use the stripslashes (PHP doc here) function on the text before nl2br (PHP doc here)
$myText = "Hello\\nWorld"; //text from a database (with line breaks escaped)
stripslashes(nl2br($myText));
print $myText;
// Result: Hello
World

A: I guess you have written to database \n as two characters, so it's not a "new line" character.
Try echo str_replace('\n','
', $row['content'])


text:
Q: How to do printf in r? I'm looking for how to do printf in r, ie I want to type:
printf("hello %d\n", 56 )

and get the same output as typing:
print(sprintf("hello %d\n", 56 )

I've read the following links:

*

*Printing newlines with print() in R

*what's a prettier way to print info with R?
... so I'm aware I could use cat("hello", 56) , and that's probably what I will do, but just wondering if there is some shortcut way of writing print(sprintf(...))?
Sorry if this question is a duplicate (I dont know).  It's awfully hard to search for 'printf r', since it returns results for php, c, ...

A: If you want a function that does print(sprintf(...)), define a function that does that.
printf <- function(...)print(sprintf(...))

printf("hello %d\n", 56)
## [1] "hello 56\n"
 d <- printf("hello %d\n", 56)
## [1] "hello 56\n"
d
## [1] "hello 56\n"

A: printf <- function(...) invisible(print(sprintf(...)))

The outer invisible call may be unnecessary, I'm not 100% clear on how that works.

A: My solution:
> printf <- function(...) cat(sprintf(...))
> printf("hello %d\n", 56)
hello 56

The answers given by Zack and mnel print the carriage return symbol as a literal. Not cool.
> printf <- function(...) invisible(print(sprintf(...)))
> printf("hello %d\n", 56)
[1] "hello 56\n"
>
> printf <- function(...)print(sprintf(...))
> printf("hello %d\n", 56)
[1] "hello 56\n"

A: I do it this way:
printf = function(s, ...) cat(paste0(sprintf(s, ...)), '\n')


text:
Q: Adding f1_score metric in compile method for Keras In Keras, assuming I have compile as:
model.compile(optimizer='nadam', loss='binary_crossentropy', metrics=['accuracy'])

And, for some reason, I want to use model.evaluate() instead of model.predict(), how can add f1 score metric to the argument metrics=['accuracy']?
Thank you,


text:
Q: Longtable not starting immediately after section tittle I have been trying to fix this problem by reading many posts for the last two day and I have not been successful.
I have a long table that spreads over three pages and I want to start after the section title.
I don't now what causes the page break. I have tried \clearspace, \needspace and \FloatBarrier among others I can't remember now.
I would appreciate any guidance!
I have provided a shorter version of my document
\documentclass[12pt]{article}
\usepackage[top=1.25in,bottom=1.25in,left=1.25in,right=1.25in]{geometry}
\linespread{1.3}
\usepackage{sectsty}
    \sectionfont{\fontsize{15}{15}\selectfont}
    \subsectionfont{\fontsize{13}{15}\selectfont}

\usepackage{graphicx}
\usepackage{subfig}
%\usepackage{latexsym}
\usepackage{placeins}

\makeatletter
\setlength{\@fptop}{0pt}
\makeatother

\usepackage{amsmath}

\usepackage{needspace}

\usepackage{longtable}
\usepackage{booktabs}
\usepackage{color}
\usepackage{indentfirst}
\usepackage{multirow}
%\usepackage{hhline}
%\usepackage{arydshln}

\usepackage{natbib}
\usepackage[titletoc,title]{appendix}

\newcommand{\tab}[1]{\hspace{.2\textwidth}\rlap{#1}}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\begin{document}
\footnotesize
\begin{longtable}[H!]{@{}cccccccc@{}}
\caption{Absolute displacements obtained from the static analysis}\\
\toprule
\multirow{2}{*}{\textbf{Joint}} & \multirow{2}{*}{\textbf{OutputCase}} & \textbf{U1} & \textbf{U2} & \textbf{U3} & \textbf{R1} & \textbf{R2} & \textbf{R3} \\
 &  & ft & ft & ft & Radians & Radians & Radians \\ \midrule
\endfirsthead
\caption{\textit{\textemdash{}Continued}}\\
\toprule
\multirow{2}{*}{\textbf{Joint}} & \multirow{2}{*}{\textbf{OutputCase}} & \textbf{U1} & \textbf{U2} & \textbf{U3} & \textbf{R1} & \textbf{R2} & \textbf{R3} \\
 &  & ft & ft & ft & Radians & Radians & Radians \\ \midrule
\endhead
\bottomrule \endfoot
\endlastfoot

1 & Settle - DL & 0.000E+00 & 0.000E+00 & -5.000E-01 & 0.000E+00 & 4.100E-05 & 0.000E+00 \\
2 & Settle - DL & 0.000E+00 & 0.000E+00 & 0.000E+00 & 0.000E+00 & 5.816E-07 & 0.000E+00 \\
3 & Settle - DL & 0.000E+00 & 0.000E+00 & 0.000E+00 & 0.000E+00 & -4.969E-07 & 0.000E+00 \\
4 & Settle - DL & 0.000E+00 & 0.000E+00 & 0.000E+00 & 0.000E+00 & 1.149E-06 & -1.056E-08 \\
5 & Settle - DL & 0.000E+00 & 0.000E+00 & 0.000E+00 & 0.000E+00 & 1.609E-06 & 1.783E-08 \\
6 & Settle - DL & 7.148E-06 & 0.000E+00 & 0.000E+00 & 0.000E+00 & 2.087E-07 & 0.000E+00 \\
7 & Settle - DL & 4.914E-06 & 0.000E+00 & 0.000E+00 & 0.000E+00 & -7.058E-08 & 0.000E+00 \\
8 & Settle - DL & 4.328E-06 & 0.000E+00 & 0.000E+00 & 0.000E+00 & -2.593E-07 & 0.000E+00 \\
9 & Settle - DL & 4.022E-06 & 0.000E+00 & 0.000E+00 & 0.000E+00 & 3.812E-07 & 0.000E+00 \\
10 & Settle - DL & 1.854E-06 & 0.000E+00 & 0.000E+00 & 0.000E+00 & -4.575E-07 & 0.000E+00 \\
11 & Settle - DL & 2.349E-06 & 0.000E+00 & 0.000E+00 & 0.000E+00 & 6.551E-07 & 0.000E+00 \\
12 & Settle - DL & 9.812E-08 & 0.000E+00 & 0.000E+00 & 0.000E+00 & 4.600E-07 & 0.000E+00 \\
13 & Settle - DL & 8.270E-07 & 0.000E+00 & 0.000E+00 & 0.000E+00 & -4.184E-07 & 0.000E+00 \\
14 & Settle - DL & 7.700E-05 & 0.000E+00 & 0.000E+00 & 0.000E+00 & 1.479E-06 & -3.821E-07 \\
15 & Settle - DL & 6.700E-05 & 0.000E+00 & 0.000E+00 & 0.000E+00 & 1.461E-06 & -3.929E-07 \\
16 & Settle - DL & 5.500E-05 & 0.000E+00 & 0.000E+00 & 0.000E+00 & 1.539E-06 & -3.398E-07 \\
17 & Settle - DL & 4.700E-05 & 0.000E+00 & 0.000E+00 & 0.000E+00 & 1.372E-06 & -3.362E-07 \\
18 & Settle - DL & 3.400E-05 & 0.000E+00 & 0.000E+00 & 0.000E+00 & 1.588E-06 & -2.313E-07 \\
19 & Settle - DL & 2.800E-05 & 0.000E+00 & 0.000E+00 & 0.000E+00 & 1.386E-06 & -2.207E-07 \\
20 & Settle - DL & 1.100E-05 & 0.000E+00 & 0.000E+00 & 0.000E+00 & 1.614E-06 & -1.148E-07 \\
21 & Settle - DL & 8.219E-06 & 0.000E+00 & 0.000E+00 & 0.000E+00 & 1.224E-06 & -1.605E-07 \\
121 & Settle - DL & -7.327E-06 & 0.000E+00 & 0.000E+00 & 0.000E+00 & 7.700E-05 & -5.503E-07 \\
122 & Settle - DL & -5.483E-07 & 0.000E+00 & 0.000E+00 & 0.000E+00 & -1.709E-08 & 0.000E+00 \\
123 & Settle - DL & 2.418E-06 & 0.000E+00 & 0.000E+00 & 0.000E+00 & 1.322E-07 & 0.000E+00 \\
124 & Settle - DL & 2.363E-06 & 0.000E+00 & 0.000E+00 & 0.000E+00 & 6.062E-08 & 0.000E+00 \\
125 & Settle - DL & 2.345E-06 & 0.000E+00 & 0.000E+00 & 0.000E+00 & 9.417E-08 & 3.309E-07 \\
126 & Settle - DL & 5.060E-04 & 0.000E+00 & 0.000E+00 & 0.000E+00 & 4.600E-05 & 0.000E+00 \\
127 & Settle - DL & 5.080E-04 & 0.000E+00 & 0.000E+00 & 0.000E+00 & 2.600E-05 & 0.000E+00 \\
128 & Settle - DL & 5.080E-04 & 0.000E+00 & 0.000E+00 & 0.000E+00 & 3.600E-05 & -1.400E-05 \\
129 & Settle - DL & -9.299E-06 & 0.000E+00 & 0.000E+00 & 0.000E+00 & 4.600E-05 & -3.990E-06 \\
130 & Settle - DL & -5.234E-06 & 0.000E+00 & 0.000E+00 & 0.000E+00 & -2.723E-06 & 1.090E-06 \\
131 & Settle - DL & -7.327E-07 & 0.000E+00 & 0.000E+00 & 0.000E+00 & -2.300E-05 & -5.499E-07 \\
132 & Settle - DL & 7.833E-06 & 0.000E+00 & 0.000E+00 & 0.000E+00 & 4.700E-05 & -6.579E-07 \\
133 & Settle - DL & 3.748E-06 & 0.000E+00 & 0.000E+00 & 0.000E+00 & -4.226E-07 & 0.000E+00 \\
134 & Settle - DL & 2.804E-06 & 0.000E+00 & 0.000E+00 & 0.000E+00 & 5.619E-07 & 0.000E+00 \\
135 & Settle - DL & 2.927E-06 & 0.000E+00 & 0.000E+00 & 0.000E+00 & 7.289E-08 & 0.000E+00 \\
136 & Settle - DL & 2.962E-06 & 0.000E+00 & 0.000E+00 & 0.000E+00 & 8.291E-08 & 4.645E-07 \\
137 & Settle - DL & 1.027E-03 & 0.000E+00 & 0.000E+00 & 0.000E+00 & 4.200E-05 & 0.000E+00 \\
138 & Settle - DL & 1.025E-03 & 0.000E+00 & 0.000E+00 & 0.000E+00 & 3.300E-05 & 0.000E+00 \\
139 & Settle - DL & 1.025E-03 & 0.000E+00 & 0.000E+00 & 0.000E+00 & 3.800E-05 & -2.800E-05 \\
140 & Settle - DL & -1.400E-05 & 0.000E+00 & 0.000E+00 & 0.000E+00 & 2.900E-05 & -6.398E-06 \\
141 & Settle - DL & -1.700E-05 & 0.000E+00 & 0.000E+00 & 0.000E+00 & -1.318E-06 & 1.613E-06 \\
142 & Settle - DL & -2.000E-05 & 0.000E+00 & 0.000E+00 & 0.000E+00 & -1.200E-05 & -8.023E-07 \\
143 & Settle - DL & 4.399E-06 & 0.000E+00 & 0.000E+00 & 0.000E+00 & 4.700E-05 & -8.006E-07 \\
144 & Settle - DL & 5.284E-06 & 0.000E+00 & 0.000E+00 & 0.000E+00 & -1.578E-07 & 0.000E+00 \\
145 & Settle - DL & 4.862E-06 & 0.000E+00 & 0.000E+00 & 0.000E+00 & 2.923E-07 & 0.000E+00 \\
146 & Settle - DL & 4.711E-06 & 0.000E+00 & 0.000E+00 & 0.000E+00 & 3.888E-08 & 0.000E+00 \\
147 & Settle - DL & 4.681E-06 & 0.000E+00 & 0.000E+00 & 0.000E+00 & 7.449E-08 & 7.542E-07 \\
148 & Settle - DL & 1.561E-03 & 0.000E+00 & 0.000E+00 & 0.000E+00 & 4.500E-05 & 0.000E+00 \\
149 & Settle - DL & 1.561E-03 & 0.000E+00 & 0.000E+00 & 0.000E+00 & 3.300E-05 & 0.000E+00 \\
150 & Settle - DL & 1.561E-03 & 0.000E+00 & 0.000E+00 & 0.000E+00 & 3.900E-05 & -4.100E-05 \\
151 & Settle - DL & -2.300E-05 & 0.000E+00 & 0.000E+00 & 0.000E+00 & 2.900E-05 & -8.542E-06 \\
152 & Settle - DL & -2.200E-05 & 0.000E+00 & 0.000E+00 & 0.000E+00 & -1.292E-06 & 2.094E-06 \\
153 & Settle - DL & -2.400E-05 & 0.000E+00 & 0.000E+00 & 0.000E+00 & -1.400E-05 & -1.024E-06 \\
154 & Settle - DL & 3.100E-05 & 0.000E+00 & 0.000E+00 & 0.000E+00 & 8.500E-05 & -8.402E-07 \\
155 & Settle - DL & 1.100E-05 & 0.000E+00 & 0.000E+00 & 0.000E+00 & 1.708E-06 & 0.000E+00 \\
156 & Settle - DL & 2.756E-06 & 0.000E+00 & 0.000E+00 & 0.000E+00 & -1.572E-06 & 0.000E+00 \\
157 & Settle - DL & 2.827E-06 & 0.000E+00 & 0.000E+00 & 0.000E+00 & -1.012E-07 & 0.000E+00 \\
158 & Settle - DL & 2.840E-06 & 0.000E+00 & 0.000E+00 & 0.000E+00 & -2.332E-07 & 8.334E-07 \\
159 & Settle - DL & 2.121E-03 & 0.000E+00 & 0.000E+00 & 0.000E+00 & 5.700E-05 & 0.000E+00 \\
160 & Settle - DL & 2.115E-03 & 0.000E+00 & 0.000E+00 & 0.000E+00 & 2.500E-05 & 0.000E+00 \\
161 & Settle - DL & 2.115E-03 & 0.000E+00 & 0.000E+00 & 0.000E+00 & 4.000E-05 & -5.600E-05 \\
162 & Settle - DL & -2.000E-05 & 0.000E+00 & 0.000E+00 & 0.000E+00 & 5.000E-05 & -9.998E-06 \\
163 & Settle - DL & -3.200E-05 & 0.000E+00 & 0.000E+00 & 0.000E+00 & -1.969E-06 & 2.630E-06 \\
164 & Settle - DL & -4.600E-05 & 0.000E+00 & 0.000E+00 & 0.000E+00 & -3.700E-05 & -1.307E-06 \\
166 & Settle - DL & 0.000E+00 & 0.000E+00 & 0.000E+00 & 0.000E+00 & 2.168E-07 & 0.000E+00 \\
167 & Settle - DL & 0.000E+00 & 0.000E+00 & -5.000E-01 & 0.000E+00 & 2.035E-07 & 3.309E-07 \\
168 & Settle - DL & 0.000E+00 & 0.000E+00 & 0.000E+00 & 0.000E+00 & 3.200E-05 & 0.000E+00 \\
171 & Settle - DL & 0.000E+00 & 0.000E+00 & -1.333E+00 & 0.000E+00 & 3.600E-05 & -1.400E-05 \\
172 & Settle - DL & 0.000E+00 & 0.000E+00 & 0.000E+00 & 0.000E+00 & 6.682E-07 & 5.209E-07 \\
173 & Settle - DL & 0.000E+00 & 0.000E+00 & 0.000E+00 & 0.000E+00 & 1.000E-05 & -5.499E-07 \\
174 & Settle - DL & 0.000E+00 & 0.000E+00 & 0.000E+00 & 0.000E+00 & -3.800E-05 & -5.503E-07 \\
175 & Settle - DL & 0.000E+00 & 0.000E+00 & 0.000E+00 & 0.000E+00 & -2.300E-05 & -3.588E-06 \\
176 & Settle - DL & 1.800E-05 & 0.000E+00 & 0.000E+00 & 0.000E+00 & 1.510E-06 & -2.128E-07 \\
177 & Settle - DL & 2.200E-05 & 0.000E+00 & 0.000E+00 & 0.000E+00 & 1.560E-06 & -1.895E-07 \\
178 & Settle - DL & 2.710E-04 & 0.000E+00 & 0.000E+00 & 0.000E+00 & 1.900E-05 & -9.837E-06 \\
179 & Settle - DL & -3.674E-06 & 0.000E+00 & 0.000E+00 & 0.000E+00 & -2.975E-07 & 6.671E-08 \\
180 & Settle - DL & 1.860E-04 & 0.000E+00 & 0.000E+00 & 0.000E+00 & 1.300E-05 & -1.200E-05 \\
181 & Settle - DL & 3.700E-05 & 0.000E+00 & 0.000E+00 & 0.000E+00 & 1.398E-06 & -2.880E-07 \\
182 & Settle - DL & 4.500E-05 & 0.000E+00 & 0.000E+00 & 0.000E+00 & 1.563E-06 & -2.977E-07 \\
183 & Settle - DL & 5.430E-04 & 0.000E+00 & 0.000E+00 & 0.000E+00 & 1.900E-05 & -2.000E-05 \\
184 & Settle - DL & -8.153E-06 & 0.000E+00 & 0.000E+00 & 0.000E+00 & -3.441E-07 & 4.369E-07 \\
185 & Settle - DL & 3.760E-04 & 0.000E+00 & 0.000E+00 & 0.000E+00 & 1.400E-05 & -2.200E-05 \\
186 & Settle - DL & 5.700E-05 & 0.000E+00 & 0.000E+00 & 0.000E+00 & 1.433E-06 & -3.829E-07 \\
187 & Settle - DL & 6.600E-05 & 0.000E+00 & 0.000E+00 & 0.000E+00 & 1.504E-06 & -3.778E-07 \\
188 & Settle - DL & 8.160E-04 & 0.000E+00 & 0.000E+00 & 0.000E+00 & 2.000E-05 & -2.900E-05 \\
189 & Settle - DL & -1.300E-05 & 0.000E+00 & 0.000E+00 & 0.000E+00 & -3.861E-07 & 5.775E-07 \\
191 & Settle - DL & 5.750E-04 & 0.000E+00 & 0.000E+00 & 0.000E+00 & 1.500E-05 & -3.400E-05 \\
192 & Settle - DL & -1.900E-05 & 0.000E+00 & 0.000E+00 & 0.000E+00 & -4.525E-07 & 9.678E-07 \\
193 & Settle - DL & 7.820E-04 & 0.000E+00 & 0.000E+00 & 0.000E+00 & 1.500E-05 & -4.600E-05 \\
194 & Settle - DL & 7.700E-05 & 0.000E+00 & 0.000E+00 & 0.000E+00 & 1.538E-06 & -3.978E-07 \\
195 & Settle - DL & 8.700E-05 & 0.000E+00 & 0.000E+00 & 0.000E+00 & 1.456E-06 & -3.795E-07 \\
196 & Settle - DL & 1.089E-03 & 0.000E+00 & 0.000E+00 & 0.000E+00 & 2.000E-05 & -4.100E-05 \\
197 & Settle - DL & 0.000E+00 & 0.000E+00 & 0.000E+00 & 0.000E+00 & 1.900E-05 & -9.837E-06 \\
198 & Settle - DL & 0.000E+00 & 0.000E+00 & 0.000E+00 & 0.000E+00 & -2.452E-07 & 6.671E-08 \\
199 & Settle - DL & 0.000E+00 & 0.000E+00 & -1.000E+00 & 0.000E+00 & 1.300E-05 & -1.700E-05 \\ \bottomrule
\label{AbsoluteDisp}
\end{longtable}
\end{document}


text:
Q: PHP Serilization fails in PHP 5.5 but not PHP 5.3 I'm trying to troubleshoot a serialization problem and want to find out more about the following:
if ($result === false && serialize(false) !== $postResult)

I'm trying to break this up into litle chunks to solve it.
if ($result === false)
{
throw new ClientException("the result is false ===");
}

Why will this throw an exception? I don't understand what this relates to. Does false have a natural state for example, no value?
Thank you for the answers, the further information is as follows:
The $result contains a serialized array of media data. If I var_dump($result), I see the array but it fails the IF statement above and I'm not sure why.
I have two bits of the same software. Two versions of PHP, 5.3 and 5.5.
I can var_dump the array and everything looks great on both versions but 5.3 passes the IF statement and 5.5 fails.
Everything else works before that except it maybe failing here:
$result = unserialize($postResult);

The actual sequence being:
$result = unserialize($postResult);

if ($result === false && serialize(false) !== $postResult)

{
throw new ClientException("failed to unserialize server result - the result is as follows:" . "Error start:". print_r($error,true). ":Error end" . "RESULT (After serialize): " . print_r($result,true) . "PARAMS: " . print_r($params,true) . "Files: " . print_r($files,true) . "URL " . print_r($url,true) . "Pre result: " . print_r($postResult,true) .":", ClientException::ERROR_UNSERIALIZE_FAILED);
            }


text:
Q: Subject verb agreement I think below sentence has a subject/verb agreement. Here noun is singular but there are two adjectives.

Public and private life is to be governed.

If the sentence has an error, please explain with suitable examples

A:
Public and private life is to be governed.

For the above sentence, the only context that fits is that Public and private are adjectives for life; therefore, the sentence is fine.


text:
Q: How to use System.Action<> correctly I am currently converting a Windows Forms application into a Console application in C#.
I am busy converting the code and I am having problems with some of the syntax which I am unsure of how to correctly convert.
Here is the original code in the windows forms app:
    private eSkan.api.TeSkanAPI feSkanAPI = null;

    private void MessageFilter_AddRemove_Invoked(bool AddFilter, IMessageFilter Filter)
    {
        if (AddFilter)
        {
            Application.AddMessageFilter(Filter);
        }
        else
        {
            Application.RemoveMessageFilter(Filter);
        }
    }
    private void MessageFilter_AddRemove(bool AddFilter, IMessageFilter Filter)
    {
        {
            IAsyncResult sr = BeginInvoke((ESKAN_ADD_REMOVE_MESSAGEFILTER)MessageFilter_AddRemove_Invoked,
                                          AddFilter, Filter);
            sr.AsyncWaitHandle.WaitOne(2000);
        }
    }

    private void IniteSkan()
    {
        lMSG.Items.Clear();
        feSkanAPI = new TeSkanAPI();
        // To add a message filter you have to add it from the MAIN thread - thus the main form
        feSkanAPI.AddRemoveMessageFilterProc = MessageFilter_AddRemove;
        feSkanAPI.OneSkanEvent += eScan_Callback;
        feSkanAPI.Thread_Start(true);
    }

    public Form1()
    {
        InitializeComponent();

    }

    private void eScan_Callback_safe(EeSkan_EventType command, object Data)
    {

        lMSG.Items.Insert(0, "++++++++");
        lMSG.Items.Insert(0, DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss"));
        lMSG.Items.Insert(0, "New Command "+command.ToString());

        if (Data is TeSkan_EventInfo)
        {
            lMSG.Items.Insert(0, "Data File : " + ((TeSkan_EventInfo)Data).DataFile);
            lMSG.Items.Insert(0, "Image File : " + ((TeSkan_EventInfo)Data).ImageFile);
        } else if (Data is string)
        {
            lMSG.Items.Insert(0, "Data String : " + (string) Data);
        }

        //lMSG.Items.Insert(0, "Image File " + ScanInfo.ImageFile);
        //lMSG.Items.Insert(0, "Data File " + ScanInfo.ImageFile);
        lMSG.Items.Insert(0, "--------");
    }

    /// <summary>
    /// When accesing GUI/Form/Components - you cannot work cross-thread.
    /// This method will invoke eScan_Callback_safe in main/GUI thread if another thread called it,
    /// or call eScan_Callback_safe directly if already on GUI/main thread
    ///
    /// </summary>
    /// <param name="ScanInfo"></param>
    private void eScan_Callback(EeSkan_EventType command, object Data)
    {

        if (InvokeRequired)
        {
            this.Invoke((ESKAN_EVENT_CALLBACK)eScan_Callback_safe, command, Data);
        }
        else
        {
            eScan_Callback_safe(command, Data);
        }
    }

    private void Form1_FormClosing(object sender, FormClosingEventArgs e)
    {
        feSkanAPI.Thread_Stop(10000);
        feSkanAPI.Dispose();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        IniteSkan();
    }

I am using Action to do the BeginInvoke part in the console application. And I would like to know what would be the best to use for "InvokeRequired" part in the "eScan_Callback()" function.

A: InvokeRequired is to check if the current thread can safely access winforms controls. If you're converting it to a console application, you can probably just replace this with the standard method call in the 'else' block.
However, it looks like this is doing some threading things, so rather than a copy & paste job, I would look at what this form is doing overall, and rewrite it in a more 'console-y' way.

A: Reading that your making a console application I don't think you need this code, just use: eScan_Callback_safe(command, Data);


text:
Q: Polymer is not defined, Reference error in Firefox What is missing in this simple code, that fails in Firefox while works fine in Chrome?
<!DOCTYPE html>
<html>
<head>
<base href="//polygit.org/components/">
<script src="webcomponentsjs/webcomponents.js"></script>
<link rel="import" href="paper-material/paper-material.html">

<dom-module id="ui-firefox">
  <template>
    <paper-material>Can you see me in Firefox?</paper-material>
  </template>
  <script>
    Polymer({
      is: "ui-firefox",
      ready: function(){ console.log("Am I ready?"); }
    });
  </script>
</dom-module>

</head>
<body>
  <ui-firefox> </ui-firefox>
</body>
</html>

A fiddle sample here https://jsfiddle.net/s4oh43za/
I have read a few posts, but I couldn't find the solution for this simple case
Thanks in advance, Fausto

A: My guess is Firefox loads HTML imports in a different way.
The Polymer docs recommend wrapping your dom-module script in HTMLImports.whenReady(function() {...}) when it's defined in index.html. This modified version of your jsfiddle works in both Firefox and Chrome after following that recommendation.


text:
Q: how to convert anyhow error to std error? I am new to anyhow and I would like to know if there is a way to convert anyhow error to std error
code
fn m() {
    let a: anyhow::Result<String> = Ok("".into());
    n(a);
}

fn n(r: std::result::Result<String, impl std::error::Error>) {
    println!("{:?}", r);
}

error msg
error[E0277]: the trait bound `anyhow::Error: std::error::Error` is not satisfied
  --> src\main.rs:82:7
   |
82 |     n(a);
   |     - ^ the trait `std::error::Error` is not implemented for `anyhow::Error`
   |     |
   |     required by a bound introduced by this call

A: Use the Deref or AsRef impl:
match a {
    Ok(v) => n(Ok::<_, &dyn std::error::Error>(v)),
    Err(e) => n(Err::<_, &dyn std::error::Error>(e.as_ref())),
}
// Or
match a {
    Ok(v) => n(Ok::<_, &dyn std::error::Error>(v)),
    Err(e) => n(Err::<_, &dyn std::error::Error>(&*e)),
}


text:
Q: tsLint enabled in Angular 2 webpack Actually i created one project with Angular 2 webpack from
https://angular.io/docs/ts/latest/guide/webpack.html
Now I want to enable tsLint in Visual Studio Code. i already add tsLint.json file in my project.
And also installed codelyzer @2.0.0-beta.4 & tslint @4.0.0 and also made changes in setting.json of VS Code.
but tsLint is still not enabled.

A: npm install --save-dev tslint-eslint-rules
Use this link if the above does not work:
https://marketplace.visualstudio.com/items?itemName=eg2.tslint


text:
Q: Adding lines to text files through Group Policy I need to add two lines to text files using group policy. I cannot replace the files with the updated one since the content of the files differs from one machine to another, but all of them have to be updated with the two new lines. Is it possible to do that?
I already know how to replace a file using a VBScript, then applying it through group policy.
Thanks,
Abdullah

A: This vbscript gives you an idea of what it should look like.  They key is to open the files for appending, not for writing.  This will just add two lines to the bottom of the text files regardless of their content.
Const ForAppending = 8

strFile1 = "c:\Temp\file1.txt"
strFile2 = "c:\Temp\file2.txt"

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile(strFile1, ForAppending)

objFile.WriteLine "New Text to add 1"
objFile.WriteLine "New Text to add 2"

objFile.Close

Set objFile = objFSO.OpenTextFile(strFile2, ForAppending)

objFile.WriteLine "New Text to add 1"
objFile.WriteLine "New Text to add 2"

objFile.Close

A: You can also just use batch files to do it as well. echo "Add this line to the end of the file." >> \\path\to\file.txt or whatever.  Just do not use the single redirection operation > instead of >, or you will be sorry.


text:
Q: Data driven tests using nested xml data file I need to write a unit test driven by a data file that contains collections of data. For obvious reasons a csv file isn't appropriate, but XML suggests itself. However I can't seem to get it to work.
Here's a fragment of the data file (only one test record shown):
<?xml version="1.0" encoding="utf-8" ?>
<testData>
  <testRecord>
    <displayColumnNames>
      <name>Include</name>
      <name>SampleInt1</name>
      <name>SampleInt2</name>
      <name>SampleInt3</name>
      <name>SampleInt4</name>
      <name>SampleInt5</name>
    </displayColumnNames>
    <valueColIDs>
      <valueColID>1</valueColID>
      <valueColID>3</valueColID>
      <valueColID>5</valueColID>
    </valueColIDs>
    <calculations>
      <calculation colID ="2"><![CDATA[500 * [:5]]></calculation>
      <calculation colID ="5"><![CDATA[500 * [:2]]></calculation>
    </calculations>
    <expected>
      <item>5</item>
    </expected>
  </testRecord>
</testData>

Basically I expected to be able to read in a number of data collections from each test record (e.g. "displayColumnNames") and iterate over the values in my test. The number of elements in each such collection will vary from test case to test case.
However the immediate stumbling block is my code line:
var displayColumnNames = TestContext.DataRow["displayColumnNames"];

which throws a test-time error "Column 'displayColumnNames' does not belong to table testRecord.".
I can get this to work nicely with simple 'flat' xml data files, but that doesn't help me. Am I attempting something that VS2008 (ie MSTest) cannot handle, or am I doing something stupid?

A: You can use
TestContext.DataRow.GetChildRows("testRecord_displayColumnNames")

to access the nested nodes. The relation name - "testRecord_displayColumnNames" can be modified to go deeper into the xml hierarchy. HTH


text:
Q: NZ-Table of NG-Zorro doesn't show any data I'm developing a page where I use a table from ng-zorro, I get the data from an API, but after I filtered the Data the table just show the "No data" display, not showing neither the pagination nor the data per page.
Did I miss some async procedure to get my data and the table read the data response?
The HTML code from my component:
<nz-table #basicTable
  nzBordered
  [nzShowSizeChanger]="true"
  [nzHideOnSinglePage]="false"
  [nzData]="filteredData"
  [nzFrontPagination]="false"
  [nzLoading]="loading"
  [nzTotal]="lastPage"
  [nzPageSize]="dataPerPage"
  [nzPageIndex]="currentPage"
  [nzPageSizeOptions]="[10, 25, 50, 75, 100]"
>

      Puntaje de exposicion
      Nombre de Dominio
      Contiene Agente
      Direccion IPv4
      Direccion IPv6
      Ultima Vez Visto
      Sistema Operativo

      {{data.exposureScore}}
      {{data.fqdn}}
      {{data.hasAgent}}
      {{data.ipv4}}
      {{data.ipv6}}
      {{data.lastSeen | date: 'dd/MM/YYYY'}}
      {{data.operatingSystem}}

</nz-table>

The Component.ts
import {Component, OnInit} from '@angular/core';
import {TableAssetsService} from "../../../core/services/table-assets.service";

@Component({
  selector: 'app-table-tenable',
  templateUrl: './table-tenable.component.html',
  styleUrls: ['./table-tenable.component.scss']
})
export class TableTenableComponent implements OnInit {

  loading: boolean = true; //Loading flag
  filteredData: any[] = [];
  date_range: number = 0;
  page: number = 1;
  limit: number = 50;
  lastPage: number = 1;
  currentPage: number = 1;
  dataPerPage: number = 10;

  constructor(private tableSvc: TableAssetsService) { }

  ngOnInit(): void {
    this.getDataFromAPI(this.date_range, this.page, this.limit);this.getDataFromAPI(this.date_range, this.page, this.limit);
  }

  getDataFromAPI (date_range: number, page: number, limit: number): void {
    this.loading = true;
    this.tableSvc.getTableAssets(date_range, page, limit).subscribe(result => {
      this.filteringData(result)
      this.loading = false;
      console.log(this.filteredData)
    })
  }

  filteringData(response: any) {
    this.lastPage = response.data["lastPage"] * response.data["dataPerPage"];
    this.currentPage = response.data['currentPage'];
    this.dataPerPage = response.data['dataPerPage'];

    for (let i = 0; i < response.data.data.length; i++) {
      this.filteredData[i] = {
        exposureScore: response.data.data[i].exposure_score !== null ? response.data.data[i].exposure_score : 0,
        fqdn: response.data.data[i].fqdn.length !== 0 ? response.data.data[i].fqdn : "Sin nombre de dominio",
        hasAgent: response.data.data[i].has_agent ? 'Si' : 'No',
        ipv4: response.data.data[i].ipv4.length !== 0 ? response.data.data[i].ipv4 : "Sin dirección IPv4",
        ipv6: response.data.data[i].ipv6.length !== 0 ? response.data.data[i].ipv6 : 'Sin direccion IPv6',
        lastSeen: response.data.data[i].last_seen,
        operatingSystem: response.data.data[i].operating_system.length !== 0 ? response.data.data[i].operating_system : 'Sin sistema operativo'
      }
    }
  }
}

Thanks a lot for your help.
(Image of the table)

A: In such a case, you would want to go back to a more simple case and restart from there :
Make your table load data from static values, no filter, no side effect, check that it works, then try to reproduce the working example from here :
https://ng.ant.design/components/table/en#components-table-demo-ajax.
Try to fork their example on stackblitz maybe, because as you can see, they are using the nzData Input attribute. I would try the same way.
Only when it works, add your filtering and other side effects.

A: so the problem was about handleling promises, the next code is the correct one.
getVulnerabilitiesStates(date_range: number): void {
    this.preStatesData = [];
    this.statesData = [];
    this.isLoadingStates = true;

    this.tenableService
      .getVulnerabilitiesState(date_range)
      .pipe(
        finalize(() => {
          this.isLoadingStates = false;
        })
      )
      .subscribe({
        next: (response: any) => {
          this.filteringStatesData(response)
            .then((filtered: any) => {
              this.statesData = filtered;
              console.log("States Data", this.statesData)
            })
            .catch((e) => {
              console.error(e);
            });
        },
      });
  }


text:
Q: Why are these functions abstract , where to find the body(specific implementation) of them?
I want to know the implementation of the function getPackageInfo (because I wanna know where is the package stored they are referring to), so I went to this to see the source code, but only found an abstract method there.
public abstract PackageInfo getPackageInfo(String packageName, int flags) throws NameNotFoundException;

Where is the implementation of the method?

A: the implementation of getPackageInfo method is in com.android.server.pm.PackageManagerService
 @Override
public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
    // reader
    synchronized (mPackages) {
        PackageParser.Package p = mPackages.get(packageName);
        if (DEBUG_PACKAGE_INFO)
            Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
        if (p != null) {
            return generatePackageInfo(p, flags);
        }
        if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
            return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
        }
    }
    return null;
}

you can look here


text:
Q: How to set the ITIMER_REAL value using setitimer for a cloned process? From what I understand, one may set the timer values for a process or thread using the setitimer function. However, doesn't this mean that I need to add this line in the code of the running process?
I am basically trying to use RR scheduling using the SIGALARM signal and setitimer(). I want to define my own quatum. This quantum is basically the timer of a process/thread. WHen the timer expires, the process/thread receives a SIGALRM and I create a handler that does sched_yield() so that the process/thread is pre-empted.
However, as I mentioned above, I do not know how I set the timer values for individual processes without altering the code of the function that I am cloning. Some code below:
void RR_switch(int sig) {
        printf("Scheduler yielding for thread id %d\n", syscall(SYS_gettid));
        sched_yield();
}

int main() {
            struct sigaction new_action, old_action;
            new_action.sa_handler = RR_switch;
            sigaction(SIGALRM, &new_action, NULL);
            int pagesize = (int) getpagesize();
            void *t_stack = malloc(pagesize);
            int child_t = clone(&test, t_stack + pagesize, CLONE_THREAD || CLONE_VM || CLONE_CHILD_SETTID || CLONE_VFORK || CLONE_SIGHAND, NULL);
            //raise(SIGSEGV);
            printf("Child thread id from main is %d\n", child_t);
            printf("Main thread id is %d\n", (int) syscall(SYS_gettid));
            return 1;
    }

I want the function "test", which is being created through clone, to have a timer value of my choice.


text:
Q: Callinga column but error not exists even though column exists in the df I am trying to plot a line graph with respect to years . I am calling the column from the dataframe but it can't see it i dont know why even though you will find in the screenshot that the column exists in the dataframe
Here i printed the df columns and the column itslef but still got the error


text:
Q: Kubernetes volume types I have dirctory on K8 master server.
I have  20 pods (With Deployment replicas).
I want all pods read from master directory /path/in/master/infiles And write their output to same directory /path/in/master/outfiles, Which Volume type should I need to use at this case? I Want my files not deleted after pod die.
I trying to look at  the following: https://kubernetes.io/docs/concepts/storage/volumes/ but still don't know  what is the best options for my case.
Any suggestions?

A: You can use hostPath volume.
A hostPath volume mounts a file or directory from the host node's filesystem into your Pod.
apiVersion: v1
kind: PersistentVolume
metadata:
  name: task-pv-volume
  labels:
    type: local
spec:
  storageClassName: manual
  capacity:
    storage: 10Gi
  accessModes:
    - ReadWriteMany
  hostPath:
    path: "/path/in/master/infiles"

Check this guide on how to use hostPath.
A better option would be to use local volume.
apiVersion: v1
kind: PersistentVolume
metadata:
  name: example-pv
spec:
  capacity:
    storage: 100Gi
  volumeMode: Filesystem
  accessModes:
  - ReadWriteOnce
  persistentVolumeReclaimPolicy: Delete
  storageClassName: local-storage
  local:
    path: "/path/in/master/infiles"
  nodeAffinity:
    required:
      nodeSelectorTerms:
      - matchExpressions:
        - key: kubernetes.io/hostname
          operator: In
          values:
          - example-node

Compared to hostPath volumes, local volumes can be used in a durable and portable manner without manually scheduling Pods to nodes, as the system is aware of the volume's node constraints by looking at the node affinity on the PersistentVolume.
Edit:
The problem with storing data in the filesystem of the nodes itself is that there is no way to sync the data between the nodes. If this is needed for the application then using a PV backed by NFS in ReadWriteMany(RWX) mode is a better option. Here is guide on how to make this work in digital ocean.


text:
Q: How to remove empty/blank lines from a file in Unix (including spaces)? How do I remove empty/blank (including spaces only) lines in a file in Unix/Linux using the command line?
contents of file.txt
Line:Text
1:<blank>
2:AAA
3:<blank>
4:BBB
5:<blank>
6:<space><space><space>CCC
7:<space><space>
8:DDD

output desired
1:AAA
2:BBB
3:<space><space><space>CCC
4:DDD

A: grep
Simple solution is by using grep (GNU or BSD) command as below.

*

*Remove blank lines (not including lines with spaces).
grep . file.txt

*Remove completely blank lines (including lines with spaces).
grep "\S" file.txt

Note: If you get unwanted colors, that means your grep is aliases to grep --color=auto (check by type grep). In that case, you can add --color=none parameter, or just run the command as \grep (which ignores the alias).

ripgrep
Similar with ripgrep (suitable for much larger files).
Remove blank lines not including lines with spaces:
rg -N . file.txt

or including lines with spaces:
rg -N "\S" file.txt

See also:

*

*How to remove blank lines from a file (including tab and spaces)?

*With sed: Delete empty lines using sed

*With awk: Remove blank lines using awk

A: To remove empty lines, you could squeeze new line repeats with tr:
cat file.txt | tr -s '\n' '\n'

A: sed '/^$/d' file.txt

d is the sed command to delete a line. ^$ is a regular expression matching only a blank line, a line start followed by a line end.

A: You can use the -v option with grep to remove the matching empty lines.
Like this
grep -Ev "^$" file.txt

A: Here is an awk solution:
awk NF file.txt

With Awk, NF only set on non-blank lines. When this condition match, Awk default action is to print the whole line.

A: This sed line should do the trick:
sed -i '/^$/d' file.txt

The -i means it will edit the file in-place.

A: Ex/Vim
Here is the method using ex editor (part of Vim):
ex -s +'v/\S/d' -cwq test.txt

For multiple files (edit in-place):
ex -s +'bufdo!v/\S/d' -cxa *.txt

Note: The :bufdo command is not POSIX.
Without modifying the file (just print on the standard output):
cat test.txt | ex -s +'v/\S/d' +%p +q! /dev/stdin

A: For me @martigin-heemels command was throwing error this fixed it (ie a dummy param to i),
sed -i '' '/^$/d' file.txt

A: xargs if you dont mind stripping leading whitespace
$ docker run -it --rm alpine sh
/ # cat <<eof > /tmp/file
> one
>
>   two
> three
>
>
>   four
> eof
/ # cat /tmp/file
one

  two
three

  four
/ # cat /tmp/file | xargs -n1
one
two
three
four


text:
Q: Cross-Origin API Spring boot Security I'm trying to call a secure Resource. I use @CrossOrigin(origins = "*") in all rest controllers. But I get cross origin error
I can't call "http://localhost:8081/ifrs/api/v1/period" with "GET" method But I can call "getJwtToken" because it's not scure.
my config is:
@Configuration
public class SecuirtyConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private JwtFilter jwtFilter;

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http
            .cors().and()
            .csrf().disable()
            .authorizeRequests()
            .antMatchers("/ifrs/api/v1/user/token").permitAll()

            .anyRequest().authenticated()

            .and()
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)

            .and()
            .addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class)
            ;

        http.exceptionHandling().authenticationEntryPoint(new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED));

    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Bean
    public PasswordEncoder getPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("*"));
        configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }

}

and JWT config:
@Component
public class JwtFilter extends OncePerRequestFilter {

    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private UserDomainService userDomainService;

    @Override
    protected void doFilterInternal(
            HttpServletRequest request,
            HttpServletResponse response,
            FilterChain filterChain) throws ServletException, IOException {

        try {

            String token = request.getHeader("Authorization");

            String jwtToken = null;
            if ( token != null ) {

                if ( token.startsWith("Bearer ") ) {

                    jwtToken = token.replace("Bearer ", "");

                    String username = jwtUtils.getUsername(jwtToken);
                    username = username.trim();

                    // isUserAuthentication
                    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

                    if (username != null && authentication == null) {
                        User user = (User) userDomainService.loadUserByUsername(username);

                        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());

                        SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
                    }

                } else if ( token.startsWith("Basic ") ) {

                    jwtToken = token.replace("Basic ", "");

                    Base64 codec = new Base64();
                    byte[] decoded = codec.decode(jwtToken);

                    String[] userAndPass = new String(decoded).split(":");
                    String username = userAndPass[0];
                    String password = userAndPass[1];

                    request.setAttribute("username", username);
                    request.setAttribute("password", password);

                }

            }

            filterChain.doFilter(request, response);

        } catch (ExpiredJwtException e) {
            throw e;

        } catch (Exception e) {
            throw e;

        }

    }

}

I test all ways to fix it. @CrossOrigin(origins = "*") is only working for not secure Resources. how to fixe it?
thanks

A: I changed my code
class SecuirtyConfig --> corsConfigurationSource :
@Bean
public CorsConfigurationSource corsConfigurationSource() {
    CorsConfiguration configuration = new CorsConfiguration();
    configuration.setAllowedOrigins(Arrays.asList("*"));
    configuration.addAllowedHeader("*");    // new Line
    configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", configuration);
    return source;
}

and configure(HttpSecurity http) :
.cors().and()
    .csrf().disable()
    .authorizeRequests()
    .antMatchers(HttpMethod.OPTIONS).permitAll()
    .antMatchers("/ifrs/api/v1/user/token").permitAll()

thanks


text:
Q: Injectivity and surjectivity on algebraic group Denote by $\mathbb{F}_q$ the finite field with $q$ elements, and denote by $\bar{\mathbb{F}}_q$ its algebraic closure. Let $G$ be an algebraic group defined over $\bar{\mathbb{F}}_q$, and let $F$ be a Frobenius morphism which defines a $\mathbb{F}_q$-structure on $G$.
Suppose that $T$ is a $F$-stable maximal torus of $G$. It is known that the character $X(T)$ of $T$ is isomorphic to $\mathbb{Z}^n$ where $n$ is the rank of $T$. Thus the dual map $F^*$ acts linearly on $\mathbb{Z}^n$.
I have a question on a proof for the following statement.
$|T^F|=\mathrm{det}(F^*-1)$, where $|T^F|$ is the cardinality of $T^F$.
Proof: Consider the exact sequence $1\rightarrow T^F\xrightarrow{i} T\xrightarrow{F-1}T\rightarrow1$, and then $1\rightarrow X(T)\xrightarrow{F^*-1}X(T)\xrightarrow{p}\mathrm{Hom}(T^F,G_m)$. Because $|\mathrm{coker}(F^*-1)|=|\mathrm{det}(F^*-1)|$, it remains to show that $p$ is surjective.
The question is the following. In the note, it is shown that because $\mathrm{Hom}(\mathrm{Hom}(T^F,G_m),G_m)=T^F\rightarrow T=\mathrm{Hom}(X(T),G_m)$ is injective, the conclusion follows.
QUESTION: Does $G_m$ have any property in group category like injective module in module category? Or how can one obtain that $A\rightarrow B$ is surjective through the fact that $\mathrm{Hom}(B,G_m)\rightarrow\mathrm{Hom}(A,G_m)$ is injective?


text:
Q: unable to spawn ssh using TCL expect in ActiveTCL I am trying to ssh through .tcl script from ActiveState TCL 'tclsh' window.
Having WINDOWS OS system.
#!/bin/sh
# \
exec tclsh "$0" ${1+"$@"}
package require Expect

set user [lindex $argv 0]
set password [lindex $argv 1]
set DeviceIpAddr [lindex $argv 2]
set DeviceHostName [lindex $argv 3]

foreach DeviceIp $DeviceIpAddr HostName $DeviceHostName {

    spawn ssh $DeviceIp
     expect "login as:"

    send "$user\r"
    expect "Password:"

    send "$password\r"
    expect "$HostName ~]#"
}

I see below error while execute in tclsh(ActiveTCL)
% tclsh Test.tcl root 321 17.250.217.151 lb02va
The system cannot find the file specified.
    while executing
"spawn ssh  root@$DeviceIp"
    ("foreach" body line 3)
    invoked from within
"foreach DeviceIp $DeviceIpAddr HostName $DeviceHostName {

        spawn ssh  root@$DeviceIp
        expect "login as:"

        send "$user\r"
        expect "Password:"

        send..."
    (file "Test.tcl" line 12)
child process exited abnormally

Kindly assist me resolving this.
Thank you.

A: First, make sure that you have ssh installed. From the bash prompt (Mac, Linux, Cygwin) or cmd prompt (Windows), type:
ssh

If you see an error, try to fix it. The most likely cause is ssh not installed, or not in the path.
Next, in your script, you did not use the $user variable, instead you use the hard-coded root. Fix that:
spawn ssh $user@$DeviceIp

The final problem: you already specified the user name from the command line, the ssh program will not ask for user again, so you must delete these two lines:
expect "login as:"
send "$user\r"

After that, hopefully everything will go as planned.


text:
Q: How do I put a php file inside a div class?
Hi good day! I don't really know how to post here since its my first time here. Please don't hesitate to teach me the basics. Anyways here is my code.

body{
    margin: 0;
    padding: 0;
    background: url(bg.jpg) no-repeat;
    background-size: cover;
  }
  .box{
    width: 450px;
    background: rgba(0, 0, 0, 0.4);
    padding: 40px;
    text-align: center;
    margin: auto;
    margin-top: 5%;
    color: white;
    font-family: 'Century Gothic',sans-serif;
  }
  .box-img{
    border-radius: 50%;
    width: 200px;
    height: 200px;
  }
  .box h1{
    font-size: 40px;
    letter-spacing: 4px;
    font-weight: 100;
  }
  .box h5{
    font-size: 20px;
    letter-spacing: 3px;
    font-weight: 100;
  }
  .box p{
    text-align: justify;
  }
  ul{
    margin: 0;
    padding: 0;
  }
  .box li{
    display: inline-block;
    margin: 6px;
    list-style: none;
  }
  .box li a{
    color: white;
    text-decoration: none;
    font-size: 60px;
    transition: all ease-in-out 250ms;
  }
  .box li a:hover{
    color: #b9b9b9;
  }
<!DOCTYPE html>

    <meta charset="utf-8">

    <link rel="stylesheet" href="style.css">
    <title>Personal WebSite</title>

DarkCode

Web Devloper - Web Designer

    <?php include("menu.php"); ?>

This is the php file that I want to include in the box (menu.php)

  <?php

class Fruit{
    public $name;
    public $color;

    function __construct($name, $color){
        $this->name = $name;
        $this->color = $color;
    }
    function get_name(){
        return $this->name;
    }
    function __destruct(){

        echo  "
The fruit is {$this->name} and the color is {$this->color}.
";
    }
}

$apple = new Fruit("Apple", "red");
//echo $apple->get_name();
?>

Running this code will display the echo statement outside of the box. How do I put that statement inside the div class?
This is the screenshot of the results of my code

A: Your current method should display the statement inside

.
But if the contents are out of the box it may be due to some problem in your CSS.
Could your share your CSS code and maybe a screenshot of how your content appears.
================== After Edit ======================
The first fix I made was: I used <?php include "./menu.php"; ?> instead of <?php include("menu.php"); ?>
The second is when you echo it gets Correctly displayed within the div.
The __destruct() function, is automatically called at the end of the script, and the contents of that are only displayed out of the box. uncommented echo $apple->get_name();

Wrapping up, __destruct() is used for recovering the heap space allocated during the lifetime of an object, closing file or database connections, and releasing network resources.
If you really want to display the H1 I made this change.
<?php

    $des="";

    class Fruit
    {
        public $name;
        public $color;

        function __construct($name, $color)
        {
            $this->name = $name;
            $this->color = $color;
        }
        function get_name()
        {
            return $this->name;
        }
        function __destruct()
        {

            global $des;
            $des = "
The fruit is {$this->name} and the color is {$this->color}.
";

        }
    }

    $apple = new Fruit("Apple", "red");
    echo $apple->get_name();
    unset($apple);
    echo $des;
?>

Helpful links:
PHP unset

A: You shuld try following source code

DarkCode

Web Devloper - Web Designer

<?php include("menu.php"); ?>

<?php echo $apple->get_name();?>

And, you can add <?php echo $apple->get_name();?> somewhere else also.
Just add
<?php echo $apple->get_name();?>
 You can add whereever you want to add it. <?php echo $apple->get_name();?>


text:
Q: How I get to know that i back from other app in swift Actually i am opening other app from my app and than after when i come back to my app using top left button.
So here i want to know is there any way to identify that i came back from other app so i will put condition on it.
After back to my app there is two method of appDelegate is called.
func applicationWillEnterForeground(_ application: UIApplication)

func applicationDidBecomeActive(_ application: UIApplication)

But I want any particular condition to put here to get to know about it.
As many down vote this question. I want to add as when i back from other app my app goes black.
So for this reason i want to check it and if it's from other app i will assign view again to controller.
Thank you in advance.
func applicationDidBecomeActive(_ application: UIApplication) {
    if someCondition {
        print("Coming back from another application")
    } else {
        print("Coming back from app switcher/home")
    }
}

A: Just adding the comment as answer:
Declare a global bool variable, something like var openingAnotherApp = false
Now when you open another app, before opening it, make your openingAnotherApp = true .
Now in your AppDelegate, you can check if openingAnotherApp is true or false. And then again change it value back to false after your condition check completes.


text:
Q: select inside dollar signs in latex using vscode How to select everything inside $math_formula_here$ in vscode when writing latex?
I have tried shift+alt+rightarrow but it does not work.

A: you can use the extension Select By
Add the following key binding
  {
    "key": "shift+alt+right",  // or any other key combo
    "when": "editorTextFocus",
    "command": "selectby.regex",
    "when": "editorLangId == latex"
    "args": {
      "backward": "$",
      "forward": "$",
      "forwardInclude": false,
      "backwardInclude": false
    }
  }


text:
Q: How to highlight a button without holding it in? I currently have a button in my side menu linked to my swift file so that it loads up a certain URL when clicked, and although it goes to said site when I tap the button, the title of the button won't highlight if I tap it, it only highlights to gray if I hold in the button for a second or two. How do I get it to react to my touch instantly?

My reputation isn't high enough to post more than two links.
Also, heres how I link it in the swift file:
@IBAction func openCurrentUpcomingRaffles(_ sender: Any) {

    let url = URL(string: "https://studiobash.herokuapp.com/dayofevent")
    webView.loadRequest(URLRequest(url: url!))
}

A: have you tried changing the button type to Custom?

A: To do this I ended up just adding regular views behind each button and whenever the action was taken of clicking on the button, I programmatically changed the background color of the normal view to a light grey so you could tell which menu item you were currently viewing:
yourView.backgroundColor = UIColor.lightGray


text:
Q: How do make my e-mail display an image from the web? I often use inline images in my e-mails, but this often results in very large e-mail sizes that can quickly fill up hard drive space for my recipients.
If I host the image online, I can link to it without including the image data in the e-mail, but then recipients have to click on the link to see the image.
Is there a way to embed an inline image such that the image data is fetched from the internet when my recipient opens the e-mail?

A: You can use HTML in your emails and embed an image with the <img> tag. From Outlook, navigate to Tools -> Options. In the "Mail format" tab, Make sure "Compose this message in:" is set to HTML.
example:
<img src="http://cdn.sstatic.net/superuser/Img/wmd-buttons.png">

results in:

A:
I often use inline images in my
  e-mails, but this often results in
  very large e-mail sizes that can
  quickly fill up hard drive space for
  my recipients.

What kind of images are we talking about? Diagrams? Proofs? And do they really need to be in the e-mail or will they work just fine as a .zip attachment?
I ask only because I've found that 9 times out of 10 the images people want to add don't really need to be inline... its just nice if they are. Its a broad generalization, but working as a programmer in the Education department of a rather large health system does show you a good cross-section of users.

If I host the image online, I can link
  to it without including the image data
  in the e-mail, but then recipients
  have to click on the link to see the
  image.
Is there a way to embed an inline
  image such that the image data is
  fetched from the internet when my
  recipient opens the e-mail?

You can use an HTML formatted e-mail (all modern clients support it in one way or another) to use a standard HTML image tag to embed the image you have hosted on the web in your e-mail. Directions for this vary from client to client (and to some extent from Outlook version to Outlook version - check out http://office.microsoft.com for directions for your version of Outlook)
Keep in mind that most e-mail clients (Outlook, Thunderbird, GMail, etc.) will initially block the image to protect the users from spammers using the image request to determine if they have a "live" address. If someone doesn't know what's going on they may never know what they are missing. This is a client setting and there is nothing you can do other than include some text explaining what is going on if they don't see an image.
Normally/usually/generally if they add you to a "trusted senders" list (or something to that effect) future images won't be blocked. Useful if this is more than a one-time thing.


text:
Q: Use NFS on ubuntu that has 2 NICs. Client cannot mount the directory I have been suffering from this issue for a while now. I have a computer (Say, A) running ubuntu and has 2 NIcs. One NIC is connected to the home network and the other is connected to the isolated private network. There is another computer (B) in the private network created by A. They are both linux. A has a NFS folder and I would like to mount it on B but it doesn't let me and the server complains that the permission denied. The firewalls are both turned off and I edited fstab and exports. Interestingly when B is on the home network B can mount the NFS directory with no problem. This behaviour concludes that the problem seems to reside on the NFS server settings. Because the NFS server has 2 NICs it seems to like to use the NIC that is connected to the home network rather than the private network. How can I switch from the home network to the private network ?
Thank you for your time.

A: what is in your /etc/exports file? You should allow mount from private network ant mount with the name ( or IP ) of the private interface of A. Let say your computer a has two IP addresses
home: 192.168.1.1/24
  private: 10.0.0.1/24
and B has
  10.0.0.2/24
Then /etc/exports should looks like:
/home 10.0.0.2(rw,...)
and on B you should mount as:
mount 10.0.0.1:/home /mnt


text:
Q: Как удалить файлы с определенным именем в нескольких папках? Python Есть архив состоит из папок, названых датами.
Необходимо пробежаться по каждой папке архива и удалить определенные файлы формата xlsm.
Понял только как удалить определенный файл, а как несколько нет(
import os

path = "C:/Archive/01-10-2021"
a = 'AL010.xlsm'        # Нужно удалить AL010, M_4613,SG010, и др. при том, что существуют другие файлы начинающиеся с AL*,M_*,SG*
for i in os.listdir(path):
    if a in i:
        full_file_path = os.path.join(path, a)
        os.remove(full_file_path)

A: Я бы сделал через glob (позволит задать шаблон), используя pathlib.
Пример:
from pathlib import Path

path = Path('C:/Archive/01-10-2021')
for file_name in path.glob('AL*.xlsm'):
    file_name.unlink()

Если поиск нужно сделать в папках с неопределенной вложенностью, то вместо glob использовать rglob, тогда поиск файла будет от текущей папки в path и в вложенных папках


text:
Q: why plotting a normalized autocorrelation gives positives and negatives values? I used the following code to compute and plot autocorrelation function ACF for an array as follows:
an_array = [1, 2, 3, 4, 5]
autocorrelation = np.correlate(an_array, an_array, mode="full")
ACF= autocorrelation[autocorrelation.size//2:]
print(ACF)

Output
[55 40 26 14  5]
Then, I calculated the normalized ACF as follows:
Normalized_ACF = (ACF- ACF.min(axis=0)) / (ACF.max(axis=0) - ACF.min(axis=0))
print(Normalized_ACF)

Output
[1.   0.7  0.42 0.18 0.]
This output is correct.
However, when I used another method using "plot.acf" built-in function in python to compute and plot the normalized ACF of the array, it gives me other values (positive and negatives) as follows.
from statsmodels.graphics import tsaplots
# Display the autocorrelation plot of your time series
fig = tsaplots.plot_acf(an_array, lags=3)
plt.show()

Output of the 2nd method:

Can anyone interprets why the two methods give different outputs?


text:
Q: boost:multiprecision I have just started using boost::multiprecision trying to speed up some calculations previously done in Matlab. I found quite an unexpected problem, though. My calculations involve complex numbers, so I am using cpp_complex_50 type (e.g. cpp_complex_50 A, B;)
At some point I need to use boost::math::tools::bracket_and_solve_root() function, which requires that the function it works on returns real values. Here comes my problem... I cannot convert my complex multiprecision variable A.real() to any type that is real, eg. to cpp_dec_float_50 type or even double. The task should be streightforward, but I am virtually drowned in error complaints from my compiler (MSVC2015), and cannot solve it. Any hints at how to convert the data are more than welcome.
A somewhat connected question is the problem of initialization of cpp_complex_50 type variables with real values. At the moment I can only use data of type double at initialization, which means I am loosing some accuracy at the initialization stage already, e.g.:
cpp_complex_50 A = 4.0 * boost::math::constants::pi<double>(); // it works

but
cpp_complex_50 A = 4.0 * boost::math::constants::pi<cpp_dec_float_50>(); // It does NOT work

Any hints are needed. I am stuck at this, despite nice initial results.
Regards
Pawel

A: cpp_complex uses cpp_bin_float.
Live On Compiler Explorer
#include <boost/multiprecision/cpp_complex.hpp>
#include <iostream>

namespace bmp = boost::multiprecision;

int main() {
    using Complex = bmp::cpp_complex_100;
    using Real    = Complex::value_type;

    Real r = 4.0 * boost::math::constants::pi<Real>();

    Complex b(r, {});
    // or
    b = r.convert_to<Complex>();

    std::cout << b.str(100) << std::endl;
}

Prints

12.56637061435917295385057353311801153678867759750042328389977836923126562514483599451213930136846827

A: Following valuable comment from sehe... the code
cpp_complex_50 A = 4.0 * boost::math::constants::pi<cpp_bin_float_50>();
cout << A << endl;

works, producing:
12.5663706143591729538505735331180115367886775975

Similarely,
cpp_bin_float_50 B = A.real();
cout << B << endl;

works as well, printing the same.