text:
Q: How do I host my script in a Google Cloud server? So I have created something small which is a image-rehost where I wish to use Python script where I have a URL such as https://i.imgur.com/VBPNX9p.jpg but with my rehost it would be
https://ip:port/abc123def456
so whenever I access that page it would give me the url that I posted here.
However the issue I am having is that I have no clue how to actually host the server that I made by node-js. Right now I just used the external IP with port of 5000. When I tried to send the image through my home ip by using the
https://external_ip:5000/abc123

the server doesn't recognize anything and nothing is being sent to the server which I in that case think I have setup something wrong.
I am using Google cloud server and I would wish to know how I can host my own server in the google cloud?

A: As you are having trouble adding a firewall rule, I'm going to suggest make sure port 5000 is open and not 8888.
To open the firewall rule for port 5000 in Google Cloud Platform follow these steps.
1) Navigate to VPC Network > Firewall rules > Create firewall rule.
2) In the 'Create a firewall rule' page, select these settings:
Name - choose a name for this firewall rule
Network - select the name of the network your instance belongs to, most probably
'default' unless you've configured a custom network.
Direction of traffic - 'Ingress'.
Action on match - 'Allow'.
Targets - 'All instances in the network'.
Source filter - 'IP ranges'.
Source IP ranges - '0.0.0.0/0'.
Second source filter - 'None'.
Specified protocols and ports - 'tcp:5000' or 'udp:5000' depending on whether the protocol you are using uses tcp or udp.
3) Hit 'Create'.
This will create a rule allowing traffic on port 5000 to all instances in your network from all IP address sources.
My advice would be to see if these settings work, and then once confirming this, lock down the settings by specifying a specific IP address or range of IP addresses in the 'Source IP ranges' text box, and adding a target tag to you instance and specifying 'Specified target tags' so the port is only open to the instance.
If this doesn't work, you may have a firewall rule turned on within the instance, which you would need to configure (or turn it off).
For more detailed information about setting firewall rules please see here.
For running Node.sj on GCE VM I will suggest you use the Bitnami Node.js package on GCP Marketplace which includes the latest version of Node.js, Apache, Python, and Redis. Using a pre-configured Node.js environment gets you up and running quickly because everything works out of the box. Manually configuring an environment can be a difficult and time-consuming hurdle to developing an application.
Also if you wish to do URL redirection you can use URL map feature provided with Google Cloud HTTP load balancer. This feature allows you to direct traffic to different instances based on the incoming URL. For example, you can send requests for http://www.example.com/audio to one backend service, which contains instances configured to deliver audio files, and requests for http://www.example.com/video to another backend service, which contains instances configured to deliver video files. You find steps to configure and more information here.


text: Q: Modifying Option Bytes at compile time I need to modify the option bytes at compile time for STM32L0xx controller and generate the binaries i.e. .hex, .bin. could you please suggest a solution for the same. I amusing STM32Cube IDE for development in C

redpajama_set_name: RedPajamaStackExchange


text:
Q: Does any built in function in VC++ to sort number? I have two columns of data. For example,
[78, c]
[28, a]
[34, g]
I want to see whether any built-in function to sort the number and tell me the order information. For example, (from small to large) the function will return [2, 3, 1] because the 2nd row has the smallest 1st column element.

A: What is your data structure?
If you're in C++/CLI, then you've got the entire .NET framework available to you.
That said, I don't believe that there's anything built-in that will tell you the order. I believe everything will actually do the sort.
If you really need the order, not a sorted list, I believe this will do it. This creates new objects that remember their original list position, sorts them, and then reads back what the original indexes were.
// I'm assuming you have a class similar to this already.
ref class MyData
{
public:
    int number;
    String^ letter;
};

ref class SortHelper : IComparable<SortHelper^>
{
public:
    MyData^ data;
    int originalIndex;

    SortHelper(MyData^ data, int index)
    {
        this->data = data;
        this->originalIndex = index;
    }

    virtual CompareTo(SortHelper^ other)
    {
        return this->data->number.CompareTo(other->data->number);
    }
};

void List<int> GetSortedIndexes(List<MyData>^ input)
{
    List<SortHelper>^ working = gcnew List<SortHelper>();
    for(int i = 0; i < input->Count; i++)
    {
        working->Add(gcnew SortHelper(input[i], i));
    }

    working->Sort();

    List<int>^ result = gcnew List<int>();
    for each(SortHelper^ helper in working)
    {
        result->Add(helper->originalIndex);
    }

    return result;
}


text:
Q: How to resolve GETJson duplicity exception? I am developing a rest server in java, netbeans.
I made my first get method and my class looks like this:
@Stateless
@Path("v1/cardapio")
public class CardapioResource {

    private Gson gson = new Gson();

    @EJB
    private CardapioRemote ejb;

    public CardapioResource() {}

    @GET
    @Produces("application/json")
    @Path("/")
    public String getCardapios(@QueryParam("key") String key) {
        Conta c = ContaDAO.busca(key);

        JsonObject obj = new JsonObject();
        if(c != null){
            JsonArray array = (JsonArray) gson.toJsonTree(ejb.findAll());
            obj.add("dados", array);
        } else{
            JsonObject status = new JsonObject();
            status.addProperty("codigo", 401);
            status.addProperty("mensagem", "Não há nenhum ID correspondente a este KEY");
            obj.add("status", status);
        }
        return obj.toString();
    }

    @GET
    @Produces("application/json")
    @Path("/")
    public String getCardapios(@QueryParam("key") String key, @QueryParam("id") String id) {
        // second method
    }
}

The above method is responsible for validating a fkey in the database and if it is valid returns a list of menus.
So I tried to do the second method, get an id ... and after validated it would return only the menu of the given id. My class looks like this:
@Stateless
@Path("v1/cardapio")
public class CardapioResource {

    private Gson gson = new Gson();

    @EJB
    private CardapioRemote ejb;

    public CardapioResource() {}

    @GET
    @Produces("application/json")
    @Path("/")
    public String getCardapios(@QueryParam("key") String key) {
      // first method
    }

    @GET
    @Produces("application/json")
    @Path("/")
    public String getCardapios(@QueryParam("key") String key,
                               @QueryParam("id") String id   ) {
        Conta c = ContaDAO.busca(key);

        JsonObject obj = new JsonObject();
        if(c != null){
            JsonArray array = (JsonArray) gson.toJsonTree(ejb.findById(Integer.parseInt(id)));
            obj.add("dados", array);
        } else{
            JsonObject status = new JsonObject();
            status.addProperty("codigo", 401);
            status.addProperty("mensagem", "Não há nenhum ID correspondente a este KEY");
            obj.add("status", status);
        }
        return obj.toString();
    }
}

After the inclusion of this second method an exception is occurring :

WebModule[/webPlataformaCardapio]StandardWrapper.Throwable [FATAL] A
  resource model has ambiguous (sub-)resource method for HTTP
  method GET and input mime-types as defined by @Consumes and @Produces
  annotations at Java methods public java.lang.String
  ws.CardapioResource.getCardapios(java.lang.String) and public
  java.lang.String
  ws.CardapioResource.getCardapios(java.lang.String,java.lang.String) at
  matching regular expression /. These two methods produces and consumes
  exactly the same mime-types and therefore their invocation as a
  resource methods will always fail.;
  source='org.glassfish.jersey.server.model.RuntimeResource@4fef476']

Imagine I have a server url servidor:porta/api/produtos?key=1 that validates the key and returns all products ... and I can have the servidor:porta/api/produtos?key=1&id=5 that validates the key and returns only product 5. Both have the same path, with no divisions of "/".
How can I solve?

A: Your error message is clear:

These two methods produces and consumes exactly the same mime-types and therefore their invocation as a resource methods will always fail

You listen to the same path, same HTTP method and mime type for input/output.
You need to make them different so your server can clearly decide which method to call
You could for example add an id to the path of the second method.
@GET
@Produces("application/json")
@Path("/id")
public String getCardapios(@QueryParam("key") String key,
                           @QueryParam("id") String id   ) {
...
}

But if you want to have only one path, you can create two business methods, one that handles only the key and the other that handles the key and the id.
private void businessMethod1(String key) {
    // do your stuff
}

private void businessMethod2(String key, String id) {
    // do your stuff
}

@GET
@Produces("application/json")
@Path("/")
public String getCardapios(@QueryParam("key") String key,
                           @QueryParam("id") String id   ) {
    if(id == null) {
        businessMethod1(key);
    } else {
        businessMethod2(key, id);
    }
}


text:
Q: Angular2-moment Pipe in Javascript I am using Ionic3 with angular2-moment. The pipe works perfectly to format a timestamp, e.g.:
html
<ion-note class="small-text-search">
  Last Online {{personModel.lastAccessDate | amTimeAgo:true}} ago
</ion-note>

outputs:
Last Online 19 days ago

This is in my html code. I would however like to do this in a Javascript string, e.x
ts
'Last Online '+personModel.lastAccessDate | amTimeAgo:true +' ago';

error:
Typescript Error Cannot find name 'amTimeAgo'.

Question
Does anyone know how to use pipes in javascript? How would I code this? Thanks.

A: Most pipes are just thin wrappers around respective services.
Some pipes have functionality that is difficult to replace otherwise (e.g. builtin Angular pipes). In this case pipe class can be instantiated and transform method can be called.
Few pipes are designed to be used solely with compiler, like the ones that use ChangeDetectorRef to integrate with components. time-ago pipe is one of those pipes.
The proper way to do this is to use services and libraries directly. Incidentally, angular2-moment is a wrapper for Moment library. It should be
'Last Online '+ moment(personModel.lastAccessDate).fromNow() +' ago';


text:
Q: My jquery plugin throws exception I am working on a project to let the font change its color when moving mouse over it.
here is the version of without jquery plugin:
here is the html code part:

my web link places here

here is the javascript part:
    var tColorTimer;
    var myColorCollection = ["#FF6682", "#26FF51", "#263FFF", "#FF16B1", "#FFB135", "#C2B5FF","#000000"];

    //bind event
    function changeFontColorWhenHover() {
        $("#myFont").bind("mouseover", function () {
            changeFontColor(0);
        });
    }

    //change font color
    function changeFontColor(m) {
        var colorValue = myColorCollection[m];
        $("#myFont").css("color", colorValue);
        if (m < 7) {
            tColorTimer = setTimeout('changeFontColor(' + (m + 1) + ')', 100);
        }
    }

    //init bind
    $(document).ready(function () {
        changeFontColorWhenHover();
    });

above codes work correctly.
but when I turned them into a sample jquery plugin, it throws me exception as expected ']', I searched the jquery plugin a lot but can't find what I missed.
here is the jquery plugin part:
    (function ($) {
    $.fn.fontdaemon = function () {
    this.each(function () {
        $(this).bind("mouseover", function () { // onmouseover event is raised
            changeFontColor($(this), 0);
        });
    });
    };

    var tColorTimer;

    var myColorCollection = ["#FF6682", "#26FF51", "#263FFF",
    "#FF16B1", "#FFB135", "#C2B5FF", "#000000"];
function changeFontColor(obj, m) {
    var colorValue = myColorCollection[m];
    alert(m + "--" + colorValue);
    $(obj).css("color", colorValue);

    if (m < 7) {
        tColorTimer = setTimeout('changeFontColor(' + obj + "," + (m + 1) + ')', 50);
    }
    alert(m + "--" + colorValue);
};
})(jQuery);

then I use below code to call it:

