text:
Q: swift: ContainerView correct action I have firstViewController and secondViewController. I want to elements from the secondViewController to overlap the firstViewController (but should be firstViewController visible like background). I use containerView for this with clear color. In storyboard I press hidden for containerView and in firstViewController.swift I have action - containerView.isHidden = false.
question: Is this correct containerView using? I do not really like that at firstViewController start data from secondViewController also loading. Maybe in my action I should call secondViewController another way?

A: I not totally clear on what effect you are trying to achieve.  So I tell you want I sometimes do for overlapping views:
(Like your secondViewController) is displayed as a modal.  So in (like your firstViewController), on a specific action:
        let vc = secondViewController()
        vc.dialogWindow.layer.masksToBounds = true
        vc.dialogWindow.borderWidth = 3
        vc.dialogWindow.borderColor = UIColor.red.withAlphaComponent(0.75)
        vc.isModalInPopover = true
        vc.modalPresentationStyle = .overFullScreen
        self.present(vc, animated: true, completion: nil)

That way the secondViewController is presented over the firstViewController.  To close it, it calls:
    self.dismiss(animated: true, completion: nil)

Maybe you'll want to adjust the properties.


text:
Q: Accessing SVG file directly from Javascript code I have this HTML code, which is invoking my javascript code. The code is for a gauge. In the javascript code, I am trying to access a SVG file, and modifying the needle (of the gauge) to display the desired value. The code is working fine. However, I do not wish to call "object id" in HTML. I want to access SVG file through javascript directly, instead of using object id in HTML. I tried using el.setAttribute('data', 'gauge.svg');   But then svg_doc isn't able to retrieve the SVG image and modify the needle. Any help would be highly appreciated.
PS : I tried my best to be as thorough in explaining the problem. However, please let me know if I am unclear somewhere.
This is Gauge.png image which is embedded in the svg code I have pasted below https://sphotos-b.xx.fbcdn.net/hphotos-snc6/179594_10150982737360698_1827200234_n.jpg
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
    <g name="gauge" width="122px" height="127px">
        <image xlink:href="gauging.png" width="122" height="127"/>
    <circle id="led" cx="39" cy="76" r="5" style="fill: #999; stroke: none">
        <animateColor id="ledAnimation" attributeName="fill" attributeType="css" begin="0s" dur="1s"
        values="none;#f88;#f00;#f88;none;" repeatCount="0"/>
    </circle>
        <g id="needle" transform="rotate(0,62,62)">
            <circle cx="62" cy="62" r="4" style="fill: #c00; stroke: none"/>
            <rect transform="rotate(-130,62,62)" name="arrow"  x="58" y="38" width="8" height="24" style="fill: #c00; stroke: none"/>
            <polygon transform="rotate(-130,62,62)" points="58,39,66,39,62,30,58,39" style="fill: #c00; stroke: none"/>
        </g>
        <text id="value" x="51" y="98" focusable="false" editable="no" style="stroke:none; fill:#fff; font-family: monospace; font-size: 12px"></text>
    </g>
</svg>

HTML+Javascript code
    <head>
    <title>SVG Gauge example</title>

    <script>
    function update1(){
        var scale=100;
        var value;
        var value1 = 69;

        var el=document.getElementById('gauge1');
        if (!el) return;

        /* Get SVG document from HTML element */
        var svg_doc = el.contentDocument;
        if (!svg_doc) return;

        /* Rotate needle to display given value */
        var needle_el = svg_doc.getElementById('needle');
        if (!needle_el) return;
        /* Calc rotation angle (0->0%, 260->100%) */
        value = parseInt(value1);
        scale = parseInt(scale);
        if (value > scale) value = scale;
        var angle = value / scale * 260;
        /* On-the-fly SVG transform */
        needle_el.setAttribute('transform','rotate('+angle+',62,62)');
    }
document.addEventListener('load', update1, true);
    </script>

    </head>

<div>
<object id="gauge1" type="image/svg+xml" data="gauge.svg" width="127" height="122"/>
</div>

</html>

A: As robertc already mentioned, you can embed the javascript code into your SVG file:
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
    <g name="gauge" width="122px" height="127px">
        <image xlink:href="gauging.png" width="122" height="127"/>
    <circle id="led" cx="39" cy="76" r="5" style="fill: #999; stroke: none">
        <animateColor id="ledAnimation" attributeName="fill" attributeType="css" begin="0s" dur="1s"
        values="none;#f88;#f00;#f88;none;" repeatCount="0"/>
    </circle>
        <g id="needle" transform="rotate(0,62,62)">
            <circle cx="62" cy="62" r="4" style="fill: #c00; stroke: none"/>
            <rect transform="rotate(-130,62,62)" name="arrow"  x="58" y="38" width="8" height="24" style="fill: #c00; stroke: none"/>
            <polygon transform="rotate(-130,62,62)" points="58,39,66,39,62,30,58,39" style="fill: #c00; stroke: none"/>
        </g>
        <text id="value" x="51" y="98" focusable="false" editable="no" style="stroke:none; fill:#fff; font-family: monospace; font-size: 12px"></text>
    </g>

    <script type="text/javascript">
        var scale=100;
        var value;
        var value1 = 69;

        /* Rotate needle to display given value */
        var needle_el = document.getElementById('needle');
        /* Calc rotation angle (0->0%, 260->100%) */
        value = parseInt(value1);
        scale = parseInt(scale);
        if (value > scale) value = scale;
        var angle = value / scale * 260;
        /* On-the-fly SVG transform */
        needle_el.setAttribute('transform','rotate('+angle+',62,62)');

    </script>
</svg>

I've put the code below the actual SVG contents so that the document is already loaded when the script is executed.
Then, you can view the SVG file directly e.g. in Firefox (I've tested it right now).

redpajama_set_name: RedPajamaStackExchange


text:
Q: calling remove(int) method for an arraylist removes the item from all similar arraylists Okey, I'm not a professional programmer so my question might sound silly.
I have this code:
ArrayList<Integer> list1 = new ArrayList<Integer>();
list1 = list2;

Please take note that list2 has three items inside [1, 2, 4]. So now, list1 has the same items inside.
But when I call remove(index) method. It removes that item from both ArrayLists.
This is my complete code:
ArrayList<Integer> list1 = new ArrayList<Integer>();
list1 = list2;
for (int i = 0; i < list1.size(); i++) {
    if (list1.get(i) == practiceId) {
        list1.remove(i);
    }
}

The purpose I'm doing this is to solve a problem which has other solutions. I'm asking this question just because I'm curious and would like to know why this happens? And how would one remove an item without removing from both ArrayLists?
Also, I have some ideas why this is happening. When I tried debugging the code step-by-step, it shows that the both ArrayLists have the same id. So I thought this might be the cause of the problem. If this is true, then is there a way to make a new ArrayList and put all items inside other ArrayList in the new one without having to add all items one by one?

A: So when you set those two lists equal to each other I don't think you are doing what you think you're doing.  That sounded funny.  When you do it the way that you have above you are actually setting the memory address of list1 to the same as list2.  So now that they both point to the same place in memory when you remove it will remove from both lists.
Make sense??

A: It is because ArrayList stores Objects and you are saying list1 = list2 which sets their reference the same, what you need to do is create another ArrayList called list2, so that their values but not their reference is the same, you can do this by.
list2.equals(list1);

A: when you are doing list1 = list2it is eventually making both object same., and while trying to delete items from one it is in terms deleting from both as both objects have same instance value.
if you want to copy items you can do as follows.
ArrayList list1 = new ArrayList();
for (int i = 0; i < list2.size(); i++) {

        list1.add(list2.get(i));

}

the above code will copy list items from list2 to list1 and would be  different objects now.
Now you can do operations on one list and it wont affect another list

A: Dont use list = list2 for copying content of arraylists. it just add a refrence to the original arraylist. For copying the content of arraylist use this:
    list1.addAll(list2);

A: Pretty much all answers mentioned are helpful.
But as I mentioned before, I don't want to add elements one by one. There was an answer which was:
ArrayList<Integer> list1 = new ArrayList<Integer>(list2);

Which was unfortunately deleted by poster. Anyways, this is exactly what I'm looking for. Clean, one line and no need for extra methods or loops or anything.
Thanks for your answers :)

A: I hope this help will you
ArrayList<Integer> list1 = new ArrayList<Integer>();
ArrayList<Integer> list2 = new ArrayList<Integer>();//added 1, 2, 4
list1 = (ArrayList<Integer>) list2.clone();

A: When you do list2 = list1, the same reference is copied to the the second list, so whatever changes you do in one list, same will happen in other. To successfully do this, you should use this :-
        list2.addAll(1);

Now, if you will remove from list2, only items will be removed from list2 and not list1


text:
Q: Morris Line graph deformed after being hidden I have setup a morris line graph in my page like this:
var chart = new Morris.Line({
        element: 'myfirstchart',

        xkey: 'Date',

        ykeys: ['Sales'],

        labels: ['Sales'],
        resize: true,
        redraw: true,
        xLabels: 'day',
        parseTime: false
    });

