text:
Q: CodeIgniter - List of files and folders using opendir I'm fairly new to certain programming techniques. Very new to OOP and MVC in general. And I'm pretty sure this is my first StackOverflow question!
I've just downloaded CodeIgniter and have a little project for myself.
I have a list of files and folders on the server and would like to use opendir, readdir and closedir etc to list out them out on a web page in ul's and li's - I've done this in procedural before in a function but have no idea where to even begin with CodeIgniter.
Is there a Helper or Library that already does this? If not, what is the best method? Should I put my code in the model folder?
So confused!

A: I hope you have learned about MVC architecture already in past year :)
Now about your question. This helper or library you have asked for really exists. For the very same "problem" I have used directory helper and its function directory_map('relative/path/to/your/directory'). This function gets recursively content from your directory and sorts it into array like this
    Array
    (
    [banner] => Array
        (
        [0] => banner1.jpg
        [1] => banner2.jpg
        [2] => banner3.jpg
        [3] => banner4.jpg
        )
    [galerie] => Array
        (
        [0] => 0-PB083393.JPG
        [1] => DSCN2897.JPG
        [2] => DSCN2908.JPG
        [3] => DSCN2917.JPG
        [thumb] => Array
            (
                [0] => 0-PB083393_thumb.JPG
                [1] => DSCN2897_thumb.JPG
                [2] => DSCN2908_thumb.JPG
            )
        )
    [0] => mapa.jpg
    )

which is quite neat and you can use it in - for example - foreach cycle and add ul/li tags.
Probably this question is not relevant after one year, but I hope it could help others.

A: Ha. This is funny. I was looking for something else and stumbled on to my first ever CI question without realising it was me :D
I've come so far with CI in just less than a month.
I found Directory Helper - directory_map that basically puts your folder structure in to an array of arrays.
I them created a recursive function in the model that turns it in to a proper drop down menu... And when it's a file, it adds in an a href link to that file.
http://ellislab.com/codeigniter/user-guide/helpers/directory_helper.html

A: If I were doing this, I would:
(1) Create a Library class with a method that takes a directory name and returns an
array of files.
(2) In my controller, I would then load the library and use it to get the list of files for the folder of interest.
(3) I would then load a view while passing the array of file names to the view where
I would assemble the list.
Start by learning how to use the controller to load a view with data (start with a static array).  Then learn how to create the library and integrate with your controller.
You might also read up about CodeIgniter's File Helper library unless you want to use the native PHP functions.
Also, learn about PHP unit testing.
I tend to use models for dealing with data from MySQL databases.  In your case, you are dealing with information about your file system.
Good luck, CI is a good choice for a PHP/MySQL framework!

A: First, welcome to CodeIgniter. It rules. Now...
You need a controller function to actually process the directory, similar to this:
public function dir_to_array($dir, $separator = DIRECTORY_SEPARATOR, $paths = 'relative')
{
    $result = array();
    $cdir = scandir($dir);
    foreach ($cdir as $key => $value)
    {
        if (!in_array($value, array(".", "..")))
        {
            if (is_dir($dir . $separator . $value))
            {
                $result[$value] = $this->dir_to_array($dir . $separator . $value, $separator, $paths);
            }
            else
            {
                if ($paths == 'relative')
                {
                    $result[] = $dir . '/' . $value;
                }
                elseif ($paths == 'absolute')
                {
                    $result[] = base_url() . $dir . '/' . $value;
                }
            }
        }
    }
    return $result;
}

Now you need to call that function to return the results, similar to:
$modules['module_files'] = $this->dir_to_array(APPPATH . 'modules');
This will put the results in a variable called $modules, which you can use in whichever way you want, typically put it in a view like this:
$this->load->view('folder/file', $modules);
If you provide an optional third parameter of TRUE to the load->view function, the result of that view will again be returned for you to use anywhere you like, otherwise it will be echoed out where you call it. The view may look something like this:
<?php

    if (isset($module_files) && !empty($module_files))
    {
        $out = '
';
        foreach ($module_files as $module_file)
        {
            if (!is_array($module_file))
            {

                // the item is not an array, so add it to the list.
                $out .= '
' . $module_file . '
';
            }
            else
            {
                // Looping code here, as you're dealing with a multi-level array.
                // Either do recursion (see controller function for example) or add another
                // foreach here if you know exactly how deep your nested list will be.
            }
        }
        $out .= '
';
        echo $out;
    }

?>

I have not checked this for syntax errors, but it should work fine. Hope this helps..


text:
Q: Set digest_size when using hmac module How to set digest_size here?
hmac.new(b'asdf', b'asdfasdf', hashlib.blake2b).hexdigest()

I've tried this to no effect:
h = hmac.new(b'asdf', b'asdfasdf', hashlib.blake2b)
h.digest_size
64
h.hexdigest()
'ad6ccffb7c84f3f2c39d1426a395bd89d340d00d5f04e2dd02d0467181d2aff961a890cc6beda987ded2c120bf359bf45500fdf6c0d60ce8abe110a8f0696c72'
h.digest_size=16
h.hexdigest()
'ad6ccffb7c84f3f2c39d1426a395bd89d340d00d5f04e2dd02d0467181d2aff961a890cc6beda987ded2c120bf359bf45500fdf6c0d60ce8abe110a8f0696c72'

In a similar vein to this when used with the hashlib module:
hashlib.blake2b(b"asdfasdf", digest_size=16).hexdigest()

redpajama_set_name: RedPajamaStackExchange


text:
Q: Want to stop Photoshop from opening at OS X startup Photoshop opens when I startup my iMac with Yosemite 10.10  I have checked off Open at Login and my System Preferences do not have an Accounts icon in order for me to stop auto login for Photoshop. Photoshop opens anyway.

A: Right click on the photoshop icon in the Dock.
Go to "Options" and uncheck "Open at Login".

A: Do you actually use Photoshop regularly & have it open when you shut down your Mac? It could be that a new feature introduced since Mac OS X 10.7 (Lion) called "Apple Persistence" is getting in the way. To disable it, open up the Terminal by going to Applications -> Utilities -> Terminal and type in this command:
defaults write -g ApplePersistence -bool no

More details can be found here:

One feature which seems to divide the masses is OS X's ability to
  relaunch your applications on startup/reboot. This feature is know as
  Apple Persistence, which is personally a feature I am not really a fan
  of. It's very rare for me to want the same applications on each use of
  my MacBook, asides from the obvious email and unified comms clients of
  course.


text:
Q: How can I resolve the Class type for generic parameter, when the parameter value is being passed as an interface? Consider a method with the following signature:
void foo(List<T> myList) ...

Let's assume, by using reflection, you need to construct such a function and obtain the PropertyInfo details of the T type parameter.  Calling typeof(T).GetProperties(...) should do the trick, so we can add the following line to our method, to obtain these details.
void foo(List<T> myList)
{
    PropertyInfo[] props =
        typeof(T).GetProperties(BindingFlags.Public
            | BindingFlags.Instance
            | BindingFlags.FlattenHierarchy);

    ...
}

This provides the information we need... except when T is an interface parameter, what I'm finding is that props only contains the interface properties and not the properties associated with class that is within the list, which inherits from the interface.
To be clear, my interface AND my class definitions are public, as are the properties within my classes.
How can I get the properties associated with the actual type that inherits an interface rather than strictly the interface properties?

A: If you want the actual type, you probably need to get it for each item:
foreach (T t in myList)
{
    Type itemType = t.GetType();

    itemType.GetProperties(...)
    // etc.
}

You can also add specific code for different types with:
if(itemType == typeof(MyConcreteType))
{
    // do specific stuff for that type
}

A: If you want to get a flat list of all object properties contained inside the List<T>, here's a LINQ solution:
IEnumerable<PropertyInfo> properties =
                          myList.SelectMany(x => x.GetType()
                                                  .GetProperties(BindingFlags.Public |
                                                                 BindingFlags.Instance));

If you need to access the declaring type, you can always look PropertyInfo.DeclaryingType
If you don't want a flat list, Select can do:
IEnumerable<PropertyInfo[]> properties =
                            myList.Select(x => x.GetType()
                                                .GetProperties(BindingFlags.Public |
                                                               BindingFlags.Instance));


text:
Q: Send multiple Iphone notification through APNS without looping I write web services for android and iphone apps in php. Recently in an app I had to send lots of Push notifications(around a few thousand) and realized the only good APNS method available on net by Ray Wenderlich was no more feasible for my purpose.
So I tried to find if there is a way through which I can group multiple device tokens in an array and send all the notifications at once which is quite possible in case of Android's Google Cloud Messaging Service. In it I can group up to 1000 device tokens at once and send them notification at once.
Notification payload remains the same so grouping device token isn't an issue. All I could get was method to loop through the device tokens and send each notification which is no more feasible.
Kindly help me with this. In short I do not want to loop through each token and send individual request. There are 100 questions on stackoverflow and 100 answers but each one uses looping individual token.