when I move my mouse over the text, then it will change its color , but it will only change to first of the color in the color array , then it will throw me an exception as "Expected ']'".
Anyone can help me out? thx.
PS: I have searched google a lot, but can't find the solution, any feedback will be appreciate, thanks very much again.

A: Your problem is that you're passing a string into setTimeout (which is discouraged). When you pass a string into setTimeout, when the timeout has elapsed, it will eval the string without any access to your local variables. Since changeFontColor is not accessible out of the anonymous function passed to $, the code in the string passed to setTimeout cannot access it either.
The solution is to pass an anonymous function to setTimeout:
setTimeout(function() { changeFontColor(obj, m + 1); }, 50);

By the way, it's not necessary to use each if all you're doing is binding; bind already binds to each of the elements in the jQuery object. It is also unnecessary to be doing $(obj) in changeFontColor since obj is already a jQuery object.


text:
Q: Pinax - Customizing the sign up process - get_profile() Trying to edit Pinax django-user-account sign up process with help of this document: http://django-user-accounts.readthedocs.org/en/latest/usage.html#customizing-the-sign-up-process
I have attached these to my views.py as instructed:
    def after_signup(self, form):
    self.create_profile(form)
    super(SignupView, self).after_signup(form)

def create_profile(self, form):
    profile = self.created_user.get_profile()

    profile.firstname = form.cleaned_data["firstname"]
    profile.save()

Well, getting error "'User' object has no attribute 'get_profile'". I'm using Django 1.7.6 and according to documentation get_profile() has been removed from Django 1.7. How should I change profile getting?

A: Even i got the same error you mentioned. We will specify the AUTH_PROFILE_MODULE=account.UserProfile.But
The AUTH_PROFILE_MODULE setting, and the get_profile() method on the User model, will be removed. follow this link http://deathofagremmie.com/2014/05/24/retiring-get-profile-and-auth-profile-module/
I'm try to using the code like this. It worked for me.
def create_profile(self, form):
    profile = self.created_user.profile
    # you can use this line to either one of it will work
    # profile = self.created_user
    profile.firstname = form.cleaned_data["firstname"]
    profile.save()


text: Q: shatter or spread out object when explosion take place there is a bomb placed in the frame..5 objects are placed around the bomb. When the bomb explodes, these 5 objects need to be shattered away. The objects must move away from the bomb in a straight line path ( can be diagonally. vertically or horizontally). These objects must be in the frame even after explosion.


text:
Q: Android - Connecting to MySQL database I have been trying out the tutorials shown on various websites on connecting a MySQL database to android. At the moment the code below, takes the values which you hard code in, (i.e year=2005 and name=tom) and runs it through the php script. What I would like know is how I can modify this, so that it takes the values of what the user enters in a textbox instead.
 package com.test;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.LinearLayout;
import android.widget.TextView;

public class test extends Activity {
/** Called when the activity is first created. */

   TextView txt;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    // Create a crude view - this should really be set via the layout resources
    // but since its an example saves declaring them in the XML.
    LinearLayout rootLayout = new LinearLayout(getApplicationContext());
    txt = new TextView(getApplicationContext());
    rootLayout.addView(txt);
    setContentView(rootLayout);

    // Set the text and call the connect function.
    txt.setText("Connecting...");
  //call the method to run the data retrieval
    txt.setText(getServerData(KEY_121));

}
public static final String KEY_121 = "http://***.****.com/mysqlcon.php"; //i use my real ip here

private String getServerData(String returnString) {

   InputStream is = null;

   String result = "";
    //the year data to send
    ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    nameValuePairs.add(new BasicNameValuePair("year","2005"));
    nameValuePairs.add(new BasicNameValuePair("name","tom"));

    //http post
    try{
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(KEY_121);
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();

    }catch(Exception e){
            Log.e("log_tag", "Error in http connection "+e.toString());
    }

    //convert response to string
    try{
            BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
            }
            is.close();
            result=sb.toString();
    }catch(Exception e){
            Log.e("log_tag", "Error converting result "+e.toString());
    }
    //parse json data
    try{
            JSONArray jArray = new JSONArray(result);
            for(int i=0;i<jArray.length();i++){
                    JSONObject json_data = jArray.getJSONObject(i);
                    Log.i("log_tag","id: "+json_data.getInt("id")+
                            ", name: "+json_data.getString("name")+
                            ", sex: "+json_data.getInt("sex")+
                            ", birthyear: "+json_data.getInt("birthyear")
                    );
                    //Get an output to the screen
                    returnString += "\n\t" + jArray.getJSONObject(i);
            }
    }catch(JSONException e){
            Log.e("log_tag", "Error parsing data "+e.toString());
    }
    return returnString;
}

}

A: Okay, I understand what do you want. You want to have an EditText or two in the app. The user will enter information in it and after pressing a button th information in the EditText should move into the mysql database. So, you want to make a dynamic app that inserts record into mysql. For that do the following to modify the above java code.
Insert following line below, TextView txt;
EditText editTxt;

Below rootLayout.addView(txt);  insert following two lines,
editTxt = new EditText(this);
rootLayout.addView(editTxt);

Now, modify this line, nameValuePairs.add(new BasicNameValuePair("name","tom")); to fetch value from the EditText.
nameValuePairs.add(new BasicNameValuePair("name",editTxt.getText().toString()));

You can also create one for year.


text:
Q: automatically execute OnCheckedChangedListener when a check box is setChecked(true) in code Suppose I have a bunch of checkboxes in a listview.
I'm fetching some data from DB to set checked to those checkboxes.
Each checkbox have some specific chekedListeners.
If a checkbox is checked if found to be needed checked from DB, will the OnCheckedChangedListener work?
I'm facing a problem,
if (type.equals("technicalskills") || type.equals("programmingskills")) {
    listChecked = Base.user_technical_skills.split(",");
    setChecked(mHolder.mCheck,listChecked,i);
    if (i == 1 && type.equals("technicalskills") && ((Base.user_technical_skills.contains("MS-Office") && listChecked.length > 1) || (!Base.user_technical_skills.contains("MS-Office") && listChecked.length > 0))) {
        position == 1;
        mHolder.mCheck.setChecked(true);
        //UserDetails.prog_listView_container.setExpanded(true);
    }
}

mHolder.mCheck.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
    @Override
    public void onCheckedChanged(CompoundButton compoundButton, final boolean b) {
        if(type.equals("technicalskills") && position == 1) {
            if (b) {
                UserDetails.prog_listView_container.expand();
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1) {
                    UserDetails.prog_listView.setAlpha(0.0f);
                    UserDetails.prog_listView.animate()
                            .alpha(1.0f)
                            .setDuration(800);
                }
            } else {
                UserDetails.prog_listView_container.collapse();
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1) {
                    UserDetails.prog_listView.animate()
                            .alpha(0.0f)
                            .setDuration(800);
                }
            }
        }
    }
});

this entire code is inside a getView() method of an Adapter extending BaseAdapter
when I'm setting mcheck.setChecked(true); by code, the OnCheckedChangedListener is not executed.


text:
Q: holomorphic and antiholomorpic function is constant A function $f\colon\mathbb{C}\rightarrow\mathbb{C}$ is called antiholomorphic, when $f$ is real differentiable and  $\frac{\partial f}{\partial z}=0$.
Why is a function which is  holomorphic and antiholomorphic a constant function ?

My idea: $f$ is holomorphic. That means  $\frac{\partial f}{\partial\overline z}=\frac{1}{2}(\frac{\partial f}{\partial x}+i\frac{\partial f}{\partial y})=0$
$f$ is antiholomorphic. That means $\frac{\partial f}{\partial z}=\frac{1}{2}(\frac{\partial f}{\partial x}-i\frac{\partial f}{\partial y})=0$
All in all $\frac{\partial f}{\partial\overline z}=\frac{\partial f}{\partial z}\Leftrightarrow \frac{\partial f}{\partial y}=0$.
Has anyone an idea how to continue ?

A: It's actually very simple once you see it!
You showed that
$$ \frac{\partial f}{\partial z} = \frac{\partial f}{\partial \bar z} = 0 \implies \frac{\partial f}{\partial z} = \frac{\partial f}{\partial \bar z} \implies \frac{\partial f}{\partial y} = 0.$$
But by almost identical logic, you could also have shown that
$$ \frac{\partial f}{\partial z} = \frac{\partial f}{\partial \bar z} = 0 \implies \frac{\partial f}{\partial z} = - \frac{\partial f}{\partial \bar z} \implies \frac{\partial f}{\partial x} = 0.$$
Hopefully you can finish off from here!


text:
Q: Can't boot Debian after force EFI installation I just installed Debian with encrypted /, I made a /boot partition and converted an NTFS partition to EFI, it installed but now I can't boot on linux. My motherboard boot list put a mirrored "N" sign like the russian letter and when I try to boot on it nothing happens. I can add that the NTFS partition that I converted to EFI ESP during installation is still around with data intact and NTFS format (accessible from windows 10, it contains windows 10 booting files).
Any idea ?
Thanks.
The partitioning layout is : 500MB NTFS that i tried to convert to EFI USP, 370 NTFS, 104 Encrypted /, 1gb /boot


text:
Q: preg_match_all to check a special structure Hi i want to check with preg_match_all if a string consist of vowel and consonant.
The structure should be as consonant|vowel|consonant|vowel.
For example:
xaxa
xuxu
baba
nunu

A: This is a bit tricky because, while my first instinct was to match vowels and then not-vowels, It also matched everything else. Then there are rules in English with y sometimes being a vowel.
This should get you there.
$string = "xaxa xuxu baba nunu nnnn";
$vowels = 'aeiouy';
$consonants = 'bcdfghjklmnpqrstvwxyz';
$pattern = "!([$consonants][$vowels][$consonants][$vowels])!i";
$found = preg_match_all($pattern,$string,$matches);

foreach ($matches[0] as $value){
    echo $value."
";
}

Strange thing about English is this will also match yyyy. If you wish not to treat y as a vowel, you can remove it from the group.
$vowels = 'aeiou';

A: This script check the alternating vowel/consonant for each word and returns them:
$subject = <<<LOD
abacagopa
titot
blux
apocop
pipo
laek
LOD;

$pattern = '~
# definitions
(?(DEFINE)(?<vowel>[aeiou]))
(?(DEFINE)(?<consonant>[bcdfghjklmnpqrstvwyz]))

# pattern
\b\g<vowel>?+(?>\g<consonant>\g<vowel>)*+\g<consonant>?+\b

~ix';

