text:
Q: Manual install in Leak Canary 2? I've been one of user who uses Leak Canary 2.
Thanks to this stuff, I could fix memory leak bug in my app.
I recently noticed that (I may be late to know this) there was update Leak Canary 2.2, so I applied newer version to my app by adding line below in Manifest

debugImplementation 'com.squareup.leakcanary:leakcanary-android:2.2'

*

*Here problem appears
Before implementing leak canary, I wanted to make it start detecting memory leaks (also installing "Leaks" application) only when I turn on Developer mode thing in my app via setting. I'm sharing my app as apk file to make users able to test and find bug easily. If "Leaks" application is installed suddenly when users install my app even though they didn't turn on developer mode, they may not know what this app is and actually, it's only useful for me because other users won't understand what this app is saying. But according to this site, I don't need to put any codes to install leak canary; it will be auto-installed. I cannot prevent it from being installed to users' devices.
class MainActivity : AppCompatActivity() {

    companion object {
        var installed = false
        @JvmField
        var watcher: RefWatcher? = null
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        ....

        val shared = getSharedPreferences(StaticStore.CONFIG, Context.MODE_PRIVATE)

        if (!installed && shared.getBoolean("DEV_MODE", false)) {
            watcher = LeakCanary.install(application)
            installed = true
        }

        ....
    }
}

Code above is how I performed manual installing before Leak Canary 2.2. Referred from this answer. When app checks boolean (DEV_MODE) which is from shared preferences is true, then it allows installing, and make watcher checks other activities or threads. If I don't call LeakCanary.install(application), "Leaks" application won't be installed, so users can use my app without seeing this additional application. Of course, if they turn on developer mode, they can use memory leak detecting feature.
But there aren't method like LeakCanaray.install() (also RefWatcher too) now, so I cannot perform manual install like before...
Are there any ways to perform manual install in Leak Canary 2.2?
Do I have to give up making it not installed automatically and notice users "Leaks" application will be installed?

A: With the recent v2.6 update, the manual installation of LeakCanary changed.
Now you are required to add the following boolean resource:
<bool name="leak_canary_watcher_auto_install">false</bool>

And run the following API whenever you are ready to do a manual install with the default Watchers (Activity, Fragment, RootView, Service):
JAVA:
AppWatcher.INSTANCE.manualInstall(app, WATCH_DURATION_MILLISECONDS);

Kotlin:
AppWatcher.manualInstall(app, WATCH_DURATION_MILLISECONDS);

For more details read the official documentation here.

A: See "Disabling LeakCanary" in the code recipes: https://square.github.io/leakcanary/recipes/#disabling-leakcanary
You'll want to define a boolean xml resource leak_canary_add_launcher_icon and set it to false (=> no launcher icon)
You can turn off instance watching with:
AppWatcher.config = AppWatcher.config.copy(enabled = false)


text:
Q: Bind - how to proxy DNS requests to another server (static-stub/forward type not working as expected) How do I proxy DNS requests from bind9 to acme-dns?
Here is my named/bind9 configuration file
options {
        directory "/var/cache/bind";
        auth-nxdomain no;    # conform to RFC1035
        dnssec-validation auto;
        listen-on-v6 { any; };

        dump-file               "data/cache_dump.db";
        statistics-file         "data/named_stats.txt";
        memstatistics-file      "data/named_mem_stats.txt";
        recursion yes;
        allow-recursion { any;}; # had to change to allow bind9 to query 127.0.0.53
        version "go away";
};

zone "xample.in" {
    type master;
    file "/usr/local/etc/bind/zones/db.xample.in";
};

zone "auth.example.com" {
  type static-stub;
  server-addresses { 127.0.0.3; };
  forward first;
  forwarders { 127.0.0.3; };
};

I setup acme-dns to run on 127.0.0.3:53. it replies to SOA, NS and TXT records.
While querying with dig TXT test.auth.example.com +trace, I see -E(0)D which can be reproduced with dig TXT test.auth.example.com @127.0.0.1 +norecurse +noedns +dnssec
Jun 17 03:14:09 in-servername named[6000]: client @0xffff7c0142c8 127.0.0.1#53223 (test.auth.example.com): query: test.auth.example.com IN TXT -E(0)D (127.0.0.1)
Jun 17 03:14:09 in-servername named[6000]: client @0xffff7c0142c8 127.0.0.1#53223 (test.auth.example.com): query failed (REFUSED) for test.auth.example.com/IN/TXT at query.c:5499

versions:
BIND 9.16.16 (Stable Release)
OS: Linux ARM64(aarch64)

I tried setting dnssec-validation no;, it did not work
Configuration files
https://github.com/joohoi/acme-dns/blob/master/config.cfg
[general]
listen = "127.0.0.1:53"
# domain name to serve the requests off of
domain = "auth.example.com"
# zone name server
nsname = "one.ns.example.com"
# admin email address, where @ is substituted with .
nsadmin = "admin.example.com"
# predefined records served in addition to the TXT
records = [
    # domain pointing to the public IP of your acme-dns server
    "auth.example.com. A 198.51.100.1",
    # specify that auth.example.org will resolve any *.auth.example.org records
    "auth.example.com. NS one.ns.xample.in.",
]

zone file
$TTL    3600
@       IN      SOA     one.ns.xample.in. webmaster.xample.in. (
                              2         ; Serial
                         604800         ; Refresh
                          86400         ; Retry
                        2419200         ; Expire
                         604800 )       ; Negative Cache TTL
;
@       86400   IN      NS      one.ns.xample.in.
@       86400   IN      NS      two.ns.xample.in.
@       IN      A       1.1.1.1
www     IN      A       1.1.1.1
_dmarc  IN      TXT     "v=DMARC1; p=reject;"
_acme-challenge IN  TXT __test_message__

Question: How do I proxy DNS requests from bind9 to acme-dns?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Converting Excel Byte Array data into Datatable C# API The requirement is that the client will send the Excel data in the form of Byte Array (will provide API link for the same to the client)
Now when the API receives the Byte Array, i want to convert into datatable for converting into XML.
Below is the code i have tried
 public string ConvertExcelByteArraytoXML()
        {

            byte[] Excelbytes = null;
            FileStream fs = File.OpenRead("C:\\PRATAP FOLDER\\test.xlsx");
            BinaryReader binaryReader = new BinaryReader(fs);
            Excelbytes = binaryReader.ReadBytes((int)fs.Length);
            string CreateXMLFILE = string.Empty;

       // the above code was to get byte array from excel

            DataSet tempDataSet = new DataSet();
            DataTable dt;
            // Deserializing into datatable
            using (MemoryStream stream = new MemoryStream(Excelbytes))
            {
                BinaryFormatter bformatter = new BinaryFormatter();
                dt = (DataTable)bformatter.Deserialize(stream);

            }
            // Adding DataTable into DataSet
            tempDataSet.Tables.Add(dt);

           using (StringWriter sw = new StringWriter())
            {
                dt.WriteXml(sw);
                CreateXMLFILE = sw.ToString();
            }
          return CreateXMLFILE;

}

Throwing error at
dt = (DataTable)bformatter.Deserialize(stream);

