text:
Q: pip : how can I change the environment? I am attempting to solve an issue I am having with pip
The context is as follows : I receive a docker image from a service in my company but I do not have the possibility to change it at all ( it comes as it is and that's it )
The image comes with a few packages already installed but are causing a conflict with the requirement.txt file I would like to use. I can obviously check the environment of the docker image and manually check for all of the pakages one by one but it not very efficient
Is there a way that I can install my requirement.txt in a way were it would take precedence over what is already installed ?
As an exemple, if I have ABC==1.4.21 already installed but I would like to have ABC==2.3 would it be possible to get pip to install the version in the requirement.txt ( the opposite is also possible ) ?
I already did attempt to unistall the previously installed packages with pip freeze | xargs pip uninstall -y but I am having issues with some of the packages such as conda : ERROR: Cannot uninstall 'conda'. It is a distutils installed project and thus we cannot accurately determine which files belong to it which would lead to only a partial uninstall.
Any help is much appreciated


text:
Q: Ubuntu server mounted in read-only? This morning my Ubuntu server suddenly appeared in read-only mode.
Google says this can happen after updates.
I restarted the server and it booted with fsck errors:
Inodes that were parts of a corrupted orphan linked list found.
/dev/mapper/vg0-root: UNEXPECTED INCONSISTENCY: RUN fsck MANUALLY
fsck died with exit status 4

Google says you can only run fsck -n on read-only. I will runn that now nd hope to fix the inconstencies.
How can I undo the realy-only mounting of the root file system? Is it safe?
I'm not experienced much in administrating so I'd prefer host support, but it's the holidays...

A: Usually, mounted file system are setup with errors=remount-ro option which is normal.
This means that if your system encounter a disk problem/inconsistency it will set the FS read-only.
fsck -n will not repair/fix anything, it will just report problems.
Badly, to remount root file system read/write you will have to reboot your machine.
At boot the system will certainly perform a fsck with repair option. If it doesn't, reboot your machine in single user mode (recovery mode) and perform a fsck -r (repair) by yourself.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Get all followers Email Ids in twitter in website How can I get my Followers EmailID in Twitter?  I have try the following code, but it does not return emailids, it returns only Name and Screen.

<?php
$trends_url = "http://api.twitter.com/1/statuses/followers/gunarsekar.json";
////// exmaple $trends_url = "http://api.twitter.com/1/statuses/followers/w3cgallery.json"; or $trends_url = "http://api.twitter.com/1/statuses/followers/22250021.json";

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $trends_url);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

$curlout = curl_exec($ch);

curl_close($ch);

$response = json_decode($curlout, true);
// print_r($response);
foreach($response as $friends){
 print_r($friends);
 echo "

";
$thumb = $friends['profile_image_url'];

$url = $friends['screen_name'];

$name = $friends['name'];

?>

<a title="<?php echo $name;?>" href="http://www.twitter.com/<?php echo $url;?>"><img class="photo-img" src="<?php echo $thumb?>" border="0" alt="" width="40" />
<?php
}

?>

Please help me to get the Email Address from Twitter.

A: The Twitter API does not even provide the authenticated User's Email.........So,providing Follower's Email is out of question.......For sending Message,you should try API to send Direct Message
I use Abraham API
https://github.com/abraham/twitteroauth
How to send a Direct message using Abraham's oauth library

A: The Twitter API does not return a user's email address

A: Look over this https://dev.twitter.com/docs/faq#6718.


text:
Q: Domain not working on create-react-app nginx I am hosting my website in a cloud ubuntu 16.04-64, it is being displayed in 200.98.201.143. However, the mb-mock.com domain that I also setup isn't working.
Here is my default file:
server {
  listen 80 default_server;
  root /home/mbpower/build;
  server_name mb-mock.com 200.98.201.143;
  index index.html index.htm;
  location / {
  }
}

I don't know if this helps but here is the repo: https://github.com/dev-campos/mbpower
I have tried several different ways to get this website hosted and this is the farthest I got, this is the last step I haven't been able to get to work, so I'm afraid to try messing around too much and breaking the rest.

A: As awran5 said I just needed to change the domain to the correct IP.


text:
Q: Caching an Array in ModX I had the Problem that I had two snippets one must be called uncached and in this I needed to retrieve an array that is generated in another snippet that must be called cached.
Caching the array is not possible and I mustn't call the snippet more often than once a week.

A: If you need to cache an array you can jsonencode it and store it in the cache manager like this:
$modx->cacheManager->set('cache_name', json_encode($tldlist), 604800); // json encoding the array and caching it for 1 week
Then when you needed the cached Array you can retrieve it and jsondecode it:
$tldarray = $modx->cacheManager->get('cache_name'); //retrieving the json string
$tldarray = json_decode($tldarray, 1); // and then converting it to an array

If the cache is expired you need to check if the array is NULL
$tldarray = $modx->cacheManager->get('cache_name');
$tldarray = json_decode($tldarray, 1);

if($tldarray == NULL){
$tldarray = $modx->runSnippet('tld_array'); //The snippet tld_array generates the array that I need
$tldarray = $modx->cacheManager->get('tld_array');
$tldarray = json_decode($tldarray, 1); //this converts the json string back to an array
}


text:
Q: Python: improve the efficency of my script using multiprocessing module (tips and suggestions) I am a beginner of Python (few weeks) and recently i had read some post in Stackoverflow about multiprocessing module. Normally i work with million of points format data (*.las file. This video to understand the source of my data) and I have interest to understand better how use multiprocessing module.
I use Python 2.7 on windows 7, intel core i7-3770CPU
Normally I use this def wrote from me as a Benchmark to understand:
# load line-by-line the las file, check if the points are inside the polygon
# if yes save a new *.las file

import shapefile
import numpy
import numpy as np
from numpy import nonzero
from matplotlib.mlab import griddata
from matplotlib.nxutils import pnpoly
from liblas import file as lasfile

def LAS2LASClip(inFile,poly,outFile):
    f = lasfile.File(inFile,None,'r') # open LAS
    h = f.header
    # change the software id to libLAS
    h.software_id = "Python 2.7"
    file_out = lasfile.File(outFile,mode='w',header= h)
    f.close()
    sf = shapefile.Reader(poly) #open shpfile
    shapes = sf.shapes()
    for i in xrange(len(shapes)):
        verts = np.array(shapes[i].points,float)
        inside_points = [p for p in lasfile.File(inFile,None,'r') if pnpoly(p.x, p.y, verts)]
        for p in inside_points:
            file_out.write(p)
    file_out.close()


text:
Q: Custom Rounding up to nearest 0.05 I want to do custom round up to near 0.05 , based on following condition.It is hard to explain , but following example will be easy to understand .
12.910 - 12.90
12.920 - 12.90
12.930 - 12.90
12.940 - 12.90
12.941 - 12.95
12.950 - 12.95

12.960 - 12.95
12.970 - 12.95
12.980 - 12.95
12.990 - 12.95
12.991 - 13.00
13.000 - 13.00

I tried several function , but it is rounding up 12.98 to 13.00.
function   customRound( num) {
    return Math.round(num * 20) / 20;
}

A: Coming at this visually, your rounding algorithm seems to look like this:

The dot is where you want to round to for that interval. ( marks the open end of an interval, ] the closed end. (12.99 belongs to the red interval.) We'll implement this algorithm by manipulating the line to match Math.floor's.
First, let's work with integers.
num * 100

Your rounding interval is left-open and right-closed, but Math.floor is left-closed and right-open. We can flip the line to match by multiplying by −1:
  num *  100 * -1
⇒ num * -100

Your rounding intervals' lengths are 5, so we need to put the ends of the intervals on multiples of 5...
num * -100 - 1

...before dividing by 5 to match Math.floor.
 (num * -100 - 1  ) / 5
⇒ num *  -20 - 0.2

Now we can take the floor.
return Math.floor(num * -20 - 0.2);

Scale back up to the original by multiplying by 5:
return Math.floor(num * -20 - 0.2) * 5;

Shift the returned value over to the dot by adding 4:
return Math.floor(num * -20 - 0.2) * 5 + 4;

Undo the alignment we did earlier:
  return Math.floor(num * -20 - 0.2) * 5 + 4 + 1;
⇒ return Math.floor(num * -20 - 0.2) * 5 + 5;

Undo the flip:
  return (Math.floor(num * -20 - 0.2) *  5 + 5) * -1;
⇒ return  Math.floor(num * -20 - 0.2) * -5 - 5;

And divide the whole thing by 100 to get your original scale back:
  return (Math.floor(num * -20 - 0.2) * -5    - 5) / 100;
⇒ return  Math.floor(num * -20 - 0.2) * -0.05 - 0.05;

Using Robin Zigmond's testing framework,

function customRound(num) {
    return Math.floor(num * -20 - 0.2) * -0.05 - 0.05;
}

// test desired results
var tests = [12.91, 12.92, 12.93, 12.94, 12.941, 12.95, 12.96, 12.97, 12.98, 12.99, 12.991, 13];

for (var i=0; i<tests.length; i++) {
  console.log(`${tests[i].toFixed(3)} - ${customRound(tests[i]).toFixed(2)}`);
}

A: If you really intended to round everything within < .01 of the nearest .05 then try the below, to get the precision of the number it uses answer from Is there a reliable way in JavaScript to obtain the number of decimal places of an arbitrary number?
function decimalPlaces(n) {
  var s = "" + (+n);
  var match = /(?:\.(\d+))?(?:[eE]([+\-]?\d+))?$/.exec(s);
  if (!match) { return 0; }
  return Math.max(
      0,  // lower limit.
      (match[1] == '0' ? 0 : (match[1] || '').length)
      - (match[2] || 0));
}

var test = 12.941;
var factor = Math.pow(10,decimalPlaces(test));
var remainder = ((test * factor) % (.05 * factor))/factor;

var result;

if (remainder>.04) {
    result = Math.round(test*20)/20;
} else {
    result = (test*factor - remainder*factor)/factor;
}

console.log('result is:',result);

A: As far as I can tell from your example, the desired behaviour appears to be "round up to the nearest 0.01, then round that result down to the nearest 0.05".
This can be implemented as follows. As you can see, it agrees exactly with your examples (I even took care to format it the same way) - but please let me know if I've got the wrong end of the stick.

function customRound(num) {
    var intermediateResult = Math.ceil(num*100)/100;
    return Math.floor(intermediateResult*20)/20;
}

// test desired results
var tests = [12.91, 12.92, 12.93, 12.94, 12.941, 12.95, 12.96, 12.97, 12.98, 12.99, 12.991, 13];

for (var i=0; i<tests.length; i++) {
  console.log(`${tests[i].toFixed(3)} - ${customRound(tests[i]).toFixed(2)}`);
}


