C# CLR Excecption "BadImageFormatException: Could not load file or assembly"

Question: I am using VS 2019 Version 16.8.2

I referred a "CLR Class Library(.NET Core)" project in my "WPF App (.NET)" project and i met a exception:
BadImageFormatException: Could not load file or assembly 'LibCLR, Version=1.0.7646.21580, Culture=neutral, PublicKeyToken=null'. An attempt was made to load a program with an incorrect format.

Let me first talk about how I did it.

Create a "WPF App (.NET)" project "TestCLR"

Add a new "CLR Class Library(.NET Core)" project "LibCLR" in this solution

The "common language runtime support" setting of "LibCLR"

Target "TestCLR" to ".NET 5.0"

"LibCLR.h" created automatically in project "LibCLR" and codes was inside

#pragma once

using namespace System;

namespace LibCLR {
    public ref class Class1
    {
        // TODO: Add your methods for this class here.
    };
}

Add "new LibCLR.Class1();" in MainWindow.xaml.cs in project "TestCLR"

using System.Windows;

namespace TestCLR {
    ///
    /// Interaction logic for MainWindow.xaml
    ///
    public partial class MainWindow : Window {
        public MainWindow() {
            InitializeComponent();
            new LibCLR.Class1();
        }
    }
}

Rebuild All and debug, then i met exception

Then i change the solution platform to x64 or x84, the exception were the same.

It works well if i choice "WPF App (.NET Framework)" for "TestCLR" in step 1 and "CLR Class Library(.NET Framework)" for "LibCLR" in step 2

Why did not it work?
Can not i use a "CLR Class Library(.NET)" project as a project reference in a "WPF App (.NET Core)" project?
How can i solve this problem?
Comment: From screenshot: "Platform: [Active(Win32)]".  That builds the x86 (aka 32-bit) version of the DLL.  It cannot be used in a .NETCore project that runs in 64-bit mode.  Build the x64 version instead.
Comment: You can't load a .NET 5 class library into a .NET framework application, is that what you're trying to do?
Comment: Hi, i tried both x86 and x64, but none works.
Comment: But i targeted both with ".NET 5.0", is it wrong?
Comment: Can you please share the .csproj files?
Answer: You should change Platform target to "X86" here
Answer: The most common answer is changing between x86 and x64 targets.  In a comment to your original question, here, you mentioned that you tried that and it didn't work for you.  So, I have a suggestion.  You are building a WPF project, and targeting dotnet 5.0. Dotnet 5.0 is OS-agnostic.  WPF is OS-specific.  It needs Windows.
Try using an OS-specific Target Framework Moniker. Open the .csproj file of both projects.  Try setting both projects to <TargetFramework>net5.0-windows</TargetFramework>
Clean solution, rebuild, and test.
We've got a solution here that is dependent on Windows.  We shouldn't have to, but let's try explicitly targeting it. Especially that C++ project.
More reading

NET 5: Merging .NET Core and .NET Standard with New Target Framework Monikers (TFMs)
New templates Targeting .NET 5.0
Cannot compile WPF applications targeting .NET 5


Elysia cron and feeds being stuck - how to resume the imports?

Question: I have a bunch of Feeds imports, programmed automatically with Elysia Cron.
There is a problem with the size of the content to be loaded, as the import uses to hang, and always at about the same approx. point in a definite feed. The feed, imported manually, throws no errors and do all its stuff perfectly, only fails in automated cron, getting stuck.
After I unblock the Feed with this
<code> update feeds_source set state = 'b:0;';
 update feeds_source set fetcher_result='b:0;';
</code>
And reset the Elysia table with this
<code> UPDATE elysia_cron SET running = 0 WHERE name = :name_of_process
</code>
sometimes the Elysia Cron starts again, but, to my dismay, no Feed process is launched even if Elysia Cron says otherwise. There is a Running indication, but no feed importation is done, and the progress indicator in the Feed itself indicates that it is not working.
What can I do, someone has the same problems? I have read tons of documentation, but I find no solution, I see terrible stories on the net about updating processes enduring for weeks, shouldn't just 4.000 products (nodes, taxonomies) load in just 5 minutes?
Answer: I have discovered that the following lines had been wiped out from the code somehow in my module:
<code> while (FEEDS_BATCH_COMPLETE != $source->import()){
// nothing
 } // while
</code>
This piece of code keeps de feeds working after it finishes. When the resetting is done via phpMyAdmin, the cron itself (called every minute) launches again the tasks. The Elysia task when being called, but the callback did not do anything as the feed had started and the code lacked the while() construction


VAR MODEL: Error in solve.default(Sigma) : system is computationally singular: reciprocal condition number

Question: I am using R vars package to implement VAR model in a multivariate time series model. I tried to run:
VAR(foo_ts, p = 6)
but I was getting this error message:
Error in solve.default(Sigma) :
  system is computationally singular: reciprocal condition number = 0
foo_ts is a time series data.
I have tried to adapt examples in stackexchange  and stackoverflow but have not been successful in running the VAR model. I have successfully run the VAR model on other datasets but not on foo_ts. Any help will be appreciated.
Comment: Have you tried looking up the error message online?
Comment: Yes. I have looked at the message online. The answer I saw is that "It means your design matrix is not invertible". But then, I do not have clue on how to adapt the solution when using R vars package.
Comment: No package will help you if the problem lies in the data. You need to reconsider the variables you have; some of them form a linear combination equal to a constant. To solve the problem, you could get rid of the variable(s) causing that.
Comment: @RichardHardy, my guess would be severe overfitting rather than multicollinearity here.
Comment: @ChristophHanck, yes, that must be the case. I did not inspect the data and forgot to consider this possibility.
Answer: Your time series is too short to fit that many parameters. Recall that, in a VAR(p) model
\begin{equation*}
x_t = d + A_1 x_{t-1} + A_2 x_{t-2} + \dots + A_p x_{t-p} + \epsilon_t,
\end{equation*}
each parameter matrix $A_i$ will have dimension $k\times k$, where $k$ is the number of parameters. Estimation simply procedes by OLS to each equation of the VAR model. That means you will have $1+k\times p$ parameters per equation (assuming $d$ for the deterministic component is just a constant). In your case, $p=6$ and there are $k=8$ variables (although two of these appear to be identically zero and hence not very useful).
Hence, you fit 49 coefficients for each equation, but only appear to have $n=21$ observations. As is well-known, the $X'X$ matrix of the OLS estimator will not be invertible when $n$ is smaller than the number of regressors.
Comment: I am getting a similar error message after running `(VAR_reduced <- VAR(VAR_data_1, p = 1, type = "both"))
summary(VAR_reduced)` but with a condition number just above zero. I am only using 3 variables but have 135 observations, so I should not be overfitting. Any idea what may cause that? Maybe I should add that I only get the error message after `summary`
Comment: Can you post a reproducible example, perhaps as a new question?
Comment: I have but on stack overflow I assumed it would fit better there, https://stackoverflow.com/questions/63077895/r-irfs-in-a-svar-model-cant-display-specified-model


Objective-C how to check if a string is null

Question: SO
I wish to check to see if the item in my array [clientDataArray objectForKey:@"ClientCompany"] is nil.
    temp = [clientDataArray objectForKey:@"ClientCompany"];
    if (temp != [NSNull null]) infofieldCompany.text = temp;

So far I have been able to achieve this through the above code, but it does give me the warnings

warning: NSArray may not respond to -objectForKey:
warning: comparison of distinct
Objective-C types struct NSNull *
and struct NSString * lacks a cast

My main interest is the second warning, but the first warning also interest me.
How should I adapt my above code?
Comment: The clientDataArray was actually an NSDictionary, but was declared as array, thus the warning.
Answer: Your first warning looks like you're trying to call objectForKey on an NSArray. Which isn't going to work, as NSArray doesn't have an objectForKey method.
As for the second warning you can just compare directly with nil, ie:
if (temp != nil)

or since nil is equivalent to 0, you can also just do:
if (temp)

Comment: yeah, I should have done that. Nice and simple too.
The first line i posted does indeed work fine, but I will have a rethink of it.
Comment: Please notice that this won't if temp is an NSString. Use Robinsons' answer
Answer: After trying all the options, i think this is the best option to comapre NSString null
if ( temp != ( NSString *) [ NSNull null ] )
{
  // do some thing
}

Comment: What advantages does this have over `temp != nil`?
Answer: Both of the answers previously given missed a fundamental point: you can't put nil into an array, so you'll never get nil out of an array. Using NSNull as a placeholder in an array is the correct thing to do, however your variable temp then cannot be declared as an NSString *, as it might not be one. Use either NSObject * or id as the type of the variable to suppress the comparison warning.
Comment: or do [string isEqual:[NSNull null]]
Answer: The best solution to test NULL or Empty values:
if (yourObj.yourString == (NSString*) [NSNull null] || yourObj.yourString.length == 0 )
{
   yourObj.yourString = @"";
}

Answer: Quiet simple
if (myString == nil){
     NSLog(@"myString is null");
}

Answer: I think the problem is (I mean the second warning) is that you're comparing NSString object, which could be set to null to an NSNull object.
Have you tried the usual C way of checking for null?
if(temp) {
// It's not null, do something.
}

I'm not 100% sure about this one, but you could try it. If you did, sorry that couldn't provide more useful information.
Good luck!
Answer: The NSNull singleton can be used to build "interleaved" arrays like obj0, obj1, obj2, NSNull, obj3, NSNull, ..., nil.

warning: 'NSArray' may not respond
  to'-objectForKey:'

NSArray does not implement objectForKey.
Your code will crash at runtime (if clientDataArray has been allocated and initialized)
You can access array elements by index (objectAtIndex:).
If you need to associate objects with keys, take a look at NSDictionary.
Answer:
if (temp != nil)
or since nil is equivalent to 0, you can also just do:
if (temp)

I am not by any stretch of the imagination a Obj-C or Cocoa expert, in C/C++ you can use something like:
if(somePtr != NULL)
And, unless you explicitly, set it to NULL or changed what it was pointing to,
you can be certain, that it is, in fact, Not Null or Null (what-ever you were looking for...)
But I have noticed (my personal experience anyway) that in Obj-C,
If you do something like:
if(someObj != nil) or the converse,
There's no Guarantee, it will tell you it's REAL status...
So (after dealing with a bunch of crashes) when I deal with Obj-C (BS), to be safe, I always have a BOOL or flag set up to track it's status, so you don't end up Free-ing, excuse me... "Release-ing" something that has already be deallocated...
Answer: Even though this question is old, I hope My Answer will help some one else.
You can try this
temp = [clientDataArray objectForKey:@"ClientCompany"];
if (![temp isKindOfClass:[NSNull class]]) infofieldCompany.text = temp;


Posterior density of nonlinear random effects

