text:
Q: OS X: Multiple version of python 2.7.X In order to install the Python module hidapi: I installed python 2.7 with home-brew:
brew install python2

I think it installed 2.7.15. Python information:
Users-MacBook-Air:~ user$ python -V
Python 2.7.10
Users-MacBook-Air:~ user$ which python
/usr/bin/python

I believe 2.7.10 was already installed (Apple OEM?).
The OS X command:
pip install hidapi

Indicates:

Requirement already satisfied: hidapi in
  /usr/local/lib/python2.7/site-packages (0.7.99.post21) Requirement
  already satisfied: setuptools>=19.0 in
  /usr/local/lib/python2.7/site-packages (from hidapi) (39.1.0)

Attempts to import HID from the Python command line results in error:
>>> import hid

Traceback (most recent call last):   File "", line 1, in
   ImportError: No module named hid

There may be more than one version of 2.7 installed (2.7.15?).

*

*How can I test if a newer (second Python instance of 2.7.X) was installed today?

*How can I invoke Python 2.7.15 if was installed today?

*How can 2.7.10 be granted visibility to the hid module?

It I can invoke Python 2.7.15 and try to import the hid module, that should inch the troubleshooting process along.
UPDATE
Users-MacBook-Air:~ user$ python2

Python 2.7.15 (default, May  1 2018, 16:44:14)
[GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.42.1)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import hid
>>>

ONLY 2.7.15 has 'hid' visibility: the other two versions return an error.
Users-MacBook-Air:~ user$ python -V
Python 2.7.10
Users-MacBook-Air:~ user$ python2 -V
Python 2.7.15
Users-MacBook-Air:~ user$ python2.7 -V
Python 2.7.10

All pip references lead to the same place:
Users-MacBook-Air:~ user$ pip -V
pip 10.0.1 from /usr/local/lib/python2.7/site-packages/pip (python 2.7)
Users-MacBook-Air:~ user$ pip2 -V
pip 10.0.1 from /usr/local/lib/python2.7/site-packages/pip (python 2.7)
Users-MacBook-Air:~ user$ pip2.7 -V
pip 10.0.1 from /usr/local/lib/python2.7/site-packages/pip (python 2.7)

A: I think you've figured out the other questions, but

How can 2.7.10 be granted visibility to the hid module

You would need to install it using pip via easy_install however adding libraries into your system Python is usually frowned upon, which is why virtualenv's exist, but, you would need to install that module as well
Besides that, Python3 should generally be used for any new Python development


text:
Q: Route 53 redirects to URL even after deleting the Hosted Zone and Record Sets? I had the static IP of my EC2 instance pointing to a domain (xyz.com), 5 days ago, we wanted to revert back to the standard ec2-....amazonaws.com url and not use the domain (xyz.com). I deleted the Hosted Zone and Record Sets 5 days ago.
Today when I go to the ec2-...amazonaws.com url, it redirects me to the domain (xyz.com)
I even disassociated the static IP and assigned a new IP to the EC2 instance, no change, still redirects to xyz.com
Can someone tell me what I am doing wrong/missing?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Delphi VirtualStringTree - Check for Duplicates? Yeah, I know I post a lot of questions, but thats because I either need assurance that I am doing it right, what I am doing wrong, or if I am totally clueless, and cant find anything in the documentation. Anyways,
I am trying to check for duplicate nodes. Here is how I would want to do it:
Loop thru my nodes, and compare each single node's text (record), but if I got many nodes, wouldnt that be too time and memory consuming? Would there be a better approach for this?
Thanks!
- Jeff.
EDIT: Thanks to Deltics, I got it working! In case we have some people with the same question, here is some working code, using 2 levels of nodes in VST!
Procedure UncheckDuplicates;
Var
 ParentNode,ChildNode : PVirtualNode;
 I,J                  : Integer;
 SL                   : TStringList;
 SkypeID              : String;
Begin

   SL := TStringlist.Create;
   try
        ParentNode                      := frmMain.vtSkype.GetFirst;

           for I := 0 to frmMain.vtSkype.RootNodeCount - 1 do
             begin
               ChildNode                := ParentNode.FirstChild;
                 for J := 0 to ParentNode.ChildCount - 1 do
                     begin
                        if NodeIsChecked(ChildNode) then
                          begin
                            SkypeID             := GetData(ChildNode).SkypeID;
                              if SL.IndexOf(SkypeID) <> -1 then
                                begin
                                  ChildNode.CheckState          := csUncheckedNormal;
                                end
                                else
                                begin
                                  SL.Add(SkypeID);
                                end;
                          end;
                     ChildNode                := ChildNode.NextSibling;
                     end;

               ParentNode               := ParentNode.NextSibling;
             end;

   finally
     SL.Free;
   end;

frmMain.vtSkype.Refresh;

End;

I am not afraid to share my code, I owe it to the community. :)

A: Normally you'd collect all your strings into a list and then sort it. You can then loop through and check adjacent items for equality.
That's O(n log n) assuming a reasonable sort algorithm as opposed to the naive algorithm which is O(n^2). If you don't have loads of items then the naive will work perfectly well though.

A: David's version will work.  If you have D2010 or later, you could also use a Set collection from DeHL, which uses a hash to check for duplicates and can process your list in O(n) time.

A: It depends at what point you are checking for duplicates.
If it is at the point at which you are adding items and you are adding all items at the same time, (or if it is possible/appropriate to move you duplicate check to point at which the treeview is populated, rather than working with an already populated tree) then maintaining a list of already added items as you go could be the simplest way, e.g. assuming you are adding items from a simple stringlist (in strings in this illustration code):
  alreadyAdded := TStringList.Create;
  try
    alreadyAdded.Sorted := TRUE;  // Sorting ensures an efficient binary lookup for IndexOf()...

    for i := 0 to Pred(strings.count) do
    begin
      if alreadyAdded.IndexOf(strings[i]) <> -1 then
        CONTINUE;

      AddNode(strings[i]);
      alreadyAdded.Add(strings[i]);
    end;
  finally
    alreadyAdded.Free;
  end;


text:
Q: Dúvida Flutter: ListView dados duplicados Bom dia!
Alguém poderia me auxiliar em uma dúvida?

*

*O que estou fazendo:
Fiz um search para o usuário pesquisar por uma Infração no app, e logo após a ação no teclado eu redireciono ele para outra página (FiltroInicioView) passando os dados como parâmetro.
    onFieldSubmitted: (string) {
      print(filterNomeInfracao);
      Navigator.of(context).push(
        MaterialPageRoute(
          builder: (context) => FiltroinicioView(filterNomeInfracao),
        ),
      );
    },

Após, redirecionar o usuário para a pagina de View da infração pesquisada,
Eu mostro a Lista das Infrações dentro de um ListView.Builder,
passando um return na lista() e passando o filterNomeInfracao[index] (Aqui ele vai me trazer todos os dados), e passando uma String chamada 'INFRAÇÕES'
  body: Column(
    children: <Widget>[
      Expanded(
        child: ListView.builder(
          padding: EdgeInsets.all(10.0),
          itemCount: filterNomeInfracao.length,
          itemBuilder: (BuildContext context, int index) {
            return Lista(
              filterNomeInfracao[index],
              'INFRAÇÕES'
            );
          },
        ),
      ),
    ],
  ),

E em seguida dentro Do BuildContext (Código de cima) eu faço a chamada para renderizar a Lista que no caso seria um card, como está abaixo:
class Lista extends StatelessWidget {
  final Infracao infracao;
  final txtInfracoes;

  Lista(this.infracao, this.txtInfracoes);

  @override
  Widget build(BuildContext context) {
    return Column(
  children:  <Widget>[
    Card(child: ListTile(title: Text(txtInfracoes))),
    Card(
      child: ListTile(
        title: Text(infracao.descricao),
      ),
    ),
  ],
);
}
}

E nisso ele faz a listagem das infrações conforme a imagem do print,
POREM, como podem observar a String "INFRAÇÕES" está repetindo,
ou seja eu precisava que fosse um campo fixo, por exemplo:
INFRAÇÕES
E aqui todas descrições

*

*O RESULTADO ESPERADO SERIA ENTÃO COM A STRING INFRAÇÕES COMO FIXO:
Print(feito no paint) abaixo do resultado esperado:

A: Você está setando o texto "INFRAÇÕES" de forma fixa a cada item da lista... Faça o seguinte:
  body: Column(
    children: <Widget>[
      Container(
        height: 30,
        width: double.infinity,
        child: Text("Infrações")
      ),
      Expanded(
        child: ListView.builder(
          padding: EdgeInsets.all(10.0),
          itemCount: filterNomeInfracao.length,
          itemBuilder: (BuildContext context, int index) {
            return Lista(
              filterNomeInfracao[index]
            );
          },
        ),
      ),
    ],
  ),

class Lista extends StatelessWidget {
  final Infracao infracao;

  Lista(this.infracao);

  @override
  Widget build(BuildContext context) {
    return Column(
  children:  <Widget>[
    Card(
      child: ListTile(
        title: Text(infracao.descricao),
      ),
    ),
  ],
);
}
}

Dessa forma irá funcionar corretamente.
Agora se você quer os itens na grid agrupados por "títulos", ai é outra história que foge da sua pergunta... Mas tu pode utilizar o packge grouped_list


text:
Q: Restful service returns - There was an error checking start element of object of type System.Byte[]. Encountered unexpected character 'ÿ' So I am trying to send an image from the client side to the service.
Service definition looks like this (implementation is nothing fancy and It doesn't reach there so excluding that code):
[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "Image")]
Stream Image(byte [] Image);

The calling client looks like this:
public static byte[] ImageToByte(Image img)
{
    ImageConverter converter = new ImageConverter();
    return (byte[])converter.ConvertTo(img, typeof(byte[]));
}

string uri = "http://localhost:8000/RestfulService/Image";

Bitmap img = new Bitmap("Random.jpg");
byte[] byteArray = ImageToByte(img);

var request = WebRequest.Create(uri) as HttpWebRequest;

if (request != null)
{
    request.ContentType = "application/json";
    request.Method = "POST";
}