text:
Q: Newsletter plugin custom button text on impresspage I install Newsletter plugin of impresspage,
in widget files i couldn't found way to change text of button "SubScribe"
and edit plugin html view

A: Firstly, it's "ImpressPages" (camelCase and plural).
HTML output of widgets is controlled with skins (https://www.impresspages.org/docs/widgets). By default is in \Plugin\Newsletter\Widget\Newsletter\skin\default.php. You can change it directly or override in your theme.
If done correctly, all strings are translatable. Install a plugin (http://market.impresspages.org/plugins/AsdTranslate) for easy translations, look for required string and translate/change it.
Another option is to change the source. Check where that string comes from. Here's where form comes from:
\Plugin\Newsletter\Model::createForm();

Open Model.php, search for createForm() method and look for submit field. And do what you want with it.


text:
Q: RecyclerView scrollbar laggy When I used the new recycler view, I noticed the scrollbar is not as fluid as in regular ScrollView/ListView. It looks like it doesn't recognize when you scroll within the adapter item, but it only changes when new item appears / old item disappears, so the progressbar jumps instead of move smoothly. This is a video demonstrating this issue.
Is there a way to make it smooth?
My layout:
<android.support.v7.widget.RecyclerView
                android:id="@+id/listRecycler"
                android:scrollbars="vertical"
                android:layout_width="match_parent"
                android:layout_height="match_parent"/>

Fragment:
    mListRecycler.setAdapter(mAdapter);
    LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
    layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
    mListRecycler.setLayoutManager(layoutManager);

Adapter:
public class NewsAdapter extends RecyclerView.Adapter<NewsAdapter.ViewHolder> {

private List<News> items;
private int itemLayout;

public NewsAdapter(List<News> items, int itemLayout) {
    this.items = items;
    this.itemLayout = itemLayout;
}

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View v = LayoutInflater.from(parent.getContext()).inflate(itemLayout, parent, false);
    v.setOnClickListener(this);
    return new ViewHolder(v);
}

@Override
public void onBindViewHolder(ViewHolder holder, int position) {
    News item = items.get(position);
    holder.text.setText(item.getTitle());
    holder.itemView.setTag(item);
}

@Override
public int getItemCount() {
    return items.size();
}

public static class ViewHolder extends RecyclerView.ViewHolder {
    @InjectView(R.id.title)
    TextView text;

    public ViewHolder(View itemView) {
        super(itemView);
        ButterKnife.inject(this, itemView);
    }
}

}

A: this is problem in L preview release. LinearLayoutManager did not have smooth scrollbars support.
Will be fixed when RecyclerView is released.

A: The RecyclerView also uses the height(if orientation vertical or width if horizontal) to compute the height(or width) of scrollbar. If your List item have same height(or width) then consider using setHasFixedSize().
mRecyclerList.setHasFixedSize(true);


text:
Q: VueJS and laravel validation array validation from Laravel to VueJS.
I need to show the right error messages to the right input field.
Any one have an idea?
form.vue :

 <input type="text" v-model="item.name" class="form-control">

  {{errors.name[0]}}

   <input type="text" v-model="item.age" class="form-control">

  {{errors.age[0]}}

Controller :
$this->validate($request, [
        'items.*.name' => 'required',
        'items.*.age' => 'required',
    ]);

I got this in my vue devtools

A: It looks like you have to itterate through your errors object. Within error your key is "items.0.name", so probably you have to use {{ errors['items.0.name'] }}. But I think you would have to change your laravel error validation.

A: is an example of two dimensional arrays
validacion.revision[0].vehiculo_revision_all

right way
validacion['revision.'+index+'.vehiculo_revision_all']

validations in the controller
$rules =[
  'revision.*.vehiculo_revision_all.*.cantidad' => 'required',
  'revision.*.vehiculo_revision_all.*.estado' => 'required'
];

array output data
revision.2.vehiculo_revision_all.0.cantidad: ["El campo revision.2.vehiculo_revision_all.0.cantidad es obligatorio."]
revision.2.vehiculo_revision_all.0.estado: ["El campo revision.2.vehiculo_revision_all.0.estado es obligatorio."]
revision.2.vehiculo_revision_all.1.cantidad: ["El campo revision.2.vehiculo_revision_all.1.cantidad es obligatorio."]

                {{ validacion['revision.'+index+'.vehiculo_revision_all.'+ins+'.estado'] }}

A: I display my error messages using sweet alert. I catch it first on my axios post.
     createAdminstrator(name, username, password, confirmpassword, superadmin) {
        const t = this;

        axios.post('/administrators', {name: name, username: username, password: password, confirmpassword: confirmpassword, superadmin: superadmin})
            .then(({data}) => {
                t.administrators.unshift(data);
                t.error = '';
            })
            .catch(error => {
                if (error.response.data.errors.username) {
                  swal(error.response.data.errors.username[0], "Error", "error");
                } else if (error.response.data.errors.confirmpassword) {
                  swal(error.response.data.errors.confirmpassword[0], "Error", "error");
                } else if (error.response.data.errors.password) {
                  swal(error.response.data.errors.password[0], "Error", "error");
                }
              });
    }


text:
Q: How to put HH:mm:ss formatted times in CSV so Excel formats them as regular text? I'm writing times into a CSV file time using the format HH:mm:ss.  When excel opens the file  it automatically recognizes this column format as time.  Is it possible to prevent Excel from doing this so the column is formatted as regular text?
Thank you

A: You have no control over formatting in a CSV file, unless you want to go through the full custom-import setup in Excel each time.
If you want to force Excel to treat something as text, then use a proper Excel file, generated using PHPExcel

A: There was recently a similar question on SuperUser: link
The same principle as the accepted answer can be employed here if all you want is a CSV that can be opened with Excel without the ill-effects of autoformatting.  You'll need to write your values to the CSV in this format:
="yourdatetimehere"

Of course the downside is that the equal signs and quotation marks will be stored in your CSV as text.  This means that this will probably cause problems for you if you plan to use the CSV in any context outside Excel.  But as a hack to get around Excel's autoformatting, this should work.


text:
Q: Cocoa Pods - File not found I am new to cocoa pods. First time trying. After installing Cocoa pods I just opened terminal and executed cd to current project directory and done pod install. Installation of pod sucess. But still Xcode saying file not found error.

How to fix this error in Xcode ? Am I need to anyting else apart from pod install ?


text:
Q: Count cells containing strings not equal to many things with multiple criteria- Excel I have two data tables on different tabs, named July and August. Within these tabs are columns with names, groups, and divisions. I am trying to compare the July names against the August names and return the number of unique names within each group/division.
I have used a Countifs function to isolate the number of names within each group and division for both July and August, but can not find a good formula to compare the string of July names against the string of August names and return the number of unique strings.
I have tried a few different nested =Sumproduct functions, including Sumproduct(Countifs(), but I am not sure how to apply this to cells containing strings. I have also tried a =Sumproduct(--(INSA(Match())). Are these functions logical to get to my end result?

A:
There is no snap is no snap in your question, due to we not sure what
  you trying to ask.
However here you go for an example answer, which worked based on few
  understanding in your question.  If this is not what you expected,
  please help me to get the snaps of your data. So that will solve your
  task.

Answer:
Here is Example Of July Sheet.
Formula Used in "D3"  =COUNTIFS(August!A:A,A3&B3&C3)
you can use Countif() also for single category (this scenario also single category) , here i used Countifs() for any addition category.
Drop The Same Formula To Down Arrow Which is in "D3" to Apply All
the Formula Which is taking count of Name&Group&Division from August Sheet.

Here is Example Of August Sheet..
Here I made a duplicate reference of concatenating each columns, it will be helpful to identify the duplicates easily.
Formula Used In "A3"   =B3&C3&D3 (or) =CONCATENATE(B3,C3,D3)
Drop The Same Formula To Down Arrow Which is in "A3"  to Apply All


text:
Q: Method repetition using overloading How i could refactor "method" in order to not repeating code? It basically does the same thing for pause, resume and stop. At the moment I'm using a method overloading with boolean, so not the best idea. I don't know what to search for, so give me tips
private static void method(final boolean pause, final boolean resume, final boolean stop) {
    planes.forEach(plane -> {
        if (pause) {
            if (plane.getPlaneMovementAnimation() != null) {
                plane.getPlaneMovementAnimation().pause();
            }
            if (plane.getLandingAnimation() != null) {
                plane.getLandingAnimation().pause();
            }
            if (plane.getRandomTransition() != null) {
                plane.getRandomTransition().pause();
            }
        } else if (resume) {
            if (plane.getPlaneMovementAnimation() != null && plane.getStatusMovementAnimation().equals("PAUSED")) {
                plane.getPlaneMovementAnimation().play();
            }
            if (plane.getLandingAnimation() != null && plane.getStatusMovementAnimation().equals("PAUSED")) {
                plane.getLandingAnimation().play();
            }
            if (plane.getRandomTransition() != null && plane.getStatusMovementAnimation().equals("PAUSED")) {
                plane.getRandomTransition().play();
            }
        } else if (stop) {
            if (plane.getPlaneMovementAnimation() != null) {
                plane.getPlaneMovementAnimation().stop();
            }
            if (plane.getLandingAnimation() != null) {
                plane.getLandingAnimation().stop();
            }
            if (plane.getRandomTransition() != null) {
                plane.getRandomTransition().stop();
            }
        }
    });
}

public static void pause() {
    method(true, false, false);
}

public static void resume() {
    method(false, true, false);
}

public static void stop() {
    method(false, false, true);
}

A: I think this would be more readable with the logic for each command in its own separate method. The way this is written now, with everything in the method named method, makes it harder to understand the logic for each command, while not removing much duplication (only the planes.foreach part). It's also possible to invoke it in ways that don't make sense, such as passing multiple true parameters. So, as a first step of a multi-step refactoring process, I would extract the logic back into the individual methods:
public static void pause() {
    planes.forEach(plane -> {
        if (plane.getPlaneMovementAnimation() != null) {
            plane.getPlaneMovementAnimation().pause();
        }
        if (plane.getLandingAnimation() != null) {
            plane.getLandingAnimation().pause();
        }
        if (plane.getRandomTransition() != null) {
            plane.getRandomTransition().pause();
        }
    });
}

public static void resume() {
    planes.forEach(plane -> {
        if (plane.getPlaneMovementAnimation() != null && plane.getStatusMovementAnimation().equals("PAUSED")) {
            plane.getPlaneMovementAnimation().play();
        }
        if (plane.getLandingAnimation() != null && plane.getStatusMovementAnimation().equals("PAUSED")) {
            plane.getLandingAnimation().play();
        }
        if (plane.getRandomTransition() != null && plane.getStatusMovementAnimation().equals("PAUSED")) {
            plane.getRandomTransition().play();
        }
    });
}

public static void stop() {
    planes.forEach(plane -> {
        if (plane.getPlaneMovementAnimation() != null) {
            plane.getPlaneMovementAnimation().stop();
        }
        if (plane.getLandingAnimation() != null) {
            plane.getLandingAnimation().stop();
        }
        if (plane.getRandomTransition() != null) {
            plane.getRandomTransition().stop();
        }
    });
}

Next, if the Plane class is able to be changed, I would encapsulate the logic for each of these commands within that class. This way, callers don't need to know about the internal details of each animation for a plane:
public static void pause() {
    planes.forEach(Plane::pause);
}

public static void resume() {
    planes.forEach(Plane::resume);
}

public static void stop() {
    planes.forEach(Plane::stop);
}

class Plane {
    public void pause() {
        if (getPlaneMovementAnimation() != null) {
            getPlaneMovementAnimation().pause();
        }
        if (getLandingAnimation() != null) {
            getLandingAnimation().pause();
        }
        if (getRandomTransition() != null) {
            getRandomTransition().pause();
        }

    }

    public void resume() {
        if (getPlaneMovementAnimation() != null && getStatusMovementAnimation().equals("PAUSED")) {
            getPlaneMovementAnimation().play();
        }
        if (getLandingAnimation() != null && getStatusMovementAnimation().equals("PAUSED")) {
            getLandingAnimation().play();
        }
        if (getRandomTransition() != null && getStatusMovementAnimation().equals("PAUSED")) {
            getRandomTransition().play();
        }
    }

    public void stop() {
        if (getPlaneMovementAnimation() != null) {
            getPlaneMovementAnimation().stop();
        }
        if (getLandingAnimation() != null) {
            getLandingAnimation().stop();
        }
        if (getRandomTransition() != null) {
            getRandomTransition().stop();
        }
    }

    // ...
}

If you're not familiar with the syntax, Plane::pause and the others like  it are shortcuts for lambda expressions called method references. Plane::pause is identical to plane -> plane.pause().
Of course, this only moves the duplication into Plane, so let's keep going. The structure of the resume method is a little different than the others, because it's checking getStatusMovementAnimation().equals("PAUSED") in each if statement. We can extract that check to an outer if, since it's the same for each one:
    public void resume() {
        if (getStatusMovementAnimation().equals("PAUSED")) {
            if (getPlaneMovementAnimation() != null) {
                getPlaneMovementAnimation().play();
            }
            if (getLandingAnimation() != null) {
                getLandingAnimation().play();
            }
            if (getRandomTransition() != null) {
                getRandomTransition().play();
            }
        }
    }

Now the structure for each method is almost identical. Assuming that getPlaneMovementAnimation(), getLandingAnimation(), and getRandomTransition() all return the same type (I'll call it Animation), we can extract a method that returns a collection of non-null animations for the plane:
class Plane {
    private Collection<Animation> getActiveAnimations() {
        Collection<Animation> activeAnimations = new HashSet<>();
        if (getPlaneMovementAnimation() != null) {
            activeAnimations.add(getPlaneMovementAnimation());
        }
        if (getLandingAnimation() != null) {
            activeAnimations.add(getLandingAnimation());
        }
        if (getRandomTransition() != null) {
            activeAnimations.add(getRandomTransition());
        }
        return Collections.unmodifiableCollection(activeAnimations);
    }

    public void pause() {
        getActiveAnimations().forEach(Animation::pause);
    }

    public void resume() {
        if (getStatusMovementAnimation().equals("PAUSED")) {
            getActiveAnimations().forEach(Animation::play);
        }
    }

    public void stop() {
        getActiveAnimations().forEach(Animation::stop);
    }

Now, there's hardly any duplication. Only the getActiveAnimations().forEach and planes.forEach calls. Personally, I don't think it's worth trying to remove that duplication, since it's just a single call in each place. If you really wanted to, though, you could extract forEachPlane and forEachAnimation methods like this:
private static void forEachPlane(Consumer<Plane> action) {
    planes.forEach(action);
}

A: You can try the following code I use to call a method by its name, then you can use switch/if on the method names
Also to decrease your code size you can try the following:
Use one method to invoke pause/resume/stop with a string parameter ie.
handle_method("pause");

then that method you can use like:
  public static void handle_method(String play_resume_or_stop)
    {
        try {
        Class<?> methods_in_class = Class.forName("com.xxx.xxx.PlaneStuff"); // convert string classname to class
        Object methods = methods_in_class.newInstance(); // get all methods in your class

        if (plane.getPlaneMovementAnimation() != null)
        {
            String methodNameIWant = "plane.getPlaneMovementAnimation()." + play_resume_or_stop; // your method name
            Method myMethod = methods.getClass().getMethod(methodNameIWant);
            myMethod.invoke(methods); // invoke your method
        }
        if (plane.getLandingAnimation() != null)
        {
            String methodNameIWant = "plane.getLandingAnimation()." + play_resume_or_stop;
            Method myMethod = methods.getClass().getMethod(methodNameIWant);
            myMethod.invoke(methods); // invoke your method
        }
        if (plane.getRandomTransition() != null)
        {
            String methodNameIWant = "plane.getRandomTransition()." + play_resume_or_stop;
            Method myMethod = methods.getClass().getMethod(methodNameIWant);
            myMethod.invoke(methods); // invoke your method
        }
        }catch (Exception allExpections){}

    }


text:
Q: Old sci-fi novel where people live in domes controlled by aliens and only traders can move between them The setting is a small village that lives under a dome (can't remember why but it's a pastoral setting, no tech).  Traders can move between domes as they have permission from aliens to do so.  Aliens have monitors that fly around like bees, only they are larger (maybe drone sized?).
The story begins with two children playing with a radio and a small (maybe a "baby") alien monitor wanders into the barn where they are fooling with it.  Somehow they damage it with the radio I think.
That's about where I ran out of time and had to return the book to the library over 20 years ago.


text:
Q: Dynamic inheritance from Model I have a Photo-Model that helps me achieve storing each image as a thumbnail aswell:
class Photo(models.Model):
    image = models.ImageField(upload_to=upload_path, default=default_image)
    thumbnail = models.ImageField(upload_to=upload_path_2, editable=False, default=default_image_2)
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)

    class Meta:
        abstract = True

Now I have another Model, lets call it User, which inherits from Photo:
class User(Photo):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)

Now lets say there are multiple classes inheriting from Photo and depending on the inheriting class, I want to set another upload_path and default_image. How Do I achieve that? Can I somehow use the constructor?
Thanks in Advance!

A: I'd say that the best way to handle your use-case is slightly different. You can pass a function to upload_to. This function will be provided the signature instance and filename of the uploaded file (docs).
You can check class of the instance with isinstance or something similar and change the output accordingly.
def upload_path(instance, filename):
    if isinstance(instance, User):
        return 'user_{0}/{1}'.format(instance.user.id, filename)
    return 'photo/{1}'.format(filename)

Doing the same for default is a little bit harder. The default function won't be passed any reference to the model or field which will make it harder to override it based on model. You could simply add an image field to each of the concrete models, but I don't know if that would be appropriate.


text:
Q: How can I add all previous cells to a cell using a function in Microsoft Excel? If I have a column:
0  |
1  |
2  |
3  |
4  |
I would like for in the column on the right to take a cell on the left and add all previous cells to it. So that it looks like the two columns below:
0 |   0
1 |   1
2 |  3
3 |  6
4 |  10
I've tried manually adding each but I know there must be a function that can accomplish this. Thank you.

A: Assuming the first column starts in A1, B1 could contain:
=SUM(A$1:A1)

Copy that down the column as needed.

A: Assuming you are looking to use these two columns in a lookup to get the sum of all the previous numbers in a consecutive order which starts with 0 or 1, that can be accomplished with a single formula. Such a total is called a triangle number, and the formula for that is (x^2)/2 + (x/2).
Due to the comment, the Excel version of the formula (assuming the source value to convert is in A1) is =(A1^2/2)+(A1/2).
If that is your goal, the formula is a much more elegant solution.


text:
Q: Show/hide onClick JQuery I want to show/hide text which is display: none; on CSS once the button is clicked and clear the input field on onClick function. Now the text is still shown once its already display. Thank you for your help.

$('#submit').click(function (e) {
    e.preventDefault();
    str = $('#string').val();

    if (checkPalin(str)) {
        return $('#true').css('display', 'block');
    } else {
        return $('#false').css('display', 'block');
    }
});
#result span {
    display: none;
    font-weight: bold;
}
<input type="text" name="string" id="string" value="check">
<input id="submit" type="submit" value="check">

    This string is a padindrome!
    This string is
        not a padindrome

A: Try:
$('#submit').click(function (e) {
    e.preventDefault();
    str = $('#testString').val();
    // Console logging
    console.log('The value entered was: ' + str);
    if (checkPalin(str)) {
        // Clear the value of #testString
        $('#testString').val('');
        // Display the #true result
        $('#true').show();
        // Hide the #false result
        $('#false').hide();
        // Console logging
        console.log('The value ' + str + ' passed our condition');
    } else {
        // Clear the value of #testString
        $('#testString').val('');
        // Display the #false result
        $('#false').show();
        // Hide the #true result
        $('#true').hide();
        // Console logging
        console.log('The value ' + str + ' failed our condition');
    }
    return false;
});

You'll essentially be checking the condition as you were, except you'll be using the Hide() and Show() methods to display your results as needed.


text:
Q: Matching .NET References to Namespaces This seems confusing to me - im creating a class library, and adding all the necessary references for the source files contained in it.
Now, off the bat, there were over 300 compiler errors complaining about missing namespaces.
The library will now compile after i just added all of the System.* references, however this is obviously not the best way.
I.e. if a classes needs using System.Web.Script;, there is no System.Web.Script reference, how would i find out which one of these references contained it? System.Web didnt.

A: Yes a namespace and an assembly are two different concepts in .NET ... They can, but don't need to share a common name.
Best thing is to inspect the type your missing in MSDN (hit F1 in Visual Studio when your text cursor is above a class that you're missing). The MSDN documentation will tell you which namespace and which assembly that type is defined in.

A: Well, the compiler will complain about missed classes, not missed namespaces. You have to look for the classes on the MSDN, there you will find the related namespace and assembly.
For instance for the DropDownList
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.dropdownlist%28v=VS.80%29.aspx
at the top you can read
Namespace: System.Web.UI.WebControls
Assembly: System.Web (in system.web.dll)

A: Namespaces can be re-openwd so more than one assembly can define classes in one namespace.
// AssemblyFoo.dll
namespace MyNamespace {
    class Bar {}
}

// AssemblyBaz.dll
namespace MyNamespace {
    class Qux {}
}

For MyNamespace.Bar you need to reference AssemblyFoo.dll, for MyNamespace.Qux you need to reference AssemblyBaz.dll. You can't deduce the needed assemblies just from the namespace.
The best thing you can do it to look up where the class is defined using the MSDN.

A: You can also use the Object Browser in Visual Studio to click on a namespace, and it will show the assembly and the path to it.  As long as the assembly is in the GAC or Visual Studio otherwise knows about it, you should be able to find it in there.
You can also type in "System.Web.Script" into the object browser's search box, and it'll find the namespace, which you can then right click and say "Go To Definition".  It'll take you to the parent, which will be the namespace/assembly grouping, and you'll see the .dll that it resides in.


text:
Q: Edit each row of a column in a huge dataframe I have a dataframe with some columns
The first column is called TIME...in the first row of that column the time is 2022-06-01T00:00:00.0/2022-06-01T00:01:00.0
in the second row, the time is 2022-06-01T00:01:00.0/2022-06-01T00:02:00.0
I want to cut whatever exists in each row of THAT COLUMN  after the /
for row in DATA['TIME']:
    for char in row:
        while char != "/" :
           continue
        else :
           break
print (column)

A: You can either use pandas.Series.str.split :
DATA["TIME"] = DATA["TIME"].str.split("/", expand=True)[0]

Or pandas.Series.str.extract :
DATA["TIME"] = DATA["TIME"].str.extract("(.+)/", expand=False)

# Output :
print(DATA)
                    TIME
0  2022-06-01T00:00:00.0
1  2022-06-01T00:01:00.0


text:
Q: Multiple git profiles I have multiple git repo (Client1, Client2, personal).
I did configured the profiles as suggested here.
https://medium.com/@trionkidnapper/ssh-keys-with-multiple-github-accounts-c67db56f191e
Now my config file have 3 different profiles.
Host github.com
HostName github.com
PreferredAuthentications publickey
IdentityFile ~/.ssh/id_rsa_personal

Host gitlab.client1.com
HostName github.com
PreferredAuthentications publickey
IdentityFile ~/.ssh/id_rsa_client_a

Host github.com/client2.com
HostName github.com
PreferredAuthentications publickey
IdentityFile ~/.ssh/id_rsa_client_b

Till yesterday everything is fine, whenever I do git pull or push for client_a corresponding IdentityFile is using for the changes to pull or push.
Today When I tried to do git pull on client b repo  ~/.ssh/id_rsa_personal is going to be used instead of ~/.ssh/id_rsa_client_b and it's failing as it is not the intended one(permission issue). Not sure how to point to ~/.ssh/id_rsa_client_b instead of ~/.ssh/id_rsa_personal.
Any thoughts?

A: As Rup says in the comments, change the Host to something shorter like Host client2 (this is just for convenience), add IdentitiesOnly yes to each host so that it only offers the specified file, and make the remote URL something like git@client2:yourrepo.git.


text:
Q: why can't call a function in A class but can call it in B class I need to call updateGold() in ShowMoney class but failed.
If success,it should show money.gold in console, but don't show anything.
And golText.text don't update.
Even I change to Debug.Log("OK") in updateGold(),don't show anything in console.
But when I call updateGold() in Money class, it success. What the difference?
=========================================================
//Prop.cs
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.EventSystems;

public class Prop : MonoBehaviour,IPointerClickHandler
{
    public int goldPrice;
    public int diamondPrice;
    public int propID;

    public GameObject goldError;
    public GameObject diamondError;
    public GameObject purchasePanel;

    //check if purchased when back to this Level
    void Awake()
    {
        if(Bag.propIsPurchased[propID]==true)
        {
            alreadySold();
        }
    }

    //show purchase panel and add delegate
    public void OnPointerClick (PointerEventData eventData)
    {
        purchasePanel.SetActive(true);
        ConfirmPurchase.ensureOperation += this.purchase;
        CancelPurchase.cancelOperation += this.cancel;
    }

    public void purchase()
    {
        if (goldPrice>0)
        {
            if(goldPrice > Money.gold)
            {
                goldError.SetActive(true);
            }
            else
            {
                Money.payGold(goldPrice);
                ShowMoney.updateGold();//problem here
                Bag.addProp(propID);
                alreadySold();
            }
        }
        //...
    }
//...

//ShowMoney.cs
using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class ShowMoney : MonoBehaviour
{
    public GameObject goldText;
    public GameObject diamondText;

    public static Text golText;
    public static Text diaText;

    void Awake()
   {
        golText = goldText.GetComponent<Text>();
        diaText = diamondText.GetComponent<Text>();
        updateGold();
        updateDiamond();
    }

    public static void updateGold()
    {
        Debug.Log(Money.gold);
        golText.text = Money.gold.ToString();
    }

    public static void updateDiamond()
    {
        diaText.text = Money.diamond.ToString();
    }
}

//Money.cs
using UnityEngine;
using System.Collections;

public class Money: MonoBehaviour
{
    public static int gold = 100;
    public static int diamond = 20;

    public static Money instance;
    void Awake()
    {
        instance = this;
    }

    public static void earnGold(int gol)
    {
        gold += gol;
    }

    public static void earnDiamond(int dia)
    {
        diamond += dia;
    }

    public static void payGold(int gol)
    {
        gold -= gol;
        //ShowMoney.updateGold();//can work here
    }

    public static void payDiamond(int dia)
    {
        diamond -= dia;
    }
}

A: Define your method Before Void and still Problem not solved then Make Protected Method that only accessible by its next method .
public static void updateGold()
{
    Debug.Log(Money.gold);
    golText.text = Money.gold.ToString();
}

public static void updateDiamond()
{
    diaText.text = Money.diamond.ToString();
}

public void Awake()
{
    golText = goldText.GetComponent<Text>();
    diaText = diamondText.GetComponent<Text>();
    updateGold();
    updateDiamond();
}


text:
Q: Unable to pull a bts.dot.gov MapLayer using Leaflet in R I'm trying to get the noise pollution layer from the following bts.dot.gov ESRI MapServer to render in R:
https://maps.bts.dot.gov/services/rest/services/Noise/CONUS_road_and_aviation_noise/MapServer
I'm using the following code in RStudio (all necessary packages are installed):
leaflet() %>%
  setView(-117.1, 32.9, 10) %>%
  addEsriBasemapLayer(esriBasemapLayers$Oceans, autoLabels = TRUE) %>%
  addEsriDynamicMapLayer(
    url = paste0("https://maps.bts.dot.gov/services/rest/services/Noise/CONUS_road_and_aviation_noise/MapServer"))

However, none of the noise pollution data is being rendered; I only see a blank map.
The following, virtually identical code for an ArcGIS MapServer does work (wildfire data):
leaflet() %>%
  setView(-117.1, 32.9, 10) %>%
  addEsriBasemapLayer(esriBasemapLayers$Oceans, autoLabels = TRUE) %>%
  addEsriDynamicMapLayer(
    url = paste0("https://maps7.arcgisonline.com/arcgis/rest/services/USDA_USFS_2014_Wildfire_Hazard_Potential/MapServer"))

Am I missing something here? The two map services seem very similar, but I have little experience. The BTS map does support dynamic layers, while the Wildfire map does not, but I have tried pulling the map using this option (among others) as well:
options = dynamicMapLayerOptions(dynamicLayers = "0")

A: Solved it.  I needed to set useCors to FALSE:
leaflet() %>%
  setView(-117.1, 32.9, 10) %>%
  addEsriBasemapLayer(esriBasemapLayers$Oceans, autoLabels = TRUE) %>%
  addEsriDynamicMapLayer(
    url = paste0("https://maps.bts.dot.gov/services/rest/services/Noise/CONUS_road_and_aviation_noise/MapServer/"),
    options = dynamicMapLayerOptions(useCors = FALSE))


text:
Q: Scalar in compactification in several dimension In sec-$8.4$ $($String theory vol $1$$)$ Polchinski states that

With more than one compact dimension, the anti-symmetric tensor also has scalar components $B_{mn}$

I am not understanding why the scalar is identified to the element $B_{mn}$. The scalar should come from decomposing symmetric-traceless, trace part of metric of the coordinates which are compactified? Like the scalar $g_{25,25}$ when we did KK reduction of $g_{\mu\nu}$. Most probably I'm missing some part?

A: First of all, when I hear "the trace part" of a metric in $D$ dimensions, I think of $g_{\mu\nu} g^{\mu\nu}$ which is just a constant.
Polchinski is talking about tensors which have a scalar as one of their restricted representations. In other words, exactly what you were doing by choosing indices that point in a compact direction. The observation is that for a symmetric tensor in $D$ dimensions, you only need to compactify one dimension to get a scalar. This would be $g_{25, 25}$. On the other hand, you would need to compactify at least two dimensions to get a scalar from the $B$ field because it is anti-symmetric. That means $B_{25,25} = 0$. You need to be able to write something like $B_{24,25}$.


text:
Q: How to use CalciteAssert when test my own adapter? I wrote a calcite adapter and now I want to write some tests to verify my physical plan. I want to use CalciteAssert to do that like in Cassandra Adapter, but outside the Calcite Project how can I do that?
  @Test public void testFilter() {
    CalciteAssert.that()
        .with(TWISSANDRA)
        .query("select * from \"userline\" where \"username\"='!PUBLIC!'")
        .limit(1)
        .returns("username=!PUBLIC!; time=e8754000-80b8-1fe9-8e73-e3698c967ddd; "
            + "tweet_id=f3c329de-d05b-11e5-b58b-90e2ba530b12\n")
        .explainContains("PLAN=CassandraToEnumerableConverter\n"
           + "  CassandraFilter(condition=[=($0, '!PUBLIC!')])\n"
           + "    CassandraTableScan(table=[[twissandra, userline]]");
  }

A: There has been talk of changing this in the future, but currently you can add the test code as a dependency to your project. In Maven, this would look something like this:
<dependency>
    <groupId>org.apache.calcite</groupId>
    <artifactId>calcite-core</artifactId>
    <version>1.20.0</version>
    <classifier>tests</classifier>
    <type>test-jar</type>
</dependency>


text:
Q: React - Env variables in development AND production As I've read here, React does support environment variables as long as they are prefixed with REACT_APP_. However, I need them in development and production. How can I get this support?
Note: I'm using Next.js

A: I'm sure this has been answered before, but it says it right on what you linked. Create 2 files, .env.development and .env.production in the root of your project (same level as package.json, .gitignore, etc). Whichever script you run determines which one gets used, in accordance with the hierarchy listed below.
.env: Default.
.env.local: Local overrides. This file is loaded for all environments except test.
.env.development, .env.test, .env.production: Environment-specific settings.
.env.development.local, .env.test.local, .env.production.local: Local overrides of environment-specific settings.

Files on the left have more priority than files on the right:

npm start: .env.development.local, .env.development, .env.local, .env
npm run build: .env.production.local, .env.production, .env.local, .env
npm test: .env.test.local, .env.test, .env (note .env.local is missing)


text:
Q: org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:compileDebugJavaWithJavac' I recently updated my Android Studio to Android Studio 3.1. When I try build my project I get this error relating to Gradle. Not sure why I am getting this error because my android project built fine on a previous version of Android Studio. My Gradle got updated with the Android Studio update. Here is the information I get when I try to build the project:
    org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:compileDebugJavaWithJavac'.
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:100)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:70)
    at org.gradle.api.internal.tasks.execution.OutputDirectoryCreatingTaskExecuter.execute(OutputDirectoryCreatingTaskExecuter.java:51)
    at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(SkipUpToDateTaskExecuter.java:62)
    at org.gradle.api.internal.tasks.execution.ResolveTaskOutputCachingStateExecuter.execute(ResolveTaskOutputCachingStateExecuter.java:54)
    at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:60)
    at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:97)
    at org.gradle.api.internal.tasks.execution.CleanupStaleOutputsExecuter.execute(CleanupStaleOutputsExecuter.java:87)
    at org.gradle.api.internal.tasks.execution.ResolveTaskArtifactStateTaskExecuter.execute(ResolveTaskArtifactStateTaskExecuter.java:52)
    at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:52)
    at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:54)
    at org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter.execute(ExecuteAtMostOnceTaskExecuter.java:43)
    at org.gradle.api.internal.tasks.execution.CatchExceptionTaskExecuter.execute(CatchExceptionTaskExecuter.java:34)
    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker$1.run(DefaultTaskGraphExecuter.java:248)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:199)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:110)
    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:241)
    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:230)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.processTask(DefaultTaskPlanExecutor.java:123)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.access$200(DefaultTaskPlanExecutor.java:79)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker$1.execute(DefaultTaskPlanExecutor.java:104)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker$1.execute(DefaultTaskPlanExecutor.java:98)
    at org.gradle.execution.taskgraph.DefaultTaskExecutionPlan.execute(DefaultTaskExecutionPlan.java:626)
    at org.gradle.execution.taskgraph.DefaultTaskExecutionPlan.executeWithTask(DefaultTaskExecutionPlan.java:581)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.run(DefaultTaskPlanExecutor.java:98)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor.process(DefaultTaskPlanExecutor.java:59)
    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter.execute(DefaultTaskGraphExecuter.java:128)
    at org.gradle.execution.SelectedTaskExecutionAction.execute(SelectedTaskExecutionAction.java:37)
    at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:37)
    at org.gradle.execution.DefaultBuildExecuter.access$000(DefaultBuildExecuter.java:23)
    at org.gradle.execution.DefaultBuildExecuter$1.proceed(DefaultBuildExecuter.java:43)
    at org.gradle.execution.DryRunBuildExecutionAction.execute(DryRunBuildExecutionAction.java:46)
    at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:37)
    at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:30)
    at org.gradle.initialization.DefaultGradleLauncher$ExecuteTasks.run(DefaultGradleLauncher.java:314)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:199)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:110)
    at org.gradle.initialization.DefaultGradleLauncher.runTasks(DefaultGradleLauncher.java:204)
    at org.gradle.initialization.DefaultGradleLauncher.doBuildStages(DefaultGradleLauncher.java:134)
    at org.gradle.initialization.DefaultGradleLauncher.executeTasks(DefaultGradleLauncher.java:109)
    at org.gradle.internal.invocation.GradleBuildController$1.call(GradleBuildController.java:78)
    at org.gradle.internal.invocation.GradleBuildController$1.call(GradleBuildController.java:75)
    at org.gradle.internal.work.DefaultWorkerLeaseService.withLocks(DefaultWorkerLeaseService.java:152)
    at org.gradle.internal.invocation.GradleBuildController.doBuild(GradleBuildController.java:100)
    at org.gradle.internal.invocation.GradleBuildController.run(GradleBuildController.java:75)
    at org.gradle.tooling.internal.provider.runner.BuildModelActionRunner.run(BuildModelActionRunner.java:53)
    at org.gradle.launcher.exec.ChainingBuildActionRunner.run(ChainingBuildActionRunner.java:35)
    at org.gradle.launcher.exec.ChainingBuildActionRunner.run(ChainingBuildActionRunner.java:35)
    at org.gradle.tooling.internal.provider.ValidatingBuildActionRunner.run(ValidatingBuildActionRunner.java:32)
    at org.gradle.launcher.exec.RunAsBuildOperationBuildActionRunner$1.run(RunAsBuildOperationBuildActionRunner.java:43)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:199)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:110)
    at org.gradle.launcher.exec.RunAsBuildOperationBuildActionRunner.run(RunAsBuildOperationBuildActionRunner.java:40)
    at org.gradle.tooling.internal.provider.SubscribableBuildActionRunner.run(SubscribableBuildActionRunner.java:51)
    at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:47)
    at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:30)
    at org.gradle.launcher.exec.BuildTreeScopeBuildActionExecuter.execute(BuildTreeScopeBuildActionExecuter.java:39)
    at org.gradle.launcher.exec.BuildTreeScopeBuildActionExecuter.execute(BuildTreeScopeBuildActionExecuter.java:25)
    at org.gradle.tooling.internal.provider.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:80)
    at org.gradle.tooling.internal.provider.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:53)
    at org.gradle.tooling.internal.provider.ServicesSetupBuildActionExecuter.execute(ServicesSetupBuildActionExecuter.java:57)
    at org.gradle.tooling.internal.provider.ServicesSetupBuildActionExecuter.execute(ServicesSetupBuildActionExecuter.java:32)
    at org.gradle.tooling.internal.provider.GradleThreadBuildActionExecuter.execute(GradleThreadBuildActionExecuter.java:36)
    at org.gradle.tooling.internal.provider.GradleThreadBuildActionExecuter.execute(GradleThreadBuildActionExecuter.java:25)
    at org.gradle.tooling.internal.provider.ParallelismConfigurationBuildActionExecuter.execute(ParallelismConfigurationBuildActionExecuter.java:43)
    at org.gradle.tooling.internal.provider.ParallelismConfigurationBuildActionExecuter.execute(ParallelismConfigurationBuildActionExecuter.java:29)
    at org.gradle.tooling.internal.provider.StartParamsValidatingActionExecuter.execute(StartParamsValidatingActionExecuter.java:69)
    at org.gradle.tooling.internal.provider.StartParamsValidatingActionExecuter.execute(StartParamsValidatingActionExecuter.java:30)
    at org.gradle.tooling.internal.provider.SessionFailureReportingActionExecuter.execute(SessionFailureReportingActionExecuter.java:59)
    at org.gradle.tooling.internal.provider.SessionFailureReportingActionExecuter.execute(SessionFailureReportingActionExecuter.java:44)
    at org.gradle.tooling.internal.provider.SetupLoggingActionExecuter.execute(SetupLoggingActionExecuter.java:45)
    at org.gradle.tooling.internal.provider.SetupLoggingActionExecuter.execute(SetupLoggingActionExecuter.java:30)
    at org.gradle.launcher.daemon.server.exec.ExecuteBuild.doBuild(ExecuteBuild.java:67)
    at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
    at org.gradle.launcher.daemon.server.exec.WatchForDisconnection.execute(WatchForDisconnection.java:37)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
    at org.gradle.launcher.daemon.server.exec.ResetDeprecationLogger.execute(ResetDeprecationLogger.java:26)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
    at org.gradle.launcher.daemon.server.exec.RequestStopIfSingleUsedDaemon.execute(RequestStopIfSingleUsedDaemon.java:34)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
    at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:74)
    at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:72)
    at org.gradle.util.Swapper.swap(Swapper.java:38)
    at org.gradle.launcher.daemon.server.exec.ForwardClientInput.execute(ForwardClientInput.java:72)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
    at org.gradle.launcher.daemon.server.exec.LogAndCheckHealth.execute(LogAndCheckHealth.java:55)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
    at org.gradle.launcher.daemon.server.exec.LogToClient.doBuild(LogToClient.java:62)
    at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
    at org.gradle.launcher.daemon.server.exec.EstablishBuildEnvironment.doBuild(EstablishBuildEnvironment.java:82)
    at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
    at org.gradle.launcher.daemon.server.exec.StartBuildOrRespondWithBusy$1.run(StartBuildOrRespondWithBusy.java:50)
    at org.gradle.launcher.daemon.server.DaemonStateCoordinator$1.run(DaemonStateCoordinator.java:295)
    at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63)
    at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:46)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:55)
    at java.lang.Thread.run(Thread.java:745)