{"The input stream is not a valid binary format. The starting contents
  (in bytes) are: 50-4B-03-04-14-00-06-00-08-00-00-00-21-00-EB-7A-D2
  ..."}

Can someone suggest what am i doing wrong here.

A: Like I mentioned in the comment, you can try the following code to convert the byte array
to datatable.
Code:
class Program
    {
        static void Main(string[] args)
        {
            byte[] b = File.ReadAllBytes("D:\\2.xlsx");      // you get from the client
            File.WriteAllBytes("test.xlsx", b);             //Create an hourly file
            DataTable table = Exceltodatatable("test.xlsx");  // convert it to datatable
            File.Delete("test.xlsx");                         // delete the file
        }

        public static DataTable Exceltodatatable(string path)
        {
            DataTable dt = new DataTable();
            string connectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";" + "Extended Properties='Excel 12.0 Xml;HDR=YES;IMEX=1;MAXSCANROWS=0'";
            using (OleDbConnection conn = new OleDbConnection(connectionString))
            {
                using (OleDbCommand comm = new OleDbCommand())
                {
                    string sheetName = "sheet1";
                    comm.CommandText = "Select * from [" + sheetName + "$]";
                    comm.Connection = conn;
                    using (OleDbDataAdapter da = new OleDbDataAdapter())
                    {
                        da.SelectCommand = comm;
                        da.Fill(dt);
                        return dt;
                    }
                }

            }
        }
    }


text:
Q: enableBodyScroll unsuccessful - targetElement must be provided when calling enableBodyScroll on IOS devices Выдает такую ошибку в проекте на Vue.js. Не могу найти достаточной информации в сети. Не критично, но работать неприятно в дебаге. Возможно кто-то сталкивался. Подскажите что и куда нужно вставить чтобы больше не выскакивала.
Спасибо!


text:
Q: Non-phantom maps from $\mathbb CP^{\infty}$ to a finite complex It is not true that every map from $\mathbb CP^{\infty}$ to a finite complex is null-homotopic. For example it is a result due to Brayton-Gray that there are non-null maps $\mathbb CP^{\infty} \to S^3$, this story is told in P. May's "More Concise Algebraic Topology" (see cor. 2.4.3 on page 40). However, the examples constructed there are phantom maps, i.e. they become trivial when restricted to any finite subcomplex $\mathbb CP^k \subset \mathbb CP^{\infty}$. (A way to think about this is that it is just not possible to find a compatible choice of null-homotopies.) So my question is:
Does there exist a finite CW-complex $X$ and a non-phantom map $\mathbb CP^{\infty} \to X$?
Here are some thoughts:
(1) One can show that any such map has to be trivial on cohomology (with $\mathbb Z$ coefficients, using the cup product structure of $\mathbb CP^{\infty}$) and consequently also on homology (here we have to use that $X$ is finite). Lifting the map to the universal cover $\tilde{X}$ of $X$ and using Hurewicz, one can also see that the map is zero on all homotopy groups ($\mathbb CP^{\infty}$ only has one). However, there are plenty of non-trivial maps inducing zero on all homotopy and homology groups, the easiest example is maybe given by the composition $T^3 \to S^3 \to S^2$ where the first map collapes the complement of a ball and the second one is the Hopf map.
(2) Using the Sullivan conjecture/Miller's theorem one can probably show that the $p$-completion of any such map is null.
(3) Going in the opposite direction, maybe one can start with a non-trivial map $\mathbb CP^{k} \to X$ which induces zero on all homotopy and homology groups and then somehow prove that it extends to $\mathbb CP^{\infty}$. However I do not see how one could show in practice that extending the map is possible...

A: All maps of $\mathbf CP^\infty$ to a finite complex are phantom maps; see
A. Zabrodsky, On phantom maps and a theorem of H. Miller,
Israel J. Math 58 (1987) 129-143. For maps out of classifying spaces of Lie groups, see Friedlander-Mislin, Locally finite approximations of Lie groups, I, Invent. Math. 83 (1986), 425-436.


text:
Q: Why do I get a connection error trying to connect to mongo Doing an excercise, I have to build an application that allows to register users and edit them. I follow the instructions of the book however still i am stuck, because i get an error:

Unhandled rejection MongoError: cannot connect to server
      at Collection.listIndexes (/home/mihaly/meanbook/node_modules/mongoose/node_modules/mongodb/lib/collection.js:1732:11)
      at indexInformation (/home/mihaly/meanbook/node_modules/mongoose/node_modules/mongodb/lib/db.js:1607:25)
      at Db.indexInformation (/home/mihaly/meanbook/node_modules/mongoose/node_modules/mongodb/lib/db.js:1571:44)
      at ensureIndex (/home/mihaly/meanbook/node_modules/mongoose/node_modules/mongodb/lib/db.js:1066:8)
      at Db.ensureIndex (/home/mihaly/meanbook/node_modules/mongoose/node_modules/mongodb/lib/db.js:1042:44)
      at ensureIndex (/home/mihaly/meanbook/node_modules/mongoose/node_modules/mongodb/lib/collection.js:1802:13)
      at Collection.ensureIndex (/home/mihaly/meanbook/node_modules/mongoose/node_modules/mongodb/lib/collection.js:1790:44)
      at tryCatcher (/home/mihaly/meanbook/node_modules/connect-mongo/node_modules/bluebird/js/release/util.js:11:23)
      at ret [as ensureIndexAsync] (eval at  (/home/mihaly/meanbook/node_modules/connect-mongo/node_modules/bluebird/js/release/promisify.js:184:12),
  :13:39)
      at MongoStore.setAutoRemoveAsync (/home/mihaly/meanbook/node_modules/connect-mongo/src/index.js:123:40)
      at MongoStore.handleNewConnectionAsync (/home/mihaly/meanbook/node_modules/connect-mongo/src/index.js:116:18)
      at MongoStore (/home/mihaly/meanbook/node_modules/connect-mongo/src/index.js:95:26)
      at Object. (/home/mihaly/meanbook/CH26/auth_server.js:20:10)
      at Module._compile (module.js:410:26)
      at Object.Module._extensions..js (module.js:417:10)
      at Module.load (module.js:344:32)
      at Function.Module._load (module.js:301:12)
      at Function.Module.runMain (module.js:442:10)
      at startup (node.js:136:18)
      at node.js:966:3

here is how my file looks like...
var express = require('express');
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var expressSession = require('express-session');
var mongoStore = require('connect-mongo')({session: expressSession});
var mongoose = require('mongoose');
require('./models/user_model.js');
var conn = mongoose.connect('mongodb://localhost/myapp');
var app = express();
app.engine('.html', require('ejs').__express);
app.set('views', __dirname + '/views');
app.set('view engine', 'html');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(cookieParser());
app.use(expressSession({
  secret: 'SECRET',
  cookie: {maxAge: 60*60*1000},
  store: new mongoStore({
      db: mongoose.connection.db,
      collection: 'sessions'
    })
  }));
require('./routes')(app);
app.listen(8080);

I think i've installed all the necessary modules, and mongo is running. Does anyone know where i made the mistake?


text:
Q: $.ajax to $getJSON I want to convert following Jquery code to use $.ajax intead of $.getJSON, what will be $.ajax code for this?
$(function () {
    $('#checkExists').click(function () {
     $.getJSON($(this).attr('href'), function (result) {
            alert(result);
            if (result) {
                alert('the record exists');
            }
        });
        return false;
    });
});

Please suggest

A: $.ajax({
  url: $(this).attr('href'),
  success: function (result) { ... },
  dataType: 'json'
});

Also, I'd suggest using event.preventDefault() instead of return false;


text:
Q: VBA Excel - How to transfer Values of Named Ranges from Workbook B into same/similar Named Ranges in Workbook A? Thank you in advance for any help. My knowledge is Beginner Level. I can read code but struggle with writing.
Also, I assume there is always a better (more efficient) way to write code.
The solution is a combination of several objectives:
1. Command button with assigned macro (finished)
2. Error handling (have a little code for this)
3. Identify second Workbook to transfer from (have code for this)
4. Copy & Paste values of 90+ Named Ranges into Workbook A (caveman code using macro recorder)
5. Copy & Paste objects (pictures) of 5 Name Ranges into Workbook A (haven't gotten this far)
6. User Feedback (Transfer Successful or Transfer Failed with error message)
Code: (skipping objective 1)
Sub Button_Transfer_FromOlderVersion()

' Start of Error Handling
    On Error GoTo Errorcatch

' Declare string variable and use current open workbook filename as value
    Dim WorkbookNameNew As String
    WorkbookNameNew = ThisWorkbook.Name

' Declare string variable for 2nd workbook not yet identified
    Dim WorkbookNameOld As String

' Find out the name of the 2nd workbook
' Declare string variable for finding and separating the filename from the path
    Dim sFileName As String

' Show the open dialog and pass the selected file name to the string variable "sFileName"
    sFileName = Application.GetOpenFilename

' If the user cancels finding the workbook file then exit subroutine
    If sFileName = "False" Then Exit Sub

' Troubleshooting: Show me the filename with path of Workbook B
    MsgBox sFileName

' Troubleshooting: Show me the filename of Workbook A
    MsgBox WorkbookNameNew

' Open Workbook B which the user just selected
    Workbooks.Open Filename:=sFileName

' Separate the filename from the path for Workbook B
    WorkbookNameOld = Dir(sFileName)

' Troubleshooting: Show me the filename of Workbook B
    MsgBox WorkbookNameOld

' Make sure Workbook B is the active workbook
    Windows(WorkbookNameOld).Activate

' Make sure the correct worksheet is active
    Worksheets("WorksheetName").Activate

' Select and copy the value of the first Named Range
    Range("NamedRange01").Select
    Selection.Copy

' Make Workbook A the active workbook
    Windows(WorkbookNameNew).Activate

' Select the corresponding Named Range in Workbook A
    Range("NamedRange01").Select
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False

' User Feedback of successful transfer and name of Workbook B
    MsgBox ("TRANSFER COMPLETED FROM:" & " " & WorkbookNameOld)

Exit Sub

' Finish Error Handling
Errorcatch:
MsgBox Err.Description

End Sub

My apologies if the spacing, indenting, and commenting are not optimized for reading. I'm still learning best practices.
Please note: some name ranges are spelled different and I need to map them so that the copy/paste is accurate.
Also, instead of using copy/paste wouldn't it be better to list all the Named Ranges in an Array with associated variables?  And wouldn't it be better to copy all the values and objects into the Array and then switch to Workbook A and paste all the content?
Thanks again for your help.

A: You don't need to bother with activating the workbook or sheets before copying or pasting. That just slows things down. In addition you can turn of screen updating and calcluation to speed things up even more.
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual

Windows(WorkbookNameOld).Worksheets("WorksheetName").Range("NamedRange01").Copy
Windows(WorkbookNameNew).ActiveSheet.Range("NamedRange01").PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False

Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic


text:
Q: jQuery selector for element, ID, and style It looks jquery selector for element and style is done this way:
$("div[style='width: 420px; text-align: left;']");

And a selector for wildcard ID (in the front) is like this:
$("[id^=targ_mt1_]");

How do you combine the two?

A: The square brackets of the wildcard selector come before the square brackets of the style selector:
$("textarea[id^=targ_mt1_][style='width: 420px; text-align: left;']")

This can be seen in the following:

const text = 'text';
$("textarea[id^=targ_mt1_][style='width: 420px; text-align: left;']").val(text);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea id="targ_mt1_1" style='width: 420px; text-align: left;'></textarea>


text:
Q: Case keyword and setting variable in makefile What do the following three lines do in a Makefile?
1. SRCS:c=o
2. case "$*" in
3. support)

 OBJS=$(SRCS:c=o)
 %.o: %.c
         case "$*" in \
             support) $(CC) $(CCOPT) -c $(OPTS) $*.c ;; \
             *) $(PCC) $(PCCOPT) -c $(OPTS) $*.c ;; \
             esac

Please let me know if you need more information.

A: OBJS=$(SRCS:c=o) is a Substitution Reference:

When we say "at the end of a word", we mean that a must appear either followed by whitespace or at the end of the value in order to be replaced; other occurrences of a in the value are unaltered. For example:
foo := a.o b.o c.o
bar := $(foo:.o=.c)

sets 'bar' to 'a.c b.c c.c'. See Setting Variables.
...

This bit:
     case "$*" in \
         support) $(CC) $(CCOPT) -c $(OPTS) $*.c ;; \
         *) $(PCC) $(PCCOPT) -c $(OPTS) $*.c ;; \
         esac

is the recipe of the %.o: %.c target and is a shell script.
See case in the Bash Reference Manual and in the POSIX spec.
The support) and *) bits are part of the case statement (as is esac).


text:
Q: Are values set inside a loop lost once the loop is over? I'm doing an online course by the name of "Object-Oriented programming with Java"
And I can't figure out exercise 36..

Create a program that asks the user to input numbers (integers). The program prints "Type numbers" until the user types the number -1. When the user types the number -1, the program prints "Thank you and see you later!" and the sum of the numbers entered by the user (without the number -1).

import java.util.Scanner;

public class LoopsEndingRemembering {
    public static void main(String[] args) {
        Scanner reader = new Scanner(System.in);
        int n = 0;
        int sum = 0;
        while (n != -1) {
            System.out.println("Type numbers");
            n = Integer.parseInt(reader.nextLine());
            sum = sum + n; // <-- The value set here is tossed once the loop of over?..
        }
        System.out.println("Thank you and see you later!");
        System.out.println("The sum is " + sum); // <-- Does not acknowledge the free state of 'loop' and any variables that come of it
    }
}

So when I click the 'Run tests locally' (it's a plugin
button) in Netbeans I'm getting:

With input 1 -1  you should print "the sum is 1" expected:<1> but was:<0>

The '0', to my understanding, is indicating that the last println only recognizes the initialization of 'sum'..why is that?..

A: Change you while loop to check the users input as the last thing in the loop. Example:
public static void loopTest()
{
    Scanner reader = new Scanner(System.in);
    int n = 0;
    int sum = 0;
    System.out.println("Type a number then press enter... type '-1' to sum the numbers and exit");
    n = Integer.parseInt(reader.nextLine());
    while (n != -1)
    {
       sum = sum + n;
       n = Integer.parseInt(reader.nextLine());
    }
    System.out.println("Thank you and see you later!");
    System.out.println("The sum is " + sum ); // <-- Does
}


text:
Q: LinkedIn API button automatically logs people in I am using the LinkedIn API for login. I have that pretty little button. It works great.
However, when people "logout" of my app, something goes wrong. I do this:

*

*Log the user out: IN.User.logout();

*Redirect to my landing page for not logged in users: window.location = "/index.php";
Everything is fine, but when they get to my landing page for logged out users, where I have the log-in with LinkedIn button, they immediately get logged back in again.
Why would they be automatically logged in again? Didn't I just log them out? Shouldn't they need to click the log in with LinkedIn button again?
Here is the code for the button:
<script src="http://platform.linkedin.com/in.js" type="text/javascript">
    api_key: lydbpp0zdpad
    onLoad: LinkedInSignIn.redirect
    authorize: false
</script>

A: When you change the window.location, the browser kills all requests currently in progress. This may be preventing the logout request from going through. Can you try delaying for 5s before redirecting them? (There are ways to get around this problem without delaying, if it is indeed the issue.)


text:
Q: SP 2010 Adding a picture library with some pictures through a feature I would like to add the following feature to my Web Template.
 - Add a picture library with some default pictures in it
First step would be creating a custom list from the type picture library.
But how would you be able to add some pictures (items) to this library?

