text:
Q: AngularJS and efficiency (or: storing values for multiple uses) I recently started studying a bit of AngularJS (with almost no previous experiences in programming). I would like to create a tool for statistical analysis and to do so I worked on a few "proof-of-concept" examples.
Like this one: http://jsfiddle.net/nitecorp/udcjnoxo/
It works but I have the feeling that the way I am using the functions is highly inefficient:

    Average Age
    {{getAverage()}}

    Younger
    {{getStats(getAges())['younger']}}

    Older
    {{getStats(getAges())['older']}}

Question
What is the right approach to store getAges and use the results instead of recalculating every time? Same for getStats: can I just store the values instead of recalculating twice (in the example)?
Note: In this example is not a big deal, but I need to apply that code to a more complex scenario, with more complex stats (standard deviation, variance etc) and using more than 1M values...
Thanks

A: Use a $watch to listen for updates to your data structure, then update your variables accordingly.
I've created a fork of your fiddle to illustrate this, with the code below demonstrating the important bits:
$scope.$watch(
    function(scope) {
        return $scope.dogs.length;
    },
    function(oldVal, newVal) {
        console.log('dogs changed');
        $scope.updateStats($scope.getAges());
        $scope.updateAverage();
    });


text:
Q: How to overwrite each line in a file with a string I have a string pattern that has to be overwritten from the second to 207th line of a file.
Currently I have this method to overwrite every 0, 1 or space in the full pattern (which is 207 lines of 3000 length each).
using (var fileStream = File.Open(filePath + fileName, FileMode.OpenOrCreate, FileAccess.Write))
        {
            var minLength = Math.Min(pattern.Length, fileStream.Length);
            Console.WriteLine("Started overwriting file " + fileName);
            for (var i = 0; i < minLength; i++)
            {
                fileStream.Position = i;

                if (pattern[i] == '0')
                {
                    fileStream.WriteByte(byteCharZero);
                }
                else if (pattern[i] == '1')
                {
                    fileStream.WriteByte(byteCharOne);
                }
                else if (pattern[i] == ' ')
                {
                    fileStream.WriteByte(byteCharSpace);
                }
            }
        }

This method works like a charm, till line 110. Then it jumps back one space and on line 161 it does the same thing again. That way the pattern is not in the correct place.
I don't know why this is, but I will approach the problem in another way to solve it:
Now I want to overwrite the second till 207th line with a string pattern that consist of one line. How do I accomplish overwriting separate linse in the method above?

A: You are talking about "lines", so the first thing to check is the line-endings. Is it, perhaps, that the line-endings are usually CRLF, except for near line 161 where it is just CR or LF? A different line-ending would certainly account for an off-by-one.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Surjectivity of x^2 - floor(x)^2 How would I go about proving $f(x) = x^2 - \lfloor x\rfloor^2$ is surjective when $f: \mathbb{R}^{\geq 0} \to \mathbb{R}^{\geq 0} $?
Not sure where to start...
I believe it's true but but it almost seems too easy but proving it is a challenge for me.

A: Hint: The image of the interval $[n,n+1)$ is $[0,1+2n)$.
Spoiler:

 $x=n+y$ with $y \in [0,1)$ implies $f(x)=y^2+2ny$.

Here is a plot:

A: Let $t \geq 0$. Choose any $n >\frac {t-1} 2$ and take $x =\sqrt {t+n^{2}}$. Then $f(x)=t$.  [You can check that $n \leq x \leq n+1$. So $f(x)=x^{2}-n^{2}=t$].


text:
Q: Narrow down DT using plotly_click in Rmarkdown Plot plotly heatmap on Rmarkdown. I want to display the DT of the clicked data by clicking the heatmap. It was possible with Shiny. Is it possible to reproduce this function with Rmarkdown? Thank you
rmarkdown.Rmd
```{r}
library(plotly); library(DT); library(shiny)
p <- plot_ly(data=iris, x=~Sepal.Length, y=~Sepal.Width, z=~Petal.Length, type="heatmap", source = "heat")
p

observeEvent(event_data("plotly_click", source = "heat"),{

x <- event_data("plotly_click", source = "heat")$x
iris_ <- filter(iris, Sepal.Length == x)

dt <- datatable(iris_)

})
dt
```

A: This is the only way I could get it to work, but hoping you can convert this into a heatmap. For me, the heatmap wasn't rendering properly. This example uses the crosstalk function and utilizes brushing and will auto render the DT table of the selected table.
```{r}
library(ggplot2)
library(plotly)
library(DT)

m<-highlight_key(iris)
p<-ggplot(m,aes(Sepal.Length,Sepal.Width))+geom_point(aes(color = Species))
gg<-highlight(ggplotly(p),"plotly_selected")
crosstalk::bscols(gg,DT::datatable(m))
```


text:
Q: How to upload single file on AWS elastic beanstalk I uploaded an php laravel application on elastic beanstalk. When I need to update a single file i need to zip the complete application and upload the new version.
Is there any option to upload only the single file in elastic beanstalk?


text: Q: Is it possible to run android studio in ubuntu 12.04 32 bit system I'm trying to install Android Studio on 32-bit machine having Intel Dual-Core processor (32-bit) with 4 GB RAM and Intel mobility graphics on Ubuntu 14.04 operating System, but after executing "studio.sh" file I couldn't find any response from Android Setup Wizard nor Android Studio.


text:
Q: How do I generate a 'live preview' of a textbox? Just like on SO when typing a question, I see the live version included in a box below the textbox - or on Github, I can simply go to 'preview' without saving the record, how do I achieve that with Rails?
Assume I have a Question model, that has an attribute of body that I want to see a live preview (either character by character or by pressing a preview button that shows it).

A: in HTML you can put this:
<% if params[:preview_button] %>
 <%= textilize @project.description %>
<% end %>

...
<%= submit_tag 'Create' %>
<%= submit_tag 'Preview', :name => 'preview_button' %>

*# => params = { "preview_button" => "Preview" ....* - you will see;
def create
 @project = Project.new(params[:project])
 if params[:preview_button] || !@project.save
   render :action => 'new'
 else
   flash[:notice] = "Successfully created project."
   redirect_to project_path(@project)
 end
end

You can rewrite create action, add ajax to form preview by putting remote: true
i try to show main idea.


text:
Q: TRESTClient capture a reasonably exception cause, e.g. when server is not available I'm struggeling with how to capture the exception cause when I send a RESTRequest to a server which isn't available at the time of the request.
I do get an exception, but it's really a poor exception to work with when I need to present a error message dialog to the user and e.g. disconnect the client.
Question is: How am I supposed to capture the "right" exception in my application, the details of which are "hidden" and end up as a relatively useless ERESTException?
This is not an EHTTPProtocolException, so the event on the client or request will not occur on this error.
BTW. Using Delphi 10.2.1.
The ERESTException.Message I receive back, looks like this:
Exception REST request failed: Error sending data: (12029) A connection with the server could not be established
I'm using TRESTClient, TRESTRequest and TRESTResponse.
When I execute a request to an offline REST service it fails (of course)
System.Net.HttpClient.Win

function TWinHTTPClient.DoExecuteRequest(const ARequest: THTTPRequest; var AResponse: THTTPResponse;
  const AContentStream: TStream): TWinHTTPClient.TExecutionResult;
.....

  // Send Request
  LRes := WinHttpSendRequest(LRequest.FWRequest, WINHTTP_NO_ADDITIONAL_HEADERS, 0, WINHTTP_NO_REQUEST_DATA, 0, LDataLength, 0);
  if not LRes then
  begin
    LastError := GetLastError; // this returns 1209
    case LastError of
      ERROR_WINHTTP_SECURE_FAILURE:
        Exit(TExecutionResult.ServerCertificateInvalid);
      ERROR_WINHTTP_CLIENT_AUTH_CERT_NEEDED:
        Exit(TExecutionResult.ClientCertificateNeeded);
      else
        raise ENetHTTPClientException.CreateResFmt(@SNetHttpClientSendError, [GetLastError, SysErrorMessage(GetLastError, GLib.Handle)]);
    end;
  end;

ENetHTTPClientException is raised and captured in REST.Client
procedure TCustomRESTRequest.Execute;
      try
.....

      except
        // any kind of server/protocol error
        on E: EHTTPProtocolException do
        begin
          FExecutionPerformance.ExecutionDone;
          // we keep measuring only for protocal errors, i.e. where the server actually anwered, not for other exceptions.
          LContent := E.ErrorMessage; // Full error description

          //Fill RESTResponse with actual response data - error handler might want to access it
          ProcessResponse(LURL, LResponseStream, LContent);

          if (E.ErrorCode >= 500) and Client.RaiseExceptionOn500 then
            raise ERESTException.Create(E.Message);
          HandleEvent(DoHTTPProtocolError);
        end;
        // Unknown error, might even be on the client side. raise it!
        on E: Exception do
        begin
          // If Execute raises an Exception, then the developer should have look into the actual BaseException
          raise ERESTException.CreateFmt(sRESTRequestFailed, [E.Message]);
        end;
      end;


text:
Q: Doubt in the range of variance of First Principal Component This is my first problem on this forum. Here is the problem:

The covariance matrix of a four dimensional random vector $\boldsymbol X$ is of the form
$$\begin{bmatrix}1&\rho&\rho&\rho\\
\rho&1&\rho&\rho\\
\rho&\rho&1&\rho\\
\rho&\rho&\rho&1\\
\end{bmatrix}\,,$$ where $\rho<0$. If $v$ is the variance of the first principal component, then

*

*$v$ cannot exceed $5/4$.

*$v$ can exceed $5/4$, but cannot exceed $4/3$.

*$v$ can exceed $4/3$, but cannot exceed $3/2$.

*$v$ can exceed $3/2$.

In this problem, I have been given a covariance matrix of a random variable and I am required to compute the range of variance of first principal component. I am having difficulty dealing with these terms, so I have chosen a specific example where $\rho = -0.5$. So, Now, the resulting matrix is given by:
\begin{pmatrix}
1 & -0.5 & -0.5 &-0.5 \\
 -0.5&1  & -0.5 & -0.5\\
 -0.5&  -0.5&  1& -0.5\\
 -0.5&  -0.5&  -0.5& 1
\end{pmatrix}
If I take $\lambda = 1.5$ then this satisfies the characteristic equation ($|A - \lambda I|$ = 0) of the resulting matrix and hence it will be one of the roots of the characteristic equation. I also know that variance of principal component is nothing but characteristic roots. Now, I only have one root at this point and from there only I can see that $\lambda = \frac{3}{2}$ which does not lead to any of the options given. The correct answer is shown as (b).