Caused by: org.gradle.api.internal.tasks.compile.CompilationFailedException: Compilation failed; see the compiler error output for details.
    at org.gradle.api.internal.tasks.compile.JdkJavaCompiler.execute(JdkJavaCompiler.java:50)
    at org.gradle.api.internal.tasks.compile.JdkJavaCompiler.execute(JdkJavaCompiler.java:35)
    at org.gradle.api.internal.tasks.compile.NormalizingJavaCompiler.delegateAndHandleErrors(NormalizingJavaCompiler.java:98)
    at org.gradle.api.internal.tasks.compile.NormalizingJavaCompiler.execute(NormalizingJavaCompiler.java:51)
    at org.gradle.api.internal.tasks.compile.NormalizingJavaCompiler.execute(NormalizingJavaCompiler.java:37)
    at org.gradle.api.internal.tasks.compile.CleaningJavaCompilerSupport.execute(CleaningJavaCompilerSupport.java:35)
    at org.gradle.api.internal.tasks.compile.CleaningJavaCompilerSupport.execute(CleaningJavaCompilerSupport.java:25)
    at org.gradle.api.internal.tasks.compile.incremental.IncrementalCompilationFinalizer.execute(IncrementalCompilationFinalizer.java:39)
    at org.gradle.api.internal.tasks.compile.incremental.IncrementalCompilationFinalizer.execute(IncrementalCompilationFinalizer.java:24)
    at org.gradle.api.tasks.compile.JavaCompile.performCompilation(JavaCompile.java:207)
    at org.gradle.api.tasks.compile.JavaCompile.compile(JavaCompile.java:133)
    at com.android.build.gradle.tasks.factory.AndroidJavaCompile.compile(AndroidJavaCompile.java:125)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:73)
    at org.gradle.api.internal.project.taskfactory.IncrementalTaskAction.doExecute(IncrementalTaskAction.java:46)
    at org.gradle.api.internal.project.taskfactory.StandardTaskAction.execute(StandardTaskAction.java:39)
    at org.gradle.api.internal.project.taskfactory.StandardTaskAction.execute(StandardTaskAction.java:26)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter$1.run(ExecuteActionsTaskExecuter.java:121)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:199)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:110)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:110)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:92)
    ... 107 more