A: Create a module, call it e.g. Pictures and add pictures to it. The elements.xml looks like this:
<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <Module Name="Pictures" Url="MyPictureLibrary">
    <File Path="Pictures\pic1.png" Url="pic1.png" Type="GhostableInLibrary"/>
    <File Path="Pictures\pic2.png" Url="pic2.png" Type="GhostableInLibrary" />
  </Module>
</Elements>

Add the module to a web scoped feature. (Assuming you call your library MyPictureLibrary and the feature that deploys this module is activated in the same web as the library)
Edit: Or do it through code like Rob suggested.

A: Once you have you're library created, you could use:
SPList.RootFolder.Add(...)

To add the files to the root folder of the library.  The Add method has numerous overrides depending on how you want to add the file (byte array versus stream, with or without metadata, etc.)
I can provide a more complete code snippet if needed...let me know.


text:
Q: Ionic native device plugin @ionic-native/device returns all nulls I need to do a device detection in my Ionic project so I've installed @ionic-native/device plugin per instructions here: https://ionicframework.com/docs/native/device/
However when I wire it in inside of a component, then run ionic serve to preview changes, console.log returns Device object with all values set to null, same happens when I try to use individual property e.g. this.device.model:

Here is how I use it inside of a component:
import {Device} from "@ionic-native/device";
// ...

@Component({
    // ...
})
export class MyComponent {

    constructor(private device: Device) {
    }

    ngOnInit() {
        console.log(this.device);
    }

}

And I've added it to AppModule as well:
import {Device} from "@ionic-native/device";
// ...

@NgModule({
    // ...
    providers: [
        Device
    ]
})
export class AppModule() {
}

Cordova device plugin was auto injected into config.xml:
<?xml version='1.0' encoding='utf-8'?>
<widget <!-- ... --> >
    <!-- ... -->
    <plugin name="cordova-plugin-device" spec="2.0.0" />
</widget>

Here is my Ionic stack (at least packages that should be relevant to the issue):
"@angular/*": "^5.2.4",      // all packages
"@ionic-native/*": "4.5.2",  // all packages

"@ionic-native/device": "4.5.2"
"ionic-angular": "3.9.2",
"cordova-plugin-device": "2.0.0",
"typescript": "2.6.2"

Thanks!
UPDATE:
I was able to get device details in the browser by running:
cordova run browser

This assumes you have added browser as a platform, if not run:
ionic cordova platform add browser