A: Let $\Sigma$ be the covariance matrix of $\boldsymbol X$. Variance of the first principal component is then the largest eigenvalue of $\Sigma$.
Now you can write $\Sigma=(1-\rho)I_4+\rho\mathbf1\mathbf1'$ where $\mathbf1$ is a column vector of all-ones, which means you can use the Matrix determinant lemma to find the characteristic polynomial $\det(\Sigma-\lambda I_4)$ and solve for the eigenvalues of $\Sigma$. Or you might take it as a standard result (see this or this) that there are two distinct eigenvalues of $\Sigma$, namely $1-\rho$ (with multiplicity $3$) and $1+3\rho$. This is perhaps easy to remember if you recall that $\det\Sigma=(1-\rho)^3(1+3\rho)$. Because $\rho$ is negative, the largest eigenvalue is $1-\rho$.
Observe that $$0\le\operatorname{Var}(\mathbf 1'\boldsymbol X)=\mathbf 1'\Sigma\mathbf 1=4(1+3\rho)$$
This yields $$\rho\ge -\frac13 \quad,\text{ i.e. },\quad 1-\rho\le \frac43$$
One can also use $\det\Sigma\ge 0$ to obtain this bound.
Combining this with $\rho<0$, we have $$1<1-\rho\le \frac43$$
There is no other restriction on $1-\rho$, so option (2) is correct.


text:
Q: Call binary from React Native? Is it possible to include and exec a compiled binary inside a React Native project? I'm exploring handling the business logic in React Native with languages other than Javascript, but still have the compiled code be cross platform.

A: You can access native modules, so uncompiled source code in either Java or Objective-c / Swift is possible. Compiled binaries are always compiled for one platform, which means that you can not link such binaries in to react native. For moving the logic away from Javascript, you have two options

*

*Connect a web server and store most of the business logic there, so use the iOS / Android app mostly as a view layer.

*Find a transpiler, that transpiles the language you would like to use to Javascript


text:
Q: Parsing JSON array to Server with Swift 3.0 I am trying to send a JSON array to the web server. I have looked at several examples online i.e. https://www.youtube.com/watch?v=aTj0ZLha1zE&t and Saving CoreData to a Web Server with Swift 3.0 that have demonstrated how to parse data but I am struggling to achieve this.
Below is my function which should send the data to the server:
func sendRecordToServer() -> [Record] {

        let fetchRequest = NSFetchRequest<NSDictionary>(entityName:"Record")
        fetchRequest.resultType = .dictionaryResultType
        do {
            let records = try context.fetch(fetchRequest)

            if let jsonData = try? JSONSerialization.data(withJSONObject: records, options: []) {
                // jsonData is a byte sequence, to view it you would need to convert to string
                print(String(bytes: jsonData, encoding: String.Encoding.utf8))

                let URL_SAVE_DATA = URL(string: "http://localhost/api/postdata.php")
                let request = NSMutableURLRequest(url: URL_SAVE_DATA!)

                request.httpMethod = "POST"
                request.httpBody = jsonData

                let task = URLSession.shared.dataTask(with: request as URLRequest){
                    data, response, error in

                    guard let data = data, error == nil else {
                        // check for fundamental networking error
                        print("error=\(String(describing: error?.localizedDescription))")
                        return
                    }

                    let responseString = String(data: data, encoding: .utf8)
                    print("responseString = \(String(describing: responseString))")
                }
                task.resume()
            }

        } catch {
            print("Error fetching data from CoreData")
        }
        return records
    }

After encoding the data to JSON, it prints out like this:

Optional([["record_id": 8EC9C1C9-7DD4-4343-B7CC-E4615FDDA150, "name": John ], ["record_id": 7EEA551D-9432-4737-99FB-6BFCF3A92D21, "name": Fred Smith]])

However as I try parsing it though to the server I get this and nothing get sent to the server:

responseString = Optional("")

Update:
Following up from the comment below here is what my posdata.php looks like:
<?php

//creating response array

$json = file_get_contents('php://input');
//echo $json shoulkd show the json string

$array = json_decode($json, true);
// var_dump($arr) should show the array structure

$response = array();

if($_SERVER['REQUEST_METHOD']=='POST'){

    //getting values
    $record_id = $_POST['record_id'];
    $name = $_POST['name'];

    //including the db operation file
    require_once '../includes/DbOperation.php';

    $db = new DbOperation();

    //inserting values
    if($db->createTeam($record_id, $name)){
        $response['error']=false;
        $response['message']='Record added successfully';
    }else{

        $response['error']=true;
        $response['message']='Could not add record';
    }

}else{
    $response['error']=true;
    $response['message']='You are not authorized';
}
echo json_encode($response);

DBOperation:
<?php

class DbOperation
{
    private $conn;

    //Constructor
    function __construct()
    {
        require_once dirname(__FILE__) . '/Config.php';
        require_once dirname(__FILE__) . '/DbConnect.php';
        // opening db connection
        $db = new DbConnect();
        $this->conn = $db->connect();
    }

    //Function to create a new user
    public function createTeam($record_id, $name)
    {
        $stmt = $this->conn->prepare("INSERT INTO record (record_id, name) values (?, ?)");
        $stmt->bind_param("si", $record_id, $name);
        $result = $stmt->execute();
        $stmt->close();
        if ($result) {
            return true;
        } else {
            return false;
        }
    }

}


text:
Q: Ionic Cordova Run Browser give device permissions quick question.
I am currently working on an ionic application which I am testing using the comman 'ionic cordova run browser'. This works fine for most things, however when I try to upload an image to the application I get the following message
Permission Denied
Sorry, we don't have
permission to access your
device's images. Please check
the settings on your phone
and try again.

While I understand where this message comes from and why it appears, my question is how to I make it think that it has the required permissions when running on the browser?


text:
Q: Godot with C# command line problem EditorSettings::_get - Property not found When I open Godot and try to create new project this prompt with this error pops up:
Mono: Logfile is: C:\Users\Admin\AppData\Roaming/Godot/mono/mono_logs/2020_05_19 23.56.43 (2276).txt
WARNING: _get: EditorSettings::_get - Property not found: mono/editor/editor_path_optional
     At: editor/editor_settings.cpp:151

A: This is a harmless but known issue which will be fixed in Godot 3.2.2.


text:
Q: JAXB/Jersey issue with unmarshaling complex types with interfaces I'm struggling with the few problems marshal/unmarshall JSon and it looks i will never get it work :(
Look the first issue: I have a class Response that contains few fields: String error, String error_code and Object response. Class responsible to fill all the data to response, fill the error fields if needed and send it back to the client for further analisys.
"Object response" can be any of type (why Object? because it didn't worked with interfaces and that would be the second part of the question)
code snippet:
   @XmlRootElement
    @XmlAccessorType(XmlAccessType.FIELD)
    public class Response
    {
        public static final String ERROR_FIELD_NAME = "error";
        public static final String ERROR_CODE_FIELD_NAME = "error_code";
        public static final String RESPONSE_FIELD_NAME = "response";

        @XmlElement(name = Response.ERROR_CODE_FIELD_NAME)
        private String errorCode;

        @XmlElement(name = Response.ERROR_FIELD_NAME)
        private String errorMessage;

        @XmlElementRefs(
            {@XmlElementRef(type = AClassResponse.class),
        @XmlElementRef(type = BClassResponse.class)})
        private Object entity;

and etc...
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.adapters.XmlAdapter;

//@XmlRootElement(name = Response.RESPONSE_FIELD_NAME)
//@XmlJavaTypeAdapter(AClassResponse.Adapter.class)
@XmlRootElement
public class AClassResponse
{
    private TargetObject target;

    public TargetObject getTarget()
    {
        return target;
    }

    public void setTarget(TargetObject target)
    {
        this.target = target;
    }
}

JSON 1 (for XmlElementRef AClassResponse.class ):
    {
      "error" : "",
      "error_code" : "",
      **"aClassResponse" :**
         { "target" :
            { "accountId" : "5bd0812b",
              "id" : "6ccb6ae1-30c3-4aa0-8d1e-6ed61b6bb217",
              "isCaseSensitive" : "false",
              "maxNumberOfConnections" : "0",
              "name" : "targetName",
              "pathDelimiter" : "/",
              "type" : "SMB"
            }
         }
    }

JSON 1 (for XmlElementRef BClassResponse.class):
   {
      "error" : "",
      "error_code" : "",
      **"bClassResponse" :**
         { "target" :
            { "accountId" : "5bd0812b",
              "id" : "6ccb6ae1-30c3-4aa0-8d1e-6ed61b6bb217",
              "isCaseSensitive" : "false",
              "maxNumberOfConnections" : "0",
              "name" : "targetName",
              "pathDelimiter" : "/",
              "type" : "SMB"
            }
         }
    }

Now the problem:
Look on JSon above, "aClassResponse" : and "bClassResponse" : are always dynamic (means the name is derived from the class name) - an this is not what I need.
My goal is to give this name a persistent name "response", so any remote clients will aware about this and rely on this name.
I know, to fix that I can annotate AClassResponse.class with @XmlRootElement(name = "response"), and it does work untill you have more than one @XmlElementRef defined.
If two or more, this cause an issue with marshaling/unnmarshaling, and JAXB doesn't know what class to bind it should bind to the entity field, since it rely on name as well (name = "response")
@XmlElementRefs(
        {@XmlElementRef(type = AClassResponse.class),
        @XmlElementRef(type = BClassResponse.class)})
        private Object entity;

it treat it like this:
@XmlElementRefs(
            {@XmlElementRef(name = "response", type = AClassResponse.class),
            @XmlElementRef(name = "response", type = BClassResponse.class)})
            private Object entity;

Assume this a correct behaviour and there is nothing i can do to keep the the same (name = "response") for any of object types.
OK, i tried to workaround it by introducing interface instead of Object type  + @XmlJavaTypeAdapter(AClassResponse.Adapter.class) for each of implementation - however it didn't worked either, throwing exception that interfaces are not supported and etc...
This article seems can shed some light on this, http://jaxb.java.net/guide/Mapping_interfaces.html
but it fails too, saying that it can't instantiate abstract class abstract class AbstractFooImpl
@XmlJavaTypeAdapter(AbstractFooImpl.Adapter.class)
interface IFoo {
  ...
}
**abstract class AbstractFooImpl implements IFoo {**
  ...

  static class Adapter extends XmlAdapter<AbstractFooImpl,IFoo> {
    IFoo unmarshal(AbstractFooImpl v) { return v; }
    AbstractFooImpl marshal(IFoo v) { return (AbstractFooImpl)v; }
  }
}

class SomeFooImpl extends AbstractFooImpl {
  @XmlAttribute String name;
  ...
}

class AnotherFooImpl extends AbstractFooImpl {
  @XmlAttribute int id;
  ...
}

class Somewhere {
  public IFoo lhs;
  public IFoo rhs;
}

Any advices on how i can workaround this? Please help..
thank you.

A: You could use the @XmlElements annotation and do the following:
@XmlElements({
    @XmlElementRef(name = "response", type = AClassResponse.class),
    @XmlElementRef(name = "response", type = BClassResponse.class)
})
private Object entity;

A: JAXB doesn't do interfaces. The solution is either generics or abstract classes (annotated with @XmlTransient to make JAXB ignore the base class and @XmlSeeAlso to make it use specific implementations instead). That solves the Java part, but you still need to fix the XSD part of the equation (remember that JAXB only sees an XML version of your JSON through Jersey).
For that purpose you can use the @XmlElementRef and @XmlElementRefs annotations on your field so that the XSD will map to a choice of the specific implementations.
@XmlTransient // JAXB doesn't like abstract types, so do not map this type name
// XmlSeeAlso only required if BaseImpl/BaseImpl2 are not otherwise auto-discovered by JAXB
@XmlSeeAlso({BaseImpl.class, BaseImpl2.class })
public abstract class Base {
  @XmlElement(name='still-works')
  public String thisFieldWillStillBeMappedByJAXB;
}

@XmlRootElement("base-impl")
public class BaseImpl {}

@XmlRootElement("alternative")
public class BaseImpl2 {}

public class Complex<E extends Base> {
   @XmlElementRefs({
     @XmlElementRef(type=BaseImpl.class),
     @XmlElementRef(type=BaseImpl2.class)
   })
   public E impl; // will be an instance of either "base-impl" or "alternative"
}


text:
Q: Cannot make working ListView item delete action I'm making some listview based app with ability to delete specific row with a button in it, like on screenshot below: Screenshot
Here are my classes:
MainActivity:
        package com.example.patryk.notes;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    ListView listView;
    LayoutInflater layoutInflater;
    ArrayList<Item> itemList = new ArrayList<Item>();
    ItemArrayAdapter itemArrayAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        itemArrayAdapter = new ItemArrayAdapter(this, R.layout.list_item, itemList);
        listView = (ListView) findViewById(R.id.item_list);
        listView.setAdapter(itemArrayAdapter);

        layoutInflater = getLayoutInflater();
        ViewGroup footer = (ViewGroup) layoutInflater.inflate(R.layout.list_view_footer, listView, false);
        listView.addFooterView(footer);

        itemList.add(new Item("Item", 1));

    }

       public void addRow(View v) {
        itemList.add(new Item("Item", itemList.size() + 1));
           Log.d("add", "metoda add row");
           itemArrayAdapter.notifyDataSetChanged();
       }

}

ItemArrayAdapter
package com.example.patryk.notes;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;

import java.util.ArrayList;

/**
 * Created by patryk on 04.01.2018.
 */

public class ItemArrayAdapter extends ArrayAdapter<Item> {

    private int listItemLayout;
    ImageButton deleteButton;

    public ItemArrayAdapter(Context context, int layoutId, ArrayList<Item> itemList) {
        super(context, layoutId, itemList);
        listItemLayout = layoutId;
    }

    @NonNull
    @Override
    public View getView(final int position, @Nullable View convertView, @NonNull ViewGroup parent) {

        Item item = getItem(position);

        ViewHolder viewHolder;
        if (convertView == null) {
            viewHolder = new ViewHolder();
            LayoutInflater inflater = LayoutInflater.from(getContext());
            convertView = inflater.inflate(listItemLayout,parent, false);
          //  viewHolder.item = (TextView) convertView.findViewById(R.id.row_item);
            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }

        deleteButton = (ImageButton) convertView.findViewById(R.id.xButtonID);
        deleteButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                 **here expected to do something**
            }
        });

        return convertView;
    }

    private static class ViewHolder {
        TextView item;
    }

}