Here is my project gradle file:
    buildscript {
    repositories {
        maven { url 'https://maven.fabric.io/public' }
    }
    dependencies {
        classpath 'io.fabric.tools:gradle:1.25.2'
    }
}
apply plugin: 'com.android.application'
apply plugin: 'io.fabric'
repositories {
    maven { url 'https://maven.fabric.io/public' }
    maven { url 'https://jitpack.io' }
}
apply plugin: 'realm-android'
android {
    compileSdkVersion 27
    defaultConfig {
        applicationId "com.koeksworld.homenet"
        minSdkVersion 19
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        vectorDrawables.useSupportLibrary = true
    }
    buildTypes {
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation project(':giphy-android-sdk-core')
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:27.1.0'
    implementation 'com.android.support:support-v13:27.1.0'
    implementation 'com.toptoche.searchablespinner:searchablespinnerlibrary:1.3.1'
    implementation 'com.android.support:support-vector-drawable:27.1.0'
    implementation 'com.android.support:customtabs:27.1.0'
    implementation 'com.android.support:cardview-v7:27.1.0'
    implementation 'com.android.support:recyclerview-v7:27.1.0'
    implementation 'com.google.firebase:firebase-crash:12.0.1'
    implementation 'com.android.support:support-v4:27.1.0'
    implementation 'com.android.support:design:27.1.0'
    implementation 'com.twitter.sdk.android:twitter:3.1.1'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    implementation 'com.facebook.android:facebook-login:4.29.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
    implementation 'com.google.firebase:firebase-core:12.0.1'
    implementation 'com.google.firebase:firebase-messaging:12.0.1'
    implementation 'com.google.firebase:firebase-auth:12.0.1'
    implementation 'com.firebase:firebase-jobdispatcher:0.8.5'
    implementation 'com.github.bumptech.glide:glide:3.8.0'
    implementation 'com.android.support:support-annotations:27.1.0'
    implementation 'me.relex:circleindicator:1.2.2@aar'
    implementation 'com.android.support:multidex:1.0.3'
    implementation 'com.google.android.gms:play-services-ads:12.0.1'
    implementation('com.crashlytics.sdk.android:crashlytics:2.8.0@aar') {
        transitive = true;
    }
    implementation('com.giphy.sdk:core:1.0.0@aar') {
        transitive = true
    }
}
apply plugin: 'com.google.gms.google-services'

Does anyone know what could be causing the issue?

A: Earlier today, I was in the process of migrating my fragments from android.app.Fragment to android.support.v4.app.Fragment. android.app.Fragment is deprecated as of API level P.

This class was deprecated in API level P.
  Use the Support Library Fragment for consistent behavior across all devices and access to Lifecycle.

Source: https://developer.android.com/reference/android/app/Fragment.html
I updated my google play services to version 3.2. I restarted Android Studio 3.1, and when I tried to build the project, it gave me errors about my Fragment being the incorrect type for a FragmentTransaction in one of my activities. After resolving this error with 2 of my fragments, I was able to build my project successfully and run on my phone.
Its really weird I know, but it works.


text:
Q: Nullpointerexception in getView of custom ArrayAdapter I'm getting a Nullpointerexception in my custom ArrayAdapter in my App. I do not know why a Nullpointer is raised here. And i can not reproduce this exception. The exception did not appear a long time and i have no code changes, so this makes it even more strange.
The code is:
private class MyAdapter<T> extends ArrayAdapter<String> {

    private Map<String, String> selectedDevices;

    public MyAdapter(Context context, int textViewResourceId) {
        super(context, textViewResourceId);
        BluetoothDbAdapter dbHelper = new BluetoothDbAdapter(context);
        dbHelper.open();
        selectedDevices = dbHelper.fetchAllDevicesAsMap();
        dbHelper.close();
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View view =  super.getView(position, convertView, parent);
        CheckedTextView item = (CheckedTextView) view;
        CharSequence text = item.getText();
        if (selectedDevices.values().contains(text)) {
            item.setChecked(true);
        }
        return item;
    }

}

The Exception is raised in getView method in the first line. I have debugged my App and called super.getView with null parameters but no Nullpointerexception was raised, so it seemes that super have been null, but how can this be??? The StackTrace is:

java.lang.NullPointerException
  at android.widget.ArrayAdapter.createViewFromResource(ArrayAdapter.java:355)
  at android.widget.ArrayAdapter.getView(ArrayAdapter.java:323)
  at de.hartig.abt.activity.BluetoothDeviceList$MyAdapter.getView(BluetoothDeviceList.java:140)
  at android.widget.AbsListView.obtainView(AbsListView.java:1408)
  at android.widget.ListView.makeAndAddView(ListView.java:1727)
  at android.widget.ListView.fillDown(ListView.java:652)
  at android.widget.ListView.fillFromTop(ListView.java:709)
  at android.widget.ListView.layoutChildren(ListView.java:1580)
  at android.widget.AbsListView.onLayout(AbsListView.java:1240)
  at android.view.View.layout(View.java:7057)
  at android.widget.FrameLayout.onLayout(FrameLayout.java:333)
  at android.view.View.layout(View.java:7057)
  at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1249)
  at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1125)
  at android.widget.LinearLayout.onLayout(LinearLayout.java:1042)
  at android.view.View.layout(View.java:7057)
  at android.widget.FrameLayout.onLayout(FrameLayout.java:333)
  at android.view.View.layout(View.java:7057)
  at android.view.ViewRoot.performTraversals(ViewRoot.java:1045)
  at android.view.ViewRoot.handleMessage(ViewRoot.java:1727)
  at android.os.Handler.dispatchMessage(Handler.java:99)
  at android.os.Looper.loop(Looper.java:123)
  at android.app.ActivityThread.main(ActivityThread.java:4680)
  at java.lang.reflect.Method.invokeNative(Native Method)
  at java.lang.reflect.Method.invoke(Method.java:521)
  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:858)
  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
  at dalvik.system.NativeStart.main(Native Method)