Question: Consider the nonlinear mixed effects model for the $j$th observation $y_{ij}$,  $j=1,\dots,n_i$, $i=1,\dots,N$, of individual $i$ at time $t_{ij}$ :
$$
y_{ij} = f(\alpha_i, t_{ij}) + g(\alpha_i, t_{ij}) \varepsilon_{ij}.
$$
Here $\alpha_i$ is the random effect, $\alpha_i \sim \mathcal{N}(\mu,\Sigma)$ and $\varepsilon_{ij} \sim \mathcal{N}(0,\sigma^2)$. The parameters of this model are $\theta = (\mu, \Sigma, \sigma^2)$.
My question: how can one estimate (realy, I mean estimate) the conditional distribution $p(\alpha_i| y_i; \theta)$ with $y_i = (y_{i1}, \dots, y_{in_i})$?
Thanks
Comment: So $\theta=\Sigma$ ? Or are there other parmaters ? And you consider a Bayesian approach ?
Comment: Sorry about that two mistakes now corrected in my post: $\theta = (\mu, \sigma, \Sigma)$.
Comment: I would actually consider any approach, Bayesian could indeed be one of them.
Comment: For the Bayesian framework I think its easier to do if you use conditional distributions rather than equations.  You've done this for the random effects, but not for the linking model.  Also you've used $\sigma$ twice - probably better to write $g(\alpha_i,t_{ij})$ instead or use a different parameter for the error variance.
Comment: Is $\alpha$ a vector or a scalar?
Comment: I don't understand the other comment regarding "conditional equations"...I don't know what that is.
Comment: I would write your model as $(y_{ij}|\alpha_i\sigma)\sim N(f_{ij},g_{ij}^2\sigma^2)$
Comment: This model is classical and as far as I know, te equation writing is preferred - even in Bayesian approaches. I believe changing this could be confusing...but I might be wrong.
Comment: Sorry: $\alpha_i$ is a vector (its variance is a matrix, $\Sigma$).
Answer: This conditional distribution does not have a closed-form expression because your function $f$ is non-linear in $\alpha_i$. Estimating the whole conditional distribution itself may seem difficult, but you may estimate $$\mathbb{E} (\alpha_ i|y_i ; \theta)\qquad (*)$$ for example. As far as I know, this may be done by considering one of these solutions:

Approximate your model: Take a first order taylor expansion of your model function $f$ and use linear mixed model tools to estimate the best linear unbiased predictor (see for instance pinheiro and bates, 2000, chap 7.)
Consider numerical MCMC integration in a Bayesian frame of work, and using the Gaussian $p(\alpha_i; \hat\theta)$ as an informative prior, with $\hat\theta$ an estimate obtained on your sample. Here, you do not have to approximate your model but you will have to deal with potential problems related to MCMC procedures (choice of an algorithm, convergence, mixing...)

These are the 2 traditional approaches to estimate (*) and are implemented in most recent the recent libraries for nonlinear mixed models. However, there may be other ways, especially if you really want to estimate the whole distribution.
Comment: I would clarify point 1 by saying that rather than approximating the model, you are approximating the posterior distribution of the parameter.  You will get a different "approximate model" for different parameters.
Comment: Thank you for your replies. I want to avoid method 1 because of the first order approximation. I also want to get closer to the full distribution, I need more than just the expectation.


Calling function inside of function

Question: When I code stuff, I try to divide all things in functions (methods, if you like). Function X does stuff X, Y does tuff Y and not like method X does stuff X, Y & Z! This gives me more re-usable code. I like that. :)
Lets take a look on this code:
var user = {
  users: [],
  userCount: 0,
  addUser: function(user) {
    (this.users).push(user);
  },
  incrementCount: function() {
    ++this.userCount;
  }
}

var user = { // 2nd example.
  users: [],
  userCount: 0,
  addUser: function(user) {
    (this.users).push(user);
    ++this.userCount;
  }
}

(It's in JavaScript, but language here is non-essential.)
In my opinion, second example will be easier and safer to use for, lets say, API user.
It's easy to forget to call user.incrementCount(). What do you think? Second example does it automatically.
So how to find a balance? Any best-practices about calling functions inside of functions?
Thanks for reading this.
Edit:
This came in my mind just now:
var user = {
  users: [],
  userCount: 0,
  addUser: function(user) {
    (this.users).push(user);
    this.incrementCount();
  },
  incrementCount: function() {
    ++this.userCount;
  }
}

Answer: It's a little different in JS, since there isn't a way to make functions truly private when using object literal notation, but...
It's all about the API you want your objects to expose to their consumers. Do you want consumers of your API to be able to increment the count separately from adding a user? If so:
{ addUser: /* snip */, incrementCount: /* snip */ }

Otherwise:
{ addUser: /* snip */, _incrementCount: /* snip */ }
// or just
{ addUser: /* snip */ }

In this particular case, I would strongly recommend against storing any separate count at all, since the users array already does that for you.
var user = {
  _users: [],
  addUser: function(user) {
      this._users.push(user);
  },
  getUserCount: function () {
      return this._users.length;
  }
  // and if you need to expose the users array directly,
  , getUsers: function () {
      return this._users;
  }
}

Comment: All API and `user` was just an example.
Comment: Yes, and I'm answering based on that example.
Answer: Personally, I don't think you should even expose that stuff through an API. Also, it would be easier and (at least in JavaScript) more intuitive, to just use users.length.
Ultimately, I think keeping your interface really simple is generally a good thing. Abstraction is a good thing. If I were using someone else's library, I'd be pretty disappointed to learn that I was expected to manually increment that value.
Update:
One more thing I think is worth mentioning:
By having your code maintain state internally and keeping the API simple, you not only make the user's life easier, but you also protect against misuse (to the extent that it's possible). It's easy to imagine a scenario where someone uses that increment method incorrectly, and as a result, it's going to break stuff.
Comment: Based on the OP's particular example: my sentiments exactly.
Answer: You are right in saying "Function A does A-Stuff."
BUT: a function that works on data, that is hidden (more or less) from the outside, should do stuff you want with the data (for Example add a User) and makes shure, that the data still is correct (for example if you have a list of users, increment the Usercounter to make make shure it is always correct).
If you leave want the user of your API do this stuff for you, it is not comfortable anyways.
Imagine, you add more functionality to your list of users (for example, tell the user that it has been added to the list, store the Users in a binary tree and so on), and you have to do all the organisation stuff from the outside of your function, where are the benefits of that??
Answer: I know you've just intended the sample code to be a simple example, but with something like a count or length variable I can't think of a reason why I'd ever want to let that be set independent of the function(s) that add or remove items. When using the object you don't want to have to call an add() and an increment() method every time you add, and you really don't want to be able to do one without the other or your object ends up in an invalid state.
So I'd never do it the first way, and surely the way you added in your edit is even worse. There's nothing wrong with having your functions call each other, but again in your example I'd want the increment function to be private.
Better to make the count variable private and only allow it to be retrieved via a function and set via add/remove functions (though you don't even need a count variable when you can just return users.length). The following pattern with an immediately executed anonymous function lets you have private variables and functions, and you only return an object containing public functions. The public functions can still access the private variables/functions, but the private stuff can't be accessed from outside.
var user = (function() {
   var users = [],    // private variables
       private1,
       private2;

   function privateFunction1() { /* do something */ }

   return {
      getUserCount : function() {
                       return users.length;
                     },
      addUser:       function(user) {
                       users.push(user);
                       // return index of new user
                       return users.length - 1;
                     },
      getUser :      function(userIndex) {
                       return users[userIndex];
                     },
      someFunc :     function(someParam) {
                       return someParam + privateFunction1();
                     }
   }
})();

user.addUser("Fred");
user.addUser("Mary");
console.log(user.getUserCount()); // 2
console.log(user.getUser(1));     // Mary

Calling function inside of function


How do I use Jenkins s3 publish plugin to the same location for every build?

Question: I am using Jenkins to build my application, which I then need to publish to s3. One of the outputs is an installation exe file that I then provide as a link to users of the application. Because of this I need this installer file to always be in the same place, for every build. However, no matter how I set up my S3 Publishing post-build step the the artifacts are uploaded to a separate folder for every build, like so

Is there a way for me to set up the publish to the root of the directory/bucket every time, overwriting the old file if neccesary?  This would eliminate the jobs/TestTrayApp/{buildnumber} directories. This is my s3 publish post-build step setup:
Comment: @fuzzi Unchecking "Manage artifacts" will publish to the root of the folder you specify, every build.
Comment: I'm currently experiencing the same issue. Did you find a solution to this?
Answer: I'm not sure I fully understand what exactly what you want, but based on what I could gather up,you have an .exe file which needs to be in a particular location before publishing to s3 ?
Why not add a another post build action before your actual post build(publishing to s3) copy .exe to the destination location and then initiate publish build.
wont that be easier :)
Comment: I think that the issue is that the Destination bucket is set to "/blahblahblah", however s3 publish creates a new folder structure of blahblahblah/jobs/Test/{buildnumber}, so the files are added in these directories, rather than just in the root folder blahblahblah.
Comment: You have checked the manager artifact, so it should take the same structure as per your project build ... Can you confirm whether or not your build isn't actually creating the structure that you described. Also can you check Jenkins logs and see that it actually says that it's copying to so and so location. If it does have you tried deleting that location from s3 and try building again... This time did it actually create the folder structure from Jenkins (check the logs)
Comment: The "source" option contains only the file to be pushed to S3.  Creating a new S3 bucket from the build, adds the file with the "jobs/{job-name{/{build-number}" structure, rather than adding to the root.  The output from Jenkins is : " Publish artifacts to S3 Bucket bucket={bucket-name} "
Comment: As per what you have mentioned Jenkins is doing it's job, it's taking the file and pushing it to s3. Internally I'm not sure for s3, but it will use a scp command (transfer files across servers/system). Can you attach the log file screenshot (located from Jenkins downloaded directory ) or you'll get the log from manage Jenkins logs
Answer: You simply need another build step that copies the published .exe artifact to the permanent location for users to download.
I think you are confusing "publishing an app to your production environment" and publishing build artifacts. I believe the intent of this Jenkins S3 publish plugin is not to be used for your final release production version but as a build step to archive build artifacts, archive might have the same meaning as publishing in this context regarding your build artifacts. See this article for why I am thinking the Jenkins S3 publish plugin is not meant to be used to actually publish the final release version of your application.
Use a Jenkins Pipeline or add another build step to your Freestyle to copy the exe from S3 build artifact archive to your final permanent storage container for users to download from your website/app.
Answer: Unselect both Manage artifacts and Flatten directories checkboxes. And as per the Source give the directory name followed by a / which contains your executable. For example:

This way your latest executable will always be placed in bucket/blahblahblah/executable/executable.exe location no matter how many times your job runs.
Comment: What if we want to publish under ' bucket/blahblahblah/executable.exe ' . I am stuck in this case


Is it important to practice ear training with different instruments/sounds?

Question: In ear-training, specifically interval/chord recognition, is it important to mix up the intruments/sounds we use ?
Will it somewhat hinder my learning if most of my ear-training is done through, say, samples of piano ? Or will these skills carry just fine to other sounds ?
Answer: It certainly won't do any harm to mix and match different sounds. Each instrument has different overtones/harmonics which is one reason why they sound different from each other, and sometimes this will fool you into identifying the interval wrongly.
Piano is a favourite, for several reasons - availability, ease of recording, clear sounding notes, etc. Avoid bells and some organ sounds, as these do have many harmonics which will put you off the scent, so to speak. Guitars and violins are good, as both notes can be played simultaneously. Quite difficult with trumpets, saxes and such like, which usually play notes in sequence!
Comment: Interesting ! Personally, the main reason why I ask is because I use online ear training tools and apps, and some don't offer that feature to change the intrument/sound that is playing the interval/chord.


Check RAID software: my status