item
package com.example.patryk.notes;

/**
 * Created by patryk on 04.01.2018.
 */

public class Item {

    private String name;
    private double value;

    public Item(String name, double value) {
        this.value = value;
        this.name = name;
    }

    public double getValue() {
        return value;
    }

    public void setValue(int value) {
        this.value = value;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

I've tried many ideas from Stack Overflow but always there has been my clue missing. Firstly I wanted to make delete action on OnclickListener method in ItemArrayAdapter class, but the problem was to access ArrayList "itemList" located in MainActivity class, so I couldn't perform itemList.remove(position).
On the other hand I wanted to make deleteRow method in MainActivity and attach it to delete button on ItemArrayAdapter class by adding android:onClick="deleteRow" tag, but that makes exception similar to that: IllegalStateException
I'd rather chose first idea, so I would like to know how to get access to this ArrayList within adapter class
cheers :)

A: Reference variable of ArrayList is send to the adapter class. So you can easily do this:
public class ItemArrayAdapter extends ArrayAdapter<Item> {

        private int listItemLayout;
        ImageButton deleteButton;
        private ArrayList<Item> itemList;

        public ItemArrayAdapter(Context context, int layoutId, ArrayList<Item> itemList) {
            super(context, layoutId, itemList);
            listItemLayout = layoutId;
            this.itemList = itemList;
        }

Then
deleteButton = (ImageButton) convertView.findViewById(R.id.xButtonID);
deleteButton.setTag(position);
deleteButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int pos = (int) v.getTag();
                    itemList.remove(pos);
                    notifyDataSetChanged();
                    notifyDataSetInvalidated();
                }
            });

A: You don't need to access the MainActivity, item list is available in the constructor
public ItemArrayAdapter(Context context, int layoutId, ArrayList<Item> itemList) {
        super(context, layoutId, itemList);
        listItemLayout = layoutId;
    }

You better assign to a variable and use it.
Like this
Private ArrayList <Item> itemList;
public ItemArrayAdapter(Context context, int layoutId, ArrayList<Item> itemList) {
        super(context, layoutId, itemList);
        listItemLayout = layoutId;
        this.itemList = itemList
    }

After remove please call notifytheDataSetChange method to refresh the list view.


text:
Q: Notes and Attachments on Contacts in Customer Community I don't see Notes and Attachments related list on Contacts.
From page 24  Communities Implementation guide  it says Customer Users don't see Notes and Attachments related list on accounts or contacts

Also there is an idea  related to customer portal

Any work around for this ?


text:
Q: pthread_mutex_t struct: What does lock stand for? I am looking at the pthread_mutex_t structure in the pthreadtypes.h file. What does the "__lock" stand for? Is it like a lock number assigned to the mutex?
typedef union
{
  struct __pthread_mutex_s
  {
     int __lock;
     unsigned int __count;
     int __owner;
     #if __WORDSIZE == 64
     unsigned int __nusers;
     #endif
    /* KIND must stay at this position in the structure to maintain
     binary compatibility.  */
     int __kind;
     #if __WORDSIZE == 64
     int __spins;
     __pthread_list_t __list;
     # define __PTHREAD_MUTEX_HAVE_PREV 1
     #else
     unsigned int __nusers;
     __extension__ union
    {
      int __spins;
      __pthread_slist_t __list;
    };
    #endif
  } __data;
 char __size[__SIZEOF_PTHREAD_MUTEX_T];
 long int __align;

} pthread_mutex_t;

A: The __lock member of struct __pthread_mutex_s __data is used as a futex object on Linux.  Many of the following details may differ depending on the architecture you're looking at:
See the pthread_mutex_lock.c code for the high level locking function for pthread mutexes - __pthread_mutex_lock(), which generally will end up calling LLL_MUTEX_LOCK() and the  definitions of LLL_MUTEX_LOCK() and friends, which end up calling lll_lock(), etc., in lowlevellock.h.
The lll_lock() macro in turn calls __lll_lock_wait_private(), which calls lll_futex_wait(), which makes the sys_futex system call.


text:
Q: Get current input in select2 I'm initializing select2 on multiple inputs. However when making the AJAX call to get the items, I need to pass an additional parameter, which is stored in the data-id attribute of each input which I'm applying select2 on. So I need to get a reference to the current input.
Here's an example:
<input class="event-period" data-id="1"/>
<input class="event-period" data-id="2"/>

<script type="text/javascript">
$('.event-period').select2({
    ajax: {
        url: "/some-url/",
        dataType: 'json',
        delay: 250,
        data: function (params) {
            // need to get data-id of current input here
            // the "this" keyword is the ajax object, so I can't use that
            return {
                query: params.term,
                page: params.page
            };
        },
        processResults: function (data, page) {
            return {
                results: data.items
            };
        }
    }
});
</script>

A: use "each()" JQuery function when you define the inputs
   $('.event-period').each(function(){
      var id = $(this).attr("data-id");
      $(this).select2({
        ajax: {
            url: "/some-url/",
            dataType: 'json',
            delay: 250,
            data: function (params) {
                alert(id); //<-  now you can get this
                // need to get data-id of current input here
                // the "this" keyword is the ajax object, so I can't use that
                return {
                    query: params.term,
                    page: params.page
                };
            },
            processResults: function (data, page) {
                return {
                    results: data.items
                };
            }
        }
      });
    });


text:
Q: Unmatched Vlookup data from another workbook in formula I want to create a master Excel sheet that takes the data from other Excel sheets by using the chassis number of the car as a primary key. I am using the Vlookup (buscarv in Spanish) function in Excel but I don't get the matching data that I want with the function:
=Vlookup(A2;'Listado Julio.xlsx'!Tabla5[#Todo]; 3)

Image showing the formula and the data that it is supposed to show:

Instead, the formula takes the last value of the matrix from where it is supposed to search from the answer.
Could somebody tell me what the formula is missing?

A: If you want to have an exact match, you need to set the last optional argument of vlookup to False, so you your formula would be =Vlookup(A2,'Listado Julio.xlsx'!Tabla5[#Todo], 3, FALSE)

A: An easy way would be to tell it exactly which columns to use:
=VLOOKUP(A2,Listado!B:C,2,0)

There might be some regional formatting differences. The last arg for me is 0, which means only return exact matches.

A: In cell B2 you could also enter an INDEX MATCH function instead of the v-lookup. The INDEX MATCH can replace all v-lookup and h-lookup tasks and requires less processing power as Excel does not have to count the rows / columns.
In cell B2 enter:
=INDEX('Listado'!C:C,MATCH('Hoja1'!A2,'Listado'!B:B,0))

Then copy that formula down the column.


text:
Q: image manipulation with Glide is not working I am using Glide image library without framework.I follow the tutorial
http://glide.thephpleague.com/1.0/installation/
My question is most likely How to use image manipulation library Glide with plain PHP but it is not my question and that solution not work for me.
when I point url localhost/myproject/routes.php nothing displayed.
when I print the $server variable it is printed.
<?php
require 'vendor/autoload.php';
use League\Flysystem\Adapter\Local;
use League\Flysystem\Filesystem;
use League\Glide\ServerFactory;

// Setup Glide server
$server = League\Glide\ServerFactory::create([
    'source' => 'img/users/source',
    'cache' => 'img/users/cache',
]);

echo '<pre>';
print_r($server);
echo '</pre>';

echo $server->outputImage('users/1.jpg', ['w' => 300, 'h' => 400]);


text:
Q: AssertionError: group argument must be None for now python i m using PIR sensor to find out intruder is present or not. if intruder is present it will go to sleep for 1 min now i have to reset sleep time, for this i m using thread but it shows assertion error, help me out, below is my code.
from threading import Thread, Event
import time

import RPi.GPIO as GPIO

class MyThread(Thread):
    def __ini(self, timeout=60):
        self.intruder_spotted = Event()
        self.timeout = timeout

        self.daemon = True

    def run(self):
        while True:
            if self.intruder_spotted.wait(self.timeout):
                self.intruder_spotted.clear()
                print("Intruder")
            else:
                print("No intruder")

t = MyThread(60)

GPIO.setmode(GPIO.BCM)
GPIO.setup(18,GPIO.IN)

try:
    t.start()
    while True:
        i=GPIO.input(18)
        if i==1:
            t.intruder_spotted.set()

        time.sleep(1)

except KeyboardInterrupt:
    GPIO.cleanup()
    exit(0)

A: need Update the int of the class my Thread. It's __init__ not __ini. And the call to the parent init with super
class MyThread(Thread):
    def__init__(self, timeout=60):
    super(MyThread, self).__init__()
    self.intruder_spotted = Event()
    self.timeout = timeout
    self.daemon = True


text:
Q: How to retrieve multiple records from table? I have a table having data.
id type
1  max
1  sam
1  rom
2  jak

I want to retrieve all the type where id=1;
if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) {
            while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
                NSString *aRecord = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 0)];
                NSLog (@"%@",aRecord);
            }

this statement retrive me only the last record. How can i get all the records?
how to catch these records in the variable. I am using aRecord but it store only last record. So this is the main concern

A: The sql ro do this is simply:
select * from <table_name> where id = 1

do something like this:
NSMutableString *myRecords = [NSMutableString initWithString:@""];

if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) {
            while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
                NSString *aRecord = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 0)];

                myRecords = [myRecords stringByAppendingString:[NSString stringWithFormat:@"%@ ",arecord]];
                NSLog (@"%@",aRecord);
                }

