text:
Q: JSON files to array I have a heart.json file that I need transfer to a database and looking for a solution. In the file I have the following data:
      {"activities-heart":[{"dateTime":"2016-04-08","value":{"customHeartRateZones":[],"heartRateZones":[{"caloriesOut":1720.78208,"max":99,"min":30,"minutes":972,"name":"Out of Range"},{"caloriesOut":313.1456,"max":139,"min":99,"minutes":59,"name":"Fat Burn"},{"caloriesOut":0,"max":169,"min":139,"minutes":0,"name":"Cardio"},{"caloriesOut":0,"max":220,"min":169,"minutes":0,"name":"Peak"}],"restingHeartRate":73}}]
    ,"activities-heart-intraday":{"dataset":[
{"time":"00:00:00","value":83},
{"time":"00:01:00","value":80},
{"time":"00:02:00","value":76},
{"time":"00:03:00","value":78},
{"time":"00:04:00","value":78},
{"time":"00:05:00","value":79},
{"time":"00:06:00","value":79},
{"time":"00:07:00","value":78},
{"time":"00:08:00","value":76},
{"time":"00:09:00","value":77},
{"time":"00:10:00","value":83},
{"time":"00:11:00","value":81},
{"time":"00:12:00","value":80},
{"time":"00:13:00","value":80},
{"time":"00:14:00","value":80},
{"time":"00:15:00","value":75},
{"time":"00:16:00","value":75},
{"time":"00:17:00","value":76},
{"time":"00:18:00","value":76},
{"time":"00:19:00","value":76},
{"time":"00:20:00","value":78},
{"time":"00:21:00","value":83},
{"time":"00:22:00","value":76},
{"time":"00:23:00","value":74},
{"time":"00:24:00","value":75},
{"time":"00:25:00","value":74},
{"time":"00:26:00","value":75},
{"time":"00:27:00","value":75},
{"time":"00:28:00","value":75},
{"time":"00:29:00","value":77},
{"time":"00:30:00","value":82},
{"time":"00:31:00","value":82}

I am looking at putting the "time" value and "value" value into the database from this file but have no idea as to how please would someone be kind enough to take the time to help me out.

A: Here's your JSON converted to a database script that inserts the values in the database. Now go and try to find how to create the database and table by yourself.
You should install a database server in your machine, then create a database, then create a table, then run the script below.
The table should have 2 columns (named time and value) and their types should be "time" and integer (or numeric depending on your database).
I'm assuming this is a relational database you're talking.
If along the way you have any doubts on how you do any of the parts, be free to ask more.
insert into your_table (time, value) values ("00:00:00",83);
insert into your_table (time, value) values ("00:01:00",80);
insert into your_table (time, value) values ("00:02:00",76);
insert into your_table (time, value) values ("00:03:00",78);
insert into your_table (time, value) values ("00:04:00",78);
insert into your_table (time, value) values ("00:05:00",79);
insert into your_table (time, value) values ("00:06:00",79);
insert into your_table (time, value) values ("00:07:00",78);
insert into your_table (time, value) values ("00:08:00",76);
insert into your_table (time, value) values ("00:09:00",77);
insert into your_table (time, value) values ("00:10:00",83);
insert into your_table (time, value) values ("00:11:00",81);
insert into your_table (time, value) values ("00:12:00",80);
insert into your_table (time, value) values ("00:13:00",80);
insert into your_table (time, value) values ("00:14:00",80);
insert into your_table (time, value) values ("00:15:00",75);
insert into your_table (time, value) values ("00:16:00",75);
insert into your_table (time, value) values ("00:17:00",76);
insert into your_table (time, value) values ("00:18:00",76);
insert into your_table (time, value) values ("00:19:00",76);
insert into your_table (time, value) values ("00:20:00",78);
insert into your_table (time, value) values ("00:21:00",83);
insert into your_table (time, value) values ("00:22:00",76);
insert into your_table (time, value) values ("00:23:00",74);
insert into your_table (time, value) values ("00:24:00",75);
insert into your_table (time, value) values ("00:25:00",74);
insert into your_table (time, value) values ("00:26:00",75);
insert into your_table (time, value) values ("00:27:00",75);
insert into your_table (time, value) values ("00:28:00",75);
insert into your_table (time, value) values ("00:29:00",77);
insert into your_table (time, value) values ("00:30:00",82);
insert into your_table (time, value) values ("00:31:00",82);


text:
Q: How to check if two functions are equal? I need to keep a list of unique functions. So, listeners below should have a length of 1
final listeners = <VoidCallback>[];
for (int i = 0; i < 5; i++) {
  void listener() => setState(() {});
  if (!listeners.contains(listener)) {
    listeners.add(listener);
  }
}

But contains is returning false, so the same closure is added 5x. I tried testing with listener.hashCode but each hash was unique, so listeners.length was 5.
Is it possible to test for the same function?
If I move the function outsize
final listeners = <VoidCallback>[];
for (int i = 0; i < 5; i++) {
  void listener() => setState(() {});
  if (!listeners.contains(listener)) {
    listeners.add(listener);
  }
}

Then listeners.length is 1, but I'm writing a library and need to accommodate the first use case.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to embed a redirection url to a website? (in React Native) I would like to integrate this text in my app "https://www.google.com". When we click on it I will want the mobile browser to open and display the website. How to do this? I am novice, any help would be appreciate.

<TouchableOpacity>
<View>
    <Text style={{color: 'grey', fontSize: 17, fontFamily:'Arial', fontStyle: 'bold', textAlign: 'center',
    marginTop: 6, marginLeft: 25, marginBottom: 20}}>
                https://www.google.com/
    </Text>
  </View>
</TouchableOpacity>

A: You do not need to wrap Text inside a View and then inside TouchableOpacity, for a Text itself has onPress property. Avoid unnecessary nesting of elements.
<Text style={{color: 'grey',
 fontSize: 17,
 fontFamily:'Arial',
 fontStyle: 'bold',
 textAlign: 'center',
        marginTop: 6,
 marginLeft: 25,
 marginBottom: 20}}
 onPress = {() => {Linking.openURL('https://google.com')}}>
  https://www.google.com/ /* Whatever appropriate text you want to display */
  </Text>

A: According to official React Native Linking documentation:

If you are using the managed expo-cli workflow, see the guide on Linking in the Expo documentation for the appropriate alternative.

And this page says:

Often WebBrowser is a better option because it's a modal within your app and users can easily close out of it and return to your app.

So you can also use this one:
<Text style={{
  color: 'grey',
  fontSize: 17,
  fontFamily:'Arial',
  fontStyle: 'bold',
  textAlign: 'center',
  marginTop: 6,
  marginLeft: 25,
  marginBottom: 20
 }}
 onPress = {() => {WebBrowser.openBrowserAsync('https://google.com')}}>
</Text>

A: I don't know if this is still an option but in past i used this https://github.com/obipawan/react-native-hyperlink
For sure working solution is to split your text and the link part put like this

<Text onPress={ ()=> Linking.openURL('https://google.com') } >Google.com</Text>

A: You can use Linking component exposed by React Native
Step#01 Import Linking Component
 import { Linking } from 'react-native';

Step#02 Use this with onPress prop of component.
 <Pressable onPress={() => Linking.openURL('https://google.com')} />


text:
Q: How do I decode this JSON payload (msearch esasticsearch)? I am trying to reverse engineer an API call to this url: https://respublica.co/elasticsearch/msearch
When I look in the payload tab, the JSON query looks like this and I do not understand it, is ther anyway I could decode this?
{"z":"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","y":"bM0kriQGnK34eBZ6Cz30sA==","x":"a7bsy6/TdR2roPynoJBNxLE9Pn86gf2KxVh+6nOXRdE="}

I can send a request with this payload, but I want to alter it so I can lookup different users on the API
This is the URL of the website that makes the request: https://respublica.co/profile?user=Cao_Cao


text:
Q: Unxpect CORS policy error when using auth api from locally First of all, i have an backend RESTapi running on my ubuntu server on the cloud(works perfectly 100%).
And I also have an frontend webapplication running on the same server(works perferctly aswell), and i can use the login system and all that stuff.
Now my issue: I am deploying the frontend locally at my computer for development purposes, but i still want to have the connection to my backend at the cloud instead of also deploying the backend locally.
Problem is now that when im using the authentication from my local computer i get this error:
Access to fetch at 'http://ip-adress-to-the-backend-at-the-cloud:5000/api/auth' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The 'Access-Control-Allow-Origin' header has a value 'http://*:3000' that is not equal to the supplied origin. Have the server send the header with a valid value, or, if an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

The thing is: it worked perfectly logging in while using the webapp locally at my computer until last week.. Now that i made some changes in my ".env" file, "server.js" and "routes.js" file, it doesnt work.
The strange thing is that i tried removing the changes from those files but still aint working.
Here is my .env file:
 APP_PORT=*****
DB_HOST=*****
DB_USER=*****
DB_PASSWORD=******
DB_NAME=******
JWT_SECRET=******
JWT_KEYSECRET=*******
ALLOWED_ORIGIN=http://ipadress_to_both_the_frontend_and_backend:3000

here is my server.js:
const express = require('express');
const app = express();
require('dotenv').config();

if(process.env.JWT_SECRET == undefined || process.env.JWT_KEYSECRET == undefined){
    console.log("Fatal error: Secret is not set")
    process.exit(1);
}

require('./startup/routes')(app)
require('./startup/database')

app.listen(process.env.APP_PORT, () => {
    console.log("Server is running: " + process.env.APP_PORT);
})

and my routes.js:
require('dotenv').config();
const users = require('../api/user/user.router')
const keys = require('../api/keys/keys.router')
const equipmentType = require('../api/equipmenttypes/equipmenttype.router');

const auth = require('../api/authentication/auth.router')
const helmet = require('helmet')
const express = require('express')

module.exports = function (app) {
    app.use(express.json());
    app.use(express.urlencoded({ extended: true }));
    app.use(express.static('public'))

    app.use(helmet.xssFilter())
    app.use(helmet.frameguard())
    app.use((req, res, next) => {
        res.setHeader('Access-Control-Allow-Origin', process.env.ALLOWED_ORIGIN);
        res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
        res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With, content-type, x-auth-token, x-api-key');
        res.setHeader('Access-Control-Allow-Credentials', true);
        next();
    })

    app.use('/api/user', users)
    app.use('/api/auth', auth)
    app.use('/api/key', keys)
    app.use('/api/equipmenttypes', equipmentType)

}

A: Firstly, install cors by npm i cors
Add this to your server.js file:

const cors = require("cors");

app.use(cors());

A: The solution was simple, I changed the line inse my env file this:
ALLOWED_ORIGIN=*
No, this is not a good thing to do, and not secure at all, but now i can accsess the backend api from localhost, and i can optimize my work.


text:
Q: Finding $\sqrt[4x]{x}$ assuming $x^{-81^{81^{-x}}}=81$ Question.

Suppose $\displaystyle x^{-81^{81^{-x}}}=81$. Find $\sqrt[4x]{x}$.

Attempt.
As far as I know, when we face this kind of problems in preparation for the university entrance exam in Latin America, we should take powers to a convenient value and try to resemble the exponents by their factors to look the same as the term in left.  For example, converting $$(ax)^x = a \Rightarrow (ax)^{ax}=a^a$$ Let us solve for $ax=a$, then $x=a^{a-1}$.  But I can't do that here.  I tried making it $A^A$, where $A=81^{-x}$, but the roles of exponent and base are interchanged in the problem, so it doesn't work.

A: We have
$$81^{-1} = x^{81^{81^{-x}}},$$
and hence
$${\left(81^{-1}\right)}^{81^{a}} = {\left(x^{\left(81^{81^{-x}}\right)}\right)}^{81^a} = x^{\left(81^{{81^{-x}}}\right)\cdot \left(81^a\right)} = x^{\displaystyle 81^{\left({81^{-x}}+a\right)}}.$$
Therefore, with $a = -81^{-x}$ we have
$${\left(81^{-1}\right)}^{81^{-81^{-x}}} = x^{81^0} = x,$$
or
$$x = 81^{-81^{-81^{-x}}}.\tag{$*$}$$
Substituting $x$ repeatedly in the expression above would gives us
$$x = 81^{-81^{-81^{-81^{\dots}}}}, \tag{1}$$
and if this made sense we could identify $x = 81^{-x}$.
It would then follow that $\sqrt[4x]{x} = \frac13$.

We can be more rigorous as follows.
Let $f:\Bbb R\longrightarrow \Bbb R$ be given by $f(t) = -(81^t)$.
Observe that $t = 81^{-t} \iff -t = -\left(81^{-t}\right) \iff -t$ is a fixed point of $f$.
Now, $f$ is a strictly decreasing function, and it's thus easy to see that it has a single fixed point.
We can rewrite equation $(*)$ as follows:
$$-x = -\left(81^{-\left(81^{-\left(81^{-x}\right)}\right)}\right) = f^3(-x),\tag{$**$}$$
so $-x$ is a fixed point of $f^3$.
Of course, the fixed point of $f$ is also a fixed point for $f^3$.
It remains to check that $f^3$ also has a single fixed point, from which it follows that $-x$ must be the fixed point of $f$.
This once again follows from the fact that $f^3$ is strictly decreasing; if this is not clear, it's a good exercise to look at how monotonicity behaves with compositions of strictly decreasing and strictly increasing functions.
We've shown hence that $x = 81^{-x}$, so that indeed $\sqrt[4x]{x} = \frac13$ as we had guessed before.

For what it's worth, $x = 81^{-x}$ has a solution in terms of Lambert's $W$, given by
$$x = \frac{W(\log(81))}{\log(81)}\approx 0.285360471863842099782478678983274970610868803768259$$
One can check that the approximation above 'satisfies' the equation
$$x^{-81^{81^{-x}}}=81$$
of the opening statement.


text:
Q: Detecting accelerometer shakes android I'm trying to detect left, right, up and down shakes. I researched and found this code.
public void onSensorChanged(SensorEvent event) {
            // TODO Auto-generated method stub

            if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {

                float[] values = event.values;

                // Movement
                float x = values[0];
                float y = values[1];
                float z = values[2];

                long actualTime = System.currentTimeMillis();
                if ((actualTime - lastUpdate) > 100)
                {
                    long diffTime = (actualTime - lastUpdate);
                    lastUpdate = actualTime;

                    if(Round(x,4)>8.0000){
                        Log.d("sensor", "=====LEFT====");

                    }
                    else if(Round(x,4)<-8.0000){
                        Log.d("sensor", "=====RIGHT====");

                    }
                    else if(Round(z,4) < -0.0){
                       Log.d("sensor", "=====UP====");

                    }

                    else if(Round(y,4) < 1.0){
                        Log.d("sensor", "=====DOWN====");

                    }

                float speed = Math.abs(x+y+z - last_x - last_y - last_z) / diffTime * 10000;

                if (speed > SHAKE_THRESHOLD) {
                    //Log.d("sensor", "shake detected w/ speed: " + speed);
                    //Toast.makeText(this, "shake detected w/ speed: " + speed, Toast.LENGTH_SHORT).show();
                }
                last_x = x;
                last_y = y;
                last_z = z;
                }
            }

        }

I tried to study it but I have some questions.
1. Where can I set the delay every after shake detection? I want it to detect a shake after 1 second of the last detected shake.
2. Why is that if I place it to a flat surface, it always detects down.
3. I can't detect a right movement shake
Any help and suggestion will be appreciated.

A: First off, this code appears to detect movement rather than a shake (where I understand shake to be a motion which goes one way, then back the other), which might be causing problems in how you understand it's working.

Where can I set the delay every after shake detection? I want it to detect a shake after 1 second of the last detected shake.

if ((actualTime - lastUpdate) > 100) is where the interval between detections occurs - the 100 here tells the program to only see what the change is after 100 ms, so if you wanted 1 second, change this to 1000

Why is that if I place it to a flat surface, it always detects down.

I'm not entirely sure of the context and direction here as it's not clear, but don't forget that 'down' as you think of it might not be down in your space, but in the phone's, where down is only down when the phone is upright. If the phone is on it's back, left and right are the same, but down (i.e. towards the ground) is actually back for the sensor, as it's towards the back of the phone.

*

*I can't detect a right movement shake

TBH I've no idea why, the code seems fine here. May be a phone thing, may be an implementation problem (as I said, the above code is movement overall, not a returning 'shake', so it could be how you're shaking it right to test this isn't triggering it, but your shake left is triggering it


text:
Q: log4net watching function does not work if create appender in code? I want to set a Rolling Appender dynamic in code rather than in config file. So I have a function that will return log4net.ILog
    <Assembly: log4net.config.XmlConfigurator(ConfigFile:="Log4Net.config", Watch:=True)>
Public Function genLogXMLCfg(cls As Object) As log4net.ILog
    Dim clsName As String = cls.ToString()
    Dim rollAppen As New RollingFileAppender()

    rollAppen.Name = clsName + "Appender"
    rollAppen.RollingStyle = RollingFileAppender.RollingMode.Composite
    rollAppen.File = "logs\\"
    rollAppen.DatePattern = "'" + clsName.ToLower() + "'" + "yyyyMMdd'.log'"
    rollAppen.LockingModel = New log4net.Appender.FileAppender.MinimalLock()
    rollAppen.AppendToFile = True
    rollAppen.StaticLogFileName = False
    rollAppen.MaxSizeRollBackups = 3
    rollAppen.MaximumFileSize = "100KB"
    Dim layout As New log4net.Layout.PatternLayout("%d [%t] %-5p %c (line:%L) - %m%n")
    rollAppen.Layout = layout
    layout.ActivateOptions()
    rollAppen.ActivateOptions()

    Dim logg As ILog = LogManager.GetLogger(clsName)
    Dim l As log4net.Repository.Hierarchy.Logger = DirectCast(logg.Logger, log4net.Repository.Hierarchy.Logger)
    l.AddAppender(rollAppen)
    l.Repository.Configured = True
    Return logg
End Function

Because I want to dynamic generate rolling appender from code but at the same time I want to set the logger from config file, so I have following config file call (Log4Net.config)
   <configSections>
       <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
   </configSections>
   <appSettings>
    <add key="log4net.Config" value="log4net.config"/>
    <add key="log4net.Config.Watch" value="True"/>
   </appSettings>
<log4net>
    <logger name="ConsoleApplication1.LogTest2">
        <level value="WARN" />
    </logger>
    <logger name="ConsoleApplication1.testCls">
        <level value="INFO" />
    </logger>
</log4net>

Now I test the function by following code:
       Dim cls As LogTest2 = New LogTest2()
    Dim tCls As testCls = New testCls()
    Dim l4n As log4net.ILog
    Dim l4n2 As log4net.ILog

    l4n = cls.genLogXMLCfg(tCls.GetType().ToString())
    l4n2 = cls.genLogXMLCfg(cls.GetType().ToString())

    l4n.Debug("... Here is a debug log -2.")
    l4n.Info("... and an Info log.")
    System.Threading.Thread.Sleep(3000)
    l4n.Warn("... and a warning 1.")
    l4n.Debug("... Here is a debug log -1.")
    l4n.Warn("... and a warning 2.")
    l4n.Warn("... and a warning 3.")
    l4n2.Warn("l4n2 cls and a warning -1.")
    l4n.Warn("... and a warning 4.")
    l4n.Warn("... and a warning 5.")
    Console.Write(" ... ... ... ")
    System.Threading.Thread.Sleep(3000)
    l4n.Warn("... and a warning 6.")
    l4n.Debug("... Here is a debug log 1.")
    l4n.Warn("... and a warning 7.")
    l4n2.Debug("l4n2 cls Here is a debug log.")
    l4n2.Info("l4n2 cls and an Info log.")
    l4n.Fatal("... and a fatal .")
    l4n2.Fatal("l4n2 and a fatal .")
    l4n.Debug("... Here is a debug log 2.")
    l4n.Warn("... and a warning 8.")
    l4n.Error("... and an error.")
    l4n.Debug("... Here is a debug log 3.")
    l4n.Fatal("... and a fatal .")
    l4n.Debug("... Here is a debug log 4.")
    l4n2.Debug("l4n2 cls Here is a debug log.")
    l4n2.Info("l4n2 cls and an Info log.")
    l4n2.Warn("l4n2 cls and a warning.")
    l4n2.Error("l4n2 cls and an error.")
    l4n2.Fatal("l4n2 cls and a fatal .")

After that, two log file generated in logs folder call
**consoleapplication1.logtest220130610.log** and **consoleapplication1.testcls20130610.log**
The content are:

**consoleapplication1.logtest220130610.log**
2013-06-10 18:41:38,802 [9] WARN  ConsoleApplication1.LogTest2 (line:182) - l4n2 cls and a warning -1.
2013-06-10 18:41:41,819 [9] FATAL ConsoleApplication1.LogTest2 (line:193) - l4n2 and a fatal .
2013-06-10 18:41:41,831 [9] WARN  ConsoleApplication1.LogTest2 (line:206) - l4n2 cls and a warning.
2013-06-10 18:41:41,833 [9] ERROR ConsoleApplication1.LogTest2 (line:207) - l4n2 cls and an error.
2013-06-10 18:41:41,836 [9] FATAL ConsoleApplication1.LogTest2 (line:208) - l4n2 cls and a fatal .

**consoleapplication1.testcls20130610.log**
2013-06-10 18:41:35,767 [9] INFO  ConsoleApplication1.testCls (line:176) - ... and an Info log.
2013-06-10 18:41:38,792 [9] WARN  ConsoleApplication1.testCls (line:178) - ... and a warning 1.
2013-06-10 18:41:38,795 [9] WARN  ConsoleApplication1.testCls (line:180) - ... and a warning 2.
2013-06-10 18:41:38,800 [9] WARN  ConsoleApplication1.testCls (line:181) - ... and a warning 3.
2013-06-10 18:41:38,804 [9] WARN  ConsoleApplication1.testCls (line:183) - ... and a warning 4.
2013-06-10 18:41:38,806 [9] WARN  ConsoleApplication1.testCls (line:184) - ... and a warning 5.
2013-06-10 18:41:41,809 [9] WARN  ConsoleApplication1.testCls (line:187) - ... and a warning 6.
2013-06-10 18:41:41,813 [9] WARN  ConsoleApplication1.testCls (line:189) - ... and a warning 7.
2013-06-10 18:41:41,817 [9] FATAL ConsoleApplication1.testCls (line:192) - ... and a fatal .
2013-06-10 18:41:41,823 [9] WARN  ConsoleApplication1.testCls (line:195) - ... and a warning 8.
2013-06-10 18:41:41,826 [9] ERROR ConsoleApplication1.testCls (line:196) - ... and an error.
2013-06-10 18:41:41,828 [9] FATAL ConsoleApplication1.testCls (line:199) - ... and a fatal .

Everything are OKAY. But....
    If I change the config file during the program running, let say I change the level from INFO to FATAL
            <logger name="ConsoleApplication1.testCls">
            <level value="FATAL" />  <!-- INFO to FATAL -->
        </logger>

the two log file now are:
 **consoleapplication1.logtest220130610.log**
2013-06-10 19:05:20,880 [9] WARN  ConsoleApplication1.LogTest2 (line:182) - l4n2 cls and a warning -1.
**consoleapplication1.testcls20130610.log**
2013-06-10 19:05:17,848 [9] INFO  ConsoleApplication1.testCls (line:176) - ... and an Info log.
2013-06-10 19:05:20,872 [9] WARN  ConsoleApplication1.testCls (line:178) - ... and a warning 1.
2013-06-10 19:05:20,875 [9] WARN  ConsoleApplication1.testCls (line:180) - ... and a warning 2.
2013-06-10 19:05:20,877 [9] WARN  ConsoleApplication1.testCls (line:181) - ... and a warning 3.
2013-06-10 19:05:20,884 [9] WARN  ConsoleApplication1.testCls (line:183) - ... and a warning 4.
2013-06-10 19:05:20,886 [9] WARN  ConsoleApplication1.testCls (line:184) - ... and a warning 5.

I wonder that why the watch function cannot update log properly and seem will affect other log file even I only change one logger data? May I know the reason? What wrong of my code

A: When you change your config file will your program is running. Log4net will reread you config file because of the Watch:=True. However your genLogXMLCfg is not executed. So your configuration of your appenders in not configured after you save the new config. There is no appender, so you do not see any new entries in your logs.


text:
Q: Keyboard not showing up in Devices and Printers my PS2 keyboard is not showing up in the Devices and Printers category. I upgraded to Windows 10 from Windows 7, which is running fine. Any suggestions on how to fix this?

A: *

*PS2 is not like USB, it is not Plug And Play.

*Make sure that any PS2 devices that you'd like to use are plugged in before the computer boots. They cannot be used otherwise.

*PS2 devices will not show up in Devices and Printers. Only USB and such shows up there. PS2 devices provide no other information about themselves. They just.. exist.

So, if your peripheral works, great, that's all you have to do.
If it does not, make sure you plug it in before the computer boots.


text:
Q: Tamagawa number for functional fields Let $G$ be a split semi-simple simply connected group over a global field $F$ and let
$\omega$ be a top-degree differential form on $G$ without zeroes (defined over $F$). It is well
known that $\omega$ defines a measure on the adele group $G(\mathbb A)$. The Tamagawa number formula states (if I understand correctly) that
1) If $F$ is a number field then the volume of $G(\mathbb A)/G(F)$ is 1
2) If $F$ is a functional field isomorphic to $\mathbb F_q(X)$ where $X$ is a projective curve over $\mathbb F_q$ then the above volume is equal to $q^{(g-1)\dim G}$
where $g$ is the genus of $X$.
My questions are the following:
a) Do I understand the statements correctly?
b) What is the reason why 1) and 2) look somewhat differently? Can one formulate the statement in a uniform way for all global fields?
Edit: In fact my understanding was wrong. In 1) one needs to multiply
by the volume of $(\mathbb A/F)^{\dim G}$ which is equal exactly to $q^{(g-1)\dim G}$
in the functional case. I was confused by the case $F=\mathbb Q$ where the above factor is 1.