Question: I have an Ubuntu dedicated server and I got a message from my provider saying that one of my disks has en error and that I must "check whether my RAID software is functioning properly" before they replace the disk. Here is what I typed in shell and the report I got:
root@Ubuntu-1204-precise-64-minimal # cat /proc/mdstat
Personalities : [linear] [multipath] [raid0] [raid1] [raid6] [raid5] [raid4] [raid10]
md3 : active raid1 sda4[0] sdb4[1]
      1839089920 blocks super 1.2 [2/2] [UU]

md1 : active raid1 sda2[0] sdb2[1]
      523968 blocks super 1.2 [2/2] [UU]

md2 : active raid1 sda3[0] sdb3[1]
      1073610560 blocks super 1.2 [2/2] [UU]

md0 : active raid1 sdb1[1] sda1[0]
      16768896 blocks super 1.2 [2/2] [UU]

unused devices: <none>

root@Ubuntu-1204-precise-64-minimal # mdadm -D /dev/md0
/dev/md0:
        Version : 1.2
  Creation Time : Wed Nov  6 08:02:41 2013
     Raid Level : raid1
     Array Size : 16768896 (15.99 GiB 17.17 GB)
  Used Dev Size : 16768896 (15.99 GiB 17.17 GB)
   Raid Devices : 2
  Total Devices : 2
    Persistence : Superblock is persistent

    Update Time : Thu Sep 10 04:02:26 2015
          State : clean
 Active Devices : 2
Working Devices : 2
 Failed Devices : 0
  Spare Devices : 0

           Name : rescue:0
           UUID : 872ad258:c42ccb36:e9e19c96:98b55ee9
         Events : 156

    Number   Major   Minor   RaidDevice State
       0       8        1        0      active sync   /dev/sda1
       1       8       17        1      active sync   /dev/sdb1

Does this mean RAID is functioning and all my drives are synchronized? If not, how to check whether the drives are sychronized and that it is safe to replace the disk?
Thanks.
Answer: Yup. The output of cat /proc/mdstat and mdadm -D both show that things are ok for this array.
State: clean
and
[UU]
are the important notifiers that things are working as intended with your array.
You can double check from the kernel documentation on md
clean - no pending writes, but otherwise active.
    When written to inactive array, starts without resync
    If a write request arrives then
    if metadata is known, mark 'dirty' and switch to 'active'.
    if not known, block and switch to write-pending
    If written to an active array that has pending writes, then fails.

and the Linux Kernel Wiki on mdstat
Paraphrasing from the wiki entry:

The [UU] represents the status of each device, either U for up or _ for down.

If you wanted to set up email to alert you if there was an issue with your software raid array, then you could use this post from the Ubuntu forums: http://ubuntuforums.org/showthread.php?t=1185134 which should walk you through a process to set up emails to a remote account.
If you want to double-check the array is ok, you can always use this command: /usr/share/mdadm/checkarray -a /dev/mdX This command should also be in /etc/cron.d/mdadm and run monthly.
Aside from that, a possible run of smartctl might be reasonable, if you suspect impending hardware failure that isn't triggering failures in your array yet. Examples can be found here: SMART checks with smartctl
And finally, because this can never be said too much: Make sure you have good tested backups! =D Raid is very nice, but it is not a substitute for backups, and messages like that from your provider are less scary when you know you have good backups. =)
Hope that helps. =)
Comment: +1 from me, particularly for *RAID is not backups*.

Check RAID software: my status


SonicWall VPN or Windows VPN?

Question: Until recently, the small company I work for (~10 people) has relied on an IT resource to manage our network infrastructure. One of the last things he implemented before leaving was a VPN connection to our SVN repositories hosted inside the company firewall (so people could update and commit to SVN remotely). I wanted to expose a couple more resources via VPN (namely, we're revving up some internal Git repositories that we'll want to access through VPN), so I was exploring how to get that working.
While investigating how VPN had been configured for SVN, I found that we weren't using our SonicWall's VPN/SSLVPN - we were using our Windows Server 2008 machine's "Routing and Remote Access Service".
I'm pretty new to dealing with server configuration and firewall stuff, so I had a couple questions about this:

Is it "better" to use the VPN functionality built into SonicWALL or to use Windows "Routing and Remote Access Service"? By "better", I mean, are the two equivalent choices with one being a clearly superior option to the other?
If I go with SonicWALL, it seems that it would be better to use the SSL-VPN rather than the "normal" VPN option. Is that correct?
In a tutorial video, I saw that SSL-VPN through SonicWALL uses a web portal system to connect to VPN. With our current Windows implementation, anyone who wants to connect via VPN just creates a new VPN connection in their OS. If we use SSL-VPN, do we have to use the web portal, or can people still use their OS-configured VPN connections (like OSX's System Preferences > Network > VPN Connection type)?
Answer: The sonicwall vpn is better in my own opinion, why?

Your server load to do the job is gave to the router, which is optimized for that.
You keep only one device facing the internet, while with rras + a router you expose more gear to the internet.
The ssl vpn allow you to easilly configure the vpn as that mean you got a router that got a web portal, that you can create menu on it in case someday you decide to publish more ressource.

2 - No, its easier for the end user if they dont know hat they do, but both option work.
3 - Yes and no, as by default you need the sonicwall global vpn client, as it add another layer of security, but you can create pptp compatible configuration in the sonicwall. (and you got the vpn extension from the webpage, which is in reality an activex that autoconfigure the vpn)
Comment: Thanks for the info! I'll consider switching us over to the SonicWALL VPN feature in that case.
Comment: i would recomment sonicwall netextender instead of global vpn client

SonicWall VPN or Windows VPN?


Foreach ou for por item de nota fiscal

Question: Preciso fazer um foreach por item no meu código só que não estou conseguindo realizar.
Ex.: tenho uma nota que tem 2 itens, e preciso ler as informações da nota por item, leio o item 01 e depois leio o item 02, só que não estou conseguindo implementar isso no meu código abaixo.
Segue meu código.
private void btn_laudo_Click(object sender, EventArgs e)
{
    string ItemNota = @"SELECT
                    SD.D2_COD,
                    SD.D2_LOTECTL,
                    QR.QER_REVI,
                    SD.D2_ITEM
                  FROM SD2020 AS SD
                  INNER JOIN QER020 AS QR WITH(NOLOCK) ON QR.QER_LOTE = SD.D2_LOTECTL
                  WHERE SD.D2_DOC = '" + txt_nota.Text + "' AND SD.D2_ITEM = '" + txt_item.Text + "'";

    SqlCommand comando = new SqlCommand(ItemNota, conex);
    conex.Open();
    SqlDataReader ler = comando.ExecuteReader();
    if (ler.Read() == true)
    {
        txt_lote.Text = ler[1].ToString();
        txt_codprod.Text = ler[0].ToString();
        txt_revi.Text = ler[2].ToString();
    }
    conex.Close();

    this.CabeçalhoLaudoTableAdapter.Fill_CabLaudo(this.DSLaudosPS.CabeçalhoLaudo, txt_nota.Text, txt_item.Text);
    this.CorpoLaudoTableAdapter.Fill_CorpoLaudo(this.DSLaudosPS.CorpoLaudo, txt_codprod.Text, txt_lote.Text, txt_revi.Text);
    this.rpw_laudo.RefreshReport();
}

Comment: E qual é a dificuldade, jovem?
Comment: E qual o problema? O que tentou fazer com o `foreach`?
Comment: então preciso fazer um foreach pra ler por item de nota fiscal e não estou sabendo fazer este foreach, preciso ler o item 01 produto x e preencher os textbox que passo dentro do reportview que esta no código, ai depois leio p item 02  produto y e passo as informações para o textbox dentro o reportviwer abaixo . Não sei se estou conseguindo explicar minha necessidade.
Comment: Se perceber no minha query acima eu preencho manualmente o numero da nota e o numero do item ai abaixo eu eu leio e preencho os textbox dentro do datareader, ai passo todos os parametros preenchido para dentro dos  textbox no reportviwer.
Answer: Remova a chave do item da query, e faça o loop no DataReader. O Processamento que você precisa fazer na linha, faça dentro do loop.
string ItemNota = @"SELECT
                    SD.D2_COD,
                    SD.D2_LOTECTL,
                    QR.QER_REVI,
                    SD.D2_ITEM
                  FROM SD2020 AS SD
                  INNER JOIN QER020 AS QR WITH(NOLOCK) ON QR.QER_LOTE = SD.D2_LOTECTL
                  WHERE SD.D2_DOC = '" + txt_nota.Text + "';";

    SqlCommand comando = new SqlCommand(ItemNota, conex);
    conex.Open();
    SqlDataReader ler = comando.ExecuteReader();

    while (ler.Read())
    {
          //faça o que precisa com cada linha aqui
        this.CabeçalhoLaudoTableAdapter.Fill_CabLaudo(this.DSLaudosPS.CabeçalhoLaudo, txt_nota.Text, txt_item.Text);
        this.CorpoLaudoTableAdapter.Fill_CorpoLaudo(this.DSLaudosPS.CorpoLaudo, ler[0].ToString(),ler[1].ToString(), ler[2].ToString());
        this.rpw_laudo.RefreshReport();
    }
    ler.Close();
    conex.Close();

Comment: Muito obrigado Rovann...ajudou muito mesmo.
Comment: Obrigado Rovann, mas o que estou preenchendo nos textbox, eu to jogando pra dentro do reportview abaixo no código.
Comment: acredito que nem seja necessário jogar pra textbox... joga direto pro reportview
Comment: Rovann obrigado pela ajuda, mas ainda esta faltando algum detalhe, porque e o seguinte, na nota que estou digitando tem dois itens, 01 e 02, quando eu rodo o codigo, ele le as informações dos dosi itens mas na tela do reportviwer só mostra na tela o item 02, não mostra o item 01, tinha que mostrar item 01 uma pagina e item 02 outra pagina.
Comment: Acredito que aí seja algo com o reportviewer, nesse caso, não trabalho com ele e não saberia te ajudar. Como a pergunta só fala sobre o loop nos itens, creio que possa ser finalizada.

Foreach ou for por item de nota fiscal


Using nginx: require authentication when request from public IP, not needed when local

Question: I wrote a simple file browser app which is served using node on port 3000. I use nginx as a front-end which proxies this service. This is on my home server.
I would like to be able to require basic HTTP authentication when I'm accessing it over my public IP, but not when I'm at home. I have this configuration:
location /files {
  satisfy any;
  allow 10.1.0.0/24;
  deny all;
  auth_basic "Authentication Required";
  auth_basic_user_file /etc/access_list;
  proxy_pass http://127.0.0.1:3000/;
}

However, this isn't working. When I'm on my home network on the same subnet, it is still requiring me to do the basic HTTP authentication. I had thought the order "allow > deny > auth" paired with "satisfy any" is correct. Am I doing anything wrong here? Is this possible?
Comment: Ok, this is stupid. The second line should read 10.1.1.0/24.
Comment: Did you make sure you're accessing it via internal IP? What does your `access_log` say?
Comment: Access log is showing I'm requesting from 10.1.1.157, the IP of my notebook.
Comment: That's correct. Is everything working now?
Answer: There is typo in above config. The connection is from 10.1.1.157, but the configuration file just allows from 10.1.0.0/24.
The fix is simple: Change the problematic line to the following one:
allow 10.1.1.0/24;


Dual spaces, Am I doing right?

Question:
Let $\mu$ be the counting measure on the measurable space $(N,P(N))$.
$1 <p,q< \infty$ , $\frac{1}{p}+\frac{1}{q}=1$.
Define: $\phi: l_q\to (l_p)^*$ such as for all $(a_n)\in l_p$ and $(b_n)\in l_q$:
$\phi((b_n)_n)((a_n)_n)=\sum_{n=1}^{\infty} a_n b_n$.

A.Show that $\phi$ is well-defined, linear, injective and $\|\phi(b_n)_n\|\leq \|(b_n)_n\|_q$.

B.Show that $\phi$ is surjective and $\|\phi(b_n)_n\|=\|(b_n)_n\|_q$.
Hints for part B:

1.Let $f\in (l_p)^*$, $\forall n\in N$, denote $e_n(k)$ as:
$e_n(k)$ = 1 if n=k and 0 otherwise.
So $e_n\in l_p$ (why?). And look at $b_n:=f(e_n)$.

$\forall n\in N$ define:
$\lambda_n= |b_n|^q/ b_n$ if $b_n \neq 0$ and 0 otherwise.
Let $N_0\in N$ show that $\sum_{n=1}^{N_0} (|b_n|^q)^{1/q} \leq \|f\|$.

This what I did (according to my understanding of this question).
$\phi$ is well defined:
It means to make sure that the given sum is in $(l_p)^*$ which is equivalent to say that the defined sum is a function from $l_p$ to $C$.
$|\phi(b_n)(a_n)|=\left|\sum_n a_n b_n\right|\leq \sum_n |a_n b_n| \leq \|a_n\|_p \|b_n\|_q < \infty$, by using the Holder inequality.
$\phi$ is Linear:
Let $b_n , c_n \in l_q$ , $a_n \in l_p$ , $b,c \in C$.
Then, $\phi(b(b_n)+c(c_n))(a_n)= \sum_n (a_n)(b(b_n)+c(c_n))=\sum_n (b(a_n)(b_n)+c(a_n)(c_n))=b\sum_n (a_n)(b_n)+ c\sum_n (a_n)(c_n)= b \phi(b_n)(a_n)+ c \phi (c_n)(a_n)$.
$\phi$ is injective:
Let $(a_n)\in l_p$ , $(b_n), (c_n) \in l_q$.
Assume that :  $\phi(b_n)(a_n)=\sum_n (a_n)(b_n)=\phi(c_n)(a_n)=\sum_n (a_n)(c_n)$, so $\sum_n (a_n)((b_n)-(c_n))=0$ and since it is true for every $a_n \in l_p$, we have $b_n=c_n$ ,$\forall n$ thus $(c_n)_n=(b_n)_n$.
And the last thing, $\|\phi(b_n)\| =\|\sum_n (a_n)(b_n)\| \leq \sum_n \|(a_n)(b_n)\| \leq \|a_n\|_p \|b_n\|_q$ ,here i used the holder inequality, so $\|\phi(b_n)\|=\sup_{\|a_n\|_p=1}  |\phi(b_n)| \leq \|b_n\|$ .
Part B:
$\phi$ is surjective:
Is is easy to see that $e_n \in l_p$ since
$\|e_n\|_p=(\sum_n |e_n|^p)^{1/p}=1 < \infty$ so $e_n \in l_p$.
(Here we use the p-norm definition), we'll need this later!.
We aim to find a sequence $(b_n)_n\in l_q$ such as $\phi((b_n)_n)=f$. Look at:
$b_n=f(e_n)$ so we get $\phi((b_n)_n)(e_n)=\sum_n e_n*b_n=b_k=f(e_k)=f(e_n)$ (using $e_n$ definition).
We want to show that $b_n\in l_q$:
$\|b_n\|_q= \|f(e_n)\|\leq \|f\|_{l_p^*} \|e_n\|_p = \|f\|_{l_p^*}<\infty$ since we assume that $f\in l_p^*$.
Is what I did fine?
Can you please help me with the other part in 2?
Comment: This is a special case of the well-known Riesz Representation Theorem (The dual of $L^p$ is $L^q$), which can be found in any functional analysis textbook.
Comment: You can find the proof of the Riesz theorem for the dual of Lp in many places, but it is instructive to prove this particolar case by yourself, in which a more direct proof is available
Comment: Is this available online @Danny Pak-Keung Chan
Comment: Yes @Romulus Augustulus , unfortunately I am not managing to show all the things..
Answer: As for the part A, for $\| \phi(b_n)\|$ what is meant is the norm in $\ell_p^*$, the standard dual norm in a Banach space, so, if you apply the definition of dual norm, with your computation you've almost finished.
As for the party B, I didnt understand what you write. The idea of the proof is that you want to prove that there exists $\mathbf{b}=(b_n)_n$ such that $f=\phi(\mathbf{b})$, but of such a sequence exists, it is determined by the fact that $\phi(\mathbf{b})(e_k)= b_k$, so it must necessarily be $f(e_k)= b_k$. Then you have to prove that $\mathbf{b}\in\ell_q$ and that $\phi(\mathbf{b})= f$. The latter is easier, the former a bit trickier
Comment: For the first part, you can look for the norm on the dual of a Banach space, which you can find on any book on functional analysis, or on the internet. For the second part, the fact that $\phi((b_n))=f$ follows from the definitions; to prove that $(b_n)_n\in\ell_q$, you can prove that $\|(b_n)_n\|_{\ell_q}=\|f\|_{\ell_p'}$. The inequality $\ge$ follows from the first part, to prove the inequality $\le$ you have to apply the definition of dual norm
Comment: Hi @Romulus Augustulus thanks.Can you please show me the these things, since I am not succeeding to show it correctly:/
Comment: Hi @Romulus Augustulus , thanks, i've edited it, hope it is fine now. Can you please help me with the other inequality of the second part, i am not getting how λ is related to the problem?
Comment: Part A is right. For part B, I think that sometimes you are confusing the symbol $b_n$ meaning the succession $(b_n)_n$, and as its $n$-th element. In my answer I used a confusing notation, so I changed it, hoping it's more clear. You substantially proved that $\phi(\mathbf{b})=f$, but in the proof that $\mathbf{b}\in\ell_q$ I think that you're confusing the two concepts

Dual spaces, Am I doing right?


Clicking any administration menu link results in empty overlay screen

Question: I've created a Drupal site which behaves rather strange - whenever I click an item in the administration menu or use a contextual link to edit a page, the half-opaque overlay shows, but no editing window opens on top of it as it should  (not just "not immediately", but never).
Once I'm in "overlay mode", if I click a menu item, the linked page opens as it should, on top of the overlay. From here, all items work as intended, except when opened in a new tab - that will also only show an empty overlay page.
When the overlay is eventually closed again (for example, by clicking the home link to return to the front page), the error described above will reoccur the next time an administrative link is clicked.
Can anyone assist me in finding the source of this problem? Please let me know if you need additional information.

The site was built on 7.53 originally and is now updated to 7.54 (up to date). No changes to the .htaccess file have been made, therefore all of my changes are within the /sites/ directory.
I'm using these contrib modules: Chaos tools, CKEditor, Views, Views UI, Webform
My administration theme is Seven.
I've set up other Drupal 7 sites on the same environment and didn't have this problem, so I clearly I did something different here. I have no idea where to start looking, though, and wasn't successful in finding other questions or external info covering anything even remotely related.
Answer: The issue turned out to be caused by me including jQuery via the following line in my theme's info file:
scripts[] = js/jquery-3.1.1.min.js

Removing this line and using the jQuery version included by default (1.4.4) will return the $ is not a function error when using $() syntax, which can be resolved by wrapping existing jQuery code in the following:
jQuery(function ($) {
  // ...
});


Interpretation of the Maximum Likelihood Estimator formula

Question: Let $\mathbf{X} = (X_1, \ldots, X_n)$ be an i.i.d sample from the parametric family of distributions $\mathcal{P} = \{P_\theta: \theta \in \Theta \subset \mathbb{R}^k\}$ ($X_i \sim P_\theta$ are random variables, not just real numbers). In my statistics textbook there is the following formula for the Maximum Likelihood Estimator $\hat\theta(\mathbf{X})$ (which is also a random variable, not an estimate):

$$\hat\theta(\mathbf{X}) = \underset{\theta \in \Theta}{\operatorname{argmax}} L(\mathbf{X}; \theta),$$
  where $L(\mathbf{X}; \theta)$ is a random variable which is obtained from an ordinary (numerical) likelihood function $L(\mathbf{x},θ)$ by substituting random vector $\mathbf{X}$ on place of numerical vector $\mathbf{x}$.

I am concerned about the fact that random vector $\mathbf{X} = (X_1, \ldots, X_n)$ implicitly depends on $\theta$ because $X_i \sim P_\theta$. This makes it difficult to interpret the maximization process.
Should I treat random variables $(X_1, \ldots, X_n)$ as constants in the maximization process?
If not, what will be the correct interpretation of the above formula?
Comment: The concept of MLE is: assuming the observed $\pmb{x}$ is "most-likely" to occur, we wish to find the value of $\theta$ which maximizes the likelihood $L(\pmb{x};\theta)$.  Thus the MLE of $\theta$ will be a function of $\pmb{x}$. Now for further analysis, if we wish to find distribution or confidence interval of the MLE of $\theta$, we replace $\pmb{x}$ by $\pmb{X}$.
Answer: To make the distinction between $\theta$ which is the running argument in the likelihood function $L({\mathbf X};\theta)$ and $\theta_0$ which is the parameter at the source of the generation of $\mathbf X$ [assuming the model is true and there is such a $\theta_0$], one can write $\mathbf X$ as the deterministic transform$${\mathbf X}={\mathbf \Psi}(\epsilon,\theta_0)\sim P_{\theta_0}$$where $\epsilon$ is a "white noise" in the sense it is a random vector with a fixed distribution, of dimension possibly larger than the dimension of $\mathbf X$ (to keep the representation as general as possible). The likelihood function then writes as$$L({\mathbf \Psi}(\epsilon,\theta_0);\theta)$$which can be optimised in $\theta$ [and not in $\theta_0$ since, while ${\mathbf X}={\mathbf \Psi}(\epsilon,\theta_0)$ is observed, $\epsilon$ is not.
Comment: Thanks! You mean that I should write $X_i \sim P_{\theta_0}$ (where $\theta_0$ is true parameter) instead of $X_i \sim P_\theta$ in my post above to use the formula for $\hat\theta(\mathbf{X})$? It seems that in this case $\mathbf{X}$ will not depend on varying parameter $\theta$ and the formula will be correct.
Comment: (+1) Exactly so! This "tale of two $\theta$'s" is also at the core of the EM algorithm.
Answer: Although Xi'an's answer is correct I want to note that in most cases we use model where random vector $\mathbf{X}=(X_1, \ldots, X_n)$ doesn't depend on any parameter at all, only its distribution depends on $\theta$. In such cases the maximization process is easily interpreted. You can find details here.


Howto send keystrokes with V-Lang

Question: I want to send keystrokes with V lang to try to create a testing tool. How can I do that?
Like send(enter) or something like that
Comment: Command line or graphical app?
Comment: Command line for a while, but graphical method will be needed soon
Answer: I'll recommend you look at the examples directory.
It's very, very, feature rich :)
For terminal input specifically you can look at the term.ui module:
Here's an example from pong.v.
If you do not need all the bells and whistles of term.ui you can use the readline module.
For graphical apps there's both gg and the lower level sokol modules.
gg example using input here - and sokol example here.
Comment: I want to write a keystoke, not to read one
Comment: I see. In that case you'll currently need to generate OS events yourself [which isn't necessarily done easily](https://stackoverflow.com/a/10100458/1904615)

Howto send keystrokes with V-Lang


Using querySelectorAll to select all href that matches document.URL?

Question: I'm trying to add a class when an href matches the document's URL using:

However, I'm stuck on the first line as it returns an empty nodelist.
document.querySelectorAll('a[href="'+document.URL+'"]')

HTML

Another Level 1

Also, what is the use of the next selectors (+) in +document.URL+? Why not just use a[href="document.URL"] as it returns the full path?
Link
Comment: `+` isn't part of the selector. It's the string concatenation operator. `'a[href="'document.URL'"]'` is a SyntaxError.
Comment: would only work if you have full absolute href's. If using relative ones you will have to loop over all `a`
Comment: Taking into account your last edit, `location.pathname` (instead of `document.URL`) may be what you're looking for. You may have to cut the trailing `/` though.
Comment: did you put this script at the end of the document?
Comment: yes, before body close
Comment: How do links in the source actually look like?
Comment: add also the HTML, cause maybe you don't have an `a` element with the href attribute equals to all the URL returned by `document.URL`.
For your second question, that's a concat of a string and a variable which holds a string
Comment: Given a link `const link = document.querySelector("a[href]")`, look at its actual `href` attribute: `console.log(link.getAttribute("href"));`. Does the output match your expectation and could it ever be exactly equal to `document.URL`? That is, do all links that you expect to potentially match contain the _full URL_ in their attributes?
Answer: The href attribute in your HTML is /-training-test/menu-test/sub-menu-1/another-level-1/. But document.URL is a fully-qualified URL, something like http://www.yourdomain/com/-training-test/menu-test/sub-menu-1/another-level-1/, so the href doesn't match this exactly.
Instead of document.URL, try using location.pathname, which is just the pathname part of the URL.


Sorting PayPal Date in MySQL

Question: PayPal's Date format is "HH:MM:SS MON DD, YYYY PDT", e.g. "21:49:27 SEP 12, 2013 PDT". In inputting the information into MySQL I simply copies the column I am really not even concerned the hour, minutes, and second. Presently I have:
strSQL = SELECT ID_PayPal, first_name, last_name, item_number, results_amount, donation_amount, country_code,  STR_TO_DATE(MID(payment_date,12,10), '%m-%d-%Y') AS date_for_sort FROM PAYPAL ORDER BY date_for_sort DESC"
The result is:
 Jan 26, 2013
 Jan 07, 2013
 May 26, 2013
 Jan 30, 2013
 Feb 23, 2013
 Sep 07, 2013
 Jan 14, 2013

As you can see not want I want. Suggestions? Thanks. Rick
Comment: Great thought. I seemed it would work, but here are my results:Jan 02, 2014
Jan 26, 2014
Jan 01, 2014
Jan 24, 2014
Jan 29, 2014
Jan 13, 2014
Jan 21, 2014
Jan 25, 2014
Feb 10, 2014
Apr 04, 2014
Jan 23, 2014
Mar 28, 2014
Jan 03, 2014
Mar 23, 2014
Jan 25, 2014
Apr 15, 2014
Apr 07, 2014
Apr 20, 2014
Jan 03, 2014
Jan 28, 2014
Jan 18, 2014
May 02, 2014
May 14, 2014
Feb 09, 2014
Jan 14, 2014
Jan 01, 2014
Jan 04, 2014
May 12, 2014
Jan 20, 2014
Feb 02, 2014
Comment: Could you add your table structure and some actual sample data? If the date is stored as a string in the format you're showing, my answer below should give the correct answer as the sqlfiddle shows, but if you're not giving all the details on how it's stored it may not.
Comment: I'll delete my answer below since "it doesn't work" isn't enough of a description to figure out why your data doesn't look like my working sample data.
Answer: By using the STR_TO_DATE() function, I am guessing that you have a varchar string (not a date formatted column) for the payment_date column in the database.
I do not like functions inside functions as it can get confusing and they sometimes don't work... or could be the order in which they process... which one of the two seems to be the case in your situation.
Thus I suggest a sub-query is what you really need, as in the 2nd example below.
The bottom line is: Your STR_TO_Date(,'**%m**-%d-%Y') is not working or formatting based on your result set, obvious as the desired %m is still showing Jan-day-year rather than O1-day-year. Perhaps its a matter of missing quotes somewhere near or in the  ' Mid() ' but who knows?) I cant test without a creating a table and data.....
%M is the full month (January, February....)
%m is the numeric month (01, 02, 03.....which is what you are trying to format).
%b for short month  (Jan, Feb...)
Like I stated functions inside functions are temperamental so this might work.
MID(STR_TO_DATE(payment_date,"%T %m-%d-%Y"),12,10)
(remove this and the next line from query)
(Not tested: re-adjust the 12,10 desired results as needed)

If the above does not fix the issue, you could start from scratch and try a double sub-query nested in the outer query of all the other results you desire... such as
Inner subqueries
SELECT  STR_TO_DATE(D1, "%m-%d-%Y")
FROM(
SELECT MID(payment_date, 12,10) AS D1)
AS date_for_sort ORDER BY date_for_sort DESC;

I would leave out the ORDER BY... and play with that last as it may need to be in the outer query result set!"the above is nested as part of an outer query that Is NOT shown/coded in the example".
But, this example works and is a starting point!
Breaking down the query it would be the same as:
Outer Query------01-10-2017 (in sql date format)
Inner Query----- July 10 2017 (a string)
and the result would be
08-10-2017
A date format that you can ORDER BY as date_for_sort is generated as a date -(Pointing out again, you did specify %m rather than %b).
I don't have a data table to work and test with as to offer you a working correction, thus the above 2nd code is hopefully a hint or nudge in the right directions.
The fact is there is about 3 query-code-combo-ways I can think of to query and get your results, but I don't want to confuse anyone as this reply is a few years late. lol.
Hopefully the OP has a working model in the 4+ years of this late response. :-)
Hope this helps someone else though!
BobDCoder

Sorting PayPal Date in MySQL


How to shutdown/restart my UWP-Application?

Question: I'm working on a programm for RaspberryPi with Windows IoT core 17763. My IDE is Visual Studio 2019. I use C# and UWP for my programm.
Restart and shutdown doesn't work.
For these functions the app has 3 buttons.

Button Exit: termination of the app and start the IoT core app.
Button Restart: full reboot of the system.
Button Shutdown: full shutdown the system.

How does my app behave?

while debugging: All 3 buttons just terminate the app and the debugging ends.
when app is in autostart: All 3 Buttons perform a restart of the app. No shutdown, no reboot of the system, no IoT core app.

Here the relevant code of my application
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using System;
using Windows.System;

public sealed partial class MainPage : Page
{

    public MainPage()
    {
        InitializeComponent();
    }

    //button to exit application
    private void FlyoutExit_Click(object sender, RoutedEventArgs e)
    {
        Application.Current.Exit();
    }

    //button to restart system
    private void FlyoutReboot_Click(object sender, RoutedEventArgs e)
    {
        ShutdownManager.BeginShutdown(ShutdownKind.Restart, TimeSpan.FromSeconds(0));
    }

    //button to shutdown system
    private void FlyoutShutdown_Click(object sender, RoutedEventArgs e)
    {
        ShutdownManager.BeginShutdown(ShutdownKind.Shutdown, TimeSpan.FromSeconds(0));
    }

}

Here is the Package.appxmanifest
<Package
xmlns="http://schemas.microsoft.com/appx/manifest/foundation/windows10"
xmlns:mp="http://schemas.microsoft.com/appx/2014/phone/manifest"
xmlns:uap="http://schemas.microsoft.com/appx/manifest/uap/windows10"
xmlns:iot="http://schemas.microsoft.com/appx/manifest/iot/windows10"
IgnorableNamespaces="uap mp iot">
<Capabilities>
<iot:Capability Name="systemManagement"/>
<Capability Name="internetClient" />
<iot:Capability Name="lowLevelDevices"/>
<DeviceCapability Name="serialcommunication">
  <Device Id="any">
    <Function Type="name:serialPort" />
  </Device>
</DeviceCapability>
</Capabilities>
</Package>

Answer:
When the application exits in debugging mode, visual studio will dis-connect the remote debugging. The behavior is correct. After the application exits, Windows IoT Core will start the default app which is configured as start-up.
ShutdownManager requires the use of the IoT systemManagement capability. You need to add the following to Package.appmanifest, otherwise, the app will exit with an exception.
<iot:Capability Name="systemManagement"/>
Comment: @TonicLoyal, when the app is in debug mode, does shutdown/restart work with no exception? ShutdownManager works fine for me even the app in debug mode or not.
Comment: The behavior while debugging is clear for me. But when the app is not in debug. I added my Package.appxmanifest to the main post. I don't get any exception. The app just restarts.
Comment: If possible, could you please share your project?
Comment: no exception even in debug. In debug the app just closes and returns to the IoT core app. How can i share the project? Does StackOverflow support this, or does it need to be uploaded externally?
Comment: I found my mistake. I copied the buttons for reboot and shutdown from the exit button. So I forgot to change the Click="Exit_Click" in XAML. All 3 had the same click. So no matter what i clicked, the current.Exit() was always taken. My only question now is, how to exit the app and start the IoT core app. ANy idea?


Support duplicate entries in a M2M associative table

Question: I am working on a SQL-Alchemy app using flask and flask-db and have been scratching my head over how to solve this question. My models looks like this:
class event_schematics_map():
    event_schematics_table = db.Table(
        'event_schematics_table',
        db.Column('fk_schematic_id', db.Integer, db.ForeignKey('schematics.id')),
        db.Column('fk_event_id', db.Integer, db.ForeignKey('events.id'))
    )

class Events(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(120), index=True, unique=False)
    date = db.Column(db.String(120), unique=False)
    owner = db.Column(db.Integer, db.ForeignKey('user.id'))
    schematics = db.relationship('Recipe', secondary=event_schematics_map.event_schematics_table, backref='schematic')

class Schematics(db.Model):
    __tablename__ = 'schematics'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    name = db.Column(db.VARCHAR(70), index=True)
    schematics_description = db.Column(db.String(1024), index=True)
    creator_id = db.Column(db.Integer, db.ForeignKey('user.id'))

Schematics are created and are on the many side of O2M with a user table separately not shown above. The map table is used as the glue in the M2M relationship.
Currently I am adding new schematics to each event and updating the assoc table like so: events.schematics.append(SomeNewSchematic) which works fine until I attempt to enter multiple instances of the exact same Schematic like this:
schem1 = Schematics(name='TheOnlySchematic')
schem2 = Schematics(name='TheOnlySchematic')
event.schematics.append(schem1)
event.schematics.append(schem2)
etc

in which case I can only apply one as I think the entry is being duplicated. I believe this may be solved by an additional field in the assoc table event_schematics_map, but unsure if I am overlooking something simpler or how to implement this.
Effectively I want to support multiple entries of the exact same model
I believe my problem is along the same lines as can I append twice the same object to an instrumentedlist in sqlalchemy - but I could not see a solution for this.
Really appreciate any pointers or to know how to solve this problem.
Comment: Having an exact duplicate in a many-to-many relationship doesn't make any sense unless there is some other attribute associated with the link, such as a date or a version number or something like that. In that case you'd need to add that attribute to your association class (event_schematics_map) to track that piece of information and to make the rows in the association table unique.
Answer: Thank you for your reply and setting me straight here,
You are quite right, duplicate entries does not make sense.
I ended up solving this by using an associative table as discussed in other answers to track the occurrence of each schematic.


como renderizar no ReactJS dados de uma API?

Question: desculpa galera, sou muito novato em programação e estou fazendo um projeto para uma faculdade. Consegui conectar-me a api, consigo trazer o objeto de lá, so que não consigo renderizar esses dados que são retornados, ja tentei muita coisa e nao funcionou. Alguém pode me dar uma luz? Amanha tenho que apresentá-lo e não sei como fazer.  o código está assim e perdido no que fazer ...
const Empresa = () => { const [itens, setItens] = useState([]) async function buscar(event) {

event.preventDefault();

const cpf = document.getElementById('cpf').value

try {

  if (cpf !== null) {
    if (cpf !== '') {
      const response = await api.post('/pacientes/atestados',
        {
          cpf
        });

        setItens(response.data);

      if (response.data !== null) {
        setItens(response);
        console.log(itens)

      }
      if (response.data == '') {
        console.log(response.data)

        alert('CPF não cadastrado')

      }

    }

    else {
      alert('Preencha todos os campos')
    }
  }
}

catch (error) {
  alert(error);

}
} return (

<>

Bem vindo Empresa!

Pesquisar Atestado

  <form >

       CPF
      <input name="cpf" className="controle de formulário"
        id="cpf" placeholder="Digite o cpf do funcionário"
      />

    <button type="submit"
      className="form-contact-button" onClick={buscar}> Buscar atestado </ button>
  </ form>

  {/* <button id="form-contact-button2" onClick={sair}>SAIR</button> */}
</>

Answer: Boa tarde Wendel!
Espero que não seja tarde demais para apresentar seu trabalho.
Vou tentar te ajudar:
Primeiramente, como você definiu api em api.post?
api é como você definiu o nome da biblioteca que você importou?
Segundamente, você está fazendo uma requisição POST para /pacientes/atestados.
Lembre-se que você quer renderizar um dado do banco. Pelo que entendi pelo contexto, você quer passar um cpf e buscar o atestado do cpf, caso tenha, certo?
Se é isso que você quer, você precisa fazer uma requisição GET para o endereço, e provavelmente é melhor terminar o endereço com uma barra, já tive problemas graças à isso (ex.: /pacientes/atestados/).
Depois de usar o setItens com toda a lista de atestados, você pode fazer o seguinte:
const resultado = itens.find( cpfPaciente => cpfPaciente === cpf );
/* no exemplo acima, considerei que o atestado tem o campo cpfPaciente, e vai ler todos os itens e procurar pelo atestado cujo cpfPaciente é o mesmo que foi colocado no input id="cpf". Quando achar o atestado do cpf que você procurou, ele armazena em result.
*/
Para mostrar os dados, pode usar o hook abaixo:
const [atestado, setAtestado] = useState({});
Agora pode definir atestado como o resultado da busca
setAtestado(resultado)
No final, coloca {atestado} depois do botão de busca para renderizar na tela.
DICA:
Não use espaços e acentos em classNames (e IDs também). Um elemento pode ter uma ou mais classes, que são separadas por espaço, então em className="grupo de formulário", estão sendo consideradas três classes distintas, "grupo", "de" e "formulario". Troque os espaços por hífens (-) que o css funciona melhor.


How can I prevent the screen flashing grey at every workbook open in a macro suite

Question: The suite is triggered by a button on Sheet1 of DrillDown.xlsm.
The suite uses the following workbooks: wbIn, wbOut, wbTarget. The contents of wbIn are used to identify which workbook file should be opened as wbTarget. The relevant rows are then copied from wbTarget to wbOut. During a run of the suite there may be from 1 to 4 wbTargets used. Each one is closed before the next one is opened.
During the execution of the suite there will be between two and five file open events (wbIn and up to four wbTargets). At each of these, Sheet1 of DrillDown.xlsm disappears from view and is replaced by a grey screen. This is followed by a brief re-display of Sheet1 before it again is removed and replaced by the grey screen.
Any thoughts on what I can do to hold focus on Sheet1 of DrillDown.xlsm throughout the entire run of the suite?
I have trawled the net and as a result I have done the following:
Application.ScreenUpdating = False is set.

There is no use of Activate anywhere in the suite. There is no use of Select anywhere in the suite.
The code which opens the target workbook is as below
Set wbTgt = Workbooks.Open(Filename:=sTargetWbk, ReadOnly:=True)
Set wsTgt = wbTgt.Sheets(1)

Updated at 13:52 GMT+1 on 31-07-2019
In what follows, "Main Screen" is the content of Sheet1 of ThisWorkbook. If I can work out how big an image file should be, and how to add one, I will let you all see what the "grey screen" looks like. The sequence of events, after accepting the user's input is as follows:
Main Screen with Hour-glass mouse pointer - no immediate flicker
Flicker to Grey Screen with steady Hour-glass
Hour-glass changes to small White Cross steady
Back to Hour-glass which flickers steadily
Main Screen flashes up very briefly
Then repeat three more times (because I used all four target files on this test) from Flicker to Grey Screen...
By providing these details about the mouse pointer behaviour and the screens displayed, however briefly, I'm hoping somebody out there can get an understanding of what is going on "under the covers" of Excel. All my mouse pointer settings are as factory-shipped.
Updated at 1422 GMT+1
Here's the Grey Screen image. It was captured by "Print Screen" and then taken into Photoshop to downsize it to fit the web page. I hope!
Grey Screen
Comment: Marco, Please read posts more carefully. I quote "...I have done the following: Application.ScreenUpdating = False is set."
Comment: Have done that and it made matters worse!   I now see, briefly, each workbook displayed after it opens, and this then stays in view until the next one opens.
Comment: Do you call any other macros from your initial macro?
Comment: Macro suite schema:
DrillDown calls SelectInputWorkbook, PopulateWorkbook, CreateWorkbook, CloseWorkbooks
PopulateWorkbook calls HandleNewFileNumber, HandleSameFileNumber
CreateWorkbook calls TidySheets
CloseWorkbooks
Comment: If you call any custom macros from within your initial macro, make sure to include `Application.ScreenUpdating = False` in those macros aswell.
Comment: How much code is contained in the workbook in question? It's kinda hard to troubleshoot without being able to see what's going on.
Comment: @eirikdaude When the entire module of code is copied and pasted into a Word document and set to "No Spacing" it occupies eight and half A4 portrait pages. That code is spread across ten macros. I am about to update the original post with the exact sequence of flicking. Watch this space.
Answer: I am not sure if there is any easy way to prevent the problem you are describing - I am guessing you are seeing the various workbooks being opened on top of the current one, although I can't recall having experienced anything quite similar despite at times working with quite big workbooks and macros.
I wrote the macros you can see below in an attempt to replicate your problem, but didn't see it - of course there is a lot less work done in the various workbooks in my example than in what you describe, so maybe some of the problems come from that. I tried running the macro both with and without the settings in the bottommost macros turned off, but nothing seemed to replicate your problem.
Option Explicit

Sub test1()
    Call speedup

    Call test2

    Call slowdown
End Sub

Private Sub test2()
    Dim i As Long

    For i = 1 To 4
        With Workbooks.Open(Filename:="C:\Users\EirikDaude\Desktop\Test\Test" & CStr(i) & ".xlsx", ReadOnly:=True)
            Application.Wait (Now + TimeValue("0:00:03"))
            Debug.Print .FullName
            .Close
        End With
    Next i
End Sub

Private Sub speedup()
    Application.EnableEvents = False
    Application.ScreenUpdating = False
    Application.DisplayStatusBar = False
    Application.EnableAnimations = False
    Application.Calculation = xlCalculationManual
End Sub

Private Sub slowdown()
    Application.EnableEvents = True
    Application.ScreenUpdating = True
    Application.DisplayStatusBar = True
    Application.EnableAnimations = True
    Application.Calculation = xlCalculationAutomatic
End Sub

As you can see, I am turning off some Excel settings, similarly to what you found when you googled. Contrary to the suggestions in the comments on your question, I recommend only doing this in the main sub you are calling the others from, in order to keep track of which ones are turned off and which ones are turned on. Of course you may need to e.g. calculate some formulas in your sheet in the middle of your code execution, but if you do I would recommend doing so "manually" using Application.Calculate or Application.CalculateFull. I'll leave it as an exercise to you to figure out what the different settings do, it should be easy enough to google them.
As you may have guessed already, I think the best recipe for minimizing the amount of grey screen you see is making your code more efficient. Playing around with the settings shown in my macros could be a start, otherwise there are a lot of sites out there making recommendations on how to achieve this (I like this one, for instance). From what you wrote, doing something like wb1.worksheet.range.value = wb2.worksheet.range.value instead of copying the same might be a good place to start. Of course, without knowing exactly what your macro looks like, or what it does, it is hard to offer much concrete advice. I hope this at least could be of some help, I'm sorry I couldn't be more helpful with the concrete problem you are facing.
Comment: The settings suggested by eirikdaude in his answer have been tried. They have had no effect. It's beginning to look as though there is no solution using Excel alone. As this particular project is for my own use, I think I'll just have to accept that what it does is how it does it; no alternative.
Answer: Problem SOLVED!
I added a ThisWorkbook.Activate statement immediately prior to the Set wbTarget =... statement. Now the focus remains on the main worksheet.
My inspiration came from further Google searches around the subjects of Excel Window Focus Hold in combination with other terms I had used. No single search result gave me the answer. It was more a case of a slow dawning that Activate, along with everything else it did, set the focus on the Excel window specified.
I never expected to be the one who contribute the solution to his own problem on my very first posting to this forum. The encouragement you guys gave me kept me going until the end.
Thanks!


Query contacts by name using Office 365 Rest API

Question: Is it possible to search contacts by name (GiveName, DisplayName, LastName or Surname) using the OData filters?
Here's the documentation I'm using: Office 365 API OData filters
I see in the documentation where they say some properties cannot be filtered but they don't give a full list (complex types are listed but they don't include contact names).
My guess is no because when I try:
<code>/contacts?$filter=DateTimeCreated+ge+2014-09-01T00:00:00Z
</code>
I get a 200 response with correct data but when I try by any of the name properties:
<code>/contacts?$filter=DisplayName+eq+Jordan+Example
/contacts?$filter=LastName+eq+Example
/contacts?$filter=Surname+eq+Example
</code>
I get 400 Bad Response with no details in the response body but I know (and double checked) that the contact exists.
Would also love to search with a wildcard but trying not to be too greedy.
Answer: It should work, but you need to wrap your values in single quotes ('). Try:
<code>/contacts?$filter=DisplayName eq 'Jordan Example'
/contacts?$filter=LastName eq 'Example'
/contacts?$filter=Surname eq 'Example'
</code>
Comment: Is it possible to search on name like when I looking for all contacts where the givenName starts with Mi


Verificação de tabela sempre igual

Question: Estou com o seguinte código:
<?PHP
$status = mysqli_query($connecta, "SELECT `online` FROM `char` WHERE `name`='[ADM] koda'");
$resultado = mysqli_num_rows($status);

echo '

posicao
name
guilda	';
if($resultado == 0) {
echo 'off
';
}
if ($resultado == 1) {
echo 'on
';
}
  ?>

Problema:
Mesmo com a query com o valor na database em 0, ele continua mostrando o echo 'on'.
A query no SQL retorna corretamente,o problema é de lógica no IF.
Alguém conhece alguma solução?
Answer: A função mysqli_num_rows retorna o número de registros da consulta, e não o campo do select.
Você precisa verificar se o resultado da consulta é igual a 0:
$status = mysqli_query($connecta, "SELECT `online` FROM `char` WHERE `name`='[ADM] koda'");
$resultado = mysqli_fetch_assoc($status);
// ...
if ($resultado['online'] == 0) {

}

Comment: Era isso mesmo :) Obrigado!
Answer: Uma alternativa, só para ilustrar o uso do num_rows:
<?PHP
   $status = mysqli_query($connecta,
      "SELECT `online` FROM `char` WHERE `name`='[ADM] koda' AND `online` = 1");
   $resultado = mysqli_num_rows($status);

Neste caso, em vez de saber o STATUS do usuário, basta acrescentar a clausula online = 1 para ver se existe algum registro com essa condição ou não.
Notas:

Eu ainda prefiro o caminho da resposta do @luciorubens.
Com MYSQLI_USE_RESULT no 2o parametro do mysqli_query o resultado pode dar problemas. O ideal é MYSQLI_STORE_RESULT
Comment: Ah, ótima alternativa! `+1`

Verificação de tabela sempre igual


Copy specific files listed in a CSV file

Question: I'm working in a Windows 2008 R2 Server and I'm trying to copy certain files listed in a csv file from one partition to another, headers are:

ZipFile,Site.A,Site.B

ZipFile column contains the name of each file (name.zip).
Site.A column contains the full path where the file is at source.
Site.B column contains the full path where the file needs to be at the destination.
The code of the script is: (I've been looking on this site to get ideas)
$CSV_Path = "N:\File_with_paths.csv"
$CSV = Import-CSV $CSV_Path

ForEach ($File in $CSV) {
    Copy-Item -Path "$($File.'Site.A')$($File.'ZipFile')" -Destination "$($File.'Site.B')"
}

It fails but I cannot see what the error is.  If I run it it shows an error for less than a second and the script does not copy any file.
Comment: Did you missed the "\" in "$($File.'Site.A')-->\<--$($File.'ZipFile')"?
Comment: You should be able to see your errors in the automatic `$Error` variable.
Answer: To debug this, set a breakpoint for the Copy-Item cmdlet. This will let you step into debugging mode whenever your script reaches that particular command. If your script is named myCopyScript.ps1:
Set-PSBreakPoint -Script myCopyScript.ps1 -Command Copy-Item
.\myCopyScript.ps1

The script will now run until Copy-Item is invoked, at which point you will be inside the loop, but able to interact with the variables present.
This is a great opportunity to see what your $path name actually is:
Write-Host "$($File.'Site.A')$($File.'ZipFile')"

When you are done troubleshooting, remove the break point and exit the DEBUG prompt:
Get-PSBreakPoint | Remove-PSBreakPoint
Exit # This will simply stop the debugging nested prompt

If you in fact forgot the \ between the source directory and the file name, here is a safer way of getting the full path to the file:
$SourceFile = Join-Path -Path $File.'Site.A' -ChildPath $File.ZipFile


Problemas com wiselinks e turbolinks

Question: Eu preciso que, após clicar num botão, apareça um modal, dentro desse modal há um form populado (ou não) com objetos rails. O problema é que não consigo mudar o header accept para js de forma que o rails renderize (não printe o código na tela mas sim execute) um .js.erb. Para resolver isso, resolvi colocar no botão um data-remote=true para que o .js.erb fosse executado mas a página não fosse recarregada, porém eu preciso mudar a url e por isso queria usar o wiselinks com o atributo data-push=true, mas os dois juntos não funciona. Alguém consegue me ajudar com o problema do modal ou consegue me ajudar a como eu faço o modal aparecer com o remote e alterar a url com o pushState???
PS. o ideal seria que ao clicar no botão o modal aparecesse (com o conteúdo debaixo da action anterior) e ao acessar a url diretamente o modal também fosse renderizado (com um conteúdo de outra action embaixo)
Comment: Você tento resolver isso usando o history api do html5, http://diveintohtml5.info/history.html ?
Answer: Tu pode criar uma função que mostra o modal, baixar o JSON do objeto e fazer isto via JS:
function mostraModal(obj) {
  alert('Objeto: ' + obj.nome);
}

É claro que em vez de alert() tu pode usar algum plugin mais elaborado, usando HTML, etc.

Problemas com wiselinks e turbolinks


How to create code to continue count timer on vb.net

Question: Somebody please help, i want to create app with vb.net, but the problem is how to create code on vb.net to continue the timer billing count, when the computer goes down it's cause the electric down and then i turn on back of computer and the timer of billing app is continue again. thank you all for the answer. sorry for my bad english.
Comment: Post the relevant code of your app
Comment: Hi, and welcome to Stack Overflow, This is just a message I send to new members to help things along a bit. The learning curve for a new user isn't steep as such, but finding out how to use stack isn't always obvious. Please do take a few minutes and have a look here **[ask]** and it's also important to look here .. **[mcve]** .. **Also, if an answer is valid for you, click on the tick to the left of the answer so that the question is marked as answered** and this makes sure that the person who posted it gets reputation. Cheers.
Answer: As I understand, you don't need a timer at all. Just save the start time to database or to text file on your computer. Then you can always find the timer value no matter if your computer was down (current time minus start time).
Comment: Ok thank you i'll try your answ, can you give me the web tuts or link about my question.


MacOS codesign command on Bitrise failure: Segmentation fault: 11

Question: For some reason, I need to run a manual code signing for my macos app on Bitrise. When doing that with the following command:
codesign --deep --force --verify --verbose --sign "Developer ID Application: Name (ID)" "MyApp.app"

It always returned with the error:
line 11:  3043 Segmentation fault: 11

Does anyone know how to fix that?
Answer: While looking for possible solutions I came across these two posts:
Segmentation fault: 11 when attempting to codesign .app
https://forums.developer.apple.com/thread/65055
They helped me to find a solution to my issue. The answer marked as correct at the first link states that:
--timestamp=none

would fix it which was not true for me. But the second answer, as well as the solution mentioned in the second link, contains the correct hint.
I needed to sign with hex identifier and not with the certificate name.
You can get the hex identifier for your certificates executing this command:
security find-identity -p codesigning

Using the hex identifier returned for my certificate this is the command I need to run on Bitrise in order to sign MyApp.app
codesign --deep --force --verify --verbose -s <<hex identifier>> "MyApp.app"

Be aware that the order of the options is also important. '-s' had to be the last option for me.
(And remember to include the Bitrise workflow step 'Certificate and profile installer')
===Edit===
I'm talking about MacOS Sierra stack here.
Comment: Thanks for sharing the solution @Thor_Bux

Just one note: this is not bitrise specific, but macOS Sierra specific. A couple of keychain/signing related things changed in Sierra, which worked (a bit differently) on El Capitan. It's important to note, as on bitrise.io you can select both Sierra and El Capitan stacks.
Comment: The reason why I explicitly mentioned Bitrise here is that this issue does not occur on my local Mac which also runs Sierra. Thanks for mentioning that I should include the MacOS version.
Answer: I found a solution by signing with the hex id of the certificate instead.
You can find the HEX ID by running:
security find-identity -v
Credit Here: -- Segmentation fault: 11 when attempting to codesign .app


Xpath expression with breaks in the middle

Question: I have the following code

  F10_12-03_R1200

  v01.00_Vorgelegt

which i have to access using Xpath.
I've tried using
 .//tr/td[contains(text(), 'F10_12-03_R1200')]

Which works but also matches other nodes.
When trying
 .//tr/td[contains(text(), 'F10_12-03_R1200') and contains(text(), 'v01.00_Vorgelegt')]

nonthing is coming.
Any hint?
Thanks!
Answer: When I change your XPath too:
.//tr/td[contains(., 'F10_12-03_R1200') and contains(., 'v01.00_Vorgelegt')]

It outputs the desired output in Altova XML Spy. I have tested it.
See next screenshot: http://i929.photobucket.com/albums/ad134/markdark81/xpath.png


Sequence of functions divided by constants converge to zero

Question: I am trying to show the following:

If $\{ f_n \}$ is a sequence of a.e. real-valued measurable functions in X, and the measure $\mu(X) < \infty$, there exist positive constants $a_n$ such that $\{ f_n / a_n \}$ converges a.e. to zero.

Here is my attempt: if $f_n$ is a.e. real-valued then the set on which it is not real-valued has measure zero. That set can be covered by some collection of open sets with arbitrarily small positive measure (can it?). Let $E_n$ be such an open covering. Then $f_n$ is everywhere real-valued on $X-E_n$. Furthermore, $X-E_n$ is a closed set, so it contains all its limit points. Therefore $f_n$ assumes a maximum value on $X-E_n$ (does it?), so we can choose a constant $a_n$ such that $|f_n| / a_n$ can be made arbitrarily small. Now if, for example, we let $a_n$ be $n$ times the maximum value of $f_n$ and let $E_n$ have measure $2^{-n}$ this sequence converges a.e. to zero.
I feel like there are a bunch of things wrong with this. I think the gist of the proof is that if the function is a.e. real-valued then we can remove the pieces where it isn't real-valued, and then the function will be bounded everywhere else. That's what I'm trying to show, but I'm not sure how. Any hints?
Comment: In general, $f_n$ does not attain its maximum on $X-E_n$. Simply consider $f_n(x)=x$; then $E_n = \emptyset$ and $f_n$ does not attain its maximum on $\mathbb{R} = \mathbb{R}-E_n$.
Comment: @saz Hmm, that's true. Can I somehow use the fact that the measure of $X$ is known to be finite, then?
Answer: Regarding your own thoughts: First of all, if $f_n$ is real-valued, then we can choose a set $F_n$, $\mu(F_n) =0$, such that $\{|f_n|=\infty\} \subseteq F_n$. Since $F:= \bigcup_n F_n$ is still a set of measure zero, we can assume without loss of generality that $|f_n|<\infty$ for all $n \in \mathbb{N}$.
As I already pointed out in my comment, $f_n$ does in general not attain its maximum on $X-E_n$, so your argumentation doesn't work.

Hints:

Show that $$\mu(|f_n| \geq R) \to 0 \qquad \text{as} \, R \to \infty.$$
Deduce from the first step that there exists $R_n$ such that $$\mu\left(|f_n| \geq \frac{R_n}{n} \right) \leq \frac{1}{2^n}.$$ Conclude from $$\sum_{n \geq 1} \mu(|f_n| \geq R_n)$$ and $\mu(X)<\infty$ that $$\frac{|f_n(x)|}{R_n} \leq \frac{1}{n}$$ for $\mu$-almost all $x$ and $n=n(x)$ sufficiently large.


QR and Cholesky decomposition

Question: A while ago I asked for help to develop a polynomial regression model using least squares, where the system was solved by cholesky decomposition, you can check it here Cholesky Polynomial Regression
Now I need to solve the same problem using rather than Cholesky Decomposition the QR decomposition. To save the work of remaking from scratch, I'll just change the parts that change from one procedure to another, then my doubts are
i) The least squares solution obtained through cholesky decomposition and QR decomposition are similar? I ask this because if they are pretty similar I would save a lot of work, making the graphics of various degree polynomials.
ii)The condition number in $A=QR$ decomposition is obtained from $R$ matriz right?
Thanks in advance
Answer: For Q the condition number cond(Q) = 1 since it is orthogonal, this is true for all orthogonal matrices so indeed the cond(A) = cond(QR) = cond(R).
I'm not sure I can answer the other parts of your question however, I hope this helps.
Comment: This helps in parts, thank you.

QR and Cholesky decomposition


pdf files in assets folder in Android application

Question: I am shipping PDF files by placing them in the assets folder of my android application. I am able to read the retieve the filenames using AssetManager. I need to display them on screen and I am able to do that. But I need to open them using a pdfviewer.
To write an intent on onclick() on each item, I need to pass the URI of the PDF file. And using the AssetManager I cannot get the URI of the file. Is there a better way I can handle this whole thing?
Even if we were able to retrieve the URI, can the PDF viewer be able to read the PDF file in the assets folder?
UPDATE:
Based on the suggestion below , I wrote the following code
  try {

                Uri path = Uri.parse("android.resource://com.csg.android.myproject/raw/csgsample")  ;
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setDataAndType(path, "application/pdf");
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

                try {
                    startActivity(intent);
                }
                catch (ActivityNotFoundException e){
                    Toast.makeText(FirstTab.this, "NO Viewer", Toast.LENGTH_SHORT).show();
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

It throws an ActivityNotFoundException with the following exception message:
android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.intent.action.VIEW dat=android.resource://com.csg.android.myproject/assets/pdf/csgsample typ=application/pdf flg=0x4000000 }

I queried the device using PackageManager and I found the Adobe reader installed. But I am not sure why it is throwing this error. I also tried placing this in assets folder instead and then changed the URI accordingly and ran the program but still I end up with the same error.
Answer: You can place them in the res/raw folder, and then create resource URIs to point to them. They are in the form of android.resource://com.example.myapp/raw/my_resource. What I do not know for sure is if other apps such as a PDF reader would be able to open them. Try it out!
Comment: Thanks for the solution. I tried using the URI and it is throwing ActivityNotFoundException. I edited my original post and added code block above. Can you please look at it and help me if possible. Thanks.
Comment: Try adding CATEGORY_DEFAULT, or removing the flag maybe? Your intent looks right, so it might just not be possible for Adobe to read your resources.


How to union with an array and maintain portability?

Question: I am trying to extract a series of 5-bit chunks of data from an array of bytes; or, essentially, read a byte array as if it were an array of 5-bit chunks. An illustration of this idea can be seen below:

Since the least common multiple of 5-bits and 8-bits is 40-bits, I created a union of 8 5-bit chunks and a 5-element byte array as follows:
union Converter {
    struct {
        uint32_t chunk0 : 5;
        uint32_t chunk1 : 5;
        uint32_t chunk2 : 5;
        uint32_t chunk3 : 5;
        uint32_t chunk4 : 5;
        uint32_t chunk5 : 5;
        uint32_t chunk6 : 5;
        uint32_t chunk7 : 5;
    } __attribute__((packed));
    struct {
        uint8_t bytes[5];
    };
};

Note that the value of each chunk will be later stored in a 32-bit unsigned integer, hence a uint32_t is used to store the value of each chunk in the converter. The idea behind this technique is that I can simply read the values for each of the chunks from the first structure and obtain the associated chunk values. In order to assign the byte array to the union, I used the following:
// Create an array of values
uint8_t someArray[5] = {0xff, 0xff, 0xff, 0xff, 0xff};

// Create a coverter
Converter converter;

// Copy the byte array into the converter
std::memcpy(converter.bytes, someArray, 5);

Then the chunk values will be read off as follows:
std::cout << "Chunk 0: " << converter.chunk0 << std::endl;
std::cout << "Chunk 1: " << converter.chunk1 << std::endl;
std::cout << "Chunk 2: " << converter.chunk2 << std::endl;
// Continue to the remaining chunks...

The issue arises with the value of the last chunk: Each of the 0-6 chunks evaluate to 31, which is correct, but the last chunk evaluates to 7. Instead, it should be 31. Looking at the memory (note: I am using an x64 machine, and therefore, little-endian), I see the following values:
Address           0 - 3     4 - 7     8 - B     C - F
000000000024FE20  FFFFFFFF  FF000000  49194000  00000000

Interestingly, if I change the value of the first two blocks of memory (a block being a 4-byte group) to FFFFFFFF FF010000 (changing the second group from FF000000 to FF010000), the value of the last chunk changes from 7 to 15. In order for the value of 31 to be obtained for the last chunk, the two blocks must be set to FFFFFFFF FF070000.
Since 5 bytes and 8 5-bit chunks should directly overlap, assuming no padding, where am I mistaken in my implementation? In this particular case, I am constrained to using C++98 and am attempting to achieve maximal efficiency.
Comment: `std::bitset` perhaps?
Comment: To start with, using unions to "convert" between types is UB.
Comment: The simplest solution is often the best. Use `uint8_t[N]` as your underlying data structure and write an algorithm to extract the ith 5-bit number from it.
Comment: @unseenghost WIth your bit-struct, shifts and mask are used too, it's just that the compiler hides it from you.
Comment: @unseenghost After the usual compiler optimizations, probably there won't be any difference. [To say for sure, a look at the asm output is necessary, which depends not only on the code, but your compiler and flags.]
Comment: I appreciate the suggestion and in other circumstances, I would agree. Unfortunately, I am constrained to using only C++98 compliant code. Apart from this constraint, I am also attempting to achieve the maximum efficiency possible.
Comment: @KerrekSB - Would the overhead of performing shifts and masking add any noticeable inefficiencies? This algorithm is performed often, and therefore, I am trying to make it is efficient as I can. I currently have an implementation similar to what you have mentioned, but I wanted to see if I could squeeze more efficiency from the current solution.
Comment: @unseenghost: What overhead? Those operations have to happen one way or another...
Comment: That's a fair point (about the compiler performing the operations). My focus is: Does me doing it manually induce any overhead above and beyond the logic created by the compiler? I.e., will doing it manually be less efficient than the compiler generated code?
Comment: @deviantfan Thanks. I can look at the generated ASM if need be.
Answer: The bit field format in C++ does not guarantee no padding. It probably refuses to split your five bit chunk across two 32-bit ints with your compiler.
You will need to write your own unmangler.


Preciso atribuir null à uma variável após o uso?

Question: Há a necessidade de atribuir null no objeto após o seu uso?
No exemplo abaixo logo após utilizar a lista eu tenho um método que demanda um grande tempo para ser executado. Eu preciso atribuir null à lista para otimizar a aplicação?
private void Exemplo()
    {
        List<Cliente> listaClientes = ObterClientes();

        foreach (Cliente cliente in listaClientes)
        {
            SalvarClientes(cliente);
        }

        // Preciso fazer isto?
        listaClientes = null;

        FazAlgumaCoisaDemorada();
    }

Answer: A resposta é não, não tem efeito algum na performance.
Se a ideia é libertar memória, também não terá consequência, ela só será libertada quando o GC determinar que é a melhor altura para isso.
Tentar forçar a libertação de memória pode até provocar perdas de performance.
Answer: Nesse caso porque a variável é local, ela é destruída no final do método. Até poderia ser útil se essa lista for muito grande e se esse FazAlgumaCoisaDemorada() precisar de muita memória. Aí é provável que o GC seria acionado em algum momento no meio dele e o ideal é que ele possa liberar o máximo de memória possível. Mas isso é uma circunstância bem específica e rara.
Não faça "por via das dúvidas". Tem que testar e ver se tem vantagem e não causa outros problemas.
Na maior parte dos casos não afetará a performance. Curiosamente anular pode causar algum delay porque fica mais fácil haver uma coleta de lixo, mas será um delay benéfico pela natureza do GC do .NET.
Pode ser útil am algum caso onde a variável é estática ou faz parte de objeto que deve permanecer vivo por muito tempo e não quer manter vivo o objeto que ela se refere, aí é melhor liberar o objeto referenciado. Para fazer isso a forma mais simples é anular a variável.
Quase sempre quando precisa anular uma variável de instância ou estática, é porque algo foi mal arquitetado.
A liberação de memória não ocorre por ocasião do anulação da variável e sim quando o coletor de lixo resolver trabalhar. E por favor, não force sua chamada!


I have written a news web scraper code the error is IndexError: list index out of range and its not resolving

Question: import requests
from bs4 import BeautifulSoup
import pandas as pd

headers = {
    'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36'
}

if __name__ == '__main__':
    # Access the page
    r = requests.get('https://tribune.com.pk/kse-100-index/')

    if r.status_code == 200:
        html = r.text
        soup = BeautifulSoup(html, 'lxml')

    news_date = soup.find_all("span", {"class": "excerpt"})

    news_title = soup.find_all("h2", {"class": "title"})
    # news_title = soup.find_all("div",{"class":"story  cat-0 group-0 position-14 sub-story clearfix"})

    news_description = soup.find_all("p", {"class": "excerpt"})
    date_list = []
    title_list = []
    description_list = []
    # print("Hello world")
    for date in news_date:
        date_list.append(date.text)
    for title in news_title:
        title_list.append(title.text)
    for description in news_description:
        description_list.append(description.text)
    for i in range(30):
        print("Date: ", date_list[i])
        print("Title: ", title_list[i])
        print("Description: ", description_list[i])
        print()

    s1 = pd.Series(date_list[0:30], name='News Date')
    s2 = pd.Series(title_list[0:30], name='News Heading')
    s3 = pd.Series(description_list[0:30], name='News Description')
    df = pd.concat([s2, s3], axis=1)
    df = df.fillna("None")
    # d = {'Phone name': phone_name_list, 'Price per month': price_per_month_list,'Interest List': interest_list, 'Total Price List': total_price_list,'Unlimited Offer List': unlimited_offer_list}
    # df = pd.DataFrame(data=d)
    print(df)
    df.to_csv('tribune1.csv', encoding='utf-8')

It's an Express Tribune web scraper. I want to print the date, headlines and description. When I was running the code previously, there wasn't any error. But after adding the date section, the error appeared.
I would be thankful to you if you could help me resolve the error.
Comment: Please post the full traceback.
Answer: Change this in your code.
if(len(date_list) > 0 ):
    for date in news_date:
        date_list.append(date.text)
    for title in news_title:
        title_list.append(title.text)
    for description in news_description:
        description_list.append(description.text)
    for i in range(max(len(date_list), 30)): # So as to have 30 or less items
        print("Date: ", date_list[i])
        print("Title: ", title_list[i])
        print("Description: ", description_list[i])
        print()
 else:
     print("Not found");

Make sure you have proper indentation.
Comment: you should also make proper indentations.
Comment: BTW: instead of `if(len(date_list) > 0 ):` you can do `if date_list:`
Comment: @AalimHussain share your traceback , what error you are getting add that too in your question.