if (request.Method == "POST")
{
    request.ContentLength = byteArray.Length;
    Stream postStream = request.GetRequestStream();
    postStream.Write(byteArray, 0, byteArray.Length);
    postStream.Close();
}

if (request != null)
{
    var response = request.GetResponse() as HttpWebResponse;

It throws an exception at the last line with

The remote server returned an error: (400) Bad Request.

I've tried all possible things I can think of for:

request.ContentType

A: Where I am doing something similar (posting a raw file) I accept the input as a Stream (not byte[]).
Also I would expect the content type of the request to be application/octet-stream although "application/json; charset=utf-8" would probably work.
When I was testing this, using Stream as the input parameter type or return value of the WebInvoke method was the trick to get the raw body of the request / response.


text:
Q: How to Request Direct Sponsored Content Poster Role in Linkedin API? I am getting a 404 Error when I try to make the GET request to make a member a Direct Sponsored Content Poster Role on an Organization.
So following the sample here, I am using the organization ID and I am using the person that I want to add ID to the URL request. So my code looks like this:
    sendRequest(GET, "https://api.linkedin.com/v2/organizationAcls/" + URLEncoder.encode("(organization:urn:li:organization:" + organization + ",role:DIRECT_SPONSORED_CONTENT_POSTER,roleAssignee:urn:li:person:" + roleAssignee +")" , StandardCharsets.UTF_8.toString()), null);

With the sendRequest method:
    public String sendRequest(String method, String url, String parameters) throws ExternalApiException, IOException{
    URL obj = new URL(url);
    HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

    // add request header
    con.setRequestMethod(method);

    con.setRequestProperty("Authorization", "Bearer " + token);
    if (method == POST)
        //Removed POST logic as its irrelevant
    int responseCode = con.getResponseCode();

    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();

    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    in.close();

    return response.toString();
}

Lastly, an example of the URL post-encodement is as follows, with organization = 1234567 AND roleAssignee = abcDEfg:
https://api.linkedin.com/v2/organizationAcls/%28organization%3Aurn%3Ali%3Aorganization%3A1234567%2Crole%3ADIRECT_SPONSORED_CONTENT_POSTER%2CroleAssignee%3Aurn%3Ali%3Aperson%3AabcDEfg%29
Update 1 (11/10/2020): Wanted to add the response body that was returned as well. As mentioned the error code is 404 and the response body returned was:
{"serviceErrorCode":0,"message":"Resource organizationAcls does not exist","status":404}

A: So I spoke with a Linkedin Technical Support member and it appears there is an error in their documentation.
The correct call requires a PUT request.
Additionally, the URL for the request is: https://api.linkedin.com/v2/organizationAcls/(organization:urn%3Ali%3Aorganization%3AXXXXXXX,role:DIRECT_SPONSORED_CONTENT_POSTER,roleAssignee:urn%3Ali%3Aperson%3AXXXXXXX).
Where the 'XXXXXXX' needs to be the associated organization id and the associated person id.
Lastly, as part of the request, a request body needs to be passed in. The request body is a JsonObject that contains the following properties.

*

*state

*role

*roleAssignee

*organization
For state, the only possible value is REQUESTED.
For role, the only possible value is DIRECT_SPONSORED_CONTENT_POSTER.
For role assignee,  it is "urn:li:person:" + roleAssignee, the id of the user you wish to use add to the below organization.
Lastly, for the organization, it is "urn:li:organization:" + organization, the id of organization you wish to add the above user to.


text:
Q: Trouble having SDL_TTF and OPENGL work together For a game I'm working on, I'm hoping to use OpenGL for a lot of the graphics and SDL_TTF for the text. I can get both to work but not at the same time. Here's my code (based off Lazy Foo):
#include "SDL/SDL.h"
#include "SDL/SDL_ttf.h"
#include "GL/gl.h"

const bool useOpenGl = true;

//The surfaces
SDL_Surface *message = NULL;
SDL_Surface *screen = NULL;

//The event structure
SDL_Event event;

//The font that's going to be used
TTF_Font *font = NULL;

//The color of the font
SDL_Color textColor = {255, 255, 255};

void apply_surface(int x, int y, SDL_Surface* source, SDL_Surface* destination, SDL_Rect* clip = NULL)
{
    //Holds offsets
    SDL_Rect offset;

    //Get offsets
    offset.x = x;
    offset.y = y;

    //Blit
    SDL_BlitSurface(source, clip, destination, &offset);
}

bool init()
{
    SDL_Init (SDL_INIT_EVERYTHING);
    if (useOpenGl)
    {
        screen = SDL_SetVideoMode (1280, 720, 32, SDL_SWSURFACE | SDL_OPENGL); //With SDL_OPENGL flag only opengl is sceen, without only text is
    } else {
        screen = SDL_SetVideoMode (1280, 720, 32, SDL_SWSURFACE);
    }

    TTF_Init();

    SDL_WM_SetCaption ("TTF Not Working With OpenGL", NULL);

    if (useOpenGl)
    {
        glClearColor(1.0, 0.0, 0.0, 0.0);
        glMatrixMode(GL_PROJECTION);
        glLoadIdentity();
        glOrtho(0.0, screen->w, screen->h, 1.0, -1.0, 1.0);
        glEnable(GL_BLEND);
        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    }

    return true;
}

bool load_files()
{
    font = TTF_OpenFont ("arial.ttf", 28);

    return true;
}

void clean_up()
{
    SDL_FreeSurface (message);

    TTF_CloseFont (font);
    TTF_Quit();

    SDL_Quit();
}

int main(int argc, char* args[])
{
    //Quit flag
    bool quit = false;

    init();
    load_files();

    if (useOpenGl)
    {
        glClear(GL_COLOR_BUFFER_BIT); //clearing the screen
        glPushMatrix();

        glBegin(GL_QUADS);
        glColor3f(1.0, 0.0, 0.0);
        glVertex2f(0, 0);
        glColor3f(0.0, 1.0, 0.0);
        glVertex2f(1280, 0);
        glColor3f(0.0, 0.0, 1.0);
        glVertex2f(1280, 720);
        glColor4f(0.5, 0.5, 1.0, 0.1);
        glVertex2f(0, 720);
        glEnd();

        glPopMatrix();
        glFlush();
    }

    //Render the text
    message = TTF_RenderText_Solid (font, "The quick brown fox jumps over the lazy dog", textColor);

    //Apply the images to the screen
    apply_surface (0, 150, message, screen);

    //I'm guessing this is where the problem is coming from
    SDL_GL_SwapBuffers();
    SDL_Flip (screen);

    while (quit == false)
    {
        while (SDL_PollEvent (&event))
        {
            if (event.type == SDL_QUIT)
            {
                quit = true;
            }
        }
    }

    clean_up();

    return 0;
}

If the variable useOpenGl is set to false the program will only use SDL_TTF, if it's set to true it will use both SDL_TTF and OpenGL.
From playing around with it the problem seems to be with whether or not I use the "SDL_OPENGL" flag when creating the window.

A: SDL_TTF uses software rendering and is not compatible with OpenGL mode.
You might have to look for another library such as FTGL or freetype-gl.


text:
Q: Return a random case from an enum in Swift I just wrote a function that generates a random integer in a range of 0...2. The goal is to return a random case from an enum based on the random integer.
I'd like to prefer to use the case statement but I don't like the default case which returns an arbitrary enum. Omitting the default case will not work since switch is not able to know how much cases will occur. Even though the default case would never happen I don't consider this to be a clean solution.
Which solution would you prefer respectively consider to be the cleanest solution - please elaborate. Is there a better/more elegant way to return a random case from an enum?
If-else solution:
    func generateRandomSign() -> Sign {
        let randomSelection = Int.random(in: 0...2)

        if randomSelection == 0 {
            return .rock
        } else if randomSelection == 1 {
            return .paper
        }
        return .scissor
    }

Switch solution:
    func generateRandomSign() -> Sign {
        let randomSelection = Int.random(in: 0...2)

        switch randomSelection {
        case 0: return .rock
        case 1: return .paper
        case 2: return .scissor
        default: return .rock
        }
    }

A: There's no need for messing around with Ints. You should rather declare your Sign enum to conform to CaseIterable and call randomElement() on its allCases property (which as its name suggests, contains all cases of the enum).
This way you don't sacrifice type safety and you're guaranteed to get back a case of Sign every time.
enum Sign: CaseIterable {
    case rock
    case paper
    case scissor

    static func random() -> Sign {
        return allCases.randomElement()! // safe to force unwrap, since the enum has at least 1 property, so this can never be `nil`
    }
}

You can call it like let randomSign = Sign.random()


text:
Q: How to Get Mysql Field Data I have a registration system , username, password, email id are stored in a table, how can i export or get all email ids of all my registered users in Phpmyadmin itself (or any other way).

A: Run query
select email_id from users

Then use export feature of phpmyadmin.After you run the query, click the export link and you can export the query result in many different formats (e.g CSV, Excel, Word...)
Please change table and column names according to you.

A: try this>>
$sql = "select email_id from table_name";
$result = mysql_query($sql);

$email_collector = array();

while( $row = mysql_fetch_assoc($result) ){
  //store email in array
  $email_collector[] = $row['email_id'];
}

print_r($email_collector);

Change email_id and table_name according to your database

A: If you want to get list of users and their email in a text file try the below query
SELECT username, email INTO OUTFILE 'data.txt'
  FIELDS TERMINATED BY ','
  LINES TERMINATED BY '\n'
  FROM table2;


text:
Q: How can I apply "this" context inside method's function? (Javascript) Since I'm passing a function to another class method as a callback, I need to apply my function's this value as itself. I know there is some way using bind,call,apply but I want to set function's "this" value inside the function. Is there any way?
function CallBack(){
    this.setValue(...whatever);
    this.somekindofMethods(...whatever);
    !!Can I set "this" inside the function??
}


text:
Q: Converting array/matrix initialization code from C++ to C# I am in the middle of converting C++ code to C#. I am having trouble with some C++ array static initialization. Consider the following piece of C++:
int Values[][32] = {
   {}, {}, {1, 2, 3}, {1}
};

What this does is creates a matrix of 4x32 integers. I need to do same or similar in C# in as straightforward way as possible. I am looking to get either
static int[][] Values = {...};

...or
static int[,] Values = {...};

The thing is C# does not seem to allow array initialization with uneven sub-array sizes. Other than this, if one specifies new int[4,32] {...} then everything between curly braces must be of exactly 32 length. With C++ one can specify {1, 2, 3} and the compiler will fill in the rest of the missing array members with zeros.
[EDIT] I have tried using LINQ and got what I desire but it looks cumbersome.

A: In C# the size of your array initializer must match the declared size of the array. You do not need to declare the size if you would like to avoid duplication.
If you need all entries to be of the same size, you can do it with a little helper function Expand, like this:
static int[] Expand(int[] src, int size) {
    var res = new int[size];
    Array.Copy(src, res, src.Length);
    return res;
}

static int[][] Values = new int[4][] {
    Expand(new[] {1}, 32)
,   Expand(new[] {1,2,3}, 32)
,   Expand(new[] {1,2,3}, 32)
,   Expand(new[] {1,2,3, 4, 5}, 32)
};

A: I deleted my previous answer and am adding another (less eloquent) one that should work.
// utility function you can put in a class
static int[] BuildArray32(params int[] values)
{
    int[] retVal = new int[32];
    Array.Copy(values, retVal, values.Length);
    return retVal;
}

// array initializer code
int[][] Values = {
    BuildArray32(),
    BuildArray32(),
    BuildArray32(1, 2, 3),
    BuildArray32(1),
};

EDIT Or you could make a builder class :)
class MatrixBuilder
{
    int width;
    List<int[]> rows;