A: You can't send to Apple Push Notification Service a single request with multiple device tokens. Their binary format simply does not support this. You will have to send an individual request for each token. If you send all the requests in a single connection, TCP will batch them together for you, which will improve performance. However, there is no way to avoid sending the same payload for each of the device tokens.


text:
Q: XnaSerializer в Monogame Изучая руководство отсюда: XNA Game Programming Adventures
XNA 4.0 RPG Tutorials
В одном из уроков наткнулся на XnaSerializer из
Microsoft.Xna.Framework.Content.Pipeline.Serialization.Intermediate
Однако ни в XNA, ни в Monogame не могу найти это пространство имен.
Подскажите где найти?
A: Ищите в SDK сборку Microsoft.Xna.Framework.Content.Pipeline и подключайте её к проекту в Solution Explorer'е. Но помните:

*

*Эта сборка не включена в XNA Redistributable, поэтому не стоит использовать её в рантайме (только в build time для подготовки контента);

*Эта сборка работает только под Windows, под Xbox и Windows Phone её нет.

Источники: 1, 2


text:
Q: Fourier vs. Laplace Suppose I have an RLC network in a black box, and I bang it hard in the lab to get the impulse response. I have two options now, I can take the Fourier transform or I can take the Laplace transform to get the frequency response. How do I know which one to choose and what is the physical difference between each?
I have been told that the Laplace transform also gives you the transient response or the decay whereas the Fourier transform does not. Is this true? If I suddenly apply a sinusoidal signal at the input, then there should be a transient response for a brief period of time where the output is not a sinusoid until the system settles. Can someone give me a practical example in terms of an RLC network to show how this is true?
Also, often in circuits class, we take the Laplace transform of a circuit where the real part of \$s = \sigma + j\omega\$ is assumed to be zero anyway, so when we use \$\frac{1}{Cs}\$ to denote the Laplace transform of the capacitor, it is assumed that this is equivalent to \$\frac{1}{j\omega C}\$. I believe the real part is zero since the current through the capacitor is 90 degrees out of phase with the voltage across - is this correct? I thought Fourier transform was the same as Laplace transform with \$\sigma = 0\$. However, that does not seem to be true - consider \$x(t) = u(t)\$:
$$\mathcal{F}\{x(t)\} = \int_{-\infty}^\infty{u(t)e^{-j\omega t}}dt = \pi\delta(\omega) + \frac{1}{j\omega} \neq \mathcal{L}\{x(t)\} = \int_0^\infty{e^{-st}dt} = \frac{1}{s}$$
We can see that even if I substitute \$s = j \omega\$ with no real part at the output of the Laplace transform, they are still not equal. How come the Fourier transform has an extra impulse component but Laplace does not? When can I substitute \$s = j\omega\$ and expect the Fourier transform to equal the Laplace transform?
Edit: the latter part of my question has answers here and here.

A: Ok, so you bang a black box made of RLC components and you measure the response - the impulse response.  Now you want to know the frequency response, meaning the response to any sinusoidal.
First of all, you can't really excite your system with a pure sinusoidal.  It's too late, you should have started at the big bang.  The best you can do is use a causal sinusoidal, which has extra frequency components.
But let's say that what you want to know is the response of the system to an arbitrary input in the time domain. You don't really need Fourier or Laplace to know this.  A convolution will do.
What do you have in hand, really?  You measured the impulse response.  Somehow you plotted it out, let's say continuously, as opposed to an ADC that sampled the signal - which is usually what happens, and you'd be asking about the Z-transform vs FFT instead.  Let's also assume that the bang you gave it was a good delta: strong but short.
Since your system is RLC, it is linear, so superposition principles work (we wouldn't be talking about this otherwise anyway).  Any input can be constructed by adding attenuated impulses offset in time (sort of - it's a limit thing).  So the total response is just adding all these individual responses together.  This addition is exactly what the convolution input(t)*impulseResponse(t) does.  You could consider the RLC system as a "hardware convoluter".  This is probably the most accurate way of predicting a response to an arbitrary input.
Now I want to clarify something, which is how Laplace relates to Fourier.  Our domain is causal functions, since it doesn't make sense to compare the unilateral Laplace with Fourier otherwise.  Besides, all real signals are causal.    Mathematically, the Laplace transform is just the Fourier transform of the function pre-multiplied by a decaying exponential.  It is that simple.  So if a Fourier transform doesn't exist because the integrals are infinite, Laplace may still exist if the decaying exponential is strong enough, because the intergral of the 'attenuated' function would converge.  From a mathematical standpoint, this can be extremely useful in certain cases.
But what you really may want is to make a control system for your plant.  In that case, what you do is inspect the response and then approximate it with a 1st or 2nd order model plus group delay.  So it won't be exact, but by doing this you ditch all the little details of the actual response, and gain the enormous advantage of being able to plug this model onto control equations and algorithms and dozens of books' worth of control theory knowledge and design and simulate  your control system.  In that case, you'd use a Laplace model, since immediately get poles and zeroes that can be used for stability analysis.

A: The Fourier and the Laplace transform are not the same. First of all, note that when we talk about the Laplace transform, we very often mean the unilateral Laplace transform, where the transformation integrals starts at \$t=0\$ (and not at \$t=-\infty\$), i.e. with the Laplace transform we usually analyze causal signals and systems. With the Fourier transform this is not always the case.
In order to understand the differences between the two, it is important to look at the region of convergence (ROC) of the Laplace transform. For causal signals, the ROC is always a right-half plane, i.e. there are no poles (of a rational function in \$s\$) to the right of some value \$\sigma_0\$ (where \$\sigma\$ denotes the real part of the complex variable \$s\$). Now if \$\sigma_0<0\$, i.e. if the \$j\omega\$ axis is inside the ROC, then you simply obtain the Fourier transform by setting \$s=j\omega\$. If \$\sigma_0>0\$ then the Fourier transform does not exist (because the corresponding system is unstable). The third case (\$\sigma_0=0\$) is interesting because here the Fourier transform does exist but it cannot be obtained from the Laplace transform by setting \$s=j\omega\$. Your example is of this type. The Laplace transform of the step function has a pole at \$s=0\$, which lies on the \$j\omega\$ axis. In all such cases the Fourier transform has additional \$\delta\$ impulses at the pole locations on the \$j\omega\$ axis.
Note that it is not true that the Fourier transform cannot deal with transients. This is just a misunderstanding which probably comes from the fact that we often use the Fourier transform to analyze the steady-state behavior of systems by applying sinusoidal input signals that are defined for \$-\infty<t<\infty\$. Please also see this answer to a similar question.


text:
Q: Math finance question In a stationary population of 120, 000 lives, the number of deaths is 2000 annually. The complete expectation of life for a 40-year-old is 30 years. 60% of the population is under age 40.
What is the average age at death for an individual in this population?
What is the average age at death for an individual who dies before age 40?
I know the answer for the average age at death for an individual in this population is supposed to be 60. I am not sure how to get this though. Is it because if I start with 120000 and subtract 2000 each year that an individual lives but then multiple its by a percentage, thats how I get it?
For the average age at death for an individual that dies before 40, I know the answer should be 20. Do I get this by doing the same as the first part but multiple my 60% because 60% is under age 40?
Thank you

A: Average life expectancy at birth is $\frac{120000}{2000} = 60$ because of the stationary population

The number of people aged over $40$ is $0.4 \times 120000 = 48000$
Since they live an average of $30$ years beyond $40$, there must be $\frac{48000}{40} = 1600$ of them arriving at age $40$ each year, and a total of $1600 \times (30+40)=112000$ of them in the population, of which $48000$ are over $40$ and $64000$ are under $40$ at any one time
So $2000-1600=400$ are born each year who will die before $40$ and there are $120000 -112000 = 8000$ of them in the population at any one time.  The average life expectancy at birth for an individual who dies before age $40$ is therefore $\frac{8000}{400}= 20$