And upon displaying the results after a post (in done method of jquery's post) I do this:
 chart.setData(data.lineData);
 chart.redraw();
 $(window).trigger("resize");

But the graph looks ugly and deformed completely like this:

The graph itselef is hidden in a div which is then displayed upon showing the results...
What could be the problem here?

A: Yes, this is a well known weakness of Morris Chart. You can go through by resizing the svg element with its parent element width
var t_w = $('#myfirstchart').parent().width();
$('#myfirstchart svg').width(t_w);
chart.redraw();


text:
Q: Starting two instances of jetty with different maven (war)modules I have a multi-module maven project, of which two modules generate wars. Both serverModules depend on persistenceModule. Each server module is configured with its own jetty-maven-plugin which bring the server up during pre-integration-test phase and stops it during post-integration-test. Each serer module has its own jetty configurations- login services & ports.
    --trunk
          |_serverModuleA
          |_serverModuleB
          |_persistenceModule

serverModuleB has some integration tests, which invoke services provided in serverModuleA. So, it is required that serverModuleA is up and running while integration tests in serverModuleB are executed.
I cannot bring up two jetty instances, from serverModuleB, as jetty-maven-plugin does not support it.
Appreciate any help.


text:
Q: Access to DOM using node.js i want to access to html file and get an element by id using node.js, this is my html file :
<!DOCTYPE html>

<meta charset="UTF-8">
<title>Diagram </title>

I want to do get  document.getElementById("GraphImage").src but with node.js.
I've found that I can use cheerio or jsdom to acces the DOM with node.js, so I've tried this code with cheerio:
var cheerio = require('cheerio'),
    $ = cheerio.load('file.html');

But I didn't founnd the instruction that allow me to get the image.src from the html file, like this instruction: document.getElementById("GraphImage").src

A: cheerio.load() accepts a string as the argument. By setting: cheerio.load('file.html') cheerio will try to implement DOM from the string file.html. Obviously, that is not what you want.
You should get the html data from your file first, then pass it to the cheerio. Also as @Quentin metioned, cheerio is a cut down implementation of jQuery, so you should use jQuery selectors to get a ceratin element. For your particular case it would be: $("#GraphImage"). Here is how your code should look like:
 var cheerio = require('cheerio'),
     $ = cheerio.load('file.html'),
     fs = require('fs');
 fs.readFile('./index.html', function (err, html) {
    if (err) {
        throw err;
    } else {
        $ = cheerio.load(html.toString());
        console.log($('#GraphImage').attr('src'));
    }

EDIT:
Also, in the html file that you have provided, you are appending some objects to the DOM with the help of javascript. If you want to access them on the server, the javascript should be interpreted there. You can use something like phantomjs to achieve it, but things get much more complicated.

A: It looks like your mixing client side and server side javascript.
but to answer your question you can access the src in the following way:
 var src = $('#GraphImage').attr("src");

make sure you first load your html file with fs
// EDIT: Your are getting 'undefined' because the img tag is dynamically generated and not present at the moment you are loading the file with node on the server. That's what I meant your are mixing client code with server side code.
You might want to grab the diagramContainer $('#diagramContainer') and add an image tag inside it and set the source. $('#diagramContainer').prepend('')
If you have a path you can set it directly if you generate the png on the server an have a binary stream things can get more tricky.


text:
Q: LLVM HOW TO USE ALREADY COMPILED FILE? I have .so file already created of an LLVM pass.
Also I have the following script :
INPUT=${1}
LLVM_HOME=~/Workspace
if [ $(uname -s) == "Darwin" ]; then
    SHARED_LIB_EXT=dylib;
else
    SHARED_LIB_EXT=so;
fi

clang -emit-llvm support/${INPUT}.c -c -o support/${INPUT}.bc && \

    ${LLVM_HOME}/llvm/Debug+Asserts/bin/opt -load ../../../Debug+Asserts/lib/CS201PathProfiling.${SHARED_LIB_EXT} -pathProfiling support/${INPUT}.bc -S -o support/${INPUT}.ll && \
    ${LLVM_HOME}/llvm/Debug+Asserts/bin/llvm-as support/${INPUT}.ll -o support/${INPUT}.bb.bc && \
    ${LLVM_HOME}/llvm/Debug+Asserts/bin/lli support/${INPUT}.bb.bc

Since I already have my .so file I do not want the script to recompile my program as I already have the complied .so file.
Can anyone tell what changes could be made in the script so that it would work for my case.
Thank you

A: Note: this question is not really LLVM-specific. You're asking how to make sure one file is newer than another (the source is newer than the .so built from it) and only then re-do some operation.
Bash lets you implement this with operators like -nt [see this question for one example].
That said, a better approach is to use a proper build system, such as make.


text:
Q: Copy table and paste it in other sheet I need to copy the only table on one worksheet (PRODUCT), then paste it to another sheet (TERMSHEET). I've third recording, searching in the internet but cannot find anything that works. The table is in range (A60:C66) and need to paste it in range (A108:B116).

A: here is the solution:
sheets("PRODUCT").range("A60:C66").copy sheets("TERMSHEET").range("A108")


text:
Q: How to hide TclTk window in R while it is being drawn TclTk is working fine in R, it's just that I can see the widgets being placed on the window as it is being built. Is there a way to hide the window, and only show it once it is built? Paste the following into R and you'll see the window filling up. That's what I don't want user to see (if possible). Thanks.
require(tcltk)
dlg = tktoplevel()
# command to hide window ?
for (i in 1:10) {
    l = list()
    for (i in 1:20) l[[i]]=tkbutton(dlg,text="SO")
    do.call(tkgrid,l)
}
# command to show window now it is built ?
tkwait.window(dlg)
tkdestroy(dlg)

A: I have the following pattern in gWidgetstcltk:
library(tcltk)
tclServiceMode(FALSE)
win <- tktoplevel()
tkwm.state(win,"withdrawn")
tclServiceMode(TRUE)

## ... do your thing then:
tkwm.state(win,"normal")

A: You can just wrap the whole thing in curly braces. That's worked for me so far.
Something like:
{ # Begin building window
  (code)
} # End building window


text:
Q: How to save canvas as an image in j2me? I want to save the current state of the canvas as an image as I will use it in the next pointerevent. If I use repaint it will clear the canvas and I can't get the previous state of canvas. So, I want to save it as image and then iterate it over and over so that finally I can make out what I want.
 The final question is how to save the canvas as image ?.
 Or Is there any possibility of converting the Graphics object to a byte array ?

A: You can't save the canvas as an image.
You have to create an image first, and then you can paint onto that image.
Basically that means that your midlet will be doing more work, since you first have to draw onto your image, and then you have to draw that image onto the canvas. But it's the only way you can do what you want.

A: Create an Image with same size (width and height) of the screen. When you want to save the canvas state call Canvas.paint passing the image Graphics.
class MyCanvas extends Canvas {
  private Image lastScreen;

  protected void sizeChanged(int w, int h) {
    if (lastScreen == null || w != lastScreen.getWidth()
        || h != lastScreen.getHeight) {
      lastScreen = Image.createImage(w, h);
    }
  }

  protected void paint(Graphics g) {
    // paint the whole screen
  }

  protected void pointerReleased(int x, int y) {
    paint(lastScreen.getGraphics());
  }
}


text:
Q: ServerSelectionTimeoutError when connecting to aws with pymongo I am attempting to connect to MongoDB hosted on an AWS instance with a key file. I am able to ssh into the instance and connect to the database with no issues. When I try to connect to the database from a remote location with pymongo I receive this error:
 ServerSelectionTimeoutError: SSL handshake failed: EOF occurred in violation of protocol
Port 27017 is open and the source is set to 0.0.0.0/0.
from pymongo import MongoClient

client = MongoClient('mongodb://ec2-123-45-678-910.compute-1.amazonaws.com',
                     27017,
                     ssl=True,
                     ssl_keyfile='/path_to/mykey.pem')

db = client.test
coll = db.foo
coll.insert_many(records)

ServerSelectionTimeoutError: SSL handshake failed: EOF occurred in violation of protocol (_ssl.c:645)

This question is nearly identical to mine, however the error is different and the solution posted there does not apply to my issue.
The address and key here have been changed, I have been going in circles on this for hours with no luck, any help would be appreciated.

A: This issue can cause because of following issue:

*

*version of pymongo (suggest to use 3.3.0, which worked for me)

*It can be a DNS issue, etc, in fact you could check for a DNS issue using:
telnet xx.xx.xx.xx port

*can be a firewall issue

*Can be an issue with ssl key. Try the following to test:
    import os

    import pymongo

    import ssl

    URL="url:port/db?ssl=true"

    client = pymongo.MongoClient(URL, ssl_cert_reqs=ssl.CERT_NONE)

    db = client.get_default_database()

    print db

    print db.collection_names()

A: I had the same problem (SSL handshake) with Pymongo module to connect to DocumentDB Azure (Data Base).
The error  :
ServerSelectionTimeoutError: SSL handshake failed: EOF occurred in violation of protocol (_ssl.c:590)
I was using pymongo==3.4.0
To resolve this :
Change the version of pymongo by installing the 3.3.0 version
pip install pymongo==3.3.0
Try:
import pymongo
pymongo.__version__

A: For me, the problem was that my Python setup only supported TLS 1.0 – not TLS 1.1 or above.
You can check it like this:
Python 3
> from urllib.request import urlopen
> urlopen('https://www.howsmyssl.com/a/check').read()

Python 2
> from urllib2 import urlopen
> urlopen('https://www.howsmyssl.com/a/check').read()

Check the output for the key tls_version. If it says TLS 1.0 and not TLS 1.1 or TLS 1.2 that could be the problem.
If you're using a virtualenv, be sure to run the command inside.
Solution: Install Python with a newer version of OpenSSL
In order support TLS 1.1 or above, you may need to install a newer version of OpenSSL, and install Python again afterwards. This should give you a Python that supports TLS 1.1.
The process depends on your operating system – here's a guide for OS X.
virtualenv users
For me, the Python outside of my virtualenv had TLS 1.2 support, so just I removed my old virtualenv, and created a new one with the same packages and then it worked. Easy peasy!
See also:

*

*The warning about TLS 1.0 in the Python 3 section in the PyMongo documenation. Although it's under the Python 3 section it also applies to Python 2

A: I had the same issue and talked for 30 minutes with the Mongo Atlas support which deployed over AWS. I run the next terminal command:
/Applications/Python\ 3.6/Install\ Certificates.command

A: I had the same issue. Please check if you are connected via VPN. when I disconnected it resolved my problem.


text:
Q: Preload typekit font css Does anyone know how to preload typekit font? Right now my computed font is Ariel and I get the error:
The resource https://use.typekit.net/dwg7avv.css was preloaded using link preload but not used within a few seconds from the window's load event. Please make sure it has an appropriate as value and it is preloaded intentionally.
The font works if I do a normal import.
<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8">
  <title>font</title>

  <style>
    body {
      font-family: proxima-nova, sans-serif;
      font-style: normal;
      font-weight: 100;
    }
  </style>
  <link rel="preload" href="https://use.typekit.net/dwg7avv.css" as="style" crossorigin>
</head>

<body>
  This is my font.
</body>

</html>

A: Short answer, you have to load the stylesheet at the end of your head element.
For explanation why, you can check out the documentation from mozilla https://developer.mozilla.org/en-US/docs/Web/HTML/Preloading_content
So with your example it should be like:
<head>
  <link rel="preload" href="https://use.typekit.net/dwg7avv.css" as="style">
  <link rel="preload" href="main.js" as="script">
  ...
  <link rel="stylesheet" href="https://use.typekit.net/dwg7avv.css">
</head>

A: I've just faced exactly the same problem, and I did solve with this structure
<!-- https://use.typekit.net & https://p.typekit.net is the font file origin (Lighthouse required both links from Adobe) -->
    <!-- It may not have the same origin as the CSS file (https://use.typekit.net/pgd3inh.css) -->
    <link rel="preconnect" href="https://use.typekit.net" crossorigin />
    <link rel="preconnect" href="https://p.typekit.net" crossorigin />

    <!-- We use the full link to the CSS file in the rest of the tags -->
    <link rel="preload" as="style" href="https://use.typekit.net/dwg7avv.css" />

    <link rel="stylesheet" href="https://use.typekit.net/dwg7avv.css" media="print" onload="this.media='all'" />

    <noscript>
        <link rel="stylesheet" href="https://use.typekit.net/dwg7avv.css" />
    </noscript>

This article helps me to solve it and know why

A: It's a bug, I had the same problem and i'm now giving up:
https://bugs.chromium.org/p/chromium/issues/detail?id=593267
Funny is, the only reason I tried to use preload, was of the chrome lighthouse test that recommendet it to me.
And here the picture of it kinda preload but not actualy working!


text:
Q: Shortening the sentence to find a search value Searching for values that uses the same value
Example
SELECT Name, UnitPrice, Quantity, Color
FROM Product
WHERE Name Like '2' OR UnitPrice Like '2' OR Quantity LIKE '2' OR  Color LIKE '2'

is there a way to shorten the sentence so that i do not need to repeat Variable LIKE 'value'?

A: LIKE without wildcards is =
SELECT Name, UnitPrice, Quantity, Color
FROM Product
WHERE '2' IN (Name, UnitPrice, Quantity, Color)

This expands out to a series of OR conditions
Note that the string '2' will be CAST as needed after OR expansion
If you do require wild cards and LIKE, you'd have to use a series of OR statements.
Finally, this won't scale performance-wise. With good indexing, (eg one per column and other 2 as INCLUDE columns) then this would probably be better written as separate queries with UNION between them
Edit, for clarity
OP wants to use wildcards. Therefore my IN suggestion will not work. So you have to do this
WHERE
    Name Like '%2%' OR
    UnitPrice Like '%2%' OR
    Quantity LIKE '%2%' OR
    Color LIKE '%2%'

Because of the leading wildcard, there is no point adding indexes. So my text above about indexes+includes is irrelevant


text:
Q: why admin panel of django appears different in production version? first of all, I don't know whether it's only my issue or someone else have it too. my production version of django admin (which I use it in my website) looks different from what I see, when I lunch a project on my personal computer.
you can see the difference In two pictures :
local version (127.0.0.1:8000)
production version (mywebsite)
something that I want to mention:
My settings.py :
STATIC_ROOT = '/home/django/django_project/django_project/static'
STATIC_URL = '/static/'

About the path:
root@myuser:/home/django/django_project/django_project/static# ls
admin  css  fa  fonts  img  js

Console log when running admin panel shows that static files related to admin panel like jquery.js does not rendering properly.
mywebsite.com/:12 GET https://mywebsite.com/static/admin/js/vendor/jquery/jquery.js net::ERR_ABORTED
mywebsite.com/:18 GET https://mywebsite.com/static/admin/js/vendor/xregexp/xregexp.js net::ERR_ABORTED
mywebsite.com/:199 GET https://mywebsite.com/static/admin/js/change_form.js net::ERR_ABORTED
mywebsite.com/:208 GET https://mywebsite.com/static/admin/js/prepopulate_init.js net::ERR_ABORTED
mywebsite.com/:12 GET https://mywebsite.com/static/admin/js/vendor/jquery/jquery.js 404 (Not Found)
jquery.init.js:7 Uncaught ReferenceError: jQuery is not defined
    at jquery.init.js:7
(anonymous) @ jquery.init.js:7
actions.js:4 Uncaught TypeError: Cannot read property 'fn' of undefined
    at actions.js:4
    at actions.js:144
(anonymous) @ actions.js:4
(anonymous) @ actions.js:144
prepopulate.js:2 Uncaught TypeError: Cannot read property 'fn' of undefined
    at prepopulate.js:2
    at prepopulate.js:39
(anonymous) @ prepopulate.js:2
(anonymous) @ prepopulate.js:39
mywebsite.com/:18 GET https://mywebsite.com/static/admin/js/vendor/xregexp/xregexp.js net::ERR_ABORTED
mywebsite.com/:200 GET https://mywebsite.com/static/admin/js/change_form.js net::ERR_ABORTED
mywebsite.com/:209 GET https://mywebsite.com/static/admin/js/prepopulate_init.js 404 (Not Found)
DateTimeShortcuts.js:277 Uncaught TypeError: django.jQuery is not a function
    at Object.addCalendar (DateTimeShortcuts.js:277)
    at init (DateTimeShortcuts.js:45)
addCalendar @ DateTimeShortcuts.js:277
init @ DateTimeShortcuts.js:45
/missing-admin-media-prefix/img/icon_calendar.gif:1 GET https://mywebsite.com/missing-admin-media-prefix/img/icon_calendar.gif 404 (Not Found)
Image (async)
HTMLElement.appendChild @ VM155:323
addCalendar @ DateTimeShortcuts.js:224
init @ DateTimeShortcuts.js:45

web server is nginx, config file:
location /static {
    alias /home/django/django_project/django_project/static;
}

# Proxy the static assests for the Django Admin panel
location /static/admin {
   alias /usr/lib/python2.7/dist-packages/django/contrib/admin/static/admin/;
}

I also changed the second address to :
alias /home/django/django_project/django_project/static/admin;

but still not working. (I use digital ocean as hosting)

*

*I did not edited the admin template

*I used collectstatic command in production version

*Checked it with different browsers

*Version of django is 1.11 in both server and local

So do I have to do something else after doing collectstatic ?

A: The collectstatic command copies static files from admin site and other packages to your static directory so you don't need the second location block shown in your question.
Also change
location /static {
    alias /home/django/django_project/django_project/static;
}

For
location /static/ {
    root /home/django/django_project/django_project;
}

A: Yes, now you need to set permissions for your static/admin directory which has created after collectstatic command.In your root directory of the project (On production), run the following command.
sudo chown -R user:www-data static
Where user = Your current user of the system.


text:
Q: Customizing asp:HyperLinkField I am using the standard GridView.
I have this part working so far.
    <asp:HyperLinkField ShowHeader="true" DataTextField="id" DataNavigateUrlFields="id"
 DataNavigateUrlFormatString="edit.aspx?id={0}"
DataTextFormatString="Edit" />

However each page needs a 'number' and a 'userid' parameter.
I cannot figure out how to add these parameters to the above HyperLinkField.
  <asp:HyperLinkField ShowHeader="true" DataTextField="id"
   DataNavigateUrlFields="id"DataNavigateUrlFormatString="edit.aspx?id={0}
   &number=Request.QueryString["number"]&
   userid=Request.QueryString["userid"]" DataTextFormatString="Edit" />

Can someone tell me what I am missing to be able to add this custom URL to my HyperLinkField?

A: Try using a templatefield, something like (untested):
 <asp:TemplateField HeaderText="Edit">
  <ItemTemplate>
   <a href='<%# "edit.aspx?id="+Eval("id") + "&number=" +Request.QueryString["number"]+"&userid=" +Request.QueryString["userid"]  %>'>Edit
  </ItemTemplate>
 </asp:TemplateField>


text:
Q: Error while trying to save list of plots using marrangeGrob and ggsave I'm getting error when trying to save list of lists of plots in one pdf this way:
ggplot2::ggsave("plots.pdf",
         gridExtra::marrangeGrob(grobs = unlist(plots,recursive = F), nrow=2, ncol=1),
         device = "pdf",units = "in",width = 8,height = 13)

where "plots" is a list of lists of 2 plots.
I hope to to plot each inner list of plots in one page.
I'm using ggsave because I didn't find a solution where I can control the width and height of the plots.
> length(plots)
[1] 13
> length(plots[[1]])
[1] 2

This is the error:

Error: Can't add theme to a theme object.

plotting code:
ggplot()+
      ggplot2::geom_col(data = (merged_spec[[2]] %>%
                                  dplyr::filter(is.na(ion))),
                        aes(x=mz,y=intensity_perc,color=col)) +

      ggplot2::geom_pointrange(data = (merged_spec[[2]] %>%
                                         dplyr::filter(!is.na(ion))),
                               aes(x=mz,y=intensity_perc,ymin=0,ymax=intensity_perc,color=col),
                               fatten = 3)+

      ggrepel::geom_text_repel(data = merged_spec[[2]],
                               aes(x=mz,y=intensity_perc,color=col,label=ion),
                               show.legend = F,
                               size=3.5,nudge_y = -0.1,
                               #arrow = arrow(type = "closed",ends = "first",length = unit(2,"mm")),
                               segment.linetype = 3)+

      ggplot2::geom_col(data = (merged_spec[[1]] %>%
                                  dplyr::filter(is.na(ion))),
                        aes(x=mz,y=intensity_perc,color=col))+

      ggplot2::geom_pointrange(data = (merged_spec[[1]] %>%
                                         dplyr::filter(!is.na(ion))),
                               aes(x=mz,y=intensity_perc,ymin=0,ymax=intensity_perc,color=col), fatten = 3)+

      ggrepel::geom_text_repel(data = (merged_spec[[1]] %>%
                                         dplyr::filter(!is.na(ion))),
                               aes(x=mz,y=intensity_perc,color=col,label=ion),
                               show.legend = F,size=3.5,nudge_y = 0.1,
                               #arrow = arrow(angle = 45,type = "closed",ends = "first",length = unit(2,"mm")),
                               segment.linetype = 3)+

      ggplot2::geom_hline(yintercept = 0)+

      #xlim(min(rbind(syn_ions,endo_ions)$mz)-5,max(rbind(syn_ions,endo_ions)$mz)+5)+
      ggplot2::scale_color_manual(values=c(colorb,colnoise,colory))+
      #ggplot2::scale_x_continuous(breaks = seq(100,1200,50))+
      ggplot2::scale_y_continuous(breaks = seq(-1,1,0.2), expand = expansion(mult = 0.09))+
      ggplot2::scale_x_continuous(limits = c(min(rbind(syn_ions,endo_ions)$mz)-5,max(rbind(syn_ions,endo_ions)$mz)+5),breaks = seq(100,1200,100))+

      ggplot2::labs(x= "m/z",y="Intensity (norm)",title = MS2Peptide,
                    subtitle = paste(method,"=",abs(round(corr,4))))+

      ggplot2::theme_minimal(base_size = 18) +
      ggplot2::theme(panel.grid = element_blank(),
                     panel.border = element_rect(fill=NA,size = 0.001),
                     axis.ticks=element_line(size = 0.001))+
      ggplot2::guides(color=F,label=F,fill=F)+

      # annotate(geom = "text",label="Endogenous", x = ((max.mz - min.mz)/2)-200,y=1.4,size=5)+
      # annotate(geom = "text",label="Synthetic",x = ((max.mz - min.mz)/2)-200,y=-1.4,size=5)+
      ggplot2::annotate(geom = "text",label="Endogenous", x = -Inf, y=Inf, hjust = -0.4, vjust =  4.7,size=5)+
      ggplot2::annotate(geom = "text",label="Synthetic",x = -Inf, y=-Inf, hjust = -0.8, vjust =  -3.9,size=5)+

      ggplot2::annotate(geom = "text",label=pepAnno,x = seq(((max.mz - min.mz)/2)+100,((max.mz - min.mz)/2)+450,15)[1:length(pepAnno)],y=-1.4,size=5)+
      ggplot2::annotate(geom = "text",label=pepAnno,x = seq(((max.mz - min.mz)/2)+100,((max.mz - min.mz)/2)+450,15)[1:length(pepAnno)],y=1.4,size=5)+
      # Synthetic anno
      ggplot2::geom_segment(data = annotations[[1]],
                            aes(x=startx,y=starty,
                                xend = endx, yend = endy,
                                color = col))+
      ggplot2::annotate(geom = "text",label = annotations[[1]]$label,
                        x = annotations[[1]]$label_posx,y = annotations[[1]]$label_posy,
                        color = colory,size = 2.5)+

      ggplot2::geom_segment(data = annotations[[2]],
                            aes(x=startx,y=starty,
                                xend = endx, yend = endy, color = col))+

      ggplot2::geom_segment(data = annotations[[3]],
                            aes(x=startx,y=starty,
                                xend = endx, yend = endy, color = col))+
      ggplot2::annotate(geom = "text",label = annotations[[3]]$label,
                        x = annotations[[3]]$label_posx,y = annotations[[3]]$label_posy,
                        color = colorb,size = 2.5)+

      ggplot2::geom_segment(data = annotations[[4]],
                            aes(x=startx,y=starty,
                                xend = endx, yend = endy, color = col))+
      # Endo anno
      ggplot2::geom_segment(data = annotations[[5]],
                            aes(x=startx,y=starty,
                                xend = endx, yend = endy, color = col))+
      ggplot2::annotate(geom = "text",label = annotations[[5]]$label,
                        x = annotations[[5]]$label_posx,y = annotations[[5]]$label_posy,
                        color = colory,size = 2.5)+

      ggplot2::geom_segment(data = annotations[[6]],
                            aes(x=startx,y=starty,
                                xend = endx, yend = endy, color = col))+
      ggplot2::geom_segment(data = annotations[[7]],
                            aes(x=startx,y=starty,
                                xend = endx, yend = endy, color = col))+
      ggplot2::annotate(geom = "text",label = annotations[[7]]$label,
                        x = annotations[[7]]$label_posx,y = annotations[[7]]$label_posy,
                        color = colorb,size = 2.5)+

      ggplot2::geom_segment(data = annotations[[8]],
                            aes(x=startx,y=starty,
                                xend = endx, yend = endy, color = col))

Any help will be greatly appreciated!
Thanks!

A: I found a solution (sort of):
Apparently I have installed devs version of ggplot2 (3.3.2.#####). Downgrading it to version 3.3.2 solved the error.


text:
Q: Uniform Convergence Weierstrass Hi could you help me with the following:
If I have a function $g \in C^2(0,R)$ with $|g''(x)| \le M$, i.e. its second derivative is bounded except a finite number of points where at those irregularity points none of the assumptions mentioned above holds can you give me a sequence of functions $f_n$ with $f_n^\prime \longrightarrow g'$  and $f_n \longrightarrow g$ uniformly and $|f_n^{\prime\prime}(x)| \le M$?
I think about polynomials but can not justify that they have all the requirements??
Thanks a lot!!

A: Think of the following functions:
$$f_n(x) = \left\{
\begin{matrix}
g_n(x), \mbox{if } x \in I, \\
l_k, \mbox{ if } x \notin I.
\end{matrix}
\right.$$
Where $I \subset \left[0,2 \right]$ denotes the subset in which the conditions hold, and $l_k = \lim_{x \to x_k}g_n(x)$, being $x_k$ the points outside $I$. Since the $g_n$ are continuous almost for every point, their limits on those irregular points still exist, so you can use them to make the $f_n$ continuous.
Now, the $f_n$ are continuous in a compact set, so they are bounded and they are obviously $\mathcal{C}^2$. Plus, $\left| f''_n (x) \right| \leq \left| g''(x) \right| \leq M$, so I guess it will do the trick.
I hope this helps.


text:
Q: Spring mongodb, save document twice: in its own collection and as embedded of other I have two collections: Foo and Bar. This last one has a relationship hasToMany with Foo. I would like save Foo in one collection and Bar in other but with embedded Foo documents instead of just use a DBRef.
@Document
Foo {
   String title;
}

@Document
Bar {
   String title;
   List<Foo> foos;
}

Expected collections:
Foo:
[{ObjectId("5ddad4b73679ca0ecbf3cd4b"), title: "Hello Foo 1", _class: com.play.spring.mongo.Foo},
{ObjectId("34acd4b73679ca0ecbf3cd4b"), title: "Hello Foo 2", _class: com.play.spring.mongo.Foo}]

Bar:
[{ObjectId("asdd4b73679ca0ecbf3cd4b"),
title: "Hello Bar 1"
foos: [
{ObjectId("5ddad4b73679ca0ecbf3cd4b"), title: "Hello Foo 1", _class: com.play.spring.mongo.Foo},
{ObjectId("34acd4b73679ca0ecbf3cd4b"), title: "Hello Foo 2", _class: com.play.spring.mongo.Foo}
],
_class: com.play.spring.mongo.Bar}]

But when I save the Bar document I get this error:
java.lang.IllegalArgumentException: Target bean of type java.util.ArrayList is not of type of the persistent entity (com.play.spring.mongo.Foo)!: java.util.ArrayList
If I remove @Document from Foo, embedded document work on Bar and if @DBRef is added to foos in Bar, then it creates references from Bar to Foo. But with the two annotations @Document it does not work.

A: I created an abstract class Roo and I did Foo inherit from it. In addition I changed Bar so that it contains a list of Roo.
@JsonDeserialize(as=Exercise.class)
abstract class Roo {
}

@Document
Foo extends Roo {
   String title;
}

@Document
Bar {
   String title;
   List<Roo> foos;
}


text:
Q: Issue with ReactRefreshWebpackPlugin and WebpackPluginServe - changes visible only after page refresh I have issue, I always worked with webpack-dev-server and react-hot-dom, but after webpack5 it stopped working.
Unfortunetly after running webpack--watch, react not "live refresh" with above configuration, but after page refresh - all changes are visible. Is that problem with ReactRefreshWebpackPlugin which is not production ready? Or maybe because of wsl2?
Webpack.config:
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ReactRefreshWebpackPlugin = require('@pmmmwh/react-refresh-webpack-plugin');
const { WebpackPluginServe: ServePlugin } = require('webpack-plugin-serve');

const outputPath = path.resolve(__dirname, 'build');

module.exports = {
  mode: 'development',
  watch: true,
  entry: {
    main: ['webpack-plugin-serve/client', './src/index.tsx'],
  },
  output: {
    path: outputPath,
    filename: 'bundle.[contenthash].js',
    publicPath: '/',
  },
  module: {
    rules: [
      {
        test: /\.(j|t)sx?$/,
        include: path.join(__dirname, 'src'),
        use: "babel-loader",
      }, {
        test: /\.scss$/,
        use: [
          'style-loader',
          'css-loader',
          'sass-loader'
        ]
      }
    ]
  },
  plugins: [
    new ServePlugin({
      static: outputPath,
      status: true,
    }),
    new ReactRefreshWebpackPlugin({
      overlay: {
        sockIntegration: 'wps',
      },
    }),
    new HtmlWebpackPlugin({
      title: "Pixelart",
      template: './index.html',
    })
  ],
  resolve: {
    extensions: ['.ts', '.tsx', '.js', '.jsx'],
  }
};

babel.config
module.exports = (api) => {
    // This caches the Babel config
    api.cache.using(() => process.env.NODE_ENV);
    return {
        presets: ['@babel/preset-env', '@babel/preset-react', '@babel/preset-typescript'],
        // Applies the react-refresh Babel plugin on non-production modes only
        plugins: ['react-refresh/babel']
    };
};


text:
Q: Fiware IOTagent JSON creates a big log file The IOTAgent JSON is creating a very big log file, with the messages sent to the Orion Context Broker. Is it possible to configure in this nodejs process some rules for log management, maximun size, rotation, compression, log level messages. How to do ?
Many thanks in advance for your support
Best Regards

A: I don't know the exact cause of the problem, but you could consider the following hints:

*

*Use ERROR or WARNING (*) as logLevel field in config.js. Levels INFO or DEBUG are very verbose.

*You can use logrotate to rotate logs. Log rotate is a general purpose tool which many documentation around, so it should be easy to master (with time to learn, of course ;). The following configuration files in the IOTA-JSON repo may help:

*

*logrotate configuration

*crontab configuration to invoke logrotate
(*) I don't remember if the right config token is WARNING or WARN (or both!), you would need to test, sorry...


text:
Q: How to filter word permutations to only find semantically correct ngrams? (Python 3, NLTK) I want to create a number of permutations from a list of 200 words -- this obviously creates a problem because this leads to some ridiculously gigantic number of possible permutations (up to 5 words in a phrase).  In order to effectively limit this number I have a two pronged attack:

*

*Pass the words through a POS filter so that only linguistically sound phrases are created and

*filter by those permutations that are actual ngrams -- i.e. have a high PMI / likelihood score.

The second part of this concept has me wondering -- I know that NLTK offers the ability to find ngrams but every example I have seen analyzes a corpus, which makes sense because a freqdist is needed.  However, is it possible to find the PMI of a word permutation?
Would it be possible to find the PMI score of my word permutations BASED on the common collocations found within a custom Corpus? Can it be done manually?
For example, while the permutation (the verbose tea) is linguistically sound, it is not a contextually good permutation.
I know the code to find common collocations within a block of text/corpus but this is a very unique problem which I was hoping someone could give some advice.  At the very least, help me wrap my head around this!
Example
**KW**
 Ball
 Bat
 Pinch
 Home
 Run
 Base
 Hitter
 Pitcher
 Call
 etc...

MORE BACKGROUND:
Now, there are a number of permutations that can be made from this list, but only a handful that would actually make sense.  Passing this list through a POS filter allows me to create keywords that make linguistic sense -- but not those that are semantically correct i.e. "Call Ball Hitter".  This is my struggle, to somehow create semantically correct permutations based on some sort of scoring criteria like a PMI.  Now my idea was to scrape a website, i.e. http://en.wikipedia.org/wiki/Baseball, find common ngrams within it, and then somehow judge the relative semantic strength of a keyword permutation based on that corpus.  But I am struggling to conceptualize this and am unsure if it is even possible.  But Really, I  would love to hear any other ideas about how to efficiently find ngram permutations!  The exercise here boils down to efficiently eliminating nonsensical permutations without having to manually categorize/score everything!

A: Just thinking out loud here - the Google Books NGram Viewer has scraped its corpus and made public the list of all [1,2,3,4,5]-grams that appeared more than 40 times, and their frequency counts. So you could take each ngram that you generate and look up its frequency in the Google ngram database. Ngrams with a higher count are more likely to be semantically sound.
... Downside is that downloading Google's entire ngram dataset is like 1 TB and I don't know if they have an api for it.
EDIt:
I would be shocked if there wasn't an api for this. Also Google doesn't seem to be the only game in town, a quick search turned up:

*

*Microsoft Web N-gram Services

*www.ngrams.info

*www.wordfrequency.info

A: I figured out my own answer with what I think is a pretty nifty solution!  It is based on this article:  http://research.microsoft.com/en-us/um/people/jfgao/paper/webngram.sigirws.v2.pdf.  The idea here is to NOT create a bunch of random garbage permutations and then sift through them to find the one semantically correct one.  The idea is to ONLY create semantically correct permutations in the first place.  This can be done by creating sentences in stages according to the basic principle of n-1, or the idea that a word is only semantically dependent on the preceeding word.
So the plan is to find all pairs of bigrams within a relevant corpus and their frequency.  The higher the frequency, the more likely that expression is semantically correct.  So say you have a list like this with bigrams that appear 10 times each in the corpus
The man
a plan
in Panama
Panama City
Man Who
Who is
is awesome

From there you construct sentences within STAGES according to N-1.  So you take a starting keyword from your original list.  From there, find a bigram in your second list that starts with that same word followed by another word and append them together.  So for example take the word 'THE' from your original list and after looking through the above corpus, you should now have this as a phrase 'THE THE MAN'.  Rinse and repeat with that phrase: look for a bigram that follows the n-1 principle and now find a bigram that starts with 'man'.  You now have 'THE THE MAN MAN WHO'.  Rinse and repeat!  This should create phrases that are semantically in the right order  (obviously you will remove duplicates at the end from the sentence).
What do you guys think?

A: You are not revealing your POS list, but unless your keyword list is much more complicated than the fragment you are showing us, this seems to be resolvable to just "find the longest sequences of words on the list".  The only way to be sure a phrase is legit is that it occurs in the input corpus, so the PMI calculation is a red herring.  Maybe even the POS filtering is unnecessary.
words='Ball|Bat|Pinch|Home|Run|Base|Hitter|Pitcher|Call'
curl -s 'http://en.wikipedia.org/wiki/Baseball' |
grep -Eio "\<($words)( +($words))+\>"

(I tried with grep -w but this didn't work properly with grep -o for me on OSX, so I added the \<...\> word boundaries instead.)
The output for this particular URL and partial keyword list is the following (filtered through sort -u | uniq -c | sort -rn):
  18 home run
   2 base ball
   1 pinch hitter

(This is simple enough that I didn't bother writing a Python script. It could easily be done with Requests.)
In the more general case, a sentence like "the ball the pitcher threw was a spitball" contains fragments straddling tree boundaries which you would like to filter out (like "*the ball the pitcher" if you add "the" to your word list) and then you do need some linguistics (or statistics...) here.


text:
Q: Assigning İf Function to Columns in Excel with Python
I am making a workplace software that assigns personnel to production lines according to incoming orders and special situations, but I have a problem with extracting data from excel, I could not find how to put the "if" function in a column consisting of 0 and 1 in excel. I'm waiting for your help
While importing columns with pandas, I encountered N/A's in column shapes. I ignored this but I can't apply the if condition to these columns


text:
Q: Compare database value from laravel to a javascript value I have a simple seating chart that has a designated ip address. It is generated through  javascript. And I have a database that is occasionally being populated by ip address and computer name. I query the database using Laravel.
Routes.php
Route::get('seatplan', 'SeatplanController@seatplan');

Controller
public function seatplan()
{

$ipadd = Client::all();
return View::make('seatplan',['ipadd' => $ipadd]);

}

Blade
@foreach($ipadd as $ipadds)
    {{$ipadds->ipadd}}
    <br />
@endforeach

How can I compare them so that if  a new data is inserted in the database I can compare the ip address and display the computer name.
Here is my js
var cols = document.getElementsByClassName("col");
var seatNum = 1;
var n = "192.168.240.";

for (var i = cols.length - 1; i >= 0; i--) {
  if (i % 2 == 0) {
  for (var j = 0; j < cols[i].children.length; j++) {
    cols[i].children[j].innerHTML = n.concat(seatNum);
    seatNum++;
  }
} else {
  for (var j = cols[i].children.length - 1; j >= 0; j--) {
    cols[i].children[j].innerHTML = n.concat(seatNum);
    seatNum++;
   }
  }

}

http://codepen.io/anon/pen/eZNzoV
http://i.imgur.com/WNaVkX0.png?1

A: Your question is not very clear, but what I understand you are trying to do is to determine which seats are taken, correct?
If so, juste generate a JS variable from you PHP data. Instead of doing a foreach, do: <script>var takenSeats = <?php json_encode($ipadd) ?></script>.I don't know Laraval so I use plain PHP but the point is to use json_encode so that your PHP array will be rendered as a JS array and assigned to a global JS var.
Then update your JS to have (for example):
var text = n.concat(seatNum);
if (takenSeats.indexOf(ip) !== -1) {
  ip += ' taken';
}
cols[i].children[j].innerHTML = text;

As this code necessits the takenSeats variable to be initialised make sure to put the json_encode before this.
Here is a fork of your codepen illustrating this


text:
Q: Dash symbolic link to access external assets I am using Dash to create an app. As in the templated structure, there is an "assets" folder that can contain CSS, logos etc..
Now I want to add some other assets as well that are stored elsewhere in the file system. I know that there is the option to set the app.config['assets_external_path'] to wherever these assets are located. However, Dash then only looks ins this directory, and e.g. my CSS files and logo PNGs are not found anymore. To not mess up my file system and keep my git repo clean, I don't want to move the CSSs and PNGs to the external path.
So I tried to create a symbolic link (I am on Windows) in the assets folder within my Dash app code, but this doesn't seem to work somehow.
Here's my situation:
External assets path: C:\\Users\\John\\data\\ensemble
App assets path: C:\\Users\\John\\my_app\\assets
So, I have created a symbolic link named 'ensemble' in C:\\Users\\John\\my_app\\assets pointing to C:\\Users\\John\\data\\ensemble. Now I want to be able to access a data file from the "ensemble" directory like this when the app is running on localhost:
http://127.0.0.1:8050/assets/ensemble/data.geojson
but I get a 404 error. Is there something wrong or is there something worng in the way I tried it?


text:
Q: Did the Old Republic have better worker safety standards than the Empire? I'm obsessed with the liability Imperial installations seem to carry in terms of worker accidents.  (For instance, they build installations where you have insane drops, with no railings at all.  We saw this recently I think on Starkiller Base in The Force Awakens.)
Mustafar is especially concerning.  I recall a droid skimming on the actual lava on some sort of vehicle that offered scant protection.  I know droids aren't considered people, but I got the strong sense biological organisms are working with the same lack of safety measures. (I understand that the natives of Mustafar have thick, heat resistant skins, but that's not going to help all that much if you fall 1000 feet into a river of lava!)
It seems pretty clear that the Empire (and probably the Tech Union, which had possession of Mustafar previously) aren't concerned with working conditions, but:
Was the Old Republic any better than the Empire in terms of worker safety standards?

A: Quite the opposite.
If you consider that the Empire hasn't been in place very long and that most of the infrastructure dates to the days of the Old Republic. The second death star can be considered to be one of the few pieces of large infrastructure that was constructed entirely under Imperial control.
The two fight scenes between Luke and Vader have safety railings. The climax fight on the Death Star has lots of safety railings, banisters and otherwise. It's why:

 Vader has to lift the Emperor over the safety railing to throw him to his death.


text:
Q: No balloon tip appears when the script is run [reflection.assembly]::loadwithpartialname("System.Windows.Forms")
[reflection.assembly]::loadwithpartialname("System.Drawing")
# notify.icon type: Information, Warning or Error.
$notify = new-object system.windows.forms.notifyicon
$notify.icon = [System.Drawing.SystemIcons]::Information
$notify.visible = $true
$notify.showballoontip(10,"", "The CPU is hot.",[system.windows.forms.tooltipicon]::None)

When I run the above, only an icon appears in the notification area, but no balloon tip appears. What's wrong with the script? I am using Windows 10 version 1803.

A: I've never seen ShowBalloonTip used in that way. This should work:
[reflection.assembly]::loadwithpartialname("System.Windows.Forms")
[reflection.assembly]::loadwithpartialname("System.Drawing")
# notify.icon type: Information, Warning or Error.
$notify = new-object system.windows.forms.notifyicon
$notify.icon = [System.Drawing.SystemIcons]::Information
$notify.visible = $true
$notify.BalloonTipIcon = "Warning"
$notify.BalloonTipText = "The CPU is hot."
$notify.BalloonTipTitle = "Title"
$notify.ShowBalloonTip(1000)


text:
Q: Adding data from Mongo to GeoServer? I'm finishing my last degree on informatics but I'm having trouble getting Tiles/Layers.
I have a DB on MongoDB - with this Schema (GeoJSON)
db.stations.insert({
    "name": "station 1",
     "geometry": {
"coordinates": [
            50,60
       ],
         "type": "Point"
     }
 })
I'm trying to integrate with Geoserver to get WMS. I got the Mongo Plugin and I can use it to add a New Store.
After the Store. It shows empty. What should I do next? Or what am I doing wrong?

A: You can (as Daniel suggests) add the MongoDB extension to GeoServer which will allow you to view the data as a WMS or WMTS (tiles) in your OpenLayers app. You could also look at using the WFS-T standard to handle the updates via GeoServer and could then make use of any of the supported datastores to store your data.

A: You could try to create an index on your collection:
db.stations.createIndex({ geometry: "2dsphere" });

After this command I was able to find the collection in the layer list


text:
Q: MySQL throwing "execute command denied to user" when running stored procedure remotely I have a nodejs service which is trying to run a stored procedure on a mysql database but the call fails with execute command denied to user.
The same service can successfully execute simple SELECTs and return data with no problems.
If I connect to the mysql database using the mysql command line utility, and log in as the same user that the nodejs service is configured to use, then the stored procedure works fine.
Why does running the stored proc remotely fail, but running it locally work?
EDIT
Following the advice below, this is the result of running show grants whilst accessing mysql from the command line:

And this is the result when I run it through my node app:
{"Grants for myuser@%":"GRANT USAGE ON *.* TO `myuser`@`%` IDENTIFIED BY PASSWORD '*blahblahblahblahblahblah'"}

I don't understand why the GRANT SELECT, INSERT etc has gone since i thought using the % wildcard meant that it shouldnt care about which domain it thinks myuser is coming from.

A: Keep in mind that 'user'@'localhost' is a different user spec than 'user'@'%' or any other remote user. They are effectively two different users, and they can have different sets of privileges.
I suggest you connect as the user locally and run SHOW GRANTS;. Then connect remotely and do the same.
You need the EXECUTE privilege to execute procedures. I think that privilege will be missing when you connect as the user remotely.

Re your updated question:
The privileges shown, which only include USAGE, means that the user can login (i.e. authenticate) but does not have any privileges on anything. But the user identity 'myuser'@'%' is the same as the other case where several privileges are present, including EXECUTE.
I would try to verify that you are in fact connecting to the same instance of MySQL.
Do the following queries and check whether they all give the same result in your app's session and the interactive session:
SELECT @@hostname, @@port, @@socket;
SELECT @@server_uuid, @@server_id;
SELECT USER();
SELECT VERSION();
SHOW GLOBAL STATUS LIKE 'Uptime';

If they don't, then your node app is connecting to a different instance of MySQL Server. The uptime will be different, since it changes every second, but it should be consistent with the times between when you execute the query from each client.


text:
Q: MIPS 32-bit unsigned multiplication without using mult or div I have been working on a program does multiplication of two 32-bit unsigned integers without using the MIPS mult(multu) or div(divu) commands.
I want the output to look just like how the multu function would, as a 64-bit high word/low word combo.
I have been using a model where the multiplier is the right hand side of the product as so:
for (i=0; i<32; i++)
{
   if LSB(multiplier)==1
   {
       LH product += multiplicand;
   }
   right shift product-multiplier 1;
}

Currently in my code I am unsure if I am taking care of the possible carry-out bit from the 32-bit addition properly.
I am currently getting an output of "0 0" no matter what integer values I choose to operate on.
In my code I am calling the right most bit the LSB(low word), left most the MSB(high word).
My code:
.data

    promptStart:    .asciiz "This prrogram does AxB without using mult or div"
           getA:    .asciiz "Please enter the first number(multiplicand): "
           getB:    .asciiz "Please enter the second number(multiplier): "

          space:    .asciiz " "

         result:    .asciiz "The product, using my program is: "
         mipMult:   .asciiz "The product, using MIPs multu is: "

       endLine: .asciiz "\n"

.text

main:
    #"welcome" screen
    li  $v0,4           # code for print_string
    la  $a0,promptStart     # point $a0 to prompt string
    syscall             # print the prompt

    li  $v0,4           # code for print_string
    la  $a0,endLine     # point $a0 to prompt string
    syscall             # print the prompt

    #prompt for multiplicand
    li  $v0,4           # code for print_string
    la  $a0,getA        # point $a0 to prompt string
    syscall             # print the prompt

    #acquire multiplicand
    li  $v0,5           # code for read_int
    syscall             # get an int from user --> returned in $v0
    move    $s0,$v0         # move the resulting int to $s0

    move    $s4,$s0         #copy of multiplicand to use in multu

    #prompt for multiplier
    li  $v0,4           # code for print_string
    la  $a0,getB        # point $a0 to prompt string
    syscall             # print the prompt

    #acquire multiplier
    li  $v0,5           # code for read_int
    syscall             # get an int from user --> returned in $v0
    move    $s1,$v0         # move the resulting int to $s0

    move    $s5,$s1         #copy of multiplier to use in multu

    jal MyMult
    j   print

MyMult:

    #$s2 -> lw product, $s1 -> hw multiplier, $s0 -> multiplicand

    beq $s1, $0, done       # if multiplier=0--> mult gives 0
    beq $s0, $0, done

    move    $t0, $0         #initialize 'counter'= 31
    add $t0, $t0, 31

    move    $s2, $0         #initialize product = 0

    loopOut:
        beq $t0, $0, done   #loop check

        andi    $t1, $s1, 1 #Stores LSB(MSB?) of $s1 in $t1
        bne $t1, $0, loopIn #check if LSB is equal to 1
        srl $s1, $s1, 1
        srl $s2, $s2, 1 #right shift product & multiplier

        add $t0, $t0,-1 # counter = counter -1
        j   loopOut

    loopIn:
        addu    $s2, $s2, $s0   #Lw product($s2/$s1)+= multiplicand($s0)
        sltu    $t2, $s2, $s0   #catch carry-out(0 or 1) and stores in $t2

        srl $s1, $s1, 1
        srl $s2, $s2, 1 #right shift pro-plier..how to save LSB of $s2?

        #add carry-out $t2 to LSB of product $s2
        addu    $s2, $s2, $t0   #Is this right?

        addu    $t0, $t0,-1 # counter = counter -1
        j   loopOut

    done:
        jr $ra

print:
    # print result string
    li  $v0,4           # code for print_string
    la  $a0,result      # point $a0 to string
    syscall             # print the result string

    # print out the result
    li  $v0,1           # code for print_int
    move    $a0,$s2         # put result in $a0
    syscall             # print out result

    li  $v0,4           # code for print_string
    la  $a0,space       # point $a0 to string
    syscall             # print the result string

    li  $v0,1           # code for print_int
    move    $a0,$s1         # put result in $a0
    syscall             # print out result

    # print the line feed
    li  $v0,4           # code for print_string
    la  $a0,endLine     # point $a0 to string
    syscall             # print the linefeed

doMult:
#Do same computation using Mult
    multu   $s4, $s5
    mfhi    $t0
    mflo    $t1

    li  $v0,4           # code for print_string
    la  $a0,mipMult     # point $a0 to string
    syscall

    # print out the result
    li  $v0,1           # code for print_int
    move    $a0,$t0         # put high in $a0
    syscall             # print out result

    li  $v0,4           # code for print_string
    la  $a0,space       # point $a0 to string
    syscall             # print the result string

    # print out the result
    li  $v0,1           # code for print_int
    move    $a0,$t1         # put low in $a0
    syscall             # print out result

    # print the line feed
    li  $v0,4           # code for print_string
    la  $a0,endLine     # point $a0 to string
    syscall             # print the linefeed

    # All done, thank you!
    li  $v0,10          # code for exit
    syscall             # exit program

A: As far as I can tell, even your algorithm is broken. You should be shifting the multiplicand to the left (for the addition), and the factor to the right (for bit testing). The product should not be shifted. Also, the multiplicand needs to be extended to 64 bits, and you need a 64 bit shift that correctly transfers bits across the word boundary.
.data

    promptStart:    .asciiz "This program does AxB without using mult or div"
           getA:    .asciiz "Please enter the first number(multiplicand): "
           getB:    .asciiz "Please enter the second number(multiplier): "

          space:    .asciiz " "

         result:    .asciiz "The product, using my program is: "
         mipMult:   .asciiz "The product, using MIPs multu is: "

       endLine: .asciiz "\n"

.text

main:
    #"welcome" screen
    li  $v0,4           # code for print_string
    la  $a0,promptStart # point $a0 to prompt string
    syscall             # print the prompt

    li  $v0,4           # code for print_string
    la  $a0,endLine     # point $a0 to prompt string
    syscall             # print the prompt

    #prompt for multiplicand
    li  $v0,4           # code for print_string
    la  $a0,getA        # point $a0 to prompt string
    syscall             # print the prompt

    #acquire multiplicand
    li  $v0,5           # code for read_int
    syscall             # get an int from user --> returned in $v0
    move    $s0,$v0     # move the resulting int to $s0
    move    $s5,$s0     # copy of multiplicand to use in multu

    #prompt for multiplier
    li  $v0,4           # code for print_string
    la  $a0,getB        # point $a0 to prompt string
    syscall             # print the prompt

    #acquire multiplier
    li  $v0,5           # code for read_int
    syscall             # get an int from user --> returned in $v0
    move    $s1,$v0     # move the resulting int to $s0

    move    $s6,$s1     # copy of multiplier to use in multu

    jal MyMult
    j   print

MyMult:
    move $s3, $0        # lw product
    move $s4, $0        # hw product

    beq $s1, $0, done
    beq $s0, $0, done

    move $s2, $0        # extend multiplicand to 64 bits

loop:
    andi $t0, $s0, 1    # LSB(multiplier)
    beq $t0, $0, next   # skip if zero
    addu $s3, $s3, $s1  # lw(product) += lw(multiplicand)
    sltu $t0, $s3, $s1  # catch carry-out(0 or 1)
    addu $s4, $s4, $t0  # hw(product) += carry
    addu $s4, $s4, $s2  # hw(product) += hw(multiplicand)
next:
    # shift multiplicand left
    srl $t0, $s1, 31    # copy bit from lw to hw
    sll $s1, $s1, 1
    sll $s2, $s2, 1
    addu $s2, $s2, $t0

    srl $s0, $s0, 1     # shift multiplier right
    bne $s0, $0, loop

done:
    jr $ra

print:
    # print result string
    li  $v0,4           # code for print_string
    la  $a0,result      # point $a0 to string
    syscall             # print the result string

    # print out the result
    li  $v0,1           # code for print_int
    move    $a0,$s4     # put result in $a0
    syscall             # print out result

    li  $v0,4           # code for print_string
    la  $a0,space       # point $a0 to string
    syscall             # print the result string

    li  $v0,1           # code for print_int
    move    $a0,$s3     # put result in $a0
    syscall             # print out result

    # print the line feed
    li  $v0,4           # code for print_string
    la  $a0,endLine     # point $a0 to string
    syscall             # print the linefeed

doMult:
#Do same computation using Mult
    multu   $s5, $s6
    mfhi    $t0
    mflo    $t1

    li  $v0,4           # code for print_string
    la  $a0,mipMult     # point $a0 to string
    syscall

    # print out the result
    li  $v0,1           # code for print_int
    move    $a0,$t0         # put high in $a0
    syscall             # print out result

    li  $v0,4           # code for print_string
    la  $a0,space       # point $a0 to string
    syscall             # print the result string

    # print out the result
    li  $v0,1           # code for print_int
    move    $a0,$t1         # put low in $a0
    syscall             # print out result

    # print the line feed
    li  $v0,4           # code for print_string
    la  $a0,endLine     # point $a0 to string
    syscall             # print the linefeed

    # All done, thank you!
    li  $v0,10          # code for exit
    syscall             # exit program


text:
Q: Delphi MailMerge Word2010 new page command I am trying to update my membership software written in Delphi, to mailmerge in to Word2010.
I'm using
wrdApp := CreateOleObject('Word.Application');
wrdDoc := wrdApp.Documents.add();

then for each merge field name in a template I'm replacing it with the corresponding field value from a table.
I have successfully done this for single members thanks to a previous answer: MS Word 2010 mailmerge in Delphi 5
However I'm having trouble iterating this code for all members in the table. Ideally I need the template to appear on a new page in the same document with the next members details on.
Currently I can only overwrite the same document for each member, or create a new document each time.
Can anyone advise me how to either recreate the template on the next page, merge multiple documents in to the same one or suggest an alternative method.
many thanks

A: You're not actually creating a mailmerge.
Here's some code (see note below) that might help. It's using Delphi's TWordApplication component to handle the connection and provide the datatypes, but it should give you a direction to go in:
// Drop a TWordApplication (from the Servers palette page) on a new blank form,
// and change it's name to WordApp. No other property changes or components are
// used.

procedure TForm1.FormCreate(Sender: TObject);
var
  Doc: _Document;
  DBName: string;
  Pause, SQL, Connection, SaveChanges: OleVariant;
begin
  WordApp.Connect;
  Doc := WordApp.Documents.AddOld(EmptyParam, EmptyParam);
  WordApp.Visible := True;

  SetUpMergeDoc(Doc);
  DBName := 'YourDatabasePath\DatabaseName';
  Connection := 'YourADOorODBCConnectionString';
  SQL := 'SELECT * FROM customer';
  Doc.MailMerge.OpenDataSource(DBName, EmptyParam, EmptyParam, EmptyParam,
                               EmptyParam, EmptyParam, EmptyParam, EmptyParam,
                               EmptyParam, EmptyParam, EmptyParam, Connection,
                               SQL, EmptyParam, EmptyParam, EmptyParam);
  // Do the actual mailmerge.
  Pause := False;
  Doc.MailMerge.Destination := wdSendToNewDocument;
  Doc.MailMerge.Datasource.FirstRecord := wdDefaultFirstRecord;
  Doc.MailMerge.Datasource.LastRecord := integer(wdDefaultLastRecord);
  Doc.MailMerge.Execute(Pause);

  // Save the mailmerged document
  SaveChanges := wdDoNotSaveChanges;
  WordApp.Quit(SaveChanges, EmptyParam, EmptyParam);
  Doc := nil;
  WordApp := nil;
end;

procedure TForm1.SetUpMergeDoc(Doc: _Document);
var
  R: Range;
  Direction: OleVariant;
begin
  R := Doc.Range(EmptyParam, EmptyParam);

  Direction := wdCollapseEnd;
  R.InsertAfter('Dear ');
  R.Collapse(Direction);

  { Insert a field with the name of the datasource field }
  Doc.MailMerge.Fields.Add(R, 'Company');
  R := Doc.Range(EmptyParam, EmptyParam);
  R.Collapse(Direction);
  R.InsertParagraphAfter;
  R.InsertAfter('We have yet to receive payment for our invoice of ');
  R.Collapse(Direction);
  Doc.MailMerge.Fields.Add(R, 'LastInvoiceDate');
  R := Doc.Range(EmptyParam, EmptyParam);
  R.Collapse(Direction);
  R.InsertAfter('.');
  R.InsertParagraphAfter;
  R.InsertAfter('Cough up or we''ll send the boys round.');
  R.InsertParagraphAfter;
end;

NOTE: Much of this code was obtained from a downloaded example I got from the Word automation page of Deborah Pate's website. (Deborah was (and may still be) a member of TeamB.) I simply modified it to connect via TWordApplication and updated it to compile under Delphi XE.
As I said, it's using TWordApplication to make the connection to Word and expose the methods and types used. Everything else is done in the code itself.

A: It seems you are not really performing a mailmerge but fore of a search and replace. Is there a reason for this? Otherwise why not just set up a 'real' mailmerge which would solve your problems.


text:
Q: reverse an array in java using recursion I am just starting to learn recursion and was able to use it write a simple factorial program without much of a problem. Now I am trying to write a recursive method that writes an array in reverse order but I can't figure out what I'm doing wrong. What am I missing? Thank you.
import java.io.*;

public class Recursion {
  public static void main(String[] args) throws IOException{
    int myArray[] = {1,2,3,4,5,6,7,8,9,10};
  }

  public static void reverseDisplay(int[] ary, int position){
    if(position > 0)
      System.out.print(ary[position]);
     reverseDisplay(ary, position - 1);
  }
}

A: *

*You do not call your recursion method.

*You have an endless recursion because reverseDisplay() is always
being executed due to missing enclosing brackets.

*Also your stop condition has to be >= 0 because the first index of an array is 0.

Your method should read:
import java.io.IOException;

public class Recursion {
    public static void main(String[] args) throws IOException{
        int myArray[] = {1,2,3,4,5,6,7,8,9,10};

        reverseDisplay(myArray, myArray.length -1);
    }

    public static void reverseDisplay(int[] ary, int position){
        if(position >= 0) {
            System.out.print(ary[position]);
            reverseDisplay(ary, position - 1);
        }
    }
}

A: When doing recursion you need something called a base case. You need the base case to end the recursion or you will get a stack overflow.
You might try something like this. The return statement stops the recursion from being endless.
public static void reverseDisplay(int[] ary, int position){
     if(int == -1)
         return;
     System.out.print(ary[position]);
     reverseDisplay(ary, position - 1);
  }

A: Try:
import java.io.*;

public class Recursion {
  public static void main(String[] args) throws IOException{
    int myArray[] = {1,2,3,4,5,6,7,8,9,10};

    reverseDisplay(myArray,0);
  }

  public static void reverseDisplay(int[] ary, int position){
    if(position == ary.length){
        return;
    }

    reverseDisplay(ary, position + 1);
    System.out.print(ary[position]);
  }
}

If position == ary.length you finish the recursion, else you call reverseDisplay recursively and after that print the current position of ary.


text:
Q: how to use mysqldump command in php? I want to backup my database. So I've used this command
$command = "mysqldump --user=root asset_management > D:\assetmanagement\public\backup\backup.sql";
system($command);
But this will produce an empty sql file.. can anyone help?

A: Suppose your mysqldump is in the C:/wamp/bin/mysql/mysql5.1.33/bin/ folder
$mysqlPath="C:/wamp/bin/mysql/mysql5.1.33/bin/";
//There should be password for root user. Blank password will not work.

$command = $mysqlPath . "mysqldump.exe asset_management > D:\assetmanagement\public\backup\backup.sql --user=root --password=yourpassword ";

A: $command = "mysqldump --user=root -pass=yourpassword asset_management > D:\assetmanagement\public\backup\backup.sql"; system($command);


text:
Q: how to change div style which is in master page from content page code behind file I want to include that style class from external css file into content page code behind file. css file name is screen.css and it is having   .bodydefault class so how to access that css class from code behind?

A: I don't fully understand the question but what are trying to do with the class in the code behind?
If you have linked the screen.css file in the master page you can set the class of an element in the code behind using the following...
LinkButton1.CssClass = "bodydefault";

You can remove it using the following...
 LinkButton1.CssClass = null;
 LinkButton1.Attributes["class"] = null;


text:
Q: How do I edit and save a large bitmap in Android? Currently writing it out as tiles but it is slow to join them back together I'm using renderscript on Android to edit photos, currently due to the texture size limit and memory limits on Android the app will crash if I try anything too large eg photos taken with the devices camera.
My first thought to get around this was to use BitmapRegionDecoder and tile the large photo into manageable pieces, edit them through renderscript and save them one at a time, then stitch it all together using PNGJ - a PNG decoding and encoding library that allows writing PNG images to disk in parts so I don't have the full image in memory.
This works fine but stitching it together takes a rather long time - around 1 minute at a guess.
Are there any other solutions I should consider? I can change to JPEG if there is a solution there, but I haven't found it yet. Basically I'm looking for the other side of a BitmapRegionDecoder, a BitmapRegionEncoder.
Just to be clear, I do not want to resize the image.

A: *

*Load the image in horizontal stripes using BitmapRegionDecoder. The code below assumes that it is PNG and uses PNGJ to copy the metadata to new image, but adding support for JPEG should not be too difficult.

*Process each stripe with Renderscript.

*Save it using PNGJ. Do not use high compression or it will slow down to a crawl.

PNG version of this image (4850x3635px) takes 12 seconds on Nexus 5 with a trivial RS filter (desaturation).
void processPng(String forig,String fdest) {
    try {
        Allocation inAllocation = null;
        Allocation outAllocation = null;
        final int block_height = 64;

        FileInputStream orig = new FileInputStream(forig);
        FileInputStream orig2 = new FileInputStream(forig);
        FileOutputStream dest = new FileOutputStream(fdest);

        BitmapRegionDecoder decoder = BitmapRegionDecoder.newInstance(orig, false);
        Rect blockRect = new Rect();

        PngReader pngr = new PngReader(orig2);
        PngWriter pngw = new PngWriter(dest, pngr.imgInfo);
        pngw.copyChunksFrom(pngr.getChunksList());

        // keep compression quick
        pngw.getPixelsWriter().setDeflaterCompLevel(1);

        int channels = 3; // needles to say, this should not be hardcoded
        int width = pngr.imgInfo.samplesPerRow / channels;
        int height = pngr.imgInfo.rows;

        pngr.close(); // don't need it anymore

        blockRect.left = 0;
        blockRect.right = width;

        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inPreferredConfig = Bitmap.Config.ARGB_8888;
        Bitmap blockBitmap;
        byte []bytes = new byte[width * block_height * 4];
        byte []byteline = new byte[width * channels];

        for (int row = 0; row <= height / block_height; row++) {
            int h;

            // are we nearing the end?
            if((row + 1) *  block_height <= height)
                h = block_height;
            else {
                h = height - row * block_height;

                // so that new, smaller Allocations are created
                inAllocation = outAllocation = null;
            }

            blockRect.top = row * block_height;
            blockRect.bottom = row * block_height + h;

            blockBitmap = decoder.decodeRegion(blockRect, options);

            if(inAllocation == null)
                inAllocation = Allocation.createFromBitmap(mRS, blockBitmap);

            if(outAllocation == null)
            {
                Type.Builder TypeDir = new Type.Builder(mRS, Element.U8_4(mRS));
                TypeDir.setX(width).setY(h);

                outAllocation = Allocation.createTyped(mRS, TypeDir.create());
            }

            inAllocation.copyFrom(blockBitmap);
            mScript.forEach_saturation(inAllocation, outAllocation);
            outAllocation.copyTo(bytes);

            int idx = 0;

            for(int raster = 0; raster < h; raster++) {
                for(int m = 0; m < width; m++)
                {
                    byteline[m * channels] = bytes[idx++];
                    byteline[m * channels + 1] = bytes[idx++];
                    byteline[m * channels + 2] = bytes[idx++];
                    idx++;
                }

                ImageLineByte line = new ImageLineByte(pngr.imgInfo, byteline);
                pngw.writeRow(line);
            }
        }
        pngw.end();
    } catch (IOException e)
    {
        Log.d("BIG", "File io problem");
    }
}

A: Based on @MiloslawSmyk answer, this is the version to load a large JPEG and save it with PNGJ:
fun processPng(forig: String, fdest: String) {
    try {
        val blockHeight = 64

        val orig = FileInputStream(forig)
        val dest = FileOutputStream(fdest)

        val decoder = BitmapRegionDecoder.newInstance(orig, false)
        val blockRect = Rect()

        val channels = 3 // needles to say, this should not be hardcoded
        val sizeOptions = BitmapFactory.Options().apply {
            inJustDecodeBounds = true
        }
        BitmapFactory.decodeFile(forig, sizeOptions)
        val height: Int = sizeOptions.outHeight
        val width: Int = sizeOptions.outWidth

        val pngw = PngWriter(dest, ImageInfo(width, height, 8, false))

        // keep compression quick
        pngw.pixelsWriter.deflaterCompLevel = 1

        blockRect.left = 0
        blockRect.right = width

        val options = BitmapFactory.Options().apply {
            inPreferredConfig = Bitmap.Config.ARGB_8888
        }
        var blockBitmap: Bitmap
        val byteLine = ByteArray(width * channels)

        for (row in 0..height / blockHeight) {
            // are we nearing the end?
            val h: Int = if ((row + 1) * blockHeight <= height)
                            blockHeight
                        else {
                            height - row * blockHeight
                        }

            blockRect.top = row * blockHeight
            blockRect.bottom = row * blockHeight + h

            blockBitmap = decoder.decodeRegion(blockRect, options)

            // convert bitmap into byte array
            val size = blockBitmap.rowBytes * blockBitmap.height
            val byteBuffer = ByteBuffer.allocate(size)
            blockBitmap.copyPixelsToBuffer(byteBuffer)
            val bytes = byteBuffer.array()

            var idx = 0

            for (raster in 0 until h) {
                for (m in 0 until width) {
                    byteLine[m * channels] = bytes[idx++]
                    byteLine[m * channels + 1] = bytes[idx++]
                    byteLine[m * channels + 2] = bytes[idx++]
                    idx++
                }

                val line = ImageLineByte(pngw.imgInfo, byteLine)
                pngw.writeRow(line)
            }
        }
        pngw.end()

    } catch (e: IOException) {
        Log.d("BIG", "File io problem")
    }

}


text:
Q: Как заставить callback, вызванный из await-функции отработать до ее завершения (async () => {
  let anything;

  await anyNoReturnFunctionFromLibrary(arg1, (err, result) => {
    if (err) throw(err);
    anything = result;
  });

  anotherFunction(anything.property1);
})();

Вопрос: можно ли как-то заставить отработать callback функции  anyNoReturnFunctionFromLibrary до вызова функции  anotherFunction, чтобы переменная anything проинициализировалась. Вариант вставить anotherFunction в callback работает, но он мне не нравится, т.к. логика будет расширяться, и всю ее придется делать в callback


text:
Q: Weird behaviour with fwrite I'm trying to save a struct into a file. It works fine and I can load it without any problem. But when I'm inspecting my save file with a hex editor, I can see some parts of a previous printf stored in the file. I really don't understand how this is possible, especially when my program works totally fine to load the struct.
I have three structs (Orientation, ShipType, Status and PlayerType are enumerations, you can replace them by Int) :
struct Map
{
    int width, height;
    int* cases;
};
typedef struct Map Map;

struct Ship
{
    int x, y, length, firstShoot, color;
    int hasBeenDiscovered;
    Orientation orientation;
    ShipType type;
    Status status;
};
typedef struct Ship Ship;

struct Player
{
    int activeShips;
    Map map[2];
    char lastMoves[5][128];
    Ship ships[10];
    PlayerType type;
    int shipcolor[4];
    int color;
};
typedef struct Player Player;

Here is the tree of my program :
main() -> playMenu() -> actionMenu() -> save()
Here is a screen of one of my menus (playMenu())
https://imgur.com/iSvj6jk
The printf part I'm talking about is just this :
    printf("=========== BATAILLE NAVALE ===========\n"); // You can see part of "=======" in my save file
    printf("        ~~~~Jouer une partie~~~~\n\n");
    printf("1. Joueur contre joueur\n");
    printf("2. Joueur contre ordinateur\n");
    printf("3. Charger une partie\n\n"); // You can see "partie"
    printf("0. Quitter\n"); // You can see "0. Quitter"

    printf("\nVotre choix : "); // You can see "Votre choix"
    scanf("%d", &choix);

And here is the screen of a chunk of my file seen through an hex editor
https://imgur.com/OntYGDH
You can clearly see that some of my menus are written in that file. How is this possible ?
Unfortunately, I can't post any more code because I would have to post so much but do you have any idea what might cause this and where I need to look in order to fix this ?
Here is the code of my save() function, you can see that it has nothing to do with those menus :
int save(Player players[2], int currentPlayer)
{
    int* i;
    FILE* file = NULL;

    file = fopen("save.txt","w+");

    if (file != NULL)
    {
        fwrite(players, sizeof(Player), 2, file);

        fwrite(players[0].map[0].cases, sizeof(int), players[0].map[0].width * players[0].map[0].height, file);
        fwrite(players[0].map[1].cases, sizeof(int), players[0].map[1].width * players[0].map[1].height, file);
        fwrite(players[1].map[0].cases, sizeof(int), players[1].map[0].width * players[1].map[0].height, file);
        fwrite(players[1].map[1].cases, sizeof(int), players[1].map[1].width * players[1].map[1].height, file);

        fwrite(&currentPlayer, sizeof(int), 1, file);
    }
    else
    {
        // error
    }

    fclose(file);

    return 1;
}


text:
Q: In nightwatch how to make all functions / commands execute sequentially Like in jquery, we have option like async: false.
How to make all functions and commands to be executed sequentially?  i.e. synchronous in nightwatch, so that it works like normal execution flow without jumping to next command , by not waiting asynchronsously for webdriver commands like click, etc.


text:
Q: Ratio of adjacent elements of vector in Matlab I like to use diff(A) but this time i am looking for ratios between the elements of a vector.
A = [1, 2, 3, 4, 5];
diff(A) = 1, 1, 1, 1

i am looking for a function like:
ratio(A) = 2, 1.5, 1.3333, 1.25

A: What's wrong with simple indexing?  Chaining exp, diff then log seems to be quite heavy in overhead.  Simply have the numerator access elements starting from the second position to the end and divide element-wise by the denominator starting from the first position to the second-last position:
ratio = A(2:end) ./ A(1:end-1);

Example Output
>> A = [1 2 3 4 5]

A =

     1     2     3     4     5

>> ratio = A(2:end) ./ A(1:end-1);
>> ratio

ratio =

    2.0000    1.5000    1.3333    1.2500

The above also works for both positive and negative values.

A: If A only contains positive elements, this solution works on multidimensional arrays:
exp(diff(log(abs(A))))
ans = 2, 1.5, 1.3333, 1.25

A: You can always loop over the elements of A
for i = 2:length(A)
    ratio(i-1) = A(i)/A(i-1) ;
end

Works for positive or negative values.


text:
Q: I want to block window.location.href in a new tab in chrome I have a link that opens in a new tab, in the new tab's header it has javascript like this which redirects it to a different page:
window.location.href = "{a different URL}";

I need to debug the new tab before it redirects in an incognito window. What can I do in chrome to stop the new tab from redirecting so that I can debug it? I can't take the redirect out because I need to debug it in a live environment to replicate an issue.

A: You can set a breakpoint for beforeunload in the source panel of the Chrome debugger:

This will fire when window.location changes


text:
Q: Give me a sample on Long-polling(Comet) with Rails? Recently I am studying ajax. I'm curious about Long-polling. I know simple polling ,and I have  make a demo (send a request every 5 seconds.).But Long-polling ,There is a pivotal step that Server-Side can suspend the request until the data update . So I wannt know how to suspend the request??
I am a Front-End developer . I'm poor about Server-Side. Just know basic Rails only.I find some samples but they all use PHP or JAVA....
Anybody can give me a demo that use Long-polling with Rails?


text:
Q: Looping through products from a particular collection I am using the following code to loop through products in the sidebar of the blog section of a website...

{% for product in collections.all.products limit: 8 %}

  {{ product.title | escape  }}

{% endfor %}

I have looked for the solution to this but have turned up nothing... I would like to change the code to be able to specify the collection, so that it only loops through that specific collection.
But I would also like to use a plugin such as meta fields master to specify the collection for each blog post.
Is this possible?

A: collection.all refers to all products. Try with this below code. Ex: If your collection handle is abc-collection , below code with fetch first 8 products from the collection.

{% for product in collections['abc-collection'].products limit: 8 %}

  {{ product.title | escape  }}

{% endfor %}


text:
Q: Connecting Azure SQL database using managed identity from container instance I want to connect Azure SQL server instance using managed identity from Container Instance application which is running R script on ubuntu container.
Currently I am using DBI package with odbc driver to connect using SQL login, but would like to get rid off using separate SQL logins for apps.

A: You can assign System-Assigned Managed Identity for your Container Instance
Go to your Azure Container Instance --> Select Identity under Settings --> Enable System-Assigned status as ON and click on save
Go to your Azure SQL server --> Select Access Control --> Select Add Role Assignment --> Select your Container Instance Object --> Assign the required role
Now, you can use Managed Identity to connect to Azure SQL database from your container instance
You do not need to provide any additional credentials
You can use get_managed_token() in your script to connect to Azure SQL Database
By default, get_managed_token retrieves a token using the system-assigned identity for the resource.


text:
Q: gnuplot splot approximation or interpolation? I'm rendering heat map using gnuplot splot with pm3d using next script
set view map
set dgrid3d
set pm3d interpolate 20,20
set palette defined(\
0 '#00dc00',\
3640 '#00ff00',\
32767 '#c8ff00',\
61894 '#ff8000',\
65535 '#ff7000')
splot "d:/source.dat" using 1:2:3 with pm3d

"source.dat" file contains next values
0 0 36
1 0 36
2 0 36
0 1 36
1 1 36
2 1 36
0 2 36
1 2 36.9
2 2 36

Gnuplot produced next image

But I'm not understand why I have red color in top center point which is equals to 36.6 temperature according to the pallete. In data file I have 36.9 instead of that. It seems to me that gnuplot approximated this value. How I could configure in to interpolate all points?


text:
Q: Quicksort: Non-in-place implementation works. In-place implementation exceeds maximum recursion depth. Why? def quicksort_stable(l):
    if not l:
        return l
    else:
        pivot = l[0]
        return quicksort_stable([x for x in l if x < pivot]) \
                + [x for x in l if x == pivot] \
                + quicksort_stable([x for x in l if x > pivot])

def quicksort_inplace(l):
    def partition(start_idx, end_idx):
        left_idx = start_idx + 1
        right_idx = end_idx
        while True:
            while left_idx <= right_idx and l[left_idx] <= l[start_idx]:
                left_idx += 1
            while right_idx >= left_idx and l[right_idx] >= l[start_idx]:
                right_idx -= 1

            if right_idx < left_idx:
                break
            else:
                l[left_idx], l[right_idx] = l[right_idx], l[left_idx]

        l[start_idx], l[right_idx] = l[right_idx], l[start_idx]

        return right_idx

    def qs(start_idx, end_idx):
        if start_idx < end_idx:
            split_idx = partition(start_idx, end_idx)
            qs(start_idx, split_idx - 1)
            qs(split_idx + 1, end_idx)

    qs(0, len(l) - 1)
    return l

if __name__ == '__main__':

    import random

    l1 = [random.randint(0, 9) for x in range(10000)]
    l2 = [x for x in l1]

    l1 = quicksort_stable(l1)
    quicksort_inplace(l2)

I deliberately chose the first element as the pivot instead of randomizing to ensure that both implementations behave the same way.
Both implementations are implemented recursively. In the call stack, it seems like quicksort_inplace should take O(lg n) space while quicksort_stable should take O(n) space since it creates a new list every time it recurses.
Yet, quicksort_inplace is the one that causes "maximum recursion depth exceeded" while quicksort_stable works fine.
Why is this so?

A: I believe the reason for this behavior is that your list contains lots of repetitions (every element appears ~1000 times), and you "cheated" implementing the stable version by gathering all elements equal to pivot at once and not getting back to them (which is of course great!).
So to actually compare these two procedures it should look like this:
    def quicksort_stable(l):
        if not l or len(l)==1:
            return l
        else:
            pivot = l[0]
            rst = l[1:]
            return quicksort_stable([x for x in rst if x < pivot]) \
                    + [pivot] \
                    + quicksort_stable([x for x in rst if x >= pivot])

Plus, in order to have the destructive (inplace) version of the above you should change a condition on your second while to greater-than (so that on right of right_idx there are elements no less than pivot), i.e.
        while right_idx >= left_idx and l[right_idx] > l[start_idx]:

If you do this you'll find that both procedures cause stack overflow on arrays with 10000 elements from range(0,9) (note also that with range(0,99) this is not the case because they require less "cuts").


text:
Q: How to create query in sql to pivot data? I have two tables named PRODUCT and DETAIL
TABLE: PRODUCT
slno  product
1          x
2          y
3          z

TABLE: DETAIL
product    detail
x          good
y          bad
z          worse
x          bad

I need to get output as
TABLE
X      Y       Z
good   bad     worse
bad

A: This data transformation is known as a PIVOT and starting in SQL Server 2005 there is a function to convert the data from rows to columns.
There are several ways that this can be done depending on whether or not you have a static number of values to transpose into columns. All of them involve adding a row_number() to the data so you can return the multiple rows of any of the products.
You can use an aggregate function with a CASE expression:
select
  max(case when product = 'x' then detail end) x,
  max(case when product = 'y' then detail end) y,
  max(case when product = 'z' then detail end) z
from
(
  select p.product, d.detail,
    row_number() over(partition by p.product order by p.slno) rn
  from product p
  inner join detail d
    on p.product = d.product
) src
group by rn

See SQL Fiddle with Demo
You can use the PIVOT function:
select x, y, z
from
(
  select p.product, d.detail,
    row_number() over(partition by p.product order by p.slno) rn
  from product p
  inner join detail d
    on p.product = d.product
) src
pivot
(
  max(detail)
  for product in (x, y, z)
) piv

See SQL Fiddle with Demo.
If you have an unknown number of values (products in this case) to turn into columns, then you will want to use dynamic SQL:
DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)

select @cols = STUFF((SELECT distinct ',' + QUOTENAME(product)
                    from product
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)')
        ,1,1,'')

set @query = 'SELECT ' + @cols + ' from
             (
                select p.product, d.detail,
                  row_number() over(partition by p.product order by p.slno) rn
                from product p
                inner join detail d
                  on p.product = d.product
            ) x
            pivot
            (
                max(detail)
                for product in (' + @cols + ')
            ) p '

execute(@query)

See SQL Fiddle with Demo
The result of all of the queries is:
|    X |      Y |      Z |
--------------------------
| good |    bad |  worse |
|  bad | (null) | (null) |

A: This is your query.
    select p.product, d.detail from product p
inner join detail d on  p.product = d.product

A: Look into the SQL Join statements. This blogpost explains it nicely.

A: select d.product, d.detail from detail d
join product p on d.product = p.product