    public MatrixBuilder(int width)
    {
        this.width = width;
        this.rows = new List<int[]>();
    }

    public MatrixBuilder Add(params int[] row)
    {
        int[] wideRow = new int[width];
        Array.Copy(row, wideRow, row.Length);
        rows.Add(wideRow);
        return this;
    }

    public int[][] ToMatrix()
    {
        return rows.ToArray();
    }
}

int[][] Values2 = new MatrixBuilder(32)
    .Add()
    .Add()
    .Add(1, 2, 3)
    .Add(1)
    .ToMatrix();

A: You can't do it in c#. you can either initialise the arrays all to zeros, then apply your known initial values afterwards:
        int[][] initAll = new []
                               {
                                   new int[32] ,
                                   new int[32] ,
                                   new int[32] ,
                                   new int[32]
                               };

or initialize a jagged array:
int[][] initJagged = new[]
                               {
                                   new[] {1, 3, 5, 7, 9},
                                   new[] {1, 3, },
                                   new[] {1, 3,0,0,0,0,},
                                   new int[32]
                               };


text:
Q: How to add unityplayer as subview in android layout? Iam trying to add unityview as subview in android layout.
I create relative layout in android xml file and added unityview to relativelayout.
But the unityview is appearing as small image at left bottom of relative layout.
The black portion is my relativelayout but unity view not occupying enter relative layout.
The code is as follows:
  public class MainActivity extends UnityPlayerActivity {

            public static Context mContext;
            private Handler handler=new Handler();
            private UnityPlayer m_UnityPlayer;

            @Override
                protected void onCreate(Bundle bundle) {
                    super.onCreate(bundle);

                            mContext = this;
                            m_UnityPlayer = new UnityPlayer(this);

                            int glesMode = m_UnityPlayer.getSettings().getInt("gles_mode", 1);

                            boolean trueColor8888 = false;

                            m_UnityPlayer.init(glesMode, trueColor8888);

                            setContentView(R.layout.activity_main);

                            //This is my relative layout
                            RelativeLayout layout = (RelativeLayout) findViewById(R.id.relativelayout2);
//Relativelayout width is 750dp and height is 640dp.

                            LayoutParams lp = new LayoutParams (750, 640);

//Iam adding unityview to layout here

                            layout.addView(m_UnityPlayer.getView(), 0, lp);

            }
            }

A: Finally  I got the solution.

*

*MainActivity should be extend as Activity, not UnityPlayerActivity.

*Add these two lines to activity in android manifest

<meta-data android:name="unityplayer.UnityActivity" android:value="true" />
<meta-data android:name="unityplayer.ForwardNativeEventsToDalvik" android:value="false" />

The working code is:
    public class MainActivity extends Activity implements OnTouchListener {
        public static Context mContext;
        private Handler handler=new Handler();
        protected UnityPlayer mUnityPlayer;

        protected void onCreate(Bundle savedInstanceState) {

        requestWindowFeature(Window.FEATURE_NO_TITLE);
                super.onCreate(savedInstanceState);
                mContext = this;
                    getWindow().takeSurface(null);
                setTheme(android.R.style.Theme_NoTitleBar_Fullscreen);
                getWindow().setFormat(PixelFormat.RGB_565);

                mUnityPlayer = new UnityPlayer(this);
                if (mUnityPlayer.getSettings ().getBoolean ("hide_status_bar", true))
                    getWindow ().setFlags (WindowManager.LayoutParams.FLAG_FULLSCREEN,
                                           WindowManager.LayoutParams.FLAG_FULLSCREEN);

                int glesMode = mUnityPlayer.getSettings().getInt("gles_mode", 1);
                boolean trueColor8888 = false;
                mUnityPlayer.init(glesMode, trueColor8888);

                View playerView = mUnityPlayer.getView();

                setContentView(R.layout.activity_main);

                FrameLayout layout = (FrameLayout) findViewById(R.id.frameLayout2);

                LayoutParams lp = new LayoutParams (750, 630);

                layout.addView(playerView, 0, lp);

    }

    protected void onDestroy ()
    {
        mUnityPlayer.quit();
        super.onDestroy();
    }

    // onPause()/onResume() must be sent to UnityPlayer to enable pause and resource recreation on resume.
    protected void onPause()
    {
        super.onPause();
        mUnityPlayer.pause();
    }
    protected void onResume()
    {
        super.onResume();
        mUnityPlayer.resume();
    }
    public void onConfigurationChanged(Configuration newConfig)
    {
        super.onConfigurationChanged(newConfig);
        mUnityPlayer.configurationChanged(newConfig);
    }
    public void onWindowFocusChanged(boolean hasFocus)
    {
        super.onWindowFocusChanged(hasFocus);
        mUnityPlayer.windowFocusChanged(hasFocus);
    }
    public boolean dispatchKeyEvent(KeyEvent event)
    {
        if (event.getAction() == KeyEvent.ACTION_MULTIPLE)
            return mUnityPlayer.onKeyMultiple(event.getKeyCode(), event.getRepeatCount(), event);
        return super.dispatchKeyEvent(event);
    }

}

The result:


text:
Q: no pg_hba.conf for entry postgres remote connection error when catch all mask in pg_hba.conf Getting the following error while trying to connect to postgres remotely...
FATAL:  no pg_hba.conf entry for host "109.153.58.128", user "colemans", database "colemanbros", SSL off

But the pg_hba.conf I have contains the following
host    colemans        colemanbros     0.0.0.0/0       md5
host    colemans        colemans        0.0.0.0/0       md5

Both are valid users and the database is correct. Why is it failing?
The IP mask of 0.0.0.0/0 should catch all incoming connections, right?
Or am I doing something wrong?
PS: the postgresql.conf file is set to listen on '*'

A: According to the official Postgres document the order of your entries is wrong. It should be like:
host    database        user            address         auth-method  [auth-options]

In your case(based on your error):
host    colemanbros     colemans        0.0.0.0/0       md5