(From the link in the answer posted by @AndrewLively: https://stackoverflow.com/a/49034015/448816)

A: If you are running in the browser using ionic serve then most of the ionic-native plugins won't work since it is not treated by ionic as a valid browser platform.
This is not well documented, but is discussed in an issue in the ionic-native repo.

A: Should see the packages installed and see they are in the same version in "package.json"

Core and Native packages must be in the same version or the native package should not be larger.

The folder "platforms" must be delete

Use these commands
    ionic build

    ionic cordova platform add browser

    cordova run browser

code for .ts
console.log('Device Model is: ' + this.device.model);

And works !


text:
Q: I need only 4 mappers and 2 reducers in AWS but that does not happen? How do u make sure
only 4 map and 2 reduce are there
because when i use 1 large instance
it sometimes give me 6 map 2 reduce
random no.
i tried putting mapred.map.tasks=4
in the extra args while settingup the job
that also didn`t work

A: Try to set number of mapper and reducers with bootstrap action.
     elastic-mapreduce --create \
     --name "cluster_name" \
     --bootstrap-action s3://elasticmapreduce/bootstrap-actions/configure-hadoop --args -m,mapred.map.tasks=4,-m,mapred.reduce.tasks=2,-m,mapred.tasktracker.map.tasks.maximum=4,-m,mapred.tasktracker.reduce.tasks.maximum=2


text:
Q: Help with first networking program Here's the code.
public class testClient {
public static void main(String[] args) {
    testClient abc = new testClient();
    abc.go();
}
public void go() {
    try {
        Socket s = new Socket("127.0.0.1",  5000);
        InputStreamReader  sr = new InputStreamReader(s.getInputStream());
        BufferedReader reader = new BufferedReader(sr);
        String x = reader.readLine();
        System.out.println(x);
        reader.close();
    } catch(IOException ex) {
        ex.printStackTrace();
    }
  }
}

public class testServer {
public static void main(String[] args) {
    testServer server = new testServer();
    server.go();
}
public void go() {
    try {
        ServerSocket s = new ServerSocket(5000);
        while(true) {
            Socket sock = s.accept();

            PrintWriter writer = new PrintWriter(sock.getOutputStream());
            String toReturn = "No cake for you.";
            writer.println(toReturn);
        }
    } catch(IOException ex) {
        ex.printStackTrace();
    }
  }
}

java.io.* and java.net.* are imported in both classes.
Now, when I try to run these(using different terminals), nothing happens. What am I doing wrong?
Screen: http://i29.tinypic.com/250qlmt.jpg

A: Your output is apparently buffered. After writing your output, try flushing:
        writer.println(toReturn);
        writer.flush();

Also, you may consider calling sock.close() in your server if you're done with the socket, otherwise the client will be left wondering what to do next.

A: When using PrintWriter you need to call flush method. Changed your code to following and it works :).
public class testServer {
public static void main(String[] args) {
    testServer server = new testServer();
    server.go();
}
public void go() {
    try {
        ServerSocket s = new ServerSocket(5000);
        while(true) {
            Socket sock = s.accept();

            PrintWriter writer = new PrintWriter(sock.getOutputStream());
            String toReturn = "No cake for you.";
            writer.println(toReturn);
            writer.flush();
        }
    } catch(IOException ex) {
        ex.printStackTrace();
    }
  }
}

A: Check out this simple working example.
 import java.net.*;
    import java.io.*;
    public class Server {
        Server() throws IOException {
            ServerSocket server = new ServerSocket( 4711 );
            while ( true ) {
              Socket client = server.accept();
              InputStream in = client.getInputStream();
              OutputStream out = client.getOutputStream();
              int multiplikator1 = in.read();
              int multiplikator2 = in.read();
              int resultat = multiplikator1 * multiplikator2;
              out.write(resultat);
       }
       public static void main (String[] args) {
       try {
        Server server = new Server();
       } catch (IOException e) {
          e.printStackTrace();
       }
    }
}

    import java.net.*;
    import java.io.*;
    public class Client {
        Client() throws IOException {
            Socket server = new Socket ( "localhost", 4711 );
            InputStream in = server.getInputStream();
            OutputStream out = server.getOutputStream();
            out.write( 4 );
            out.write( 9 );
            int result = in.read();
            System.out.println( result );
            server.close();
        }
        public static void main (String[] args) {
           try {
           Client client = new Client();
         } catch (IOException e) {
           e.printStackTrace();
        }
      }
    }

A: Close the writer.


text:
Q: How to check which Spring Boot version goes with spring-cloud-gcp-starter-data-spanner 1.1.0.RC1? I intended to use Spring Data Cloud Spanner starter (version 1.1.0.RC1) with Spring Boot application but cannot find the official document of which Spring Boot version it goes with. Running my app and it works well with Spring Boot 2.x.x but not with Spring Boot version 1.x.x (ClassNotFoundException). Could anyone help:

*

*Any document to show which SpringBoot version goes with Spring Data Cloud Spanner starter (version 1.1.0.RC1)?

*Any way to make Data Cloud Spanner starter (ideally 1.1.0.RC1) work with SpringBoot version 1.5.17?

Thank you.

A: TL;DR Spring Boot 2.1 but you shouldn't have to care.
Spring Cloud Data Spanner is part of the Spring Cloud GCP project that recently joined the official Spring Cloud release train.
Rather than figuring out which version of a particular library is needed , I'd strongly recommend you to use proper dependency management in your build and let default apply. That way you can select a Spring Cloud generation (i.e. release train) and the dependencies that you need will be managed for you automatically (that is, no need to provide a version for them).
The latest 1.0 RC, RC2 at the time of writing, is part of the Greenwich release train with a RC2 release this week.
To get started with proper dependency management, go to https://start.spring.io and select "GCP Support" to get a build with the proper BOM import. Once you've done that you can add the starter without a version and things will be managed for you.
The relationships between Spring Boot version and Spring Cloud release train is documented here and on start.spring.io as well.


text:
Q: How I can add more columns to show in my relationships in adonis using node.js? I have this model:
Book:
class BookSchema extends Schema {
  up () {
    this.create('books', (table) => {
      table.increments()
      table.string('description')
      table.timestamps()
    })
  }

BookUnit:
class BookUnitSchema extends Schema {
  up () {
    this.create('book_unit', (table) => {
      table.increments()
      table.integer('book_id').references('id').inTable('books').notNullable()
      table.integer('unit').notNullable()
      table.string('description')
      table.integer('user_id').references('id').inTable('users')
      table.timestamps()
      table.unique(['unit', 'sequence', 'book_id'])
    })
  }

BookUnitQuestion
class BookUnitQuestionSchema extends Schema {
      up () {
        this.create('book_unit_question', (table) => {
          table.increments()
          table.integer('book_unit_id').references('id').inTable('book_unit')
          table.string('question_form')
          table.string('option_form')
          table.string('type_answer')
          table.string('description')
          table.string('correct_answer_description')
          table.integer('correct_answer_description_id')
          table.text('image_sound')
          table.boolean('status').defaultTo(false)
          table.integer('user_id').references('id').inTable('users')
          table.timestamps()
        })
      }

I need to make a query that me returns all the questions of one determined book. I try this way:
const Book = use('App/Models/Book')

const book = await Book.find(2) //Get book from id
await book.load('book_unit_questions') // Load book_unit_questions
const questions = book.getRelated('book_unit_questions') // Return questions
return questions

So, I have this json:
[ {"id":1,"book_unit_id":2,"description":null,"created_at":null,"updated_at":null},
     {"id":2,"book_unit_id":5,"description":454,"created_at":null,"updated_at":null}
]

I need to put more book_unit informations inside this json, like book_unit.description, book_unit.sequence"...
Porém, eu preciso de mais informações sobre o book_unit_id, como por exemplo, o description dele.
In my query I return book_unit_id but I need to add this others columns of bookunit, how I can do this?
My book models:
user () {
    return this.belongsTo('App/Models/User')
        .select('id', 'username')
}

book_units(){
    return this.hasMany('App/Models/BookUnit')
}

book_unit_questions() {
    return this.manyThrough('App/Models/BookUnit', 'book_unit_questions')
}

BookUnit Models:
book_unit_questions() {
    return this.hasMany('App/Models/BookUnitQuestion')
}

book () {
    return this.belongsTo('App/Models/Book')
}

user () {
    return this.belongsTo('App/Models/User')
        .select('id', 'username')
}

bookUnit Question model:
static get table () { return 'book_unit_question' }

user () {
    return this.belongsTo('App/Models/User')
        .select('id', 'username')
}

book_units(){
    return this.belongsTo('App/Models/BookUnitQuestion')
}

books () {
    return this.manyThrough('App/Models/Book', 'book_unit_questions', 'id', 'book_unit_id')
}


text:
Q: KineticJS Container.getIntersections very slow I need to detect collisions in my HTML5 canvas (I'm using the KineticJS library), and thus far have used my own methods to detect if a certain point is within a certain shape.
I recently noticed that there's a method from the Container class, getIntersections(point) which should do exactly what I want. However it seems to be EXTREMELY slow, so when moving an object on the canvas and using the method for every new position, it becomes unusable.
Has anyone used this method for collision detection? If not, are there any tips on collision detection in a HTML5 canvas? I'm having trouble detecting if a point is inside a rectangle that is rotated by a certain amount of degrees.

A: I have noticed the same thing, getIntersections takes a long time. It is also called for mouse events etc. which makes it even worse.
I don't know how to make it faster, but one thing that affects the speed considerably is the number of Shapes you have on your stage. So one way to speed things up would be to remove unnecessary Shapes when they are not needed and bring them back dynamically when needed.

A: I have used getIntersection() in a mobile game (a simulation for air traffic control) and it worked quite well given that it was called multiple number of times to detect a collision among all the existing planes in the game frame. In case you have to detect just one specific point, a possible solution could be to add a very small dummy rectangle for that place and get list of all objects intersecting with it and iterate over this list. Naming the objects of interest can speed up your condition verification.

A: https://github.com/ericdrowell/KineticJS/issues/150
This is exactly what you need.

okay, to be clear, there are two ways to get an intersected shape
  based on mouse position:
1) getIntersection() - preferred 2) getIntersections() - very slow,
  and should be used for special situations
the getIntersection() method is blazingly fast, and returns an object
  containing information about the intersection point, such as a
  reference to a KineticJS shape if one is there, or pixel color
  information.
the getIntersections() method does the same thing, except that it
  iterates through and redraws every single node in the stage in order
  to return a collection of intersections that may have been layered on
  top of eachother.
99 times out of a 100, you're probably just interested in the visible
  intersected node which is at the top of nodes beneath it.
I've actually considered removing the getIntersections() method
  entirely, but haven't because there are some special situations when
  you actually do need a collection of intersections. At this time, I
  haven't been able to find a way to speed up getIntersections, although
  I'll keep looking into it.


text:
Q: PageUp, PageDown, Home and End on laptop don't work in X11 I have Dell Inspirion 3168 with Xubuntu 16.10. I noted a problem.
PageUp, PageDown, Home and End on laptop's keyboard (fn+arrow keys) work in console, in evtest, showkey (emit right keycode, as example PgDn is 109), but don't work in X11 (xev and X applications). But on external USB keyboard these keys work properly.


text:
Q: R dplyr - Rearrange columns by pattern of names I've got some long format data that 1) needs to be reshaped to wide and then 2) needs the columns resorted according pattern of their names. The example data is below:
#Orignial data
set.seed(100)
long_df <- tibble(id = rep(1:5, each = 3),
                  group = rep(c('g1','g2','g3'), times = 5),
                  mean = runif(15, min = 1, max = 10),
                  sd = runif(15, min = .025, max = 1))
long_df

# A tibble: 15 x 4
      id group  mean    sd
   <int> <chr> <dbl> <dbl>
 1     1 g1     3.77 0.677
 2     1 g2     3.32 0.224
 3     1 g3     5.97 0.374
 4     2 g1     1.51 0.375
 5     2 g2     5.22 0.698
 6     2 g3     5.35 0.547
 7     3 g1     8.31 0.718
 8     3 g2     4.33 0.550
 9     3 g3     5.92 0.755
10     4 g1     2.53 0.435
11     4 g2     6.62 0.192
12     4 g3     8.94 0.776
13     5 g1     3.52 0.885
14     5 g2     4.59 0.560
15     5 g3     7.86 0.296

#Reshaped to wide
wide_df <- long_df %>%
  pivot_wider(id_cols = id, names_from = 'group', values_from = c('mean','sd'))
wide_df

# A tibble: 5 x 7
     id mean_g1 mean_g2 mean_g3 sd_g1 sd_g2 sd_g3
  <int>   <dbl>   <dbl>   <dbl> <dbl> <dbl> <dbl>
1     1    3.77    3.32    5.97 0.677 0.224 0.374
2     2    1.51    5.22    5.35 0.375 0.698 0.547
3     3    8.31    4.33    5.92 0.718 0.550 0.755
4     4    2.53    6.62    8.94 0.435 0.192 0.776
5     5    3.52    4.59    7.86 0.885 0.560 0.296

#Wide with proper column order
final_df <- wide_df %>%
  select(id, mean_g1, sd_g1, mean_g2, sd_g2, mean_g3, sd_g3)
final_df

# A tibble: 5 x 7
     id mean_g1 sd_g1 mean_g2 sd_g2 mean_g3 sd_g3
  <int>   <dbl> <dbl>   <dbl> <dbl>   <dbl> <dbl>
1     1    3.77 0.677    3.32 0.224    5.97 0.374
2     2    1.51 0.375    5.22 0.698    5.35 0.547
3     3    8.31 0.718    4.33 0.550    5.92 0.755
4     4    2.53 0.435    6.62 0.192    8.94 0.776
5     5    3.52 0.885    4.59 0.560    7.86 0.296

Does someone know a way to either a) pivot the long data with the output being in the proper order or b) use a regex or sort variable to reorder the columns into the desired order? A tidyverse style solution would be preferred, but other approaches are welcome too.

A: You can run ends_with successively on a character vector of the numeric suffixes:
long_df %>%
  pivot_wider(names_from=group, values_from=c(mean, sd)) %>%
  select(id, ends_with(as.character(1:3)))

     id mean_g1 sd_g1 mean_g2 sd_g2 mean_g3 sd_g3
  <int>   <dbl> <dbl>   <dbl> <dbl>   <dbl> <dbl>
1     1    3.77 0.677    3.32 0.224    5.97 0.374
2     2    1.51 0.375    5.22 0.698    5.35 0.547
3     3    8.31 0.718    4.33 0.550    5.92 0.755
4     4    2.53 0.435    6.62 0.192    8.94 0.776
5     5    3.52 0.885    4.59 0.560    7.86 0.296

This might need the development version of dplyr to work (devtools::install_github("tidyverse/dplyr")). I'm running the development version and haven't checked this code with the current CRAN release.
You can also pivot_longer to the "longest" version of the data frame and then pivot_wider to get the desired column order without resorting:
long_df %>%
  pivot_longer(cols=c(mean, sd)) %>%
  pivot_wider(names_from=c(name, group), values_from=value)

     id mean_g1 sd_g1 mean_g2 sd_g2 mean_g3 sd_g3
  <int>   <dbl> <dbl>   <dbl> <dbl>   <dbl> <dbl>
1     1    3.77 0.677    3.32 0.224    5.97 0.374
2     2    1.51 0.375    5.22 0.698    5.35 0.547
3     3    8.31 0.718    4.33 0.550    5.92 0.755
4     4    2.53 0.435    6.62 0.192    8.94 0.776
5     5    3.52 0.885    4.59 0.560    7.86 0.296


text:
Q: Let's talk about phrasing of the "Protected Questions" message Currently, the Protected message text reads:

Given that we now strive to become more welcoming to new users, shouldn't we change the phrasing to something that doesn't seem as hostile as the existing text?
I'd suggest something that doesn't conflate thanks, me too and spam with the new users. E.g.

This question is protected to prevent "thanks!", "me too!", or spam answers. To answer it, you must have earned at least 10 reputation on this site (the association bonus does not count).

A: Today SE's "new users" are called "new contributors", and some identify themselves with that very same title, so perhaps they don't feel alienated. Is there any proof that this is a contentious point?
A friendlier more easy-going message might be

"Oops! Sorry, due to "thanks!", "me too!", and spam answers, we have to protect this question. Only users with at least 10 reputation on this site (the association bonus does not count) can post an answer."

Substitute "new users" with plain vanilla  "users"?

A: Note that the message you see is only shown to users eligible to answer protected questions. Users who aren't eligible see a different message:

Thank you for your interest in this question. Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?

I don't believe that this message is that unwelcoming. If you're specifically referring to the message shown to eligible users, please comment.


text:
Q: react.js change state of the topmost parent element from a deeply nested child I am using react-async along with node.js. React-async is used to use react.js in the asynchronous way. To make ajax calls, I am using super-agent. The PostList Component is the topmost parent component. Through its setTopmostParentState method, the component's state can be changed. I want to call this method from Comp4. The parameter to this method will come from an ajax call using the 'super-agent' node middleware.
How can I change the state from Comp4 ? If it was a parent component and then a child component issue, then the state-changing method could be easily passed as a prop to the  child component. But
a few nestings make it difficult to pass the parameter from the deeply nested child to the topmost parent.
Code Snippet:
    var Comp4 = React.createClass({

      clickHandler: function() {

        request.get('/api/prods_find/' + cat_id + '/' + subcat_id,

          function(resp) {

            var prods_menu = resp.body;

* * * //CALL setTopmostParentState of the PostList component with the value prods_menu***

          });

      },
      render: function() {
        '
Target element
'

      }

    });

    var Comp3 = React.createClass({

      render: function() {

        < Comp4 > < /Comp4>

      }

    });

    var Comp2 = React.createClass({

      render: function() {

        < Comp3 > < /Comp3>

      }

    });

    var Comp1 = React.createClass({

      render: function() {

        < Comp2 > < /Comp2>

      }

    });

    var PostList = React.createClass({

      mixins: [ReactAsync.Mixin],

      getInitialStateAsync: function(cb) {

        request.get('http://localhost:8000/api/posts', function(response) {

          cb(null, {
            prods_menu: response.body
          });

        });

      },
      setTopmostParentState: function(prods_menu) {

        this.setState({

          prods_menu: prods_menu
        });
      },
      render: function() {

        var prods = this.state.prods_menu.prods;

        var menu = this.state.prods_menu.menu;

        return (

          < Comp1 > < /Comp1>

        );
      }

    });

A: In your specific case, I would suggest passing down a function to be called by your deepest child Component.
var Comp4 = React.createClass({

      clickHandler: function() {

        request.get('/api/prods_find/' + cat_id + '/' + subcat_id,

          function(resp) {

            var prods_menu = resp.body;
            this.props.updateParentState(prods_menu);

          });

      },
      render: function() {
        '
Target element
'

      }

    });

    var Comp3 = React.createClass({

      render: function() {

        < Comp4 {...this.props} > < /Comp4>

      }

    });

    var Comp2 = React.createClass({

      render: function() {

        < Comp3 {...this.props} > < /Comp3>

      }

    });

    var Comp1 = React.createClass({

      render: function() {

        < Comp2 {...this.props} > < /Comp2>

      }

    });

    var PostList = React.createClass({

      mixins: [ReactAsync.Mixin],

      getInitialStateAsync: function(cb) {

        request.get('http://localhost:8000/api/posts', function(response) {

          cb(null, {
            prods_menu: response.body
          });

        });

      },
      setTopmostParentState: function(prods_menu) {

        this.setState({

          prods_menu: prods_menu
        });
      },
      render: function() {

        var prods = this.state.prods_menu.prods;

        var menu = this.state.prods_menu.menu;

        return (

          < Comp1 updateParentState={this.setTopmostParentState} > < /Comp1>

        );
      }

    });

But as you can see, this is quite cumbersome. That's why Flux was created. Using Flux, you could Dispatch a message to a Store containing the new data, and the Store would notify your Component, re-rendering it.
You can learn more about Flux here https://facebook.github.io/flux/

A: Not saying it is perfect, but in situation like this I am using PubSub library for component communication. For example https://www.npmjs.com/package/pubsub-js.
In your topmost component you can do this:
var EVENT_NOTIFY_TOPMOST = "EVENT_NOTIFY_TOPMOST";
componentDidMount: function() {
    eventToUnsubscribe = PubSub.subscribe(EVENT_NOTIFY_TOPMOST, function( msg, data ){
        console.log( data ); //logs "world"
    });
}

componentDidUnmount: function() {
    //don't forget this
    PubSub.unsubscribe(eventToUnsubscribe )
}

And in your deepest child you can do this:
PubSub.publish(EVENT_NOTIFY_TOPMOST , "world");


text:
Q: Chat *Server* on Embedded platform I am currently building a chat server (meebo style).
The architecture is something like this.

*

*Bitlbee over libpurple is on host B. Its a trivial server on data center.

*User communicates with bitlbee via web server (just like meebo) on Host A. The backend of this web server maintains chat session. It just translates the user commands to proper bitlbee comamnd and sends back to host A.

The most important part here is that host A will be deployed in embedded Linux.
I have 2 questions.

*

*To keep the chat session persistent I am thinking of using node.js. As its much more easier to create a real time application with persistent connection. But I doubt if its supported in such platform.

*If I use C instead of node.js (I am not using any web server) I can talk to the irc server at host A by libirc. But how do I implement all the web server features in C (like session, url/cookie/post data parsing etc) ?

Also if you think my approach is wrong or there is a better approach please tell me how can I improve this architecture?
Note: This is NOT a high volume chat server.

A: If building V8/Node.js is prohibitive on the embedded platform, the next best thing would be to take the event loop and platform layer (libuv) and HTTP parser (http-parser) of Node, both written in C and use those as a starting point. These are the same libraries used to build Node.js so they are battle tested and will give you the performance characteristics you seek.
Ryan Dahl, author of Node.js, demonstrates exactly how to use libuv and http-parser to build an asynchronous web server in C.

A: Put a ZNC server between Bitlbee and the web-based IRC client.  Bitlbee will think that the user has never logged out and ZNC can maintain a backlog of messages until the user connects again with the web client.

A: I would try to go with node.js if that is your choice, also what embedded system is it? As knowing that would help more.  Also, another plus for node.js is that it does have session handling built it, but if you wanted to do it in C try and see if you can get a sqlite wrapper running on the embedded device to store the session information.
But, if possible stick to something with less work on embedded devices, feels bad to reinvent a lot of stuff or have to fiddle with compile issues for your device.


text:
Q: Visual basic first element of array I'm just starting with visual basic.
The first element in an array
i.e. dim y(9) as Integer
Will that have elements 0-8 or 1-9 in?
i.e. if I did
y(1) = 84

does that make the first or second element in the array equal to 84?
I've looked at a few online sources and I'm a bit confuzzled.
Thanks

A: The first position for arrays in VB.NET is zero; same rules apply to any in-built collection/function requiring indexing and to other .NET languages, like C#. On the other hand, "old" VB (VB6 and older or VBA) has zero as first index for arrays and one for in-built functions (this is somehow confusing for people coming from VB to VB.NET). What is common to all the VB versions (.NET and older ones) and different to other languages like C#, is that the number used when instantiating the array (9 in y(9)) does not indicate its size but its last index (the size of y(9) is 10).
In summary, your array includes 10 positions: from 0 to 9.

A: The elements in the array start from 0 in VB.NET
A sample example from MSDN:

You may also find this interesting to read:- Why numbering should start at zero


text:
Q: Adjust first page offset in PDFView I'm trying to build a small pdf viewer with PDFKit.
To achieve a parallax effect, I constrained the PDFView to the superview instead of the safe-area. Unfortunately the PDFView has the wrong offset inside it's ScrollView.
My idea: There should be a way to change the LayoutGuide or Safe-Area to make this properly.
App screenshot with a misplaced pdf


text:
Q: Select method of fullcalendar works more than once I'm trying to make a calendar instance using full calander. In the select method, I've already made it display a modal when the alert () function is running. But the whole problem began here.

select: function(arg) {
  $("#modal-success").modal('show');
  $('#eventSubmit').on('click', function(e) {
    console.log(arg);
    calendar.addEvent({
      title: $('#eventTitle').val(),
      start: arg.startStr + "T" + $('#eventTime').val(),
      color: "green"

    });
    calendar.unselect();
    $("#modal-success").modal('hide');
  });
},

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/4.2.0/bootstrap/main.css" />

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                            ×</button>

Etkinlik başlığını ve saatini giriniz

            Etkinlik Adı
            <input type="text" id="eventTitle" class="form-control" required>

            Etkinlik Saati

              <input autocomplete="off" type="text" id="eventTime" name="eventTime" class="form-control timepicker" required>

        <button type="button" class="btn btn-outline pull-left" data-dismiss="modal">Kapat</button>
        <input type="button" id="eventSubmit" class="btn btn-outline" value="Kaydet">

Console.log(arg) output (1 submit):
{start: Wed Oct 16 2019 00:00:00 GMT+0300 (GMT+03:00), end: Thu Oct 17 2019 00:00:00 GMT+0300 (GMT+03:00), startStr: "2019-10-16", endStr: "2019-10-17", allDay: true, …}

Console.log(arg) output (2 submit):
{start: Wed Oct 16 2019 00:00:00 GMT+0300 (GMT+03:00), end: Thu Oct 17 2019 00:00:00 GMT+0300 (GMT+03:00), startStr: "2019-10-16", endStr: "2019-10-17", allDay: true, …}

{start: Thu Oct 17 2019 00:00:00 GMT+0300 (GMT+03:00), end: Fri Oct 18 2019 00:00:00 GMT+0300 (GMT+03:00), startStr: "2019-10-17", endStr: "2019-10-18", allDay: true, …}

Where am I doing wrong?


text:
Q: How should I link libraries in automake normally linked with pkg-config? I'm trying to get my project buildable with automake. Specifically while using Allegro5.
I can build my code using the following command just fine
g++ -std=c++0x *.cpp -o mygame $(pkg-config --libs allegro-5.0 \
allegro_acodec-5.0 allegro_audio-5.0 allegro_color-5.0 allegro_dialog-5.0 \
allegro_font-5.0 allegro_image-5.0 allegro_main-5.0 allegro_memfile-5.0 \
allegro_physfs-5.0 allegro_primitives-5.0 allegro_ttf-5.0)

But my Makefile will not work.
Here is my src/Makefile.am
bin_PROGRAMS = mygame

AM_CXXFLAGS = "-std=c++0x"

mygame_SOURCES = Animation.cpp Body.cpp GameObject.cpp Menu.cpp Vector3.cpp \
    Arena.cpp Button.cpp Keyboard.cpp Mesh.cpp Assets.cpp Character.cpp \
    main.cpp Mouse.cpp Barrier.cpp Environment.cpp Manager.cpp TitleMenu.cpp

mygame_LDADD = allegro-5.0 allegro_acodec-5.0 allegro_audio-5.0 \
    allegro_color-5.0 allegro_dialog-5.0 allegro_font-5.0 allegro_image-5.0 \
    allegro_main-5.0 allegro_memfile-5.0 allegro_physfs-5.0 \
    allegro_primitives-5.0 allegro_ttf-5.0

CLEANFILES = mygame *.o

And here is my configure.ac
AC_INIT(bayou, 0.1.0)
AM_INIT_AUTOMAKE

AC_LANG_CPLUSPLUS
AC_PROG_CXX
LT_INIT

AC_OUTPUT(
    Makefile \
    src/Makefile\
)

Running my first command works just fine. Running make gives me
make: *** No rule to make target `allegro-5.0', needed by 'mygame'.  Stop.

So how should I set up my configure.ac and Makefile.am's so I can use libraries I normally link with pkg-config?

A: pkg-config is there to tell you dynamically which paths/flags to use.
It is meant to be used dynamically, rather than to run it on your development machine and then copy'n'paste it into the makefile and then expect it to run on any deployment machine.
Here's an updated Makefile.am, based on your own answer:
bin_PROGRAMS = mygame
AM_CXXFLAGS = "-std=c++0x"

PKGLIBS=allegro-5.0 \
    allegro_acodec-5.0 allegro_audio-5.0 allegro_color-5.0 allegro_dialog-5.0 \
    allegro_font-5.0 allegro_image-5.0 allegro_main-5.0 allegro_memfile-5.0 \
    allegro_physfs-5.0 allegro_primitives-5.0 allegro_ttf-5.0
mygame_CXXFLAGS = $(shell pkg-config --cflags $(PKGLIBS)) $(AM_CXXFLAGS)
mygame_LDADD = $(shell pkg-config --libs $(PKGLIBS))

mygame_SOURCES = Animation.cpp Body.cpp GameObject.cpp Menu.cpp Vector3.cpp \
    Arena.cpp Button.cpp Keyboard.cpp Mesh.cpp Assets.cpp Character.cpp \
    main.cpp Mouse.cpp Barrier.cpp Environment.cpp Manager.cpp TitleMenu.cpp

it might be that in your setup, the entire allegro-foo doesn't need any special compiler-flags, but it might as well need some. therefore my example also sets the compiler-flags for your program (mygame_CXXFLAGS).
finally, it get's rid of the unneeded CLEANFILES.
Also, you could go the autotools route, and use the PKG_CHECK_MODULES macro in your configure.ac

A: My lead in the suggestion worked. I did not have to modify my configure.ac (though I probably should so I can verify expected packages are installed)
Anyway, I ran pkg-config <insert libs from comment here> in a terminal window, which gave the following output
-L/usr/local/lib -lallegro_acodec -lallegro_audio -lallegro_color
-lallegro_dialog -lallegro_image -lallegro_main -lallegro_memfile
-lallegro_physfs -lallegro_primitives -lallegro_ttf -lallegro_font
-lallegro

So my new Makefile.am looks like
bin_PROGRAMS = mygame

AM_CXXFLAGS = "-std=c++0x"

mygame_SOURCES = Animation.cpp Body.cpp GameObject.cpp Menu.cpp Vector3.cpp \
    Arena.cpp Button.cpp Keyboard.cpp Mesh.cpp Assets.cpp Character.cpp \
    main.cpp Mouse.cpp Barrier.cpp Environment.cpp Manager.cpp TitleMenu.cpp

mygame_LDADD = -Lusr/local/lib -lallegro_acodec \
    -lallegro_audio -lallegro_color -lallegro_dialog -lallegro_image \
    -lallegro_main -lallegro_memfile -lallegro_physfs -lallegro_primitives \
    -lallegro_ttf -lallegro_font -lallegro

CLEANFILES = mygame *.o

I'd like to thank the academy and my parents for seeing me through this trying time. They've meant so much to me! *blows kisses


text:
Q: How to request directions from current location to destination using Google Maps JavaScript API I've been exploring Google Maps JavaScript API for web and I am getting stuck trying to display directions between the user's current location and a destination.
I am able to display directions between two locations when they are predefined using LatLng(lat, lng). I am also able to find the current location of a user. I just can't seem to do both.
function initMap() {

    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(locationSuccess, locationError);
    }
    else {
        alert("Geolocation not supported");
    }

}