text:
Q: Firebase retrieving multiple objects in multiple nodes I am trying to read data from a firebase realTime database in android
(For some reason FireBase sorts the location data and then the VideoEntry but I think it's correct anyway...according to the json generated)
In case you needed this is how I add the nodes:
    submitVideoButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String locationName = locationInput.getText().toString();
                    double lat = Double.parseDouble(latInput.getText().toString());
                    double lon = Double.parseDouble(longInput.getText().toString());

                    String userid = mFirebaseUser.getEmail().substring(0, mFirebaseUser.getEmail().indexOf("@"));
                    String cleanUserId = userid.replaceAll("\\W", "");
                    updateUserInfo(cleanUserId, mFirebaseUser.getEmail(), "nsaofdhiqo3", locationName, lat, lon);
                }
            });

        }

        private void updateUserInfo(String userId, String email, String videoId, String locName, double lat, double lon) {
            LocationData location = new LocationData(locName,lat,lon);
            VideoEntry videoEntry = new VideoEntry(videoId,location);
            UserData user = new UserData(email, videoEntry);

            mDatabaseRef.child("users").child(userId).setValue(user);
        }

    {
      "users" : {
        "valentinogiuseppe00" : {
          "mName" : "valentino.giuseppe00@gmail.com",
          "mVideoEntry" : {
            "mLocationData" : {
              "mLatitude" : 58,
              "mLongitude" : 10,
              "mName" : "locationName"
            },
            "mVideoId" : "nsaofdhiqo3"
          }
        }
      }
    }

This is what I tried so far:
    databaseRef.addChildEventListener(new ChildEventListener() {
                @Override
                public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
                    double lat = 0.0, lon = 0.0;
                    String locName = null;
                    String fVideoId = null, videoName = null;
                    String userName = null;

                    //TODO Need to re-structure the  to add markers
                    for (DataSnapshot userSnapshot : dataSnapshot.getChildren()) {
                        Log.d(TAG, "userSnapShot children #:" + userSnapshot.getChildrenCount());
                        userName = userSnapshot.child(cleanUserId).getValue(String.class);
                        for (DataSnapshot videoSnapShot : dataSnapshot.getChildren()) {
                            Log.d(TAG, "videoSnapShot children #:" + videoSnapShot.getChildrenCount());
                            fVideoId = videoSnapShot.child("videoId").getValue(String.class);
    //                        videoName = videoSnapShot.child("").getValue(String.class);
                            for (DataSnapshot locationSnapShot : dataSnapshot.getChildren()) {
                                Log.d(TAG, "locationSnapShot children #:" + (locationSnapShot.getChildrenCount()));
                                lat = locationSnapShot.child("mLatitude").getValue(Double.class);
                                lon = locationSnapShot.child("mLongitude").getValue(Double.class);
                            }
                        }
                    }
                }

Please let me know if you need something else from me.
I am missing something little since I can see the map that gets generated and all the value within
Thanks fellow Devs

A: if you want to get all the values inside mVideoEntry with the data of mLocationData
do this
Create a new class that will be your pojo object this will be called userPojo.class
public class UserPojo {

   private long mLatitude;
   private long mLongitude;
   private String mName;

    public long getmLatitude() {
        return mLatitude;
    }

    public void setmLatitude(long mLatitude) {
        this.mLatitude = mLatitude;
    }

    public long getmLongitude() {
        return mLongitude;
    }

    public void setmLongitude(long mLongitude) {
        this.mLongitude = mLongitude;
    }

    public String getmName() {
        return mName;
    }

    public void setmName(String mName) {
        this.mName = mName;
    }

}

then just in your reference iterate inside mVideoEntry child and get your values
databaseRef.child("users").child("valentinogiuseppe00").child("mVideoEntry").addValueEventListener(new ValueEventListener() {
  @Override
  public void onDataChange(DataSnapshot dataSnapshot) {

    for(DataSnapshot snapShot : dataSnapshot.getChildren()){
    UserPojo user= snapShot.getValue(UserPojo.class);
    //Getting your values
     long longitude = user.getmLongitude();
     long latitude = user.getmLatitude();
     String name = user.getmName();
     Log.e("Data: " , "" + latitude + "" + longitude + "" + name);
     }
  }

  @Override
  public void onCancelled(DatabaseError databaseError) {
    System.out.println("The read failed: " + databaseError.getCode());
  }
});

with this you should be able to get all your mLocationData inside each mVideoEntry


text:
Q: Making a linked list iterable in ES6 I have a linked list in JavaScript that I need to make iterable with a for of loop. I have almost done it but there seems to be no way to get the first value included in the result. Here is a simplified version:
var obj = {value: 1, next: {value: 2, next: {value: 3, next: {value: 4, next: {value: 5, next: {value: 6, next: {value:7, next: null}}}}}}};

obj[Symbol.iterator] = function() {
  var current = this;
  return {
    next() {
      if (current.next !== null) {
        current = current.next;
        return {value: current.value, done: false};
      }
      return {done: true}
    }
  }
}

for (const x of obj) {
  console.log(x)
}

// this is how you get the values printed with no loop
// console.log(obj.value + '->' + obj.next.value + '->' + obj.next.next.value)

A: The problem is you're moving current to the next node before retrieving the value.

var obj = {value: 1, next: {value: 2, next: {value: 3, next: {value: 4, next: {value: 5, next: {value: 6, next: {value:7, next: null}}}}}}};

obj[Symbol.iterator] = function() {
  var current = this;
  return {
    next() {
      if (current) {
        var value = current.value;
        current = current.next;
        return {value: value, done: false};
      }
      return {done: true};
    }
  };
};

for (const x of obj) {
  console.log(x);
}

It's much easier to implement an iterator with a generator function.

var obj = {value: 1, next: {value: 2, next: {value: 3, next: {value: 4, next: {value: 5, next: {value: 6, next: {value:7, next: null}}}}}}};

obj[Symbol.iterator] = function*() {
  var current = this;
  while (current) {
    yield current.value;
    current = current.next;
  }
};

for (const x of obj) {
  console.log(x);
}

A: You should be testing for current, not current.next:
obj[Symbol.iterator] = function() {
  var current = this;
  return {
    next() {
      if (current !== null) {
        var res = {value: current.value, done: false};
        current = current.next;
        return res;
      } else {
        return {done: true};
      }
    }
  };
}

But can write it much simpler as a generator method:
obj[Symbol.iterator] = function* () {
  for (var current = this; current !== null; current = current.next) {
    yield current.value;
  }
}

Btw, I would recommend not putting this iterator on every node of the list (or even on the first one). Put in on a separate object that points to the head of the list, or make it a static helper function:
let list = {
  head: obj, // could be null either
  *[Symbol.iterator]() {
    for (var current = this.head; current !== null; current = current.next) {
      yield current.value;
    }
  }
}

function* linkedList(head)
  for (; head !== null; head = head.next) {
    yield head.value;
  }
}


text:
Q: How to design key schema to have only one DynamoDB table per application? According to DynamoDB doc: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/bp-general-nosql-design.html
"You should maintain as few tables as possible in a DynamoDB application. Most well designed applications require only one table."
But according to my experience you always have to do the opposite thing due to partition key design.
Let's consider the next situation. We have several user roles, for example, "admin", "manager", "worker". Usual workflow of an admin is to CRUD manager data, where read operation is to get not one manager but all manager list. The same is for the manager - he CRUDs worker data.
We have only two scenarios of key usage for both cases:

*