text:
Q: I am getting invalid string like android.support.v7.widget.AppCompatEditText while getting edittext value Here is my java fragment code
    public class A_AssignExam extends android.support.v4.app.Fragment {
        EditText username;

        @Override
        public void onActivityCreated(Bundle savedInstanceState) {
            super.onActivityCreated(savedInstanceState);
            username=(EditText)view.findViewById(R.id.usernameeditassignexam);
            Log.d("Username------>", ""+username);
    }

I get the following error message
android.support.v7.widget.AppCompatEditText {52750c5c VFED..CL ......I. 0,0-0,0 #7f0d00d8 app:id/usernameeditassignexam}
org.veetech.veeknowintern D/Username------>: android.support.v7.widget.AppCompatEditText {52750c5c VFED..CL ......I. 0,0-0,0 #7f0d00d8 app:id/usernameeditassignexam}
org.veetech.veeknowintern D/Username------>: android.support.v7.widget.AppCompatEditText {52750c5c VFED..CL .F. ..... 152,0-572,90 #7f0d00d8 app:id/usernameeditassignexam}

A: You are printing the class/instance as returned by toString by default instead you need to do
Log.d("Username------>", username.getText().toString());

If you don't already know - the same problem is why you are having to do "" + -  This is because if you did Log.d(TAG, username); it would tell you the signature does not match - it does not know what to do with this Object 'EditText'. By concatenating it with an emtpy string you're saying treat this object as a string too, so Java casts it by calling the toString method of the object. In the future you'll be able recognise this as a signal you're using the object by accident instead of its value

A: You should use
Log.d("Username------>", username.getText().toString());

.toString() is needed when you want a String.
Because .getText() returns CharSequence.


text:
Q: django alternative to tiny tiny rss I love the idea behind tiny-tiny rss: it's lightweight, open-source, frequently updated, and seems to work very well.  Furthermore, the client only needs a browser. I want to play around with the source code and customize it a bit, but I don't know PHP.  I was wondering, are there any django or python projects like tiny tiny rss?  I'm looking for a reader where the client only needs a web browser.

A: Newsblur (https://github.com/samuelclay/NewsBlur) seems to be an appropriate choice: server side is based on python with django, celery and pymongo. MIT license.


text:
Q: Make Django MEDIA_URL arbitrary? I have a server that I would like to be accessible from many different addresses:
192.168.1.101
mh00h.com (via dd-wrt router)
192.168.100.101 (ip of dd-wrt router, port forwarded to server)

If the server is accessed from the 192.168.100.x network, how can I make Django's MEDIA_URL arbitrary such that a PC accessing any of these subnets will be able to access the /media directory?
The server runs gunicorn, django, and nginx.

A: One way using the socket lib:
import socket

if socket.gethostname() == 'mh00h.com':
    MEDIA_URL = 'foo'
else:
    MEDIA_URL = 'bar'

Edit:
I think I misunderstood your question, just write a middleware layer that does your switch logic, or configure nginx if you know all the ip cases beforehand. Btw what is the actual problem you're trying to tackle?


text:
Q: Knockout JS passing value into function I have read many similar topics, but none of the answers seems to work for my case. I am working with Google Maps API to implement show/hide markers function using knockout data-binding. With show markers, there are no problems. But since I have to pass markers variable into hideMarkers function, I can't get this going.
Here is the html:

   <input id="hide-listings" type="button" value="Hide Listings" class="btn1 btn-primary text-center" data-bind="click: hideMarkers">

Here is my ViewModel:
function viewModel() {
    var self = this;
    self.places = ko.observableArray(locations);
    self.address = ko.observable();
    self.city = ko.observable();
    self.title = ko.observable();
    self.id = ko.observable();
    this.markers = ko.observable();
    this.zaddress = ko.observable();
    this.taddress = ko.observable();
    this.paddress = ko.observable();
    this.filter = ko.observable();
    this.visiblePlaces = ko.computed(function() {
        return this.places().filter(function(place) {
            if (!self.filter() || place.title.toLowerCase().indexOf(self.filter().toLowerCase()) !== -1)
                return place;
        });
    }, this);
    //Zooms to a selected marker, open infowindow and displays current weather
    self.zoomToPlace = function() {
        // Initialize the geocoder.
        var geocoder = new google.maps.Geocoder();
        // Get the place.
        var address = this.address;
        var id = this.id;
        var city = this.city;
        var weatherAPIXU = "http://api.apixu.com/v1/current.json?key=453477e8eec14cbc805210143171706&q=" + city;
        $.getJSON(weatherAPIXU, function(data) {
            var forecast = data.current.temp_c;
            $(".weather").html(forecast + '° C');
        });
        // Geocode the address/area entered to get the center. Then, center the map on it and zoom in
        geocoder.geocode({
            address: address,
        }, function(results, status) {
            map.setCenter(results[0].geometry.location);
            map.setZoom(15);
            google.maps.event.trigger(markers[id], 'click');
        });
    };
    self.showListings = function() {
        var bounds = new google.maps.LatLngBounds();
        // Extend the boundaries of the map for each marker and display the marker
        for (var i = 0; i < markers.length; i++) {
            markers[i].setMap(map);
            bounds.extend(markers[i].position);
        }
        map.fitBounds(bounds);
    };
    // This function takes the input value in the find nearby area text input
    // locates it, and then zooms into that area. This is so that the user can
    // show all listings, then decide to focus on one area of the map.
    self.zoomToArea = function() {
        // Initialize the geocoder.
        var geocoder = new google.maps.Geocoder();
        // Get the address or place that the user entered.
        var zaddress = this.zaddress();
        // Make sure the address isn't blank.
        if (zaddress === '') {
            window.alert('You must enter an area, or address.');
        } else {
            // Geocode the address/area entered to get the center. Then, center the map on it and zoom in
            geocoder.geocode({
                address: zaddress,
            }, function(results, status) {
                if (status == google.maps.GeocoderStatus.OK) {
                    map.setCenter(results[0].geometry.location);
                    map.setZoom(15);
                } else {
                    window.alert(
                        'We could not find that location - try entering a more' +
                        ' specific place.');
                }
            });
        }
    };
    // This function allows the user to input a desired travel time, in
    // minutes, and a travel mode, and a location - and only show the listings
    // that are within that travel time (via that travel mode) of the location
    self.searchWithinTime = function() {
        // Initialize the distance matrix service.
        var distanceMatrixService = new google.maps.DistanceMatrixService();
        var taddress = this.taddress();
        // Check to make sure the place entered isn't blank.
        if (taddress === '') {
            window.alert('You must enter an address.');
        } else {
            hideMarkers(markers);
            // Use the distance matrix service to calculate the duration of the
            // routes between all our markers, and the destination address entered
            // by the user. Then put all the origins into an origin matrix.
            var origins = [];
            for (var i = 0; i < markers.length; i++) {
                origins[i] = markers[i].position;
            }
            var destination = taddress;
            var mode = document.getElementById('mode').value;
            // Now that both the origins and destination are defined, get all the
            // info for the distances between them.
            distanceMatrixService.getDistanceMatrix({
                origins: origins,
                destinations: [destination],
                travelMode: google.maps.TravelMode[mode],
                unitSystem: google.maps.UnitSystem.IMPERIAL,
            }, function(response, status) {
                if (status !== google.maps.DistanceMatrixStatus
                    .OK) {
                    window.alert('Error was: ' + status);
                } else {
                    displayMarkersWithinTime(response);
                }
            });
        }
    };
    // This function fires when the user select "go" on the places search.
    // It will do a nearby search using the entered query string or place.
    self.textSearchPlaces = function() {
        var bounds = map.getBounds();
        var place = this.paddress();
        hideMarkers(placeMarkers);
        var placesService = new google.maps.places.PlacesService(map);
        placesService.textSearch({
            query: place,
            bounds: bounds
        }, function(results, status) {
            if (status === google.maps.places.PlacesServiceStatus
                .OK) {
                createMarkersForPlaces(results);
            }
        });
    };
    // This function will loop through the listings and hide them all.
    this.hideMarkers = function(markers) {
        for (var i = 0; i < markers.length; i++) {
            markers[i].setMap(null);
        }
    };
}
ko.applyBindings(new viewModel());

Please, advice me on how to best approach this issue, thank you!

A: If markers is this.markers then you dont need to pass the markers to the function as its available:
this.hideMarkers = function(markers) {
    var m = markers == null ? this.markers : markers;
    for (var i = 0; i < m.length; i++) {
        m[i].setMap(null);
    }
};

This means you can pass markers also to this function and if you dont it will default to your this.markers.
You can pass extra parameters in knockout like this also, if that is all your looking:
<input data-bind="click: hideMarkers.bind($data, markersYouWishtoHide)">

http://knockoutjs.com/documentation/click-binding.html

A: I have figured it out! The problem was that I was passing the value into the function inside the viewModel, but not in my click data-binding! The correct html:

     <input id="hide-listings" type="button" value="Hide Listings" class="btn1 btn-primary text-center" data-bind="click: function() {hideMarkers(markers)}">

And the ViewModel function is simply:
self.hideMarkers = function() {
    for (var i = 0; i < markers.length; i++) {
        markers[i].setMap(null);
    }
};


text:
Q: MySQL in Android I am new to Android Development. I have created an application Which stores the name and age in mysql database.
Now I want to retrieving that name and age from the database and display it in ListView. I tried the HttpPost method for retrieving but I am not able to do that.

A: For an internet server: Try making a wrapper in PHP that gives back XML or JSON as output. Then use a HTTP request to get the XML / JSON output.
For a local persistent storage: Maby check out this Android tutorial.


text:
Q: Regarding elastic search memory usage I am currently using elasticsearch 0.9.19. The machine I am using is having around 300GB disk space and the RAM on it is around 23GB. I have allocated around 10GB of ram to elastic search. My operations are write intensive. They are around 1000docs/s. I am only running elastic search on the machine and no other process. The doc size is not large. They are small only with not more than 10 fields. The elastic search is being run only on one machine with 1 shard and 0 replicas.
The memory used, starts increasing very rapidly when I am sending 1000 docs/s. Though I have allocated 10GB RAM only to elastic search but still almost 21 GB ram gets consumed and eventually the elastic search process results in out of heap space. Later I need to clear the OS cache to free all the memory. Even when I stop sending elastic search, 1000docs/s then also the memory does not get automatically cleared.
So For e.g If I am running elastic search with around 1000doc/s write operations then, I found that it went to 18 GB Ram usage very quickly and later when I reduced my write operations to only 10 docs/s then also the memory used still shows around 18 GB. Which I think should come down with decrease in the number of write operations. I am using Bulk API for performing my write operations with size of 100 docs per query. The data is coming from 4 machines when the write operations are around 1000docs/sec
These are the figures which I am getting after doing top
Mem:  24731664k total, 18252700k used,  6478964k free,   322492k buffers
Swap:  4194296k total,              0k used,  4194296k free,  8749780k cached
PID     USER        PR  NI  VIRT     RES    SHR   S   %CPU  %MEM    TIME+       COMMAND
1004  elastics     20   0   10.7g   8.3g    10m   S    1    35.3   806:28.69      java
Please tell if any one has any idea, what could be the reason for this. I have to stop my application because of this issue. I think I am missing any configuration. I have already read all the cache related documentations for the elastic search over here
http://www.elasticsearch.org/guide/reference/index-modules/cache.html
I have also tried clearing cache using clear cache API and also tried flush api. But didnot got any improvement.
Thanks in advance.

A: To summarize the answer on the mailing list thread: the problem was that the Ruby client wasn't able to throttle its inserts, and Lucene memory usage does grow as large numbers of documents are added.  I think there may also be an issue with commit frequency: it's important to commit from time to time in order to flush newly added documents to disk.  Is the OP still having the problem?  If not, could you post the solution?

A: I think that your ingesting is to heavy for the cluster capacity.
Then data keeps stacked in memory.
You should monitor your disk I/O, it should be the bottleneck.
You should then :

*

*slower the ingestion (you could maybe use a stronger queue like Kafka, rabbit MQ etc..., or use the persisted queue system of logstash)

*use quick SSD hard drive to speed up IO capacity

*add more nodes (and adjust shards of your indices) for a better I/O parallelism

As small optimization, you can improve performance a little by :

*

*increasing the refresh_interval. This action consume RAM, so avoid refreshing when you're in heavy ingesting node could help a lot

*if you are doing a first ingestion in your index, try to remove all replicas in ingesting phase, and re add the replicas after ingestion

A: One more thing to consider is Ram / storage ratio for elastic search should
be. 1:16 For best performance.
That means -  if you use 64 gb ram then storage would be 1024 GB or 1TB .


text:
Q: nodejs modify data during piping from source to destination I have a simple http server that will pipe all data from the req object(source) to res(destination) object. but how can I change output data from source, before writing it to the destionation?
by changing data I mean sth simple like calling toUpperCase() on data.
http.createServer(function(req, res){
    if(req.method.toLowerCase() != 'post')
        res.end() ;
    req.pipe(res) ;
}).listen(9090) ;

A: You could create your own Transform stream like this that sits in between the two streams:
var inherits = require('util').inherits;
var TransformStream = require('stream').Transform;

function UpperStream() {
  TransformStream.call(this);
}
inherits(UpperStream, TransformStream);
UpperStream.prototype._transform = function(chunk, encoding, cb) {
  for (var i = 0; i < chunk.length; ++i) {
    var ch = chunk[i];
    // Check for lowercase character
    if (ch >= 97 && ch <= 122) {
      // Make it uppercase
      chunk[i] &= ~32;
    }
  }
  cb(null, chunk);
};

Then you could just do something like:
http.createServer(function(req, res){
    if(req.method.toLowerCase() != 'post')
        return res.end() ;
    req.pipe(new UpperStream()).pipe(res) ;
}).listen(9090) ;


text:
Q: Use all biblatex fields in bibdesk In the BibDesk wiki (BibDesk Tips and Tricks) there is some information on customizing BibDesk for biblatex, including a link to a TypeInfo file that can be used to create all of the biblatex fields automatically.
The has to be saved as ~/Library/Application Support/BibDesk/TypeInfo.plist.
Im using texmaker, bibDesk under osx 10.9.5. The folder doesn't exist so I created it. Didn't help.
Does anybody know where to copy the "TypeInfo.plist" file?
Alan Munn refers to this in that Question: Bibliography tools that are compatible with biblatex and biber


text:
Q: How to open Android Keyboard in Speaking mode programmatically? I want to open the Android Keyboard in Speaking mode by default programmatically when I focus on editText.

I know android:inputType="voice" is in enhancement, is there
  another way?

I don't want to use SpeechRecognizer because the difference with the one used by default in Android keyboard is that it works offline.


text:
Q: Repeat rows with specific value I would like to repeat rows contain specific values in R with df as below
df <- data.frame(name1 = c("x","y","z"),
                 name2 = c(0,1,2))
df

  name1 name2
1     x     0
2     y     1
3     z     2

My desired output
  name1 name2
1     x     0
2     x     0
3     y     1
4     y     1
5     z     2

I would like to say only rows containing 'x' and 'y' will be repeated one time.
So far, I only came up with the idea of using add_row and replace NA values by the corresponding values. Any sugesstions for this using tidyverse?

A: We could do it this way:
library(dplyr)
df %>%
  filter(name1=="x" | name1=="y") %>%
  bind_rows(df) %>%
  arrange(name1)

  name1 name2
1     x     0
2     x     0
3     y     1
4     y     1
5     z     2

A: We may also do this as
library(dplyr)
library(tidyr)
df %>%
   uncount(1 +(name1 %in% c('x', 'y')))
  name1 name2
1     x     0
2     x     0
3     y     1
4     y     1
5     z     2

A: I just couldn't remember, but I thought there was a shorter way to do this:
df[sort(c(seq_len(nrow(df)), rep(which(df$name1 %in% c("x", "y")), 1))),]

    name1 name2
1       x     0
1.1     x     0
2       y     1
2.1     y     1
3       z     2

A: You can create a new column specifying number of times a row should be repeated and then use uncount to repeat them.
library(dplyr)
library(tidyr)

df %>%
  mutate(repeat_row = ifelse(name1 %in% c('x', 'y'), 2, 1)) %>%
  uncount(repeat_row)

#  name1 name2
#1     x     0
#2     x     0
#3     y     1
#4     y     1
#5     z     2

A: You can do this using tidyr::add_row, but describe what you want to put into the row by using indexing.
library(tidyverse)
df <- data.frame(name1 = c("x","y","z"),
                 name2 = c(0,1,2))
df %>%
  add_row(df[1,], .before = 2) %>%
  add_row(df[2,], .before = 3)


text:
Q: Watching files with Git I use a little script that queries Git for which files have been recently changed and then takes action based on those files.
When the tool is invoked I run git status --porcelain to get a list of files to act upon.
But this breaks down in the following situation:
echo "lorum ipsum" > foo.txt
./tool `git status --porcelain` # tool acts upon foo.txt
git checkout .
./tool `git status --porcelain` # tool doesn't know to act upon foo.txt

Is there a way to ask Git to tell you which tracked file was last altered even if it's no longer altered in the eyes of Git?
Perhaps the files that were last updated since last Git query? Or the files updated in the last hour?

A: The closest I have to propose is what I mentioned in "git status - list last modified date":
IFS=''; git status -s | while read -n2 mode; read -n1; read file; \
  do echo $mode $(stat -c %y "$file") $file; \
done|sort

That allows me to add to the index and group modifications (done since the last commit), from the oldest to the newest.
By focusing on git status output, that avoids checking all the files that haven't changed yet.
On the second call of the pseudo-code from the question, foo.txt wouldn't be concerned.


text:
Q: Problem with loops on Pandas DataFrame Loop enter image description here
I am facing problem in converting DataFrame A to DataFrame B. I have tried using the .transpose() method. However, it did not work. Please help if you can. I cannot share the code, as it is confidential.

A: Please check these functions:

*

*melt

*explode

*stack
Also, converting your df (or parts of it) to dictionary may be useful: to_dict.


text:
Q: VBScript Using Computername to Name a File New to VBScript and having a problem grasping this concept.
This is the code:
Set WshNetwork = WScript.CreateObject("WScript.Network")
strCompName = WshNetwork.Computername
Wscript.Echo WshNetwork.Username >j:\strCompName.txt
WScript.Quit()

Basically I want to the username dumped to a text file and the text file should be named with the name of the computer.  I've tried putting the strCompName in quotes, single quotes, parenthesis with no success.

A: Here is the code that you can use. You need to use FileSystemObject. The FileSystemObject is used to gain access to a computer's file system. It can create new files and access existing ones.
Set WshNetwork = WScript.CreateObject("WScript.Network")
Set objFSO = CreateObject("Scripting.FileSystemObject")

strCompName = WshNetwork.Computername

'writing to file
outFile="c:\TEMP\" & strCompName & ".txt"
Set objFile = objFSO.CreateTextFile(outFile,True)
objFile.Write WshNetwork.Username & vbCrLf
objFile.Close

Set objFile = Nothing
Set objFSO = Nothing
Set WshNetwork = Nothing

WScript.Quit()

Save this in .vbs file and run and you will get a text file with computer name in TEMP folder (Change the path if you like).

A: This code should work. This code opens the file and appends it if the file exists or creates a file and writed to it if it does not exist.
'constants
Const ForReading = 1, ForWriting = 2, ForAppending = 8
Const TristateUseDefault = -2, TristateTrue = -1, TristateFalse = 0

'Load domain, username, & computer variables
Set oShell = CreateObject( "WScript.Shell" )
sDomain = oShell.ExpandEnvironmentStrings( "%USERDOMAIN%" )
sUserName = oShell.ExpandEnvironmentStrings( "%USERNAME%" )
sComputer = oShell.ExpandEnvironmentStrings( "%COMPUTERNAME%" )

'Setup filesystemobject
Set oFSO=CreateObject("Scripting.FileSystemObject")

'Check to see if file exists. If exists open it forAppending
'else create file and write to it.

outFile="c:\export\" & sComputer & ".txt"
If oFSO.FileExists(outFile) Then
    Set objFile = oFSO.OpenTextFile(outFile, ForAppending, True, TristateTrue)
Else
    Set objFile = oFSO.CreateTextFile(outFile,True)
End If

'write to file
objFile.WriteLine sDomain & "\" & sUsername & " - " & Now

'clean up objects
objFile.Close
Set objFile = Nothing
Set oFSO = Nothing
Set oShell = Nothing


text:
Q: Counting Occurrences of Letter Combinations I'm trying to count the number of occurrences of each letter combination in a text file:
'aa', 'ab',...'zy', 'zz'
I have managed to be able to count the occurrence of single letters easily enough using collections.Counter and am just wondering if there is a similar approach for 2 letter combinations.
Thanks

A: If you just want the letters, you can filter the non alphas, you don't need to store any extra data in memory, all you have to do is chain the chars and keep track of the previous char each time:
from collections import Counter
from itertools import chain

with open("in.txt") as f:
    prev = f.read(1)
    c = Counter()
    for ch in filter(str.isalpha, chain.from_iterable(f)):
        c[prev + ch] += 1
        prev = ch
print(c)

If you want all chars just remove the filter:
with open("in.txt") as f:
    prev = f.read(1)
    c = Counter()
    for ch in chain.from_iterable(f):
        c[prev + ch] += 1
        prev = ch
print(c)

A: import collections, itertools

def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = itertools.tee(iterable)
    next(b, None)
    return zip(a, b)

text = "I'm trying to count the number of occurrences of each letter combination in a text file"

counter = collections.Counter(pairwise(text))

The "trick" is to use a generator, like the one I copied from the python documents, to access the letter combinations. It can be extended naturally to three or more letters.
If you want to ignore the white spaces, tokenize the input first.

A: from collections import Counter

txt = "Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?"

txt1 = txt[:-1]
txt2 = txt[1:]
print (Counter([t1+t2 for t1, t2 in zip(txt1,txt2)]))


text:
Q: How to save a nested object in react js form input using hooks? Here I am trying to save category_id to database which is part of category object like
object:{
category_id:""
}
But doing the following way is throwing error "detatched entity passed to persist".It's confusing.Please helo
            <FormGroup>
                <label for="category_id">category_id</label>
                <Input
                    placeholder="Enter category id"
                    id="category_id"
                    name="category_id"
                    type="textarea"
                    onChange={(e) => {
                      setProduct({ ...product, category: { categoryId: e.target.value } })
                    }}
                />
            </FormGroup>

A: in onChange function call a separate function and pass the value as parameter
onChange={(e)=>sendData(e.target.value)}

and
let products = {}
const sendData = (value)=>{
setInputValue(value)
productDetails = { ...products, catId:inputValue}
setProd(products)
}


text:
Q: How to set up on default View Quick Edit In SharePoint there is a Quick Edit Button in the Library ribbon under "View Format".
How can I enable the library to be shown in Quick Edit mode as the default?
Could I make a "Quick Edit" view?

A: Add a custom button above your List View Web Part.
execute the following JS functions on click of it.
Use this to open Quick Edit:
InitGridFromView(window['WPQ2SchemaData'].View);

Use this to exit Grid View:
ExitGrid(window['WPQ2SchemaData'].View);

You can also use the following code to check the status of web part:
var gridinfo = GetCtxFromView(window['WPQ2SchemaData'].View);
        if (gridinfo.inGridMode) {
        //in grid mode
        }else{
        //in normal mode
        }

If you want to open the Quick Edit view by default, create a data sheet view instead of standard view.

A: Create a New View the way @calebben3 describes. Select Datasheet View

and make it default view

Next time You open the library it will show up in Quick Edit mode ( same as Datasheet view).

A: If you are wanting the document library to show the Quick Edit View by default just follow these steps.

*

*Create a new view. Beneath "+ new document" you should see "All Documents" click on the dots to the right and click "Create View".

*On the View Type page that appears click the view type of "Datasheet View" (in the right column usually)

*Name the view what you wish in the Name section and be sure to check the "Make this the default view" box, be sure to check the columns you want to display as needed. Then click "Ok" at the top or the bottom of the page.

*You will be back at the library page and the default view will now show your documents listed in the Quick Edit mode!

A: Are you talking about this button?

To have access to that button, you need to have at least Edit permission on the site.

A: To add a custom Quick Edit button to your page or view, add a Script Editor web part and embed the following code. Make sure you change the number in [WPQ2SchemaData] to the web part number of the list/library you want to Quick Edit. You can find that by inspecting the list/library web part using Developer Tools (F12).
<!DOCTYPE html>
<html>
<body>

<button onclick="QuickEditFunction();return false;">Quick Edit</button>

<script>
function QuickEditFunction()
{
InitGridFromView(window['WPQ2SchemaData'].View);
}
</script>

</body>
</html>


text:
Q: Proper way to get SHA-1 for signing Flutter application I'm little confused about how to get SHA-1 key for console.cloud.google.com.
The flutter documentation says: create a keystore.jks file anywhere and use it from [project]/android/app/build.gradle.
Configure signing in gradle
Others says to use C:\Users\yourusernamehere.android\debug.keystore
and get sha-1 by running: ./gradlew signingReport
flutter generate sha1
What is the correct way to sign?

A: go to the android directory of your project and run gradlew signingReport


text:
Q: draw a elastic line in uiviewcontroller from touchbegin to touch move i am implementing an application where i need to draw a line on UIViewController.
line should straight and behave elastically, likethis Image,
you can take reference to my question from this app.
i have gone through lot of tutorial, where i found this
and implement too, but out put is like : line is not straight and also not behaves elastically.
if anyone know how can i implement such line, please guide me.
thanks.


text:
Q: Gforth - How to get codepoints of a string? I know that gforth stores characters as their codepoints in the stack, but the material I'm learning from doesn't show any word that helps to convert each character to codepoint.
I also want to sum the codepoints of the string. What should I use to do that?

A: In Forth we distinguish primitive characters (usually an octet that covers ASCII) and extended characters (usually Unicode).
Any character is always represented in the stack as its code point, but how extended characters are represented in memory is implementation depended.
See also Extended-Character word set:

Extended characters are stored in memory encoded as one or more primitive characters (pchars).

So to convert a character into a code point it's enough to read this character from the memory.
To read a primitive character, we use c@ ( c-addr -- char )
: sum-codes ( c-addr u -- sum ) 0 -rot over + swap ?do i c@ + 1 chars +loop ;

\ test
"test passed" sum-codes .

NB: native string literals are supported in the recent versions of Gforth. Before that you need to use the word s" as s" test passed".
To read an extended character, we can use xc@+ ( xc-addr1 -- xc-addr2 xchar )
: sum-xcodes ( c-addr u -- sum )
  over + >r 0 swap
  begin ( sum xc-addr ) dup r@ u< while
    xc@+ ( sum xc-addr2 xchar ) swap >r + r>
  repeat drop rdrop
;

\ test
"test ⇦ ⇨ ⇧ ⇩" 2dup dump cr sum-xcodes . cr

dump shows that in Gforth the extended characters are stored in the memory in UTF-8 encoding.


text:
Q: Deployed Flutter application to Google Play Store but it's stuck at the splash screen Deployed Flutter application to Google Play Store but it's stuck at the splash screen and never open
I did match my AppID and still facing the same issue
Here is my manifest.xml:
<!-- TODO: Changed by Parveen Before merge 1 -->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.mrbox.store">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <!--
    io.flutter.app.FlutterApplication is an android.app.Application that
    calls FlutterMain.startInitialization(this); in its onCreate method.
    In most cases you can leave this as-is, but you if you want to provide
    additional functionality it is fine to subclass or reimplement
    FlutterApplication and put your custom class here.
    -->
    <!-- TODO: Add By Parveen before merge 1 -->
    <application
        android:name="io.flutter.app.FlutterApplication"
        android:label="Mr.Box Store"
        android:usesCleartextTraffic="true"
        android:icon="@mipmap/launcher_icon">
        <activity
            android:name=".MainActivity"
            android:launchMode="singleTop"
            android:theme="@style/LaunchTheme"
            android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
            android:hardwareAccelerated="true"
            android:windowSoftInputMode="adjustResize">
            <!--
            Specifies an Android theme to apply to this Activity as soon as
            the Android process has started. This theme is visible to the user
            while the Flutter UI initializes. After that, this theme continues
            to determine the Window background behind the Flutter UI.
            -->
            <meta-data
                android:name="io.flutter.embedding.android.NormalTheme"
                android:resource="@style/NormalTheme"
                />
            <!--
            Displays an Android View that continues showing the launch screen
            Drawable until Flutter paints its first frame, then this splash
            screen fades out. A splash screen is useful to avoid any visual
            gap between the end of Android's launch screen and the painting of
            Flutter's first frame.
            -->
            <meta-data
                android:name="io.flutter.embedding.android.SplashScreenDrawable"
                android:resource="@drawable/launch_background"
                />
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
            <intent-filter>
                <action android:name="FLUTTER_NOTIFICATION_CLICK" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
            <!--
            TODO: Changed by parveen before merge 1
            android:name="default-url"
            android:value="https://inspireui.com"
            -->
            <meta-data
                android:name="default-url"
                android:value="https://www.mrboxstore.com" />
            <intent-filter android:autoVerify="true">
                <action android:name="android.intent.action.VIEW" />

                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.BROWSABLE" />
                <!-- TODO: Changed by parveen before merge 1 android:value="inspireui.com" -->
                <data android:scheme="https"
                    android:host="mrboxstore.com" />
                <data android:scheme="http" />
            </intent-filter>
        </activity>
        <meta-data
            android:name="com.google.firebase.messaging.default_notification_icon"
            android:resource="@drawable/logo" />
        <!--
        Set color used with incoming notification messages. This is used when no color is set for the incoming
        notification message.
        -->
        <meta-data
            android:name="com.google.firebase.messaging.default_notification_color"
            android:resource="@color/notiColor" />
        <!-- Google map and Admod setup -->
        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="@string/api_key" />
        <meta-data
            android:name="com.google.android.gms.ads.APPLICATION_ID"
            android:value="@string/admob_api" />
        <!-- Facebook Login configuration -->
        <meta-data
            android:name="com.facebook.sdk.ApplicationId"
            android:value="@string/facebook_app_id" />
        <activity
            android:name="com.facebook.FacebookActivity"
            android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation"
            android:label="@string/app_name"
            android:exported="true" />
        <activity
            android:name="com.facebook.CustomTabActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.VIEW" />
                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.BROWSABLE" />
                <data android:scheme="@string/fb_login_protocol_scheme" />
            </intent-filter>
        </activity>
        <!--
        Don't delete the meta-data below.
        This is used by the Flutter tool to generate GeneratedPluginRegistrant.java
        -->
        <meta-data android:name="flutterEmbedding"
            android:value="2" />
    </application>
</manifest>

A: Things to try

*

*Make sure flutter doctor -v runs without ANY complaints

*Edit android/gradle.properties and add the flag: android.bundle.enableUncompressedNativeLibs=false

*Do a flutter clean command

*Try creating a release build using flutter build appbundle
Test Locally / Offline

*

*download bundletool

*Generate a set of APKs from your app bundle, following this guide

*Deploy the app to your connected device(s) following this Guide
Works?

*Upload your bundle to Google Play using the internal test track, or the alpha or beta channels to test the bundle before releasing it in production
Instructions for doing this can be found here

*Good Luck :)

A: Because it is not working after uploading on google play. then there might be some issue with your app signing. You can follow the steps here

A: I have faced issues like this when I used facebook login sdk, so I would suggest checking following:

*

*Check if you have signed the apk/appbundle with proper release keystore

*Check if you have opt in for google's automatic signing on playstore while deploying app
2.1 If yes then it will change the sha-1 value which is used in facebook app for authentication, for it to work use the one generated by google in playstore

A: Assuming that you publish an App Bundle (.aab file) the issue can be related to the format itself since it is not testable via IDE. E.g. when running the app in Release mode on a device .apk is created and provisioned to it, not .aab.
What I did in the past to troubleshoot .aab (also had failures only with GPlay version, local Debug and Release modes worked fine) was to use Firebase Test Lab. You can run automated monkey tests on 5 physical devices and 15 virtual devices every day free-of-charge. Just log in to Firebase Console, cretae an empty project, go to Test, upload your .aab file, select devices (it's worth also to choose different locales) and wait for completion. After that check logs in test results, you might find answers there (in my cases there was an issue with localization resources which got broken while producing .aab release package).
This option can be esier/faster than splitting .aab locally with comand line into APKs and testing on a local device.

A: In my experience, try to check your database(sqlite) if created. Try to replace the path and check if the database is created properly.


text:
Q: Display Web Interface by entering IP of LAN computer So basically, I have a software which can consist of 1 to many clients and 1 to many servers. I want to create a web interface for my server side software. A client should be able to get their server machine's IP address and enter it into a web browser. It will then display our web interface populated with different buttons which interact with the server side software.
Generally, we are trying replicate the technology of connecting to a wireless router. For example, with the IP of your router, you are able to enter it into a browser like Chrome and it will display your wireless router's configuration screen where you can change the configurations of your router.
Would I need to use a service like IIS or Apache to do something like this?
If someone can please help me get into the right direction, I would really appreciate it.
I thank you all in advance!

A: If you want the user to access your interface through a web browser then yes, you will need an HTTP server to serve your interface. Apache and IIS can be used here.
As you tagged your question with the [C#] tag, I think you will write your application using .NET technologies so IIS will be your server of choice.
Concerning using the IP address to access your server, it's not an issue as long as you know the IP and you can reach it. It the server is behind a router, you may have to play a little with the NAT configuration.


text:
Q: How to insert Date and Time when a check box is checked in google sheet? so I wrote a script that is working on edit and looking if the active cell in column A or column D. In column D I have a checkbox I want to fill the Column F with current time when the checkbox is true. You can see my script below. Currently it fills when column A is edited but It doesnt do anything if the checkbox is checked.
function onEdit() {
  var s = SpreadsheetApp.getActiveSheet();
  if( s.getName() == "Sheet1" ) { //checks that we're on Sheet1 or not
    var r = s.getActiveCell();
    if( r.getColumn() == 1 ) { //checks that the cell being edited is in column A
      var nextCell = r.offset(0, 4);
      nextCell.setValue(new Date());
    }
   else if( r.getColumn() == 4 ) { //checks that the cell being edited is in column A
      if(r.getValue() == "TRUE") {
        var nextCell = r.offset(0, 2);
          nextCell.setValue(new Date());
      }
    }
  }
}

A: *

*You want to put the date object to the column "F" when the checkbox at the column "D" is checked.

*You want to run the script with the OnEdit event trigger.

Modification points:

*

*In your script, I think that the if statement of if(r.getValue() == "TRUE") {} is required to be modified. In this case, when r.getValue() is the boolean type, r.getValue() == "TRUE" is always false. By this, the script in the if statement is not run. I think that this is the reason of your issue.

Modified script 1:
When your script is modified, please modify as follows.
From:
if(r.getValue() == "TRUE") {

To:
if(r.getValue() === true) {

or
if(r.isChecked()) {

*

*In this case, also you can use isChecked().

Modified script 2:
When the event object is used, the process cost of your script can be reduced a little. Ref The sample script using the event object is as follows.
Sample script:
function onEdit(e) {
  var range = e.range;
  var sheet = range.getSheet();
  if(sheet.getSheetName() == "Sheet1") {
    if(range.columnStart == 1) {
      var nextCell = range.offset(0, 4);
      nextCell.setValue(new Date());
    } else if(range.columnStart == 4 && range.isChecked()) {
      var nextCell = range.offset(0, 2);
      nextCell.setValue(new Date());
    }
  }
}

References:

*

*getValue()

*isChecked()

*Event Objects


text:
Q: Why does two joined circles (wedge sum) with a point removed deformation retract to a single circle? Let $X$ and $Y$ be two unit circles in $\mathbb{R}^2$. $X$ is centered at $(1,0)$, while $Y$ is centered at $(-1,0)$.
Consider $A = X \cup Y$. Let $p \in Y$ be a point that is not $(0,0)$.
Why is $X$ a deformation retract of $A - p$?
Attempt: Intuitively, I can expand the hole in $Y$ and pushed both "arms" into the point $(0,0)$. But what would the retract $r: A - p \to X$ be exactly?
Also, the fact that $Y - p$ is homeomorphic to the real line via sterographic projection, and that the real line is contractible feels like I should be able to retract $Y-p$ to the point $(0,0)$.

A: Let $p = (-1 + \cos\psi, \sin\psi)$ for $\psi \in (-\pi, \pi)$. Consider $H: A\setminus\{p\} \times [0, 1] \to A\setminus\{p\}$ given by
$$H((-1+\cos\theta, \sin\theta), t) = \begin{cases}
(-1 + \cos((1-t)\psi-t\pi), \sin((1-t)\psi-t\pi)) & \theta \in (-\pi, \psi)\\
(-1 + \cos((1-t)\psi+t\pi), \sin((1-t)\psi+t\pi)) & \theta \in (\psi, \pi)
\end{cases}$$
and $H(x, t) = x$ otherwise. The first case retracts the bottom arc to $(0, 0)$ while the second case retracts the top arc to $(0, 0)$.


text:
Q: How is energy conserved? From what I've heard, there is no absolute grid you can put on the universe, and therefore you can only ever talk about relative motion.
I've also heard that energy is conserved and constant no matter your location or velocity.
But how does this work with kinetic energy? Surely if I start walking in a certain direction, all the galaxies in that direction have decelerated, and those behind me will have accelerated by the same amount. But since the equation for kinetic energy is $E = (1/2)mv^2$, this means that the galaxies which have, from my perspective, accelerated, have gained more kinetic energy than those which have, from my perspective, decelerated. How does this work?
I'm assuming that the energy changes that happen when I walk are insignificant compared to the extra kinetic energy gained by billions of galaxies.

A: There is no single preferred frame for examining the universe, but that doesn't mean all frames are identical.  In fact, for many forms of analysis, we require an inertial frame.
The fact that you start walking does not mean that every other object in the universe has accelerated.  It means that you are examining them from another frame of reference or you are using a frame that is itself accelerating (non-inertial).
Energy is not conserved when translating between different frames of reference.  To keep things sane, you need to pick one (inertial) frame of reference and stick to it.
You have two obvious ones in your scenario.  One frame in which you are at rest before you begin walking, and a frame in which you are at rest after you begin walking.
In either frame, the only object that we consider to change speed is you, so your KE changes before and after $t=0$, while the other objects do not.

A: Let's tackle this problem from the perspective of Newtonian mechanics since that will be most illuminating to the confusion at hand. In Newtonian mechanics, there are special preferred reference frames, inertial reference frames, which you can define as a frame in which no pseudo forces arise - i.e. a frame in which Newton's first law applies. This problem you are seeing is then simply a confusion between the two different concepts of conservation and frame invariance. Energy is conserved but it is not frame invariant. Different inertial reference frames will measure different energies of objects, but a given inertial reference frame will always measure total energy to be constant. Hopefully that distinction is clear. Now, in this context, when you are accelerating you are changing from one inertial frame (not walking) to another (walking at constant pace - after you finished accelerating) and so the energy that you measure will NOT have remained the same since you have changed reference frames. You have simply shown that Energy is not frame invariant. During the acceleration phase, you are in a non-inertial reference frame so your analysis is not preferred in Newtonian Mechanics. You would have to introduce pseudo force(s) to explain why everything else is accelerating around you even though no apparent forces are acting on exterior objects (i.e. why is Newton's first law failing for you).


text:
Q: Fallo en configuración de failregex en fail2ban Estoy tratando de configurar el failregex de Fail2ban para captar peticiones a /seccion del sitio.
Lo que busco con esto es limitar la cantidad de peticiones a esta sección del sitio. Y si el límite de peticiones en un tiempo establecido es superado, bloquear la IP mediante iptables.
El problema es que he creado el failregex para machear las peticiones del access_log y algo debe estar mal. Porque no hace nada.
Adjunto a continuación la línea del failregex junto con parte del access_log. Para ver si alguien puede decirme qué está mal.
failregex = ^<HOST> -.*"(GET|POST). .*\/seccion\/*

Y el access_log:

200.43.12.170 - - [14/Mar/2016:08:34:23 -0300] "GET /js/jquery.flexslider-min.js HTTP/1.1" 200 21422 "http://www.dominio.com/seccion/locales_13/te-regalamos-entradas-para-la-convencian-de-camics-y-anima-level-up_a_219112" "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.87 Safari/537.36"

A: Hice un test con la siguiente regex y me funciona con el log que :
<HOST> -.*"(GET|POST) .*\/seccion\/*

Aquí hice te dejo con la prueba: http://rubular.com/r/FridZ6jstD (fijate que puse dos líneas de log: una con /seccion/ y otra sin esto)
UPDATE:
Puedes usar la siguiente herramienta para probar tus regex: http://thefragens.com/2010/11/checking-fail2ban-regex/


text:
Q: Azure Metric Alert - Corresponding Logs I have created an Alert Rule in Event Grid for Dropped Events, alert works fine and I get the email, but neither in the Alert email or when I go and look at it in the Azure portal it shows me the actual error, like which subscription(s) had the failure and the error text (in my case I actually stopped one of the Functions that was subscribing one of the events to test the Alert)
In the Diagnostic Settings of Event Grid, I have set the logs to be sent to Log Analytics workspace but even after this I see no logs for the corresponding failures, am I missing anything? Is there an easy way to see the logs against a particular Alert?

A: Azure alerts proactively notify you when important conditions are found in your monitoring data. Log alerts allow users to use a Log Analytics query to evaluate resources logs every set frequency, and fire an alert based on the results.
You can search for the functions app logs under log analytics, check this Monitoring Azure Functions with Azure Monitor Logs documentation for the steps to do it.
Azure monitor processes terabytes of customer's log from across the world, which can also cause logs ingestion latency. It can be solved by optimizing the log alert queries.


text:
Q: Disable Chrome search on invalid urls How can I prevent Chrome/Chromium from searching via the address bar unless I explicitly start with "?" or any other keyword?
I'm trying to avoid searches where I'd rather have an error message stating invalid url.

A: You can add a new search engine in preferences, set URL to %s and use it as the default one - this will produce the message you want instead of actually searching.

A: More likely it's your ISP or DNS that redirect if you type in a invalid URL. If you type an URL that is invalid you should get this message: This webpage is not available.You might get this too: Oops! Google Chrome could not find....


text:
Q: How to Add html element in data attribute I want to add whole html element to data attribute so that on click I can set it to localstorage and can use it on next pages as well instead of doing the same stuff again on next page ...
Here is what I was doing...
Checking if img_src has a value or not
if false than set a div with letter X and some styling
if true set img tag with src and some width and height
      var img_src="userpic.png"; //this value comes from db
      if(img_src=="" || img_src==null){
        var po_img = '
X
';
      }
      else{
        var po_img = '';
      }

Jquery on click
        $(".col").on('click',function(){
           window.localStorage.setItem('img',$(this).data('img'));
           window.localStorage.setItem('religion',$(this).data('religion'));
           window.localStorage.setItem('category',$(this).data('category'));
        });

But this adding html inside data attirbute results

This above image is my html page result

A: One solution that works is using jQuerys constructor to create the elements and then using those elements to set the data- attributes to store it. This example works and seems to do what you want.

var img_src = "userpic.png"; //this value comes from db
var element = {
  student: {
    photo: "myImage.com"
  }
}; // for this example only

var $po_img;
if (img_src == "" || img_src == null) {
  $po_img = $('
', { class: "class-groupPic bg-1"});
  $po_img.text("X");
} else {
  $po_img = $('', {src: element.student.photo, width: 34, height: 34});
}

var $myDiv = $('
', { id: "myDiv", class: "col"});
$myDiv.text("I am the div");
$myDiv.attr("data-img", $po_img[0].outerHTML);
$myDiv.attr("data-religion", "Hindu");
$myDiv.attr("data-category", "OBC");

// add the div to the DOM
document.write($myDiv[0].outerHTML);

// Retrieve the img HTML from the div's data attribute
var theImage = $("#myDiv").attr("data-img");
console.log(theImage);


text:
Q: Convert string to XML using .Net I store the XML output to String and Again convert this string to XML .I successfully convert XML output to String, but i got problem again converting string to XML.
sample code:
 webservice.Service1 objService1 = new webservice.Service1();
    String s = objService1.HelloWorld();   //Convert XML output into String
    XmlDocument xd = new XmlDocument();
    xd.LoadXML(s);

I use LoadXML() method, but i got error
Data at the root level is invalid. Line 1 position 1.

Its grateful, if any body give right code to convert String To XML in c#.
Thank you,

A: You should use XDocument. XDocument is better than XMLDocument. It is very efficient, simple and easy to use.
Your code :
webservice.Service1 objService1 = new webservice.Service1();
    String s = objService1.HelloWorld();   //Convert XML output into String
    XmlDocument xd = new XmlDocument();
    xd.LoadXml(s);

Solution:
XDocument xd = XDocument.Parse(s);

A:       XmlDocument xd = new XmlDocument();
      xd.LoadXml("<root>123</root>");

It works.
You should print the s value and check it is a valid xml string.


text:
Q: Converting csv with Powershell i have a csv that is encoded in DOS Latin 1 (Codepage 850). It must be converted to do later some replacements with powershell in the file. I have several lines in a bat file. Here the one to convert the csv and export it with a new name. If i convert it manually (Libre Office) the processing later works fine with the scripts.
powershell -Executionpolicy Bypass -Command "import-csv -encoding oem .\import.csv -delimiter ';' | export-csv '.\export-temp.csv'"

The exported file is empty. I have tried it too with adding -encoding in the output. It doesnt work. Does anyone have a idea what the problem might be? I have done several hours of researches but couldnt find any solutions.
This is the content of the csv file:
MsgType; Date; Time; SenderEAN; Sender; SenderCVR
ItemInventory; 300622; 161457; 5790001405397; See; 15049847;
Art_No; Mod_No; Description; Var1Name; Var2Name; Brand; Inv; Expe; N_No
1001005; 1001005; Exp; green; 46; Här; 5;  ; 57073
1001055; 1001055; Vis; green; 48; Här; 15;  ; 57073

Update: Here is the Error from Powershell. It says, that the Element "Här" already exists. Does anyone have an idea what it means?
import-csv  .\import.csv -encoding oem -Delimiter ';' | export-csv '.\export-temp.csv'
import-csv : Das Element " Här" ist bereits vorhanden.
In Zeile:4 Zeichen:1

*

*import-csv  .\import.csv -encoding oem -Delimiter ';' | export-csv '. ...

*
  + CategoryInfo          : NotSpecified: (:) [Import-Csv], ExtendedTypeSystemException
  + FullyQualifiedErrorId : AlreadyPresentPSMemberInfoInternalCollectionAdd,Microsoft.PowerShell.Commands.ImportCsvCommand

Sorry when my english is not the best, hello from Germany :)
Regards, Hubertus
Update: to clarify what i want to do. In a following step i remove the 2 lines on the top, and select the columns "Inv" and "N_No" and export them to a modified .csv file. This file is always empty. When i change the encoding manually before to utf8 it works fine. For testing reason i have splitted it in smaller pieces.  Here the full code. 3 lines in a .bat file:
powershell -Executionpolicy Bypass -Command "gci '.\import.csv' -recurse | %%{(gc $_.Fullname) | select -skip 2 | set-content $_.Fullname}"

powershell -Executionpolicy Bypass -Command "import-csv -encoding oem .\import.csv -delimiter ';' | export-csv -encoding utf8 '.\export-temp.csv' -delimiter ';' "

powershell -EP Bypass -C "import-csv -encoding utf8 '.\export-temp' -delimiter ';' | select N_No, Inv | export-csv '.\export.csv' -delimiter ';' -NoTypeInformation"

The output file has only the name of the columns but no values.


text:
Q: How to add labels to plot with facets? I'm working with a data frame like this:
food_totals <- tibble::tribble(
  ~ food, ~ year, ~ total, ~ overall_change,
  "Orange", 2012, 5, -3,
  "Orange", 2013, 3, -3,
  "Orange", 2014, 2, -3,
  "Kiwi", 2012, 4, 2,
  "Kiwi", 2013, 5, 2,
  "Kiwi", 2014, 6, 2,
  "Eggplant", 2012, 4, -4,
  "Eggplant", 2013, 2, -4,
  "Eggplant", 2014, 0, -4
)

I want to create a set of line charts to show the change over time for each, which is easy enough.
food_totals %>%
           ggplot(aes(year, total)) +
  geom_line(aes(colour = food, group = food)) +
  facet_wrap(vars(food)) +
  theme(axis.text.x = element_text(angle = 90))

The problem I'm having is that I want to include an annotation on each of the charts that shows the value in that food's "overall_change" column. I'd like the annotation to be a label on the top center of the chart itself. Whenever I try to insert overall_change as a label, I run into errors.
Thank you for your time!

A: When adding labels to facet plots, I've found that it's usually easier to compute what you want ahead of time:
food_labels <- food_totals %>%
  group_by(food) %>%
  summarize(x = mean(year), label = unique(overall_change))

  food         x label
  <chr>    <dbl> <dbl>
1 Eggplant  2013    -4
2 Kiwi      2013     2
3 Orange    2013    -3

We can then plot this using the average year per facet to center the text ("x" in the data frame above), and Inf for the y-value to ensure that labels always appear at the top of the plot.
food_totals %>%
  ggplot(aes(year, total)) +
  geom_line(aes(colour = food, group = food)) +
  geom_text(data = food_labels, aes(x = x, label = label), y = Inf, vjust = 2) +
  facet_wrap(vars(food)) +
  theme(axis.text.x = element_text(angle = 90))


text:
Q: automatically adding submenu items Here's the solution that @bainternet has posted here:
Add child pages automatically to nav menu
/**
* auto_child_page_menu
*
* class to add top level page menu items all child pages on the fly
* @author Ohad Raz <admin@bainternet.info>
*/
class auto_child_page_menu
{
    /**
     * class constructor
     * @author Ohad Raz <admin@bainternet.info>
     * @param   array $args
     * @return  void
     */
    function __construct($args = array()){
        add_filter('wp_nav_menu_objects',array($this,'on_the_fly'));
    }
    /**
     * the magic function that adds the child pages
     * @author Ohad Raz <admin@bainternet.info>
     * @param  array $items
     * @return array
     */
    function on_the_fly($items) {
        global $post;
        $tmp = array();
        foreach ($items as $key => $i) {
            $tmp[] = $i;
            //if not page move on
            if ($i->object != 'page'){
                continue;
            }
            $page = get_post($i->object_id);
            //if not parent page move on
            if (!isset($page->post_parent) || $page->post_parent != 0) {
                continue;
            }
            $children = get_pages( array('child_of' => $i->object_id) );
            foreach ((array)$children as $c) {
                //set parent menu
                $c->menu_item_parent      = $i->ID;
                $c->object_id             = $c->ID;
                $c->object                = 'page';
                $c->type                  = 'post_type';
                $c->type_label            = 'Page';
                $c->url                   = get_permalink( $c->ID);
                $c->title                 = $c->post_title;
                $c->target                = '';
                $c->attr_title            = '';
                $c->description           = '';
                $c->classes               = array('','menu-item','menu-item-type-post_type','menu-item-object-page');
                $c->xfn                   = '';
                $c->current               = ($post->ID == $c->ID)? true: false;
                $c->current_item_ancestor = ($post->ID == $c->post_parent)? true: false; //probbably not right
                $c->current_item_parent   = ($post->ID == $c->post_parent)? true: false;
                $tmp[] = $c;
            }
        }
        return $tmp;
    }
}
new auto_child_page_menu();

How to use it?
I have to implement it on a published website so I'm not in a position to experiment much...
c/p code to functions.php?
call the function from inside the header?


text:
Q: Check for 2 classes jQuery html element I currently have tr:not(.discarded) to check if a row has been class discarded. How can I check that a row doesn't have discarded or bad class? Should I use tr:not(.discarded) or tr:not(.bad) or something else?

A: The :not selector can take multiple CSS selectors as arguments.
Here is a reference for this selector.
E.g.
$('tr:not(.discarded,.bad)')