text:
Q: How can I prevent Visual Studio from scrolling down to the bottom of the file when pasting a snippet of text? When inserting a copied text in Visual Studio 2010 via CTRL+V, the text is pasted, and VS automatically scrolls down to the bottom of the file.
I've encountered this at least for XAML and C# files.
Any ideas on how to de-activate this scrolling?

A: go to "options"-->"keyboard" and check if there is such a keyboard shortcut enabled.
You can try to reset this settings if you don't find.

A: This was happening on my VS 2019 only within CSS <style> tag. I've resolved it using the following setting:


text:
Q: Release Management 2015 with TFS 2015 Build vNext We are trying to use Release Management for Visual Studio 2015 and Team Foundation Server 2015 to build and eventually deploy from our Code System to our QA System.
We have defined 2 different types of builds in TFS 2015 (The new scriptable build Definition – Team Foundation Build and XAML definition):
We are able to queue both these definitions and they build successfully.
Next when we go to Release Management Client for Visual Studio 2015 and create a new Release, after selecting the Release Template, it allows us to select a Build. Searching these Builds returns only the builds from the XAML definitions and not from the Team Foundation Build ones.
How do we get Release Management to use the builds from Team Foundation Builds?

A: To release them automatically,
For the XAML build system, make sure to copy the release template (named similarly to ReleaseTfvcTemplate.12.xaml ) to your BuildProcessTemplates from "C:\Program Files (x86)\Microsoft Visual Studio 14.0\Release Management\Client\bin" and use it as the Process Template for your release build.
For the new scriptable build system, you will also need to either run a Command Line task that executes ReleaseManageBuild.exe (found in the same folder as above) with some supplied arguments ( more information here: http://blogs.msdn.com/b/visualstudioalm/archive/2014/04/04/release-management-continuous-deployment-with-visual-studio-online-and-any-ci-systems.aspx ).
Or, you can use the tasks found in this answer:
https://stackoverflow.com/a/32994949/3317095
I have not personally tested Daniel Mann's task, but it looks very similar to the one I made for myself and I incorporated some of his code into mine. And let's be honest, he's the subject matter expert in this area.


text:
Q: Throw the ball in a park I am trying to solve the problem of throw the ball in a park which I found at https://brainly.in/question/53867717
My solution to the problem:
seconds = 6
player = random.sample(range(1, 11), 10)
next_receiver = player[0]
for i in range(1, seconds):
   next_receiver = player[next_receiver-1]
   # next_receiver at the end of the loop is the player who will have the ball

This solution gives the correct answer; however, it has one problem. When the size of player is of the order 10^9 and seconds=9999999, it takes longer to get an answer. In my PC it takes about 1 minute and 20 seconds to get the answer. I cannot think of any better way to solve this problem. Any hints?

A: We know that most likely there is a cycle in which we get stuck in at the end. If this cycle is smaller than the seconds count we can use it to speed up the process by jumping ahead a multiple of the cycle size
def throw_balls(start, receiver, seconds):
    current_player = start

    # Stores which player already received the ball and the second at which they got it.
    already_seen = dict()

    for i in range(seconds):
        current_player = receiver[current_player - 1]
        if current_player in already_seen:
            # This player previously received the ball, so we are in a cycle
            loop_length = i - already_seen[current_player]
            remaining = seconds - i
            break
        else:
            already_seen[current_player] = i
    else:
        return current_player
    return throw_balls(current_player, receiver, remaining % loop_length)

Note that this does not guarantee faster execution, for example when each player passes the ball onto the next person, this will behave the exact same as your solution, although slower since we are doing extra work.
Edit:
After a lengthy discussion @Kelly Bundy and I came to the conclusion that this probably will not help the situation you put yourself in with the way you are initializing receiver, although it probably helps with the way to original problem is formulated.
If receiver is a permutation of the potential targets, so no two players will targeted the same person, then the expected cycle size for N=10^9 is to large to notice/reach in ~10^7 steps (see 100 Prisoners Problem). A simple calculation results in a chance of 1% that a cycle is reached in 10^7 steps.
However, the original problem sounds like it's not a permutation, but instead each player's target is chosen independently of everyone else. This means that two players can target the same person. In that case, there is a close to 100% chance that a cycle will be reached after only 10^6 steps and this changed algorithm will show a 10x theoretical speedup.


text:
Q: Multiplication by group elements is an open mapping In a topological group $G$, let $L_x(u)=xu$.  In much of the literature on topological groups, the fact that this is an open mapping (so, if $U \subset G$ is open then $L_x(U)$ is open) is used without proof.  Any good proofs, given that we can assume it is a continuous map?

A: It is an homeomorphism, so it is open, $L_{x^{-1}}$ is the inverse of $L_x$, if $h$ is an homeomorphism, $({h}^{-1})^{-1}(U)=h(U)$ is open since $h^{-1}$ is continuous.


text:
Q: Form Activated event and messagebox causes unwanted looping I am using an activated event in my vb.net application this is followed by an if statement which causes a messagebox to apear as result of a conditon..
The problem is that the messagebox causes my form to loose focus and then re-activate again everytime the messagebox is clicked resulting in a type of loop which I'm now stuck in how can I get round this?
      Private Sub form1_Activated(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Activated

    if "EXTERNAL DOCUMENT IS A DRAWING ENVIRONMENT" then
    'NOTHING
    Else
    msgbox("Select drawing environmet first")
me.close()
    end if

    end sub

The line "EXTERNAL DOCUMENT IS A DRAWING ENVIRONMENT" is a procedure where a variable result returned by autodesk inventor identifying what type of drawing environment is the active document... (this just shortens the whole explanation)

A: You can use a flag as Malcor says, or you can remove the handler prior to show the Msg, so:
Private Sub form1_Activated(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Activated

  if "EXTERNAL DOCUMENT IS A DRAWING ENVIRONMENT" then
    'NOTHING
  Else
    RemoveHandler Me.Activated, addressof form1_Activated
    msgbox("Select drawing environment first")
    me.close()
  end if

end sub

A: Not Tested. But this may work....
Private WarningShowed As Boolean = False
Private Sub form1_Activated(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Activated

    If Not WarningShowed Then
        WarningShowed = True
        If "EXTERNAL DOCUMENT IS A DRAWING ENVIRONMENT" Then
            'NOTHING
        Else
            MsgBox("Select drawing environmet first")
            Me.Close()
        End If
    End If

End Sub


text:
Q: Can ice freeze? We know that ice is already the frozen (solid) form of water. The question is more like: Can this frozen form freeze further? Or can it become more solid? (for example, by exposing to colder temperatures and/or a higher pressure).
Water can partially freeze but we can think of a solid frozen state. It is said that virtually all ice in the biosphere is ice Ih (hexagonal crystal form of ordinary ice), but there is also Ice Ic (metastable cubic crystalline) that is present in upper atmosphere in very low temperatures (between −140 and −50 °C). [There are also different forms of ice created in labs.]1
Furthermore, scientists predict that there is an out-of-this-world kind of ice that is present at extremely high pressures nonexistent on Earth but in the range of the pressure regimes on Uranus and Neptune (planets whose major components include ice). At this pressure, oxygen-hydrogen-oxygen bonds get squeezed together, forming new shapes. The new ices eventually become metals, but not as quickly as others had previously thought.2

Static crystal structure of a phase of ice at a pressure of 2 terapascals.2
In the end, can we say that different crystalline forms have different solid states? Can ice freeze further by transforming into a different crystalline form?
Further clarification: "More solid" and "freeze further" might not sound scientific but I wanted to ask in that way for simplification. I meant changes in material properties by saying "more solid". For example,change in hardness, molecules getting closer, stronger bonds etc. [It is even said that ice can become metal at very high pressures.]
Also, when ice is changing solid phases, what is happening there? I thought it is transforming into a harder structure in some phases almost like "freezing further"? I thought this might happen when ice changes into another solid phase. That's why I ask if ice can freeze or not.
Note: There is also fractional freezing but it is related to solutions mainly, for example that contains water and alcohol. It is used in freeze distillation processes.

1 Wikipedia - Ice, Ice Ih, Ice Ic
2 http://news.cornell.edu/stories/2012/01/scientists-predict-out-world-kind-ice

A:
Can this frozen form freeze further? Or can it become more solid? (for example, by exposing to colder temperatures and/or a higher pressure).
Can ice freeze further by transforming into a different crystalline form?

The ice will remain solid while lowering temperature or pressure but might change in state, or phase, as you mention. But you should use other words than "freeze further" or "become more solid", since that has no meaning.
Freezing means solidifying. That is a word for the transition from liquid$\to$solid. Since that doesn't occour again in between solid phases, "freeze further" has no meaning.
Ice is usually structured in a lattice. Of course if ice would at some point at extreme conditions make transitions to and from an amouphous state, then yes it would be like "liquifying" the ice again (an amouphous state has the same microstructure as a liquid). This would give ice the same type of structure as e.g. glass. If this is the case maybe the exact definition of the word "freezing" could be discussed, as the ice might be considere to "melt" and "freeze" within the solid state. For me this is mostly a discussion of the definition of the word.
As far as I am aware, ice does not take an amourhpous form, but I might be wrong in extreme conditions.

can we say that different crystalline forms have different solid states?

Yes, and those "states" are called phases (from Wikipedia article):

As you mention, different phases are different molecular structures or lattices. Both temperature and pressure have influence on the points of phase change, as shown in the figure.
The figure could more fittingly be extended to a 3D-coordinate system with a third axis of specific volume. Volume, pressure and temperature are three key proporties that define the points of phase changes, both between gas-liguid, solid-liquid and solid-gas and between different solid states.


text:
Q: How do I add 'setPreserveViewport' option to KmlLayer in Java? I'm relatively new, so there might be a very simple answer to this question, but how do I add the 'setPreserveViewport' option to KmlLayer in Java? I have found one solution, but that doesn't work to well with showing multiple KML layers.
So what I have now is:
    final KmlLayer KMLmap1 = KmlLayer.create("https://earthbuilder.googleusercontent.com/04956359305736194955-05414812628978701557-4/2/kml/link.kml");
    final KmlLayer KMLmap2 = KmlLayer.create("https://dl.dropboxusercontent.com/u/20845226/alledanmarks5regioner.kml");

    class KMLButtonPanel extends FlowPanel {
    public KMLButtonPanel() {
            Button KML1Btn = new Button("KML 1", new ClickHandler() {
              public void onClick(ClickEvent event) {

                  kmlUnload(KMLmap2);

                  kmlLoad(KMLmap1);

              }

            });

            Button KML2Btn = new Button("KML 2", new ClickHandler() {
              public void onClick(ClickEvent event) {

                  kmlUnload(KMLmap1);

                  kmlLoad(KMLmap2);

              }

            });
    }

public void onModuleLoad() {

    private void kmlLoad(KmlLayer layer) {
                layers = layer;
                layers.setMap(map);

        }

      private void kmlUnload(KmlLayer layer) {
                layers = layer;
                layers.setMap(null);
        }
    }

I also have a lot of other code, so I have just copied the lines out that are relevant. Now the thing I want to do, is somehow add the setPreserveViewport(true) option – and that's where I'm at! How do I do that?

A: For anyone interested, the solution was quite simple:
  private KmlLayer layers;

  private String KMLmap1 = "https://earthbuilder.googleusercontent.com/04956359305736194955-05414812628978701557-4/2/kml/link.kml";
  private String KMLmap2 = "https://dl.dropboxusercontent.com/u/20845226/alledanmarks5regioner.kml";

and then when I run kmlLoad(KMLmap1); or kmlLoad(KMLmap2); I get:
private void kmlLoad(String string) {

        if (layers != null) {
            kmlUnload();
        }

        KmlLayerOptions layerOpts = KmlLayerOptions.create();
        layerOpts.setPreserveViewport(true);
        KmlLayer newlayers = KmlLayer.create(
                string,
                layerOpts
            );
        layers = newlayers;
        newlayers.setMap(map);

  }

  private void kmlUnload() {
        layers.setMap(null);
    }


text:
Q: how to use Zend_Registry::getInstance     <?php

        require_once('Zend/Registry.php');
        $registry = Zend_Registry::getInstance();
        $registry['name'] = 'Quentin Zervaas';
        echo sprintf('My name is %s', $registry['name']);

    ?>

Question:
what does this line mean? $registry = Zend_Registry::getInstance();And how to use this function?

A: Zend_Registry functions as application level storage where you can store variables, objects or anything else which you need during the execution of the application.
The below statement returns the object of Zend_Registry class using the singleton pattern.
Zend_Registry::getInstance();

To add the value to registry.
$registry = Zend_Registry::getInstance();
$registry->set('variableName', 'value');
or
Zend_Registry::set('variableName', $value);

And this is how you get the value
$registry = Zend_Registry::getInstance();
$registry->get('variableName');
or
Zend_Registry::get('variableName');

A: The getInstance() method returns the singleton registry object. This registry object is iterable, making all values stored in the registry easily accessible. For example.
$registry = Zend_Registry::getInstance();

foreach ($registry as $index => $value) {
    echo "Registry index $index contains:\n";
    var_dump($value);
}


text:
Q: What's the relationship between consensus and transaction in computer science? One sentence on wiki  confused me, claiming that 2pc is special type of consensus.
Two-phase_commit_protocol
In transaction processing, databases, and computer networking, the two-phase commit protocol (2PC) is a type of atomic commitment protocol (ACP). It is a distributed algorithm that coordinates all the processes that participate in a distributed atomic transaction on whether to commit or abort (roll back) the transaction (it is a specialized type of consensus protocol)
As I know, consensus aims at deciding one single variable's value on difference sides in a system and transaction is likely to ensure multiple variables' value. If I'm right then consensus algorithm shoud be a subset of transaction. Why the opposite??


text:
Q: Uncertainty Principle for a Totally Localized Particle If a particle is totally localized at $x=0$, its wave function $\Psi(x,t)$ should be a Dirac delta function $\delta(x)$. Accordingly, its Fourier transform $\Phi(p,t)$ would be a constant for all $p$, thus the particle's momentum is totally uncertain. I guess this is what the Uncertainty Principle told us.
But in another hand, since the particle is totally localized at $x=0$, it is not moving and therefore static. Its velocity should be 0, so is its momentum, which contradicts the conclusion above.
So, what's wrong with my thinking?
Is it that there shouldn't be a TOTALLY STATIC particle, or it's in a non-normalizable state, so the uncertainty principle is not applicable?

A: The origin  of your problem was already explained in the previous answers, let me just do so in a bit more detail. It is better to think of some normalizable wave function rather than the $\delta$-function itself. As you probably know, you can get arbitrarily close to a $\delta$-function by making a wave packet narrow and taking a suitable limit (see below for a concrete example).
Now you are right that you can localize your particle to an arbitrarily narrow region around $x=0$. You can even make it "static" in the sense that the average (quantum expectation value) of its momentum will be, and stay, zero. However, the uncertainty principle tells you that once the spread (dispersion) of coordinate $\Delta x$ is very small, the spread of momentum $\Delta p$ will be very large. Therefore, even if you initially localize the particle to a very narrow wave packet, it will broaden quickly with time. In fact, this broadening will be the faster, the sharper was the initial localization of the particle. If the wave function is initially Gaussian, then for a free particle you can solve the Schroedinger equation exactly and see that the wave function remains Gaussian, just its width grows (asymptotically as $\sqrt t$). So after some time, the particle is no longer localized, as a consequence of the very same uncertainty principle.
Even if the particle is not free but moves in some potential, making the initial wave packet at $t=0$ very narrow will result in the same spreading since the average kinetic energy (which is proportional to $\Delta p^2$ if the average momentum is zero) is much higher than the variation of the potential energy within the size of the wave packet.
There is one caveat in my above argument though. If you, simultaneously with narrowing down the wave packet, confine the particle by an increasingly strong potential, then you can keep it localized. Consider as a model the harmonic oscillator, defined by the Hamiltonian
$$
H=\frac{p^2}{2m}+\frac12m\omega^2x^2.
$$
The coherent states are Gaussian wave packets which thanks to the special form of the potential remain localized: both $\Delta x$ and $\Delta p$ are time-independent and given explicitly by
$$
\Delta x=\sqrt{\frac{\hbar}{2m\omega}},\quad
\Delta p=\sqrt{\frac{m\hbar\omega}2}.
$$
If you now take the limit $\omega\to\infty$, the Gaussian packet goes asymptotically to the $\delta$-function. This corresponds to your particle localized infinitely close to $x=0$. The prize for this is that you have to make the potential infinitely strong, which simultaneously makes the particle oscillate with infinite frequency around the origin. So you cannot quite say that its momentum is zero.

A: The Heisenberg uncertainty principle says that $\Delta(x)\cdot\Delta(p)\ge \hbar $.
This means that in order to measure the position $x$ one loses knowledge of the value of the momentum fulfilling the inequality.
Your assumptions on the momentum argument are wrong.

since the particle is totally static, its velocity should be 0, so is its momentum

Totally static (which is not a quantum mechanical possibility anyway) means that the $\Delta p$ is infinitesimally small, which means that the position $x$ is not known for the Heisenberg uncertainty to hold.
It is two different QM situations.

A: You can localize a particle in a strong potential, like atomic one. Take an electron in the field of atomic nucleus $Z$ and look at its localization when $Z\to\infty$. You have space and momentum wave functions that answer your questions. In particular, one cannot have a static localized electron, but orbiting the nucleus.

A: 1) Imagine that the wavefunction at $t=0$ is completely localized at $x=0$,
$$\Psi(x,t=0)~=~\delta(x),$$
with
$$\langle(\Delta\hat{x})^2\rangle_{t=0}~=~0, $$
and
$$\langle(\Delta\hat{p})^2\rangle_{t=0}~=~\infty. $$
2) To answer whether the system evolves or not, let us consider the wavefunction $\Psi(x,t=t_1)$ for some future time $t=t_1>0$. If the wavefunction $\Psi(x,t)$ should continue to be localized at $x=0$, we must demand that the position operator $\hat{x}$ commutes with the Hamiltonian $\hat{H}$. In a realistic system, this is not the case (because of the kinetic part in $\hat{H}$). Instead the wavefunction spreads out
$$\langle(\Delta\hat{x})^2\rangle_{t=t_1}~>~0, $$
which means that there is a non-zero chance that the particle will move to the left or to the right in position space. It could still happen that the momentum would vanish in average,
$$\langle\hat{p}\rangle_{t=t_1}~=~0. $$
But that does not imply that one couldn't record a non-zero momentum measurement at $t=t_1$.


text:
Q: Unable to start debugging on the web server. The underlying connection was closed: An unexpected error occurred on a send We are developing a SOAP-based WCF Service in Visual Studio:

The virtual directory did get created.  However, when I try to run the code in Visual Studio 2015 (F5) Debug mode, it give me the following error:

Unable to start debugging on the web server.  The underlying
  connection was closed: An unexpected error occurred on a send

The aforementioned error started showing up when our company changed their Windows Domain name. How I can resolve the problem?
Here are the technologies used in our development environment:

*

*Windows Server 2012 R2 Standard 64-bit Operating System, x64-based processor

*Microsoft Visual Studio Enterprise 2015 Version 14.0.25431.01  Update 3

*Internet Information Services ( Version 8.5.9600.16384 )

A: 1- Select your site in IIS.
2- Go to top-right and click on bindings.
3- Select your application and click edit.
4- Select a SSL certificate, if it doesn't exist then you may need to create
it.

A: I needed to make a Fake Self-Signed Certificate, and associate it with the https 443 port of the Web site as the picture below shows:

A: For me it worked after windows update.

*

*Go to settings then update & Security.

*Click on check online for updates from Microsoft update -> It will start downloading the updates and will installing automatically.

*once installation and downloading completed it will ask for restart then go for restart the system and then try.


text:
Q: How can I detect when someone opens the slave side of a pty (pseudo-terminal) in Linux? Having more than one process read from a serial device (/dev/ttyXX) makes it so that both processes can't get all of the data -- the data will be split between them in some way.  I'd like to write a program that reads from a serial device, creates several master/slave pty pairs, and then allows programs that were made to read from the serial device to instead read from the ptys so that all reading processes receive the data from the serial device and have the ptys act like the serial device in the sense that when they start reading from the pty they get only the most recent data.  In other words, you won't get any data that was written before you started to read (it's my experience that this is how /dev/ttyXX devices work, or at least the RS-232 anemometer I'm reading from).  Named pipes can mimic these semantics by trapping SIGPIPE to determine that there is no reader and thus we can choose not to write to that particular named pipe.  However, some binaries that were written to use terminals may fail when talking to named pipes, as checks for isatty() and the errno condition on calls like tcsetattr() can cause failing conditions.  The key here is to be able to use existing binaries that were written for a terminal.
So, if I can detect when the slave side of the pty is opened for reading, this should give me roughly the same semantics as there being no SIGPIPE in the named pipe case.  I notice that HP-UX has TIOCTRAP as an ioctl() command which seems to do exactly what I want, but sadly it is not available on Linux.
I've been reading references for days and the number of options for this type of thing is staggering.  The answer might lie in the terminal settings, blocking/non-blocking behavior, setting buffer sizes somewhere, conditions reported from poll()/select(), or some combination.  I can't seem to find anything, though.  I'm wondering if it's possible that I need to write my own device driver, but it seems like I should be able to do this without going that far.
So, for clarification:
- The question is: How can I detect when someone opens the slave side of a pty (pseudo-terminal) in Linux?
- I want a reader opening the slave side of the pty to receive data written strictly after the reader opens the pty (if my multi-writing process just writes data for a while before the reader opens the slave side, the data will buffer up and eventually the writer will block and the slave reader, upon opening, will immediately get all the buffered data -- this is not desirable as I want it to get only data generated in the immediate temporal vicinity)

- It must be a pty, not a named pipe, socket, etc, as isatty() and tcsetattr(), etc need to be OK so that existing binaries work

A: Add an inotify watch on the slave pty and poll on that.  You can get an inotify event on open.  You can then poll on the inotify file descriptor and the master pty file descriptor.  You can get an inotify event for open (IN_OPEN).  This will unblock the poll when the slave side is opened.

A: The reason you can't find this is because there's no documented interface specifically to allow it.  However, there is a trick that allows you to do it.  After opening the pseudo-terminal master (assumed here to be file descriptor ptm), you open and immediately close the slave side:
close(open(ptsname(ptm), O_RDWR | O_NOCTTY));

This sets the HUP flag on the tty master.  You now poll the HUP flag regularly with poll() (say, whenever data comes in from your data source):
struct pollfd pfd = { .fd = ptm, .events = POLLHUP };
poll(&pfd, 1, 10 /* or other small timeout */);

if (!(pfd.revents & POLLHUP))
{
    /* There is now a reader on the slave side */
}

If the reader ever goes away, POLLHUP will be set again.
In your case, you probably don't even need to remember from one loop to the next whether a given pty has a reader - just block on read() on your data source, then when data is available, simultaneously poll() all of your master ttys and send the data to any of them that do not have POLLHUP set.


text:
Q: Android app: text getting cropped on smaller devices We are developing an android app. The text displaying properly on 5" devices. But getting cropped on smaller devices (4", 3.5"). why is it happening? Any help welcome. Please see screenshots below. "Credit" "Debit" and "Net" displayed instead of "Credit Card" "Debit Card" and "Net Banking" in screenshot below.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="#ffffff" >
    <include android:layout_width="match_parent"
              android:layout_height="wrap_content"
              layout="@layout/sdk_header"
              />

 <RelativeLayout
     android:id="@+id/topLogoLayout"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:orientation="vertical"
      android:layout_marginTop="0dp"
      android:layout_marginRight="0dp"
      android:layout_marginLeft="0dp"
      android:layout_marginBottom="-11dp"
      android:background="#e5e5e5"
      android:paddingTop="10dp"
      android:paddingBottom="20dp">

  <TextView
      android:id="@+id/youtxt"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignParentLeft="true"
      android:gravity="right"
      android:layout_marginTop="5dp"
      android:text="You"
 android:textSize="40sp"
 android:textColor="#727272"
 android:layout_marginLeft="10dp" />

 <RelativeLayout
     android:id="@+id/arrowLayout"
     android:layout_toRightOf="@+id/youtxt"
     android:layout_toLeftOf="@+id/companyLogo"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:layout_marginTop="5dp"
     android:layout_centerHorizontal="true">

  <TextView
      android:id="@+id/txt_amount"
      android:layout_height="wrap_content"
      android:layout_width="wrap_content"
      android:layout_alignParentTop="true"
      android:layout_centerHorizontal="true"
      android:text="Rs. 10"
      android:textColor="#727272"
      android:textSize="18sp" />

   <ImageView
      android:id="@+id/arrow"
      android:layout_width="wrap_content"
      android:layout_height="18dp"
      android:src="@drawable/arrow"
      android:layout_below="@+id/txt_amount" />

  </RelativeLayout>

  <ImageView
      android:id="@+id/companyLogo"
      android:layout_marginTop="5dp"
      android:layout_marginRight="30dp"
      android:layout_width="70dp"
      android:layout_height="50dp"
      android:layout_alignParentRight="true"
      android:src="@drawable/wallet_logo"
      android:scaleType="fitXY" />
  </RelativeLayout>

  <ImageView
      android:id="@+id/orange_line"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:layout_alignParentRight="true"
      android:src="@drawable/orange_line"
      />
  <com.viewpagerindicator.TabPageIndicator
      android:layout_marginTop="0dp"
      android:id="@+id/indicator" android:layout_height="wrap_content" android:layout_width="fill_parent" />
  <android.support.v4.view.ViewPager android:id="@+id/pager" android:layout_width="wrap_content" android:layout_height="wrap_content" >

  </android.support.v4.view.ViewPager>

</LinearLayout>

A: This is a complex topic on which a book could be written (and probably has). I'll focus on the only problem I can see: text size.
It seems that your fonts are too big on the small screen. This affects what appear to be tabs and buttons, although the EditText has the problem too (it just doesn't overflow).
The useful way of measuring screen size is the sw-dp (shortest width device independent pixel). The dp density is adjusted so that it is around 160dpi on all devices. For a 5" tablet that will be around a 3" width and it should be an sw480dp device. The 3"-3.5" screen has around a 2" width and should be an sw320dp device.
To make this work at the simplest level, you need to place some text size settings in your value-sw240dp folder that are about 3/4 of the text size for your default sw480dp device.
For example, this might appear in your dimen file in that folder.
<dimen name="view_field_text_size">14sp</dimen>

I can't give you a cookbook because I have no info about your other use of styles or dimensions. Perhaps in a layout you might have:
<EditText
   <android:textSize="@dimen/view_field_text_size"
/>

It's better to put it in a style, but that's outside the scope here.

A: Different devices may have different pixel density, screen size, Orientation, Resolution and Density-independent pixel (dp).
Solution -

*

*Define different layout files for different screen sizes.

*Ensuring your layout can be adequately resized to fit the screen

*Providing appropriate UI layout according to screen configuration

*Ensuring the correct layout is applied to the correct screen

By default, Android resizes your application layout to fit the current device screen. In most cases, this works fine. In other cases, your UI might not look as good and might need adjustments for different screen sizes. For example, on a larger screen, you might want to adjust the position and size of some elements to take advantage of the additional screen space, or on a smaller screen, you might need to adjust sizes so that everything can fit on the screen.
The configuration qualifiers you can use to provide size-specific resources are small, normal, large, and xlarge. For example, layouts for an extra large screen should go in layout-xlarge/.
Beginning with Android 3.2 (API level 13), the above size groups are deprecated and you should instead use the swdp configuration qualifier to define the smallest available width required by your layout resources. For example, if your multi-pane tablet layout requires at least 600dp of screen width, you should place it in layout-sw600dp/. Using the new techniques for declaring layout resources is discussed further in the section about Declaring Tablet Layouts for Android 3.2.
Look - Multiple Screen Support  and Support Screen training docs.

A: you just need to create different folders related to density or screen size like
Option 1.
values-large
values-small
values-normal

For more explanation check this link...
Multiple Screen Support
Option 2.
mTextView.setTextSize(16 * getResources().getDisplayMetrics().density);

this will give TextSize depending on density..


text:
Q: Perl script works OK in command prompt, but fails on ODBC as a CGI script Issue: Perl script works fine in command prompt, but fails on ODBC as a CGI script
Settings:
Win XP Pro 64 bit version 2003 SP2
Apache 2.2.17 Win32
Active Perl 5.12.2 (not Perl64)
an ODBC DSN is created for SQL SERVER
Details: from command prompt, Phone.pl runs OK - it gets query results as expected - which means DBI works fine
as a CGI script, Phone.pl prints HTML as expected before ODBC init code. (Apache settings work OK for non-ODBC script.)
here's the msg in error.log of Apache
[Tue Nov 23 13:27:57 2010] [error] [client 127.0.0.1] DBI connect('SQLSVR206','administrator',...) failed: [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified (SQL-IM002) at C:/CGI/Phone.pl line 32
Any idea why it behaves differently?
#!c:/perl/bin/perl.exe
use CGI qw(:standard);
use strict;
use warnings;
use DBI;

my ($sqlstr, $sql_UNITED, $dbh206);

# 206
# select * from getProvFINON('270762789')#TIN
my @colUNITED = qw/ADR_LN_1_TXT  PROV_SYS_ID  ZIP_CD  FULL_NM  SOURCE  PROV_TIN  BILL_TEL/;

sub Init(){
    $dbh206 = DBI->connect ("dbi:ODBC:SQLSVR206",'USER','PASSWORD',{RaiseError=>1})
        or die $DBI::errstr;
    $sqlstr = qq/ select * from getProvFINON(?) /; #parameters TIN
    $sql_UNITED = $dbh206->prepare($sqlstr)
        or die "prepare failed: " . $dbh206->errstr();
}

sub test1{
    my $tin = shift();
    $sql_UNITED->execute($tin) or die $sql_UNITED->errstr;
    my $row = $sql_UNITED->fetchrow_hashref;
    while(defined ($row)){
    foreach(@colUNITED){
        print $row->{$_}."~~~";
    }
    print "<p>";
    $row = $sql_UNITED->fetchrow_hashref;
    }
}

print header;
print "test text<p>";
Init();
test1('270762789');
print "999999999999<p>";

==========================================================
UPDATE: part of the problem is the 32-bit VS 64-bit ODBC issue
see http://support.microsoft.com/kb/942976
HOWEVER, after I set up ODBC, I still got following error in Apache log
[Wed Nov 24 01:38:48 2010] [error] [client 127.0.0.1] DBI connect('SQLSVR206-32','',...) failed:              [Microsoft][ODBC SQL Server Driver][SQL Server]Login failed for user 'MYDOMAIN\GARY$'. (SQL-28000) at C:/CGI/test.pl line 15
I logged in as MYDOMAIN\administrator and started Apache.
ODBC was set up to use "With Windows NT authentication using the network login ID" Where does this "MYDOMAIN\GARY$" come from? Thanks!
==========================================================
FINAL UPDATE: Apache services runs using "Local System account", and that's where the "MYDOMAIN\GARY$" comes from. The thing is GARY is not with the company and his ID has been dropped from SQL Server, but ODBC code in CGI inherited GARY from Apache, resulting in error 28000.
So the problem was a convolution of
1) 32/64 bit ODBC DSN and
2) default account used by Apache

A: Maybe the ODBC datasource is listed under 'User DSN' and not 'System DSN'.  I think that the identity that your web server runs as only has access to System DSN.
In case my post doesn't make sense, I'm editing it in order to add a link to information about the difference between User vs. System DSN's: http://www.truthsolutions.com/sql/odbc/creating_a_new_odbc_dsn.htm

A: Something is up with Windows 7 ODBC connections that I can't figure out either.  I'd set up the ODBC and it would test fine but get a similar error as you show.  Even connecting MS SQL Server Mgmt Studio to some SQL servers I have to explicitly put in extra connection settings.  Since I only have the issue on some SQL servers (which I don't own) I think it's a server side problem.
On PERL i finally gave up and just created the DSN file with said extra connection settings and pointed to it directly.  Note how the server name is there twice.
use DBI;
use SQL::Abstract;
my $CONNECT = "FILEDSN=thefile.dsn";
my $dbh = DBI->connect("dbi:ODBC:$CONNECT", "myidsid", "passwordThatsNotUsed");

with the ODBC file looking something like:
[ODBC]
DRIVER=SQL Server Native Client 10.0
UID=myidsid
Address=servername,3180
Network=DBMSSOCN
APP=Microsoft® Windows® Operating System
Trusted_Connection=Yes
SERVER=servername
PWD=someTextInPlaceOfPasswordAsItsNotUsed


text:
Q: Is sa_sigaction is thread safe?   struct sigaction action;

  action.sa_sigaction = ChildHandler;
  sigfillset (&action.sa_mask);
  action.sa_flags = SA_SIGINFO;

  sigaction (SIGCHLD, &action, NULL);

void ChildHandler (int sig, siginfo_t *sip, void *notused)
{
int x= 7;
int y = 9;
int z = x + y ;
int y=1;
}

function ChildHandler called when SIGCHLD is arrived.
How that implement? do I need to protect ChildHandler with lock?
Otherwise in the example if 2 signal will arivved in the same time , the code cala will be wrong


text:
Q: Custom wp_query with working pagination on a page template I'm trying to add a custom query to a WordPress template and include pagination but my pagination isn't appearing, for example's sake I'm trying to add this to page.php.
I have the following markup which works perfectly when place inside a category template like category.php, the pagination shows up and functions just fine. The issue is that the pagination doesn't appear when the same code is place in page.php or any custom page template.
The query:
              <?php
                $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
                $loop = new WP_Query(
                    array(
                        'post_type' => 'post',
                        'posts_per_page' => 10,
                        'paged' => $paged,
                        'orderby' => 'desc',
                    )
                );
              ?>

              <?php if ($loop->have_posts()): while ($loop->have_posts()) : $loop->the_post(); ?>

                // Loop Markup goes here.

              <?php endwhile; ?>
              <?php endif; ?>

              <?php wp_reset_query(); ?>

              <?php pagination(); ?>

Pagination() as defined in functions.php:
              function pagination() {
                  global $wp_query;
                  $big = 999999999;
                  echo paginate_links(array(
                      'base' => str_replace($big, '%#%', get_pagenum_link($big)),
                      'format' => '?paged=%#%',
                      'current' => max(1, get_query_var('paged')),
                      'total' => $wp_query->max_num_pages
                  ));
              }
              add_action('init', 'pagination');

I've seen a few posts requesting help on the same subject, but I didn't come across an elegant solution.
Any advice would be much appreciated! My knowledge of PHP is pretty limited, I took the pagination() function from the HTML5 Blank theme by Todd Motto so I don't 100% understand what that function defines.

A: Managed to find a solution by merging my code from the original post with the following code from this tutorial:
I'm posting a complete example of a simple page.php for anyone lost and needing more context to implement this, this works perfectly for me with no broken aspects like each page number returning the same posts or anything.
<?php get_header(); ?>

    <?php if (have_posts()): while (have_posts()) : the_post(); ?>

              <?php
                if ( get_query_var('paged') ) {
                    $paged = get_query_var('paged');
                } elseif ( get_query_var('page') ) { // 'page' is used instead of 'paged' on Static Front Page
                    $paged = get_query_var('page');
                } else {
                    $paged = 1;
                }
                $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
                $loop = new WP_Query(
                    array(
                        'post_type' => 'post',
                        'posts_per_page' => get_option('posts_per_page'),
                        'paged' => $paged,
                        'post_status' => 'publish',
                        'orderby' => 'desc',
                        'orderby' => 'date' // modified | title | name | ID | rand
                    )
                );
              ?>

              <?php if ($loop->have_posts()): while ($loop->have_posts()) : $loop->the_post(); ?>

                // Loop code goes here.

              <?php endwhile; ?>

              <?php if ($loop->max_num_pages > 1) : // custom pagination  ?>
                <?php
                  $orig_query = $wp_query; // fix for pagination to work
                  $wp_query = $loop;
                  $big = 999999999;
                  echo paginate_links(array(
                      'base' => str_replace($big, '%#%', get_pagenum_link($big)),
                      'format' => '?paged=%#%',
                      'current' => max(1, get_query_var('paged')),
                      'total' => $wp_query->max_num_pages
                  ));
                  $wp_query = $orig_query; // fix for pagination to work
                ?>
              <?php endif; ?>

              <?php wp_reset_postdata(); else: echo '
'.__('Sorry, no posts matched your criteria.').'
'; endif; ?>

    <?php endwhile; ?>
    <?php endif; ?>

<?php get_template_part('footer'); ?>


text:
Q: why web service is called asynchronously? What is the reason behind it? Why web service is called asynchronously? What is the reason behind it?

A: "Asynchronous" means "not at the same time as other things". The only other "things" are the normal page loads, and these requests happen independently, hence they are "asynchronous".


text:
Q: RSpec - Test against actual files, not mock data I'm very new to RSpec, so this is quite a basic question. I'm writing something which parses a lot of data from a file, does some processing and returns a summarised result, which is all very lovely to do with Ruby.
I want to put some RSpec tests around this code but I do not want to mock up data inside the test. The files are big and complex and since I want the code to work with these files I want to work directly with some in the tests.
I have done a lot of Googling and I've been unable to find any examples of best practices for such a situation - everything I find seems to suggest mock data instead.
So, to be clear, I'd like to know the best practices for running RSpec tests against actual test data files and not against something mocked up in the test code its self. I'm perfectly happy opening files, reading them, etc., that's not the problem. What I'm really interested in is how best to structure my tests and test data directories.

A: What I have done in the past is to create a data folder within the specs folder to hold the files I want to read from.
I understand your motivation for wanting to use the actual files, since there are usually all sorts of little edge cases within an actual file that you may not think of on your own. My advice would be to have a test that opens the file and tests for the information that you want. But also, if that test fails, create a new test to address the particular issue within the file that you found.
For example, suppose that when trying to open the file you find that it doesn't properly handle non-UTF8 data. Create a new test with the line in question as the data used (rather than simply leaving it as part of the larger test). That way, if it ever fails again, you'll be able to pinpoint exactly where the pain point is.

A: Rails has a test/fixtures directory for structured sample data.
https://guides.rubyonrails.org/testing.html#fixtures-in-action


text:
Q: Symfony switch language I use symfony 1.4.11 .User can switch language , in my layout I have
<?php foreach (sfConfig::get('app_cultures_enabled') as $key => $lng): ?>
    <?php echo link_to_if($sf_user->getCulture() != $lng,
    "",
    preg_replace('/sf_culture=[a-z][a-z]/', 'sf_culture='.$lng, $sf_context->getRouting()->getCurrentInternalUri(true)))?>
  <?php endforeach ?>

So in each page I generate link, that I can switch language.
But I have page with next rout:
page:
  url:   /:sf_culture/page/:slug
  param: { module: page, action: show}
  requirements: { sf_culture: (?:se|no|en), sf_method: GET }

And when I go to this page I have error, that :
The "/:sf_culture/page/:slug" route has some missing mandatory parameters (:slug).
I think that problem in
<?php echo link_to_if($sf_user->getCulture() != $lng,
        "",
        preg_replace('/sf_culture=[a-z][a-z]/', 'sf_culture='.$lng, $sf_context->getRouting()->getCurrentInternalUri(true)))?>

it can not generate link with slug, or..

A: If I'm reading this right, it looks like you're trying to mimick the slug variable using $sf_context->getRouting()->getCurrentInternalUri(true).
I've never done a language switch link this way but basically if that works, you need to pass it as a variable called "slug" to the routing. Somewhere in that magical link_to_if() function you need to have:
'&slug=' . $slug // the slug!

... given that slug is a named parameter that the routing rule is expecting.
UPDATE:
This is how I'd normally change language:
I'd create a separate action (e.g. changeLanguage) without a template, and then create links to it with the language as a parameter:
mysite.com/change-language/fr/ (?lang=fr)
mysite.com/change-language/de/ (?lang=de)
mysite.com/change-language/es/ (?lang=es)

In that action, I use $this->getUser()->setCulture($lang) to change language and anything else I want to do, and then use $this->redirect($request->getReferer()) to redirect the user back to the page they came from. If your app needs to use multi-language URLs, I would ensure that those get rendered on their own pages from a URL parameter (like the "slug"). And if you're doing this with SEO in mind, things also get a little more complicated because you should link directly to different language pages instead of using re-directs etc (to pass link juice).
Hope that helps.


text:
Q: How does SQL Server internally rename a table? Using Microsoft SQL Server 2014, we are performing some operations which require re-building a table structure. We have narrowed down our approach to two methods:

*

*Create new "temporary" table (Not the #TempTable kind), dump data into temp table, delete original, then dump the data back.

*Rename existing table, create new table, then dump the data from temp to new.

My colleague insists #1 is the ideal option to choose. However, I'm convinced that #1 will take twice as much time as #2 (since we have BLOB data consuming massive storage). Colleague claims that when you rename a table, internally, SQL Server creates a new table and dumps the data over anyway. I highly disagree. I'm sure that SQL Server just simply modifies the name of the existing table. While searching for how this actually works, I cannot find any information.
So how does SQL Server internally rename a table? Does it create a new table, dump the data, then delete the old one? Or does it simply modify the name?

A: Does it make sense?
sp_helptext 'sp_rename'


text:
Q: The boost asio endpoint class As described in the boost documentation :
ip::basic_endpoint::port (1 of 2 overloads)
unsigned short port() const;

This getter gets the port associated with the endpoint. The port number is always in the host's byte order.
I know that Little-endian byte ordering places the least significant byte first.
However, Big-endian byte ordering places the most significant byte first.
in C language, we use those functions :
uint32_t htonl(uint32_t hostlong);
uint16_t htons(uint16_t hostshort);
uint32_t ntohl(uint32_t netlong);
uint16_t ntohs(uint16_t netshort);

How to get the correct port number in boost asio?
Thanks

A: https://www.boost.org/doc/libs/1_69_0/doc/html/boost_asio/reference/ip__basic_endpoint/port.html

This getter gets the port associated with the endpoint. The port number is always in the host's byte order.

So, since you call the function on that host, just calling the function returns you the correct port.
I suppose this "strange" comment came about when the authors of the library were implementing the lower layers of some protocols/thinking of raw sockets. Just a warning that you need to do the transformation to network byte order if you are implementing specific protocols. This makes the comment almost completely redundant at the level of abstraction that basic_endpoint provides, but who knows maybe it was something someone forgot to adhere to once when implementing (a specialization of) it.

A: The problem is that the UDP is a connectionless protocol. Therefore, the remote_endpoint holds a garbage after sending data.
The code that proves that
boost::system::error_code ec;
boost::asio::ip::udp::endpoint endpoint = socket.remote_endpoint(ec);
if(ec)
{
    std::cout << "An error occurred." << '\n';
    std::cout << ec.value() << " " << ec.message() << '\n';
    return;
}

output :
An error occurred.
107 Transport endpoint is not connected


text:
Q: How let cmd output less info I have a batch file, for example: test.bat, there is only one command in it:
echo Hello

Then I run it:
D:\cmd\test.bat

Then it outputs the result:
 //output begin
                     -- This is a blank line, I don't want this
 D:\cmd\echo Hello   -- This is not what I want
 Hello               -- I only want to print this line
                     -- This is a blank line, I don't want neither.
 //output end

I only want to print the output of  commands run in the batch file, here is the echo command.
But, there are two blank lines, one is at the head of the result, and the other one is at the end of the result. And the D:\cmd\echo Hello in the result is neither not what i want.
What should I do?  Any help would be great, thanks in advance.

A: Just put
@echo off

in the first line of your batch file. This will prevent output of the command's invocation when they are run (as does prepending a command with @), so it eliminates all the lines that bother you.
Taken from http://ss64.com/nt/echo.html
Type ECHO without parameters to display the current echo setting (ON or OFF).

In most batch files you will want ECHO OFF, turning it ON can be useful when
debugging a problematic batch script.

In a batch file, the @ symbol is the same as ECHO OFF applied to the current line only.

Normally a command is executed and takes effect from the next line onwards, @
is a rare example of a command that takes effect immediately.


text:
Q: Google maps like auto-complete or auto-suggest API for postal addresses I'm part of a project that requires auto-complete or auto-suggest feature for postal addresses (something similar to what google maps has). As the user starts to type in the number and then the street google starts to suggest valid options. I would like to know if there is an api (even commercial) available in the market.
Note: I'm not looking for an address validation API.
I could also buy a address database and implement this on top of it. But thats a lot of Dev overhead involved if we need to build something robust and sophisticated. Any good pointers will help.
Thanks
Bala

A: This looks to give you a solution similar to the one you are searching for.  If you  replace the on_click event with the Javascript onkeyup you should then be able to check the address realtime.
This is a quick step-by-step integration guide describing how to add a RapidAddress postcode based address finder to a HTML website. We recommend you read the JavaScript user guide first.
Step #1
Download the latest version of the JavaScript class from the downloads section. You could also use the integration pack, it contains ready made HTML pages that may be handy as a starting point.
Upload the JavaScript file crafty_postcode.class.js to your webserver and reference it in your HTML, you may have to use relative or absolute paths in the src property:

NOTE: the "ISO-8859-1" bit is important as the JS script is compressed.
Step #2
Create and configure the JavaScript object:

Step #3
Create an address form in HTML:
<form method="post" name="address">
 Postcode:

 <input type="text" name="postcode"/>
 <button type="button" onclick="cp_obj.doLookup()">Find Address</button>

 Company:

 <input type="text" name="companyname"/>

 Address:

 <input type="text" name="address1"/>

 <input type="text" name="address2"/>

 <input type="text" name="address3"/>

 Town:

 <input type="text" name="town"/>

 County:

 <input type="text" name="county"/>
</form>

NOTE: "companyname", "address2/3" and "county" are optional, you can leave these  fields out if it suits your site. Remember to delete also them from the JavaScript config in step 2. For example if you do not want the county field : cp_obj.set("elem_county", "");
Note the 'Find Address' button, the onclick action calls the doLookup() method.
The address results (or an error message) will be placed in the element with id="crafty_postcode_result_display".
All done!
If things don't work for any reason, email any error codes/messages to us. We will be happy to help. You may also want to read the JavaScript user guide, if you haven't already.
As found at:
http://www.craftyclicks.co.uk/web-service/docs/javascript-address-finder-how-to-add-rapidaddress

A: You can use googles geo autocomplete api
http://code.google.com/p/geo-autocomplete/
This will give you the same auto-complete for locations that you would get on googlemaps.


text:
Q: Drawing interval charts in excel Is it possible to draw such charts in excel? How?

A: This was a fun one. I don't know if there's a good way to extend the functionality of the existing box-and-whiskers charts in Excel, but luckily I was able to come up with a quick-and-dirty way to fake it with a scatterplot. Basically, we're just going to iterate along the intervals and pick enough points to display on a scatterplot that it looks indistinguishable from a box-and-whiskers. Because it makes every interval a different series, you can also format things like coloring to more easily distinguish them.
Here's the end result for some of my data (you can modify the markers used by underlying scatterplot to change things like the line thickness):

The code is looking for a formatted table with names for each series and separate columns for the min/max of each dimension. Here's how the input table is formatted:

And lastly, here's the macro I run to generate it:
' Build and display an "Interval Chart"
Public Sub MakeIntervalChart()
    Dim inRow As Long, outRow As Long, lastRow As Long, startRow As Long
    Dim interX As Double, interY As Double, intervalAmt As Double
    intervalAmt = 0.01 ' CHANGE ME

    ' Source / Destination Worksheet Parameters (CHANGE ME)
    Dim wsSource As Worksheet, wsDest As Worksheet
    Set wsSource = Worksheets("Data")
    Set wsDest = Worksheets.Add()
    wsDest.Name = "IntervalChart"

    ' Create output chart
    Dim boxChart As Chart
    Set boxChart = wsDest.Shapes.AddChart2(240, xlXYScatter).Chart
    boxChart.HasLegend = True

    outRow = 1
    lastRow = wsSource.Cells(wsSource.Rows.Count, 1).End(xlUp).Row

    For inRow = 2 To lastRow
        ' Retrieve current interval (CHANGE ME)
        Dim seriesName As String
        Dim minX As Double, maxX As Double, minY As Double, maxY As Double
        seriesName = wsSource.Cells(inRow, 1)
        minX = wsSource.Cells(inRow, 2)
        maxX = wsSource.Cells(inRow, 3)
        minY = wsSource.Cells(inRow, 4)
        maxY = wsSource.Cells(inRow, 5)

        startRow = outRow

        'intervalAmt = (maxX - minX) / 50.0

        ' Top and Bottom of box
        For interX = minX To maxX Step intervalAmt
            wsDest.Cells(outRow, 1) = seriesName
            wsDest.Cells(outRow, 2) = interX
            wsDest.Cells(outRow, 3) = minY
            outRow = outRow + 1
            wsDest.Cells(outRow, 1) = seriesName
            wsDest.Cells(outRow, 2) = interX
            wsDest.Cells(outRow, 3) = maxY
            outRow = outRow + 1
        Next

        'intervalAmt = (maxY - minY) / 50.0

        ' Left and Right of box
        For interY = minY To maxY Step intervalAmt
            wsDest.Cells(outRow, 1) = seriesName
            wsDest.Cells(outRow, 2) = minX
            wsDest.Cells(outRow, 3) = interY
            outRow = outRow + 1
            wsDest.Cells(outRow, 1) = seriesName
            wsDest.Cells(outRow, 2) = maxX
            wsDest.Cells(outRow, 3) = interY
            outRow = outRow + 1
        Next

        ' Add new series (box)
        With boxChart.SeriesCollection.newSeries()
            .Name = seriesName
            .XValues = wsDest.Range("B" & startRow & ":B" & outRow - 1)
            .Values = wsDest.Range("C" & startRow & ":C" & outRow - 1)
        End With
    Next
End Sub

You'll want to change things like the input/output sheet names and the expected format of the input table (assuming you don't want to be stuck with my format). You'll also want to tune the 0.01 parameter for your data. I left it with a very small interval you'll be able to use with the sort of sample data you. You can either tweak this increment value to something other than 0.01 depending on your needs, or you can use the code in the commented lines intervalAmt = (maxX - minX) / 50.0 and tweak the 50.0 value (which will be the number of markers to draw for each segment of the boxes). Be careful with tweaking these values - you could easily end up wasting tons of time generating way more markers than you need in order to achieve a straight line.

A: JavaScript has powerful libraries such as Highcharts and D3 to draw graphs like this, and Funfun enables to code JavaScript in Excel. Try this solution with Highcharts on the website, and tell me if it's what you want:
https://www.funfun.io/1/edit/59f9d122ff5aa66c5ca8b9ee
Once you are satisfied with a solution, you can directly load it into your Excel by the same link, thanks to the Funfun Excel add-in. Here are screenshots:

Of course, you can edit the data and the code in Excel as you want:


text:
Q: How to avoid rounding numbers having more than 16 digit precision in Javascript Objective is to read data from json file using node js. Observed that numbers with more than 16 digit precision are rounded.
Code:
var raw = fs.readFileSync(file);
JSON.parse(raw);

Result:
0.59190000000000009 is rounded to 0.5919000000000001

4647.3424257097241 to 4647.342425709725

6441579.5333300168 to 6441579.533330017


text:
Q: Issue with PHP/MYSQLi Password validation using salt I am having an issue getting the password being stored on in mysql to match the Login password using salt.
Here is the code from my password creation:
        $hash = hash('sha256', $password);

        function createSalt()
        {
        $text = md5(uniqid(rand(), true));
            return substr($text, 0, 3);
        }

        $salt = createSalt();
        $password = hash('sha256', $salt . $hash);

Here is the code in my login page:
        $userData = $result->fetch_array(MYSQL_ASSOC);

        $hash = hash('sha256', $password);

        $password = hash('sha256', $userData['salt'] . $hash);

        //$hash = hash('sha256', $userData['salt'] . hash('sha256', $password) );

        if($password != $userData['Password']) // Incorrect password. So, redirect to login_form again.

There are no errors creating the password in mysql (the field is populated with i.e 0d02a88c1e1057a64df6b3fed4c6ad64e228313b803e9f9b36...
While the Login creates something like: 51839f9a15dac1f26825f4cd5d2ecf7ae83ea88d440415b04fb6ae41c3a0566f
Just not sure where the issue is. Thanks in advance, I am very new to PHP.

A: First, you have some confusing variable naming here - you use $password to represent both the plaintext password and the salt-and-hashed representation. That makes it harder to read your code.
Second, let's look at your code as a series of states to find where they might be going wrong:

*

*Password entry. Is the same string being passed in both cases? Have you paid attention to whitespace and capitalization? Use a debugger to verify. If the plaintext password is not byte-for-byte identical, the initial sha256 hash should show differences at this point.

*Salt generation/retrieval. Did you save/retrieve the exact same salt, byte-for-byte? Again, watch for whitespace/capitalization and also check that your database isn't silently truncating or changing the encoding for the string.

*Compare the strings after they have been concatenated but before the second sha256 hash operation. By definition, since the final output is different, either your plaintext password or salt is not byte-for-byte identical. This will help you tell if one or both are the culprits.

A: Make your life easier and store your passwords more safe, with the function password_hash().
The SHA-* algorithms are not appropriate for hashing passwords, because they are ways too fast. The function password_hash() will not only calculate a better suited BCrypt hash, it will also take care of the generation of a safe salt, and you won't have to store/retrieve the salt in a separate database field (it will become part of the resulting hash-value).
// Hash a new password for storing in the database.
// The function automatically generates a cryptographically safe salt.
$hashToStoreInDb = password_hash($password, PASSWORD_BCRYPT);

// Check if the hash of the entered login password, matches the stored hash.
// The salt and the cost factor will be extracted from $existingHashFromDb.
$isPasswordCorrect = password_verify($password, $existingHashFromDb);


text:
Q: sns.clustermap ticks are missing I'm trying to visualize what filters are learning in CNN text classification model. To do this, I extracted feature maps of text samples right after the convolutional layer, and for size 3 filter, I got an (filter_num)*(length_of_sentences) sized tensor.
df = pd.DataFrame(-np.random.randn(50,50), index = range(50), columns= range(50))
g= sns.clustermap(df,row_cluster=True,col_cluster=False)
plt.setp(g.ax_heatmap.yaxis.get_majorticklabels(), rotation=0) # ytick rotate
g.cax.remove() # remove colorbar
plt.show()

This code results in :

Where I can't see all the ticks in the y-axis. This is necessary
because I need to see which filters learn which information. Is there
any way to properly exhibit all the ticks in the y-axis?

A: kwargs from sns.clustermap get passed on to sns.heatmap, which has an option yticklabels, whose documentation states (emphasis mine):

If True, plot the column names of the dataframe. If False, don't plot the column names. If list-like, plot these alternate labels as the xticklabels. If an integer, use the column names but plot only every n label. If "auto", try to densely plot non-overlapping labels.

Here, the easiest option is to set it to an integer, so it will plot every n labels. We want every label, so we want to set it to 1, i.e.:
g = sns.clustermap(df, row_cluster=True, col_cluster=False, yticklabels=1)

In your complete example:
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import numpy as np

df = pd.DataFrame(-np.random.randn(50,50), index=range(50), columns=range(50))
g = sns.clustermap(df, row_cluster=True, col_cluster=False, yticklabels=1)
plt.setp(g.ax_heatmap.yaxis.get_majorticklabels(), rotation=0)  # ytick rotate
g.cax.remove()  # remove colorbar

plt.show()


text:
Q: multiply function I need to extract bit of a decimal number.
for example, y=52 (110100 to binary) and j=2..
so i need to return 1...
if j=3 return 0...
this is my function...
function int multiply(int x, int y) {

    var int tx;
    var int ty;

    let tx = x;
    let ty = y;

    let tx = Math.abs(x);
    let ty = Math.abs(y);

    var int shiftedX;
    let shiftedX = tx;

    var int result;
    let result = 0;

    var int i;
    let i = 0;
    while(i<16){
        if( i-th bit of ty = 1 )//pseudo code...
        {
            let result = result + shiftedX;
        }
        let shiftedX = shiftedX + shiftedX;
    }
    if(((x > 0) & (y < 0)) | ((x < 0) & (y > 0))){
        return -result;
    }
    return result;
}

I wrote in the "if" pseudo code
How can i do this with really code??

A: At the time of answering this question, it was tagged under C or C++...

First of all, get rid of the following symbols (as they are not part of the language):
- function
- var
- let

As to your question, you can use the following piece of code:
for (i=0; i<16; i++)
{
    if ((ty>>i) & 1)
    {
        result += shiftedX;
    }
    shiftedX <<= 1;
}

A: Jack appears to lack bitshifts, but that's OK, we can make the right mask in the same way as shiftedX is kept current (instead of doing tx << i), like this:
var int shiftedX;
let shiftedX = x;
var int mask;
let mask = 1;
var int i;
let i = 0;
while(i < 16){
    if((y & mask) = mask)
    {
        let result = result + shiftedX;
    }
    let shiftedX = shiftedX + shiftedX;
    let mask = mask + mask;
    let i = i + 1;
}

You can leave out the abs stuff and the sign-fix on the end (as long as you leave them both out), signed and unsigned multiplication are the same thing.

A: I'm one of the moderators at the official Nand2Tetris help forum
    http://nand2tetris-questions-and-answers-forum.32033.n3.nabble.com/
Be sure to check and post there for help, too.
Regarding signed versus unsigned multiplication:
When you multiply two 16-bit numbers, you get a 32-bit result.  The bottom 16-bits of this result is the same whether the numbers you are multiplying are signed or unsigned; only the upper 16-bits are different.
Since the Math.multiply routine only returns 16 bits, you don't need to worry about the signs of x and y.


text:
Q: What does the "=" do in ```export class NgForOfContext = NgIterable> {``` I was looking at the source for ngForOf in Angular and I came across this line:
export class NgForOfContext<T, U extends NgIterable<T> = NgIterable<T>> {

see: https://github.com/angular/angular/blob/master/packages/common/src/directives/ng_for_of.ts#L14
I played around with the = operator and changed it to & and |. However, even with the typescript docs I couldn't figure out what the = operator actually does.
Kind Regards

A: If you don't pass anything to U, then U will fall back to NgIterable<T> as a default value.
See docs


text:
Q: How many matrix colorings are possible? We have a small square matrix having size up to $8$. And we have a large number of colors up to $10^6$. In how many ways we can color the matrix so that all the same color cells are not adjacent? Cells are adjacent if there is any common edge between them.

A: let the cells be numbered like 1, 2,3 ... starting from top left corner we have $10^6$ ways for $1^{st}$ cell, $10^6-1$ for second to eight cell. considering $9^{th}$ as the one below $1^{st}$ cell the no of possible ways is again $10^6-1$, and for $10^{th}$ to $16^{th}$ cell the No of ways is $10^6-2$ and so on therefore the Total No of turns out to be $$10^6(10^6-1)^{7\times8}(10^6-2)^{7\times7}$$
if you assume $10^6-1 \approx 10^6-2 \approx  10^6 $ then the formula can be simplified to $10^{6*64}$ this i think is ok if colors can be re used