Does any body know how i can solve this problem? Thanks for help!!!

A: From the stack trace you can clearly see that super was not null, as it did go into android.widget.ArrayAdapter.getView().
You can look at the source for android.widget.ArrayAdapter.createViewFromResource line 355 to try to determine the true cause of your null pointer.
UPDATE
I took a peek at the code and it is failing on this line text.setText(item.toString()); so either text or item are null.
You can look at the code yourself here:
android.widget.ArrayAdapter source

A: You are probably calling add with a null value and the ArrayAdapter is choking on it. To diagnose the problem further we'd need to see the code for fetchAllDevicesAsMap or wherever you are adding elements to the ArrayAdapter.
An excerpt from ArrayAdapter.java inside createViewFromResource:
T item = getItem(position);
if (item instanceof CharSequence) {
    text.setText((CharSequence)item);
} else {
    text.setText(item.toString());
}

This indicates that ArrayAdapter will succumb to a NullPointerException if one of the elements in the underlying array is null.


text:
Q: Bash command if command succeed How can I change the output of a command accordding to the output of that command?
I do an snmp validation, but there are possible answers:

*

*The command was executed but there was no answer.

*The command was executed OK but the result was not the one I expecte (in this case, this would be the output:
SNMPv2-MIB::sysUpTime.513 = No Such Instance currently exists at
this OID)