*get a list of all items (item key doesn't matter)

*work with a particular item using its full key.

Naturally we should have uniformly distributed partition key (as the doc emphasises) so we can't select user role for it and should use user id. Since we already have as partition key some random id, we don't need sort key at all since it simply doesn't work - we already access exectly one user by only using the partition key part. At this point we realize that user id is working like a charm for CUD operations but for every R operation we need to scan all the table and then filter the result by user role which is ineffective. How can this be improved? Very naturally - let's just have own table for each user type! Then we will scan for manager list from admin API and for worker list from the manager one.
I use DynamoDB almost for a year and still can't get it. For me the reality is that for real life scenarios sort key is something that you can never use (the only real case for it I had was to access items like "agreements" that belong to the two users of different types the same time, so the primary key was { partion: "managerId", sort: "userId" } and secondary global index was { partition: "userId", sort: "managerId" } so I could effectively query for all particualar manager agreement list or all particular user agreement list providing only corresponding manger or user id for the query. The approach is discussed in doc here: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/bp-adjacency-graphs.html).
I feel that I don't understand the concept at all. What can be an effective way of key schema for provided example to use only one DynamoDB table for both user types?

A: It sounds like what you need in this case is a Global Secondary Index (https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GSI.html) where the partition key is the user role. That way, you can query all users with a particular role through that UserRoleIndex and, with the help of a sort key on the user ID, single out one particular user within that role.
Alternatively, if you are starting from scratch with a new table, you might not even need an index (unless you don't know the role of a user when you delete them). You can use a "composite primary key" (https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.CoreComponents.html#HowItWorks.CoreComponents.PrimaryKey) where the partition key and the sort key would be the same as in the index I am suggesting above.
Using the same notation that you used in your question, I would recommend { partition: "userRole", sort: "userId" }.
DynamoDB can be hard to understand sometimes and there definitively are cases where a traditional SQL database makes more sense. This video from AWS re:Invent 2018 is great to understand the difference between the two: https://www.youtube.com/watch?v=HaEPXoXVf2k&feature=youtu.be.
In your case, though, it looks like you have a very clear access pattern, so DDB would work for you.

A: you can have a schema like
user_id, role, <other columns>

where

*

*user_id = hash-key

*role = GSI hash-key

This way, you can read and get all managers' list by querying the GSI
With GSI, DynamoDb creates another table and maintains it ,so you don't need to maintain multiple tables.
let me know if you have any questions


text:
Q: Simple Ajax Call to MVC method always returns error I have a very simple ajax call to an MVC method and it always return an error with a blank responseText.  I have called and used ajax for many years and cannot seem to figure what is causing this:
here is the js code:
 $.ajax({
    url: "/Mobile/MyMVCMethod",
    data: null,
    type: "POST",
    dataType: 'html',
    success: function (data) {
        alert("test");
    },
    error: function (request, status, error) {
        alert(status);
        alert(request.responseText);
        alert(error);
    }
});

here is my C#:
[HttpPost]
public string MyMVCMethod()
{
    return "test";
}

the code makes it to method but return an error with no details
I have tried ActionResult because I wanted to return a PartialView but since it was not working I tried to narrow it down and find out if will work with just a string.  THis is happening even if the C# was this:
[HttpPost]
public ActionResult MyMVCMethod()
{
    return PartialView("MyView");
}

MyView:

hello world

Now I see an error in Ajax " Resource Not Found"  even though it executed the MVC method

A: $.ajax({
        url:"Mobile/MyMethod",
        method:"post",
         datatype:"json"
}).done(function( data ) {
    alert( "Data " + data );
  });

and make sure call only normal method not action result.then try it may it will work for you


text:
Q: Route specific layer 2 traffic output to another interface Supposing I have 1 interface (wlan0) and 1 virtual interface (wlan0:0).
What I want is to route specific layer 2 traffic (arp request only for example) from wlan0 to wlan0:0
My problem is very similar to the following question, but for layer 2:
Only allow certain outbound traffic on certain interfaces


text:
Q: Restore default working dir if bat file is terminated abruptly I have a scenario where during execution of a batch file, it navigates to a different folder (say to "../asdf"); and at the end of execution it will set the current working dir as the same folder from where the user called the .bat file.
But if the user terminates the batch processing before it is complete, the cmd show the current working dir (say "../asdf").
But in my case, I need to restore the working dir to the default/predefined one. Is it possible?

*

*Batch file is written by me, so I can modify it.

*CMD is opened through a desktop shortcut to CMD, which I have control of; so properties like working dir or passing args to CMD etc can be done there.

A: In your batch script use setlocal to encapsulate the running environment of your batch session.  If the user terminates the script before you cd or popd to return, your script will still exit in the directory in which it started.  Here's a brief test:
@echo off
setlocal
pushd c:\Users
cd
exit /b

Output:
C:\Users\me\Desktop>test.bat
c:\Users

C:\Users\me\Desktop>

Notice I didn't popd or cd %userprofile%\Desktop, but I still ended up back at my Desktop after the script exited.
Additionally, setlocal keeps you from junking up your environment with orphaned variables that mean nothing outside of your batch script.  It's just good practice.  At the console, type help setlocal for more info.


text:
Q: React ternary operator displays ":" block first. Why? I have a simple react app where a current user from firebase is passed into a Header component. If the user is signed in, I want to display the "SIGN-IN" link, and if they aren't, a "SIGN OUT" link. The code works however if a user is signed in, it first displays "SIGN-IN" then switches to "SIGN OUT" rather than just only displaying "SIGN OUT". The switch is painfully obvious when first loading the page. How can I make it never display the sign in if the user is signed in?
Header:
const Header = ({ currentUser }) => {
    return (

            <ReactSVG src={crown}/>

                <Link to="/shop">SHOP</Link>
                <Link to="/contact">CONTACT</Link>
                {
                    currentUser ?
 auth.signOut()}>SIGN OUT

                                : <Link to="/sign-in">SIGN-IN</Link>
                }
                <Link to="/cart">CART</Link>

    )
}
export default Header;

App:
class App extends Component {
    constructor() {
        super();
        this.state = {
            currentUser: null
        }
    }

    componentDidMount() {
        auth.onAuthStateChanged(user => {
            this.setState({ currentUser: user});
            console.log(user);
        });
    }

    componentWillUnmount() {
        auth.signOut();
    }

    render() {
        return (
            <>

                <Switch>
                    <Route exact path="/" component={HomePage}/>
                    <Route path="/sign-in" component={CredentialsPage}/>
                    <Route path="/shop" component={ShopPage}/>
                    <Route path="/shop/hats" component={Hats}/>
                    <Route path="/shop/jackets" component={Jackets}/>
                    <Route path="/shop/sneakers" component={Sneakers}/>
                    <Route path="/shop/womens" component={Womens}/>
                    <Route path="/shop/mens" component={Mens}/>
                </Switch>
            </>
        )
    }
}
export default App;

A: Both onAuthStatedChanged and setState are asynchronous.
Your initial state is currentUser: null. this is what renders first. only then, after the async calls resolves the state includes your currentUser. If you want to prevent the lag you should keep track of the state of fetching and defer the rendering of that component (maybe with an indicator or display nothing)

A: You should keep a flag to check if data is received from server. isLoadComplete variable represents if data is loaded from server or not.
{
       isLoadComplete && {  currentUser ?
 auth.signOut()}>SIGN
       OUT
: <Link to="/sign-in">SIGN-IN</Link>}
}


text:
Q: JMS MQ Implement retry logic without throwing exception I have a JMSReceiver class which is listening on a MQ Queue. This class implements the MessageListener interface. I wish to implement the logic to retry a message for specified number of times by getting the message to rollback. To do so I have to catch the business exception and wrap it in a RuntimeException so that message gets rolled back to the MQ and gets replayed. i wish to implement this in better way.
Current Implementation
class JMSReceiver implements MessageListener{
public void onMessage(Message msg){
        logger.info("**********Message received in consumer");
         try {
             //Do some business which throws a business exception
         } catch (Exception e) {
            try {
                logger.info("####Redelivery count"+msg.getIntProperty("JMSXDeliveryCount"));
                if(msg.getIntProperty("JMSXDeliveryCount")<10){
                    logger.info("####MQ ISSUE: Redelivery attempted for message. Redelivery attempt: "+msg.getIntProperty("JMSXDeliveryCount"));
                    throw new RuntimeException("Redelivery Attempted"+e.getMessage());
                }else{
                    logger.info("####MQ ISSUE: Redelivery attempts exhausted for message");
                }
            } catch (JMSException e1) {
                e1.printStackTrace();
                logger.info("####MQ ISSUE: Exception occured while getting JMSXDeliveryCount");
             }
      }
     }

Expected
The above implementation works. It rollsback the message to MQ and the redelivery count increases. I even tried doing session.rollback() but when I do that the redelivery count does not increase and I can replay the message. Please advise a better way to implement this ?

A: You can create JMS session with CLIENT_ACKNOWLEDGE as message acknowledge mode. And then in the onMessage() method, do not call msg.Acknowledge(). Not calling msg.Acknowledge() will ensure the same is delivered again.
session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);

Note that calling Acknowledge() on one message will acknowledge all messages received since the last time the method was called.
Update
Session creation
    connection = cf.createConnection("user","password");
    System.out.println("Connection created.");
    session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
    System.out.println("Session created.");

OnMessage() method - Message is being acknowledged on 6th attempt.
    consumer.setMessageListener(new MessageListener() {
      public void onMessage(Message msg) {
        try {
            // Display the message that just arrived
            System.out.println(msg);

            if(msg.getIntProperty("JMSXDeliveryCount") > 5){
                msg.acknowledge();
            }
        } // end try
        catch (Exception e) {
          System.out.println("Exception caught in onMessage():\n" + e);
        }
        return;
      } // end onMessage()
    }); // end setMessageListener


text:
Q: sub string python pandas I have a pandas dataframe that has a string column in it. The length of the frame is over 2 million rows and looping to extract the elements I need is a poor choice. My current code looks like the following
for i in range(len(table["series_id"])):
    table["state_code"] = table["series_id"][i][2:4]
    table["area_code"] = table["series_id"][i][5:9]
    table["supersector_code"] = table["series_id"][i][11:12]

where "series_id" is the string containing multiple information fields I want to create an example data element:
columns:
 [series_id, year, month, value, footnotes]