As Peter Hosey points out in the comments, this will give you one string with all three records separated by a space.  You probably want to populate an array with these records instead.


text:
Q: Distinction of keyboard and piped file input in Java I am adding a command line interface to a Java program. It receives arguments on the command line and some input from the keyboard. It displays a text message to prompt for each of the necessary keyboard inputs.
If someone redirects the System.in from a file, the display text should be suppressed.
My first approach is to run the following check at startup:
System.in.available() > 0

Is this reliable or is there a better way of distinction?


text:
Q: C++. How to sort by module with saving the original order of elements I'm trying to sort element in vector by module with the condition that the initial order of equal (by module) elements does not change. Logic tells me that the comparator should take less than or equal to save the original order.
std::sort(v.begin(), v.end(), [](int a, int b) {
    return abs(a) <= abs(b);
});

But with and example of 1 -1 1 -1 my compiler return -1 1 -1 1. Unfortunately it saves order with less than sign(I don't understand why).
Decided that std::sort is not stalbe, I tried to use std::stable_sort and with and example of -1 1 1 -1 -1 it reversed elements in order -1 -1 1 1 -1 - Although I expected that the order would not change with a sign less than or equal.
What am I wrong about? Is there a lambda that is guaranteed to preserve the order of the elements?

A:
What am I wrong about?

Your programs had undefined behaviour, because std::sort and std::stable_sort require a strict weak order, which <= isn't. Importantly when you compare an element to itself, the comparison must return (a value that converts to) false.
If you want a stable sort, use std::stable_sort with a valid Compare
std::stable_sort(v.begin(), v.end(), [](int a, int b) {
    return abs(a) < abs(b);
});


text:
Q: RWD Mobile Device Image Swap JavaScript I am using a bit of JavaScript to do an image swap.
Works great on desktop browsers, but not working on mobile/smaller devices.

Any idea's how to make this work on all devices (i.e. desktop, ipads, iphones, other mobile devices)?
New Code:

But onclick, it shoots the page back upto the top of the browser?!?!

A: The 'onmouseover' event isn't really the best choice to make something working cross device, because you simply don't have a mouse on mobile, tablets.
Maybe think about making it working on the click event for mouseless devices ?


text:
Q: Replacing recorded values with Data file - Data driven testing I have recorded a simple Coded UI test from visual Studio 2013. What it does is;

*

*Launches a website

*Fills in a form with (8 fields)

*Saves the form and closes it

Now, I wish to use a data.csv file to replace those 8 values. All the searching I did, I could only find options where every input field had different method hence was easy to find and replace values. In my case, 1 method and 8 fields.
How do I do that? Where do I make the changes since my main file looks like this:

Where and what changes should I make to use CSV file instead of manual values that I recorded.
My designer file code is as below for couple of input fields:
// Type '123456789' in 'i' text box
uIIEdit.Text = this.createKundeParams.UIIEditText;

// Type '{Tab}' in 'i' text box
Keyboard.SendKeys(uIIEdit, this.createKundeParams.UIIEditSendKeys, ModifierKeys.None);

// Type 'Jeff Hardy' in 'name_i' text box
uIName_iEdit.Text = this.createKundeParams.UIName_iEditText;

// Type '{Tab}' in 'name_i' text box
Keyboard.SendKeys(uIName_iEdit, this.createKundeParams.UIName_iEditSendKeys, ModifierKeys.None);

A: you can put all the 8 values in 1 csv row and treat them as one input to be passed to the method that sets the fields, alternatively you can change the method to accept one value and field name and sets the field with the value

A: Create the CSV file.
Add the CSV file to the project.
Make sure the CSV file is deployed.
Add the CSV file as a data source for an individual test.
Read the CSV fields and use them in the test.
The detailed steps, with some variations, are explained below.
Visual Studio 2010 has a "data source wizard" that does some of these steps. Visual Studio versions 2012 and 2013 do not have the wizard and so all the steps have to be done manually.
Create the CSV file
One way is to create the file in a spreadsheet then save it as Comma Separated Values. Another way is to use a text editor and just write the file. I use a spreadsheet program for big data source files and a text editor for creating small files. Some editors add a byte order mark (BOM) at the start of a file, that will be added to the first field name of the CSV which appears to make the field unreadable. See this page for more about the BOM.
Add the CSV file to the project
Use the context menu in solution explorer, select Add -> Existing Item. Then browse to the required file. Note the file filter will probably need to be altered to be . or *.csv.
Make sure the CSV file is deployed
Open the properties panel for the CSV file from solution explorer. Set "Copy to output directory" to "Copy if newer" or to "Copy always". Some documents recommend "Copy if newer" but I prefer "Copy always" as occasionally a file was not copied as I expected. The difference between the two copy methods is a little disk space and a little time, but disks are normally big and the time to copy is normally small. Any savings are, in my opinion, far outweighed by being sure that the file will be copied correctly.
Add the CSV file as a data source for an individual test
Replace the [TestMethod] attribute with the correct data source line. This Microsoft blog shows the replacement code for several possible data source file types. For CSV use:
[DataSource("Microsoft.VisualStudio.TestTools.DataSource.CSV",
    "|DataDirectory|\\data.csv", "data#csv",
    DataAccessMethod.Sequential), DeploymentItem("data.csv"),
    TestMethod]

Note that the file name occurs three times and one copy has a # rather than a .. I have not found any useful documentation about the different fields of the Datasource(...) attribute so cannot advise further on how to choose values for non-CSV data sources.
The |DataDirectory| part above is replaced by the directory where files are deployed when the tests run. The whole file name within the string quotes could be replaced by a full path name of a file, if required.
Read the CSV fields and use them in the test
The Coded UI record and generate tool creates classes with fields that hold values entered into text boxes or used in assertions. Each action method has a ...Params class and each assert method has an ...ExpectedValues class, where the ... is the method name. The default values of these fields are the values used when the test was recorded. The recorded values can be overwritten by an assignment before the action or assertion method is called. The fields of the current row of the data source are accessed from TestContext.DataRow[...].
Suppose a Coded UI test has an EnterValue method that writes text into two fields of the screen and it also has a CheckResult method that asserts one field. The test method might then be written as follows.
[DataSource...
    TestMethod]
public void CodedUITestMethod1()
{
    this.UIMap.EnterValueParams.UIItem0TextSendKeys = TestContext.DataRow["ValueOne"].ToString();
    this.UIMap.EnterValueParams.UIItem1TextSendKeys = TestContext.DataRow["ValueTwo"].ToString();
    this.UIMap.EnterValue();

    this.UIMap.CheckResultExpectedValues.UIItem0TextDisplayText = TestContext.DataRow["Result"].ToString();
    this.UIMap.CheckResult();
}

The ...Params and ...ExpectedValues classes allow the test to create values when the test runs. For example, if the EnterValue method also wanted to write tomorrow's date into a field we could add the following line before it is called:


text:
Q: ActiveX not installed after confirm installation prompt I have a cabinet to deploy an activex inside my site.
The installation prompts correctly and when i click "confirm" seem that activex will be installed, but unfortunatly is not...its ask me for installation every time...
How install works?
There is a way to see errors of installation?
My cabinet .inf file is this:
[version]
signature="$CHICAGO$"
AdvancedINF=2.0

[Add.Code]
Setup.msi=Setup.msi

[Deployment]
InstallScope=operator

[Setup.msi]
file-win32-x86=thiscab
clsid={72645213-AEA3-49E1-B65E-268101ADF535}
FileVersion=1,0,0,0

[Setup Hooks]
RunSetup=RunSetup

[RunSetup]
run="""msiexec.exe""" /i """%EXTRACT_DIR%\Setup.msi""" /qn

Thanks

A: To view ActiveX intallation log you can use Code Download Log Viewer. Download from Microsoft
Other than that, maybe try running msi without /qn and check that installation


text:
Q: How to run NRF connect RSSI function in a infinite loop with a wait time for a BLE device? I am trying to run NRF.setRSSIHandler 10 times in a BLE device and print the average value. After that wait for 5 second and rerun the loop again for infinite time. But for JavaScript's callback function issue, it is not giving the expected output. I've tried using several closure solutions but none of them work. Is there any way to get the correct output?
Code:
`
let count = 0;
let average = 0;
//infinite loop
while (count <1){
for (let i = 0; i < 10; i++) {

NRF.setRSSIHandler( function (rssi) {
  let distance = Math.pow(10, ((-56 - (rssi)) / (20))) * 3.28084;
  average = average + distance;
  NRF.setRSSIHandler();
});
}
console.log(average/i);
wait(5000);
}

`


text:
Q: How can I limit an Active Directory user to only use mstsc I would like to create a domain user with the sole permission to run the MSTSC program, or activate RDP from a desktop icon.
I don't want that user to be able to do anything else on the server he will be accessing.
Is this possible ?
Thank you in advance.

A: You can do this with group policy. Create an ou and link a Group policy to it. You can try the link for more info.
http://msdn.microsoft.com/en-us/library/ms811966.aspx


text:
Q: Create a global snackbar using Vue, Vuetify and Vuex I try to create a global snackbar to trigger every times an axios http error occurs, I followed this tutorial :  https://dev.to/stephannv/how-to-create-a-global-snackbar-using-nuxt-vuetify-and-vuex-1bda
But I don't want use Nuxt, only Vue, Vuex and Vuetify, so I tried to created a plugin available everywhere, but I get these errors : [vuex] unknown mutation type: snackbar/showMessage and TypeError: Cannot read property '$snackbar' of undefined.
Here is my code :
src/main.js
import Vue from 'vue'
import router from "@/router";
import "./filters/filters";

import App from './App.vue'

import vuetify from "@/plugins/vuetify";

import VueSignaturePad from 'vue-signature-pad';
import axios from "axios";

import store from "@/store/snackbar";
import snackbarPlugin from "@/plugins/snackbar";

Vue.prototype.$http = axios;

Vue.config.productionTip = false

Vue.use(snackbarPlugin, { store });
Vue.use(VueSignaturePad);

axios.interceptors.response.use(
    function (response) {
        return response;
    },
    function (error) {
        // handle error
        if (error.response) {
            this.$snackbar.showMessage({ content: error.response.data, color: 'error', timeout: 10000 })
        }
    });

new Vue({
    router,
    store,
    vuetify,
    render: h => h(App)
}).$mount('#app')

src/store/snackbar.js
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const store = new Vuex.Store({
    state: {
        content: '',
        color: '',
        timeout: ''
    },
    mutations: {
        showMessage (state, payload) {
            state.content = payload.content
            state.color = payload.color
            state.timeout = payload.timeout
        }
    }
});

export default store;

src/plugins/snackbar.js
const snackbarPlugin = {
    install: (Vue, {store}) => {
        if (!store) {
            throw new Error('Please provide vuex store.');
        }

        Vue.prototype.$snackbar = {
            showMessage: function ({
                                       content = '',
                                       color = '',
                                       timeout = ''
                                   }) {
                store.commit(
                    'snackbar/showMessage',
                    {content, color, timeout},
                    {root: true}
                );
            }
        };
    },
};

export default snackbarPlugin;

src/utils/Snackbar.vue
<template>
    <v-snackbar v-model="show" :color="color" elevation="20">
        {{ message }}
        <v-btn color="accent" @click.native="show = false">
            <v-icon>close</v-icon>
        </v-btn>
    </v-snackbar>
</template>

<script>
export default {
    data() {
        return {
            show: false,
            message: "",
            color: "",
            timeout: 5000
        };
    },
    created () {
        this.$store.subscribe((mutation, state) => {
            if (mutation.type === 'snackbar/showMessage') {
                this.message = state.snackbar.content
                this.color = state.snackbar.color
                this.timeout = state.snackbar.timeout
                this.show = true
            }
        })
    }
};
</script>

src/App.vue
<template>
    <v-app>
        <Snackbar></Snackbar>
        <side-bar/>
        <Header/>
        <Main/>
    </v-app>
</template>

<script>
    import Snackbar from "@/utils/Snackbar";
    import SideBar from "@/components/layouts/SideBar";
    import Header from "@/components/layouts/Header";
    import Main from "@/components/layouts/Main";

    export default {
        name: 'App',
        components: {
            Snackbar,
            SideBar,
            Header,
            Main
        },
        beforeMount() {
            console.log('app')
            this.getRole()
            this.getEtats()
        },
        methods: {
            getRole() {
                this.$http.get('/rol')
                    .then(response => {
                        let agent = {}
                        agent.role = response.data.data.role
                        agent.username = response.data.data.username
                        localStorage.setItem('badge.agent', JSON.stringify(agent))
                    })
                    .catch(function (error) {
                        console.log(error)
                    })
            },
            getEtats() {
                this.$http.get('/nyx/badge/demande/accesnro/etats')
                    .then(response => {
                        localStorage.setItem('badge.etats', JSON.stringify(response.data.data))
                    })
                    .catch(function (error) {
                        console.log(error)
                    })
            }
        }
    }
</script>

I purposely throw a 404 error on the /role route to bring up the snackbar but the errors occurs.
Please do you have any idea what's wrong when i call this.$snackbar.showMessage ({content: error.response.data, color: 'error', timeout: 10000 }) in main.js ?

A: Because you do not use Vuex modules (https://vuex.vuejs.org/guide/modules.html), you should call commit without snackbar prefix:
store.commit('showMessage',{
    content, color, timeout}
);

Check this post (Using vuejs plugin on the main.js file). There is an explanation, how to use plugin in main.js and App at the same time.
main.js
import Vue from "vue";
import router from "@/router";
import "./filters/filters";

import App from "./App.vue";

import vuetify from "@/plugins/vuetify";

import VueSignaturePad from "vue-signature-pad";
import axios from "axios";

import store from "@/store/snackbar";
import snackbarPlugin from "@/plugins/snackbar";

Vue.prototype.$http = axios;

Vue.config.productionTip = false;

Vue.use(snackbarPlugin, { store });
Vue.use(VueSignaturePad);

axios.interceptors.response.use(
  function(response) {
    return response;
  },
  function(error) {
    // handle error
    if (error.response) {
      snackbarPlugin.showMessage({
        content: error.response.data,
        color: "error",
        timeout: 10000
      });
    }
  }
);

new Vue({
  router,
  store,
  vuetify,
  render: h => h(App)
}).$mount("#app");

snackbar.js
import store from "../store/snackbar";

const snackbarPlugin = {
  showMessage: ({ content = "", color = "", timeout = "" }) => {
    store.commit("snackbar/showMessage", { content, color, timeout }, { root: true });
  },
  install: (Vue, { store }) => {
    if (!store) {
      throw new Error("Please provide vuex store.");
    }
    Vue.prototype.$snackbar = snackbarPlugin;
  }
};

export default snackbarPlugin;

main.js


text:
Q: Python If Elseif Else working strange Guys I was trying very basic program in python using id, elif and else statements. I feel something is not right. Check out my code below.
YourChoice = input(str("Do you want to Continue?(Y/N): "))

YourChoiceLower = YourChoice.lower()

if YourChoiceLower == 'y' or 'yes':
    print("Yes Block Statement")
elif YourChoiceLower == 'n' or 'no':
    print("No Block Statement")
else:
    print("Wrong Choice")

Now when I run the above code, it just asks me with the Y/N question. When I  type y or Yes it just return the If block statementBut when I type n or No it just Still execute the If Block instead of Elseif or Else block
check out the below Lines of execution
>>>
Do you want to Continue?(Y/N): Y
Yes Block Statement
>>>
Do you want to Continue?(Y/N): YeS
Yes Block Statement
>>>
Do you want to Continue?(Y/N): N
Yes Block Statement
>>>
Do you want to Continue?(Y/N): nO
Yes Block Statement
>>>
Do you want to Continue?(Y/N): Somethingelse
Yes Block Statement
>>>
Can some one explain me what's going on, I'm confused why its working strange Please guide me friends  Thanks in Advance :-)
Note: I'm using Python 3.4

A: The condition YourChoiceLower == 'y' or 'yes' does not work as you think it does. It checks if YourChoiceLower == 'y', or if 'yes'. The last sub-expression, 'yes', makes no sense.
Instead the condition needs to check YourChoiceLower in both sub-expressions, like
if YourChoiceLower == 'y' or YourChoiceLower == 'yes':
    ...

You could easily have checked this yourself, in an interactive session:
>>> a = 'a'
>>> a == 'a' or 'b'
True

The result is True because a == 'a' is true. But then:
>>> a = 'b'
>>> a == 'a' or 'b'
'b'

Here you no longer get a boolean result, instead we just get back the string 'b'. This is because a == 'a' is false, so the right side of the or is evaluated, giving the result 'b'.


text:
Q: Late initialization error, but non nulling wont solve I am receiving the following error when running a build,
Another exception was thrown: LateInitializationError: Field
'_pageManager@638124189' has not been initialized.
Performing hot reload...
I am following this tutorial, https://suragch.medium.com/steaming-audio-in-flutter-with-just-audio-7435fcf672bf, but I want this logic in a widget that isnt main, which I think is where my confusion is coming from.
Here is a scrollbar widget, nested in a music page widget, nested in a widget initialized in main.
here is the page manager
If i change over
late final PageManager _pageManager;
to
PageManager? _pageManager
As i've seen in some suggestions, I receive lots of errors like this " Error: Property
'buttonNotifier' cannot be accessed on 'PageManager?' because
it is potentially null."  however the post calls for null safety, anyway.


text:
Q: How can I make an annotation like maps app has I have an app with map and a lot of annotations that are made with custom image, and my problem is that when i drag the map or zoom the annotation shows another point (lat , lon).
So I was wondering because I see this bug in other applications too, is there any way to fix it (to be as the maps annotation that always shows the right lat and lon).
This is the code I use for annotation:
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {

    if annotation is MKUserLocation {
        return nil
    }

    var reuseId = ""

    if annotation is FBAnnotationCluster {

        reuseId = "Cluster"
        var clusterView = mapView.dequeueReusableAnnotationView(withIdentifier: reuseId)
        clusterView = FBAnnotationClusterView(annotation: annotation, reuseIdentifier: reuseId, configuration: FBAnnotationClusterViewConfiguration.default())
        return clusterView
    }else{

        reuseId = "pin"
        var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: reuseId)
        if  annotationView == nil {
            annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: "pin")
            annotationView!.image = UIImage(named: "locat.png")

        }
        else {
            annotationView!.annotation = annotation

        }

        let cpa = annotation as! FBAnnotation

        annotationView!.image = nil

        let image = UIImage(named:cpa.nameImage)

        annotationView!.image = image

        return annotationView
    }

}