function locationSuccess(position) {

    var directionsService = new google.maps.DirectionsService();
    var directionsDisplay = new google.maps.DirectionsRenderer();
    var trafficLayer = new google.maps.TrafficLayer();

    var myLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
    var LA = new google.maps.LatLng(34.0522, -118.2437);

    var mapOptions = {
        zoom: 8,
        center: {lat: 34.2805, lng: -119.2945}
    };

    var map = new google.maps.Map(document.getElementById('map'), mapOptions);
    directionsDisplay.setMap(map);
    trafficLayer.setMap(map);

    //This will mark the current location if found
    // var myLocationMarker = new google.maps.Marker({
    //     position: myLocation,
    //     map: map,
    //     title: 'Current location'
    // });

    map.setCenter(myLocation);

    var request = {
        origin: myLocation,
        destination: LA,
        travelMode: 'DRIVING'
    };

    directionsService.route(request, function (result, status) {
        if (status == google.maps.DirectionsStatus.OK)
            directionsDisplay.setDirections(result);
    });

}

function locationError() {
    alert("Couldn't get location");
}

A: I'm not sure what the issue was that was preventing you from realising your goals - I tried the code above and it appeared to work - as it was too cold to work in the garage I had a little play and created a small demo; perhaps though you or someone else might find the following useful?
Initially when the call to navigator.getCurrentLocation resolves with the user's location the map loads using the returned position object to form the map centre location. The route to the pre-defined destination is then calculated using the Directions service with a modified options parameter - notably in this instance to hide the default markers. The reason for hiding the markers is because they do not expose any events and thus we cannot bind any listeners to them so we add our own. The added markers allow the route to be dynamically re-calculated ( can also drag the actual route itself )
The text version of the directions is available by clicking on one of the two markers.
The destination is in Birmingham, UK. If you are outwith the UK this might not work immediately without editing this location. Also, a valid API key is required.
<!DOCTYPE html>

        <title>Google Maps: Directions from my location to...</title>
        <meta charset='utf-8' />