The data:
[['SMS01000000000000001' '2006' 'M01' 1966.5 '']
 ['SMS01000000000000001' '2006' 'M02' 1970.4 '']
 ['SMS01000000000000001' '2006' 'M03' 1976.6 '']

However series_id is column of interest that I am struggling with. I have looked at the str.FUNCTION for python and specifically pandas.
http://pandas.pydata.org/pandas-docs/stable/basics.html#testing-for-strings-that-match-or-contain-a-pattern
has a section describing each of the string functions i.e. specifically get & slice are the functions I would like to use. Ideally I could envision a solution like so:
table["state_code"] = table["series_id"].str.get(1:3)

or
table["state_code"] = table["series_id"].str.slice(1:3)

or
table["state_code"] = table["series_id"].str.slice([1:3])

When I have tried the following functions I get an invalid syntax for the ":".
but alas I cannot seem to figure out the proper way to perform the vector operation for taking a substring on a pandas data frame column.
Thank you

A: I think I would use str.extract with some regex (which you can tweak for your needs):
In [11]: s = pd.Series(["SMU78000009092000001"])

In [12]: s.str.extract('^.{2}(?P<state_code>.{3}).{1}(?P<area_code>\d{4}).{2}(?P<supersector_code>.{2})')
Out[12]:
  state_code area_code supersector_code
0        U78      0000               92

This reads as: starts (^) with any two characters (which are ignored), the next three (any) characters are state_code, followed by any character (ignored), followed by four digits are area_code, ...


text:
Q: C#.NET - How to inherit from an existing windows forms control I'm used to working in visual C++. In learning C#.NET I tend to try to find equivalent methods to how things are done in VC++.
When I have a button in C++, to get full control over it I create a class derived from CButton (the equivalent of System.Windows.Forms.Button in .NET) and then set this class as the type for my button in order to get all events and overrides routed into my code.
In C# I haven't really found an equivalent way to do this. There seems to be no way to set which class a control should be created from, and I haven't even bothered trying to replace the auto-generated code where the object is created since it is likely to be discarded the next minute.
What's the correct way of using my own class to front a user control?
EDIT: I should clarify that I'm interested in adding my custom class to the existing project. Most of the responses so far either provide non working ways of adding it to the existing project, or working ways of creating an external library with the component (DLL), but that's a bit overkill for my particular case.

A: There isn't any trick to it. Create a new .cs source file or class using Visual Studio, remember to include the proper using System.Windows.Forms statement at the top of the file, then inherit as you normally would (note: in .NET, there are no classes with the naming convention CWhatever).

A: If you derive from System.Windows.Forms.Button, for instance, your new control will be available in the toolbox.  A new tab should appear at the top and will be named [Project Name] Components. You can just drag and drop it on a form.
As far as changing the type of a control already on a form, I've had success with changing the type in the designer generated code .cs file.
Here's a great article on creating custom .net controls:
The article discusses evey possible scenario, including using inheritance, and provides lots of sample code.
EDIT:
Add this to your project:
public class DerivedTextBox: System.Windows.Forms.TextBox
{
}

And then build the project.  DerivedTextBox should then be available in the ToolBox.

A: You may either override the functions you need with your own code, or simply create a new user control which derives from the System.Windows.Forms.Button.
It depends on if you need to create a new control which will be used many times or if this is something you need to do for specific cases only.
Edit: Have a look at the MSDN documentation:
http://msdn.microsoft.com/en-us/library/5h0k2e6x(VS.71).aspx

A: abstract class MyClass :  Windows.Form
{
....
}

public class WindowsFormClass : MyClass
{
....
}

Similary you can create any custom class and derive it from the Control Class (Button, Textbox, Grid etc.), override its methods to add your functionality, and then create a custom object out of it. It will available to you in the toolbox and you can start using it in your project.


text:
Q: How to change header formatting in Flutter table_calendar package I have the following calendar and code. How can I  have the month be only 3 letters eg Nov 2021 instead of November 2021.

 Container(
      height: MediaQuery.of(context).size.height*0.3,
      // width: MediaQuery.of(context).size.width*0.3,
      color: Colors.white,
      child: TableCalendar(
        headerStyle: HeaderStyle(
          titleTextStyle: TextStyle(fontSize: 12)
        ),
      shouldFillViewport: true,
      rowHeight:MediaQuery.of(context).size.height*0.02,
      firstDay: DateTime.utc(2010, 10, 16),
      lastDay: DateTime.utc(2030, 3, 14),
      focusedDay: DateTime.now(),
      onDaySelected: (selectedDay, focusedDay) {
        if (!isSameDay(_selectedDay, selectedDay)) {
          // Call `setState()` when updating the selected day
          setState(() {
            _selectedDay = selectedDay;
            _focusedDay = focusedDay;
          });
        }
      }
        ),
    ),

A: I achieved a responsive table with the customisation I wanted using this code:
 Container(
          height: MediaQuery.of(context).size.height*0.3,
          color: Colors.white,
          child: TableCalendar(
            calendarStyle: CalendarStyle(
              todayTextStyle: TextStyle(fontSize: MediaQuery.of(context).size.width*0.008,color: Colors.white),
              weekendTextStyle: TextStyle(fontSize: MediaQuery.of(context).size.width*0.008),
              outsideTextStyle: TextStyle(fontSize: MediaQuery.of(context).size.width*0.008),
              defaultTextStyle: TextStyle(
                  fontSize: MediaQuery.of(context).size.width*0.008
              )
            ) ,
            headerStyle: HeaderStyle(
              titleCentered: true,
              titleTextFormatter: (date, locale) => DateFormat.yMMM(locale).format(date),
              formatButtonVisible: false,
              titleTextStyle: TextStyle(fontSize: MediaQuery.of(context).size.width*0.007)
            ),
          shouldFillViewport: true,
          rowHeight:MediaQuery.of(context).size.height*0.02,
          firstDay: DateTime.utc(2010, 10, 16),
          lastDay: DateTime.utc(2030, 3, 14),
          focusedDay: DateTime.now(),
          onDaySelected: (selectedDay, focusedDay) {
            if (!isSameDay(_selectedDay, selectedDay)) {
              // Call `setState()` when updating the selected day
              setState(() {
                _selectedDay = selectedDay;
                _focusedDay = focusedDay;
              });
            }
          }
            ),
        ),

A: as new table_calender 3.0.8 to disable two weeks/format button you can set
availableCalendarFormats: const {
  CalendarFormat.month : 'Month'
}

and to center the title you also need to set up
headerStyle: HeaderStyle(
 titleCentered: true
)

A: To remove 2 weeks use different calendarFormat
To change Header titile use titleTextFormatter
And finally play with PositionedOffset to control positions.
** Everything that is possible to change is documented here: https://pub.dev/documentation/table_calendar/latest/table_calendar/table_calendar-library.html


text:
Q: How do you debug inability to delete a Namespace after ip netns add test cgroup on /sys/fs/cgroup/freezer type cgroup (rw,nosuid,nodev,noexec,relatime,freezer)
cgroup on /sys/fs/cgroup/cpu,cpuacct type cgroup (rw,nosuid,nodev,noexec,relatime,cpu,cpuacct)
cgroup on /sys/fs/cgroup/pids type cgroup (rw,nosuid,nodev,noexec,relatime,pids)
systemd-1 on /proc/sys/fs/binfmt_misc type autofs (rw,relatime,fd=34,pgrp=1,timeout=0,minproto=5,maxproto=5,direct,pipe_ino=9430)
mqueue on /dev/mqueue type mqueue (rw,relatime)
debugfs on /sys/kernel/debug type debugfs (rw,relatime)
hugetlbfs on /dev/hugepages type hugetlbfs (rw,relatime)
tmpfs on /run/user/0 type tmpfs (rw,nosuid,nodev,relatime,size=401072k,mode=700)
tmpfs on /run/netns type tmpfs (rw,nosuid,noexec,relatime,size=401076k,mode=755)
nsfs on /run/netns/test type nsfs (rw)

root@localhost:~# ip netns delete test
Cannot remove namespace file "/var/run/netns/test": Device or resource busy
root@localhost:~# umount --force /run/netns/test
umount: /run/netns/test: not mounted

netns       20            root  cwd       DIR               8,17     4096          2 /
netns       20            root  rtd       DIR               8,17     4096          2 /
netns       20            root  txt   unknown                                        /proc/20/exe

root        20  0.0  0.0      0     0 ?        S<   06:11   0:00 [netns]
root        21  0.0  0.0      0     0 ?        S    06:11   0:00 [khungtaskd]

What do I do to  fix this? It looks like netns is the only user of that mountpoint? Should/Can I kill the thread?

A: Check which process is using the namespace with fuser
fuser /var/run/netns/test

It will output a list of numbers that represent the process IDs that are using that resource.  Each process ID can then be checked using the ps command:
ps -p 123


text:
Q: Can't create handler inside threads that has not called looper? I want to send a notification after 5 seconds.
I found this code example to do something after 5 seconds, but I just can set a Log.e().
The Notification method is also working. But if I want to call the method setNotification(), I get a RuntimeError after 5 seconds:

Can't create Handler inside Thread that has not called looper.prepare().

I found very much help, but nothing works.   So I hope you can help me.
public class Reminder {
    Timer timer;

    public Reminder(int seconds) {
        timer = new Timer();
        timer.schedule(new RemindTask(), seconds * 1000);
    }
}

class RemindTask extends TimerTask {
    public void run() {
        todo_list rem = new todo_list();
        rem.setNotification("Todo!", false, 1);
    }
}

public class todo_list extends ListActivity {
    public void onCreate(Bundle savedInstanceState) {
        new Reminder(5);
    }

    public void setNotification(String text, boolean ongoing, int id) {}

}

A: You need to call rem.setNotification from a thread which will keep running always.  One way is to use runonuithread
runonUithread(new Runnable(){
    run(){
        rem.setNotification("Todo!",false,1);
    }
});

A: You'll get this error when you execute some code that shouldn't be done in another thread than the UI thread. So simple get an activity object and call runOnUiThread(Runnable action) {} on it. Place that code that generates the error in the Runnable.
I hope this helps.


text:
Q: Spark Dataframe - Method to take row as input & dataframe has output I need to write a method that iterates all the rows from DF2 and generate a Dataframe based on some conditions.
Here is the inputs DF1 & DF2 :
val df1Columns = Seq("Eftv_Date","S_Amt","A_Amt","Layer","SubLayer")
val df2Columns = Seq("Eftv_Date","S_Amt","A_Amt")
var df1 = List(
      List("2016-10-31","1000000","1000","0","1"),
      List("2016-12-01","100000","950","1","1"),
      List("2017-01-01","50000","50","2","1"),
      List("2017-03-01","50000","100","3","1"),
      List("2017-03-30","80000","300","4","1")
    )
      .map(row =>(row(0), row(1),row(2),row(3),row(4))).toDF(df1Columns:_*)

+----------+-------+-----+-----+--------+
| Eftv_Date|  S_Amt|A_Amt|Layer|SubLayer|
+----------+-------+-----+-----+--------+
|2016-10-31|1000000| 1000|    0|       1|
|2016-12-01| 100000|  950|    1|       1|
|2017-01-01|  50000|   50|    2|       1|
|2017-03-01|  50000|  100|    3|       1|
|2017-03-30|  80000|  300|    4|       1|
+----------+-------+-----+-----+--------+

val df2 = List(
  List("2017-02-01","0","400")
).map(row =>(row(0), row(1),row(2))).toDF(df2Columns:_*)

+----------+-----+-----+
| Eftv_Date|S_Amt|A_Amt|
+----------+-----+-----+
|2017-02-01|    0|  400|
+----------+-----+-----+

Now I need to write a method that filters DF1 based on the Eftv_Date values from each row of DF2.
For example, first row of df2.Eftv_date=Feb 01 2017, so need to filter df1 having records Eftv_date less than or equal to Feb 01 2017.So this will generate 3 records as below:
Expected Result :
+----------+-------+-----+-----+--------+
| Eftv_Date|  S_Amt|A_Amt|Layer|SubLayer|
+----------+-------+-----+-----+--------+
|2016-10-31|1000000| 1000|    0|       1|
|2016-12-01| 100000|  950|    1|       1|
|2017-01-01|  50000|   50|    2|       1|
+----------+-------+-----+-----+--------+

I have written the method as below and called it using map function.
def transformRows(row: Row ) = {
  val dateEffective = row.getAs[String]("Eftv_Date")
  val df1LayerMet    =  df1.where(col("Eftv_Date").leq(dateEffective))
  df1 = df1LayerMet
  df1
}

val x = df2.map(transformRows)

But while calling this I am facing this error:
Error:(154, 24) Unable to find encoder for type stored in a Dataset.  Primitive types (Int, String, etc) and Product types (case classes) are supported by importing spark.implicits._  Support for serializing other types will be added in future releases.
val x = df2.map(transformRows)

Note : We can implement this using join , But I need to implement a custom scala method to do this , since there were a lot of transformations involved. For simplicity I have mentioned only one condition.

A: Seems you need a non-equi join:
df1.alias("a").join(
    df2.select("Eftv_Date").alias("b"),
    df1("Eftv_Date") <= df2("Eftv_Date")          // non-equi join condition
).select("a.*").show
+----------+-------+-----+-----+--------+
| Eftv_Date|  S_Amt|A_Amt|Layer|SubLayer|
+----------+-------+-----+-----+--------+
|2016-10-31|1000000| 1000|    0|       1|
|2016-12-01| 100000|  950|    1|       1|
|2017-01-01|  50000|   50|    2|       1|
+----------+-------+-----+-----+--------+


text:
Q: Failed importing: Attribute "name" was already specified for element "option" <joblist>
  <job>
    <context>
      <options preserveOrder='true'>
        <option name='PDATE' value='${DATE:yyyyMMdd}' />
        <option name='TSTAMP' value='${DATE:yyyy-MM-dd'T'HH.mm.ssXX}' />
      </options>
    </context>
    <description>Load Adjustment Transactions</description>
    <dispatch>
      <excludePrecedence>true</excludePrecedence>
      <keepgoing>false</keepgoing>
      <rankOrder>ascending</rankOrder>
      <successOnEmptyNodeFilter>false</successOnEmptyNodeFilter>
      <threadcount>1</threadcount>
    </dispatch>
    <executionEnabled>true</executionEnabled>
    <group>PointsUpdate</group>
    <id>6475eb91-926f-476b-bf05-85f5e8b22eae</id>
    <loglevel>INFO</loglevel>
    <name>sglp-jbadjust</name>
    <nodeFilterEditable>true</nodeFilterEditable>
    <nodefilters>
      <filter>.*</filter>
    </nodefilters>
    <nodesSelectedByDefault>true</nodesSelectedByDefault>
    <schedule>
      <dayofmonth />
      <month day='*' month='*' />
      <time hour='00' minute='00' seconds='00' />
      <year year='*' />
    </schedule>
    <scheduleEnabled>false</scheduleEnabled>
    <sequence keepgoing='false' strategy='sequential'>
      <command>
        <exec>echo one  ${option.PDATE} two ${option.TSTAMP} three</exec>
      </command>
    </sequence>
  </job>
</joblist>

git-import importing this gives me errors, but I do not know why:
Failed importing: rundeck/jobs/PointsUpdate_0014.xml: rundeck.controllers.JobXMLException: Unable to parse xml: org.xml.sax.SAXParseException; lineNumber: 30; columnNumber: 110; Attribute "name" was already specified for element "option".

Importing into the Rundeck GUI works fine, no errors reported, and options are correct.

A: I just imported your job and also tested using Tomcat 9 + Rundeck 2.4.3 + Linux. I'm not able to reproduce this error. May you provide additional data about Rundeck version,installation method,OS?
Importing using GIT
Importing using GUI


text:
Q: Where to put utility scripts in rails I have some command-line ruby scripts for things like pre-processing text files before uploading them and scraping data.
These scripts don't rely on the rails environment, so I don't really want to make them rake tasks with the associated overhead.
Where should I put them in my folder layout? lib/utility/ or something?

A: We put ours either into the top level of lib/ or we break them down further like lib/reports or lib/stats.


text:
Q: why does sparklyr::spark_apply fail when specifying numeric schema Given a spark connection sc
iris_spk <- copy_to(sc, iris)

Next I'll take a silly example for spark_apply
iris_spk %>%
  spark_apply(
    function(x) {
      data.frame(A=c("a", "b", "c"), B=c(1, 2, 3))
    },
    group_by = "Species",
    columns = c("A", "B"),
    packages = FALSE
  )
# # Source:   table<sparklyr_tmp_3e96258604cd> [?? x 3]
# # Database: spark_connection
#   Species    A         B
#   <chr>      <chr> <dbl>
# 1 versicolor a      1.00
# 2 versicolor b      2.00
# 3 versicolor c      3.00
# 4 virginica  a      1.00
# 5 virginica  b      2.00
# 6 virginica  c      3.00
# 7 setosa     a      1.00
# 8 setosa     b      2.00
# 9 setosa     c      3.00

So far, so good. However https://stackoverflow.com/a/46410425/1785752 suggests that I can improve performance by specifying an output schema instead of just output column names. So I tried:
iris_spk %>%
  spark_apply(
    function(x) {
      data.frame(A=c("a", "b", "c"), B=c(1, 2, 3))
    },
    group_by = "Species",
    columns = list(A="character",
                   B="numeric"),
    packages = FALSE
  )

But then things go wrong:
Error: org.apache.spark.SparkException: Job aborted due to stage failure: Task 1 in stage 26.0 failed 4 times, most recent failure: Lost task 1.3 in stage 26.0 (TID 133, ml-dn38.mitre.org, executor 3): java.lang.RuntimeException: Error while encoding: java.lang.RuntimeException: java.lang.String is not a valid external type for schema of double
  if (assertnotnull(input[0, org.apache.spark.sql.Row, true]).isNullAt) null else staticinvoke(class org.apache.spark.unsafe.types.UTF8String, StringType, fromString, validateexternaltype(getexternalrowfield(assertnotnull(input[0, org.apache.spark.sql.Row, true]), 0, A), StringType), true) AS A#256
  if (assertnotnull(input[0, org.apache.spark.sql.Row, true]).isNullAt) null else validateexternaltype(getexternalrowfield(assertnotnull(input[0, org.apache.spark.sql.Row, true]), 1, B), DoubleType) AS B#257
at org.apache.spark.sql.catalyst.encoders.ExpressionEncoder.toRow(ExpressionEncoder.scala:290)
at org.apache.spark.sql.SparkSession$$anonfun$3.apply(SparkSession.scala:581)
at org.apache.spark.sql.SparkSession$$anonfun$3.apply(SparkSession.scala:581)
at scala.collection.Iterator$$anon$11.next(Iterator.scala:409) at scala.collection.Iterator$$anon$11.next(Iterator.scala:409)
... and so on

Am I specifying the schema incorrectly?

A: Ah! I think that the group_by column does not inherit it's schema from the input data frame, but needs to be declared along with the rest. I just tried
iris_spk %>%
  spark_apply(
    function(x) {
      data.frame(A=c("a", "b", "c"), B=c(1, 2, 3))
    },
    group_by = "Species",
    columns = list(Species="character",
                   A="character",
                   B="numeric"),
    packages = FALSE
  )

which worked (same result as the first try above)


text:
Q: Git merging with repos on origin I'm a git green belt and having a hard time wrapping my head around a concept, and have been surprising unable info on this topic.
We've got a repo (we are using beanstalk) that has a master and a few branches by different developers.  When you merge or rebase a branch, do you do that locally and push that merge, or do you accomplish this on repo server?  When you merge a branch locally and push this to the repo, does git understand this and the merge is reflected there as well?

A: Merges always happen on your local repo. The post-merge push retains the commit history that includes the merge.

A: You merge locally and push the result to the server. The merge is just like a normal commit in the repository.
Git will actually warn you if the target server have a newer version and merging is needed.


text:
Q: News feed. Best way to store info I'm doing a news feed in android, and to make it work faster and avoid download the same info many times, I need a way to store strings to title, url, pub_date, and the image of each post, from different sites and later be able to organize them per date. So what would be the recommended way to save this info?

A: There will be no single correct answer to your question. But I would go with implementing a content provider that would be backing the caching of your feeds in a local SQLite database.
You might be interested to watch
Google I/O 2010 - Android REST client applications


text:
Q: Error empty content gmail using javamail api send email smtp I'm working project : jsf, richfaces. I has just updated javamail api newest version 1.5.5 at https://java.net/projects/javamail/pages/Home
When i test send email from gmail to my gmail,
Subject : Subject test.
Content : Content test. And config : smtp.gmail.com, 465, SSL.
It has just subject and no content in my inbox receive gmail :

And log :

And my code :
           try {
                MailSSLSocketFactory sf = new MailSSLSocketFactory();
                sf.setTrustAllHosts(true);
                final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
                // Set the host smtp address
                props.put("mail.smtp.host", SMTP_HOST_NAME);
                props.put("mail.smtp.port", SMTP_PORT);
                props.put("mail.smtp.auth", "true");
                props.put("mail.smtp.socketFactory.class", SSL_FACTORY);
                props.put("mail.smtp.socketFactory.port", SMTP_PORT);
                props.put("mail.smtp.ssl.trust", "*");
                props.put("mail.smtp.ssl.socketFactory", sf);
            } catch (GeneralSecurityException e) {
                e.printStackTrace();
            }
            .......
            .......
            Authenticator auth = new SMTPAuthenticator();
            Session session = Session.getInstance(props, auth);
            session.setDebug(true);
            // create a message
            MimeMessage msg = new MimeMessage(session);

            msg.setText("UTF8");
            // set the from and to address
            InternetAddress addressFrom = new InternetAddress(SMTP_AUTH_USER);
            msg.setFrom(addressFrom);
            System.out.println(addressFrom);
            msg.setSubject(subject, "utf-8");
            ......
            ......
                try {
                    String content = replaceCharacterInEmail(cus, null,null, message);

                    MimeBodyPart mbp1 = new MimeBodyPart();
                    mbp1.setContent(content, "text/html; charset=utf-8");
                    // attach the file to the message
                    Multipart mp = new MimeMultipart();
                    int count = 0;
                    if(files != null){
                        while (count < files.size()) {
                            MimeBodyPart mbdp = new MimeBodyPart();
                            mbdp.attachFile(files.get(count));
                            mp.addBodyPart(mbdp);
                            count++;
                        }
                    }
                    // create the Multipart and add its parts to it
                    mp.addBodyPart(mbp1);
                    // add the Multipart to the message
                    msg.setContent(mp);
                    Transport.send(msg);
                } catch (Exception e) {
                    invalidAddress += (", " + address.trim());
                    e.printStackTrace();
                }finally{
                    if (!"".equals(emailFails)) {
                        emailFails = emailFails.substring(1);
                    }
                }

But, when i test above code at another project test (java application) with above lib javamail. It's ok :
.
I don't think problem at version of lib javamail. I don't know different between 2 project, because part send email is similar. How can i fix that error ?

A: Please observe this email structure:
-- multipart/mixed
  -- mutlipart/alternative
    -- text/plain
    -- text/html
  -- application/octet-stream (or any other mimetypes)

A: I found problem is conflict library at lib of jboss server and lib of app.ear (deploy).


text:
Q: Windows 10: Secondary HDD wakes up when primary SSD is accessed I've got an external 2,5" HDD hooked to my Windows 10 machine with a build in SSD.
Since the HDD only holds media, I'd like the drive to be in standby-mode when ever possible to reduce noise and power consumption.
However, I've noticed that whenever the OS accesses the SSD it also automatically wakes up the HDD. This is also the case when any program tries to access the SSD.
It there a way to prevent this "wake all drives" event and keep the second drive in standby mode?


text:
Q: Автоматическая live загрузка Debian с usb Есть live образ Debian на SD карте, при загрузке компьютера, выходит меню выбора (лайв, установить и т.д). Вопрос, как миновать это окно и сразу бутить лайв версию? Делается это для того, что бы если вдруг комп выключился, он не застопорился на этом окне при запуске. Спасибо.

A: Выставить в BIOS приоритет загрузки для SD-карты. Так-же, наверняка в вашем биос, включена функция «показывать меню выбора загрузки».


text:
Q: Mysql - Como selecionar os registros do mês anterior? Olá, estou tentando selecionar os registros da tabela 'Clientes' que foram registrados no mês passado. Nessa tabela existe o campo 'CreateDate' (datetime). Estou tentando fazer da seguinte forma mas não está retornando apenas os registros do mês passado, mas, sim dos meses de anos passados também. Exemplo: se o mês passado é Março a minha consulta está retornando Março de todos os anos que estão na tabela.
Estou fazendo assim:
SELECT Id, Name, CreateDate FROM Clientes WHERE MONTH(CreateDate) = MONTH(DATE_ADD(CURDATE(), INTERVAL - 1 MONTH));

A: Olá!
Tente assim:
SELECT Id, Name, CreateDate
FROM Clientes
WHERE CreateDate >= DATE_ADD(SYSDATE(), INTERVAL -1 MONTH)


text:
Q: Work in an isothermal process Is it possible to calculate the work done on a gas by an isothermal process given pressure and volume? ie Pressure at point 2 is 5.55atm and volume is 1.39m^3. Temperature or number of moles is not given.
(a=1.39m^3 and b=1.85)

Thanks.

A: As you know, for an isothermal process $\Delta {T}=0$,
From the ideal gas equation, $PV=nRT$, you can get the value of $P$ and you can substitute the value in the expression of work. Isothermal processes are slow and reversible. So, the external pressure will be equal to the internal pressure.
$W=\int P_{ext} dV$
$ = \int_{V_1}^{V_2} \frac{nrT}{V}dV$.
Integrate this.
After that, from Boyle's law at constant temperature, $PV=constant$
, thus,
$\frac{P_1}{P_2}=\frac{V_2}{V_1}$.
Now you can solve your question. You can get the value of temperature using the ideal gas equation.


text:
Q: In a Jenkinsfile, how to access a variable that is declared within a sh step? Say I have a Jenkinsfile. Within that Jenkinsfile, is the following sh step:
sh "myScript.sh"

Within myScript.sh, the following variable is declared:
MY_VARIABLE="This is my variable"

How can I access MY_VARIABLE, which is declared in myScript.sh, from my Jenkinsfile?

A: To import the variable defined in your script into the current shell, you can use the source command (see explanation on SU):
# Either via command
source myScript.sh
# Or via built-in synonym
. myScript.sh

Supposing your script does not output anything, you can then instead output the variable to fetch it in Jenkins:
def myVar = sh(returnStdout: true, script: '. myScript.sh && echo $MY_VARIABLE')

If indeed outputs comes from your script, you can fetch the last output either per shell:
(. myScript.sh && echo $MY_VARIABLE) | tail -n1

or via Groovy:
def out = sh(returnStdout: true, script: '. myScript.sh && echo $MY_VARIABLE')
def myVar = out.tokenize('\n')[-1]

A: The bash variable declared in .sh file is ending with the pipeline step: sh complete.
But you can make you .sh to generate a properties file, then use pipeline step: readProperties to read the file into object for accessing.
// myScript.sh
...

echo MY_VARIABLE=This is my variable > vars.properties

// pipeline
sh 'myScript.sh'
def props = readProperties file: 'vars.properties'
echo props.MY_VARIABLE


text:
Q: Get row filtering by max(col) in postgresql I'm using postgresql and I'm unfamiliar with it. This code works but I was wondering if I could write it in a more straightforward way. Here I join bar to join bar in a subquery. I was hoping there's something simple like select * from bar group by baz using max(z)
select *
from foo f
join bar b on(f.baz=b.baz AND b.z in (select max(z) from bar group by baz))
where uid1 = 120

A: Just use distinct on:
select distinct on (f.baz) *
from foo f join
     bar b
     on f.baz = b.baz
where uid1 = 120
order by f.baz, b.z desc;

A: @Gordon's answer is almost but not quite correct. There is a subtle difference between max(b.z) and ORDER BY b.z DESC if the column can be NULL. Often overlooked and cause for much headache.
This can bite you, even with a column b.z defined NOT NULL. An outer join can introduce NULL values for the column. Wouldn't be effective in this simple query, but can be in more complex queries.
While aggregate functions like min, max or count ignore NULL values, those have to be dealt with somehow when the same column is used in the ORDER BY clause.
In default sort order NULL values sort last. When the sort order is reversed with DESC, NULL values sort first. It must be that way to stay consistent.
Hence, you get a row with baz IS NULL from DISTINCT ON if any NULL value is in the set of peers, where you would get the greatest not-null value (if any) from max(b.z). Most probably not what you want. You can fix it with NULLS LAST:

*

*PostgreSQL sort by datetime asc, null first?
Plus, while using SELECT *, you would not want to return the join column baz twice - guaranteed to be identical. The USING clause comes in handy, it only returns the column once.
So:
SELECT DISTINCT ON (baz) *
FROM   foo f
JOIN   bar b USING (baz)
WHERE  uid1 = 120   -- where from?
ORDER  BY baz, b.z DESC NULLS LAST;

NULLS LAST won't hurt, even if there are no NULL values - unless you actually want NULL values to prevail.
Detailed explanation for DISTINCT ON:

*

*Select first row in each GROUP BY group?
Faster
Since uid1 is from baz (as commented), this query is typically faster for big tables:
SELECT *
FROM   foo f
JOIN  (
   SELECT DISTINCT ON (baz) *
   FROM   bar
   WHERE  uid1 = 120
   ORDER  BY baz, z DESC NULLS LAST
   ) b USING (baz);

Depending on table definition and data distribution, there may be even faster query techniques:

*

*Optimize GROUP BY query to retrieve latest record per user

A: Hi, You can have below query,
SELECT * FROM foo f
INNER JOIN (SELECT baz, MAX(z) FROM bar GROUP BY baz) b
ON (f.baz = b.baz)
WHERE f.uid1 = 120;

Just joining bar with the MAX(z) derived and populating your required value.
uid1 must be from foo table and since f is used as alias, if not change to b.uid1


text:
Q: Back Transformation If I had a response variable that was square-root transformed, and an explanatory variable that is log transformed, and I wished to back transform the model using the summary statistics below, such that Y ~ (X)^2, how would I interpret the meaning of the relationship between X and Y using the estimated Beta coefficient?
I thought it was interpreted as: "If there is a 1% increase in X, there is approximately a change of sqrt(2.1014))/100 units increase in Y."
    Residuals:
        Min      1Q  Median      3Q     Max
    -37.051 -12.096  -4.908   9.701  68.071

    Coefficients:
                Estimate Std. Error t value Pr(>|t|)
    (Intercept)  -3.0147     2.0827  -1.448    0.148
    Dose.Back     2.1014     0.1679  12.514   <2e-16 ***
    ---
    Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 16.28 on 1154 degrees of freedom
Multiple R-squared:  0.1195,    Adjusted R-squared:  0.1187
F-statistic: 156.6 on 1 and 1154 DF,  p-value: < 2.2e-16

A: Your model and its estimates posit that
$$\sqrt{Y} = 2.1014  D - 3.0147 + \varepsilon$$
where $D$ is Dose.Back (or its logarithm) and $\varepsilon$ is a random variable of zero expectation whose standard deviation is approximately $16.28.$  Squaring both sides gives
$$Y = (2.1014  D - 3.0147 + \varepsilon)^2.$$
Adding $0.01$ to $D$ yields the value
$$(2.1014  (D + 0.01) - 3.0147 + \varepsilon')^2.$$
The difference is
$$2(2.1014 D - 3.0147 + \varepsilon)(\varepsilon' - \varepsilon + (0.01)(2.1014)) + (\varepsilon' - \varepsilon + (0.01)(2.1014))^2.$$
This expression, as well as its expectation, are complicated.  Let us therefore focus on the simpler question of how the expectation of $Y$ varies with $D$.  Note that
$$\eqalign{
\mathbb{E}(Y) &= \mathbb{E}\left(2.1014  D - 3.0147 + \varepsilon\right)^2 \\
              &= (2.1014D - 3.0147)^2 + 2(2.1014D - 3.0147) \mathbb{E}(\varepsilon) + \mathbb{E}(\varepsilon^2) \\
              &=(2.1014D - 3.0147)^2 + 0 + (16.28)^2.
}$$
(This result is of considerable interest in its own right because it reveals the role played by the mean squared error in interpreting the relationship between $D$ and $Y$.)
When $0.01$ is added to $D$ the value of $\mathbb{E}(Y)$ increases by
$$2(2.1014)(2.1014D - 3.0147)(0.01) + 2.1014(0.01)^2.$$
The last term $2.1014(0.01)^2 \approx 0.0002$ is so small compared to the squared errors (with their typical value of $16.28$) that we may neglect it.  In this case, to a good approximation, this fitted model associates an (additive) increase in $D$ of $0.01$ with an increase in $Y$ of
$$2(2.1014)(2.1014D - 3.0147)(0.01) = 0.0883176 D - 0.126.$$

When $D$ is the natural logarithm of some quantity $d$, a 1% multiplicative increase in $d$ causes a value of approximately $0.01$ to be added to $D$, because
$$\log(1.01 d) = \log(1.01) + \log(d) = \left(0.01 - (0.01)^2/2 + \cdots\right) + D \approx 0.01 + D.$$
If you used a logarithm to another base $b$, entailing $D = \log_b(d) = \log(d)/\log(b),$ then a 1% multiplicative increase in $d$ causes a value of approximately $(0.01)/\log(b)$ to be added to $D$, so everywhere "$0.01$" occurs in the preceding formulas you must use $(0.01/\log(b))$ instead.


text:
Q: Android AutoCompleteTextView, how to choose what it displays in the drop down? I want to somehow change AutoCompleteTextView to blindly suggest everything it has in it's ArrayAdapter (I'm using an online source for text completion suggestions so it will never be a very big array).  Is there a way to do it (make a custom array, or filter...or something), or should I just somehow roll my own custom edit view that just displays whatever I want?

A:
I want to somehow change AutoCompleteTextView to blindly suggest
  everything it has in it's ArrayAdapter

I guess you want to just use the AutoCompleteTextview's look and behavior without actually filtering the items. Now I'm not sure if I remember correctly the auto complete process but I think you could just extend AutoCompleteTextView and override the performFiltering() method to do nothing(in there the widget calls the filter() method on the adapter to limit the items in it). Then use that custom widget in your app instead of the default one.
If that doesn't work, make a custom adapter and create your own Filter(which you'll be returning in the getFilter() method of the adapter) which simply ignores the filtering.
But I find what you're trying to do a bit strange.