If you have any question about what I'm asking or anything else please feel free to leave a comment.
Thanks in advance!
EDIT
I upload it an video showing my problem
EDIT2
And here is a video from maps that showing that their annotation is not losing its lat and lon.

A: Your problem is the MKAnnotationView.centerOffset you need to adjust this property in the func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView?
As is defined in MKAnnotationView Documentation

centerOffset  Property The offset (in points) at which to display the
  view.
var centerOffset: CGPoint
Discussion By default, the
  center point of an annotation view is placed at the coordinate point
  of the associated annotation. You can use this property to reposition
  the annotation view as needed. This x and y offset values are measured
  in points. Positive offset values move the annotation view down and to
  the right, while negative values move it up and to the left.

Something like this
var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: reuseId)
        if  annotationView == nil {
            annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: "pin")
            annotationView!.image = UIImage(named: "locat.png")
            //this is an example you must to get in account the form of your current view and what you want, I think your values are CGPoint(x: 0.5, y: 1)
            annotationView?.centerOffset = CGPoint(x: 0, y: -((UIImage(named: "locat.png")?.size.height)!/2))

        }
        else {
            annotationView!.annotation = annotation

        }

Hope this helps you

A: You are not losing the lat long but your lat long are on center of your annotation image you have to change anchorPoint.
annotationView?.layer.anchorPoint = CGPoint(x: 0.5, y: 1.0)

