text:
Q: Apache Phoenix query server thin client with Kerberos I'm trying to setup Apache Phoenix QueryServer in secure HBase environment.
My hbase-site.xml is:
<configuration>
  <property>
    <name>hbase.regionserver.wal.codec</name>
    <value>org.apache.hadoop.hbase.regionserver.wal.IndexedWALEditCodec</value>
  </property>
  <property>
    <name>hbase.zookeeper.quorum</name>
    <value>zk1,zk2,zk3</value>
  </property>
<property>
    <name>hbase.security.authentication</name>
    <value>kerberos</value>
</property>
<property>
    <name>phoenix.queryserver.keytab.file</name>
    <value>/usr/lib/apache-phoenix-queryserver/bin/phoenix.keytab</value>
</property>
<property>
    <name>phoenix.queryserver.kerberos.principal</name>
    <value>rwqueryserver/_HOST@FOO.BAR</value>
</property>
<property>
    <name>phoenix.queryserver.http.keytab.file</name>
    <value>/usr/lib/apache-phoenix-queryserver/bin/phoenix.keytab</value>
</property>
<property>
    <name>phoenix.queryserver.http.kerberos.principal</name>
    <value>rwqueryserver/_HOST@FOO.BAR</value>
</property>
</configuration>

Query server is starting without any problems.
2018-12-12 09:13:07,353 INFO org.apache.phoenix.queryserver.server.QueryServer: Login successful.

I checked KDC side and I can see logins from the principal used for server/client connections. No errors on KDC side as well.
Thin client command is:
./sqlline-thin.py 'http://dns-of-query-server:8765;principal="rwqueryserver/dns-of-query-server@DATASYS.CF.WTF";keytab="/usr/lib/apache-phoenix-queryserver/bin/phoenix.keytab"'

I tried to use user's principal and server's principal - situation is the same.
java.lang.RuntimeException: Failed to execute HTTP Request, got HTTP/404

From the queryserver log:
2018-12-12 09:15:30,987 WARN org.apache.phoenix.shaded.org.eclipse.jetty.security.SpnegoLoginService:
GSSException: Failure unspecified at GSS-API level (Mechanism level: Invalid argument (400) - Cannot find key of appropriate type to decrypt AP REP - AES256 CTS mode with HMAC SHA1-96)
        at sun.security.jgss.krb5.Krb5Context.acceptSecContext(Krb5Context.java:856)
        at sun.security.jgss.GSSContextImpl.acceptSecContext(GSSContextImpl.java:342)
        at sun.security.jgss.GSSContextImpl.acceptSecContext(GSSContextImpl.java:285)
        at sun.security.jgss.spnego.SpNegoContext.GSS_acceptSecContext(SpNegoContext.java:906)
        at sun.security.jgss.spnego.SpNegoContext.acceptSecContext(SpNegoContext.java:556)
        at sun.security.jgss.GSSContextImpl.acceptSecContext(GSSContextImpl.java:342)
        at sun.security.jgss.GSSContextImpl.acceptSecContext(GSSContextImpl.java:285)
        at org.apache.phoenix.shaded.org.eclipse.jetty.security.SpnegoLoginService.login(SpnegoLoginService.java:137)
        at org.apache.phoenix.shaded.org.eclipse.jetty.security.authentication.LoginAuthenticator.login(LoginAuthenticator.java:61)
        at org.apache.phoenix.shaded.org.eclipse.jetty.security.authentication.SpnegoAuthenticator.validateRequest(SpnegoAuthenticator.java:99)
        at org.apache.phoenix.shaded.org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:512)
        at org.apache.phoenix.shaded.org.eclipse.jetty.server.handler.HandlerList.handle(HandlerList.java:52)
        at org.apache.phoenix.shaded.org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:97)
        at org.apache.phoenix.shaded.org.eclipse.jetty.server.Server.handle(Server.java:499)
        at org.apache.phoenix.shaded.org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:311)
        at org.apache.phoenix.shaded.org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:257)
        at org.apache.phoenix.shaded.org.eclipse.jetty.io.AbstractConnection$2.run(AbstractConnection.java:544)
        at org.apache.phoenix.shaded.org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:635)
        at org.apache.phoenix.shaded.org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:555)
        at java.lang.Thread.run(Thread.java:745)
Caused by: KrbException: Invalid argument (400) - Cannot find key of appropriate type to decrypt AP REP - AES256 CTS mode with HMAC SHA1-96
        at sun.security.krb5.KrbApReq.authenticate(KrbApReq.java:278)
        at sun.security.krb5.KrbApReq.<init>(KrbApReq.java:149)
        at sun.security.jgss.krb5.InitSecContextToken.<init>(InitSecContextToken.java:108)
        at sun.security.jgss.krb5.Krb5Context.acceptSecContext(Krb5Context.java:829)
        ... 19 more

When I'm trying to use non-existing principal I'm getting different errors.
I checked JCE - it's installed.
jrunscript -e 'print (javax.crypto.Cipher.getMaxAllowedKeyLength("AES") >= 256);'
true

Can you advice anything ?

A: This looks like a match to a known Java bug.
Please refer; https://bugs.java.com/bugdatabase/view_bug.do?bug_id=6907425
Have a look at the above documentation and try again with an up to date JDK version.


text:
Q: SQL- Null results not returning for select statement when executed with variable = null, but does when hardcoded I have a stored procedure which returns a list. The variable, IS2000PolicyNo, can have a Null result from tblQuote.
This is a simplified snippet showing just the variables causing the problems.

@IS2000PolicyNo int,

   IF @IS2000PolicyNo = -1
SET @IS2000PolicyNo = NULL

   BEGIN TRY
SELECT
 List= replace( (  SELECT top 500
                        cast(ISNULL(T.IS2000PolicyNo,'') as varchar)  + ';'
  FROM
 (SELECT DISTINCT
      Q.IS2000PolicyNo
   FROM
 dbo.tblQuote Q
  WHERE
  cast(isnull(Q.IS2000PolicyNo,'')as varchar)  LIKE '%'+ CAST(ISNULL(@IS2000PolicyNo,'')as varchar) + '%' )

I execute the procedure passing -1, the IF statement converts it to null, which should return all the records, but it skips the records with null values for IS2000PolicyNo.
When I hard code into the Where statement to have @IS2000PolicyNo equal to null, it returns all the records including the nulls.

WHERE
  cast(isnull(Q.IS2000PolicyNo,'')as varchar)  LIKE '%'+ CAST(ISNULL(null,'')as varchar + '%')

I have also tried just setting @IS2000PolicyNo = null instead of the If statement, and it does not return the null values.
I have stepped through the code and it correctly converts the fields to a blank in the If statements.
Thanks!

A: I am guessing that the problem is this line:
cast(isnull(Q.IS2000PolicyNo,'')as varchar) LIKE '%' + CAST(ISNULL(@IS2000PolicyNo,'')as varchar) + '%'

This is highly suspicious:

*

*Why are the values stored as ints but compared as strings?

*Why doesn't varchar() have a length?  (Very dangerous practice, but not the problem here.)

*What do you expect to happen when you pass in -1, which is not NULL?

One possibility is just to do the comparisons as ints.  It is a bit difficult to follow the logic but this might be sufficient:
((Q.IS2000PolicyNo = @IS2000PolicyNo) or coalesce(@IS2000PolicyNo, -1) = -1))

Or perhaps:
((Q.IS2000PolicyNo = '%' + cast(@IS2000PolicyNo as varchar(255)) + '%') or
 (coalesce(@IS2000PolicyNo, -1) = -1))

A: In SQL Server, ISNULL converts output to the same datatype as the input. Since your parameter is an INT, the return type is an INT. See it in action as it returns 0:
declare @foo as int;
set @foo = null;
select ISNULL(@foo,'');

To resolve, you should CAST that parameter to a VARCHAR inside your ISNULL check, not outside of it.
Or, use the ANSI standard COALESCE instead of ISNULL and you won't have this issue. A good explanation is here, specifically:

COALESCE and ISNULL differ in how they determine the data type of the
  resulting expression.
The data type of a COALESCE expression is the data type of the input
  argument with the highest data type precedence. If all inputs are the
  untyped NULL literal, you get an error.
The data type of an ISNULL expression is the data type of the first
  input. If the first input is an untyped NULL literal, the data type of
  the result is the type of the second input. If both inputs are the
  untyped literal, the type of the output is INT.

My final thought is, why is the parameter an INT if you're re-casting it into a VARCHAR throughout your queries? You can resolve the problem and possibly get better speed by changing the parameter's data type to a VARCHAR.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Server-side data submit in Meteor I am new to meteor.Iam using meteor aldeed autoform and collection2 packages in my app.here is my client js file.
Schema = {};

Schema.dc_address = new SimpleSchema({

 'dataCenterName': {
    type: String,
    index: 1,
    label:'Name of the Provider',
    regEx: /^[a-zA-Z\s]+$/
  },
'address1': {
    type: String,
    index: 1,
    label:'Address Line 1',
    regEx: /^[a-zA-Z0-9\s]+$/
  },
'address2': {
    type: String,
    index: 1,
    label:'Address Line 2',
    regEx: /^[a-zA-Z0-9\s]+$/
  },

});

  Template.dataCenters.helpers({//dataCenters is my main template
    steps: function() {
      return [{
        id: 'dc_address',
        title: 'Name & Address',
        template: 'dc_address',
        formId: 'dc_address_form',
        onSubmit: function(data, wizard) {

        var params=_.extend(wizard.mergedData(), data);
        alert(params);

     var jsonrpc = new $.JsonRpcClient({ ajaxUrl: 'http://172.16.4.190:8384' });

        jsonrpc.call(
                 'dataCenterCreate', params,
                     function(result) {alert('Pizzeria answered: ' + $.toJSON(result)); },
                    function(error)  { console.log('There was an error', $.toJSON(error)); }
            );

        }
      }];
    }
  });

here is my html page
<template name="dc_address">

  {{#autoForm doc=this.data id="dc_address_form"  schema=Schema.dc_address }}

        {{> afQuickField name="dataCenterName" placeholder="Enter DataCenter Name"}}

    {{> afQuickField name="address1" placeholder="#7 4th cross"}}

    {{> afQuickField name="address2" placeholder="ITPL-banglore"}}

    <button type="submit" class="btn btn-success btn-md pull-right">Next</button>

  {{/autoForm}}

</template>

That works pretty well although - it's CLIENT side submit  => it is not secure.
How do I implement it is in server side?

A: For security you should remove autopublish and insecure packages. Once you do this inserting anything into the databases will throw an error. Try Posts.insert({}) in the console to see the errors appear.
You get around this by adding allow and deny rules on your server (see the meteor docs for more on allow/deny rules). You can also use meteor methods using: Meteor.call(...) to insert docs into the database without having any allow rules set up. You'd have to do your own checks within the meteor method in this case.


text:
Q: Dirac Notation: Why are these two expressions equal? Consider
$$
\langle a''|(AB - BA)|a' \rangle  =  (a'' - a') \langle a''|B|a' \rangle
$$
where $a''$ and $a'$ are eigenvalues of observable, $A$, which is Hermitian (real eigenvalues). $A$ and $B$ are compatible observables. Also, the eigenvalues of $A$ are nondegenerate.
This equation is from Modern Quantum Mechanics by Sakurai and Napolitano (page 29).
So far, I have:
$$ = \langle a''|AB - BA|a'\rangle = \langle a''|a''B - Ba'|a' \rangle = \langle a''|(a'' - a')B|a'\rangle = (a'' - a') \langle a''|B|a'\rangle$$
But I am not sure if it is okay to take away the parentheses surrounding $(AB-BA)$ so that I can "split" the operator in the middle.