*he command was executed OK and the result was the one Expected ( a different answer than No Such Instance currently exists at this
OID)

I'd like that people running this script, in case option 1 or 2 are received read:
" SNMP not available "
And for the 3rd option:
" SNMP Available "
In my script, in option 2 my output goes to OK instead of going to Not OK
#!/bin/bash
hostname=$1
read -p "Introduce IP Address: " hostname
community="snmpcommunity"
echo "snmp validation:"
sysUpTime=`snmpget -v2c -c $comunidad $hostname 1.3.6.1.2.1.1.3.513`
if [ $? -eq 0 ]; then
    echo "snmp1 ok"
else
    echo "snmp1 not ok"
fi

A: !/bin/bash

hostname=$1
read -p "Introduce IP Address: " hostname
community="snmpcommunity"
echo "snmp validation:"
sysUpTime=`snmpget -v2c -c $comunidad $hostname 1.3.6.1.2.1.1.3.513`
if [ $? -ne 0 -o "$sysUpTime" = "SNMPv2-MIB::sysUpTime.513 = No Such Instance currently exists at this OID)" ]; then
            echo "SNMP not available"
else
      echo "SNMP available"
fi

this part of code
   if [ $? -ne 0 -o "$sysUpTime" = "SNMPv2-MIB::sysUpTime.513 = No Such Instance currently exists at this OID)" ]

if there is an error or the sysUptime variable is equal to your string and it will print SNMP not available

A: If the result of the snmpget command comes into sysUpTime variable, adding below if condition inside the first if condition should work.
if [[ $sysUpTime == *"No Such Instance currently exists at this OID"* ]]
then
  echo "snmp1 ok"
else
  echo "snmp1 not ok - Instance already exist."
fi


text:
Q: Почему разрывается соединение Wi-Fi после обновления Linux? Установил Linux. Решил обновиться через sudo apt upgrade, но после установки обновленя стало разрываться соединение с WiFi. Ну, то есть раз в 5 минут стабильно отпадает инет. До обновления такого не было.
Что делать?
PS Также есть вопрос про падение звука после обновления

A: Проблемы решил через Synaptic установив все обновления оттуда. Сразу интернет перестал отваливаться.


text:
Q: Is there a way to store previous value in a row and change when a new condition is met? I have a dataset which has data-time and value as columns for each ID. I do some calculations on it but stuck while using recursive functions.

This is how the dataset looks,

Date-Time     Volume      ID    Load
10/22/2019     3862       10
10/23/2019     3800       10
10/24/2019     3700       10
10/25/2019     5000       10     Yes
10/26/2019     4900       10
10/27/2019     4800       10
10/22/2019     3862       11
10/23/2019     3800       11
10/24/2019     3700       11
10/25/2019     5000       11     Yes
10/26/2019     4900       11
10/27/2019     4800       11

I looped the ID in a different function and made a call.

This is what I tried,

curr_load = 0
def Load_number(data):
    global curr_load
    if(data['Load'] == 'Load'):
        curr_load = curr_load + 1

    return curr_load

ids = unique(data)
    newdata = pd.DataFrame()
    for id in ids:
        data = data.loc[data['ID'] == id]
        data = calculations(data)

def calculations(data):
    data['Load_number'] = data.apply(Load_number, axis = 1)

Required output is,