echo preg_replace($pattern, '$0
', $subject);


text:
Q: Answer is likely to be used for objectionable purposes Should I answer a question if the information I am about to publish can be useful for others but also can and is very likely to be used for some dark business?
For instance - I was going to make a self-answered question on SO about how to automatically check if a email address exists on Gmail. This information could be useful for the community (I think) but it obviously can be used by spammers to make databases of existing emails.
So I am not sure if I should post it.

A: Except rare cases, we don't have access to such secrets which could be dangerous in the short, concantrated format what the SE Q&A format requires.
In your example, if my boss would ask, how long would it be for me it implement a tool to check the existence of a mail address on google, I would say, 1 hour.
This question happens quite often on different SE sites (example). The answer is mostly the same: the real dangers are too little.
There are some exceptions, for example, on the security SE, questions about the offensive side of the security are offtopic.
I think, in the case of such rare exceptions, the site knows already the problem and tunes its policies to close them out as offtopic.
So, I don't think that your content would be really dangerous, but I think it would be surely useful, so you can post it. :-)


text:
Q: jqueryte text editor. How to remove certain HTML tags that are posted in "source code" I want users to be able to use the editor or paste source HTML, but I want to link which tags are allowed (not img, a, etc).
How can I set jQueryTE to remove these tags, or all tags that aren't on my approved tag list?


text:
Q: How could one show xtick labels in multiple lines? I have the following code for my bar chart.
\documentclass[12pt,a4paper,oneside]{report}
\usepackage{pgfplots}
\usepgfplotslibrary{colorbrewer}
\pgfplotsset{width=14cm,compat=1.9}
\pgfplotstableread[row sep=\\,col sep=&]{
    Category&2007&2008&2009\\
        CSSSSSSSSSSSSSSSSSSSSSSS  & 29 & 22   & 32 \\
        CROsssssssssssssssssss & 20 & 11   & 14\\
        NCO & 23 & 20   & 28\\
        Ph  & 13 & 23   & 10 \\
        IS  & 52 & 32   & 38 \\
        L   & 8  & 21   & 11 \\
        NUK & 4  & 7    & 9 \\
        IS1  & 52 & 32   & 33\\
        L1  & 8  & 21   & 11 \\
        NUK1 & 4  & 7    & 9 \\
}\mydata

\begin{document}
\begin{tikzpicture}
\begin{axis}[
ybar,
symbolic x coords={CSSSSSSSSSSSSSSSSSSSSSSS,CROsssssssssssssssssss,NCO,Ph,IS,L,NUK,IS1,L1,NUK1},
x tick label style={align=center},
xtick=data,
% reduce height of axis a bit
height=9cm,
% set width of bars
bar width=4pt,
% remove gap below bars
ymin=0,
enlarge x limits=.3,
% remove frame around legend, add some space
legend style={draw=none,column sep=2mm},
legend columns=2,
% customize how the legend images are drawn
% draw a square instead of two bars
legend image code/.code={%
       \draw[#1,draw=none,/tikz/.cd,yshift=-0.25em]
        (0cm,1pt) rectangle (6pt,7pt);},
% color map from colorbrewer
cycle list/Paired,
% the above only sets the color, need to specify that bars should be filled
every axis plot/.append style={fill}
]
\addplot table[x=Category,y=2007]{\mydata};
\addplot table[x=Category,y=2008]{\mydata};
\addplot table[x=Category,y=2009]{\mydata};

\legend{2007,2008,2009}
\end{axis}
\end{tikzpicture}
\end{document}

I get the output like

The xlabels CSSSSSSSSSSSSSSSSSSSSSSS,CROsssssssssssssssssss are overlapping. How do I separate them in multiple lines so that they do not overlap?

A: If you really want to, introduce spaces the breaking points and set some text width. I did not have the patience to tune the width till all \underfull and \overfull complaints disappeared.
\documentclass[12pt,a4paper,oneside]{report}
\usepackage{pgfplots}
\usepgfplotslibrary{colorbrewer}
\pgfplotsset{width=14cm,compat=1.9}
\pgfplotstableread[row sep=\\,col sep=&]{
    Category&2007&2008&2009\\
        CSS SSS SSS SSS SSS SSS SSS SSS & 29 & 22   & 32 \\
        CRO sss sss sss sss sss sss s & 20 & 11   & 14\\
        NCO & 23 & 20   & 28\\
        Ph  & 13 & 23   & 10 \\
        IS  & 52 & 32   & 38 \\
        L   & 8  & 21   & 11 \\
        NUK & 4  & 7    & 9 \\
        IS1  & 52 & 32   & 33\\
        L1  & 8  & 21   & 11 \\
        NUK1 & 4  & 7    & 9 \\
}\mydata

\begin{document}
\begin{tikzpicture}
\begin{axis}[
ybar,
symbolic x coords={CSS SSS SSS SSS SSS SSS SSS SSS,CRO sss sss sss sss sss sss s,%
NCO,Ph,IS,L,NUK,IS1,L1,NUK1},
x tick label style={align=center},
xtick=data,
% reduce height of axis a bit
height=9cm,
% set width of bars
bar width=4pt,
% remove gap below bars
ymin=0,
enlarge x limits=.12,
% remove frame around legend, add some space
legend style={draw=none,column sep=2mm},
legend columns=2,
% customize how the legend images are drawn
% draw a square instead of two bars
legend image code/.code={%
       \draw[#1,draw=none,/tikz/.cd,yshift=-0.25em]
        (0cm,1pt) rectangle (6pt,7pt);},
% color map from colorbrewer
cycle list/Paired,
% the above only sets the color, need to specify that bars should be filled
every axis plot/.append style={fill},
xticklabel style={align=center,text width=6mm}
]
\addplot table[x=Category,y=2007]{\mydata};
\addplot table[x=Category,y=2008]{\mydata};
\addplot table[x=Category,y=2009]{\mydata};

\legend{2007,2008,2009}
\end{axis}
\end{tikzpicture}
\end{document}


text:
Q: DLL using MFC without CWinApp? I've recently came across a DLL (github) that uses MFC dialogs (it imports "afxdlg.h" and calls CFileDialog, for example) and appears to statically link to MFC, but doesn't have a class based on CWinApp. I'm somewhat confused: is it a MFC DLL or not? How come it doesn't have CWinApp?
Rephrased: In a Win32 DLL I use some MFC classes (e.g. I include "afxdlgs.h" and use CFileDialog) and link MFC statically. There's no DllMain. Will the final DLL have DllMain from Win32 or from MFC?
If it picks the MFC version, then another question: What is the simplest way to make a Win32 DLL with DllMain (no threads) to use MFC DllMain? Is the following correct?
#include "afx.h" /* correct? */

class MyDll: public CWinApp
{
public:
    /* do I need constructor and destructor here? */
    virtual BOOL InitInstance();
    virtual BOOL ExitInstance();
} theDll;

BOOL
MyDLL::InitInstance()
{
    CWinApp::InitInstance();
    /* code from old DllMain, DLL_PROCESS_ATTACH.
       For hInst use theDll.m_hInstance */
    return TRUE;
}

BOOL
MyDLL::ExitInstance()
{
    /* code from old DllMain, DLL_PROCESS_DETACH */
    return CWinApp::ExitInstance();
}

A: I think the simplest way to convert a standard dll to a MFC dll is to make a new MFC-dll-project and then use the generated files and paste the rest of your code into it.
AFAIK there is no difference in the source files, but there are some in the linker settings. Starting with a new project saves a lot of time and trouble.

A: CWinApp class is nothing but a controlled class which would be called in the main/tmain function which will be starting point when you start the process.  As MFC is just a library it can be used in the general console application too as per the flags given in the project properties.
The instance of cwinapp is created from the function AfxWinMain in appmodul.cpp
/////////////////////////////////////////////////////////////////////////////
// export WinMain to force linkage to this module
extern int AFXAPI AfxWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
    _In_ LPTSTR lpCmdLine, int nCmdShow);

extern "C" int WINAPI
_tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
    _In_ LPTSTR lpCmdLine, int nCmdShow)
#pragma warning(suppress: 4985)
{
    // call shared/exported WinMain
    return AfxWinMain(hInstance, hPrevInstance, lpCmdLine, nCmdShow);
}

So creating the so called directly in main function also works.


text:
Q: Maven java-doc plugin not found in IntelliJ In my IntelliJ one of POM is showing error due to plugin not found as per snippet below :

All my build configuration is correct (as per answer Maven plugins can not be found in IntelliJ)
Below is my IntelliJ settings :

Can someone please help ?

A: Issue resolved only after updating IntelliJ version to 2020.2.3
Issue not resolved in older version but even with this error there is issue no InteLLiJ build and debugger also working without any issue.


text:
Q: How to remove PHP Notice from production environment not present in development environment I've built a web app that works perfectly in my development environment. In my production environment, however, I get notices that I cannot reproduce in my dev environment although I've set PHP to report all errors with 'error_reporting(E_ALL);' at the start of the page.
eg,'Notice: Undefined index: name in /home/bontshit/public_html/admin/library/functions.php on line 202'. How can I track down the problem without simply muting the error reporting?
I'm using The AppServ Open Project - 8.6.0 for Windows
Now you running on PHP 5.6.30; my production environment is on the same version of PHP. I've added the code the notice I mentioned refers to and clearly (I believe) the index 'name' was defined.
$categories = array();
while($row = dbFetchAssoc($result)) {
    extract($row);

    if ($cat_parent_id == 0) {
        // we create a new array for each top level categories
        $categories[$cat_id] = array('name' => $cat_name, 'children' => array());
    } else {
        // the child categories are put into the parent category's array
        $categories[$cat_parent_id]['children'][] = array('id' => $cat_id, 'name' => $cat_name);
    }
}

// build combo box options
$list = '';
foreach ($categories as $key => $value) {
    $name     = $value['name'];
    $children = $value['children'];

    $list .= "<option value=\"$key\"";

    if ($key == $catId) {
        $list.= " selected";
    }

    $list .= ">$name</option>\r\n";

    foreach ($children as $child) {
        $list .= "<option value=\"".$child['id']."\"";
        if ($child['id'] == $catId) {
            $list.= " selected";
        }

        $list .= ">  ".$child['name']."</option>\r\n";
    }
}

A: I simply flushed out the contents of my db and reloading the data. So far everything is working again. I don't know how it corrupted to begin with but I'm glad to move forward. Wow! After all that. KISS principle at its best :P .. Thanks guys.


text:
Q: how do i restart a svnadmin load from a revision I have a dump file that I was loading when my connection to the server was terminated and the load stopped.  I was able to go into the new repository and see what the last revision was.  From what I have read, which is very little, it appears that I have to rebuild the dump file using the top of my existing dump file and then removing the sections corresponding to the revision numbers that have already been loaded.
Is it possible to begin the load without having to edit the initial dump file?

A: I believe that the second comment that ThisSuitIsBlackNot made is the correct answer.  Also, you can refer to the link in the first comment for additional details.
Thank you.


text:
Q: Getting cursor row in contenteditable div (jquery) I need to get learn where is my cursor on contenteditable div.
when I press enter, contenteditable div creates a "" as a row. just like:

then, I need to learn, in which row is my cursor, then I'm gonna append some html codes in it.
How can I do this with jquery?

A: You can use JQuery's insertAfter() function for this.
JSFiddle
$('.contenteditable div').click(function() {
  $('
New Div
').insertAfter(this);
});

When you click on one of the divs inside contenteditable, it inserts a new div right after it.  I added the text 'New Div' to make it more obvious where the new entry went.

A: use this:
$('button').click(function(){
var $div=$('div'), isEditable=$div.is('.editable');
$div.prop('contenteditable',!isEditable).toggleClass('editable') })

demo: http://jsfiddle.net/Wu4VD/65/
Edited later:
I think you want that! on event click, on div for edit, to see the row (index or id)

Some text 1

Some text 2

Some text 3

Some text 4

$('.contenteditable div').click(function(){
    alert($(this).attr("id"));
 });

Click here to see demo


text:
Q: Transpose and eigenvalues There is a question in Hoffman Kunze, $V$ finite dimensional, $T$ a linear operator with $\alpha$ non zero such that $T\alpha=c\alpha$ for some $c$. The question is to show that there is $f$ is the dual nonz ero such that $T^tf=cf$, where $T^t$ denotes the transpose.\
My attempt: I took $\alpha$ an extend it to a basis, say $\alpha,e_2,...,e_n$ and then took the dual base $f,f_2,...,f_n$. I think my $f$ should work but Im a bit confused. Because now, for $x\in V$, $x=f(x)\alpha+\sum f_i(x)e_i$, hence:
$$T^tf=(f\circ T)(x)= f\left(f(x)T\alpha+\sum f_i(x)Te_i\right)$$
$$=f\left(f(x)c\alpha+\sum f_i(x)Te_i\right)=cf(x)+\sum f_i(x)f(Te_i)$$
I dont know how to get rid of the terms $Te_i$. Can someone help me fix my proof? Or should I go other direction?


text:
Q: Disable and Enable Arrowkeys by javascript I have a scenario where first I need to disable keyboard arrow keys and after some processing again Enable it,for this I write this jquery function
function DisableArrowKeys() {
        var ar = new Array(37, 38, 39, 40);
        $(document).keydown(function(e) {
            var key = e.which;
            if ($.inArray(key, ar) > -1) {
                e.preventDefault();
                return false;
           }
            return true;
        });
    }

this function can disable arrow keys,after some processing I need to enable arrow key for this I made changes in the function like below
function EnableArrowKeys() {
        var ar = new Array(37, 38, 39, 40);
        $(document).keydown(function(e) {
            var key = e.which;
            if ($.inArray(key, ar) > -1) {
                return true;
            }
        });
    }

But when we call that function it does not enable arrowkeys.

A: You need to keep a reference to your disabling function, and unbind it when you are ready to accept arrow keys once more.  Something like:
var ar = new Array(37, 38, 39, 40);
var disableArrowKeys = function(e) {
    if ($.inArray(e.keyCode, ar)>=0) {
        e.preventDefault();
    }
}

$(document).keydown(disableArrowKeys);

// then when you are ready to enable, unbind the function...
$(document).unbind('keydown', disableArrowKeys);

A: The second handler (attached in EnableArrowKeys function) is not cancelling the first one. jQuery event handlers are chained:
If there are multiple handlers registered, they will always execute in the order in which they were bound.
So, use unbind function in EnableArrowKeys function instead of adding another handler.
function EnableArrowKeys() {
    $(document).unbind('keydown');
}

A: You could do this:
var DisableArrowKeys = function(e){
    if ($.inArray(e.which, ar) > -1) {
        e.preventDefault();
        return false;
    }
    return true;
}
$(document).bind("keydown", DisableArrowKeys);

and then to unbind:
$(document).unbind("keydown", DisableArrowKeys);


text:
Q: Meaning of count it off The phrase is from an animated tv series called Teenage Mutant Ninja Turtles theme song.
You can see the full lyrics here:
https://genius.com/Teenage-mutant-ninja-turtles-turtles-theme-2003-lyrics
This is where it first appears:

Teenage Mutant Ninja Turtles
Turtles, count it off!
One, Two, Three, Four!

Wikipedia says it's something related to music to establish the piece's initial tempo, time signature and style. But this doesn't appear to be related to music at all. Is it?
Perhaps it's just because the main characters are four? Or maybe because they follow four rules?
The four rules from the lyrics

One! / Live by the code of the martial arts.
Two! / Never fight unless someone else starts.
Three! / Always stick together no matter what.
Four! / If all else fails then it's time to kick butt!

Dictionary.com had this entry:

Count off
Count aloud from one end of a line of persons to the other, each person counting in turn. For example, The soldiers counted off one by one. This usage and the practice it describes come from the military.
  But what is

A: To count something off means to audibly mark a group of things with consecutive numbers.
In music, the leader counts off the beats of a measure before the music begins to signal the desired tempo to the musicians.
As a way for a group of people to count itself, the group 'counts off' one by one until the last person has counted off. The number that the last one recites is the number of people in the group.
In these lyrics the turtles count off in several ways. They count off the beats to start the first and third verses while they're counting themselves off one by one, and they count off the four rules they live by. Then they count off beats again during the conclusion. Because of the repetition, counting to four is a theme in the song - perhaps to emphasize the fact that they are four of them and they have four rules that they live by. The number four ties it all together simply and helps keep the audience of young children engaged.
One potentially confusing thing is when the turtles sing 'count it off', it's not clear what it is. What are they counting off? To me it seems that it's part of the whimsical nature of the song that we don't know exactly. Songs are poetry so they don't always exactly make literal sense like stories do. They count off beats of the song, they count the four of themselves off from one to four, they count off the four parts of their code of conduct. In this song 'it' is all of these things. In any case, it's obvious that the turtles know what to count without being told. They know something we don't know. This emphasizes the idea that they're a tight team, perfectly coordinated, with a plan for action.
The song can be heard on YouTube.com.

A: "Count it off" here is a filler line in the song. It is an imperative statement - perhaps to their fellow Turtles, perhaps to the audience -, but it refers to the fact that the Turtles are about to "count it off" by saying, "One, Two, Three, Four" to start the song. Not exactly an industry standard in music (generally, "count (someone) in" is more commonly heard among real musicians), but it's clear that the Turtles are alluding to starting the song by counting to four.
As in real music, the counting is done to establish a consistent tempo for the song to follow. That means communicating how fast or slow the song is going to be performed.


text:
Q: Seaborn PairGrid axes in common ranges I have a PairGrid as shown below. However, I want the x-axes show a common range (1 to 9) and the y-axes show a another common range (0 to 10). How can I do that? Thanks.
import seaborn as sns
import matplotlib.pyplot as plt
sns.set(style="white")

df = sns.load_dataset("iris")

g = sns.PairGrid(df, diag_sharey=False, vars=['sepal_length','sepal_width'])
g.map_lower(sns.kdeplot, cmap="Blues_d")
g.map_upper(plt.scatter)
g.map_diag(sns.kdeplot, lw=3)


text:
Q: Can I view only a specific part of code and make the rest disappear? I'm using IntelliJ and VSCode and i'm wondering if there is a way to mark a part of the code and the tool will only display and focus on that code and will make the rest disappear. This will help to get rid of clutter code that i'm not interested in.

A: You can point the cursor over the code block you want to focus on, press Ctrl+Shift+NumPad - to collapse all code blocks and press Ctrl+NumPad - to expand the selected one. See Write and edit source code | Code Folding for more information.
In addition you can consider using Distraction Free Mode.


text:
Q: How to use git lfs in AWS CodeBuild? Since AWS CodeBuild doesn't seem to support git LFS (Large File System) I tried to install it:
version: 0.2

phases:
  install:
    commands:
      - apt-get install -y bash curl
      - curl -s https://packagecloud.io/install/repositories/github/git-lfs/script.deb.sh | bash
      - apt-get install -y git-lfs
  pre_build:
    commands:
      - echo Downloading LFS files
      - git lfs pull
  build:
    commands:
      - echo Build started on `date`
  post_build:
    commands:
      - echo Build completed on `date`

For the above code I'm getting the following error (renamed repo address):
[Container] 2020/06/18 16:02:17 Running command git lfs pull
fatal: could not read Password for 'https://username@bitbucket.org': No such device or address
batch response: Git credentials for https://username@bitbucket.org/company/repo.git not found.
error: failed to fetch some objects from 'https://username@bitbucket.org/company/repo.git/info/lfs'

[Container] 2020/06/18 16:02:17 Command did not exit successfully git lfs pull exit status 2
[Container] 2020/06/18 16:02:17 Phase complete: PRE_BUILD State: FAILED
[Container] 2020/06/18 16:02:17 Phase context status code: COMMAND_EXECUTION_ERROR Message: Error while executing command: git lfs pull. Reason: exit status 2

Can I do something else in order to fetch LFS files?

A: CodeBuild does not natively support git LFS. The workaround would be to set up Git LFS 1 and cloning the repository 2 as part of the buildspec.yml execution.
Use 'git-credential-helper: yes' in buildspec for CodeBuild to provide the credentials to git commands 3.

A: CodeBuild does not support Git LFS, however it's possible to install it on-the-fly and then run git lfs pull from the source directory to download the files. Like this:
env:
  git-credential-helper: yes

phases:
  install:
    commands:
      - cd /tmp/
      - curl -OJL https://github.com/git-lfs/git-lfs/releases/download/v2.13.2/git-lfs-linux-amd64-v2.13.2.tar.gz
      - tar xzf git-lfs-linux-amd64-v2.13.2.tar.gz
      - ./install.sh
      - cd $CODEBUILD_SRC_DIR

  pre_build:
    commands:
      - git lfs pull

<rest of your buildspec.yml file>

A: CodeBuild doesn't support Git LFS out of the box. One workaround would be to install it manually, but this will work only if you are connecting to GitHub, BitBucket or other provider directly (e.g. via SSH key).
If you are using it with CodePipeline and using repositories connection (aka "CodeStar Source Connections") then it won't work. When you connect your BitBucket or GitHub account this way, it creates some kind of "proxy" that doesn't support git-lfs resources:
batch response: Repository or object not found: https://codestar-connections.eu-central-1.amazonaws.com/git-http/[..].git/info/lfs/objects/batch

Check that it exists and that you have proper access to it

Failed to fetch some objects from 'https://codestar-connections.eu-central-1.amazonaws.com/git-http/[..].git/info/lfs'

With GitHub however there is a workaround:
GitHub CodeBuild git-lfs workaround
First you have to make sure that in the pipeline's Source stage, source output artifact it set to CODE_ZIP which equals to following setting in the Console:

Then in GitHub, in the repository settings, make sure that git-lfs resouces are included in source code archives:

This will make it work. Now source code downloaded by CodePipeline and passed to CodeBuild will include git-lfs files.


text:
Q: Password Encription (SHA1) by Oracle Weblogic 10.3.2 Weblogic 10.3.2 uses SHA-1 (and others) for pass encryption. For example the following password:

abcdefg

with SHA-1 encryption results:

teshjSf9GOUIvRHljjMafld8YsWTlQ4=

I have tried various websites that do SHA-! encryption, but none that result with the above answer. There is a possibility Salt is being utilized. Basically, what steps were taken to get the result.
Any help is appreciated.

A: Passwords should be salted. Hopefully even Oracle knows that. If so, you'll need the salt for a particular password.
You'll also need to know the number of times the hash function was applied, and how the salt was combined with the password. I doubt this is considered a published interface, so WebLogic is unlikely to document this.

A: try this, it works for weblogic SQL Authenticator
public static void main(String args[]) throws NoSuchAlgorithmException {
String password="abcdef";
System.out.println("{SHA-1}"
                 + new sun.misc.BASE64Encoder()
                .encode(java.security.MessageDigest.getInstance("SHA1")
                .digest(password.getBytes())));
}


text:
Q: How to use Azure App to send email on users behalf? I try to send an email on users behalf from Azure Web App using Open Graph. Email has to be sent using office365 mail server and should be saved in users Sent mailbox. Mentioned App can be accessed by authorized users only, authorization is performed with the use of below endpoint:
https://login.microsoftonline.com/{tennantid}/oauth2/authorize?response_type=code+id_token&redirect_uri={domain}.auth%2Flogin%2Faad%2Fcallback&client_id={clientId}&scope=openid+profile+email&response_mode=form_post

Once user logs in, I fetch access token for further requests to Open Graph:
https://login.microsoftonline.com/{tennantid}/oauth2/v2.0/token

grant_type  "client_credentials"
client_secret   "{clientSecret}"
client_id   "{clientId}"
scope   "https://graph.microsoft.com/.default"

Next, I post to sendMail endpoint:
https://graph.microsoft.com/v1.0/me/sendMail

and pass necessary parameters, as well as authorization Bearer {accessToken} header where accessToken was retrieved in previous step. This returns an error:
"code":"NoPermissionsInAccessToken","message":"The token contains no permissions, or permissions can not be understood."

As for permissions, app has delegated permissions set up for mail.send so that it can send emails on behalf of logged in user only. App does not ask user for permissions when logging in, ther are no consents presented.
I have no more ideas how to make it work after digging into documentations and spending there quite some time so any tip will be appreciated.

A: As you are using the Client Credential grant type you will be getting the App token and you need to have application token set for it.
The API doesn't know what is the meaning of /me here since its a client credential flow.
If you want to use client credential flow then to send mail you need to specify the call this way.
https://graph.microsoft.com/v1.0/users/{Userid/UPN}/sendMail
So please add Mail.Send Application permission in you App in Azure as shown in the below screenshot and then make the above call.

You can also verify whether you are have permissions or not by using your access token at JWT site.


text:
Q: How to model a DC motor in LTSpice if only its nominal voltage and max. current is known? Is there a simple way to model a DC motor in LTSpice when controlling it with a PWM signal? Lets say the motor is 9V/2A.
I was thinking the safest way to measure the stall current and use the nominal voltage but I think there is more to handle this.
edit: Or should I say, can we model a DC motor as a resistance if we know at a particular rpm and voltage it draws known amount of current?

A: What are you modeling it for?
Noise immunity of nearby circuitry?
PID control loop characteristics, to allow loop tuning?
Short circuit, temperature and stall current protection?
Overvoltage protection, including driving the shaft without applied power?
Or basic startup and speed control in the driver?
All of these require different simple models, or one really comprehensive model, which would be unnecessarily complicated in most scenarios..
For a simple model for a toy motor, you can ignore mechanical aspects like the inertia of the load.
I suggest running several models of increasing complexity or severity.

*

*A simple resistance = rated voltage/rated current. Tests basic operation. Look at power dissipation in the driver, compare with your heatsink.

*A simple resistance = measured winding resistance. Tests that the driver can survive a stalled motor. It's OK if it shuts down or consumes enough current to reliably blow a fuse (say >= 2x the fuse rating). Or Look at power dissipation in the driver in this worst case, compare with your heatsink.

*A more complex model including back-EMF (speed-dependent voltage source) and a realistic inductance in series with the stall resistance. This tests the driver can supply enough current to start it, and overvoltage conditions from the motor's inductance. Drive the voltage source with a ramp from 0 to rated speed over a few seconds.

*If it is possible to rotate the shaft while the driver is unpowered, teh motor will act as a generator. Model (3) can be used to test that the driver will survive this scenario.

A:
Or should I say, can we model a DC motor as a resistance if we know at a particular rpm and voltage it draws known amount of current?

It won't be realistic; using only a resistor your motor won't have any inertia. Even minimal models of motors use an inductor and back emf source. Furthermore, when you approach the stall condition your motor is no longer a linear magnetic circuit because it approaches saturation.
For SPICE2 models that work with most implementations have a look at the "level 1" circuit in "DC machine models for SPICE2 simulation". They use a trick in which a diode is used to approximate the tanh curve approaching saturation; that's "approach 2" in there. You could also use a piece-wise linear circuit as in their "approach 1", but then you'll have a sharp transition.

A: Usually it is modeled with a R and a L in series and a speed dependent voltage source (EMF).
You could try to give a short voltage pulse onto the motor terminals (it mustn't start to move, so it would be best to fix the rotor) and measure the current. The current will settle and you can measure the time constant and calculate your R and L values like this.
For determining the KV value to model the voltage source, I recommend the following PDF: https://hal.inria.fr/file/index/docid/746891/filename/82.pdf
If you also want to model it's mechanical behaviour (acceleration, speed etc.) it's getting tougher in LTSpice (you might want to switch to Matlab or similar for that). It is basically also an first order system which can be described as an integrator (neglecting the usually speed dependent friction). You should find more information on that in control theory literature.
Cheers C.


text:
Q: How to access application running on Gitlab review apps? .gitlab-ci.yml file
image: node:latest

services:
# This folder is cached between builds

stages:
  - deploy
cache:
  paths:
  - node_modules/
deploy_staging:
  stage: deploy
  script:
    - echo "Deploy to staging server"
    - npm install
    - npm install pm2 -g
    - pm2 start bin/www --name mms
    - ps -ef | grep mms
  environment:
    name: staging
    url: http://staging.example.com

I have deployed a nodeJS application on the server, how can I access the endpoints of the app using this URL?

A: You seem to be confusing what the environment can and can not do. The url variable is just for your convenience:

This is an optional value that when set, it exposes buttons in various places in GitLab which when clicked take you to the defined URL.

Gitlab doesn't create an endpoint under the URL, you supply the URL under which the application is reachable after the deploy.

A: Link to answer which solves all queries
This is most accurate answer to solve all gitlab CI queries


text:
Q: When is it fair to purposefully cause undefined behaviour? The standard library habitually allows for undefined behaviour if you break any requirements on template types, give erroneous function arguments, or any other breach of contract. Is it considered a good practise to allow this in user libraries? When is it fair to do so?
Consider writing an operator[] for a container:
template <typename t>
T& container<T>::operator[](int i)
{
  return internal_array[i];
}

If i indexes outside the bounds of the internal_array, we hit undefined behaviour. Should we allow this to happen or do bounds checking and throw an exception?
Another example is a function that takes an int argument but only allows a restricted domain:
int foo(int x)
{
  if (x > 0 && x <= 10) {
    return x;
  }
}

If x is not within the domain, execution will reach the end of the function without a return statement - this gives undefined behaviour.
Should a library developer feel bad for allowing this or not?

A:
When is it fair to purposefully cause undefined behaviour?

Assuming you're asking this from the point of view of a library implementer: whenever you warn your client that failing to comply with the pre-conditions of a given function causes Undefined Behavior, and your client breaks those pre-conditions.
The C++11 Standard Library defines a lot of such functions: just think of the subscript operator for sequence collections.
If you're asking this from the viewpoint of an application programmer, on the other hand, the answer is of course "never", unless you are writing non-portable code that relies on some documented extension of your compiler and/or on some functionality of your Operating System (but then it's arguable whether you are still "talking C++").

Should a library developer feel bad for allowing this or not?

If that was the case, mr. Stepanov should feel horrible by now. No, it is not bad, it just depends on whether your library is designed for maximum efficiency or for maximum safety - with a lot of nuances in the middle.

A: It all boils down to documentation.
Intuitively you wouldn't expect [] to do any bound checking, but you could also provide an at method to your container that throws an exception (yay, just like the folks that write the std). Of course you could throw an exception, but document this behavior.
The second is fair-play as well as long as you clearly document that the behavior is undefined if the function is called with the bad arguments and you have a good reason to do so (red on). If you're designing a performance-critical library, you don't want the overhead of checking input. If not, throw an exception.


text:
Q: Github action variable substitution for xml connectionstring replacement I'm trying to replace the connectionString in an App.Config XML file for a WPF app based on prod/qa/dev environments.  I'm trying to use the github actions variable substitution (https://github.com/marketplace/actions/variable-substitution) to do it.
The goal is to replace the following section with alternative sources:
        <add name="DefaultConnection"
             connectionString="Data Source=(LocalDb)\\MSDB;DbFilename=aspcore-local.mdf;" />

I was able to successfully change a simple json file, but how can this section be replaced in an XML file?
    - name: variable substitution in json
      uses: microsoft/variable-substitution@v1
      with:
        files: 'test.xml'
      env:
        configuration.connectionStrings.DefaultConnection.connectionString: "test" ????

    <?xml version="1.0" encoding="utf-8"?>
    <configuration>
        <connectionStrings>
            <add name="DefaultConnection" connectionString="replaceme!"/>
        </connectionStrings>
    </configuration>

I initially thought to transform the file using https://learn.microsoft.com/en-us/azure/devops/pipelines/tasks/utility/file-transform?view=azure-devops but that's only available in Azure DevOps vs. GitHub actions.
I know there is a better way, I just don't know what it is...
thanks!

A: I wound up using a combination of regex (awesome generator), search and replace strings, and XML path search/replace for connection strings, appx settings, version, etc.  I used a channel variable (prod, beta, etc.) in combination with if: statement to apply the necessary changes.
   - name: change update location for dev
      run: |
       $autoupdate = "<AppInstallerUri>\\\\([a-zA-Z]+(\\[a-zA-Z]+)+)</AppInstallerUri>"
       $devautoupdate = "<AppInstallerUri>c:\temp</AppInstallerUri>"
       $Path = "D:\a\repo..wapproj" #specify location of checked out WAP project file
       (Get-Content -Path $Path -Raw) -replace $autoupdate, $devautoupdate | Out-File $Path
      if: ${{ inputs.channel == 'dev'}}

    - name: App.config change statements for prod
      run: |
       (Get-Content -Path D:\a\.....repo-project location of App.config -Raw) -replace '<connectionStrings configSource="ConnectionStrings.dev.config">','<connectionStrings configSource="ConnectionStrings.prod.config">' | Set-Content -Path D:\a\.....repo-project location of App.config -Raw) -replace '<appSettings configSource="AppSettings.dev.config" />','<appSettings configSource="AppSettings.prod.config" />'
      if: ${{ inputs.channel == 'prod'}}

    - name: assign prod variables
      run: |
        echo "MsixPackageId=MyApp.Prod" >> $env:GITHUB_ENV
        echo "MsixPublisherId=CN=Acme Inc, O=Acme, L=Mars, S=Milky Way, C=Universe" >> $env:GITHUB_ENV
        echo "MsixPackageDisplayName=MyApp (Prod)" >> $env:GITHUB_ENV
      if: ${{ inputs.channel == 'prod'}}

    - name: Update manifest version
      run: |
        [xml]$manifest = get-content ".\$env:Wap_Project_Directory\Package.appxmanifest"
        $manifest.Package.Identity.Version = "${{ env.Ver }}"
        $manifest.Package.Identity.Name = "${{ env.MsixPackageId }}"
        $manifest.Package.Identity.Publisher = "${{ env.MsixPublisherId }}"
        $manifest.Package.Properties.DisplayName = "${{ env.MsixPackageDisplayName }}"
        $manifest.Package.Applications.Application.VisualElements.DisplayName = "${{ env.MsixPackageDisplayName }}"
        $manifest.save(".\$env:Wap_Project_Directory\Package.appxmanifest")


text:
Q: Remove certain consecutive duplicates in list I have a list of strings like this:
['**', 'foo', '*', 'bar', 'bar', '**', '**', 'baz']

I want to replace the '**', '**' with a single '**', but leave 'bar', 'bar' intact. I.e. replace any consecutive number of '**' with a single one. My current code looks like this:
p = ['**', 'foo', '*', 'bar', 'bar', '**', '**', 'baz']
np = [p[0]]
for pi in range(1,len(p)):
  if p[pi] == '**' and np[-1] == '**':
    continue
  np.append(p[pi])

Is there any more pythonic way to do this?

A: Not sure about pythonic, but this should work and is more terse:
star_list = ['**', 'foo', '*', 'bar', 'bar', '**', '**', 'baz']
star_list = [i for i, next_i in zip(star_list, star_list[1:] + [None])
             if (i, next_i) != ('**', '**')]

The above copies the list twice; if you want to avoid that, consider Tom Zych's method. Or, you could do as follows:
from itertools import islice, izip, chain

star_list = ['**', 'foo', '*', 'bar', 'bar', '**', '**', 'baz']
sl_shift = chain(islice(star_list, 1, None), [None])
star_list = [i for i, next_i in izip(star_list, sl_shift)
             if (i, next_i) != ('**', '**')]

This can be generalized and made iterator-friendly -- not to mention more readable -- using a variation on the pairwise recipe from the itertools docs:
from itertools import islice, izip, chain, tee
def compress(seq, x):
    seq, shift = tee(seq)
    shift = chain(islice(shift, 1, None), (object(),))
    return (i for i, j in izip(seq, shift) if (i, j) != (x, x))

Tested:
>>> list(compress(star_list, '**'))
['**', 'foo', '*', 'bar', 'bar', '**', 'baz']

A: This is in my opinion pythonic
result = [v for i, v in enumerate(L) if L[i:i+2] != ["**", "**"]]

the only "trickery" being used is that L[i:i+2] is a list of one element when i == len(L)-1.
Note that of course the very same expression can also be used as a generator

A: This works. Not sure how Pythonic it is.
import itertools

p = ['**', 'foo', '*', 'bar', 'bar', '**', '**', 'baz']

q = []
for key, iter in itertools.groupby(p):
    q.extend([key] * (1 if key == '**' else len(list(iter))))

print(q)

A: from itertools import groupby

p = ['**', 'foo', '*', 'bar', 'bar', '**', '**', 'baz']
keep = set(['foo',  'bar', 'baz'])
result = []

for k, g in groupby(p):
    if k in keep:
        result.extend(list(g))
    else:
        result.append(k)

A: A solution without itertools.groupby() :
p = ['**', 'foo', '*', 'bar', 'bar', '**', '**', '**', 'baz', '**', '**',
     'foo', '*','*', 'bar', 'bar','bar', '**', '**','foo','bar',]

def treat(A):
    prec = A[0]; yield prec
    for x in A[1:]:
        if (prec,x)!=('**','**'):  yield x
        prec = x

print p
print
print list(treat(p))

result
['**', 'foo', '*', 'bar', 'bar', '**', '**', '**',
 'baz', '**', '**',
 'foo', '*', '*', 'bar', 'bar','bar', '**', '**',
 'foo', 'bar']

['**', 'foo', '*', 'bar', 'bar', '**',
 'baz', '**',
 'foo', '*', '*', 'bar', 'bar', 'bar', '**',
 'foo', 'bar']

Another solution, inspired from dugres
from itertools import groupby

p = ['**', 'foo', '*', 'bar', 'bar', '**', '**', '**', 'baz', '**', '**',
     'foo', '*','*', 'bar', 'bar','bar', '**', '**','foo','bar',]

res = []
for k, g in groupby(p):
    res.extend(  ['**'] if k=='**' else list(g) )
print res

It's like Tom Zych's solution, but simpler
.
EDIT
p = ['**','**', 'foo', '*', 'bar', 'bar', '**', '**', '**', 'baz', '**', '**',
     'foo', '*','*', 'bar', 'bar','bar', '**', '**','foo','bar', '**', '**', '**']

q= ['**',12,'**',45, 'foo',78, '*',751, 'bar',4789, 'bar',3, '**', 5,'**',7, '**',
    73,'baz',4, '**',8, '**',20,'foo', 8,'*',36,'*', 36,'bar', 11,'bar',0,'bar',9,
    '**', 78,'**',21,'foo',27,'bar',355, '**',33, '**',37, '**','end']

def treat(B,dedupl):
    B = iter(B)
    prec = B.next(); yield prec
    for x in B:
        if not(prec==x==dedupl):  yield x
        prec = x

print 'gen = ( x for x in q[::2])'
gen = ( x for x in q[::2])
print 'list(gen)==p is ',list(gen)==p
gen = ( x for x in q[::2])
print 'list(treat(gen)==',list(treat(gen,'**'))

ch = '??h4i4???4t4y?45l????hmo4j5???'
print '\nch==',ch
print "''.join(treat(ch,'?'))==",''.join(treat(ch,'?'))

print "\nlist(treat([],'%%'))==",list(treat([],'%%'))

result
gen = ( x for x in q[::2])
list(gen)==p is  True
list(treat(gen)== ['**', 'foo', '*', 'bar', 'bar', '**', 'baz', '**', 'foo', '*', '*', 'bar', 'bar', 'bar', '**', 'foo', 'bar', '**']

ch== ??h4i4???4t4y?45l????hmo4j5???
''.join(treat(ch,'?'))== ?h4i4?4t4y?45l?hmo4j5?

list(treat([],'%%'))== []

.
Remark: A generator function allows to adapt the output to the type of the input with a writing around the call of the generator, it dosn't require to change th internal code of the genrator function;
That's not the case with the Tom Zynch's solution , that can't be adapted so easely to the type of the input
.
EDIT 2
I searched a one-line method, with a list comprehension or a generator expression.
I found to ways of doing this, I think it isn't possible to do without groupby()
from itertools import groupby
from operator import concat

p = ['**', '**','foo', '*', 'bar', 'bar', '**', '**', '**',
     'bar','**','foo','sun','sun','sun']
print 'p==',p,'\n'

dedupl = ("**",'sun')
print 'dedupl==',repr(dedupl)

print [ x for k, g in groupby(p) for x in ((k,) if k in dedupl else g) ]

# or

print reduce(concat,( [k] if k in dedupl else list(g) for k, g in groupby(p)),[])

Based on the same principle, it is easy to convert the function of dugres into a generator function:
from itertools import groupby

def compress(iterable, to_compress):
    for k, g in groupby(iterable):
        if k in to_compress:
            yield k
        else:
            for x in g: yield x

However , this generator function has two disadvantages:

*

*it resorts to the function groupby(), which is not easy to understand by someone not used to Python

*its execution's time is longer than the ones of my generator function treat() and the generator function of John Machin, that don't use groupby().
I slightly modified them to make them able to accept a sequence of items to be de-duplicated, and I measured the durations of execution:
from time import clock
from itertools import groupby

def squeeze(iterable, victims, _dummy=object()):
    if hasattr(iterable, '__iter__') and not hasattr(victims, '__iter__'):
        victims = (victims,)
    previous = _dummy
    for item in iterable:
        if item in victims and item==previous:
            continue
        previous = item
        yield item

def treat(B,victims):
    if hasattr(B, '__iter__') and not hasattr(victims, '__iter__'):
        victims = (victims,)
    B = iter(B)
    prec = B.next(); yield prec
    for x in B:
        if x  not in victims or x!=prec:  yield x
        prec = x

def compress(iterable, to_compress):
    if hasattr(iterable, '__iter__') and not hasattr(to_compress, '__iter__'):
        to_compress = (to_compress,)
    for k, g in groupby(iterable):
        if k in to_compress:
            yield k
        else:
            for x in g: yield x

p = ['**', '**','su','foo', '*', 'bar', 'bar', '**', '**', '**',
     'su','su','**','bin', '*','*','bar','bar','su','su','su']

n = 10000

te = clock()
for i in xrange(n):
    a = list(compress(p,('**','sun')))
print clock()-te,'  generator function with groupby()'

te = clock()
for i in xrange(n):
    b = list(treat(p,('**','sun')))
print clock()-te,'  generator function eyquem'

te = clock()
for i in xrange(n):
    c = list(squeeze(p,('**','sun')))
print clock()-te,'  generator function John Machin'

print p
print 'a==b==c is ',a==b==c
print a

The instruction
if hasattr(iterable, '__iter__') and not hasattr(to_compress, '__iter__'):
    to_compress = (to_compress,)

is necessary to avoid errors when the the iterable argument  is a sequence and the other argument only one string: this latter needs then to be modified into a container, provided that the iterable argument isn't  a string itself.
It is based on the fact that sequences like tuples, lists, stes... have the method iter, but strings haven't. The following code shows the problems:
def compress(iterable, to_compress):
    if hasattr(iterable, '__iter__') and not hasattr( to_compress, '__iter__'):
        to_compress = (to_compress,)
    print 't_compress==',repr(to_compress)
    for k, g in groupby(iterable):
        if k in to_compress:
            yield k
        else:
            for x in g: yield x

def compress_bof(iterable, to_compress):
    if not hasattr(to_compress, '__iter__'): # to_compress is a string
        to_compress = (to_compress,)
    print 't_compress==',repr(to_compress)
    for k, g in groupby(iterable):
        if k in to_compress:
            yield k
        else:
            for x in g: yield x

def compress_bug(iterable, to_compress_bug):
    print 't_compress==',repr(to_compress_bug)
    for k, g in groupby(iterable):
        #print 'k==',k,k in to_compress_bug
        if k in to_compress_bug:
            yield k
        else:
            for x in g: yield x

q = ';;;htr56;but78;;;;$$$$;ios4!'
print 'q==',q
dedupl = ";$"
print 'dedupl==',repr(dedupl)
print

print "''.join(compress    (q,"+repr(dedupl)+")) :\n",''.join(compress    (q,dedupl))+\
      ' <-CORRECT ONE'
print
print "''.join(compress_bof(q,"+repr(dedupl)+")) :\n",''.join(compress_bof(q,dedupl))+\
      '  <====== error ===='
print
print "''.join(compress_bug(q,"+repr(dedupl)+")) :\n",''.join(compress_bug(q,dedupl))

print '\n\n\n'

q = [';$', ';$',';$','foo', ';', 'bar','bar',';',';',';','$','$','foo',';$12',';$12']
print 'q==',q
dedupl = ";$12"
print 'dedupl==',repr(dedupl)
print
print 'list(compress    (q,'+repr(dedupl)+')) :\n',list(compress    (q,dedupl)),\
      ' <-CORRECT ONE'
print
print 'list(compress_bof(q,'+repr(dedupl)+')) :\n',list(compress_bof(q,dedupl))
print
print 'list(compress_bug(q,'+repr(dedupl)+')) :\n',list(compress_bug(q,dedupl)),\
      '  <====== error ===='
print

result
q== ;;;htr56;but78;;;;$$$$;ios4!
dedupl== ';$'

''.join(compress    (q,';$')) :
t_compress== ';$'
;htr56;but78;$;ios4! <-CORRECT ONE

''.join(compress_bof(q,';$')) :
t_compress== (';$',)
;;;htr56;but78;;;;$$$$;ios4!  <====== error ====

''.join(compress_bug(q,';$')) :
t_compress== ';$'
;htr56;but78;$;ios4!

q== [';$', ';$', ';$', 'foo', ';', 'bar', 'bar', ';', ';', ';', '$', '$', 'foo', ';$12', ';$12']
dedupl== ';$12'

list(compress    (q,';$12')) :
t_compress== (';$12',)
[';$', ';$', ';$', 'foo', ';', 'bar', 'bar', ';', ';', ';', '$', '$', 'foo', ';$12']  <-CORRECT ONE

list(compress_bof(q,';$12')) :
t_compress== (';$12',)
[';$', ';$', ';$', 'foo', ';', 'bar', 'bar', ';', ';', ';', '$', '$', 'foo', ';$12']

list(compress_bug(q,';$12')) :
t_compress== ';$12'
[';$', 'foo', ';', 'bar', 'bar', ';', '$', 'foo', ';$12']   <====== error ====

I obtained the following execution's time:
0.390163274941   generator function with groupby()
0.324547114228   generator function eyquem
0.310176572721   generator function John Machin
['**', '**', 'su', 'foo', '*', 'bar', 'bar', '**', '**', '**', 'su', 'su', '**', 'bin', '*', '*', 'bar', 'bar', 'su', 'su', 'su']
a==b==c is  True
['**', 'su', 'foo', '*', 'bar', 'bar', '**', 'su', 'su', '**', 'bin', '*', '*', 'bar', 'bar', 'su', 'su', 'su']

I prefer the solution of John Machin because there is no instruction B = iter(B) as in mine.
But the instruction previous = _dummy with _dummy = object() appears weird to me. So I finally think the better solution is the following code,  that works even with a string as iterable argument, and in which the first object previous being defined isn't a fake:
def squeeze(iterable, victims):
    if hasattr(iterable, '__iter__') and not hasattr(victims, '__iter__'):
        victims = (victims,)
    for item in iterable:
        previous = item
        break
    for item in iterable:
        if item in victims and item==previous:
            continue
        previous = item
        yield item

.
EDIT 3
I had undesrtood that object() was used as a sentinel.
But I was puzzled by the fact object is CALLED. Yesterday, I was thinking that object is something so peculiar that it is impossible that object  be in any iterable passed as an argument to squeeze(). So, I was wondering why you called it, John Machin, and that sowed doubt in my mind concerning its nature; that's why I asked you a confirmation that object is the super meta-class.
But today, I think I understand why object is called in your code.
In fact, it is quite possible that object be in an iterable, why not ? Super meta-class object is an object, so nothing prevents it to have been put in the iterable before a de-duplication is processed on the iterable, who knows ? Then using object itself as a sentinel is incorrect practice.
.
So you didn't use object but an instance object() as a sentinel.
But I wondered why to choose this mysterious thing that the return of a call to object is ?
My reflections went on about this point and I remarked something that must be the reason of this call:
calling object creates an instance , since object is the most base class in Python, and each time an instance is created, it is a different object from any prior created instance, with a value always different from the value of any prior object's instance:
a = object()
b = object()
c = object()
d = object()

print id(a),'\n',id(b),'\n',id(c),'\n',id(d)

print a==b,a==c,a==d
print b==c,b==d,c==d

result
10818752
10818760
10818768
10818776
False False False
False False False

So it is sure that  _dummy=object()  is a unique object, having a unique id and a unique value. By the way , I wonder what is the value of an object's instance. Anyway the following code shows the problem with _dummy=object  and the absence of problem with _dummy=object()
def imperfect_squeeze(iterable, victim, _dummy=object):
    previous = _dummy
    print 'id(previous)   ==',id(previous)
    print 'id(iterable[0])==',id(iterable[0])
    for item in iterable:
        if item in victim and item==previous:  continue
        previous = item; yield item

def squeeze(iterable, victim, _dummy=object()):
    previous = _dummy
    print 'id(previous)   ==',id(previous)
    print 'id(iterable[0])==',id(iterable[0])
    for item in iterable:
        if item in victim and item==previous:  continue
        previous = item; yield item

wat = object
li = [wat,'**','**','foo',wat,wat]
print 'imperfect_squeeze\n''li before ==',li
print map(id,li)
li = list(imperfect_squeeze(li,[wat,'**']))
print 'li after  ==',li
print

wat = object()
li = [wat,'**','**','foo',wat,wat]
print 'squeeze\n''li before ==',li
print map(id,li)
li = list(squeeze(li,[wat,'**']))
print 'li after  ==',li
print

li = [object(),'**','**','foo',object(),object()]
print 'squeeze\n''li before ==',li
print map(id,li)
li = list(squeeze(li,[li[0],'**']))
print 'li after  ==',li

result
imperfect_squeeze
li before == [<type 'object'>, '**', '**', 'foo', <type 'object'>, <type 'object'>]
[505317320, 18578968, 18578968, 13208848, 505317320, 505317320]
id(previous)   == 505317320
id(iterable[0])== 505317320
li after  == ['**', 'foo', <type 'object'>]

squeeze
li before == [<object object at 0x00A514C8>, '**', '**', 'foo', <object object at 0x00A514C8>, <object object at 0x00A514C8>]
[10818760, 18578968, 18578968, 13208848, 10818760, 10818760]
id(previous)   == 10818752
id(iterable[0])== 10818760
li after  == [<object object at 0x00A514C8>, '**', 'foo', <object object at 0x00A514C8>]

squeeze
li before == [<object object at 0x00A514D0>, '**', '**', 'foo', <object object at 0x00A514D8>, <object object at 0x00A514E0>]
[10818768, 18578968, 18578968, 13208848, 10818776, 10818784]
id(previous)   == 10818752
id(iterable[0])== 10818768
li after  == [<object object at 0x00A514D0>, '**', 'foo', <object object at 0x00A514D8>, <object object at 0x00A514E0>]

The problem is consisting in the absence of <type 'object'>   as first element of the list after treatment by imperfect_squeeze() .
However, we must note that the "problem" is possible only with a list whose FIRST element is object: that's a lot of reflections about such a tiny probability.... but a rigorous coder takes account of all.
If we resort to list, instead of object , the results are different:
def imperfect_sqlize(iterable, victim, _dummy=list):
    previous = _dummy
    print 'id(previous)   ==',id(previous)
    print 'id(iterable[0])==',id(iterable[0])
    for item in iterable:
        if item in victim and item==previous:  continue
        previous = item; yield item

def sqlize(iterable, victim, _dummy=list()):
    previous = _dummy
    print 'id(previous)   ==',id(previous)
    print 'id(iterable[0])==',id(iterable[0])
    for item in iterable:
        if item in victim and item==previous:  continue
        previous = item; yield item

wat = list
li = [wat,'**','**','foo',wat,wat]
print 'imperfect_sqlize\n''li before ==',li
print map(id,li)
li = list(imperfect_sqlize(li,[wat,'**']))
print 'li after  ==',li
print

wat = list()
li = [wat,'**','**','foo',wat,wat]
print 'sqlize\n''li before ==',li
print map(id,li)
li = list(sqlize(li,[wat,'**']))
print 'li after  ==',li
print

li = [list(),'**','**','foo',list(),list()]
print 'sqlize\n''li before ==',li
print map(id,li)
li = list(sqlize(li,[li[0],'**']))
print 'li after  ==',li

result
imperfect_sqlize
li before == [<type 'list'>, '**', '**', 'foo', <type 'list'>, <type 'list'>]
[505343304, 18578968, 18578968, 13208848, 505343304, 505343304]
id(previous)   == 505343304
id(iterable[0])== 505343304
li after  == ['**', 'foo', <type 'list'>]

sqlize
li before == [[], '**', '**', 'foo', [], []]
[18734936, 18578968, 18578968, 13208848, 18734936, 18734936]
id(previous)   == 18734656
id(iterable[0])== 18734936
li after  == ['**', 'foo', []]

sqlize
li before == [[], '**', '**', 'foo', [], []]
[18734696, 18578968, 18578968, 13208848, 18735016, 18734816]
id(previous)   == 18734656
id(iterable[0])== 18734696
li after  == ['**', 'foo', []]

Is there any other object than object in Python that have this peculiarity ?
John Machin, why did you choose an instance of object as a sentinel in your generator function ? Did you already know the above peculiarity ?

A: A generalised "pythonic" solution that works with any iterable (no backing up, no copying, no indexing, no slicing, doesn't fail if iterable is empty) and any thing-to-squeeze (including None):
>>> test = ['**', 'foo', '*', 'bar', 'bar', '**', '**', '**', 'baz', '**', '**',
...      'foo', '*','*', 'bar', 'bar','bar', '**', '**','foo','bar',]
>>>
>>> def squeeze(iterable, victim, _dummy=object()):
...     previous = _dummy
...     for item in iterable:
...         if item == victim == previous: continue
...         previous = item
...         yield item
...
>>> print test
['**', 'foo', '*', 'bar', 'bar', '**', '**', '**', 'baz', '**', '**', 'foo', '*'
, '*', 'bar', 'bar', 'bar', '**', '**', 'foo', 'bar']
>>> print list(squeeze(test, "**"))
['**', 'foo', '*', 'bar', 'bar', '**', 'baz', '**', 'foo', '*', '*', 'bar', 'bar
', 'bar', '**', 'foo', 'bar']
>>> print list(squeeze(["**"], "**"))
['**']
>>> print list(squeeze(["**", "**"], "**"))
['**']
>>> print list(squeeze([], "**"))
[]
>>>

Update for the edification of @eyquem who stated that victim could not be a sequence (or, presumably a set).
Having a container of victims means that there are two possible semantics:
>>> def squeeze2(iterable, victims, _dummy=object()):
...     previous = _dummy
...     for item in iterable:
...         if item == previous in victims: continue
...         previous = item
...         yield item
...
>>> def squeeze3(iterable, victims, _dummy=object()):
...     previous = _dummy
...     for item in iterable:
...         if item in victims and previous in victims: continue
...         previous = item
...         yield item
...
>>> guff = "c...d..e.f,,,g,,h,i.,.,.,.j"
>>> print "".join(squeeze2(guff, ".,"))
c.d.e.f,g,h,i.,.,.,.j
>>> print "".join(squeeze3(guff, ".,"))
c.d.e.f,g,h,i.j
>>>


text:
Q: jQuery: Scroll to newly appended element? Is there a way to automatically scroll to the bottom of a new element? I saw the scrollTo plugin but it is a few years old. Is there a way to do this with the base jQuery api?

A: More dynamic way by extending @Edgar Villegas Alvarado's solution:
    var htmlObject = $("
sample text
");

    $('#container').append(htmlObject);
    $('body, html').animate({ scrollTop: $(htmlObject).offset().top }, 1000);

A: You could do this:
$('body, html').css("scrollTop", $("#new_element").offset().top);

If you want it 'animated' you could do this
$('body, html').animate({ scrollTop: $("#new_element").offset().top }, 1000);

Hope this helps. Cheers

A: You can use the standard JavaScript scrollTo function, and get the position of the new element with jQuery's offset. Something along the lines of this should get you started:
window.scrollTo(0, $("#newElem").offset().top);

Here is an example showing it working :

var newElem = "

";
$("body").append(newElem);
window.scrollTo(0, $("#newElem").offset().top);

jsfiddle


text:
Q: send whole batch to dlt without retrying i'm using spring kafka and i have a kafka consumer written in java spring boot. My consumer consume batch wise and relevant configuration beans are given below.
@Bean
  public ConsumerFactory<String, Object> consumerFactory() {
    Map<String, Object> config = new HashMap<>();

    // default configs like bootstrap servers, key and value deserializers are here

    config.put(ConsumerConfig.MAX_POLL_RECORDS_CONFIG, "5");
    return new DefaultKafkaConsumerFactory<>(config);
  }

  @Bean
  public ConcurrentKafkaListenerContainerFactory<String, Object> kafkaListenerContainerFactory() {
    ConcurrentKafkaListenerContainerFactory<String, Object> factory =
            new ConcurrentKafkaListenerContainerFactory<>();
    factory.setConsumerFactory(consumerFactory());
    factory.getContainerProperties().setCommitLogLevel(LogIfLevelEnabled.Level.DEBUG);
    factory.setBatchListener(true);
    return factory;
  }

I consume messages and send those messages to an API endpoint. If the api is not available or if the rest template throw an error i want to send the whole batch to a DLT without retrying.
What i want to do is send the whole batch to the DLT without retrying. If we throw BatchListenerFailedException  that specific index number owning message from the batch will send to a DLT. In BatchListenerFailedException we can pass only one integer value as index value and not a list. But what i want is to send the whole batch as it is to a DLT topic without retrying. Is there a way to achieve that?
my spring Kafka version is 2.8.6
Edit
my default error handler is like below
@Bean
  public CommonErrorHandler commonErrorHandler() {

    ExponentialBackOffWithMaxRetries exponentialBackOffWithMaxRetries = new ExponentialBackOffWithMaxRetries(5);
    exponentialBackOffWithMaxRetries.setInitialInterval(my val);
    exponentialBackOffWithMaxRetries.setMultiplier(my val);
    exponentialBackOffWithMaxRetries.setMaxInterval(my val);

    DefaultErrorHandler errorHandler = new DefaultErrorHandler(
            new DeadLetterPublishingRecoverer(kafkaTemplate(),
                    (record, exception) -> new TopicPartition(record.topic() + "-dlt", record.partition())),
            exponentialBackOffWithMaxRetries);
    errorHandler.addNotRetryableExceptions(ParseException.class);
    errorHandler.addNotRetryableExceptions(EventHubNonRetryableException.class);
    return errorHandler;
  }

In my case in used ExponentialBackOffWithMaxRetries instead of FixedBackOff. In my case i have 3 scenarios.
1 - Retry messages and send it to DLT (Throwing any other exception than BatchListenerFailedException)
2 - Send couple of messages from the batch to DLT without retrying (Using BatchListenerFailedException for this)
3 - Send whole batch to the DLT without retrying.
3rd one is the place where i'm struggling. If i send some other exception then it will retry couple of times. (Even if i used FixedBackOff instead of ExponentialBackOffWithMaxRetries )

A: Throw something else other than BatchListenerFailedException; use a DefaultErrorHandler with a DeadLetterPublishingRecoverer with no retries (new FixedBackOff(0L, 0L)).
EDIT
Starting with versions 3.0.0, 2.9.3, 2.8.11, you can configure not retryable exceptions for batch errors.
https://github.com/spring-projects/spring-kafka/issues/2459
See
/**
 * Add exception types to the default list. By default, the following exceptions will
 * not be retried:
 *

 *
{@link DeserializationException}

 *
{@link MessageConversionException}

 *
{@link ConversionException}

 *
{@link MethodArgumentResolutionException}

 *
{@link NoSuchMethodException}

 *
{@link ClassCastException}

 *

 * All others will be retried, unless {@link #defaultFalse()} has been called.
 * @param exceptionTypes the exception types.
 * @see #removeClassification(Class)
 * @see #setClassifications(Map, boolean)
 */
@SafeVarargs
@SuppressWarnings("varargs")
public final void addNotRetryableExceptions(Class<? extends Exception>... exceptionTypes) {
    add(false, exceptionTypes);
    notRetryable(Arrays.stream(exceptionTypes));
}

Note that 2.8.x is now out of OSS support. https://spring.io/projects/spring-kafka#support


text:
Q: How To Set Min API To Certain Receiver/Activity I've created a widget for my application and I am using TextClock to display the time. Problem is, it isn't supported by android API versions lower than Jellybean.
My question is, how can I set a receiver to minimum API 17 in the manifest or something so the widget is not listed to those under API 17?

A: Set the android enabled flag for the widget receiver like below
android:enabled="@bool/widget_enabled"

And set the bool value for widget_enabled in values-r16 and values-r17 to true and false in default values


text:
Q: jQuery Single Page app dynamic divs I have a jQuery Single Page app that works but not the way I want it to.
I have a list of counties that is read from a JSON file (the list can be filtered). When one is chosen, it appears as a hyperlink that links to another "page" with a town from that county (the "page" is actually just a div in the same page). The trouble is I have to manually create the divs beforehand. E.g if there are five items in the JSON file and I want to add one more, I have to manually add an extra div in the page.
It works OK for the counties, I can add extra counties to the JSON and it builds an extra hyperlink but for the "page" it links to I need to create a new div in the html. When I create the divs dynamically (under the inner "each" in the Javascript code) nothing happens when you click on the link as the div does not exist in the html.
Is there a solution to this? (see code below)
HTML (with js):

<!doctype html>

<link rel="stylesheet" href="jquery.mobile-1.4.5/jquery.mobile-1.4.5.css"></script>
    <title>How to Parse a JSON file using jQuery</title>

Menu

                            Towns in Ireland

                            Map of Ireland

JSON file:
{

        "Kerry": {
            "town": "Kenmare"

        },

        "Cork": {
            "town": "Mallow"

        },

        "Limerick": {
           "town": "Charleville"

        },

        "Meath": {
            "town": "Trim"

        },

        "Waterford": {
            "town": "Lismore"

        }

}

A: Using AngularJs you can solve it.
Define js file as below
var app = angular.module('app', []);
app.controller('ctrl', function ($scope) {
var data;
$scope.data =[{
         "name":"Kerry",
        "town": "Kenmare"
    },
    {
        "name":"Cork",
        "town": "Mallow"
    },
    {
       "name":"Limerick",
       "town": "Charleville"

    },
    {
        "name":"Meath",
        "town": "Trim"
    },
    {
        "name":"Waterford",
        "town": "Lismore"
    }] ;
  });

HTML file code :
<!DOCTYPE html>

         {{d.name}} : {{d.town}}

I hope this will help.


text:
Q: Is interaction between ResultSet and ResultSetMetaData one-way? A colleague of mine pulled some code from the web that does something like the following:
ResultSetMetaData rsmd = rs.getMetaData();
while (rs.next()) {
  count = rsmd.getColumnCount();
  validateSame(firstRowCount, count);
}

This implies that the RSMD is maintaining an internal reference to the ResultSet and the column count could vary by row.
It seems intuitive to me that there would be one set of metadata per RS, and I'd like to refactor this code out, but I haven't been able to verify this in the Java documentation or get at it through Google searches.  Could someone please confirm or deny that the metadata is constant?

A: An SQL result set is a table whose structure is defined entirely by the query and the underlying table(s) being queried. It cannot vary row by row. You can refactor this.


text:
Q: Validate API with Authlogic I'm using Authlogic for authentication in my app, using the standard User and UserSession models.  I'm building an API into my app, and I want to authenticate API access with a single access token.  In my app, every User belongs_to a Company, which has_many users.  The API is for access to resources belonging to the company, so I'd like to use one single access token for the whole company.
My initial thought was to add a dummy user to Company that only has permission to access the API, whose single access token the company would then use to grant access to the API.  It doesn't appear that I can set a user's e-mail and password blank with AuthLogic, so this isn't panning out.  My next thought was perhaps I could add acts_as_authentic to the company itself, but I'm not sure how this would work.
I really want to use Authlogic for the solution because it integrates nicely with my ACL, and appears to have the functionallity I'm looking for mostly built in.
Is it possible to have two models that act_as_authentic?  Is there an easier way that I'm not thinking of, built into Authlogic?  Is there a way I can use a dummy user for their API key?  Which way should I do this?

A: The way I do this is:
class Something
  acts_as_authentic do |m|
    # API keys are auto generated (See +regenerate_api_key+.)
    # The password is not used for authentication (its just an api_key lookup), so a dummy field is used
    m.login_field = :api_key
    m.validate_login_field = false
    m.validate_email_field = false
    m.crypted_password_field = :api_key_hash
    m.require_password_confirmation = false
    m.validate_password_field = false
    m.crypto_provider = ApiKeyCrypto
  end
end

class ApiKeyCrypto
  def self.encrypt(*tokens)
    'X'
  end

  def self.matches?(crypted, *tokens)
    crypted == 'X'
  end
end

#application_controller.rb
def current_session
  return @current_session if defined?(@current_session)
  ...
    format.any(*api_formats) do
      @current_session = SomethingSession.find
    end
  end
  @current_session
end
def api_formats
  [:xml, :json]
end

This works great for ActiveResource FYI.

A: Sure, you can have two models acts_as_authentic. Set up the Company with the minimum Authlogic db fields , and use it's single_access_token for API access. Note that your API will not know which User is using the system, just the Company.


text:
Q: create adjacency matrix from a file using python and save output file in a .mat format I have a sample dataset similar to this:
Toyota Camry
Toyota Avalon
Honda Civic
Honda Accord
Volkswagen Passat
Volkswagen Jetta
In this dataset, I need to count how many unique values in the first column and second column. Then for each unique value how many values are connected with column two values. Example- Toyota is connected with Camby and Avalon. I need to create an adjacency m*n matrix where m=number of unique value in the first column and n=number of unique value in the second column. My final output looks like this:
    Camry   Avalon  Civic   Accord  Passat  Jetta

Toyota        1   1   0   0   0   0
Honda         0   0   1   1   0   0
Volkswagen    0   0   0   0   1   1
I need some help on how to solve this by python.

A: I wouldn't call what you want an adjacency matrix. However, the desired structure can be made quite easily (see comments in code):
import pandas
import StringIO
dataset = '''Toyota Camry
Toyota Avalon
Honda Civic
Honda Accord
Volkswagen Passat
Volkswagen Jetta'''
# read the dataset into DataFrame d
d = pandas.read_csv(StringIO.StringIO(dataset), ' ', header=None, names=(0, 1))
# make output DataFrame x with rows from first and columns from second input column
x = pandas.DataFrame(0, index=d[0].unique(), columns=d[1].unique())
# set the existing combinations to 1
for e in d.itertuples(index=False, name=None):
    x.at[e] = 1


text:
Q: What have I missed in jekyll and github pages to make syntax highlighting work? Disclaimer: This is my first ever website project, in order to learn about html, css etc. I probably need a 'for idiots' guide'
I have a jekyll/github pages site here. I have read the jekyll documentation here, which suggests all you need to do is stick the liquid tag in. Which I have, for example here.
Further research has pointed out I need to set up my config file, like this which I have here. I also have a .css I copied from a site called sciviews which is here and I've made a link into the .css to call it here.
However, my page still displays in black on white in code blocks. What have I missed?
EDIT: I believe I've made another error, the source of my syntac .css was (i think) here. Is .scss maybe not compatible with this process as I've implemented it?

A: In your html ( inside the head tag ), you are referencing an incorrect path to "syntax.css"
Change:
<link rel="stylesheet" href="/css/syntax.css" type="text/css">

To:
<link rel="stylesheet" href="/Pokemon_FieldStudies/css/syntax.css" type="text/css">

Edit
Following your edit, it seems the code inside syntax.css is a raw scss file. Such files need to be processed before they could be served to the client.
I suggest you read about SCSS and how to compile it ( A simple google search will yield more than enough tutorials ).
In case you're interested in a shortcut, you can use an online compiler such as http://www.sassmeister.com/ but that will require you to define a value for some of the missing variables defined in the scss file.


text:
Q: vba string max size is there a limit in vba string variable?
Public query As String
query="select * from ......"

i type a query that's very long and at a certain point it just stop, i can't type anything more in the quotes
i tried to copy paste my query from notepad but the query is being split to new line
i tried to print the length it's stop at 1005
len(query)

if there really is a limit in vba string
how should i do a very long string then?

A: From the documentation :

The zero length empty string and all possible character sequences
  using characters from the implementation dependent character set.
  There MAY be an implementation defined limit to the length of such
  sequences but the limit SHOULD be no smaller than (2^16 – 1)
  characters.

So you should be able to have a string length of at least 65535 characters.
However, the editor seems to have some kind of restriction regarding the length of line code, not just strings.
As mentionned, use _ to split a line code.

A: I have had this problem when writing queries as well.  The way around it I found was as follows :-
query = "SELECT * " & _
        "FROM...."

Then when you reach a suitable juncture :-
query = query & "WHERE...."

etc.  I believe the maximum is in inputting to the string in one go, not on the actual overall length.  This solution got me around the problem, so hopefully will aid you.