text:
Q: Impact of adding new column/index to existing table? I am looking to implement a new feature in a database that requires linking records to another table.  The table already contains about 76000 records and only newly added records would need a link id.  I'm looking at two approaches:

*

*add a new table with the source and target ids.  This is possibly (?) the most performant from a database point of view but requires more logic in the application.

*add a new indexed column to the existing table.  The value of this column would be null for existing records and would contain a integer value for new records.
What I'd like to understand is the the impact of the second approach the size and performance of the index specifically when I am selecting rows based on a specific value in the new column.

A: When you are working with millions of records, MySQL starts to choke a bit, depending on server speed, RAM, etc. However, 76,000 records is "nothing". So go with option 2, add a field, default NULL, indexed and use that as a foreign key into the other table. Selecting on specific rows using the new column will run very fast as long as it is indexed.


text:
Q: AOF and RDB backups in redis This question is about Redis persistence.
I'm using redis as a 'fast backend' for a social networking website. It's a single server set up. I've been transferring PostgreSQL responsibilities to Redis steadily. Currently in etc/redis/redis.conf, the appendonly setting is set to appendonly no. Snapshotting settings are save 900 1, save 300 10, save 60 10000. All this is true for production and development both. As per production logs, save 60 10000 gets invoked heavily. Does this mean that practically, I'm getting backups every 60 seconds?
Some literature suggests using AOF and RDB backups together. Thus I was weighing in on turning appendonly on and using appendfsync everysec. For anyone who has had experience of both sides of the coin:
1) Will using appendonly on and appendfsync everysec cause a performance downgrade? Will it hit the CPU? The write load is on the high side.
2) Once I restart the redis server with these new settings, I'll still lose the last 60 secs of my data, correct?
3) Are restart times something to worry about? My dump.rdb file is small; ~90MB.
I'm trying to find out more about redis persistence, and getting my expectations right. Personally, I'm fine with losing 60s of data in the case of a catastrophe, thus whether I should use AOF is also something I'm pondering. Feel free to chime in. Thanks!

A:
Does this mean that practically, I'm getting backups every 60 seconds?

NO. Redis does a background save after 60 seconds, if there're at least 10000 keys have been changed. Otherwise, it doesn't do a background save.

Will using appendonly on and appendfsync everysec cause a performance downgrade? Will it hit the CPU? The write load is on the high side.

It depends on many things, e.g. disk performance (SSD VS HDD), write/read load (QPS), data model, and so on. You need do a benchmark with your own data in your specific environment.

Once I restart the redis server with these new settings, I'll still lose the last 60 secs of my data, correct?

NO. If you turn on both AOF and RDB, when Redis restarts, the AOF file will be used to rebuild the database. Since you config it to appendfsync everysec, you will only lose the last 1 second of data.

Are restart times something to worry about? My dump.rdb file is small; ~90MB.

If you turn on AOF, and when Redis restarts, it replays logs in AOF file to rebuild the database. Normally AOF file is larger then RDB file, and it might be slower than recovering from RDB file. Should you worry about that? Do a benchmark with your own data in your specific environment.
EDIT
IMPORTANT NOTICE
Assume that you already set Redis to use RDB saving, and write lots of data to Redis. After a while, you want to turn on AOF saving. NEVER MODIFY THE CONFIG FILE TO TURN ON AOF AND RESTART REDIS, OTHERWISE YOU'LL LOSE EVERYTHING.
Because, once you set appendonly yes in redis.conf, and restart Redis, it will load data from AOF file, no matter whether the file exists or not. If the file doesn't exist, it creates an empty file, and tries to load data from that empty file. So you'll lose everything.
In fact, you don't have to restart Redis to turn on AOF. Instead, you can use config set command to dynamically turn it on: config set appendonly yes.


text:
Q: H2 Database WIth .NET Application I have created .NET APP that is supposed queries the H2 DB but at the time of "DriverManager.getConnection(DBUrl, DBUName, DBPassword);"
it gives the following error:

Error : IO Exception: "java.io.FileNotFoundException: Access to the path 'C:\Windows\System32\config\systemprofile\test.lock.db' is denied."; "C:\Windows\System32\config\systemprofile\test.lock.db
I have accessed the H2 DB throught its console its working fine but when i try to connect it with .NET App it gives above error.
Edited:
http://www.h2database.com/html/advanced.html#microsoft_dot_net
I'm using this approach to query H2 database.

A: Try to delete test.lock.db file


text:
Q: Can't overload Windows.Forms.Timer.Stop() - Sub-Name must not be a keyword I have an application with about 15.000 lines of code. It's showing some data to the user. To keep the data updated it is running a Windows.Forms.Timer . The shown data updates on each tick.
To avoid unnecessary network traffic and computer utilization on the SQL Server the timer is stopped as soon as the user goes into sub-forms using .Enabled = False or .Stop(). When they close the subform the timer is restarted with .Start() or .Enabled = True.
Somewhere in the code is a problem, that causes the Timer to completly stop so data will not be refreshed anymore. I need to find out where that happens.
To do that I am creating a new class, that Inherits Windows.Forms.Timer. I want to overload the Enabled property, Start() and Stop() sub.
Turns out that I can't.
Trying to overload the Stop() sub gets me into an Error shown by Visual Studio telling me, that I am not allowed to use 'Stop()' as a Sub-Name due to it beeing a keyword. It's not just a warning but an error that keeps me from compiling.
Can I turn this error off for these specific lines or can you give me a different approach to solve the main problem?
Public Class MyApp_RefreshTimer
    Inherits Windows.Forms.Timer

    Private Overloads Property Enabled As Boolean
        Get
            ' A part of my logging will be placed here.. probably
            Return MyBase.Enabled
        End Get
        Set(value As Boolean)
            MyBase.Enabled = value
        End Set
    End Property

    Public Overloads Sub Stop()

    End Sub

End Class

A: Since "Stop" is a keyword, you would have to bracket the procedure name:
Public Overloads Sub [Stop]()

End Sub


text:
Q: Determining if there are significant differences in gender ratio across multiple regions My data look like this:
UnigueID  Region   Sex   etc.
4567      4        M
3452      2        F
2316     12        F
2347      4        F
3987      7        M
9567      7        M

and so on for 15,000 some obs.
I have multiple regions, different numbers of obs in each region, and I want to know first and foremost are the gender proportions different? And then ideally which are different and by how much (confidence limits, etc). I thought to do an ANOVA test using proportion of females in each group as a gender mean but I wasn't getting an F-value presumably because there is no spread using that idea it is just a single number for each group, so there was no error.
I'm not sure what I'm screwing up conceptually.

A: An ANOVA should work here (assuming regions are independent and variances are equal) You can calculate:

*

*Group means - proportion of females per region

*Group standard deviations - similar as above

*Grand mean - total proportion of females in the dataset

Using that, you should be able to find an F-statistic and p-value. Now, that will only tell you if each region has the same proportion of females.
If you reject the Null, then there is more work to do. You want to figure out which of the means is actually differen and by how much. There exist many approaches, most basic of them may be Tukey's HSD or Scheffe's method.


text:
Q: WSO2 ESB 4.8.1 Clustering Is it possible to create one ESB node as a dual role as a worker and manager ?
I'm using wso2 ESB 4.8.1 and nginx as load balancer.

A: This is pretty easy. This is what you have to do.

*

*Forget about nginx and setup the ESB cluster. Lets say a cluster with one manager and one worker. I think you will be able to get it done by following the instructions here. Instead of WSO2 ELB mentioned in the doc, you are going to use nginx. Instead of the ELB, You can set the management and worker node as the well known members. i.e. In both nodes, you set both nodes as the well known members.

*Once you have the cluster working, you should be able to send requests to an artifact deployed to both nodes separately. Difference between the manager node and worker node is, manager node is the one who only commits to the svn repo. So, when you deploy new artifacts you should deploy them using the manager node.

*Now you have to configure two sites in nginx. Lets assume you decided to use esbmgt.mydomain.com for the management node and esb.mydomain.com for the worker. In esbmgt's upstream, you only mention about the manager node and also you route the requests to the 9443 port of the node. In the esb's upstream, you mention both nodes and the requests are routed to 8280 (http) and 8243 (https). Thats because the ESB serves requests using those ports and the UI is exposed via 9443 (https)

I hope the above information will help you.


text:
Q: Is it possible to load AWS SSM ARN in Init container and use in the main container How to pass AWS SSM ARN or Access Key and Secret as env variables in init container and then pass the SSM parameters to main container.

A: You're looking for a solution like https://github.com/godaddy/kubernetes-external-secrets
It supports both SSM Parameter Store and AWS Secrets Manager as backends. Pros of this comparing to init container is that you have a much more narrow scope of pods with an access to SSM. In your case it's every pod (every init container you run), in the case of kubernetes-external-secrets it's only one controller pod per cluster. And of course, it gives less boilerplate.
Similar solutions:

*

*https://github.com/mumoshu/aws-secret-operator

*https://github.com/ContainerSolutions/externalsecret-operator

*https://aws.amazon.com/blogs/containers/aws-secrets-controller-poc/


text:
Q: SqlCommand VarChar or Int? I am wondering which is the "correct" way of adding parameters to a SQLCommand. It seems to me its best to match the data types. However, is parsing the string to Int better than using the .ToString() method performance wise? Does it go against good practice? SQL server doesn't seem to care. id is of type int in the table.
command.CommandText = "SELECT name FROM table WHERE id=@ID";
command.Parameters.Add("@ID", System.Data.SqlDbType.Int).Value = int.Parse(Request.QueryString["id"]);

OR
command.CommandText = "SELECT name FROM table WHERE id=@ID";
command.Parameters.Add("@ID", System.Data.SqlDbType.VarChar).Value = Request.QueryString["id"].ToString();

A: int type in SQL Server is mapped in Int32 in CLR side. That's why the "correct" way is adding a parameter which is SqlDbType.Int. Period.

However, is parsing the string to Int better than using the
  .ToString() method performance wise?