Date-Time     Volume      ID    Load    Load_number
10/22/2019     3862       100                0
10/23/2019     3800       100                0
10/24/2019     3700       100                0
10/25/2019     5000       100     Yes        1
10/26/2019     4900       100                1
10/27/2019     4800       100                1
10/28/2019     4700       100                1
10/22/2019     3862       111                0
10/23/2019     3800       111                0
10/24/2019     3700       111                0
10/25/2019     5000       111     Yes        1
10/26/2019     4900       111                1
10/27/2019     5800       111     Yes        2
10/28/2019     5500       111                2
10/29/2019     50000      111                2

And date as,
Date-Time  Volume  ID  Load        LoadDate
10/22/2019    3862  10  None          0
10/23/2019    3800  10  None          0
10/24/2019    3700  10  None          0
10/25/2019    5000  10   Yes        10/25/2019
10/26/2019    4900  10  None        10/25/2019
10/27/2019    4800  10  None        10/25/2019
10/22/2019    3862  11  None           0
10/23/2019    3800  11  None           0
10/24/2019    3700  11  None           0
10/25/2019    5000  11   Yes        10/25/2019
10/26/2019    4900  11  None        10/25/2019
10/27/2019    4800  11  None        10/25/2019

A: That should do it:
df['Load Number'] = np.where(df.Load == 'Yes', 1, 0)

df['Load Number'] = df.groupby('ID')['Load Number'].cumsum()

(Edit)
Regarding your second question, you could use a similar approach:
df['LoadDate'] = np.where(df.Load == 'Yes', df['Date-Time'], np.nan)

df['LoadDate'] = df.groupby('ID')['LoadDate'].ffill().fillna(0)

Output:
     Date-Time  Volume  ID  Load  Load Number    LoadDate
0   10/22/2019    3862  10  None            0           0
1   10/23/2019    3800  10  None            0           0
2   10/24/2019    3700  10  None            0           0
3   10/25/2019    5000  10   Yes            1  10/25/2019
4   10/26/2019    4900  10  None            1  10/25/2019
5   10/27/2019    4800  10  None            1  10/25/2019
6   10/22/2019    3862  11  None            0           0
7   10/23/2019    3800  11  None            0           0
8   10/24/2019    3700  11  None            0           0
9   10/25/2019    5000  11   Yes            1  10/25/2019
10  10/26/2019    4900  11  None            1  10/25/2019
11  10/27/2019    4800  11  None            1  10/25/2019


text:
Q: Error using generics on grails domain class I'm trying to create a generic abstract hierarchy implementation, the code is the following:
abstract class AbstractHierarchy<T> {
    T parent

    static hasMany = [children: T]

    static constraints = {
        parent(nullable: true)
    }

    static mapping = {
        tablePerHierarchy false
    }
}

Im getting this error:
AbstractHierarchy.groovy: -1: The class java.lang.Object refers to the class java.lang.Object and uses 1 parameters, but the referred class takes no parameters.

So the question is, Am I doing something wrong? is this supported by grails?
Searching the error I found this http://jira.grails.org/browse/GRAILS-11065
I'm using grails 2.3.7 by the way.

A: On account of type erasure, I would expect that everywhere you are using T in your domain model, you might as well be using Object. So from GORM's perspective your model above is equivalent to
abstract class AbstractHierarchy {
    Object parent

    static hasMany = [children: Object]

    static constraints = {
        parent(nullable: true)
    }

    static mapping = {
        tablePerHierarchy false
    }
}

which I assume is not what you intended. So the moral of the story is: don't use generics to express relationships between your domain classes.


text:
Q: JSP and Java Servlet problems I am new to JSP and Java Servlet. I am quite confusing about Session object. I saw session When I learned PHP session and cookie. Are there complete different things? And how a Session object is created, structured and used. This object is in JSP or Java Servlet? could somebody tell me this by words(like concept). In addition, in what situation a JSP page would be appropriate for?(when should I use a Java Servlet and when should I use a Java Servlet Page).For Java Servlet object, for example, ran an email site. There will be a lot of users. How does one Java Servlet object deal with interactions from so many browsers?(like hundreds of logging, reading, etc.)I know there should be only one copy of Java Servlet object exists. But why? If only one there, when is it created and destroyed. Ah... So many questions. If someone can help me I will really grateful for this. Thanks a million!

A:
? And how a Session object is created, structured and used.

It depends on the implementation of it, here is the contract

This object is in JSP or Java Servlet?

This is as an implicit object in jsp and it can be retrieved from request instance from servlet's service method

what situation a JSP page would be appropriate for?(when should I use a Java Servlet and when should I use a Java Servlet Page).For Java Servlet object, for example, ran an email site. There will be a lot of users. How does one Java Servlet object deal with interactions from so many browsers

Use jsp as view servlet as controller, See MVC

now there should be only one copy of Java Servlet object exists. But why? If only one there, when is it created and destroyed.

each request is served in different thread so why to create different instance, we can have one instance of servlet doing all this for us. and its alive until garbage collection clears it
See : Head First

A: I think many of your questions would be answered if you had a look at the Java Servlet Life Cycle.

A: *

*You can think about a session object as a file . every user have a session with id called jsessionid , the structure of a session is normally a map data structure which store key value

in Servlert  you can construct a session object like this
HttpSession session = request.getSession(true);

then you can add item to the session like this
session.setAttribute(string ,object); ex : session.setAttribute("username","foo");

the session object exist in servlet and jsp , and btw jsp eventually is a servlet
but the difference is that when u want to use session in a jsp page there is no need to construct it. its defeind by default just use it
session.setAttribute(string,object);

*

*JSP page used when a page contains a lot of html element and have a lot of design
and jsp let you maintain the page easily on the other hand you can use servlet as jsp page
but you will deal with every line o html source code

JSP is preferred as a view in the MVC model
and the servlet as controller .
the server keeps one object for each servlet and when a new request come the servlet object put the new request (client ) in a new thread  so if you have 100 client at a time the is
100 thread in server . but you can configure the server to construct more than one object of a servlet .
i hope i could help u ..


text:
Q: Search between the third and forth occurrence in a string I have a string that contains some text:
Example:
XPTOP XPTOP 4WS00632 BLACK VERNIS

I want to extract only
4WS00632

and ignore everything else.
I did try indexing the spaces, using charindex for searching all the spaces and then a substring to start at x, end at y.
But, no luck. Sometimes it returns "4WS0063" or "P 4WS00632".
This data is not coherent only "XPTOP XPTOP" is somewhat coherent.
For instance "4WS00632" this has 8 digits, but it might have 9 or 12.
So, I really need to catch everything in between the 3rd space and 4th space.

A: Yet another option is with a bit of JSON
Example or dbFiddle
Select A.SomeCol
      ,NewVal = JSON_VALUE('["'+replace(SomeCol,' ','","')+'"]','$[2]')
 From YourTable  A

Results
SomeCol                                 NewVal
XPTOP XPTOP 4WS00632 BLACK VERNIS       4WS00632

A: Try this technique:
DECLARE @text NVARCHAR(MAX) = 'XPTOP XPTOP 4WS00632 BLACK VERNIS';

DECLARE @text_xml XML = '' + REPLACE(@text, ' ', '')+ '';

WITH DataSource (element_pos, element_text) AS
(
    SELECT  ROW_NUMBER() OVER (ORDER BY T.c)
           ,T.c.value('(.)[1]', 'nvarchar(128)')
    FROM @text_xml.nodes('a') T(c)
)
SELECT element_text
FROM DataSource
WHERE element_pos = 3;

The idea is to split the string by space and order the strings by their position. Then simply get the 3rd one.

A: This is one way of using a combination of charindex and stuff.
It could be done in a single statement but I broke it into a couple of logical steps to make it clearer.
create table #test (col1 varchar(100))
insert into #test values ('XPTOP XPTOP 4WS00632 BLACK VERNIS')

with s1(s) as (select Stuff(col1,1,CharIndex(' ',col1),'') from #test),
s2(s) as (select Stuff(s,1, CharIndex(' ',s),'') from s1)

select Left(s, charIndex(' ',s) )
from s2;

A: One method is string_split() along with some like comparisons:
select t.*, s.value
from t cross apply
     (select s.value
      from string_split(t.str, ' ') s
      where t.str like concat('% % % ', s.value, ' %') and
            t.str not like concat('% % % % ', s.value, ' %')
     ) s

A: Here is a solution using charindex - and substring:
Declare @testTable Table (TestString varchar(100));
 Insert Into @testTable (TestString)
 Values ('XPTOP XPTOP 4WS00632 BLACK VERNIS')
      , ('XYZ XYZ JW2B0037VK3 S17 SENAPE BLACK');

 Select tt.TestString
      , part1 = ltrim(substring(v.TestString, 1, p01.pos - 2))
      , part2 = ltrim(substring(v.TestString, p01.pos, p02.pos - p01.pos - 1))
      , part3 = ltrim(substring(v.TestString, p02.pos, p03.pos - p02.pos - 1))
   From @testTable                                                      As tt
  Cross Apply (Values (concat(tt.TestString, replicate(' ', 3))))       As v(TestString)
  Cross Apply (Values (charindex(' ', v.TestString, 1) + 1))            As p01(pos)
  Cross Apply (Values (charindex(' ', v.TestString, p01.pos) + 1))      As p02(pos)
  Cross Apply (Values (charindex(' ', v.TestString, p02.pos) + 1))      As p03(pos)


text:
Q: Can't add Alamofire to project with cocoapods I'm trying add Alamofire to my project using Cocoapods, doing the same thing in the quick start, changing pods file, but still can't import Alamofire.
Is there something that I must more to do?

A: In order to use CocoaPods written in Swift, you must explicitly include use_frameworks! in your Podfile to opt into using frameworks. Like this:
platform :ios, "8.0"
use_frameworks!

pod 'Alamofire', '2.0'

Without including this you'll get an error when you try to install the pods like Alamofire.


text:
Q: MySQL character set CLI and Workbench show different results
Q: Character sets shown by the MySQL CLI command lines and my MySQL workbench show different results. Why is that?
I've run into MySQL 'chcp' error and cannot view my server status after updating my MySQL workbench, current version is 8.0.27. So after searching up some google have found out it's MySQL Workbench bug dealing with other non-Engligsh languages and I've found out some solutions which were to have System variable Path include System32 and MySQL bin folder which are included well to my system path variable. Other solutions were to change my system language to English, or either check to using UTF-8 in my system locale settings. But the first solution would be very inconvenient for me to use my computer and the second solution made my console applications not able to handle non-English characters. The final solution I've found was to change the C:\Program Files\MySQL\MySQL Workbench 8.0\workbench\os_utils.py the internal code
process = subprocess.Popen(command, stdin = subprocess.PIPE, encoding="utf-8", stdout = subprocess.PIPE, stderr = subprocess.STDOUT, shell=True)
from utf-8 to other codepage. But I'm anxious that that would occur other internal bugs so I haven't tried it yet.
Q: Are there any alternative solution to this "chcp" error? except for downgrading the workbench?


text:
Q: I Want to receive a mail from a particular location Here is my Code
http://codepad.org/NHykpcrq
I have given each location a separate id. I want a mail to let me know that i received from that Location.

A: You can just assign a value in your if statements (you might want to change this to a switch statement)
if ($host == 'locahost/dribblefootball/calendar_new/calendar.php?id=1') {
    $to = 'tanmay.kamath1992@gmail.com';
    $location = 'Some Name for this thing';
} elseif ($host == 'locahost/dribblefootball/calendar_new/calendar.php?id=2') {
    $to = 'tanmay.kamath1992@gmail.com';
    $location = 'Some Name for this thing 2';
} elseif ($host == 'locahost/dribblefootball/calendar_new/calendar.php?id=3') {
    $to = 'tanmay.kamath1992@gmail.com';
    $location = 'Some Name for this thing 3';
} else { //other options
    $to = 'others@mysite.com';
    $location = 'Some Name for this thing else';
}
$formcontent .= '\n Sent from '.$location;

There might be a spelling mistake in your localhost thing :), another idé (which makes it portable) is to change the thing your looking for to be something like this:
($_GET['id'] === 1)