in
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {


text:
Q: HC12 transmission sensing I am new to arduino and I am using an accelerometer to measure acceleration on a moving rocket. I am using the HC12 wireless transmitter to do this.
What I am trying to do is to begin sending data to the computer via the HC12 transmitter only when a certain change in z axis acceleration is sensed.
I am confused unto what to do with the functions that I have made to pass values of x, y, z and data into the function Hc12.
This Hc12 function is only meant to run once every 30 seconds whereas the loop function should run about 3 times per second.
Any help would be greatly appreciated. My code is the following:
#include <SoftwareSerial.h>

SoftwareSerial HC12(7,6);

//initialising variables and functions
const int numReadings = 15;
int readings[numReadings];
int index = 0;
float total = 0;
int inputPin = A1;

float test;

const int numReadings1 = 15;
int readings1[numReadings1];
int index1 = 0;
float total1 = 0;
int inputPin1 = A2;

const int numReadings2 = 15;
int readings2[numReadings2];
int index2 = 0;
float total2 = 0;
int inputPin2 = A3;

float x;
float y;
float z;

void setup(){
 Serial.begin(115200);

 if ((readings2[index2]-readings2[index2-1])>0.5){
  HC12.begin(115200);
 }

 for (int thisReading = 0; thisReading < numReadings; thisReading++)
 readings[thisReading] = 0;

}

float Hc12(float x, float y, float z, float data)
{
  float test;
  readings2[index2] =analogRead(inputPin2);
test =readings2[index2]-readings2[index2-1];

if ((test)>0.1){

      HC12.println(data);
}//send data
return test;
 delay(30000);
}

void loop() {

//x moving avg
  total = total-readings[index];
  readings[index] =analogRead(inputPin);
  total = total +readings[index];
  index = index + 1;

  if (index>=numReadings)
  index = 0;

  x = total/numReadings;

  //y moving avg

  total1 = total1-readings1[index1];
  readings1[index1] =analogRead(inputPin1);
  total1 = total1 +readings1[index1];
  index1 = index1 + 1;

  if (index1>=numReadings1)
  index1 = 0;

  y = total1/numReadings1;

  //z moving avg

  total2 = total2-readings2[index2];
  readings2[index2] =analogRead(inputPin2);
  total2 = total2 +readings2[index2];
  index2 = index2 + 1;

  if (index2>=numReadings2)
  index2 = 0;

  z = total2/numReadings2;

   //z moving avg

  total2 = total2-readings2[index2];
  readings2[index2] =analogRead(inputPin2);
  total2 = total2 +readings2[index2];
  index2 = index2 + 1;

  if (index2>=numReadings2)
  index2 = 0;

  z = total2/numReadings2;

String data = "";
data = data + x + "," + y + "," + z ;

 delay(30);
}

A: You didn't call the function below. or Am I missing some points?
float Hc12(float x, float y, float z, float data)

I didn't check the remaining code whether there is any other mistake or not by the way.


text:
Q: jqGrid advanced search 'beforeSearch' option? I am using the most excellent jqGrid plugin, and have found lots of help on this site by searching, but I have found a problem I cannot solve, or find a solution to. This will be my first post here.
I am using a filterToolbar to do some searching of my grid. Because of the nature of the back end I need to interact with, I am unanble to use the filters that jqGrid provides, and instead need to intercept the search and modify the postdata before submitting. I do this with the filterToolbar option "beforeSearch" like this:
$("#SC_grid").jqGrid('filterToolbar', {stringResult: true, searchOnEnter: true, defaultSearch : "cn", beforeSearch: function() {
            var postData = $("#SC_grid").jqGrid('getGridParam','postData');
            var newPostData = '1=1';
            var searchData = jQuery.parseJSON(postData.filters);
            for (var iRule=0; iRule<searchData.rules.length; iRule++) {
                newPostData = newPostData + " AND " + searchData.rules[iRule].field + " LIKE '%" + searchData.rules[iRule].data + "%' ";
            }
            $("#SC_grid").jqGrid('setGridParam',{postData: { filter: newPostData, filters: ''} } );
            return false;
}});

This works great for me to build a portion of my select before submission.
I would also like to use the advanced search in the same way, but Cannot figure out how to intercept the POST before submission. There does not appear to be a beforeSearch() option abailable, and the afterShowSearch or onClose options dont have the right timings. ANy suggestions on how to proceed?
Mark

A: You are right, the current implementation of advanced searching of the jqGrid don't have any events like beforeSearch. The new version of advanced searching which are full new written will have onSearch method which could you use. The method like beforeSearch will be fired before trigger("reloadGrid",[{page:1}]), but after the postData will be filled.
The beforeSearch of the filterToolbar has one more interesting feature so you can stop the searching by returning the true value from the beforeSearch. So the beforeSearch can play validation role.
In one my old answer I described an universal method which can be used for any kind of validation or postData modification. In the answer I show how one can subclass the reloadGrid event handler of jqGrid and stop reloading of the grid if needed. The demo shows this. In the same way here one could do any other modification of the data. It's pity, but the answer will be very bad indexed and will not be fond on the most searching on the stackoverflow. So one don't know it.
In you case you need only to modify the postdata before submitting and don't need to stop the grid reloading. So you can solve the problem using at least two standard jqGrid events: beforeRequest and serializeGridData. In both you can access the search (as this.p.search) and postData (as this.p.postData) parameters. The value of search parameter will be send to the server as _search and will be set to true if any of searching/filtering method are used. So inside of one from the event handler you can modify this.p.postData.
Inside of serializeGridData you have even a way to define which data exactly will be send to the server without require to modify the data. The advantage is that if you open the advance searching dialog next time you will see (and can modify if needed) the last searching request.
If you need to have the same implementation of beforeRequest or serializeGridData on many grids of your web site you can set your default implementation of the function with respect of $.jgrid.defaults:
$.extend($.jgrid.defaults, {
         datatype: 'json', // overwrite default value of any jqGrid parameter
         serializeGridData: function(postData) {
             // your implementation
         }
});


text:
Q: Docker for windows Vs Docker inside Windows Ubuntu App? I am trying to know the best way to run Docker in Win 10 machines that dosn't have too many resources.
I am runing Docker using the docker for windows and things run quite good but I wonder if it will be better specialy about symlinks issues and resources hunger if i run Docker inside the new Ubuntu on Windows. https://www.microsoft.com/es-es/p/ubuntu/9nblggh4msv6?activetab=pivot:overviewtab
When you try to install Docker in Ubuntu for Win a message shows advising to use Docker for Windows instead.
Any thoughts out there ?


text:
Q: Changes Text Colors Via Jquery To Asp .Net Web Application I want to make changes in text colors which is in  tag  as below.
Note:- The below example is of content page hence jquery  is link to master page.
<script type="text/jscript">
window.setInterval(function(){
if($("#sw").css("color","Red")){<!—text color in Span Tag-->
$("#sw").css("color","Blue");
 }
else if($("#sw").css("color","Blue")){
$("#sw").css("color","Red");
 }
},1000);

</script>

The above example changes my text colors from Red To Blue but it's not changes from blue to red as per second condition in jquery.
What's The Problem?.

A: Try this:
<script type="text/jscript">
    window.setInterval(function(){
        if ($("#sw").css("color") == "Red") {
            $("#sw").css("color","Blue");
        } else if($("#sw").css("color") == "Blue") {
            $("#sw").css("color","Red");
        }
    }, 1000);
</script>

Basically you are trying to set the color in the if statement. You should instead check, not set.

A: You are trying to set the color now check this fiddle http://jsfiddle.net/tRzAb/
setInterval(function(){
if($("#sw").css("color") == "rgb(0, 0, 255)"){
$("#sw").css("color","Red");
 }
else{
$("#sw").css("color","Blue");
 }
},1000);

A: <script type="text/jscript">
            window.setInterval(
        function () {
            $("#sw").css("color",
                ($("#sw").css("color").trim() == "rgb(0, 0, 255)") ? "rgb(0, 255, 0)" : "rgb(0, 0, 255)"
                );
        }, 500);
        </script>


text:
Q: Export csv to dynamodb using boto3 My requirement is i have 10 million csv records and i want to export the csv to DynamoDB?  Any one could you please help on this.
And also is this possible to export tab separated values as well ?
Thanks,
in advance.

A: Convert your csv to json format and use AWS BatchWriteItem DynamoDB API
Make sure to add your primary key data in the json
import csv
import boto3

def convert_csv_to_json_list(file):
   items = []
   with open(file) as csvfile:
      reader = csv.DictReader(csvfile)
      for row in reader:
          data = {}
          data['temp'] = row['temp']
          #populate remaining fields here
          #................
          items.append(data)
   return items

def batch_write(items):
   dynamodb = boto3.resource('dynamodb')
   db = dynamodb.Table('table-name')

   with db.batch_writer() as batch:
      for item in items:
         batch.put_item(Item=item)

if __name__ == '__main__':
   json_data = convert_csv_to_json_list('file')
   batch_write(json_data)

A: Use AWS BatchWriteItem DynamoDB API to perform batch inserts.
Iterate the file contents and insert them in batches.
import boto3

dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('sample_table')

with table.batch_writer() as batch:
    for i in range(50):
        batch.put_item(
            Item={
                'ORDERNO': 'dummy',
                'DIRECTION': 'dummy',
                'LATITUDE': 'dummy',
                'LONGITUDE': 'dummy'
            }
        )

Not so good approach but without any coding
AWS Datapipeline has templates for doing data migration across different AWS services but for dynamodb, it can only load dynamodb backup data and not using csv.
Not straight forward approach, but you can do.

*

*Upload the csv file to S3

*Create a pipeline to copy data from S3 to an RDS instance(create one RDS mysql).

*Use Database migration service to copy data from RDS to dynamodb.


text:
Q: Form is still "TopMost" although it is set to false I don't know how to solve this. I have a Form2 which is opened via a Form1. Although the option "TopMost" is set to "false" the Form2 is still in the foreground. Clicking on the Form1 somewhere does nothing. Is there a way to solve this and let the Form2 pop up again into the Foreground when the button is clicked which opens it?
private void button_Click(object sender, EventArgs e)
{
    if (form2.Visible == false)
    {
        form2 = new Form2(this);
        form2.Show(this);
    }
}


text:
Q: Need to instantiate class from dll to use in other project I've created a dll, lets call it ExampleHelper.dll.
The structure of the Visual Studio Class Library which I've compiled to dll is the following:
namespace ExampleHelper
{
    public class Example
    {
        public string GetExamples(string input)
        {
            // stuff
        }
    }
}

So, I reference it in my other project in which I want to use these ExampleHelper classes, by adding a using line at the top of the file in question:
using ExampleHelper;
Now, I can see that I can access the class from ExampleHelper, which is called  Example. But, I can't access the methods in that class, which means I can't write Example.GetExamples("hello"), as it says GetExamples doesn't exist.
I noticed that I can do this:
Example e = new Example();
e.GetExamples("hello");

which I of course can use, but it doesn't feel quite right to instantiate a new object each time I want to use a helper method.
Have I done something completely wrong? My guess is yes, but I can't find where I'm going wrong. Any help appreciated!

A: You need to have an instance of Example object to call this method.
To call a method without an instace of a object, method must be static.
public static string GetExamples(string input)

should be the method's declaration.

A: Make GetExamples(string input) a static method
public static string GetExamples(string input)

Static methods do not require an instance of the class.

A: Please put your class and methods as STATIC, you'll be able to use it everywhere.
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/static


text:
Q: Determine the full oslevel (incl build date) of a local AIX repository without patching / installing In our environment, only one of our AIX servers is permitted to access the internet through the firewall. On this one server, I use suma to download all fixes for all base levels, technology levels and service packs that we have in our environment; this is done daily.
Once a month, I copy all fixes together in one folder per base level and I use inutoc to create a couple repositories that are frozen and that can be used to patch all of our AIX servers. This way we can ensure all servers are on the same oslevel. We call this a "monthly patchset".
We have a CSV file that lists all kernel versions for each "monthly patchset" for all of our UNIX/Linux OS flavors. That CSV file is used by our patching / validation scripts. For Linux / Solaris I've found "tricks" to determine the kernel version from the repository files themselves, but on AIX I'm failing to figure out the oslevel without actually patching a server with it. After patching, I can run 'oslevel -s' to figure the oslevel, but that is too late, as our patching scripts use / require the oslevel before starting the actual patching.
Does anyone know a trick to accomplish this? I've tried the following so far:

*

*Our repository folder contains many *.bff files, which are binary files, so inside those files I can't find the oslevel

*The *.bff file names are mostly 'U' followed by some numbers and '.bff' (so not usable for determining the oslevel). But some filenames actually do contain (parts of) the oslevel in the filename. For example: 7200-01-06.bff 7200-02-01-1732.bff 7200-02-06.bff 7200-03-06.bff 7200-03.bff 7200-04-01.bff 7200-04-02.bff 7200-04-03.bff 7200-04.bff 7200-05-01.bff 7200-05-02.bff 7200-05.bff. However, as you can see, from the latest oslevels, the 'build date' part is missing in the filename.

*We patch using the install_all_updates -Y -d <path_to_repo> command. I've tried using install_all_updates -p -d <path_to_repo>, hoping that it would be visible somewhere in the output, but it isn't.

*I've also tried installp -[lL] -d <path_to_repo>, but also there the oslevel isn't visible.

I hope someone can assist me with this.
Edit below (as a response to @Jeff Schaller his answer)
Thanks a lot for your assistance!
It's very close to matching, but not exactly I'm afraid...
--> installp -L -d /nim/export/repos/AIX/AIX7200_OS-Vendor_Repo_20200511 | grep :bos\.rte\.install: | sort -t: -k17n | tail -1 | awk -F: '{print $3, $17}'
7.2.4.2 1937
root@servername /nim/export
--> oslevel -s
7200-04-01-1939
root@servername /nim/export

Not sure why though... Any idea?
More detail:
--> installp -L -d /nim/export/repos/AIX/AIX7200_OS-Vendor_Repo_20200511 | grep 1937 | wc -l
     613
root@servername /nim/export
--> installp -L -d /nim/export/repos/AIX/AIX7200_OS-Vendor_Repo_20200511 | grep 1939 | wc -l
       0
root@servername /nim/export
-->

So I thought that there must be some package installed with a builddate of 1939 that is causing 'oslevel-s' to display that builddate. So I ran following commands to find this package:
--> lslpp -Lc all | awk -F':' '{print $2" "$3" "$18}' | grep 1937 | wc -l
     288
root@servername /nim/export/repos/AIX/AIX7200_OS-Vendor_Repo_20200511
--> lslpp -Lc all | awk -F':' '{print $2" "$3" "$18}' | grep 1939 | wc -l
       0
root@servername /nim/export/repos/AIX/AIX7200_OS-Vendor_Repo_20200511
--> oslevel -s
7200-04-01-1939
root@servername /nim/export/repos/AIX/AIX7200_OS-Vendor_Repo_20200511
-->

As you can see, I wasn't able to find this package... :(
Edit #2 below (as a response to @Jeff Schaller his comment)
root@servername /
--> instfix -ic | grep 7200-04 | grep :-:
root@servername /

That didn't come back with anything I'm afraid.
Also I'm not sure what you mean exactly with "... server is back-leveled from the expected oslevel...". Isn't it the opposite? 'oslevel -s' gives back 1939 as build date, while all packages indicate that the build date should be 1937. Isn't that "front-leveled" then?

A: One possibly helpful step along the way could be to use the bffcreate command to convert those bff filenames into package-based filenames. Something along the lines of bffcreate -c -d /path/to/repo.
To answer the question, though, once you've run inutoc to create the .toc file, you can ask installp to list the contents of that repo's TOC file in colon-separated output, which includes the build date in field 17. The bos.rte.install package will be among those that have the most recent build date, so you could search for that and extract its VRMF (Version, Release, Modification, Fix) and build date:
sudo installp -L -d /path/to/repo | grep :bos\.rte\.install: | sort -t: -k17n | tail -1 | awk -F: '{print $3, $17}'

That will output the VRMF and build date of the most recent build of the bos.rte.install package in that repo. Adjust the awk printing statement if you're only interested in one field or the other. The build number is in YYww format (2-digit year, 2-digit week of that year). The VRMF of bos.rte.install will loosely correspond with the output from oslevel; you could perhaps rely on the first three fields to match up with oslevel -r output; for example, a VRMF of 7.2.4.6 correlates to an oslevel of 7200-04, as would a VRMF of 7.2.4.2 -- the initial 7.2 gives the "7200" portion and the 4 gives the "-04" portion.

A: In the end, this is the solution that I've implemented (and which does provide me with the correct full oslevel):
Creating the repo

*

*Copy all packages as *.bff into ${REPO_SNAPSHOT_PATH}

*Recreate the .toc file: rm -f "${REPO_SNAPSHOT_PATH}.toc" 2>&1 ; cd "${REPO_SNAPSHOT_PATH}" ; inutoc .

*Cleanup the repo: /usr/lib/instl/lppmgr -rubxVd "${REPO_SNAPSHOT_PATH}"

*Rename the bff files to understandable package names: bffcreate -c -d "${REPO_SNAPSHOT_PATH}"

*Recreate the .toc file once more: rm -f "${REPO_SNAPSHOT_PATH}.toc" 2>&1 ; cd "${REPO_SNAPSHOT_PATH}" ; inutoc .
Figure out the full oslevel

*

*Create an LPP Source from the repo: nim -o define -t lpp_source -a server=master -a location="${REPO_SNAPSHOT_PATH}" "${LPP_SOURCE_NAME}"

*Create Spot from this LPP Source: nim -o define -t spot -a source="${LPP_SOURCE_NAME}" -a server=master -a location="${SPOT_PATH}" "${SPOT_NAME}"

*Get the full oslevel from this Spot: FULL_OSLEVEL="$(lsnim -l ${SPOT_NAME} 2>/dev/null | awk '$1=="oslevel_s" {print $3}')"


text:
Q: Normalizer not removing accents I'm using Normalizer followed by a regex to remove accents, but I'm getting back the same string with the accents still there.
import java.text.*

const val INPUT = "áéíóůø"
fun main() {
    println(Normalizer.normalize(INPUT, Normalizer.Form.NFC).replace("[\\p{InCombiningDiacriticalMarks}]+", ""))
    println(Normalizer.normalize(INPUT, Normalizer.Form.NFD).replace("[\\p{InCombiningDiacriticalMarks}]+", ""))
    println(Normalizer.normalize(INPUT, Normalizer.Form.NFKC).replace("[\\p{InCombiningDiacriticalMarks}]+", ""))
    println(Normalizer.normalize(INPUT, Normalizer.Form.NFKD).replace("[\\p{InCombiningDiacriticalMarks}]+", ""))
}

Output:

áéíóůø
áéíóůø
áéíóůø
áéíóůø

Kotlin playground: https://pl.kotl.in/62l6rUEUm
I've read a dozen questions here that say the way to strip accent marks in Java/Kotlin is to use java.text.Normalizer plus some minor variation of the above regular expression (sometimes without square brackets, sometimes without the plus). Even Apache Common's stripAccent function uses Normalizer for its implementation (but apparently handles to special characters too).
What am I doing wrong?

A: You did not make "[\\p{InCombiningDiacriticalMarks}]+" a Regex.
println(
    Normalizer.normalize(INPUT, Normalizer.Form.NFD)
        .replace("[\\p{InCombiningDiacriticalMarks}]+".toRegex(), "")
)

This produces:
aeiouø

Notice that the stroke in ø is not a diacritic mark. It can be decomposed to neither

*

*"o" and U+0338 COMBINING LONG SOLIDUS OVERLAY, or;

*"o" and U+0337 COMBINING SHORT SOLIDUS OVERLAY

You can see that these three all look a bit different: o̸øo̷
Also notice that there are two more blocks in Unicode that contains combining diacritics, called "Combining Diacritical Marks Extended" and "Combining Diacritical Marks Supplement". Consider including those in your regex too.


text:
Q: 04098. "trigger '%s.%s' is invalid and failed re-validation" I would like to write a trigger which blocks deleting records from table and blocks decreasing salary on update. It works well as two seperate triggers, but I would like to merge it into one.
Here is my trigger after merging:
  CREATE OR REPLACE TRIGGER test
    BEFORE DELETE OR UPDATE
    ON emp
    FOR EACH ROW
    BEGIN
      IF UPDATING THEN
        IF :NEW.sal < :OLD.sal THEN
          raise_application_error(-20500, 'You cannot decrease emp salary');
        END IF;
      ELSE DELETING THEN
        raise_application_error(-20500, 'You cannot delete records from emp');
      END IF;
    END;

The problem is when I try to update or delete record I get an error:
04098. 00000 -  "trigger '%s.%s' is invalid and failed re-validation"
*Cause:    A trigger was attempted to be retrieved for execution and was
           found to be invalid.  This also means that compilation/authorization
           failed for the trigger

I think that there is a problem around this line - BEFORE DELETE OR UPDATE because as I know if I FOR EACH ROW statment I should write is as BEFORE UPDATE on sal, but then I don't know how to join BEFORE DELETE statment into this.
EDIT:
Problem was around ELSE statment. It should be changed to ELSIF

A: Your IF statement syntax is incorrect. It should be:
CREATE OR REPLACE TRIGGER test
  BEFORE DELETE OR UPDATE
  ON emp
  FOR EACH ROW
BEGIN
  IF UPDATING AND :NEW.sal < :OLD.sal THEN
    raise_application_error(-20500, 'You cannot decrease emp salary');
  ELSIF DELETING THEN
    raise_application_error(-20500, 'You cannot delete records from emp');
  END IF;
END test;

I also combined the two IF statements used in the UPDATING case into one to keep it simpler.
EDIT
In the case where you don't want to allow salaries to be decreased another possible solution is to quietly change the salary back to its original value, as in:
CREATE OR REPLACE TRIGGER test
  BEFORE DELETE OR UPDATE
  ON emp
  FOR EACH ROW
BEGIN
  IF UPDATING AND :NEW.sal < :OLD.sal THEN
    :NEW.sal := :OLD.sal;  -- restore original salary
  ELSIF DELETING THEN
    raise_application_error(-20500, 'You cannot delete records from emp');
  END IF;
END test;


text:
Q: How to validate dita document I would like to validate different DITA documents (topics, maps, etc.) against DITA but i am a bit confused about the DITA xsd files. The xsd package contains a lot of xsd files in different directories. A lot of the files define the same elements, groups (without redefine, for example attribute group domains-att).
So i guess there is a "main" xsd file (sub set of all the xsd files) for every type of DITA document. Is that true and if yes, what are the main files? If it is not true, could you please tell me how validation of a DITA document works if there are multiple definitions of the same types.

A: You may find my DITA specialization tutorials useful as an introduction to DITA grammar design:
http://dita4practitioners.github.io/dita-specialization-tutorials/
The tutorials focus on DTD syntax because that's what most DITA users use, but there is an XSD document type shell tutorial, which is directly relevant to your question here:
http://dita4practitioners.github.io/dita-specialization-tutorials/body/part-config-and-extend/tutorials/document-type-shells/creating-an-xsd-shell.html
Eliot

A: The main XSD files are named <topic type name>.xsd for each topic type, for example topic.xsd, concept.xsd, or map.xsd.

A: Proper validation of CALS tables within DITA poses additional problems due to co-constraints that XSD (at least in 1.0 form) can't express.
If you're Ok with using Schematron, there's a cals-table-schematron defintion that handles this.


text:
Q: ¿Nodemailer no funciona en heroku? Cuando pruebo mi backend en el localhost, funciona correctamente, pero cuando lo despliego en heroku me manda el siguien error:

Access to XMLHttpRequest at
'https://chango-tareas-backend.herokuapp.com/api/send-email' from
origin 'https://localhost:4200' has been blocked by CORS policy: No
'Access-Control-Allow-Origin' header is present on the requested
resource.

Esta es la linea de codigo encargarda de enviar correos a traves de nodemailer
//ruta para enviar el correo con nodemailer
router.post('/send-email', cors(), async (req, res) => {

    const { nombre, email, mensaje, url, destino } = req.body;

    contentHtml = `

CV solicitante ${nombre}

Contactar a: ${email}

${mensaje}

        Click para ver
    `;

    const transporter = nodemailer.createTransport({
        host: 'host_outlock',
        port: port,
        secure: false,
        auth: {
            user: 'micorreo@hotmail.com',
            pass: 'mipassword'
        }
    });

    try{
        const info = await transporter.sendMail({
            from: "'ChangoTareas' <abisur_yue@hotmail.com>",
            to: `${destino}`,
            subject: `Solicitud de registro ${nombre}`,
            text: 'Hola guapo :v',
            html: contentHtml
        });
    }catch(err){
        next(err);
    }

    console.log('Message sent', info.messageId);

    res.status(200).send({ data: 'Success' });
});

En el console log de heroku me arroja las siguientes excepciones

2021-01-19T04:35:32.154277+00:00 app[web.1]: (node:36)
UnhandledPromiseRejectionWarning: ReferenceError: next is not defined
2021-01-19T04:35:32.154291+00:00 app[web.1]:     at
/app/src/routes/index.js:128:9 2021-01-19T04:35:32.154292+00:00
app[web.1]:     at processTicksAndRejections
(internal/process/task_queues.js:97:5)
2021-01-19T04:35:32.154416+00:00 app[web.1]: (node:36)
UnhandledPromiseRejectionWarning: Unhandled promise rejection. This
error originated either by throwing inside of an async function
without a catch block, or by rejecting a promise which was not handled
with .catch(). To terminate the node process on unhandled promise
rejection, use the CLI flag --unhandled-rejections=strict (see
https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode).
(rejection id: 1) 2021-01-19T04:35:32.154521+00:00 app[web.1]:
(node:36) [DEP0018] DeprecationWarning: Unhandled promise rejections
are deprecated. In the future, promise rejections that are not handled
will terminate the Node.js process with a non-zero exit code.
2021-01-19T04:35:54.733967+00:00 heroku[router]: at=error code=H12
desc="Request timeout" method=POST path="/api/send-email"
host=chango-tareas-backend.herokuapp.com
request_id=ba1f5e44-615f-4545-ab66-254db83c67a1 fwd="187.227.25.218"
dyno=web.1 connect=1ms service=30000ms status=503 bytes=0
protocol=https

A: Los logs de heroku señalan que te falta un parametro en el callback de tu ruta. Agrega el tercer parametro next.
router.post('/send-email', cors(), async (req, res, next) => {...

Esto es necesario por que el código que presentas, en el bloque catch, brinca a otro controlador (en este caso un global de errores) con next(error). Esto debería solucionar el problema de cors también, ya que heroku manda una petición extraña a la original lo que activa la protección por cors en el navegador.


text:
Q: Que permissões necessitam ser pedidas em tempo de execução? <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.READ_CALENDAR" />
<uses-permission android:name="android.permission.WRITE_CALENDAR" />

Essas são as minhas permissões, eu estou com duvida se eu preciso notificar o usuário para permitir ou não, eu estava vendo que a partir da API 23 é preciso fazer isso
Se eu precisar, como eu faço isso?

A: Segue o código para pedir as permissões a partir da versão 23:
String [] permissions = {"android.permission.WRITE_EXTERNAL_STORAGE", "android.permission.ACCESS_FINE_LOCATION","android.permission.WRITE_EXTERNAL_STORAGE", "android.permission.READ_PHONE_STATE", "android.permission.SYSTEM_ALERT_WINDOW","android.permission.CAMERA"};
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
    int requestCode = 200;
    requestPermissions(permissions, requestCode);
}

Na variavel permissions eu coloquei algumas permissões aleatorias, altere e coloque as que vc precisar

A: As permissões que necessitam de ser pedidas em tempo de execução são aquelas consideradas como "perigosas"(Dangerous permissions).
Dentro da lista que apresentou, READ_CALENDAR e WRITE_CALENDAR estão no grupo das "perigosas".
Veja esta resposta para saber como lidar com elas.


text:
Q: Error when I run rake test in Ruby on Rails I am getting an error when I try to run a test on my very simple app in ROR. I am taking a course online and I have this very simple database that has two tables: posts (with title and body) and comments (with ForeignKey: post_id and body. When I run rake test I get the following error:
Error: PostsControllerTest#test_should_destroy_post:
ActiveRecord::InvalidForeignKey: SQLite3::ConstraintException: FOREIGN
 KEY constraint failed: DELETE FROM "posts" WHERE "posts"."id" = ?
     app/controllers/posts_controller.rb:57:in `destroy'
     test/controllers/posts_controller_test.rb:43:in `block (2 levels) in <class:PostsControllerTest>'
     test/controllers/posts_controller_test.rb:42:in `block in <class:PostsControllerTest>'

bin/rails test test/controllers/posts_controller_test.rb:41

....

Finished in 12.539965s, 1.1164 runs/s, 1.2759 assertions/s. 14 runs,
16 assertions, 0 failures, 1 errors, 0 skips`

Any help would be appreciated. Thanks.

A: This error occurs when you delete a row in a table whose primary key is referenced in another table.  You can include ON DELETE CASCADE in your foreign key definition (where you define where the primary key is referenced by another table), or add another delete statement to delete the row referencing the primary key, before doing the delete statement you are currently doing.

A: Add this to your Post model:
has_many :comments, dependent: :destroy

This will destroy associated comments when you will destroy your Post model. So you will not get ConstraintException.
You can find more info about Rails associations here.


text:
Q: Как ускорить записать данных из списка в строку? Kotlin выполняя работу столкнулся с проблемой. Мне необходимо решить систему оду методом рунге-кутта 4 порядка. Необходимо использовать большое количество узлов, но уже на 100 000 сталкиваюсь с проблемой.
Суть проблемы в том, что решение строится быстро, примерно 3 сек, но потом данное решение мне необходимо записать в файл. Для этого я занашу данные в строку и потом просто создаю файл с этой строкой внутри. Но если решение ищется за 3 секунды, то записаь данных в строки происходит примерно 30 мин.
for (i in 0..valu.lastIndex) {
    textEx4123 += "${valu[i][0]} ${valu[i][1]} ${valu[i][2]}  \n"
    textEx4234 += "${valu[i][1]} ${valu[i][2]} ${valu[i][3]}  \n"
    textEx4341 += "${valu[i][2]} ${valu[i][3]} ${valu[i][0]}  \n"
    textEx4412 += "${valu[i][3]} ${valu[i][0]} ${valu[i][1]}  \n"
    textEx412 += "${valu[i][0]} ${valu[i][1]}  \n"
    textEx413 += "${valu[i][0]} ${valu[i][2]}  \n"
    textEx414 += "${valu[i][0]} ${valu[i][3]}  \n"
    textEx423 += "${valu[i][1]} ${valu[i][2]}  \n"
    textEx424 += "${valu[i][1]} ${valu[i][3]}  \n"
    textEx434 += "${valu[i][2]} ${valu[i][3]}  \n"
    textEx4t1 += "${x[i]} ${valu[i][0]}  \n"
    textEx4t2 += "${x[i]} ${valu[i][1]}  \n"
    textEx4t3 += "${x[i]} ${valu[i][2]}  \n"
    textEx4t4 += "${x[i]} ${valu[i][3]}  \n"
    println(i)
}

Вот код цикла, в котором я заношу данные. valu это список решений. Он является списком списков так как я решаю систему, но не в этом суть.
Как я могу ускорить процесс записи данных в строки чтобы потом записать их в файл? или есть другой подход?
P.S. Просто запись списка в файл мне не подходит, так как мне нужны данные именно в таком формате, чтобы потом рисовать 2D или 3D графики.

A: Я конечно быстро нашел ответ, после того как задал вопрос, но искал я ответ до вопроса достаточно долго.


text:
Q: Output of caesar shift reversed I'm trying to implement a simple caesar shift using java:
import java.util.Scanner;

public class Caesar_shift {
public static String message;
public static String Shift_msg;

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    System.out.print("Please type message: ");
    message = scanner.next();
    setShift_msg(message);
    System.out.println(Shift_msg);
}

public static String setShift_msg(String msg) {
    String valueOf;
    for (int i = 0, n = msg.length(); i < n; i++) {
        char c = msg.charAt(i);
        c = (char) (c + 1);
        valueOf = String.valueOf(c);
        Shift_msg = valueOf += Shift_msg;
    }
    return Shift_msg;
}

}
When I run my program,
String message = "abc"
I should get the output bcd. However, it returns "dcbnull".
How could I fix it, and also why does this happen?

A: Change the line Shift_msg = valueOf += Shift_msg; to Shift_msg += valueOf;
That explains why it was reversed. And to get rid of the null at the end, set Shift_msg = ""; either at the beginning of the method or when at the string declaration.

A: Here is your code corrected
You made a mistake with the misorder of concatenation.
It should have been Shift_msg += valueOf since you're going from beginning to end also with the original message.
The reason you have gotten null is because Shift_msg had no value to begin with, hence it should be an empty String.
public static String message;
public static String Shift_msg = "";

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    System.out.print("Please type message: ");
    message = scanner.next();
    setShift_msg(message);
    System.out.println(Shift_msg);
}

public static String setShift_msg(String msg) {
    String valueOf;
    for (int i = 0, n = msg.length(); i < n; i++) {
        char c = msg.charAt(i);
        c = (char) (c + 1);
        valueOf = String.valueOf(c);
        Shift_msg += valueOf;
    }
    return Shift_msg;
}


text:
Q: Full Calendar revert an external drop event I'm a complete beginner regarding the Full Calendar, so apologies for a possible simple question.
I am trying to revert a drop from an External Event. If I use the revertFunc(), the event snaps back to it's original position in the list but the event is still on the calendar until it is refreshed. Ideally I would like it to disappear as soon as the dialog box is closed. This is the code
drop: function(date, jsEvent, ui, resourceId)
{
  var tag = $(this).data('event').tag;
  var eventDate = $(this).data('event').projectDate;
  var calDate =  date.format();

  if (tag == PSTag)
  {
    if(eventDate != calDate)
    {
      alert('You must drop the event on the correct date');
      revertFunc();
      return;
    }
    var eventObjectId = $(this).data('event').schWork;
  }

  if (tag == WOTag)
  {
    var eventObjectId = $(this).data('event').workorder;
  }

  var title = $(this).data('event').title;
  alert(tag);
  updateCalendarEvent(eventObjectId, date.format(), resourceId, tag, title);

  if (tag != PHTag)
  {
    $(this).remove();
  }
  setupDraggableEvents();
}

Many thanks for any assistance