Sending a wrong parameter typed value as a parameter might generate more serious problems than a performance. Looks like "performance" is not even a real case in your example since you never mentioned any performance issue in your work.

SQL server doesn't seem to care

But as a developer, you should.


text:
Q: Download Xcode with developer account and then change account I have a developer account now, and I can download Xcode 5.
But soon I won't need this account anymore, and I may
get a new (organization type) account.
My question is, will I be able to use my new organization
account to write programs with Xcode 5 I downloaded previously?
And also submit possibly with this new account?
Thanks.

A: Yes.
If you submit the app to the App Store using your first account, then you can use iTunes Connect App Transfer to transfer it to a new account.
If you work on the app without submitting it to the App Store, you can change account and there will be no problems (you will have to change the App ID & provisioning profiles if you obtained these with the old account).

A downloaded copy of Xcode is not linked to an account, so you can use Xcode with any account, or no account.
The limitations come with the documentation - pre-release documentation will not be available in Xcode if you don't link an account, however Xcode will still work fine without the documentation. Once you add a new account, the documentation will download and be accessible. Documentation downloaded with your current developer account will not need to be re-downloaded if you switch account.


text:
Q: Doubt: Prove that the circumcircles of $\Delta ABC$ and $\Delta ADE$ are tangent with $\sqrt {BC}$
So, I recently started inversion and I have doubt in this solution . It's from "A beautiful Journey through Olympiad geometry " by Stefan Lozanovski. This Problem uses $\sqrt{BC}$
Here , I couldn't understand this line

Furthermore, the circles $\omega _1$
and $\omega_2$ are tangent to $(ABC)$ and to the parallel lines $\ell'$ and $BC$, so they are
symmetric with respect to the perpendicular bisector of $BC$.Thus, $D'$ and $E'$
are symmetric with respect to the perpendicular bisector of $BC$ as well.

I understood that it's enough to show that $D'E'\parallel BC $ , and I also observed that $\omega _1$
and $\omega_2$ are congruent . But the above lines aren't clear , can someone explain it ?
Thanks in advance !