And so on.
EDIT
A switch statement with the 2 changes would look like this
switch ($_GET['id']) {
    case 1:
        $to = 'tanmay.kamath1992@gmail.com';
        $location = 'Some Name for this thing';
        break;
    case 2:
        $to = 'tanmay.kamath1992@gmail.com';
        $location = 'Some Name for this thing 2';
        break;
    case 3:
        $to = 'tanmay.kamath1992@gmail.com';
        $location = 'Some Name for this thing 3';
        break;
    default:
        $to = 'others@mysite.com';
        $location = 'Some Name for this thing else';
        break;
}


text:
Q: Show number of notifications on icon I have a notification icon (font-awesome) which shows the number of notifications.
I am having a problem trying to get the number to display in the correct position, as shown in see below image

I need the text to be smaller and move right and up a little...
here is the code
.header .bubble {
  border-radius: 100%;
  height: 14px;
  width: 14px;
  background-color: rgba(226, 32, 91, 0.77);
  color: #ffffff;
  text-align: top;
  position: relative;
  top: 0px;
  float: right;
  right: -3px;
}

 2

Can anyone help, I am new to this.

A: example1: using background image
The best way to do this is to use position:absolute to child span of parent anchor.

a.notif {
  position: relative;
  display: block;
  height: 50px;
  width: 50px;
  background: url('http://i.imgur.com/evpC48G.png');
  background-size: contain;
  text-decoration: none;
}
.num {
  position: absolute;
  right: 11px;
  top: 6px;
  color: #fff;
}
2

example2: using font awesome icon
If you want to use font-awesome icon
this is code for it

a.fa-globe {
  position: relative;
  font-size: 2em;
  color: grey;
  cursor: pointer;
}
span.fa-comment {
  position: absolute;
  font-size: 0.6em;
  top: -4px;
  color: red;
  right: -4px;
}
span.num {
  position: absolute;
  font-size: 0.3em;
  top: 1px;
  color: #fff;
  right: 2px;
}
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />

  2


text:
Q: LINQ to SQL - further modifying IQueryable result set with Contains I am using LINQ to SQL and I am allowing users to set up the query via assigning values to queryStrings in the UI. I set up the primary query to return an IQueryable result and then keep refining the results set by continuing to act upon the resulting IQueryable object. Everything works fine and the code looks similar to this
var result = (from record in db.Companies
select new Company
{
     Id = record.Id,
     Name = record.Name,
     City = record.City,
     Status = record.Status
});
if (queryName != null && queryName!= "")
{
  result = result.Where(p => p.Name.Contains(queryName));
}

if (queryCity != null && queryCity!= "")
{
   result = result.Where(p => p.City.StartsWith(queryCity));
}

Now I want to extend the query my getting matching a set of elements similar to "IN CLAUSE" in SQL. Where there is a list of elements to use in the query e.g.
string[] queryStatusList = {"x", "y" };

And now I can write the code like this and everything is still OK.
var result = (from record in db.Companies
where queryStatusList.Contains(record.status)
   select new Company
   {
      Id = record.Id,
      Name = record.Name,
      City = record.City,
      Status = record.Status
   });
if (queryName != null && queryName!= "")
{
  result = result.Where(p => p.Name.Contains(queryName));
}

if (queryCity != null && queryCity!= "")
{
   result = result.Where(p => p.City.StartsWith(queryCity));
}

But, I don't want to have a where clause in the initial query. I want to build from the refined query result as done in the previous example. My question is how would I structure such a query. I tried
if (queryStatusList != null && queryStatusList.Count() > 0)
{
    result = result.Where(queryStatusList.Contains(result.Select(p => p.Status.ToString())));
}

But I get a compiler error: "The type arguments for method 'System.Linq.Enumerable.Contains(System.Collections.Generic.IEnumerable, TSource)' cannot be inferred from the usage. Try specifying the type arguments explicitly" I have tried a few variations but I'm not sure how to fix the issue.

A: I think if you change it slightly, it may work:
if (queryStatusList != null && queryStatusList.Count() > 0)
{
    result = result.Where( r=> queryStatusList.Contains( r.Status ));
}

On the other hand, you might want to look at using a PredicateBuilder to build up a single Where clause selector and use it instead.  The PredicateBuilder will give you more control and the ability to create complex queries with a mix of AND and OR clauses while still building them up dynamically.
var predicate = PredicateBuilder.True<Company>();

if (queryName != null && queryName!= "")
{
    predicate = predicate.And( p => p.Name.Contains(queryName) );
}

if (queryCity != null && queryCity!= "")
{
   predicate = predicate.And(p => p.City.StartsWith(queryCity));
}

if (queryStatusList != null && queryStatusList.Count() > 0)
{
    predicate = predicate.And( p => queryStatusList.Contains( p.Status ));
}

var result = db.Companies
               .Select( c => new Company
                {
                    Id = record.Id,
                    Name = record.Name,
                    City = record.City,
                    Status = record.Status
                }
               .Where( predicate );


text:
Q: How to get the y angle between 2 vectors in Three.js? In Three.js I have 2 3d vectors and I want to find the x-axis and y-axis angle between them.
For the x-axis I found this
toDegrees(atan2(A.z, A.y) - atan2(B.z, B.y))

from
The X angle between two 3D vectors?
which works, but for y-axis, I am trying
toDegrees(atan2(A.z, A.x) - atan2(B.z, B.x))

but it gives me the wrong value. How can I fix this?
Thanks

A: You can use Vector3.angleTo directly, it will give you the angle in radians, as usual to math functions, here I printing it in degrees (multiplying by 180 degrees/pi rad= 1)

// notice that v1 is pointing to the x-axis direction.
const v1 = new THREE.Vector3(10,0,0);
const v2 = new THREE.Vector3(3,3,0);
const v3 = new THREE.Vector3(0, 50, 23);
// Alngle between v1 and v2
console.log(v1.angleTo(v2)*180/Math.PI)
// The operation is comutative
console.log(v2.angleTo(v1)*180/Math.PI)
// An example at 90 degree
console.log(v1.angleTo(v3)*180/Math.PI)
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>

This makes it possible to find angles to any direction, if you want angle to a plane for instance, it is given by ans(a - 90) where a is the angle in degrees to the normal vector of the plane.


text:
Q: The PHP doesn't rwite in my DB I have this little problem (I think with syntaxis). First of all I have my form in HTML that have a lot of options:
<form action="chyrons.php" method="get">
            Categoría C10 Informatiu: <select name="categoria_c10"; style="font-size:16px">
                <option value="CULTURA">CULTURA</option>
                <option value="SOCIETAT">SOCIETAT</option>
                <option value="POLÍTICA">POLÍTICA</option>
                <option value="ESPORTS">ESPORTS</option>
            </select>
             | Categoría ADVOR:<select name="categoria_advor"; style="font-size:16px">
                <option value="CARDEDEU">CARDEDEU</option>
            </select>

Breu: <input type="text"; required size="125"; name="breu"; placeholder="Cardedeu es super guay!"; style="font-size:15px";/>

  Minut Chyron: <input type="text"; required size="6"; name="minut_breu"; placeholder="MM:SS"; style="font-size:15px";/>

Persona Entrevistada: <input type="text"; required size="20"; name="nom_entrevistat"; placeholder="Enric Olivé"; style="font-size:15px";/>

Carreg: <input type="text"; required size="30"; name="carreg_entrevistat"; placeholder="Alcalde de Cardedeu"; style="font-size:15px";/>

  Minut Chyron: <input type="text"; required size="6"; name="minut_entrevista"; placeholder="MM:SS"; style="font-size:15px";/>

                <button class="add_form_field">Afegeix un chyron   + </button>

Informa C10 Informatiu: <input type="text"; required size="20"; name="informa_c10"; placeholder="Reno 1 y Reno 2"; style="font-size:15px";/> | Informa ADVOR: <input type="text"; required size="20"; name="informa_advor"; value="RTVCardedeu"; disabled style="font-size:15px";/>

  Minut Chyron: <input type="text"; required size="6"; name="minut_informa"; placeholder="MM:SS"; style="font-size:15px";/>

<input type="submit"; value="Processar"; style="font-size:15px";/>
        </form>

If you see, this form goes to "chyrons.php":
<?php
$servername = "***.***.**.***";
$username = "*******";
$password = "*******";
$dbname = "******";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$sql = "INSERT INTO chyrons (categoria_c10, categoria_advor, breu, minut_breu, nom_entrevistat, carreg_entrevistat, minut_entrevista, informa_c10, informa_advor, minut_informa)
VALUES ($_GET['categoria_c10'], $_GET['categoria_advor'], $_GET['breu'], $_GET['minut_breu'], $_GET['nom_entrevistat'], $_GET['carreg_entrevistat'], $_GET['minut_entrevista'], $_GET['informa_c10'], $_GET['informa_advor'], $_GET['minut_informa'])";

if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "
" . $conn->error;
}

$conn->close();
?>

For obvious reasons I just write *** in the server name and others. The issue is on line 15, that says:

Parse error: syntax error, unexpected '' (T_ENCAPSED_AND_WHITESPACE), expecting identifier (T_STRING) or variable (T_VARIABLE) or number (T_NUM_STRING) in /usr/home/*******/web/chyrons.php on line 15

Here is my DB created:
My DB created
DB Table
I don't understand the error...
If can I get some help, I would be very grateful!