A: The parentheses are needed.
With parentheses:
$$
\langle a''|(AB - BA)|a' \rangle  = \langle a''|AB|a'\rangle- \langle a'' |BA|a' \rangle  =  \langle a'' | a'' B | a' \rangle- \langle a''|B a' | a'\rangle =  (a''-a') \langle a'' | B | a' \rangle
$$
without:
$$
\langle a''|AB - BA|a' \rangle  = \langle a''| a'' B- B a'|a' \rangle  =  a'' \langle a '' | B -a'B|a'\rangle
$$

A: What you have in the parenthesis is not an operator but a number which can be taken out.


text:
Q: Cache of Videos I am trying to cache of videos by this
try {
    URL oracle = new URL(url);
    URLConnection yc = oracle.openConnection();
    InputStream in = yc.getInputStream();

    File file = new File(getApplicationContext().getCacheDir() ,url);

    if(!file.exists()){
        file.setReadable(true);
        file.createNewFile();
        if (file.canWrite()){

            FileOutputStream out = new FileOutputStream(file);

            byte[] buffer = new byte[1024];
            int len1 = 0;
            while ( (len1 = in.read(buffer)) > 0 ) {
                out.write(buffer,0, len1);
            }

            out.close();
        }

        in.close();

        Runtime.getRuntime().exec("chmod 755 "+getCacheDir() +"/"+ url);
        videoView.setVideoPath("chmod 755 "+getCacheDir() +"/"+ url);

    }else {

        videoView.setVideoURI(Uri.parse(videoUrl));
    }
} catch (Exception e) {
    // TODO: handle exception
}
videoView.setVideoURI(Uri.parse(videoUrl));
MediaController mc = new MediaController(VideoViewC.this);
videoView.setMediaController(mc);
videoView.requestFocus();
videoView.start();
mc.show();

But I found Error java.net.SocketException: Connection reset by peer.
if you have any suggestion please give me.

A: I have my case problem, and it consisted in particular the my http server, which if not properly authenticate just closed the client connection, it is my Ask:
android-async-http Status code and response to onFailure
Maybe you have it too, due to the peculiarities of your httpservers
Did you implement caching video files?


text:
Q: PHP Telegram Bot Message Handler I want make input message in telegram bot using php language
I want something like :
When bot say "send your code"
The user send something like "AC6J7A"
How I can get the code I mean how to make message handler .
<?php
$token = 'XXXX';
define('API_KEY',$token);
function bot($method,$datas=[]){
  $url = "https://api.telegram.org/bot".API_KEY."/".$method;
  $datas = http_build_query($datas);
  $res = file_get_contents($url.'?'.$datas);
  return json_decode($res);
}

 bot('sendMessage',[
     'chat_id' => $chat_id,
     'text' => 'Send Your Code : ']);
?>

How can I get the next message of user or can i make message handler ?

A: Do this:
<?php

$token = '   TOKEN   ';
$website = 'https://api.telegram.org/bot'.$token;
$update = file_get_contents('php://input');
$update = json_decode($update, TRUE);
$message = $update['message']['text'];
$id = $update['message']['from']['id'];
$name = $update['message']['from']['first_name'];
$surname = $update['message']['from']['last_name'];
$username = $update['message']['from']['username'];

function sendMessage($id, $text, $button = null){
    GLOBAL $token;
    switch(isset($button)){
        case true:
            $H = '&reply_markup={"inline_keyboard":['.$button.']}';
            $url = 'https://api.telegram.org/bot'.$token."/sendMessage?chat_id=$id&parse_mode=HTML&text=".urlencode($text).$H;
            break;
        default:
            $url = 'https://api.telegram.org/bot'.$token."/sendMessage?chat_id=$id&parse_mode=HTML&text=".urlencode($text);
            break;
    }
    file_get_contents($url);
}

switch($message){
    case '/start':
        $botmessage = 'send your code'; ## if you want this to work you MUST define as "$botmessage" every message the bot send to the user
        sendMessage($id, $botmessage);
        break;
}

$read = file(__DIR__."/$id.txt");
switch($read[0]){
    case 'send your code':
        $codeoftheuser = $read[0];
        ## Code to be executed when the user gives you the code
        break;
}

switch($message){
    case false:  ## This has to be done to make it working in case you use callback query too
        break;
    default: ## This is to write down the last message your bot sent
        $myfile = fopen("$id.txt", 'w+');
        fwrite($myfile, $botmessage);
        fclose($myfile);
        break;
}

?>


text:
Q: Getting Angularjs with Requirejs working with restangular and twitter bootstrap I am building a new angularjs app and want to use requirejs to manage my dependencies.  I am struggling to get this to work and wonder if I'm just misunderstanding something.  I also want to use twitter bootstrap and restangular to make restful calls.  Trying to set this up leads to errors of not being able to find it.  My main,js config is as follows:
require.config({
paths: {
    angular: '../vendor/angular',
    twitterbootstrap: '../vendor/bootstrap/ui-bootstrap-tpls-0.6.0',
    restangular: '../vendor/restangular',
    domReady: '../vendor/domReady'
},
shim: {
    angular : {'exports' : 'angular'},
    restangular: {
        deps: ['underscore']
    }
   }
});

require([
'angular',
'app',
'domReady',
'twitterbootstrap',
//'underscore',
'restangular',
],
function (angular, app, domReady) {}...

I am getting errors with this:
angular is not defined
no module myApp
no module twitterbootstrap
I have tried several variations with this but just can't get it to play nicely together.  Is there something else I'm missing - I've compared it to several examples and everything seems to be in order.

A: Mixing Angular and Require is tricky. I have an experimental project in GitHub (https://github.com/nikospara/angular-require-lazy) that works in some hacky way. You may take a look as an example.
Opinions comments on this project are also wellcome.

For your errors:
Open a net console (e.g. in Firebug) and check the paths called by RequireJS. Are these paths correct?
Angular modules (in contrast to Require/AMD modules) have dependencies of their own. You must make sure that .js files of Angular modules are loaded after angular. One way to do that is to shim them, e.g. for restangular it would be something like:
shim: {
    ...
    restangular: {
        deps: ["underscore", "angular"]
    }
}

Otherwise you can load angular and the other scripts with standard <script> tags, in the correct order.
These are general directions. If you can't find the reason of the problems, maybe you should post some more code; a fiddle/plunkr would also be great, if possible.
Related post in SO: Inject module dynamically, only if required


text:
Q: Seed data in Sequelize with Many-to-Many Relationship I have messed around with trying to get some default data for my application to seed into my PostgreSQL database using sequelize. So far I have only found one way to do it, and it's not ideal.
My main question is if anyone here knows the "best practice" way to do it.
So far I have tried using Seeds, injecting the default information after syncing each model, and finally I have fallen back to requiring files that define how I want to inject the default information aftermodels.sequelize.sync() in the main app.js file.
Seeding: This method seems to fall apart when doing much more than dumping data into the database, associations, namely the classmethods, (to my knowledge) cannot be used here which makes updating a Many-To-Many relationship nearly impossible.
Model Definition: The issue with injecting default information with associations into the model is that you have to somehow import the other model definitions into the model, which I couldn't seem to get working right.
At this point I'm not so interesting in picking apart code as much as I am seeking what you would think/know to be the best way to get default data that has associations into the database. It seems like this would be a more popular issue since almost every app ships with at least a few pieces of default information. I would love to be told that I completely overlooked something and it's actually pretty simple :)
Thanks for the discussion in advance.

A: We don't need to do anything extra if we have our model associations defined already. Lets take an example where doctor can have more than one speciality. In the model definition, we can define our associations.
classMethods: {
      associate: function (models) {
        models.doctor.hasMany(models.specialty, {foreignKey: 'doctor_npi'});
      }

Now we can create an insert function and call this from seeding
insertDoctor: function (models, firstname, lastname, specialties) {
        return this.create({
          firstname: firstname,
          lastname: lastname,
          specialties: specialties,
        }, {
          include: [models.specialty],
        });
      }

Calling this function with right parameters should work.
There are more examples in the official documentation


text:
Q: Function keep initialising local variable instead of using existing variable I'm new in javascript and I'm trying to get a bunch of task from different projects from todoist and trying to assign a label for those tasks.
const task_list = {};
for (let id of project_id) {
    api.getTasks({
        projectId: id, filter: "(today | overdue | p1) & !subtask"
    })
        .then((tasks) => { Object.assign(task_list, { id: tasks }); console.log(task_list)})
        .catch((error) => console.log(error))

}

for (let id of project_id) {
    console.log(id)
    console.log(task_list.id)
}

This is currently my draft for the code. The console.log in the for loop at the bottom is printing undefined but the console.log behind the Object.assign is able to print out the correct output.
Please help.

A: You are replacing the id key of task_list object for every iteration , because Object.assign copies the keys and values from an object to the target object which is task_list in your case.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
if you are trying to create a hash table to keep track of all tasks by id
you could mutate the task_list and assign it by id
task_list[id] = tasks

or replace the original task_list  using Object.assign
const new_task_list = {}
new_task_list[id] = tasks

task_list = Object.assign(task_list, new_task_list)

or using es6 syntax
Object.assign(task_list,{[id]:tasks})

inside your later loop you can access the task value using the id key
for (let id of project_id) {
    console.log(task_list[id].id)
}

also, the last loop will print an empty object because it will get executed before api.getTasks completed the request, you would need to create an array to save all promises then use
Promise.all(promises).then(() => {
// your loop here
})

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all


text:
Q: How to get properties of functions I have functions with two different type signatures:
f :: Int -> [a] -> [a]
g :: (Int, Int) -> [a] -> [a]

The first parameter determines the length of the list that the function operates on. For example, f might operate on lists of length p-1 and g operates on lists of length p^(e-1) for first arguments p and (p,e) respectively.
I use f and g as arguments to another function h :: Int -> ([a] -> [a]) -> [a] -> [a] which needs to know this length function (h's first argument). What I find myself doing currently is:
\p -> h (p-1) (f p)
\(p,e) -> h (p^(e-1)) (g (p,e))

everywhere I use h in combination with f and g. This duplication is error prone and messy.
The goal is to find a way to avoid passing the length argument to h. Instead, h should be able to determine the length itself based on the function argument.
One non-solution would be to change the definition of f to:
f' :: (Int, Int) -> [a] -> [a]
f' (2,_) = previous def
f' (p,_) = previous def

funcToLen :: ((Int, Int) -> [a] -> [a]) -> (Int, Int) -> Int
funcToLen f' (p,_) = p-1
funcToLen g (p,e) = p^(e-1)

h' :: (Int, Int) -> ((Int, Int) -> [a] -> [a]) -> [a] -> [a]
h' (p,e) func xs = let len = funcToLen func
                       func' = func (p,e)
                   in previous def

-- usage
(\p -> h' (p,??) f')
(\(p,e) -> h' (p,e) g)

This has several drawbacks:

*

*I have to change the first argument of f, and then ignore the second part of the tuple

*When I actually use h' with f', I have to create a dummy argument for the second part of the tuple

*Most importantly, funcToLen doesn't work because I can't pattern match on function names.

Another solution that actually works is to use Either:
f' :: Int -> (Int, [a] -> [a])
f' 2 xs = (1, previous def)
f' p xs = (p-1, previous def)

g' :: (Int, Int) -> Either Int ([a] -> [a])
g' (p,1) xs = (1, previous def)
g' (p,e) xs = (p^(e-1), previous def)

h' :: (Int, ([a] -> [a])) -> ([a] -> [a])
h' ef = let len = fst ef
            f = snd ef
        in previous def

This also has a few downsides:

*

*The length function is duplicated for each pattern of f' and g'

*The type signatures of f', g', and h' are all uglier

*I can't immediately use f' and g' on their own (i.e. not as arguments to h'). Instead I have to peel off the tuple.

I'm looking for ways to clean this up so that I don't have to duplicate the length function everywhere, but also allows me to use the functions f and g' in the expected way. I expect this problem has been "solved" before, but I don't know quite what I should be looking for.

A: If you create a function c that calculates p^e-1, effectively decoupling this operation from f and g:
c :: (Int, Int) -> Int
c (p, e) = p ^ (e - 1)

you can merge f and g into the same function (by simply eliminating g). When you have to convert a tuple into an Int, you use c.
The implementation of h is also trivial and does not contain duplicated code.


text:
Q: Display Binary Raw data html I have a blob in my database and would like to store the data in a variable to display it. When I ask for the blob straight it can display, but when I try to store it in a variable and display it cannot.
Here is my code
$http.get("/getImage")
  .then(function (response) {

    $scope.image = response.data;

   // document.body.appendChild(img);
  });

my html
<img src="{{image}}" alt="Image one" width="300" height="200">

Any Ideas. This is how the data looks like.
����[This is how the data looks like][1]

Thank you.


text:
Q: Accessing memory for iterating through an array in-line I want to access elements within arrays by traversing their memory locations. Since elements of any given array are stored sequentially, I'm using the ++ operator to increment through their memory locations.
I can write some code like this:
    int someArray[4];
    someArray[0] = 44;
    someArray[1] = 55;
    someArray[2] = 66;
    someArray[3] = 77;

    int *location = someArray;
    cout << *++location << endl; // OUTPUT: 55
    cout << *++location << endl; // OUTPUT: 66

However I receive errors when I try any of the following:
    cout << *(++someArray) << endl;
    // error: lvalue required as increment operand cout << *(++someArray) << endl;

    // OR

    cout << *++&someArray << endl;
    // error: lvalue required as increment operand cout << *++&someArray << endl;

    // OR

    cout << *++(&someArray) << endl;
    // error: lvalue required as increment operand cout << *++(&someArray) << endl;

I'm quite new to c++ but from my understanding prefixing a variable with & would retrieve its memory location.
Arrays, however, would return their memory location without the &.
Whether I use & or not I receive errors.
I'm wanting to increment through the array in-line, however I have to declare a variable, within which the location is stored first.
I'm hoping for some clarification on my c++ understanding here :)

A: The problem with all three of your last lines is that you are trying to increment a constant.
The address of someArray is a constant. You can't change it. You have to assign it to a pointer variable first, and then you can change the pointer.

A: Arrays are implicitly convertible to a pointer to their first element.  That's why int* location = someArray; works.  Arrays are not themselves pointers though.
*(++someArray) is ill-formed because there is no ++ operator defined for arrays.  ++ is defined for pointers, but the result of the implicit conversion from array to pointer is a temporary (an rvalue), and the ++ operator is only defined for named objects (lvalues).
*++&someArray and *++(&someArray) are ill-formed, again, because the & operator returns an unnamed temporary pointer to the array.  Again, the ++ operator is only defined for lvalues.  Additionally, the type of &someArray is int (*)[4] (pointer to array of 4 ints), not int*.  Even for an lvalue, the ++ operator would not behave how you want on that type.

What would work here is to use the + operator instead.  *(someArray + 1) is perfectly well defined.  someArray decays to an int*, is shifted by one position, and that value dereferenced.  In fact, the subscript operator is defined in terms of the + operator.  someArray[n] is defined to be equivalent to *(someArray + n).


text:
Q: How to crop the long text as ... in ionic 3
I have a long tittle below image but I need to trim it  and the image is not properly aligned how do I make it appear clear while viewing

A: Best way to trim text from last is to create your custom pipe and use it.
import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
 name: 'trimLast'
})

export class TrimLastPipe implements PipeTransform {

transform(value: string, args: string[]): string {
    const limit = args.length > 0 ? parseInt(args[0], 10) : 20;
    const trail = args.length > 1 ? args[1] : '...';
    return value.length > limit ? value.substring(0, limit) + trail : value;
   }
}

and then register this custom pipe to module. you can use it in entire application.

A: CSS
.wrap-text {
  width: 250px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

HTML

Sachin Ramesh Tendulkar is a former Indian international cricketer and a former captain of the Indian national team.

working demo


text:
Q: Page navigation through ViewModel using MVVMLight in windows 8 I just started developing my brand new windows 8 application last week using mvvm light.I am familiar with mvvmlight WP7 navigation. How i can achieve the same in windows 8. Can any one suggest a better method to achieve the same in windows 8. I found a solution, where we override onnavigated events in vm and handle navigate to other page. But i think that method is obsolete. Any one please guide me with the proper implementation. Thanks in advance.

A: Read the article published in MSDN Magazine just recently by Laurent Bugnion himself on working with the MVVM Light Toolkit and Windows 8.
Towards the end of the article he explains exactly how to setup the NavigationService you need.
http://msdn.microsoft.com/en-us/magazine/jj651572.aspx

A: The NavigationService that was in MVVMLight has been migrated in a new package called WinRTBehaviors.  You can also get EventToCommand in Win8nl, both from nuget.  See my blog posted here:
Getting Started w/ MVVM Light for Windows 8, EventToCommand and Behaviors
http://blog.tattoocoder.com/2012/08/getting-started-w-windows-8-mvvm-light.html

A: I understand this is not the exact answer you may be looking for, but this may give you some ideas to explore.
In my case, I'm not using MVVMLight - but my own simple MVVM implementation. I use the BindableBase class (which comes with the default VS 2012 RC templates) for property notifications. I imagine, you could use MVVMLight to give you some of the infrastructure, which you can complement with something like the below.
For navigation, I define an interface that looks like:
public interface INavigationService
{
    void Navigate(Type type);
    void Navigate(Type type, object parameter);
    void EnsureNavigated(Type pageType, object parameter);

    bool CanGoBack { get; }
    bool CanGoForward { get; }
    void GoBack();
    void GoForward();

    IView CurrentView { get; }
}

And implement it as follows:
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Windows.UI.Xaml.Controls;

public class NavigationService : INavigationService
{
    private readonly Frame _frame;

    public NavigationService(Frame frame)
    {
        _frame = frame;
        _frame.Navigated += OnFrameNavigated;
    }

    private void OnFrameNavigated(object sender, Windows.UI.Xaml.Navigation.NavigationEventArgs e)
    {
        var view = e.Content as IView;
        if (view == null)
            return;

        var navMsg = new NavigationMessage()
        {
            Sender = this,
            NewView = view,
            Parameter = e.Parameter,
            NavigationMode = (int)e.NavigationMode
        };

        EventManager.Current.Publish(navMsg);

        //Anything that the parent needs to be notified should happen in of after this method
        var viewModel = view.ViewModel;
        if (viewModel != null)
            viewModel.Initialise(e.Parameter);
    }

    public void Navigate(Type pageType)
    {
        DisposePreviousView();
        _frame.Navigate(pageType);
    }

    public void Navigate(Type pageType, object parameter)
    {
        DisposePreviousView();
        _frame.Navigate(pageType, parameter);
    }

    private void DisposePreviousView()
    {
        var currentView = this.CurrentView;
        var currentViewDisposable = currentView as IDisposable;
        if (currentViewDisposable != null)
        {
            currentViewDisposable.Dispose();
            currentViewDisposable = null;
        } //view model is disposed in the view implementation
    }

    public void EnsureNavigated(Type pageType, object parameter)
    {
        var currentView = this.CurrentView;
        if (currentView == null || currentView.GetType() != pageType)
        {
            Navigate(pageType, parameter);
        }
    }

    public IView CurrentView
    {
        get { return _frame.Content as IView; }
    }

    public bool CanGoBack
    {
        get { return _frame != null && _frame.CanGoBack; }
    }

    public void GoBack()
    {
        // Use the navigation frame to return to the previous page
        if (_frame != null && _frame.CanGoBack) _frame.GoBack();
    }

    public bool CanGoForward
    {
        get { return _frame != null && _frame.CanGoForward; }
    }

    public void GoForward()
    {
        // Use the navigation frame to return to the previous page
        if (_frame != null && _frame.CanGoForward) _frame.GoForward();
    }

}

IView:
public interface IView : IDisposable
{
    IViewModel ViewModel { get; }
    void Refresh();
}

IViewModel:
public interface IViewModel : INotifyPropertyChanged, IDisposable
{
    void Initialise(object parameter);
    string ViewTitle { get; }
    void Refresh();
}

Finally, in the XAML page, define a Frame element:
<Frame x:Name="ContentFrame" />

And in the code-behind of the page: (this in the only ugly part in my opinion - but its hopefully not too bad):
var _navigationService = new NavigationService(this.ContentFrame);

You can now pass the _navigationService to the viewmodel. In my case I create the viewmodel in the code-behind of the page:
public HomePage()
{
    this.InitializeComponent();

    var _navigationService = NavigationService.GetFor(this.ContentFrame);

    DataContext = new HomePageViewModel(_navigationService);

}

Hope this helps.


text:
Q: $W = \{x\in l_0 : =0\}$ where $a=(1,\dfrac12,\dfrac13,...)$ and $l_0$ is sequences with finitely many non-zero terms. Show $W$ is separable Consider the inner product space $l_0$ consisting of all infinite sequences of complex numbers with only finitely many non-zero terms, with the inner product of $l^2$ (space of square summable sequences): $$<x,y>=x_1\overline y_1 +x_2\overline y_2 + ...$$ for $x = (x_1,x_2,...,x_n,...)$ and $y =(y_1,y_2,...,y_n,...)$.
Let $a=(1,\dfrac12,\dfrac13,\dfrac14,...)\in l^2$.
Then, $W = \{x\in l_0 : <x,a>=0\}$ is closed in $l^2$ and forms a Hilbert space.
Show that $W$ is separable. i.e. it has a countable orthonormal basis.

A: Let me show you that $W$ is not closed, by exhibiting a non-finite $x$ orthogonal to $a$.
Let
$$
x_n=\begin{cases}\dfrac1k,&\ n=k^2,\\ \\ -\dfrac{k^2+1}{k^3},&\ n=k^2+1,\\ \ \\0,&\ \text{otherwise}\end{cases}
$$
Then
$$
\sum_{n=1}^\infty |x_n|^2=\sum_{k=1}^\infty \dfrac{(k^2+1)^2}{k^6}-\dfrac1{k^2}=\sum_{k=1}\dfrac1{k^2}\,\left(\dfrac{(k^2+1)^2}{k^4}\right)\leq\sum_{k=1}^\infty\dfrac4{k^2}<\infty.
$$
If we write $x_n$ for the truncation of $x$ to its first $n$ entries (and make the rest zero), we have: for $n=k^2$,
$$
\langle x_n,a\rangle =\dfrac1k\,\dfrac1k+ \sum_{j=1}^{k-1}\dfrac1j\,\dfrac1{j^2}-\dfrac{j^2+1}{j^3}\,\dfrac1{j^2+1}=\dfrac1{k^2};
$$
and for $n\ne k^2$,
$$
\langle x_n,a\rangle = \sum_{j=1}^{k}\dfrac1j\,\dfrac1{j^2}-\dfrac{j^2+1}{j^3}\,\dfrac1{j^2+1}=0;
$$
In either case,
$$
|\langle x_n,a\rangle|\leq\dfrac1n.
$$
Then $\langle x,a\rangle=0$.
So $W$ is not closed. It is separable, being a subspace of $l_0$ that is separable.


text:
Q: Where I can find a place id on google maps I want to get the place images accord to the introductions here:
https://developers.google.com/places/documentation/details#PlaceDetailsRequests
According this document I need the "place id" of the place.
https://maps.googleapis.com/maps/api/place/details/json?placeid=ChIJN1t_tDeuEmsRUsoyG83frY4&key=AddYourOwnKeyHere

Where can I find the placeid

A: The place_id is in the SearchResults from any of the SearchRequests:
from the documentation:
{
   "html_attributions" : [],
   "results" : [
      {
         "geometry" : {
            "location" : {
               "lat" : -33.870775,
               "lng" : 151.199025
            }
         },
         "icon" : "http://maps.gstatic.com/mapfiles/place_api/icons/travel_agent-71.png",
         "id" : "21a0b251c9b8392186142c798263e289fe45b4aa",
         "name" : "Rhythmboat Cruises",
         "opening_hours" : {
            "open_now" : true
         },
         "photos" : [
            {
               "height" : 270,
               "html_attributions" : [],
               "photo_reference" : "CnRnAAAAF-LjFR1ZV93eawe1cU_3QNMCNmaGkowY7CnOf-kcNmPhNnPEG9W979jOuJJ1sGr75rhD5hqKzjD8vbMbSsRnq_Ni3ZIGfY6hKWmsOf3qHKJInkm4h55lzvLAXJVc-Rr4kI9O1tmIblblUpg2oqoq8RIQRMQJhFsTr5s9haxQ07EQHxoUO0ICubVFGYfJiMUPor1GnIWb5i8",
               "width" : 519
            }
         ],
         "place_id" : "ChIJyWEHuEmuEmsRm9hTkapTCrk",  // <----------------------------------------------
         "scope" : "GOOGLE",
         "alt_ids" : [
            {
               "place_id" : "D9iJyWEHuEmuEmsRm9hTkapTCrk",
               "scope" : "APP"
            }
         ],

A: The above solution works in most cases but sometimes fails when you have some individuals using the same address as a business. In case you have exhausted the options from the API and manual search provided in the Google documentation Here Or here
You can use the manual suggestion provided at this page which has always worked for me https://www.launch2success.com/guide/cant-find-google-places-id-trick-finding-google-places-id/

A: You should be able to find a place ID here:
https://developers.google.com/places/place-id#find-id

A: You may want a Place ID Text search by searching the place name.
Your sample request may look like
https://maps.googleapis.com/maps/api/place/textsearch/json?query=fish+market+sydney&key="YOUR_API_KEY"
You will find the "place_id" in the return JSON String.

A: Maybe try the TextSeach option or else try the Nearbysearch option which I have mentioned below maybe it works for you.
1.https://maps.googleapis.com/maps/api/place/nearbysearch/json?query={address}&key={_apiConfig.Key}
2.https://maps.googleapis.com/maps/api/place/textsearch/json?query={address}&key={_apiConfig.Key}
In response, you will get all information with a place id which is help full.


text:
Q: how do I make a rectangular progress bar that moves around a rectangular screen of a wearable device? I want to make a custom progress bar that is rectangular in shape. meaning Similar to how we can make a round or circular progress bar that can fit on a round screen of a wearable device, I want one that can fit on a rectangular or square watch face.
something like this:

the only difference it would be around a square watch face like this:

So it is similar to a circular progressbar like this:

This is what I achieved so far:
    <?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@android:id/progress"
        android:top="16dp"
        android:bottom="16dp">
        <layer-list>
            <item>
                <rotate
                    android:fromDegrees="90"
                    android:pivotX="50%"
                    android:pivotY="50%"
                    android:toDegrees="270">
                    <shape android:shape="rectangle">
                        <size
                            android:width="100dp"
                            android:height="100dp" />
                        <stroke
                            android:width="2dp"
                            android:color="@color/mit_light_grey" />
                    </shape>
                </rotate>
            </item>
        </layer-list>
    </item>
</layer-list>

but when this file is used in the progressDrawable attribute it simply draws a rectangular shape that rotates. How do I get it to behave as a progressbar?
In short I want the progressbar to display the progress around a rectangular or square screen. I am aware of a library that does that but it is among the libraries that require JCenter which is now deprecated as of March 31st 2021. So I'm trying to avoid it.


text:
Q: remove linebreaks created by div with map-information I got a little problem with a map I'm creating.
I got a map wich i add pins to with css-coordinates.
The problem is that for each div I create it adds another linebreak or two beneath the map.
Since I got roughly 130 pins to add, i figured it might become a problem later on.
Here is my code:
        //Map

 //Pin #1

 //pin 2... and so on.

Is there a way to remove the spacing added by these div-tags, I were playing around with display:none and CSS-div-props / maxheight !important.... but nothing seems to do what I want without removing my pins.
In advance, thanks a bunch :)

A: Hey friend I am also trying to develop a map as you, I first ask you what you want to develop for android platform if it is easier, install a android SDK on your machine, and low google maps that will help you and greatly facilitate a good development, then it's only you begin to develop your pins on the maps points eg here is by bus, taxi points here is, here is a hospital or a school, here is highway think your thinking is this, then looking to download any maps that already half done and you will just have to do the job demarcations desired

A: Figured it out, it was just as simple as adding another div and set the height-property of this to zero:
 //Map

 //Pin #1

 //pin 2... and so on.

And css it:
#sneaky     {
            height:0px;
            }


text:
Q: Try-Catch Statement Trouble So i've got this section of code in the screenshot below that are causing Type IOExceptions.
http://southwestdesign.org.uk/Code.jpg
I'm told that I need to wrap it in a try-catch block, wrapping each invididual block with a try catch eliminates the errors, but force closes on Android. Could someone please point me in the right direction?
@Override
    public void onStart() {
        HttpClient client = new DefaultHttpClient();
        HttpGet request = new HttpGet("http://1.php");
        HttpResponse response = client.execute(request);
        BufferedReader rd = new BufferedReader
        (new InputStreamReader(response.getEntity().getContent()));
        TextView textView = (TextView) findViewById(R.id.TextView1);
        String line = "";
        while ((line = rd.readLine()) != null) {
            textView.append(line);
        }
    }

Thanks guys.

A: You seem to do Network IO on the UI thread, which is a bad idea. So since Android 2.3, the system "catches" this and kills the process.
You should put the
 HttpResponse response = client.execute(request);

into a background thread e.g. by using an AsyncTask.

A: try {

   //do something here
   //call method

}catch (IOException ioe){

// do something else
// log ioe

}

A: it should be something like this:
@Override
    public void onStart() {

   try {
    HttpClient client = new DefaultHttpClient();
    HttpGet request = new HttpGet("http://1.php");
    HttpResponse response = client.execute(request);
    BufferedReader rd = new BufferedReader
    (new InputStreamReader(response.getEntity().getContent()));
    TextView textView = (TextView) findViewById(R.id.TextView1);
    String line = "";
    while ((line = rd.readLine()) != null) {
        textView.append(line);
    }

    }catch (IOException ex){
    }
}

more preferably use AsyncTask to get this done on a separate thread.


text:
Q: Subtracting small data.frame from large data.frame by grouped a variable I have got a very large data set
  mdf <- data.frame (sn = 1:40, var = rep(1:10, 4), block = rep(1:4, each = 10),
yld = c(1:40))

I have small data set
blockdf <- data.frame(block = 1:4, yld = c(10, 20, 30, 40)) # block means

All variables in both dataset except yld are factors.
I want to subtract block means (blockdf$yld) form each mdf$yld dataset, such that the block effects should correspond to block in mdf dataframe.
for example: value 10 will be substracted from all var within
   first block yld in mdf
                   20  -  second block yld in mdf

and so on

Please note that I might have sometime unbalance number of var within the reps. So I want to write it in such way that it can handle unbalance situation

A: This should work
newdf <- merge(x=mdf, y=blockdf, by="block", suffixes = c("",".blockmean"))
newdf$newvr <- newdf$yld-newdf$yld.blockmean
print(newdf, row.names=FALSE)
  block sn var yld yld.blockmean newvr
 1  1   1   1            10    -9
 1  2   2   2            10    -8
 1  3   3   3            10    -7
 1  4   4   4            10    -6
 1  5   5   5            10    -5
 1  6   6   6            10    -4
 1  7   7   7            10    -3
 1  8   8   8            10    -2
 1  9   9   9            10    -1
 1 10  10  10            10     0
 2 11   1  11            20    -9
 2 12   2  12            20    -8
...........................

A: This should do the trick
block_match <- match(mdf$block, blockdf$block)
transform(mdf, yld = yld - blockdf[block_match, 'yld'])


text:
Q: WPF: How to make textblock fire key event? TextBlock has KeyDown and KeyUp event, but it's never fired. Is there a way to make it happen?  I just need to detect if any key is pressed.

A: First of all you will need to set the Focusable Property of your TextBlock to True, This will allow you to Tab to the Item but not Click to select it, but if you handle the MouseDown Event you can manualy set Focus to your TextBlock.
MainWindow.xaml
<Window x:Class="WpfApplication1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
    <Grid >
       <TextBlock Name="tb1"  Height="30" Width ="100" IsEnabled="True"  Focusable="True" KeyDown="tb1_KeyDown" MouseDown="tb1_MouseDown">Hello World</TextBlock>
    </Grid>
</Window>

MainWindow.xaml.cs
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void tb1_KeyDown(object sender, KeyEventArgs e)
    {
        tb1.Background = Brushes.Blue;
    }

    private void button1_Click(object sender, RoutedEventArgs e)
    {
        tb1.Focus();
    }

    private void tb1_MouseDown(object sender, MouseButtonEventArgs e)
    {
        tb1.Focus();
    }
}


text:
Q: Gridview combine autogenerated fields and template fields I have several sqldatasources for my gridview. All of the columns are autogenerated. However they all have some consistent fields and I'd like to make those fields template fields so I can modify the edit template for them such as adding a drop down menu. Is this possible? If so, how? :-D Thanks!

A: To replace specific autogenerated columns with template columns, simply define the template column and hide the autogenerated column in code.  The autogenerated columns will by default appear after your template columns, so if you want them to be appropriately placed, you can swap the output in code as well.
In this example I am altering the output for a gridview that has two template columns and two autogenerated columns for a total of 4.  I want to replace the last of my autogenerated colums (index 3) with a template column (index 1), but I want one of my autogenerated columns (index 2) to be further to the left, so I switch it with a template column (index 1).
Private Sub gv_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gv.RowDataBound
    'hide Column 3'
    e.Row.Cells(3).Visible = False

    'Swap the results for Column 1 and Column 2'
    Dim swap = e.Row.Cells(1).Text
    e.Row.Cells(1).Text = e.Row.Cells(2).Text
    e.Row.Cells(2).Text = swap
End Sub

This is fairly simple and doesn't require any extra classes.


text:
Q: Outlook AddIn detecting this.Application.NewMail but not seeing it as unread Morning,
I have written an Outlook add outlook-addin in that detects a new mail then it should do some processing on all unread mail items, which should include the mail item that just arrived in the inbox as well as any others.

The issue is that my code fires on this event: this.Application.NewMail
Then it restricts the list of inbox items to be only the unread ones.
(obviously it makes sense the email that just arrived should be classed as unread)
However, the email that just arrived is not part of the unread collection.
The email that just arrived only gets picked up the next time an email arrives and this whole cycle is repeated, meaning the second email is not picked up until a 3rd email arrives.
I can't afford to have an email sitting then in an unprocessed state.
Any help would be greatly appreciated.

A: Do not use the NewMail event - use NewMailEx instead. It passes the entry ids of the new emails separated by "," (according o the documentation). In practice, Outlook never passes multiple entryids, but rather fires NewMailEx for each new message.
Use the entry id to call Namespace.GetItemFromID.


text:
Q: How do I send arbitrary JSON data, with a custom header, to a REST server? TL;DR -- How do I send a JSON string to a REST host with an auth header?  I've tried 3 different approaches found one that works with anonymous types.  Why can't I use anonymous types?  I need to set a variable called "Group-Name", and a hyphen isn't a valid C# identifier.
Background
I need to POST JSON but am unable to get the body and the content type correct
Function #1 - Works with anonymous types
The content type and data is correct,  but I don't want to use anonymous types.  I want to use a string
  static void PostData(string restURLBase, string RESTUrl, string AuthToken, string postBody)
    {
        HttpClient client = new HttpClient();
        client.BaseAddress = new Uri(restURLBase);
        client.DefaultRequestHeaders.Add("Auth-Token", AuthToken);
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        // StringContent content = new StringContent(postBody);

        var test1 = "data1";
        var test2 = "data2";
        var test3 = "data3";

        var response = client.PostAsJsonAsync(RESTUrl, new { test1, test2, test3}).Result;  // Blocking call!
        if (!response.IsSuccessStatusCode)
        {
            Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
            return;
        }
    }

Output #1
Content type and data is correct when using AnonymousTypes + PostAsJsonAsync, but I don't want to use anonymous types.
POST https://api.dynect.net/REST/Zone/ABCqqqqqqqqqqqqYYYYYtes3ss.com HTTP/1.1
Auth-Token: --- REDACTED -----
Accept: application/json
Content-Type: application/json; charset=utf-8
Host: api.dynect.net
Content-Length: 49
Expect: 100-continue

{"test1":"data1","test2":"data2","test3":"data3"}

Function #2 - Doesn't work as expected
Take a string and put it into a StringContent object.  This has a side effect of changing the content type.
  static void PostData(string restURLBase, string RESTUrl, string AuthToken, string postBody)
    {
        HttpClient client = new HttpClient();
        client.BaseAddress = new Uri(restURLBase);
        client.DefaultRequestHeaders.Add("Auth-Token", AuthToken);
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        StringContent content = new StringContent(postBody);

        var response = client.PostAsync(RESTUrl, content).Result;  // Blocking call!
        if (!response.IsSuccessStatusCode)
        {
            Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
            return;
        }
    }

Output #2
Content type is wrong when using StringContent + PostAsync
POST https://api.dynect.net/REST/Zone/ABCqqqqqqqqqqqqYYYYYtes3ss.com HTTP/1.1
Auth-Token: ---- REDACTED -------
Accept: application/json                      // CORRECT
Content-Type: text/plain; charset=utf-8       // WRONG!!!
Host: api.dynect.net
Content-Length: 100
Expect: 100-continue

{"rdata" : ["rname" : "dynect.nfp.com", "zone" : "ABCqqqqqqqqqqqqYYYYYtes3ss.com"], "ttl" : "43200"}
        // ^^ THIS IS CORRECT

Function #3 - Doesn't work as expected
Since I know PostAsJsonAsync sets the contentType correctly, lets use that method.  (doesn't work)
    static void PostData(string restURLBase, string RESTUrl, string AuthToken, string postBody)
    {
        HttpClient client = new HttpClient();
        client.BaseAddress = new Uri(restURLBase);
        client.DefaultRequestHeaders.Add("Auth-Token", AuthToken);
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        StringContent content = new StringContent(postBody);

        var response = client.PostAsJsonAsync(RESTUrl, content).Result;  // Blocking call!
        if (!response.IsSuccessStatusCode)
        {
            Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
            return;
        }
    }

Output #3
Content type is correct, POST body is wrong when using StringContent + PostAsJsonAsync
POST https://api.dynect.net/REST/Zone/ABCqqqqqqqqqqqqYYYYYtes3ss.com HTTP/1.1
Auth-Token: -- REDACTED ---
Accept: application/json
Content-Type: application/json; charset=utf-8
Host: api.dynect.net
Content-Length: 74
Expect: 100-continue

{"Headers":[{"Key":"Content-Type","Value":["text/plain; charset=utf-8"]}]}

Question
All I want to do is send JSON as a string, or dynamic object defined at runtime, to a server, with HTTP content type correct, and with a special 'Auth-Token' header.
Any example, if not using WebAPI, such as servicestack, or anything else is cool.

A: /// <summary>
    /// Creates a new instance of the <see cref="T:System.Net.Http.StringContent"/> class.
    /// </summary>
    /// <param name="content">The content used to initialize the <see cref="T:System.Net.Http.StringContent"/>.</param><param name="encoding">The encoding to use for the content.</param><param name="mediaType">The media type to use for the content.</param>
    [__DynamicallyInvokable]
    public StringContent(string content, Encoding encoding, string mediaType)
      : base(StringContent.GetContentByteArray(content, encoding))
    {
      this.Headers.ContentType = new MediaTypeHeaderValue(mediaType == null ? "text/plain" : mediaType)
      {
        CharSet = encoding == null ? HttpContent.DefaultStringEncoding.WebName : encoding.WebName
      };
    }

It's constructor of StringContent. Looks like that you should specify appropriate Encoding and mediaType

A: You can't directly setup an instance of HttpContent, because it is an abstract class. You need to use one of the sub-classes, depending on your need. Most likely StringContent, which lets you set the string value of the response, the encoding, and the media type in the constructor: http://msdn.microsoft.com/en-us/library/system.net.http.stringcontent.aspx
Answer from How do I set up HttpContent for my HttpClient PostAsync second parameter?


text:
Q: Integer or list to list I'm trying to convert a value that may be formatted as an integer or a list into a list.
For example
      60 --> [60]
    [60] --> [60]
[55, 65] --> [55, 65]

If I just put the variable in brackets, it creates a 1D list from an integer, but creates a nested list if it already is a list. There are lots of ways to do this with if or try statements, but there must be an easy one-liner I'm overlooking?
The following function returns the desired value, but is a recursive function really the best way to do this?
def flatten(v):
    return flatten(v[0]) + (flatten(v[1:]) if len(v) > 1 else []) \
    if type(v) is list else [v]

A: Something of this sort should do:
def func(obj):
     return obj if isinstance(obj, list) else [obj]


text:
Q: Run django-admin I'm new to django and I would like to follow this tutorial: https://docs.djangoproject.com/en/2.1/intro/tutorial01/
Unfortunately, django-admin is not in my path.
When I try to run the django-admin.py script directly, I have the following error:
$ /usr/local/lib/python3.7/site-packages/django/bin/django-admin.py
Traceback (most recent call last):
  File "/usr/local/lib/python3.7/site-packages/django/bin/django-admin.py", line 2, in <module>
    from django.core import management
ImportError: No module named django.core

Here is my configuration:

*

*System: macOS 10.13

*Python: 3.7.0 (installed via Homebrew

*Django: 2.1.4

What am I doing wrong?

A: I think You don't install django correctly. If you are highly new in django then follow these steps to setup your clean and new project environment
Create your project folder
mkdir myProject

Open this Project Folder
cd myProject

Create virtual environment
python3 -m venv env

Now, active this virtual environment
source env/bin/activate

It's time to install the Django
pip install django

Create your first project
django-admin startproject myProject

Open this Project
 cd myProject

Open your server to check it either it's work successfully or not
python manage.py runserver

A: First check if django is installed by running python -c "import django". If that is successful check if django-admin command is in your python path. If you are using a virtual environment check under virtual environment/bin/. If there is no file such as django-admin then the first solution would be to try reinstalling django. Same case if you are working outside a virtual environment.
If none of the above solves it then check  if you have both python 2 and 3. If you do check whether .py files are being associated to python 2 instead of python3.


text:
Q: How to resolve React Native Error: task: react-native-maps:compileDebugJavaWithJavac FAILED my project was working but when i installed react-native-maps and run react-native run-android i got this error:
(I refer https://github.com/react-native-community/react-native-maps/blob/master/docs/installation.md and follow all steps)
> Task :react-native-maps:compileDebugJavaWithJavac FAILED
E:\ReactNative-Projects\gardeshgaran\node_modules\react-native-maps\lib\android\src\main\java\com\airbnb\android\react\maps\AirMapView.java:12: error: package androidx.core.view does not exist
import androidx.core.view.GestureDetectorCompat;
                         ^
E:\ReactNative-Projects\gardeshgaran\node_modules\react-native-maps\lib\android\src\main\java\com\airbnb\android\react\maps\AirMapView.java:13: error: package androidx.core.view does not exist
import androidx.core.view.MotionEventCompat;
                         ^
E:\ReactNative-Projects\gardeshgaran\node_modules\react-native-maps\lib\android\src\main\java\com\airbnb\android\react\maps\AirMapView.java:73: error: package androidx.core.content does not exist
import static androidx.core.content.PermissionChecker.checkSelfPermission;
                                   ^
E:\ReactNative-Projects\gardeshgaran\node_modules\react-native-maps\lib\android\src\main\java\com\airbnb\android\react\maps\AirMapView.java:73: error: static import only from classes and interfaces
import static androidx.core.content.PermissionChecker.checkSelfPermission;
^
E:\ReactNative-Projects\gardeshgaran\node_modules\react-native-maps\lib\android\src\main\java\com\airbnb\android\react\maps\AirMapView.java:108: error: cannot find symbol
  private final GestureDetectorCompat gestureDetector;
                ^
  symbol:   class GestureDetectorCompat
  location: class AirMapView
E:\ReactNative-Projects\gardeshgaran\node_modules\react-native-maps\lib\android\src\main\java\com\airbnb\android\react\maps\AirMapView.java:165: error: cannot find symbol
        new GestureDetectorCompat(reactContext, new GestureDetector.SimpleOnGestureListener() {
            ^
  symbol:   class GestureDetectorCompat
  location: class AirMapView
E:\ReactNative-Projects\gardeshgaran\node_modules\react-native-maps\lib\android\src\main\java\com\airbnb\android\react\maps\AirMapView.java:421: error: cannot find symbol
    return checkSelfPermission(getContext(), PERMISSIONS[0]) == PackageManager.PERMISSION_GRANTED ||
           ^
  symbol:   method checkSelfPermission(Context,String)
  location: class AirMapView
E:\ReactNative-Projects\gardeshgaran\node_modules\react-native-maps\lib\android\src\main\java\com\airbnb\android\react\maps\AirMapView.java:422: error: cannot find symbol
        checkSelfPermission(getContext(), PERMISSIONS[1]) == PackageManager.PERMISSION_GRANTED;
        ^
  symbol:   method checkSelfPermission(Context,String)
  location: class AirMapView
E:\ReactNative-Projects\gardeshgaran\node_modules\react-native-maps\lib\android\src\main\java\com\airbnb\android\react\maps\AirMapView.java:949: error: cannot find symbol
    int action = MotionEventCompat.getActionMasked(ev);
                 ^
  symbol:   variable MotionEventCompat
  location: class AirMapView
Note: Some input files use or override a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
Note: Some input files use unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
9 errors

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':react-native-maps:compileDebugJavaWithJavac'.
> Compilation failed; see the compiler error output for details.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

Deprecated Gradle features were used in this build, making it incompatible with Gradle 6.0.
Use '--warning-mode all' to show the individual deprecation warnings.
See https://docs.gradle.org/5.4.1/userguide/command_line_interface.html#sec:command_line_warnings

BUILD FAILED in 2s
33 actionable tasks: 1 executed, 32 up-to-date
error Could not install the app on the device, read the error above for details.
Make sure you have an Android emulator running or a device connected and have
set up your Android development environment:
https://facebook.github.io/react-native/docs/getting-started.html
error Command failed: gradlew.bat app:installDebug. Run CLI with --verbose flag for more details.

My Android->build.gradle:
buildscript {
    ext {
        buildToolsVersion = "28.0.3"
        minSdkVersion = 16
        compileSdkVersion = 28
        targetSdkVersion = 28
        supportLibVersion = "28.0.0"
        playServicesVersion = "16.1.0"
        androidMapsUtilsVersion = "0.5"
    }
    repositories {
        google()
        jcenter()
        mavenCentral()

    }
    dependencies {
        classpath("com.android.tools.build:gradle:3.4.0")

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        mavenLocal()
        google()
        jcenter()
        maven {
            // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
            url "$rootDir/../node_modules/react-native/android"
        }
        maven {
            url "https://maven.google.com"
        }
    }
}

My App->build.gradle:
android {
    compileSdkVersion rootProject.ext.compileSdkVersion

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    defaultConfig {
        applicationId "com.gardeshgaran"
        minSdkVersion rootProject.ext.minSdkVersion
        targetSdkVersion rootProject.ext.targetSdkVersion
        versionCode 1
        versionName "1.0"
    }
    signingConfigs {

       release {

           if (project.hasProperty('MYAPP_RELEASE_STORE_FILE')) {

               storeFile file(MYAPP_RELEASE_STORE_FILE)

               storePassword MYAPP_RELEASE_STORE_PASSWORD

               keyAlias MYAPP_RELEASE_KEY_ALIAS

               keyPassword MYAPP_RELEASE_KEY_PASSWORD

           }

       }

   }
    splits {
        abi {
            reset()
            enable enableSeparateBuildPerCPUArchitecture
            universalApk false  // If true, also generate a universal APK
            include "armeabi-v7a", "x86", "arm64-v8a", "x86_64"
        }
    }
    buildTypes {
        release {
            minifyEnabled enableProguardInReleaseBuilds
            proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
            signingConfig signingConfigs.release
        }
    }
    // applicationVariants are e.g. debug, release
    applicationVariants.all { variant ->
        variant.outputs.each { output ->
            // For each separate APK per architecture, set a unique version code as described here:
            // http://tools.android.com/tech-docs/new-build-system/user-guide/apk-splits
            def versionCodes = ["armeabi-v7a":1, "x86":2, "arm64-v8a": 3, "x86_64": 4]
            def abi = output.getFilter(OutputFile.ABI)
            if (abi != null) {  // null for the universal-debug, universal-release variants
                output.versionCodeOverride =
                        versionCodes.get(abi) * 1048576 + defaultConfig.versionCode
            }
        }
    }
}

dependencies {
    implementation project(':react-native-linear-gradient')
    implementation project(':react-native-gesture-handler')
    implementation fileTree(dir: "libs", include: ["*.jar"])
    implementation "com.android.support:appcompat-v7:${rootProject.ext.supportLibVersion}"
    implementation "com.facebook.react:react-native:+"  // From node_modules

    implementation project(':react-native-maps')

}

// Run this once to be able to run the application with BUCK
// puts all compile dependencies into folder libs for BUCK to use
task copyDownloadableDepsToLibs(type: Copy) {
    from configurations.compile
    into 'libs'
}

my AndroidManifest.xml:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="com.gardeshgaran">

    <uses-permission android:name="android.permission.INTERNET" />

    <application
      android:name=".MainApplication"
      android:label="@string/app_name"
      android:icon="@mipmap/ic_launcher"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:allowBackup="false"
      android:theme="@style/AppTheme">

      <meta-data
      android:name="com.google.android.geo.API_KEY"
      android:value="*****"
      />

      <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
        android:windowSoftInputMode="adjustResize">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
      </activity>
      <activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />
    </application>

</manifest>

please help me solve this error!


text:
Q: C++, best practices, int or size_t?
Possible Duplicate:
When to use std::size_t?

hello.
Assuming usage patterns are the same (i.e. no negative numbers), which is preferable to use for various indexes, int or size_t type?
Is there performance difference in your experience on 64-bit Intel between the two?
Thank you

A: It depends on what you are doing. If you are iterating over a vector, then use std::size_t:
for (std::size_t i = 0; i < vec.size(); i++) {
   // do something with vec[i]
}

However, beware of coding errors such as:
for (std::size_t i = 99; i >= 0; i--) {
   // This is an infinite loop
}

If you are just doing a loop, you might want to use just a plain int because of the situation above. There should be no performance difference between using int and std::size_t. If you need an exact size, then you should use neither int nor size_t, but rather the types defined in stdint.h.

A: size_t is the type that should be used for array indexing when you work with a relatively generic arrays. I.e. when you have just an array of abstract chars, ints or something else.
When you are working with a specific array, i.e. an array that contains some elements specific for your application, you should normally already have a "type of choice" to count or to index the entities of that type in your application. That's the type you should use. For example, if some array contains the records for company employees, then you should already have a "type of choice" in your program that you use to designate the "quantity of employees". That's the type you should use for indexing arrays of employee records. It could be unsigned int, it could be employee_count_t or something like that. Using a naked size_t for that purpose is a design error.
Note also, that size_t is a type not immediately intended for array indexing. It is a type intended to represent the size of the largest object in the program. It "works" for arrays by transitivity: arrays are objects, hence size_t is always enough to index an array. However, when you design a program it makes more sense to think in terms of generic containers, instead of thinking in terms of specific arrays. Today it might be an array, tomorrow you might have to switch to a linked list or a tree instead. In general case, the range of size_t is not sufficient to represent the number of elements in an abstract container, which is why size_t in such cases is not a good choice.

A: The types aren't different in the sense you're implying, and generally int is 32bits, and size_t is the width of the platform word (32-64 bits). I'd suggest you use size_t when dealing with files, buffers, and anything else that might describe an area of memory or a buffer.
Furthermore you should note that int is signed, while size_t is not.
Finally, int was historically used where size_t should be used now. However int is still useful in it's own right for other purposes.

A: size_t or ptrdiff_t.  int might not be enough to access all the elements of an array.


text:
Q: Interrogate tempo.js objects for existence I'm using tempo.js 2.0 and I noticed after my Ajax requests - the response fails to re-render correctly, someone on this site pointed out, tempo.js renders fine if you don't prepare the container again, I tested and they are correct.  This works:
var template = null;

function populate(){
    if (template == null){
        template = Tempo.prepare("myDivId");
    }
    template.render(data);
}

Anyone know how I can interrogate some value in the DOM or Tempo so I can remove my global variable? var template = null;
The only thing I can think of is using jQuery and testing if tempo el type expressions exists {{ someValue }}
I tried reading the code and I don't understand javascript enough.
Big thanks!


text:
Q: Python pip install PythonMagick (Pycharm) I'm trying to install package "PythonMagick" in pycharm but I've been getting this error
EDIT: I'm trying to run doc2text but I get "ModuleNotFoundError: No module named 'PythonMagick'"
ERROR: Could not find a version that satisfies the requirement PythonMagick (from versions: none)

DEPRECATION: The -b/--build/--build-dir/--build-directory option is
deprecated. pip 20.3 will remove support for this functionality. A
possible replacement is use the TMPDIR/TEMP/TMP environment variable,
possibly combined with --no-clean. You can find discussion regarding
this at https://github.com/pypa/pip/issues/8333. ERROR: Could not find
a version that satisfies the requirement PythonMagick (from versions:
none) ERROR: No matching distribution found for PythonMagick

Has anyone had this before and can help me solve it :) ?
Thank you I appreciate any help


text:
Q: MVC: Member and Member.Items.add(Item) doesn't get saved The item doesn't get saved. Only member gets saved.
When I debug [AcceptVerbs(HttpVerbs.Post)]
 the information is empty in the Item. Why? How should I solve this?
When it  goes to the post method of create, then the ITEM dosen't follow the member. and the ITEMS doesn't get saved. I debug the information and there are 0 Number items.  Why doesn't it save Items also when I press the button.
Only the member item gets saved.
public class ClassifiedsFormViewModel
{

    IClassifiedsRepository classifiedsRepository = new ClassifiedsRepository();
    public Member Member { get; private set; }
    public SelectList Municipalities { get; private set; }

    public ClassifiedsFormViewModel(Member member)
    {
        Member = member;
        Municipalities = new SelectList(classifiedsRepository.GetMunicipalities()
                                 ,"MunicipalityId", "Municipality1");
    }

}

    public ActionResult Create()
    {
        Member member = new Member();
        Item item = new Item();
        member.Items.Add(item);

        return View(new ClassifiedsFormViewModel(member));
    }

    //
    // POST: /Items/Create

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Create(Member member)
    {

        if (ModelState.IsValid)
        {

            try
            {
                classifiedsRepository.Add(member);
                classifiedsRepository.Save();

                return RedirectToAction("Create", new { id = member.MemberId });
            }
            catch
            {
                ModelState.AddModelErrors(member.GetRuleViolations());
            }
        }

        return View(new ClassifiedsFormViewModel(member));
    }
}

A: The member which is passed into the create function is actually databound from your form.  In order to ensure that it works you have to have the elements on the form named the same as the properties in your member.  So if you have something called memberName in Member you would need to name the field in the view the same thing.
<form ...
  <input type="text" name="memberName"/>
...
</form>

Edit:
After reading your comments I'm still not 100% what you're looking to do.  IF you want the member you've created to have an item then move the item creation code down to the second Create.  What you have passes a member with an item through to a strongly typed view.  The member with the item is never persisted so it won't come back to the controller and won't make it into the model.

A:     public ActionResult Create()
    {
        Member member = new Member();
        Item item = new Item();
        member.Items.Add(item);

        return View(new ClassifiedsFormViewModel(member));
    }


text:
Q: Data Types with PIC18? Which data type do I use to store the following value ?
Value: 86400
code:
int d[6];
unsigned int all;
d[0] = 8;
d[1] = 6;
d[2] = 4;
d[3] = 0;
d[4] = 0;

all =  10000*d[0] + 1000*d[1] + 100*d[2] + 10*d[3] +  d[4];
printf("%u", all);

If I copy this code to CodeBlocks, it works fine. However, on MPLAB C18 compiler I would get a different result.
CodeBlock Output: 86400
MPLAB Output: 20864
How do you fix it? Thank you!

A: The type int is not guaranteed to be 32 bits, it may be e.g. 16 bits (i.e. have values from 0 to 65535 for unsigned int). This is the case here. You need to use the long type here.


text:
Q: How to add a where filter to a path in IBM API Connect designer I am using IBM API Connect designer and I want to add a filter to one of my paths. Specifically, I have the following API endpoint path:
http://127.0.0.1:4001/api/testusers
It relates to a table in my mySQL database.
I already have the full API built, but want to allow the API consumer to do a simple restful search: i.e.
http://127.0.0.1:4001/api/testusers?userName=Martin
However, I can't work out how to do it.  I have looked over the documentation:
http://www.ibm.com/support/knowledgecenter/SSMNED_5.0.0/com.ibm.apic.toolkit.doc/task_apionprem_configure_operation.html
I have tried to log a question on their impossible set of forums, which has crashed each time.
I think it must be pretty straight forward to add from within the designer. However, I can't work it out or perhaps I have added it and can't work out the right path to use. But, either way, it doesn't work.  Any direction is most appreciated.
The designer setup is given here:

A: There are a couple of options available.
Since you talk about connectivity to a database, I'm going to assume that you are using the Designer's model and datasource features as well (feel free to correct if I'm misunderstanding).
These components are provided by the LoopBack framework. So, without doing any custom coding, you should be able to add a filter clause to your API call as a query param in the format filter[where][property]=value.
So, in your case, it might look like: http://127.0.0.1:4001/api/testusers?filter[where][userName]=Martin
More detail here: http://loopback.io/doc/en/lb2/Where-filter.html
If you wanted to make it look more like your example, then you would need to write custom code in your underlying model. It's not difficult, but does have some learning curve. There's plenty of docs on that here: http://loopback.io/doc/en/lb2/Remote-methods.html and http://loopback.io/doc/en/lb2/Creating-models.html


text:
Q: Remove the dot after section number in ToC [without any package] I'm using the book class and I want to remove the final dot in the section number, i.e, I have
1. Chapter Name
1.1. Section Name
1.1.1. Subsection Name
1.1.1.1. Subsubsection Name

I want
 1. Chapter Name
 1.1 Section Name
 1.1.1 Subsection Name
 1.1.1.1 Subsubsection Name

Looking for similar post, I found [How remove dot after section number in ToC with babel's spanish? and although the solution is very good I still have a problem: when I use the code es-nosectiondot the dot of the chapter disappears in the ToC, same is for LoF and LoT, i.e, Figure 1 (Table 1) instead Figure 1. (Table 1.), so, following the post I use the code \def\numberline#1{\hb@xt@\@tempdima{#1\if&#1&\else.\fi\hfil}}, which is useful because it solves the previous problem, but now the dot of the section, subsection and subsubsection appears in the ToC, i.e,
1. Chapter Name
1.1. Section Name
1.1.1. Subsection Name
1.1.1.1. Subsubsection Name

This is my MWE:
\documentclass{book}

\usepackage[spanish,es-nosectiondot]{babel}

\setcounter{secnumdepth}{3}
\setcounter{tocdepth}{3}
\counterwithout{figure}{chapter}
\counterwithout{table}{chapter}
\addto\captionsspanish{%
    \renewcommand{\tablename}%
    {Tabla}%
}

\makeatletter
 %%add prefix Figura/Tabla in LoF/LoT
 \long\def\@caption#1[#2]#3{%
  \par
  \addcontentsline{\csname ext@#1\endcsname}{#1}%
    {\protect\numberline{\csname fnum@#1\endcsname}{\ignorespaces #2}}%
  \begingroup
    \@parboxrestore
    \if@minipage
      \@setminipage
    \fi
    \normalsize
    \@makecaption{\csname fnum@#1\endcsname}{\ignorespaces #3}\par
  \endgroup}
  \renewcommand*\l@figure{\@dottedtocline{1}{0em}{5em}}%
  \let\l@table\l@figure
  %%egreg's code
 \def\numberline#1{\hb@xt@\@tempdima{#1\if&#1&\else.\fi\hfil}}
\makeatother

\begin{document}

\tableofcontents
\listoffigures
\listoftables

\chapter{Chapter}
\section{Section}
\begin{table}[h]
\caption{Some table}
\centering abc
\end{table}

\begin{figure}[h]
\caption{A figure}
\centering xyz
\end{figure}
\subsection{Subsection}
\subsubsection{Subsubsection}

\end{document}

I want
ToC
1. Chapter
1.1 Section
1.1.1 Subsection
1.1.1.1 Subsubsection

LoT
Table 1.

LoF
Figure 1.

1.1 The Section
 Content
1.1.1 The Subsection
 Content
1.1.1.1 The Subsubsection
 Content

A: (I rewrote this answer from scratch after gaining a better understanding of the OP's formatting objectives.
I can't provide an answer that doesn't rely on external LaTeX packages. However, since the caption and tocloft packages have been around quite a few years, are very well debugged, and are known to work well with the book document class, I'm not going to make any apologies for employing these two packages.
I suggest you (a) keep using the instruction \usepackage[spanish,es-nosectiondot]{babel}, (b) employ the caption to change the label separator from : ("colon") to . (period) in the body of the document, and (c) employ the tocloft package to modify the appearance of figure and table entries in the LoF and LoT, respectively. You can ditch the code chunk between \makeatletter and \makeatother in your MWE, though.

\documentclass{book}
\usepackage[spanish,es-nosectiondot]{babel}
\addto\captionsspanish{%
   \renewcommand{\tablename}{Tabla}
   \renewcommand{\listtablename}{\'Indice de tablas} % do you need this?
}

\setcounter{secnumdepth}{3}
\setcounter{tocdepth}{3}
\counterwithout{figure}{chapter}
\counterwithout{table}{chapter}

%% modify the separator between caption numbers and text
\usepackage{caption}
\captionsetup{labelsep=period,skip=0.333\baselineskip}

\usepackage[titles]{tocloft}
%% modify appearance of entries in LoF and LoT
\cftsetindents{figure}{0em}{5em} % how much space to set aside
\cftsetindents{table}{0em}{5em}
\renewcommand{\cftfigpresnum}{\figurename\space} % prefix material
\renewcommand{\cftfigaftersnum}{.}               % postfix material
\renewcommand{\cfttabpresnum}{\tablename\space}
\renewcommand{\cfttabaftersnum}{.}

\begin{document}

\tableofcontents
\listoffigures
\listoftables

\chapter{Chapter}
\section{Section}
\begin{table}[h] \caption{Some table} \centering abc \end{table}
\begin{figure}[h] \caption{A figure} \centering xyz \end{figure}
\subsection{Subsection}
\subsubsection{Subsubsection}
\end{document}

A: Is this different from what you want?
\documentclass{book}
\usepackage[spanish]{babel}

\usepackage{titlesec}
\titlelabel{\thetitle\quad}

\begin{document}

\chapter{Test}
\section{Test}
\subsection{Test}

\end{document}


text:
Q: Glassfish create-service for [domain 2] I'm trying to create windows service for glassfish and I've had no problems creating one for the default domain, but when it comes to a domain I created my self, I seem to struggle.
the command I'm using is:
asadmin>create-service --domaindir C:\Program Files\glassfish-4.1.1\glassfish\domains\testdomain

I only get a filenotfound exception. I don't seem to understand glassfish's directory for its domains
aside from this, one of my other problems in the service I created for the default domain is that everytime I try to start it, it just stops immediately

The domain1 GlassFish Server on Local Computer started and then stopped. Some services stop automatically...

it gives me that kind of popup

A: The --domaindir option should point to the directory where all your domain directories are located, not the actual domain directory itself.
You also need to specify the name of the domain you want to create a service with.
In practice, this means you simply need to replace the final backslash in the command above with a space, like so:
asadmin> create-service --domaindir C:\Program Files\glassfish-4.1.1\glassfish\domains testdomain

It's a slightly confusingly named option (--domainsdir may have been a better name), but it effectively gives you the option of storing all of your user configuration away from the GlassFish binaries.
The path you've supplied in your example is actually the default directory, so doesn't need to be specified, you should just be able to name the domain you want to create a service from and GlassFish will automatically look in that directory to check if a domain is there, as follows:
asadmin> create-service testdomain


text:
Q: Trouble in creating pods in git bash terminal I'm unable to create a pod in gitbash terminal.
I have created a yaml file in Visual editor but when i did cat command it is showing no such file or directory
enter image description here

A: Did you save the file after editing? This seems more like a bash issue than a Kubernetes issue.
You can run the id command to see the user you're running as. Then use ls -l to see that the user has write permissions to your current directory.


text:
Q: Atualizar valor total com a quantidade Bom galera eu estou com o seguinte problema , eu tenho um painel simples de venda que mostra os produtos,quantidade,valor e valor total , assim que eu escolho um produto aparece o valor do item , o problema seria no caso como eu faria para que quando eu alterar a quantidade o valor total aumente conforme o tanto na quantidade

se em quantidade eu colocasse 2 no valor total seria o dobro do valor 4,259,53 e cada vez somando mais 1 , alguém pode me da uma luz ?
Meu codigo :
<!DOCTYPE html>

    <title></title>

<link rel="stylesheet" type="text/css" href="css/bootstrap.css">
<link rel="stylesheet" type="text/css" href="css/estilo.css">
<link  type="text/javascript" href="jquery.js">
<link type="text/javascript" href="post.js">
<link  type="text/javascript" href="jquery-form.js">

<form action="" method="post" enctype="multipart/form-data">
    <fieldset>
        <?php
        include ('banco.php');
        ini_set('default_charset','UTF-8');

        if($_GET){
            $id = $_GET['id_venda'];
        }

        if(isset($_POST['send'])){

            $produtos = $_POST['produtos'];
            $id_venda = $_POST['id_venda'];
            $quantidade = $_POST['quantidade'];
            $valor = $_POST['valor'];
            $valortotal = $_POST['valortotal'];

            mysql_query("INSERT INTO pedido(id, produtos, id_venda, quantidade, valor, valortotal )
            values(
                NULL,

                '{$produtos}',
                '{$id_venda}',
                '{$quantidade}',
                '{$valor}',
                '{$valortotal}'
                              );
            ");

            header("location:cabecalho.php?&id={$id} ");
        }

        ?>

    <legend style="color: #ffffff" class="btn btn-inverse">Vendas </legend>
    <?php
        ini_set('default_charset','UTF-8');
        mysql_connect('127.0.0.1','root','');
        mysql_select_db('mecanica');
        $query='Select * from produtos';
    ?>

    Produto :
    <select name="produtos" onchange="prodValor(this.value)" style="width: 400px">

    <?php
       //execução da query
        $resultado=mysql_query($query);
        while($linha=mysql_fetch_array($resultado))
            {

                echo '<option  value="' . $linha['id_produto'] . '">' . $linha['produtos'] . '</option>';
            }
            echo '</select>';
    ?>
     </select>

        Quantidade :
        <input style="width: 85px" type="number"  name="quantidade" id="quantidade" value="1">

        Valor :
        <input style="width: 85px" type="text"  name="valor" id="valorp"  >

        Valor Total:
        <input style="width: 85px" type="text"  name="valortotal" id="valortotal" >

    <?php
        ini_set('default_charset','UTF-8');
        mysql_connect('127.0.0.1','root','');
        mysql_select_db('mecanica');
        $query='Select * from pedido';
    ?>

    ID VENDA :
    <select name="id_venda" style="width: 75px">
    <?php
           $resultado=mysql_query($query);
            while($linha=mysql_fetch_array($resultado))
            {

            }
            echo '<option >' . $_GET['id_venda'] . '</option>';
            echo '</select>';
    ?>
    </select>

    <input type="submit" class="btn btn-inverse" value="Enviar" name="send">
    Cancelar
    </fieldset>
    </form>

A: Uma solução bem grosseira más acho que é por ai.
Segue o código:

valorTeste = 2129.53;
$("#nome").change(function(){
 if($("#nome").val() == 'Teste'){
    $('#valor').val(valorTeste);
  }
});
$("#qtd").change(function(){
 if($("#nome").val() == 'Teste'){
   qtd = $('#qtd').val();
    valor = $('#valor').val();
   val = valorTeste * qtd;
    $('#total').val(val);
  }
});
label{
  display:block;
}

<form>

Nome <input type="text" id="nome"/>

Qtd <input type="number" id="qtd"/>

Valor <input type="text" id="valor"/>

Valor Total <input type="text" id="total"/>

</form>

A: Use o jQuery

Seria mais ou menos assim e você resolveria seu problema.

A: Bom galera depois de tanto tentar consegui resolver, obrigado a todos pela ajuda.
Consegui com esse código :


text:
Q: Find the limit of the sum of product expression $P_n = \sum_{j = 1}^{n-1} \prod_{i = j+1}^n (1-a_i) a_j$ Let $\{a_n\}$ be a convergent sequence, assuming each $1 \geq a_i \geq 0$
consider the series of products
$$P_n = \sum_{j = 1}^{n-1} \prod_{i = j+1}^n (1-a_i) a_j$$
I would like to find $\lim_{n \to \infty} P_n$ or if not possible, find an upperbound to this sequence.

Attempt:
$$\sum_{j = 1}^{n-1} \prod_{i = j+1}^n (1-a_i) a_j \leq \sum_{j = 1}^{n-1} \prod_{i = 1}^n (1-a_i) a_j$$
Wikipedia says $\prod_{i = 1}^n (1-a_i) \leq \exp\left(-\sum_{i = 1}^n a_i\right)$
So
$$\sum_{j = 1}^{n-1} \prod_{i = j+1}^n (1-a_i) a_j \leq \exp(-\sum_{i = 1}^n a_i) \sum_{j = 1}^{n-1}  a_j$$
Then the upperbound to this limit is $$\exp\left(-\lim_{i = 1}^n \sum_{i = 1}^n  a_i\right) \cdot\lim_{n \to \infty} \sum_{j = 1}^{n-1} a_j.$$
Is this correct? An alternative approach uses the AM-GM inequality on the inner product term.

A: One can easily prove by induction that:
$$P_n=1-a_n-\prod_{i=1}^n(1-a_i).$$
In the case where the limit $\lim_{i\to+\infty} a_i=\alpha>0$, the product tends to $0$ and
$$\lim_{n\to+\infty} P_n=1-\alpha.$$
(Indeed, one can find a geometric upperbound of the product.)
In the case where the limit $\lim_{i\to+\infty} a_i=0$, the sequence of the products $\prod_{i=1}^n(1-a_i)$ is non negative and non increasing, so it converges to some $\beta\in[0,1]$ and then
$$\lim_{n\to+\infty} P_n=1-\beta.$$
Some extreme exemples:
--$a_i=0$ implies $\beta=1$.
--$a_i=\frac 1{i+1}$ implies $\beta=0$.


text:
Q: Comparing notions of degree of vector bundle In this question, $X$ will be a smooth complex projective variety.  This question will be about comparing two different ways of calculating the degree of a vector bundle on such an $X$.
I understand that, unless $X$ is a curve or $\mbox{Pic}(X)=\mathbb Z$, there is no well-defined notion of "degree" for vector bundles.
I would like to use $X=\mathbb{P}^2$ as an example.  This is a variety with $\mbox{Pic}(X)=\mathbb Z$.  A vector bundle $V$ on $\mathbb{P}^2$ has a well-defined degree, which we define to be the image of $\det V$ under the natural identification of $\mbox{Pic}(X)$ with $\mathbb Z$.  For instance, if $V$ is the tangent bundle of $\mathbb{P}^2$, then $\det V=\mathcal O(3)$, and so $\deg V=3$.
I have also seen the following way of defining the degree, for bundles on projective varieties: since $X$ is projective, there is a map $\kappa$ from $X$ into a projective space of the same or higher dimension.  Then we define a line bundle $\mathcal O_X(1)$ on $X$ by pulling back the $\mathcal O(1)$ from the projective space via $\kappa$.  Then, the degree of a bundle $V$ on $X$ is a number which I have seen denoted either
$\deg(V):=c_1(\mathcal O_X(1))^{d-1}.c_1(V)$
or
$\deg(V):=c_1(\mathcal O_X(1))^{d-1}\cap c_1(V)$,
where $d=\dim(X)$.
Question:
In the case of $X=\mathbb P^2$, the map $\kappa$ is the identity, and we have $\deg(V)=c_1(\mathcal O(1))\cap c_1(V)$, where $\mathcal O(1)$ is just the hyperplane bundle of $\mathbb P^2$ itself.
When $V$ is the tangent bundle, how do I see that the number $c_1(\mathcal O(1))\cap c_1(V)$ is equal to $3$?  My "instinct" is to think of $\mathcal O(1)$ as the line bundle of a divisor $D$, which in turn is determined by a hypersurface, specifically a projective line in $\mathbb P^2$, and then ask how many times that line is intersected by a "generic" section of $V$ (a vector field on $\mathbb P^2$, in this case, but I don't want this to depend too much on the fact that these sections are vector fields).
Is this the right way to think?
If it is, then two more questions:
(1) How can I see in a fairly intuitive way that this intersection number is $3$?
(2) Why would the intersection product of two Chern classes (elements of the cohomology ring $H^*(X,\mathbb Z)$) be equal to the intersection number of a divisor and a vector field (or of two divisors, more generally)?  (I guess there is a cohomology $\leftrightarrow$ geometry philosophy that I need to understand better.)

A: There are a couple of different issues here which might best be addressed separately, so let me use the answerbox for more space. (I will try to give full details, so apologies if I tell you things you already know.)

*

*For any vector bundle $V$ on any variety or complex manifold, we have $c_1(V)=c_1(\operatorname{det} V)$. This is a consequence of the the splitting principle.

*So your correct claim that in your example $c_1 O(1) \cup c_1(V) = \operatorname{deg} ( \operatorname{det} V)=3$ is really just an equality involving the line bundle $K^* = \operatorname{det} V$ —
you can completely ignore the fact that this line bundle is actually the determinant of some higher-rank bundle.

*Now, why are the two sides the same? By your definition $\operatorname{deg} L= d$ means precisely that $L = O(1)^d$, since in this case $O(1)$ is the generator of $\operatorname{Pic} \mathbf P^2$. So here $\operatorname{deg} ( K^*)=3$ means that $K^* = O(3)$, hence $c_1(K^*)= 3 c_1 O(1)$. So the left-hand side of your equality becomes $3 c_1 O(1) \cup c_1 O(1)$. Since $c_1 O(1)$ is represented by a line in the plane, its cup-product with itself is indeed 1, so we get $3.1=3$ on the left-hand side too.

*However: this is not generally true. The equality above hinged on the fact that the line bundle $O(1)$ generating $\operatorname{Pic} \mathbf P^2$ had $c_1(O(1) \cup c_1 (O(1)) = 1$. In general this will not be true. For example, suppose $X$ is a generic quartic surface in $\mathbf P^3$. Then its Picard group will be generated by a line bundle $L$, the restriction of $O(1)$ from $\mathbf P^3$ to the surface. Now $c_1(L)$ is represented by a hyperplane section of $X$, ie a quartic curve on $X$, and $c_1(L) \cup c_1(L) = 4$. So your equality would not hold on $X$: indeed the value of the left-hand side would be 4 times that of the right-hand side.

*Finally let me address your question (2) in the body. You are wondering why the intersection product of Chern classes would equal the intersection number of divisors. I am not sure if I am interpreting the question correctly, but the vital point here is that, to a great extent,  all the objects involved here — cohomology, characteristic classes, and intersection theory for divisors and algebraic cycles more generally — grew out of the attempt to formalise and generalise the same basic situation, namely counting the number of intersection points of two submanifolds of a compact manifold intersecting transversely. (I am not a historian of mathematics, so that statement should be liberally strewn with caveats, but the basic point is true.) Any form of intersection theory (cup product in topology, intersection numbers in algebraic geometry) is set up so that in this basic situation it returns the answer one naively expects.
To put it another way: in a definition such as
$$\deg(V):=c_1(\mathcal O_X(1))^{d-1}.c_1(V)$$
what one is really saying is

"intersect $d-1$ general hyperplanes in projective space and intersect the result with $X$ to get a smooth curve: then restrict $V$ to that curve and find its degree."

Here, the language of Chern classes and cup product allows one not to worry about any details like what "general" means, why this degree is independent of the choice of hyperplanes, and so on.