A: It's basically Thales' theorem. Let $O_1,O_2,O$ be centers of $\{\omega_1', \omega_2',\odot(ABC)\}$. Thus, $O_1-D'-O$ and $O_2-E'-O$ are collinear. Trivially, $\omega_1'$ and $\omega_2'$ have same radius say $r$. Thus, $OO_1=OO_2=r+R$ where $R$ is radius of $\odot(ABC)$. Further, $OD'=OE'=R\overset{\text{Thales'}}{\implies} D'E'\|O_1O_2$ but $O_1O_2\| BC\implies D'E'\| BC$ so done.


text:
Q: Web page delivers two different sets of output when scraped vs viewed I'm trying to scrape a web page hosted on a device on my network.  I've done this dozens of times with other model devices on the same network.  When I browse to the page in IE or Chrome, it's formatted properly and I see the source I'm expecting.
However, when I try to read the response stream in .Net or try running it in Fiddler, I'm given source for what looks like Javascript and session generating scripting rather than the numbers I care about.
I think this page is now hitting a javascript powered landing page, calling back to the printer, then formatting and outputting back into my browser.  I think my difference is that calls from inside of Fiddler and .Net GetResponseStream() calls aren't letting the javascript do what it needs to to get all of the data.
Sample
            WebRequest ConReq = WebRequest.Create(consumablePage);
            WebRequest UseReq = WebRequest.Create(usagePage);
            ConReq.Timeout = 15000;
            UseReq.Timeout = 20000;
            WebResponse ConResp = ConReq.GetResponse();
            WebResponse UseResp = UseReq.GetResponse();

            Stream Constream = ConResp.GetResponseStream();
            StreamReader Consr = new StreamReader(Constream);

            Stream Usestream = UseResp.GetResponseStream();
            StreamReader Usesr = new StreamReader(Usestream);

            string conRead = Consr.ReadToEnd();
            string useRead = Usesr.ReadToEnd();

At the end, conRead and useRead both contain:
"\r\n\r\n\r\n\r\n\r\n\r\n\r\n"

This picture is an example of a Fiddler GET, and an IE instance of the same page.  Note the Fiddler response is only 1075K and the IE response is 6602K.

How can I get a fully parsed response stream back in .Net?


text:
Q: How can I search/index multiple geo-location positions for a aggregated search? I am using $geoNear to search for a business location based of a users location. However when I perform the search, Mongo only allows me to index 1 geo-location some businesses have multiple location, and I would like to be able to turn the location index to find the closest result.
This is what I currently have:
 location : {
        type: { type: String, default: "Point" },
        coordinates: { type: [Number], default: [115.8575,-31.953] },
    },

And this is what I would like to have:
 location : [{
            name: "Suburb 1",
        type: { type: String, default: "Point" },
        coordinates: { type: [Number], default: [115.8575,-31.953] },
    },
    {
            name: "Suburb 2",
        type: { type: String, default: "Point" },
        coordinates: { type: [Number], default: [115.8575,-31.953] },
    }],

Where the search would find the closest result. Is there an ideal way to do this?
Thanks

A: If you would like to use $geoNear, you should consider redesigning your data model. $geoNear would return you the closest location (sorted), and it requires geospatial-index(es).
A suggestion would be to store a single document entry per business location.
You may also find Tutorial: Geospatial useful especially the examples.


text:
Q: Configuring firewalld (Rocky linux 9) After much pain I managed to configure firewalld so that I only allow specific services to given IP-numbers.
Now I want to give access to all IPs to https/447. But I don't know how to do that. My current configuration is listed below.
# firewall-cmd --get-active-zones
customzone
  sources: ipset:Trusted_IP_all
drop
  interfaces: enp0s31f6

The drop zone:
# more drop.xml
<?xml version="1.0" encoding="utf-8"?>
<zone target="DROP">
  <short>Drop</short>
  <description>Unsolicited incoming network packets are dropped.</description>
  <forward/>
</zone>

And the customzone:
# more customzone.xml
<?xml version="1.0" encoding="utf-8"?>
<zone target="DROP">
  <short>Custom Zone Configuration</short>
  <description>All incoming connections are blocked by default. </description>
  <service name="ssh"/>
  <service name="http"/>
  <service name="https"/>
  <source ipset="Trusted_IP_all"/>
</zone>

The "Trusted_IP_all" contain a selected few IP-nr/ranges


text:
Q: MySql : Integrity contraint fails because of MyISAM and InnoDB mix. How to fix that safely? I have a web site running on Django and MySql.
Part of the db tables are using InnoDB as engine and some other are using MyISAM.
There is no special reason for that. The project was started a long time ago and I think it is caused by a change in a configuration.
This cause some integrity constraint to fail when a InnoDB FK is referencing a MyISAM table. Changing the table from MyISAM to InnoDB fix the problem.
My problem is that this site is under production. It already has this mix of tables. There is a lot of tables.
Is there a clean and safe way to fix this problem? Do I have to change all MyISAM tables into InnoDB? Is there any risk to do that?
Thanks in advance for your help

A: You can certainly take the web site offline and convert your MyIsam tables to InnoDb.  (Do back up the db first, of course.)
Your big quality risk on a production web site isn't changing a table's storage engine, though.  It's starting to enforce database integrity constraints while the system is in production.  You may find that you have a lot of data repair to do to allow the constraints to be enforced.
You are probably wisest to build a shadow copy of this system (web site and DB) and work through all your changes carefully.  Keep track of the commands and configuration changes you do on the shadow copy, so you can do them again on the live copy when you've proven that they work.  But there is some chance they won't work.
Shadow copies are easy in this age of virtual machines.


text:
Q: PHP redirection with post values Is it possible to redirect user to external server without using:
header('Location:address.com?var=1');
or
HTML form with JS auto submit
Seems really simple but can't figure it out. I do not want to use GET, I would rather send it via headers/post if possible.
Making ajax request is slowing it down and I believe there should be some kind of solution in pure PHP.
CURL is not an option as I want to go to that link with posted data.
Cheers

A: You can do this using this method session_set_cookie_params(). It is used to transfer data from 1 url to another url using session. To get the result you have to write this function before every session_start().
session_set_cookie_param();
@session_start();


text:
Q: How to color just the section numbers in the Toc in the tufte-book class?
This is a follow-up question to How to color section numbers in the
  TOC?

How to adopt the answers in the link above to work in the tufte-book class? here is my MWE:
\documentclass[notoc,numbers]{tufte-book}
\usepackage{color}

\makeatletter
\renewcommand*\l@section{\@dottedtocline{1}{0em}{2.3em}}
\makeatother
\setcounter{secnumdepth}{3}
\setcounter{tocdepth}{3}
\begin{document}
\tableofcontents

\chapter{Test one}
\section{Introduction}
\section{Foo bar}

\end{document}

A: tufte-book uses the titlesec and titletoc pair to manage the sectional and their ToC-related entries. As such, we just need to change the appropriate \titleformat{section} entry inside tufte-common.def to get the desired result:

\documentclass[notoc,numbers]{tufte-book}
\usepackage{xcolor}

% Taken from http://mirrors.ctan.org/macros/latex/contrib/tufte-latex/tufte-common.def
\titlecontents{section}% FIXME
  [0em] % distance from left margin
  {\rmfamily} % above (global formatting of entry)
  {\hspace*{2em}\textcolor{red}{\contentslabel{2em}}} % before w/label (label = ``2.6'')
  {\hspace*{2em}} % before w/o label
  {\titlerule*[0.7em]{.}\rmfamily\upshape\contentspage} % filler + page (leaders and page num)
  [] % after

\setcounter{secnumdepth}{3}
\setcounter{tocdepth}{3}

\begin{document}

\tableofcontents

\chapter{Test one}
\section{Introduction}
\section{Foo bar}

\end{document}


text:
Q: Use Gram matrix to prove CBS inequality Hi I am trying to prove the CBS inequality i.e. $|\langle x,y\rangle |\le||x||\,||y||$ by using Gram matrix.
Now I know how to prove Gram matrix $G_w$ is positive semidefinite i.e.
for $z=(z_1,z_2,....,,z_n)^T\in\mathbb{C}^n$ and $w=\{w_1,w_2,...,w_n\}\subset X$ then the Gram matrix is positive semidefinite by showing that $$z^*G_w\,z\ge 0$$ where $G_w=\Bigg(\langle w_i,w_j\rangle\Bigg)_{1\le i,j\le n}$
But I am stuck with how to prove CBS inequality using the positive semi definiteness of Gram matrix. Any help would be highly appreciated. Thanks in advance.

A: A Gram matrix is positive semidefinite, so its every $2\times2$ principal submatrix is positive semidefinite and has nonnegative determinant, i.e. $g_{ii}g_{jj}\ge g_{ij}^2$. Write each entry of $G_w$ as an inner product of vectors among $w_1,\ldots,w_n$ and take square roots on both sides, you recover the CBS inequality.


text:
Q: How to disable arrow keys? I have template view (Extjs v6.5) where navigation inbuilt with all four (left right top down) keys, whereas my view is like a vertical list, so I wanted to use only top and down keys and disable left and right keys.
I have tried disabling buttons on itemKeyDown event of Ext JS
this.addListener('itemkeydown', (me, record, item, index, e, eOpts) => {
  if (e.keyCode === 37 || e.keyCode === 39) {
    return false;
  }
});

And keydown event of javascript button couldn't achieve it.
this.el.dom.addEventListener('keydown', (e) => {
  if (e.keyCode === 37 || e.keyCode === 39) {
    return false;
  }
});

Also tried e.preventDefault(); along with return false;
Sample code fiddle can be found here

A: Call e.stopPropagation() to keep the keyboard event from bubbling up to a parent element.
This revised code will catch the "ArrowRight" and "ArrowLeft" keys.
function ignoreRightOrLeftKeys (e) {
  if (e.key === "ArrowRight" || e.key === "ArrowLeft") {
    e.stopPropagation();
    console.log("itemkeydown stopped");
    return false;
  }
  return true;
}

this.el.dom.addEventListener("keydown", (e) => {
  console.log("keydown caught e:", e);
  return ignoreRightOrLeftKeys(e);
});

this.addListener("itemkeydown", (me, record, item, index, e, eOpts) => {
  console.log("itemkeydown caught e:", e);
  return ignoreRightOrLeftKeys(e);
});


text:
Q: Wrong Data being sent to Mysql database from VB.net through paramatized insert statement I am trying to insert data to mysql from vb.net. When I use concatenated sql query, it works well but when I make it paramatized, no error is shown by the vb.net try and catch statement, but wrong values and some null values are sent.
MysqlConn = New MySqlConnection
MysqlConn.ConnectionString = "server=127.0.0.1;userid=root;password=root;database=my_mysql_database"
Dim READER As MySqlDataReader
Try
    MysqlConn.Open()
    Dim Query As String
    'Query = "INSERT INTO my_mysql_database.edata(E_id,Name,Surname,Age,user_name,password, Gender)values('" & Txt_EID.Text & "', '" & Txt_Name.Text & "', '" & Txt_Surname.Text & "', '" & Txt_Age.Text & "', '" & Txt_User_Name.Text & "', '" & Txt_Password.Text & "', '" & Txt_Gender.Text & "')"'
    Query = "INSERT INTO my_mysql_database.edata
             values(E_id=@Eid, Name=@Name, Surname=@Surname, Age=@Age,
             user_name=@UserName, password=@Pass, Gender=@Gender, DOB=@Dob,
             Image=@Ima, Email=@Email)"
    COMMAND = New MySqlCommand(Query, MysqlConn)
    COMMAND.Parameters.AddWithValue("@Eid", Txt_EID.Text)
    COMMAND.Parameters.AddWithValue("@Name", Txt_Name.Text)
    COMMAND.Parameters.AddWithValue("@Surname", Txt_Surname.Text)
    COMMAND.Parameters.AddWithValue("@Age", Txt_Age.Text)
    COMMAND.Parameters.AddWithValue("@UserName", Txt_User_Name.Text)
    COMMAND.Parameters.AddWithValue("@Pass", Txt_Password.Text)
    COMMAND.Parameters.AddWithValue("@Gender", Txt_Gender.Text)
    COMMAND.Parameters.AddWithValue("@Dob", DTP_Date.Value)
    COMMAND.Parameters.AddWithValue("@Ima", Txt_Image.Text)
    COMMAND.Parameters.AddWithValue("@Email", Txt_Email.Text)
    READER = COMMAND.ExecuteReader
    MsgBox("Added to Database")
    MysqlConn.Close()
Catch ex As Exception
    MessageBox.Show(ex.Message)
Finally
    MysqlConn.Dispose()
End Try

When I do the paramatized way no error is shown, but a zero and all nulls are saved in mysql database.

During Debug I have checked the values stored in the parameters and they are correct, but what is sent to Mysql dataabse is a zero and all NULLS. What could be happening. How can Isend the correct values to Mysql Database
edit:
Here is a picture of datatypes

A: I might be off here, if that is the case someone can educate me. My SQL knowledge tells me your query is wrong.
You say that this one work:
Query = "INSERT INTO my_mysql_database.edata(E_id,Name,Surname,Age,user_name,password, Gender)values('" & Txt_EID.Text & "', '" & Txt_Name.Text & "', '" & Txt_Surname.Text & "', '" & Txt_Age.Text & "', '" & Txt_User_Name.Text & "', '" & Txt_Password.Text & "', '" & Txt_Gender.Text & "')"'

So why change the format of the second query? INSERT INTO Table Values (Column=Value)
Surely it is supposed to be INSERT INTO Table (Column) Values (Value). Hence your query should look like this:
Query = "INSERT INTO my_mysql_database.edata (E_id,Name,Surname,Age,user_name,password,Gender,DOB,Image,Email) Values (@Eid,@Name,@Surname,@Age,@UserName,@Pass,@Gender,@Dob,@Ima,@Email)

Also, I strongly suggest you setup E_id to be auto incremental. Adding the ID yourself seems a bit unecessary.


text:
Q: how to deploy heroku with an existing an git repository I have been working on a repository and am now pushing it to heroku.  I went through heroku for a guide    https://devcenter.heroku.com/articles/git
I checked to make sure I had the git and heroku configuration.
git remote -v

I get back a heroku config and a git config for fetch and push
heroku git:remote -a path name

However, I get back "couldn't find that app"   So I typed
heroku apps

My app is not there.   So I am missing something.  I followed the directions and can verify my remote.  Not sure what I am missing.

A: First remove the heroku remote
git remote rm heroku

Add it again correctly
git remote add heroku https://git.heroku.com/sleepy-escarpment-1894.git

Then push your app
git push heroku master


text:
Q: JavaHL.Unable to commit with my java application I want to control my Subversion environment (Sliksvn 1.8.10) with a small Java programm on a Windows 7 64 bit machine. I need to use JavaHL (1.8.x) not SVNKIt. I have implemented a funktion to checkout a repository, add files to a work copy and commit files to repository. The checkout and the add function works fine so far. The problem ist now, that the commit-funktion don't work correctly.
public void commit()
{

Set<String> paths = new HashSet<String>();
paths.add( "C:\\Users\\XXX\\Documents\\SVNTEST\\Test3" );
Depth dep = Depth.infinity;
);

CommitMessageCallback handler = new CommitMessageCallback()
{
@Override
public String getLogMessage(Set<CommitItem> arg0) {
    // TODO Auto-generated method stub
    System.out.println(arg0.size());
    return null;
}
};

CommitCallback callback = new CommitCallback()
{

@Override
public void commitInfo(CommitInfo arg0) {
    // TODO Auto-generated method stub
    System.out.println(arg0.getAuthor());

}
};
try
{

  client.commit( paths, dep, true, false, null, null, handler, callback );

}
catch( ClientException e )
{
  // TODO Auto-generated catch block
  e.printStackTrace();
}

}

When i process the commit function, then i get from the CommitMessageCallback function the amount of the commit items. This works still. My problem is now, that don't receive any CommitInfo from the CommitCallback function. I think maybe, the process breaks up in der subversion environment and my function get no result. After the process, the commit Items are still in svn status "Item is scheduled for Addition".
I work on this problem since a few days with different version of the JavaHL.jar api, but it was not successful. The big problem is also, that i receive no error message and i dont know what is wrong in code.
Have anybody a idea what is wrong in my commit function ?
Perhaps is the libsvnjavahl-1.dll file not compatible with certain JavaHL Api's ?
Thank you very much
Best regards Simon

A: Okay, i solved the problem now. The easy solution was to use the org.tigris.subversion instead of the org.apache.subversion library classes. But the question is, why exist two different version from the JavaHL library ?


text:
Q: PHP empty TMP_NAME on iOS Upload Image I am currently developing an iOS project that requests the user to upload an image to the server.
I currently have this code in my class in Objective-C:
        NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
        [request setHTTPShouldHandleCookies:NO];
        [request setTimeoutInterval:60];
        [request setHTTPMethod:@"POST"];
        NSString *boundary = @"------VohpleBoundary4QuqLuM1cE5lMwCy";
        NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];
        [request setValue:contentType forHTTPHeaderField: @"Content-Type"];

        NSMutableData *body = [NSMutableData data];
        NSMutableDictionary *parameters = [[NSMutableDictionary alloc] init];
        [parameters setValue:[SSKeychain passwordForService:@"ID" account:@"SpotterBike"] forKey:@"ID"];

        for (NSString *param in parameters) {
            [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
            [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n", param] dataUsingEncoding:NSUTF8StringEncoding]];
            [body appendData:[[NSString stringWithFormat:@"%@\r\n", [parameters objectForKey:param]] dataUsingEncoding:NSUTF8StringEncoding]];
        }

        NSString *FileParamConstant = @"uploadedfile";
        NSData *imageData = UIImageJPEGRepresentation(image, 1);

        if (imageData){
            [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
            [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"image.jpg\"\r\n", FileParamConstant] dataUsingEncoding:NSUTF8StringEncoding]];
            [body appendData:[@"Content-Type:image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
            [body appendData:imageData];
            [body appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
        }

        [body appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
        [request setHTTPBody:body];
        [request setURL:[NSURL URLWithString:@"http://212.92.57.155/App/UploadImage.php"]];

However, although the server recieves the image, I am not able to process it for further usage in it. As you see, tmp_name is empty, so I am not able to move the image to the directory.
print_r($_FILES['uploadedfile']);

(
    [name] => image.jpg
    [type] =>
    [tmp_name] =>
    [error] => 1
    [size] => 0
)

Any idea of why this is happening?

A: The image file size of the photos taken using the camera tend to be quite large for a 3G connection. Therefore, as your answer suggests, you need to increase the MAX_REQUEST_TIMEOUT

A: Just in case someone is facing the same problem, after some days of research, I have found the problem.
The images were uploaded with 3G mobile connections, as a result, there was certain amount of delay in beetwen the time the upload started until it finished.
Due the fact that, the MAX_REQUEST_TIMEOUT property had a low value, the image was not able to reach the server before the MAX_REQUEST_TIMEOUT exceeded, so the upload was aborted.
Hope it helps!


text:
Q: How does a Bootstrap modal change the page's opacity? When opening a Bootstrap modal (eg the GetBootstrap modal sample), the rest of the page is subtly faded out to draw attention to the modal:

How is Bootstrap accomplishing this? It seems that the class .modal-open is added to the body, but this only sets overflow: hidden. What else is Bootstrap adding/changing to cause that effect? Is the positioning of the modal within the page important?
(This is a roundabout way of asking why my modal isn't fading out the background when it's open. The code is too complicated to post, and presumably there's a flaw in my markup or CSS. If I knew how Bootstrap was accomplishing the opaque background I may be able to debug why it's not working for me.)

A: Bootstrap add a div and adds some classes to it. Which has black background with .5 opacity set. And add style to set height as viewport / browser screen.

If your modal is not fading out, check if you are using :
display:block!important /* notice !important */

A: When the modal appears, it adds a div container with the class modal-backdrop fade in before the modal-dialog container.


text:
Q: Issue with self join with a sub query;wanted to know the difference of 2 queries below This working:
SELECT a.year, a.name, a.runs
from players a  JOIN
     (SELECT year, max(runs) runs FROM players GROUP BY year
     ) b
     ON (a.year = b.year AND a.runs = b.runs);

This is not working:
select a.name,b.year,b.run
from players a join
     (select year, max(runs) as run, name from players group by year
     ) b
     on a.year = b.year AND a.runs = b.run;

Can someone plz help me understand this?

A: The second  Join query  is not properly group by
     (select year, max(runs) as run, name from players group by year
 ) b

because you select also name  you should group by
        (select year, max(runs) as run, name from players group by year, name
 ) b

but this give you different result