text:
Q: Index of each CharAt and multiplying each index number I am trying to multiply each every index number together and seems like parseInt also return a decimal in the end...Not sure why?
    var decNum = "12312312312312";

    if( decNum.length == 14)
    {
        var lastnum = decNum.charAt(13);

        var newNum = parseInt(decNum)/14; // rather 1231231231231 it shows 1231231231231.2 should be 13 nums left without last digit in int.

        var validNum = [1,7,4,2,8,7,3,2,1,2,3,4,1,3];
        var sum;

        for (var i = 0; i < validNum.length; i++) {

        //since I can't use charAt for for INT so parse to string and parse it back to int to do the math.
            sum += parseInt(validNum[i]) * parseInt(String(newNum.charAt(i)));
        }

A: parseInt returns a number, so var newNum = parseInt(decNum)/14; results in newNum being a number, not a string. So, you can't use charAt on a number - you want the string. You have decimals because when you divide an integer (decNum) by 14, the result is a continuing decimal.
If you want to use explicit type conversions:
const newNum = String(parseInt(decNum / 14));
You don't need to parseInt the elements of validNum since they're already integers.
Your sum is not initialized to 0, so subsequent sum += lines will fail.
Even after fixing that, it would still be more elegant to use array methods to iterate over the string, though:

const decNum = "12312312312312";
if( decNum.length == 14) {
  const newNum = String(parseInt(decNum / 14));
  const validNum = [1,7,4,2,8,7,3,2,1,2,3,4,1,3];
  const charCodeArr = newNum.split('').map(char => char.charAt(0));
  const sum = charCodeArr.reduce((sumSoFar, charCode, i) => {
    return sumSoFar + (charCode * validNum[i]);
  }, 0);
  console.log(sum);
}

A: everything works fine now, thanks, everyone.
    var decNum = "12312312312312";

    if( decNum.length == 14)
    {
        var lastnum = decNum.charAt(13);

        var newNum = String(parseInt(decNum)/14);

        var validNum = [1,7,4,2,8,7,3,2,1,2,3,4,1,3];
        var sum = 0;

        for (var i = 0; i < validNum.length; i++) {
            sum += parseInt(validNum[i]) * parseInt(newNum.charAt(i));
        }


text:
Q: Why does he deserialize twice This is not my code I just have to understand it.  The original programmer cannot be reached.
dobj is just an object type.
My main question is: Why does he deserialize again when dobj was never changed?
Please ignore all his goto's for right now they are everywhere in this program.
        ////////////////////////
        //Deserialize Original//
        ////////////////////////
        dobj = Generics.IO.BinarySerializer.Open(g_PathToTMP);

        if (dobj == null)
        {
            ///////
            //LOG//
            ///////

            goto Label_Done;
        }

        dccmcaltered = dobj as ASM001.MatSettings;

        if (dccmcaltered == null)
            goto Label_Done;
        //

        //////////////////////////////////////////
        //Apply Changes To Deserialized Original//
        //////////////////////////////////////////
        dccmcaltered.ObjectLocation = wpuiobj.ObjectLocation;
        dccmcaltered.ObjectOffset = wpuiobj.ObjectOffset;
        dccmcaltered.UserDefinedLocation = wpuiobj.UserDefinedLocation;
        dccmcaltered.Locked = wpuiobj.Locked;
        dccmcaltered.RinseLocation = wpuiobj.RinseLocation;
        dccmcaltered.RinseDepth = wpuiobj.RinseDepth;
        dccmcaltered.DrainLocation = wpuiobj.DrainLocation;
        dccmcaltered.DrainDepth = wpuiobj.DrainDepth;
        //

        ////////////////////////
        //Deserialize Original//Why did we need to Deserialize again
        ////////////////////////
        dobj = Generics.IO.BinarySerializer.Open(g_PathToTMP);

        if (dobj == null)
        {
            ///////
            //LOG//
            ///////

            goto Label_Done;
        }

        dccmcoriginal = dobj as ASM001.MatSettings;
        if (dccmcoriginal == null)
            goto Label_Done;
        //

        bResult = Generics.IO.SerializerPlus.IsBinaryEqual(dccmcoriginal, dccmcaltered);

        Label_Done:
        ;

        bCurrent = bResult;

        ///////////
        //Cleanup//
        ///////////
        FileInfo fInfo = new FileInfo(g_PathToTMP);

        if (fInfo.Exists)
            fInfo.Delete();
        //

        System.Diagnostics.Debug.WriteLineIf(!bCurrent && g_bVerbose, "[Main] Mat is not Current [ASM = 1]!");
        System.Diagnostics.Debug.WriteLineIf(bCurrent && g_bVerbose, "[Main] Mat is Current! [ASM = 0]");

Edit I added the rest of the method

A:
Why does he deserialize again when dobj was never changed?

The object referenced by dobj was changed. It is the same object no matter whether you refer to it via dobj or dccmcaltered:
dccmcaltered = dobj as ASM001.MatSettings;

This just gets a different typed reference to the same object;
dccmcaltered.ObjectLocation = wpuiobj.ObjectLocation;
dccmcaltered.ObjectOffset = wpuiobj.ObjectOffset;
dccmcaltered.UserDefinedLocation = wpuiobj.UserDefinedLocation;
dccmcaltered.Locked = wpuiobj.Locked;

And now: the values are changed.
Note that dccmcaltered retains a reference to this original object, so those changes remain accessible even after dobj is assigned a different object.

A: Somewhere later on he wants to compare the unaltered and the updated version.
First he deserializes to dccmcaltered , and sets some properties.
Then he deserializes to dccmcoriginal without setting these properties.
Glad I don't have to maintain this...
Good luck!
Yep, the comparison is (aargh):
bResult = Generics.IO.SerializerPlus.IsBinaryEqual(dccmcoriginal, dccmcaltered);
So you could just delete all about dccmcoriginal,
and verify if the properties need to change before actually changing them.

A: Because he is changing firstly deserialized object dobj with lines like dccmcaltered.ObjectLocation = wpuiobj.ObjectLocation; so he loses "original" dccmcaltered.ObjectLocation values and "restores" them (into another object) with second deserialization... strange guy... cheers

redpajama_set_name: RedPajamaStackExchange


text:
Q: "org.hibernate.ObjectNotFoundException: No row with the given identifier exists" but it does exists I'm using hibernate for my web service.
I'm able to list all the records, but unable to get just one.
The table contains:
ID (VARCHAR)                      VALUE(BIT)
celiac                               1
rate                                 1
suggestions                          0

The error shown is:
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.hibernate.ObjectNotFoundException: No row with the given identifier exists: [com.pfc.restaurante.models.Device#id="xxxxxx"]
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:894)
    org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:778)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:717)

And the main code:
    @JsonAutoDetect
    @Entity
    @Table(name = "SETTINGS")
    public class Settings implements Serializable{
        @Id
        @Column(name="ID")
        private String id;

        @Column(name="VALUE", nullable=false)
        private boolean value;
    (...)
    }
    //////////////////7
   @Controller
   @RequestMapping("/settingsService")
   public class SettingsServiceController {

    @Autowired
    SettingsService settingsService;

        @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public @ResponseBody Settings find(@PathVariable("id") String id){
        return settingsService.find(id);
    }
          (...)
}

I've read around that it could be because DB incongruence with my entity (some nullable = true when it shouldn't), but I've checked it already and there is no such a thing.
Could someone lend me a hand?
Thanks in advance!

A: Your error refers to an entity named 'Device' but your code shows an entity 'Settings'. Are they the same?
I've seen this error only in 2 situations:

*

*The main entity does not exist in the DB and Session.load() is used. Use Session.get() and check for null instead.

*Broken relationships. Consider this: EntityA owns a relation to EntityB. EntityB is deleted while the FK in EntityA is left untouched. So, whenever HB tries to load the link A-B the error happens. This can happen when running a normal search or even when saving/refreshing EntityA (HB needs to refresh the link as well).


text:
Q: DomPdf not displaying dynamic images only displaying single image I am creating print membership card based on Joomla users, after generating membershipcard it need to print as pdf, the problem was single image displaying in domp pdf correctly , but multiple image not displaying only showing single image at all the time ,
default.php
<form method='POST' action='index.php?option=com_mycomponentbs&view=MembershipCard&task=cardpdf'>
<?php foreach($orderitems as $re) { ?>

      <input type='checkbox' class="checkbox1" name='id[]' id="id" value="<?php echo $re->id?>">

      <?php echo $re->id?>	 <?php echo $re->name?>

<?php } ?>
<input type='submit' name='submit'>

cardpdf.php
foreach ($orderitems as $re):
  $user = JFactory::getUser();
  $path = JURI::Root().'back.jpeg';
  $font_path="Lin.ttf";
  $card = imagecreatefromjpeg($path);
  $white = imagecolorallocate($card, 255, 255, 255);
  imagettftext($card, 22, 0, 40, 515, $white, $font_path, $re->id);
  $file= $_SERVER['DOCUMENT_ROOT'].'tmpl/back1.jpeg';

  ImageGIF($card, $filenametemp);
  $ImageData = file_get_contents($filenametemp);
  $ImageDataEnc = base64_encode($ImageData);
  unlink($filenametemp); // delete the file
  ?>

  <img src="data:image/gif;base64,<?=$ImageDataEnc1?>>

<?php endforeach; } ?>

```


text:
Q: Set cpu and memory requirements for a Fargate AWS Batch job from an AWS Cloudwatch event I am trying to automate Fargate AWS Batch jobs by means of AWS Cloudwatch Events. So far, so good. I am trying to run the same job definition with different configurations. I am able to set the batch job as a cloudwatch event target. I have learned how to use the Constant (JSON text) configuration to set a parameter of the job. Thus, I can set the name parameter successfully and the job runs. However, I am not able to also set the memory and cpu settings in the Cloudwatch event. I would like to use a larger machine for a a bigger port such as Singapore, without changing the job definition. After all, at the moment it still uses the default vpcu and memory settings of the job definition.
{
    "Parameters": {"name":"wilhelmshaven"},
    "ContainerOverrides": {
        "Command": ["upload_to_day.py", "-port_name","Ref::name"],
        "resourceRequirements": [
            {"type": "MEMORY", "value": "4096"},
            {"type": "VCPU", "value": "2"}
        ]
    }
}

Does any one know how to set the Constant (JSON text) configuration or input transformer correctly?
Edit: If I try the same thing using the AWS CLI, I can achieve what I would like to do.
aws batch submit-job \
        --job-name "run-wilhelmshaven" \
        --job-queue "arn:aws:batch:eu-central-1:123666072061:job-queue/upload-raw-to-day-vtexplorer" \
        --job-definition "arn:aws:batch:eu-central-1:123666072061:job-definition/upload-to-day:2" \
        --container-overrides '{"command": ["upload_to_day.py", "-port_name","wilhelmshaven"], "resourceRequirements": [{"value": "2", "type": "VCPU"}, {"value": "4096", "type": "MEMORY"}]}'


text:
Q: HDInsight Azure Blob Storage Data Update I am considering HDInsight with Hive and data loaded on Azure Blob Storage.
There is a combination of both historic and changing data.
Does the solution mentioned in Update , SET option in Hive work with blob storage too?
The below Hive statement change the data in blob storage which is my requirement too?
INSERT OVERWRITE TABLE _tableName_ PARTITION ...

A: INSERT OVERWRITE will write new file(s) into the cluster file system. In HDInsight the file system is backed by Azure blobs, the wasb://... and wasb:///... names. Everything Hive does to the cluster file system, like overwriting them, will accordingly be reflected in the Azure storage BLOBs. See Use Hive with HDInsight for more details.


text:
Q: PHP session for object of class I have problem with session.
$kernel = new COM("NETOPENX50.Kernel") or die("Unable to instantiate Netopenx50.Kernel");

$_SESSION['kernel'] = $kernel;

its not working :( any idea ?

A: From the manual:

Can I store a COM object in a session ?
No, you can't. COM instances are treated as resources and therefore they are only available in a single script's context.


text:
Q: Compute a Gröbner basis for $I=\langle f_1,f_2,f_3\rangle$.
Using lexicographic order compute a Gröbner basis for
  $$I=\langle f_1=xy^2-xy+y,f_2=xy-z^2,f_3=x-yz^4\rangle\subset \Bbb R[x,y,z]$$

I was strictly using these notes to compute a Gröbner basis.

When the computation gets messy I used a computer software at least to know the answer, but the software gave me
$$\{z^8-z^6-2 z^4-z^2, y-z^6+2 z^4, x-z^6+z^4+z^2\}$$
as a Gröbner basis, which I wouldn't even imagine, because the elements in $I$ are not included. I was expecting the answer to be like $\langle f_1,f_2,f_3,\ldots\rangle$.

Edited: How can I compute a Gröbner basis by hand?

A: The Gröbner basis depends on the monomial order you choose. If you use lexicographical order you do get (in M2; commented out -- is the answer):
R=QQ[x,y,z,MonomialOrder=>Lex];
I=ideal(x*y^2-x*y+y,x*y-z^2,x-y*z^4);
gens gb I -- | z8-z6-2z4-z2 y-z6+2z4 x-z6+z4+z2 |
J=ideal oo
I==J -- true

But if you use graded reverse lexicographical order (default for M2):
R=QQ[x,y,z];
I=ideal(x*y^2-x*y+y,x*y-z^2,x-y*z^4);
gens gb I -- | y2-2z2+x+y xy-z2 x2-2z2-2x+y yz2-z2+y xz2-2z2-x+y z4-z2-x+y |
J=ideal oo
I==J -- true

In either case the ideals are the same, what needs to be true for a Gröbner basis (that it is a generating set and) that the initial terms generates the initial ideal for that monomial order.
This means that your original generators could be part of the list but that the initial terms aren't needed for generating the initial ideal.


text:
Q: Prove that $G$ is a block if and only if given a vertex and an edge of $G$ there exists a cycle containing them. Prove that $G$ is a block if and only if given a vertex and an edge of $G$ there exists a cycle containing them.
A block of a graph $G$ is a maximal connected subgraph of G that has no cut-vertex.
Attempt:
Let $u\in V(G)$ and $a\in E(G)$, $a=wv$. By hypothesis, there exists a cycle $C$ containing $u$ and $w$. As for $v$ there are two possibilities: that it is part of the vertices of the cycle or that it is not. If $v\in V(C)$ we obtain a cycle $C'$ containing $u$ and edge $a$ as follows:
\begin{align*}
C&=u, u_1, \ldots , w, w_1, \ldots v, v_1, \ldots u \\
C'&=u, u_1, \ldots , w, v, v_1, \ldots u
\end{align*}
That is, we replace the part $C$ between $w$ and $v$ by the edge $a$.
If $v\notin V(G)$ we have a situation equal to the previous demonstration and we can find two paths from $u$ to $v$, one of which contains edge $a$.


text:
Q: flutter laravel websockets Private Channel trigger current location i have laravel and set up the websockets and all is good
and in my flutter app i connect to websockets private channel and its good
but here is the bug is that i listen to the server events
but i need the app to send data to channel and let all users on same channel see the data
the flutter dont (trigger) data on channel
(the delivery boy send his current location to the channel and the customer listen to the delivery location that updated)
The Flutter Code
import 'package:pusher_client/pusher_client.dart';
import 'package:location/location.dart';
import 'package:flutter/material.dart';

class DeliveryLocationTrackingProvider extends ChangeNotifier {
  late Channel _channel;

  // the user's initial location and current location
  // as it moves
  late LocationData _currentLocation;
  // wrapper around the location API
  late Location _location;

  Location get location => this._location;
  LocationData get currentLocation => this._currentLocation;

  set location(Location location) {
    this._location = location;
  }

  set currentLocation(LocationData currentLocation) {
    this._currentLocation = currentLocation;
  }

  late PusherClient pusher;
  late Channel channel;
  late PusherOptions pusherOptions;
  //
  connectToPusher() {
    PusherAuth auth = PusherAuth(
      'http://shahwanji.com/broadcasting/auth',
      headers: {
        'Authorization': 'Bearer ${SharedManager.shared.token}',
        'Content-Type': 'application/json'
      },
    );

    pusherOptions = PusherOptions(
      host: '*********.com',
      wsPort: 6001,
      encrypted: false,
      auth: auth,
    );

    pusher = PusherClient(
      '****************',
      pusherOptions,
      enableLogging: true,
    );

    pusher.connect();

    pusher.onConnectionStateChange((state) {
      print("currentState: ${state?.currentState} -- -- ");
    });

    pusher.onConnectionError((error) {
      print("error: ${error?.message}");
    });
  }

  disconnectFromPusher() {
    // // Disconnect from pusher service
    pusher.disconnect();
  }

  Future<Channel> connectToChannel(String channelName) async {
    await this.connectToPusher();

    return pusher.subscribe(channelName);
  }
  // ////////

  listenToMove() async {
    // create an instance of Location
    this._location = new Location();

    // set the initial location by pulling the user's
    // current location from the location's getLocation()
    this._currentLocation = await this._location.getLocation();

    // subscribe to changes in the user's location
    // by "listening" to the location's onLocationChanged event

    this._connect();

    this._location.onLocationChanged.listen((LocationData cLoc) {
      //   // cLoc contains the lat and long of the
      //   // current user's position in real time,
      //   // so we're holding on to it
      this._currentLocation = cLoc;
      print("cLoc.latitude ${cLoc.latitude}");
      _channel.trigger('client-update-location', {
        'the-data-latitude': cLoc.latitude,
        'the-data-longitude': cLoc.longitude,
      });

      notifyListeners();
    });
  }

  _connect() async {
    this._channel = await connectToChannel(
        'private-delivery.${SharedManager.shared.delivery.id}');
  }

  listenLocation() async {
    await this._connect();

    this._channel.bind("update-location", (PusherEvent? event) {
      print("update-location update-location ${event?.data}");
      _channel.trigger('client-update-location',
          {'the-data-latitude': 0.0, 'the-data-longitude': 0.0});
    });

    _channel.bind("pusher:subscription_succeeded", (PusherEvent? event) {
      _channel.trigger('client-update-location',
          {'the-data-latitude': 0.0, 'the-data-longitude': 0.0});
      print('event.data ${event?.data}');
    });
  }
}

Laravel Code
<?php

namespace App\Events\Delivery;

use App\Models\Delivery;
use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;

class TrackDeliveryLocationEvent implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public Delivery $delivery;
    /**
     * Create a new event instance.
     *
     * @return void
     */
    public function __construct(Delivery $delivery)
    {
        $this->delivery = $delivery;
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return \Illuminate\Broadcasting\Channel|array
     */
    public function broadcastOn()
    {
        return new PrivateChannel('delivery.' . $this->delivery->id);
    }

    // the event name we listion to
    public function broadcastAs()
    {
        return 'update-location';
    }

    // the data send with every send
    public function broadcastWith()
    {
        return [
            'the-data' => 'Hi In Test',
        ];
    }
}


text:
Q: Access linux device through bridged interface I'm currently trying to set up a device with a bridge in my network. The device used for the Bridge has two eth interfaces and a wlan interface.
I managed to create the bridge from eth1 to wlan0. The bridge itself is working fine, I can ping the PC2 connected to the bridge at eth1 from the wlan0
Right now I can only use eth0 for ssh or accessing its page set up with lighttpd.
Is there a way to configure the network so I can use the wlan0-interface too? I tried to look into iptables but I could not find any solution.
That's the setup:
PC 1                       Bridge                  PC 2
-----------------------------------------------------
Lan--------------------->|eth0   |
                         |eth1   |--------------->Lan
                         |wlan   |

Edit:
Trying to go a bit more into detail. Both PC2 and the Bridge-device have installed lighttpd and own a homepage which can be accessed by their IP.
The bridge looks like this
$ brctl show
bridge name        bridge id              stp enabled          interfaces
br0                8000.1cba8ca5cb94      no                   eth1
                                                               wlan0

Know, what I want: While I'm connected via wlan0: insert the PC2's IP into the browser and view the Homepage -> this worked
While I'm connected via wlan0: insert the Bridge-device's IP into the browser and view the Homepage -> this does not work ... I guess because that's because I had to "ifconfig wlan 0.0.0.0 down" before creating the bridge.
I hope it gets more clear now... :)

A: Most wireless devices do not allow traffic to be sent over them with a non-local MAC.
I would suggest just not bridging your wireless device.
You might be able to get around this with ebtables NAT. External URLs are usually discouraged on the StackExchange network, but the following is a good source of explanation and example config and has been around for years:
https://wiki.debian.org/BridgeNetworkConnections#Bridging_with_a_wireless_NIC


text:
Q: Grails and pdf.js and rendering a pdf via an ajax call I am adding a feature to our application that requires an embedded pdf viewer.  The user will need to be able to view the pdf while simultaneously accessing some other forms located in another area of the screen.
Providing the file url is not acceptable for security reasons.  Instead,  the view request must go to our application which will provide additional security checks.  If the checks are successful, then the pdf is returned as a stream.  The file directory can never be accessed directly via a browser.
From what I have read,  it seems like pdf.js should work well with this as the PDFJS.getDocument method will accept a Uint8 array as well as a uri.  I've been googling on how others have solved this using a base64ToUint8Array function.
On the client side we use jQuery and bootstrap, and pdf.js and pdf.viewer.js are loaded as part of the page load.
This is all background for my current issue, which is that the server uses grails and I don't know how to send out the binary pdf data via a grails controller class.
Here is what I currently have in the controller:
def view = {
        SolutionFile solutionFile = SolutionFile.get(params.sfileId)
        InputStream pdfStream = fileStoreService.writeBinary( solutionFile.fileName, solutionFile.file)
pdfStream
    }

What is returned to the browser is generated html based on our core layout gsp file, without any included template. I don't see the pdf file data anywhere.
I get an 'Invalid Character error- string contains an invalid character' when PDFJS.getDocument is called, so I suspect that the returned response is not in base64 either.
Here is a mockup of the html:
Here is the ajax call that calls PDFJS:
jQuery(document).ready(function() {

    PDFJS.disableStream = true;
    PDFJS.disableWorker = true;

    function base64ToUint8Array(base64) {//base64 is an byte Array sent from server-side
        var raw = atob(base64); //This is a native function that decodes a base64-encoded string.
        var uint8Array = new Uint8Array(new ArrayBuffer(raw.length));
        for (var i = 0; i < raw.length; i++) {
          uint8Array[i] = raw.charCodeAt(i);
        }
         return uint8Array;
         }

    jQuery('.remote-tab').click(function(e) {
        e.preventDefault();
        var url = jQuery(this).attr("data-url");
        var dataparams = jQuery(this).attr("data-params");
        var params;
        if (dataparams != null) {
            params = JSON.parse(dataparams);
        }
       var canvasId = jQuery(this).attr("data-loadinto");

      jQuery(this.hash).find('#'+canvasId).load(url, params, function(responseTxt, statusTxt, xhr){
        console.log("about to call PDFJS");
              PDFJS.getDocument(base64ToUint8Array(responseTxt)).then(function(pdfFile) {
            PDFJS.disableWorker = true;
            var pageNumber = 1;
            pdfFile.getPage(pageNumber).then(function(page) {
                  var scale = 1;
                  var viewport = page.getViewport(scale);
                  var canvas = document.getElementById('canvas');
                  var context = canvas.getContext('2d');

                  var renderContext = {
                      canvasContext: context,
                      viewport: viewport
                  };
                  canvas.height = viewport.height;
                  canvas.width = viewport.width;
                  console.log("rendering page");
                  page.render(renderContext);
            });
        });

        });
    });
});

Any help explaining what I need to do so that the streamed PDF is returned to the ajax function correctly would be much appreciated.

A: My underlying question is how can I send a base64-encoded binary file to the browser when the server side is
written in grails, specifically how can a method written in a grails controller bypass the expected gsp template generation?
I believe I have found the solution to that in this post:
Writing binary content directly to the client bypassing the Grails view layer
The key is that the response buffer needs to be flushed as the last action in the controller method, and must
be done in that controller method.
Here is what the code in my controller method now looks like:
def view = {
    SolutionFile solutionFile = SolutionFile.get(params.sfileId)
    response.setContentType("application/octet-stream");
    fileStoreService.writeBinary( response, solutionFile.fileName, solutionFile.file)
    response.flushBuffer()
}

The other thing to note is that the setContentType must be done before the response buffer is written.  I'm not yet sure I've
got the correct content type set,  but that is a different part of the story.
The requirement that the returned result be a base64-encoded binary file is because I want to use pdf.js on
the client side.  Specifically,  I want to use PDFJS.getDocument rather than modifying the supplied viewer.html
file. PDFJS.getDocument will only accept a pdf URI (which is not acceptable in this case) or a Uint8 array (which can be generated
from a base64-encoded binary file. )
For security requirements, the stored files can not be directly accessed outside of the application, so
we have a service that will fetch the correct file given a file id.  I created a writeBinary method which
returns the encoded binary file. (At least I hope so, still working on that.)
void writeBinary( response, fileName, fileId) {
  File f=new File(getUrl(fileId))
  FileInputStream fis = new FileInputStream(f)
  try {
     byte[] buf = FileUtils.readFileToByteArray(f)
     response.outputStream << buf.encodeBase64()
    }
  catch (Exception e) {
    log.error(e.printStackTrace());
    }
  finally {
    if (fis != null) fis.close()
  }
}

So, I think I have answered the question I originally posted.  However, the client-side pdf.js part is still not working.
I will be working on that, and may ask a new question once I get clarity on the problem.  I won't reuse this question, since I made it too
difficult to read through.


text:
Q: MySQL datatype float (8, 2) value getting rounded off to one decimal point when fetched in php with Laravel framework My database has a float(8,2) field and has a value with two decimal points (5.49). While fetching it to php, the value gets rounded to one decimal point (5.5) although I expect it to be to two decimal point (5.49) and not rounded off.
I found a solution by changing the datatype to decimal, but I can not do so for production environment (some reason). How can I restrict the round off?
I am using laravel-4.2 php-5.4 and mysql-5.6 and laravel-eloquent.
Thanks in advance.

A: MySQL permits a nonstandard syntax: FLOAT(M,D) or REAL(M,D) or DOUBLE PRECISION(M,D). Here, (M,D) means than values can be stored with up to M digits in total, of which D digits may be after the decimal point. For example, a column defined as FLOAT(7,4) is displayed as -999.9999. MySQL performs rounding when storing values, so if you insert 999.00009 into a FLOAT(7,4) column, the approximate result is 999.0001.


text:
Q: How to add a element between two elements in HTML My DOM currently looks like this:

  <button> </button>

Upon click of the button, I want to add another p in between button and the initial p. I have tried prepending to the initial p, but it's not looking like what I want it to. I have also tried appending to button, but it's adopting the style of button, which I also don't want.
Ideally, I would like to retain the styling of the initial p, but add another individual block of p right before the initial one. How can I achieve this, preferably with append/prepend?

A: If you are using JQuery there is a method for that, it´s called before.
http://api.jquery.com/before/, will work fine in combination with the :first-child selector.
var count=0;
$('button').on('click', function () {
  count++;
    $("#paragraphs p:first-child").before($('
New Paragraph #' + count + '
'));
});

Working Example

A: This is a very rough draft of what you may want to try doing. Instead of attacking the issue from the paragraph attack it from the button if the DOM state is going to stay the same.
The code should look something like this
function addParagraph(sender) {
    $(sender).after( "
Test
" );
}

And you can you the onclick event of the button like this (This can be changed to anything else you might want to use)
<button onclick="addPara(this)">Add Paragraph</button>

Now because your structure is always

<button></button>

It will always push the new element right after the button and always before the next element in the structure. The alternative is to do what Gus has done and create a DIV container and keep pushing new elements into the first place in the DIV.


text:
Q: Java library for cleaning up user-entered title to make it show up in a URL? I am doing a web application. I would like to have a SEO-friendly link such as the following:
http://somesite.org/user-entered-title

The above user-entered-title is extracted from user-created records that have a field called title.
I am wondering whether there is any Java library for cleaning up such user-entered text (remove spaces, for example) before displaying it in a URL.
My target text is something such as "stackoverflow-is-great" after cleanup from user-entered "stackoverflow is great".
I am able to write code to replace spaces in a string with dashes, but not sure what are other rules/ideas/best practices out there for making text part of a url.
Please note that user-entered-title may be in different languages, not just English.
Thanks for any input and pointers!
Regards.

A: What you want is some kind of "SLUGifying" the prhase into a URL, so it is SEO-friendly.
Once I had that problem, I came to use a solution provided in maddemcode.com. Below you'll find its adapted code.
The trick is to properly use the Normalize JDK class with some little additional cleanup. The usage is simple:
// casingchange-aeiouaeiou-takesexcess-spaces
System.out.println(slugify("CaSiNgChAnGe áéíóúâêîôû   takesexcess    spaces  "));
// these-are-good-special-characters-sic
System.out.println(slugify("These are good Special Characters šíč"));
// some-exceptions-123-aeiou
System.out.println(slugify(" some exceptions ¥123  ã~e~iõ~u!@#$%¨&*() "));
// gonna-accomplish-yadda
System.out.println(slugify("gonna accomplish, yadda, 완수하다, 소양양)이 있는 "));

Function code:
public static String slugify(String input) {
    return Normalizer.normalize(input, Normalizer.Form.NFD)
            .replaceAll("[^\\p{ASCII}]", "")
            .replaceAll("[^ \\w]", "").trim()
            .replaceAll("\\s+", "-").toLowerCase(Locale.ENGLISH);
}

In the source page (http://maddemcode.com/java/seo-friendly-urls-using-slugify-in-java/) you can take a look at where this comes from. The small snippet above, though, works the same.
As you can see, there are some exceptional chars that aren't converted. To my knowledge, everyone that translates them, uses some kind of map, like Djago's urlify (see example map here). You need them, I believe your best bet is making one.

A: It seems you want to URL-encode a string. It's possible in core Java, without using external libraries. URLEncoder is the class you need.
Languages other than English shouldn't be a problem as the class allows you to specify the character encoding, which takes care of special characters like accents, etc.


text:
Q: Delineate watershed using manual points in RSAGA I'm currently trying for an automated solution to delineate watersheds within a large basin. I have a collection of locations (X,Y coords) for various tributaries reaching a larger river, and the end-game is to have each sub-basin delineated so I can calculate areas etc. I have been working in R, using SAGA and the RSAGA packages, (R 3.2.2, SAGA 2.1.2, OSX Yosemite 10.10.5).
So far, I have been able to fill the sinks:
rsaga.fill.sinks('dem_saga.sgrd', 'dem_sinkfilled.sgrd', method = "xxl.wang.liu.2006")

And have been able to make a raster of the same size and resolution as the dem, where all cells are 'NA' except for a single cell at the desired location to delineate the watershed (target.sgrd). This was achieved using rasterize command in R (e.g. rasterize(target_point, dem, 1)).
Unfortunately, although I am pretty sure the command I want is the 'Upslope Area' module, when it runs, I end up with a raster where every cell = 100.
I'm not sure exactly how to make a reproducible example, but my code:
rsaga.geoprocessor(lib = 'ta_hydrology', 4,
                    param = list(TARGET = 'target.sgrd',
                                 ELEVATION = 'dem_sinkfilled.sgrd',
                                 AREA = 'target_catch.sgrd',
                                 METHOD = 0))

Finally, the tutorial I have been working through is here. Jumping down to "Creating a Watershed map".


text:
Q: I need to delete login user details when submit a delete button,how can i do that in jsp I  need to delete login user details when submit a delete button,how can i do that in jsp
here is my Loginuser.jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
  <title>E Bank</title>
 <meta charset="utf-8">
 <meta name="viewport" content="width=device-width, initial-scale=1">
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
 <link rel="stylesheet" href="css\loginstudent.css">

        <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">

        </button>
        E Bank

Home

About

Contact

 Login

          Sign In

        <form method="post" action="login.jsp">

Developed By #Himantha #Buddhima #Amindi #Gayath

here is login.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page import ="java.sql.*" %>
<%
String userid = request.getParameter("uname");
String pwd = request.getParameter("pass");
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/ebank?
user=root&password=Gayya");
Statement st = con.createStatement();
ResultSet rs;
`enter code here`rs = st.executeQuery("select * from members where uname='" + userid + "' and pass='"
+ pwd + "'");
if (rs.next()) {
    session.setAttribute("uname", userid);
    //out.println("welcome " + userid);
    //out.println("Log out");
    response.sendRedirect("useraccount.jsp");
} else {
    out.println("Invalid password try again");
}
%>

here is useraccount.jsp
<%@ page import="com.mysql.jdbc.Connection" %>
<%@ page import="java.sql.DriverManager" %>
<%@ page import="java.sql.Statement" %>
<%@ page import="java.sql.ResultSet" %><%--
Created by IntelliJ IDEA.
User: Gayath
Date: 4/17/2020
Time: 2:03 AM
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no">
<title>Dashboard - E bank</title>
<link rel="stylesheet"
href="${pageContext.request.contextPath}/assets/bootstrap/css/bootstrap.min.css?
 h=5cf6485885415ba67d4e9cefe93072c6">
 <link rel="stylesheet" href="https://fonts.googleapis.com/css?
family=Nunito:200,200i,300,300i,400,400i,600,600i,700,700i,800,800i,900,900i">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.12.0/css/all.css">

E Bank

Update Profile details

Log Out

Delete account

Dashboard

Balance

<button>Balance</button>

<button>Online payment</button>

Copyright © Ebank2020

here is delete.jsp
 <%@page import="java.sql.Statement"%>
 <%@page import="java.sql.DriverManager"%>
 <%@page import="java.sql.Connection"%>

<%
String userid = request.getParameter("uname");
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/ebank","root","Gayya");
Statement stat = conn.createStatement();
stat.executeUpdate("delete from members where uname ='test'");
response.sendRedirect("Home.jsp");
%>

i can delete specific name when giving the value of a row but i need delete the current loginuser details.can anyone help me with this?thank you


text: Q: SQLSTATE[HY000]: General error: 126 Incorrect key file for table '/var/tmp/ ecc hello help please I searched through a thousand forums and all of them bring me back to enlarge the temp folder modified max_heap_table_size and tmp_table_size the my.cnf file and restart mysql but nothing still doesn't work help me please :(


text:
Q: Injecting in Arquillian test class always null I install JBoss Tools plugin at my Eclipse IDE and create project as New > JBoss Central > Java EE EAR Project. I used Wildfly 8.2.0.Final server. EJB module of my project template is as below

Dependencies of Arquillian for my project are created by project template and I didn't modify anythings. And then I created my first test class as
@RunWith(Arquillian.class)
public class CustomerServiceTest {
    @Inject
    private CustomerDao customerDao;

    @Deployment
    public static Archive<?> createDeployment() {

    JavaArchive archive = ShrinkWrap.create(JavaArchive.class, "test.jar")
        .addAsResource("META-INF/test-persistence.xml","META-INF/persistence.xml")
        .addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml");
    archive.addClass(CustomerDto.class);
    archive.addClass(Customer.class);
    archive.addClass(CustomerDao.class);
    archive.addClass(Dao.class);

    System.out.println(archive.toString(true));
    return archive;
    }

    @Test
    public void getCustomers() {
    // customerDao Always Null
    System.out.println("############# Testing Success ##################"+ customerDao);
    }
}

Here is console log
10:39:19,578 ERROR [org.jboss.msc.service.fail] (MSC service thread 1-7) MSC000001: Failed to start service jboss.deployment.unit."test.war".WeldStartService: org.jboss.msc.service.StartException in service jboss.deployment.unit."test.war".WeldStartService: Failed to start service
    at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1904) [jboss-msc-1.2.2.Final.jar:1.2.2.Final]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [rt.jar:1.8.0_40]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [rt.jar:1.8.0_40]
    at java.lang.Thread.run(Thread.java:745) [rt.jar:1.8.0_40]
Caused by: org.jboss.weld.exceptions.DeploymentException: WELD-001408: Unsatisfied dependencies for type CustomerDao with qualifiers @Default
  at injection point [BackedAnnotatedField] @Inject private com.solt.hms.customer.CustomerServiceTest.customerDao
  at com.solt.hms.customer.CustomerServiceTest.customerDao(CustomerServiceTest.java:0)

    at org.jboss.weld.bootstrap.Validator.validateInjectionPointForDeploymentProblems(Validator.java:372)
    at org.jboss.weld.bootstrap.Validator.validateInjectionPoint(Validator.java:293)
    at org.jboss.weld.bootstrap.Validator.validateGeneralBean(Validator.java:134)
    at org.jboss.weld.bootstrap.Validator.validateRIBean(Validator.java:167)
    at org.jboss.weld.bootstrap.Validator.validateBean(Validator.java:531)
    at org.jboss.weld.bootstrap.ConcurrentValidator$1.doWork(ConcurrentValidator.java:68)
    at org.jboss.weld.bootstrap.ConcurrentValidator$1.doWork(ConcurrentValidator.java:66)
    at org.jboss.weld.executor.IterativeWorkerTaskFactory$1.call(IterativeWorkerTaskFactory.java:60)
    at org.jboss.weld.executor.IterativeWorkerTaskFactory$1.call(IterativeWorkerTaskFactory.java:53)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266) [rt.jar:1.8.0_40]
    ... 3 more

10:39:19,578 ERROR [org.jboss.as.controller.management-operation] (management-handler-thread - 1) JBAS014613: Operation ("deploy") failed - address: ([("deployment" => "test.war")]) - failure description: {"JBAS014671: Failed services" => {"jboss.deployment.unit.\"test.war\".WeldStartService" => "org.jboss.msc.service.StartException in service jboss.deployment.unit.\"test.war\".WeldStartService: Failed to start service
    Caused by: org.jboss.weld.exceptions.DeploymentException: WELD-001408: Unsatisfied dependencies for type CustomerDao with qualifiers @Default
  at injection point [BackedAnnotatedField] @Inject private com.solt.hms.customer.CustomerServiceTest.customerDao
  at com.solt.hms.customer.CustomerServiceTest.customerDao(CustomerServiceTest.java:0)
"}}
10:39:19,578 ERROR [org.jboss.as.server] (management-handler-thread - 1) JBAS015870: Deploy of deployment "test.war" was rolled back with the following failure message:
{"JBAS014671: Failed services" => {"jboss.deployment.unit.\"test.war\".WeldStartService" => "org.jboss.msc.service.StartException in service jboss.deployment.unit.\"test.war\".WeldStartService: Failed to start service
    Caused by: org.jboss.weld.exceptions.DeploymentException: WELD-001408: Unsatisfied dependencies for type CustomerDao with qualifiers @Default
  at injection point [BackedAnnotatedField] @Inject private com.mycom.project.customer.CustomerServiceTest.customerDao
  at com.mycom.project.customer.CustomerServiceTest.customerDao(CustomerServiceTest.java:0)
"}}

I am totally a newbie in testing with Arquillian. I find and study many examples for Arquillian testing examples. These seems fine but what's wrong with mine ? Thanks for reading my question . Be happy with helping a newbie.

A: The error message suggests that JBoss was unable to create an instance of CustomerDao. The most likely reason for this is one or more missing dependencies.
Perhaps you need to add:
archive.addClass(CustomerDaoImpl.class);


text:
Q: Extract both issue and epic fields in Jira JQL I would like to get the following data from Jira:
Issue ID, Issue Summary, FixVersion (from Epic), FixVersion (from Issue).
Any suggestions are appreciated although I would love to not use commercial plugins.
Thanks
Matej


text:
Q: Don't put "Delete question" under the close banner When a question has been marked a candidate duplicate and I accept it as a duplicate, the resulting banner includes an option to "Delete question".  (Moreover, this is marked in red, further highlighting that option.)  I am concerned this is sending the wrong message to people whose question is marked as a duplicate, or who accept that their question is a duplicate.  Including this option suggests that deleting is something that should be considered or is often appropriate.
We don't want people to delete their question just because it was a duplicate. Duplicates are usually useful to retain, because they help others find a resource via search.
I propose that the "Delete question" option should be removed from the banner.  The option already exists under the question; there is no need to highlight it in the banner.


text:
Q: On the sum: $\sum\limits_{n=0}^{\infty}\left[\,\sum\limits_{k=1}^{a}\frac{1}{an+k}-\sum\limits_{k=1}^{b}\frac{1}{bn+k}\,\right]$ How to prove:

$$ \sum_{n=0}^{\infty}\left[\,\sum_{k=1}^{a}\frac{1}{a\,n+k}-\sum_{k=1}^{b}\frac{1}{b\,n+k}\,\right]=\log\left(\frac{a}{b}\right)\qquad\colon\,a\,,b\in\mathbb{N}^{+}\tag{1}$$

Obviously, we cannot split the sum:
$$ \left(\sum_{n=0}^{\infty}\,\sum_{k=1}^{a}\frac{1}{a\,n+k}\right)-\left(\sum_{n=0}^{\infty}\,\sum_{k=1}^{b}\frac{1}{b\,n+k}\right) = \left(\sum_{n=1}^{\infty}\frac1n\right)-\left(\sum_{n=1}^{\infty}\frac1n\right)=\infty-\infty $$
Any ideas? Thanks in advance.

A: For starters, let us give an integral representation to the general term of the outer sum:
$$ \sum_{k=1}^{a}\frac{1}{an+k}-\sum_{k=1}^{b}\frac{1}{bn+k} = \int_{0}^{1}\left(x^{an}\sum_{k=1}^{a}x^{k-1}-x^{bn}\sum_{k=1}^{b}x^{k-1}\right)\,dx \tag{1}$$
turning the whole sum into:
$$ \lim_{N\to +\infty}\sum_{n= 0}^{N}\int_{0}^{1}\left[\left(x^{an}-x^{bn}\right)-\left(x^{a(n+1)}-x^{b(n+1)}\right)\right]\,\frac{dx}{1-x} \tag{2}$$
If now we exploit
$$ \int_{0}^{1}\frac{x^A-x^B}{1-x}\,dx = H_B-H_A \tag{3}$$
the whole sum turns into
$$ \lim_{N\to +\infty} \left(H_{aN}-H_{bN}\right) = \log\frac{a}{b} \tag{4}$$
due to $H_n=\log(n)+\gamma+O\left(\frac{1}{n}\right).$

It is interesting to point out that we are not allowed to exchange $\sum_{n\geq 0}$ and $\int_{0}^{1}$ in $(2)$, since the hypothesis of the dominated convergence theorem are not met.


text:
Q: jQuery tickboxes, Ticked / Unticked Logic I am working on a logic for checkboxes. Where if the checkbox is unticked, It hides the created list item. An example of this is on jsFiddle I have the tick logic working, But what I'd like is the "Untick" logic to work.
I have given each li item a class, So basically looking to pair the two together to remove the list item. But just not having any luck.
Can anyone help me on extending this logic so that I show / hide the unticked li item, Otherwise I'm just left with a never ending list of items.
Thanks

A: 1) Use the change event for listening to checkboxes. If you use click, you ignore any state changes that come from keyboard interaction.
2) Your current "if not checked" code is creating a NEW li and removing that (before it's even entered the DOM) - presumably not what you meant.
I've assumed you meant to remove CURRENT lis that have a class equal to the name attribute of the changed checkbox. See updated Fiddle:
http://jsfiddle.net/qYtXX/9/

A: You can remove the spaces from the name attributes of checkboxes, try the following:
<input type="checkbox" title="100.00" class="service_check" value="8" name="Test Service Name">

=>
<input type="checkbox" title="100.00" class="service_check" value="8" name="TestServiceName">

    else if ($(this).not(":checked")) { // you can replace this line with "else {"
        var cls = $(this).attr('name')
        $("li."+cls).remove();
        $(".hidden_service_id, .hidden_service_name, .hidden_service_cost").val("");
    }

DEMO


text:
Q: How to show lambda function return values in Outputs of Cloudformation I am looking for an option to list results of AWS::Lambda::Function in Outputs of Cloudformation.
Following is the snippet of cloudformation template for AWS:Lambda::Function
Resources:
 AthenaLambdaFunction:
    Type: 'AWS::Lambda::Function'
    DeletionPolicy: Delete
    DependsOn:
      - IamRoleLambdaForAthena
    Properties:
      Code:
        ZipFile: |
          import boto3
          import botocore
          import os
          ath = boto3.client('athena')
          def handler(event, context):
              outputBucket = os.environ.get("outputBucket")
              QSTRING = 'select * from tableName limit 10'
              response = ath.start_query_execution(QueryString=str(QSTRING), ResultConfiguration={'OutputLocation': outputBucket})
              s3BucketOut = output_bucket + response['ResponseMetadata']['RequestId']
              return s3BucketOut
      Handler: index.handler
      Runtime: python3.6
      MemorySize: 128
      Role: !GetAtt IamRoleLambdaForAthena.Arn
      Timeout: 30
      Environment:
        Variables:
          outputBucket: !Ref OutputS3Bucket

I want to show the value retuned by lambda function  s3BucketOut in Outputs of Cloudformation. Something like below (off course, the code below doesn't work).
Outputs:
  LambdaFunctionOutput:
    Value: !Ref AthenaLambdaFunction.s3BucketOut
    Description: Return Value of Lambda Function

Any suggestions please. TIA

A: You are half-way through it. With your code, you created the AWS Lambda function that you want to run. Now you need to make this function run on CloudFormation and capture its value. Note that you need to make small changes on your code to allow the value to be captured by CloudFormation.
The full code will be similar to this:
Resources:
  AthenaLambdaFunction:
    Type: 'AWS::Lambda::Function'
    DeletionPolicy: Delete
    DependsOn:
      - IamRoleLambdaForAthena
    Properties:
      Code:
        ZipFile: |
          import boto3
          import botocore
          import os
          import cfnresponse # this needs to be imported for replying to CloudFormation
          ath = boto3.client('athena')
          def handler(event, context):
              outputBucket = os.environ.get("outputBucket")
              QSTRING = 'select * from tableName limit 10'
              response = ath.start_query_execution(QueryString=str(QSTRING), ResultConfiguration={'OutputLocation': outputBucket})
              s3BucketOut = output_bucket + response['ResponseMetadata']['RequestId']
              responseData = {} # added
              responseData['S3BucketOut'] = s3BucketOut # added
              cfnresponse.send(event, context, cfnresponse.SUCCESS, responseData) # return modified
      Handler: index.handler
      Runtime: python3.6
      MemorySize: 128
      Role: !GetAtt IamRoleLambdaForAthena.Arn
      Timeout: 30
      Environment:
        Variables:
          outputBucket: !Ref OutputS3Bucket

  S3BucketOutInvocation:
    Type: Custom::S3BucketOut
    Properties:
      ServiceToken: !GetAtt AthenaLambdaFunction.Arn
      Region: !Ref "AWS::Region"

Outputs:
  LambdaFunctionOutput:
    Value: !GetAtt S3BucketOutInvocation.S3BucketOut
    Description: Return Value of Lambda Function

References:
https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/template-custom-resources.html
https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-lambda-function-code.html

A: What you can do is create what is called a "Lambda-backed Custom Resource" You would use this during Stack creation to get bits of information at creation type.
Further information can be found here
AWS Lambda-backed Custom Resources


text:
Q: Binding a URI to a textbox I have a property which is of type System.URI, and I have it bound to a textbox. This seems to work pretty well, except if I type something like https://stackexchange.com/ it will not let me enter the / because I'm getting:
System.Windows.Data Error: 7 : ConvertBack cannot convert value 'http://' (type 'String'). BindingExpression:Path=webURL; DataItem='ItemViewModel' (HashCode=66245186); target element is 'TextBox' (Name=''); target property is 'Text' (type 'String') UriFormatException:'System.UriFormatException: Invalid URI: The hostname could not be parsed.
   at System.Uri.CreateThis(String uri, Boolean dontEscape, UriKind uriKind)
   at System.Uri..ctor(String uriString, UriKind uriKind)
   at System.UriTypeConverter.ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, Object value)
   at MS.Internal.Data.DefaultValueConverter.ConvertHelper(Object o, Type destinationType, DependencyObject targetElement, CultureInfo culture, Boolean isForward)
   at MS.Internal.Data.SourceDefaultValueConverter.ConvertBack(Object o, Type type, Object parameter, CultureInfo culture)
   at System.Windows.Data.BindingExpression.ConvertBackHelper(IValueConverter converter, Object value, Type sourceType, Object parameter, CultureInfo culture)'

I then tried a converter to convert the URI to a string thinking that was the problem:
public override object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
    Uri input = value as Uri;
    if (input == null) return String.Empty;
    else return input.ToString();
}

public override object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
    string input = value as string;
    if (String.IsNullOrEmpty(input)) return null;
    else return new Uri(input, UriKind.RelativeOrAbsolute);
}

this is even worse because this actually bombs if the URI is not valid.
Is there a way to bind a URI directly to a textbox? or do I just have to use a "proxy" property in my viewmodel to hold the string value. The reason I want to bind directly to the URI is that I have IDataError validation, that is checking the URI for validity which works great.

A: I implemented your converter and it worked, though I didn't have to use the override keyword.
My XAML was:
<Window.Resources>
    <Converter:UriToStringConverter x:Key="UriStringToConverter"/>
</Window.Resources>
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="Auto"/>
    </Grid.RowDefinitions>
    <TextBox Grid.Row="0"
             Margin="5"
             Text="{Binding Url, Converter={StaticResource UriStringToConverter}}" />
    <TextBlock Grid.Row="1"
               Margin="5"
               Text="{Binding Url, Converter={StaticResource UriStringToConverter}}"/>
</Grid>

and the Url property was defined as:
    private Uri url = new Uri("http://example.com");
    public Uri Url
    {
        get { return url; }
        set
        {
            url = value;
            if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs("Url"));
        }
    }

where the class implemented the INofifyPropertyChanged interface.
Note that I had to initialise the Uri with a valid url otherwise it raised an exception. Even if I type in (e.g.) "test" it successfully converts that back to a Uri (albeit an invalid one).


text:
Q: Dynamically loaded user control event subscribing I am having a very hard time subscribing to events in a dynamically loaded user control. It's probably easiest to just look at the code I am having trouble with. Any help is greatly appreciated.
On the parent page I use this method to dynamically load user controls.
 private void LoadMyUserControl(string controlName)
 {
      parent.Controls.Clear();

      // Load the user Control
      UserControl MyControl = (UserControl)LoadControl(ControlName);

      string userControlID = controlName.Split('.')[0];
      MyControl.ID = userControlID.Replace("/","").Replace("~", "");
      Type ucType = MyControl.GetType();

      // Set misc parameters
      PropertyInfo myProp = ucType.GetProperty("MyProp");
      myProp.SetValue(MyControl, "MyVal", null);

      //Dynamically subscribe to user control event
      Type objectType = MyControl.GetType();
      EventInfo objectEventInfo = objectType.GetEvent("updateParent");
      Type objectEventHandlerType = objectEventInfo.EventHandlerType;
      MethodInfo mi = this.GetType().GetMethod("HandledEvent");
      Delegate del = Delegate.CreateDelegate(objectEventHandlerType, this, mi);
      objectEventInfo.AddEventHandler(this, del);

  }

  public void HandledEvent (Object sender, EventArgs e)
  {

  }

My user control has a simple public event like this
  public partial class MyUserControl1 : System.Web.UI.UserControl
  {
         public int MyProp { get; set; }
         public event EventHandler updateParent;
  }

The error I am getting is on the ObjectEventInfo.AddEventHandler line stating "Object does not match target type."
Thanks again in advance for your assistance.

A: If you want to get a generic solution, you could create an abstract user control class with your property and your event. Then MyUserControl1 can inherit from this abstract user control. In your load method you can cast to the abstract user control and use it in an easier way. So you could create some other user controls.

A: Solution #1: Create a common interface.
// IParentControlUpdater.cs
namespace AspNetUserControlDynamicEvent {
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    interface IParentControlUpdater {
        event EventHandler<EventArgs> UpdateParent;
    }
}

// DynamicUserControl.ascx.cs
namespace AspNetUserControlDynamicEvent {
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;

    public partial class DynamicUserControl : System.Web.UI.UserControl, IParentControlUpdater {
        protected void Page_Load(object sender, EventArgs e) { }

        #region IParentControlUpdater Members

        public event EventHandler<EventArgs> UpdateParent;

        #endregion
    }
}

// Default.aspx.cs
namespace AspNetUserControlDynamicEvent {
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;

    public partial class _Default : System.Web.UI.Page {
        protected void Page_Load(object sender, EventArgs e) { }

        private void LoadMyUserControl(string controlName) {
            UserControl control = (UserControl)LoadControl(controlName);

            // Do some stuff

            ((IParentControlUpdater)control).UpdateParent += new EventHandler<EventArgs>(control_UpdateParent);
        }

        private void control_UpdateParent(object sender, EventArgs e) {
            throw new NotImplementedException();
        }
    }
}

Solution #2: Create a base class.
Create a base user control class (ie. DynamicUserControlBase for example).
// DynamicUserControlBase.ascx.cs
namespace AspNetUserControlDynamicEvent {
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;

    public partial class DynamicUserControlBase : System.Web.UI.UserControl {
        protected void Page_Load(object sender, EventArgs e) { }

        // Base event
        public event System.EventHandler<System.EventArgs> UpdateParent;
    }
}

Then in your user control's you want to dynamically create and subscribe the updateParent event:
// DynamicUserControl.ascx.cs
namespace AspNetUserControlDynamicEvent {
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;

    public partial class DynamicUserControl : DynamicUserControlBase {
        protected void Page_Load(object sender, EventArgs e) { }
    }
}

Note how it inherits from DynamicUserControlBase. Now, for your LoadMyUserControl method:
private void LoadMyUserControl(string controlName) {
    DynamicUserControlBase control = (DynamicUserControlBase)LoadControl(controlName);

    // Do some stuff

    control.UpdateParent += new EventHandler<EventArgs>(HandledEvent);
}

private void HandledEvent(object sender, EventArgs e) {
    throw new NotImplementedException();
}

However, if you are only working with one type of control you could just as easily change the boxing on LoadControl to:
WebUserControl1 control = (WebUserControl1)LoadControl(controlName); // example

But it seems as though you are possibly looking at loading many different types of user controls, so the first solution should work fine.
As for your concern via Reflection, try this:
Type type = MyControl.GetType();
EventInfo eventInfo = type.GetEvent("UpdateParent");
EventHandler handler = new EventHandler(HandledEvent);
eventInfo.AddEventHandler(MyControl, handler);


text:
Q: Anchors within the same page not working? I'm trying to link to elements within the HTML of my page, but it's not working and I'm unsure as to why.
Here's the initial link:

About Me

Past

Work

Blog

I'd like all the li's in this list to be links to somewhere else on the page (except the last one).
And at the top of this code is where I'm trying to link to:

Work

BrainDB

BrainDB is a new startup I'm working on with my co-founder, @masonlong. I write everything from Rails to AngularJS and CSS. BrainDB's goal is to augment the mind with useful and inviting services.

SummarizeIt

SummarizeIt is a JavaScript project that I built during a weekend. It utilizes an API for summarizing content, like blog posts, into bit-sized chunks.

Freelance

I freelance from time to time. I work with personal clients, as well as through Elance. I'm available.

Do the areas I link to have to use the section tag? I have multiple of these divs with ul's in them.

A: Hi you have to use 'a id' to be called by 'a href'
Here is the example:
My Works

it will call:
Works

Demo

A: The anchor needs to have the ID or name of Work but you are using it twice.
HTML Tags - links
linked text

(Target point)
a named anchor

A: use anchor tag inside li tag like this.

about

work

blog

something like this
and your link id as below

A: Try This.

Now If You Want To Link it In the Bottom Somewhere.
(Make Sure There Is Not Text here)About Section.

A: I had this issue today. Additional I wanted to smooth scroll to the anchor and that what saved my day. The "issue" can be pointed out to the  tag like @Alexander Goncharov pointed out in his answer.
document.querySelectorAll('a[href^="#"]').forEach(anchor => {
    anchor.addEventListener('click', function (e) {
        e.preventDefault();

        document.querySelector(this.getAttribute('href')).scrollIntoView({
            behavior: 'smooth'
        });
    });
});

I found this solution here

A: It's important. Anchors will not work on all pages, have tag <base> in head (but root page), if href of anchor is page-relative (begins with #).
For example you are on the page:
https://example.com/the/page/
Base tag on page like this:
<base href="https://example.com">

In code of this page there is an anchor:
anchor

With base-tag it'll follow to https://example.com/#anc , not what was expected.
To resolve this issue, you can do one of this:

*

*Use domain-relative anchor.

*Overload anchor click with javascript and swap url to domain-relative.

*Delete base tag - it is often unused.

A: I was having this problem as well (same page navigation using links) and the solution was very easy (though frustrating to figure out). I hope this helps - also I checked IE, Firefox, and Chrome and it worked across the board (as of 05-22-2019).
Your link should looks like this:
Word as link you want people to click

and your anchor should look like this:
Spot you want to appear at top of page once link is clicked

A: In my case, I found this workaround:
Instead of
<base target=_blank>

I put there:
<base href=. target=_blank>

After this modification, the external link to the file jumped to the anchor properly:
http://domainov.us/directorovich/filovskaja.html#anchorovna

A: Just my 2 cents for people having the same issue. Check whether you have another element with desired id on the page. In my case I have already had svg-icon with id="contacts", totally out of my attention, inserted right after  tag as part of svg-sprite. So, my anchor navigation () down the page to another (the second, in fact) element (section header) with the same id seemed not working.

A: Anchors won't work if the page is still loading on some browsers (tested on chrome, edge and brave, seems like a chromium thing)

*

*So if your page is infinitely loading anchors won't work on those browsers.

*Check your JavaScript for anything broken, in my case it was an onload event


text:
Q: Anyone can help to fix this run time error? Using arraylist and trying to get the last element, i am getting some runtime error.
import java.util.ArrayList;

public class MyProgram{

    private ArrayList<String> list = new ArrayList<String>();

    public void printLastThing(){
        int lastIndex = list.size() - 1;
        String thing = list.get(lastIndex);
        System.out.println(thing);
    }

    public static void main(String[] args){
        MyProgram example = new MyProgram();
        example.printLastThing();
    }
}

A: There are no elements added to the list and so it is empty. YOu are trying to fetch the element at -1 which will raise java.lang.IndexOutOfBoundsException.
In this case you should keep a check for going out of bounds.
I have added a method to check the lastindex. It will return -1 if list is emtpy and you can display that List if empty once you get -1.
import java.util.ArrayList;

public class MyProgram{

    private ArrayList<String> list = new ArrayList<String>();

    public MyProgram() {
        list.add("a");
        list.add("z");
    }

    public void printLastThing(){

        int lastIndex = getLastIndex();
        if(lastIndex >= 0)
            System.out.println(list.get(lastIndex));
        else
            System.out.println("List is empty");

    }

    private int getLastIndex() {
       if(list.size()==0) {
           return -1;
       }

       return list.size() - 1;
    }

    public static void main(String[] args){
        MyProgram example = new MyProgram();
        example.printLastThing();
    }
}


text:
Q: Visualisation of equipotential surface - linear charge I am completely new in Mathematica "programming" language.
At the university in Electrodynamics, we have gotten a homework to visualise the equipotential surfaces with function ContourPlot3D.
I have been able to get the matematical expression for such surface,
the equation should be seen on the picture.
My lastest try to write the function has been:
ContourPlot3D[
 log (((L/2 + x) + ((((((L/2) + x)^(2)) + ((y)^(2))))^(1/2)))/((-L/2 +
          x) + ((((((-L/2) + x)^(2)) + ((y)^(2))))^(1/2)))) ==
  0, {x, -2, 2}, {y, -2, 2}, {z, -2, 2}]

or
ContourPlot3D[(
   ln (((1/2 +
          x) + ((((((1/2) + x)^(2)) + ((y)^(2))))^(1/2)))/((-1/2 +
          x) + ((((((-1/2) + x)^(2)) + ((y)^(2))))^(1/2))))) ==
  0, {x, -2, 2}, {y, -2, 2}, {z, -2, 2}]

Although I have resigned on any parameters and only the variables stayed, still I can not plot the function.
Could anyone to look, where I do a mistake. In all cases is the syntax error, that "more input needed", but I don't know, what more I should define.

A: Like N0va said:
Try
Plot3D[((1/2 + x + Sqrt[1/4 + x + x^2 + y^2])/(-(1/2) + x + Sqrt[(-(1/2) + x)^2 + y^2])), {x, -2, 2}, {y, -2, 2}]

or
ContourPlot[((1/2 + x + Sqrt[1/4 + x + x^2 + y^2])/(-(1/2) + x + Sqrt[(-(1/2) + x)^2 + y^2])), {x, -2, 2}, {y, -2, 2}]

to see the potential or the equipotential lines.


text:
Q: How to Optimize query of substring searching in Postgres? I have 2 tables both as the same form
table A : content | text
table B : SubContent | text
Table B containing substring Of Texts in Table A
for exampale:
Table a :

*

*zupta . . for making south africa worse than ever .

*zur eda terkenang arwah ibu . . eda terkenang arwah ibu . .

Table B :

*

*making south africa

*terkenang arwah ibu
what i want to achive is :
making south africa | zupta . . for **making south africa** worse than ever.
terkenang arwah ibu | zur eda **terkenang arwah ibu** . . eda terkenang arwah ibu . .

the query I used is very simple
select subcontent, content from A join B on  content SIMILAR TO '%'||subcontent||'%'

the query explain :
Gather  (cost=1000.00..6611032.19 rows=1678309 width=180)
  Workers Planned: 2
  ->  Nested Loop  (cost=0.00..6442201.29 rows=699295 width=180)
"        Join Filter: (A.content ~ similar_escape((('%'::text || B.subcontent) || '%'::text), NULL::text))"
        ->  Parallel Seq Scan on A  (cost=0.00..8675.79 rows=186479 width=91)
        ->  Seq Scan on B  (cost=0.00..19.50 rows=750 width=89)

i try use Large Text Indexes  follow by this blog (Andrew Kane done a great job! )
https://medium.com/@ankane/large-text-indexes-in-postgres-5d7f1677f89f
i try to add an index on both of the columns  that didn't help the execution takes 40 minutes, any ideas?
explain after using Laurenz Albe answer
Nested Loop  (cost=27.79..100352.93 rows=1678309 width=180)
  ->  Seq Scan on q2_distinct  (cost=0.00..19.50 rows=750 width=89)
  ->  Bitmap Heap Scan on clean_distinct  (cost=27.79..111.40 rows=2238 width=91)
"        Recheck Cond: (A.content ~ similar_escape((('%'::text || q2_distinct.part) || '%'::text), NULL::text))"
        ->  Bitmap Index Scan on "clean_distinct_Post content_idx"  (cost=0.00..27.23 rows=2238 width=0)
"              Index Cond: (A.content ~ similar_escape((('%'::text || B.content) || '%'::text), NULL::text))"

A: Any join that does not have a join condition with an equality operator (=) can only use a nested loop join.
The only index that can potentially help here is a trigram index on A:
CREATE EXTENSION pg_trgm;
CREATE INDEX ON "A" USING gin (content gin_trgm_ops);

But you shouldn't expect to get good execution times with a query like that.

A: Postgres' in-built textsearch functions could help here. But you will need to add a second column to table A to help index it. You will also need to know the language of each string in table A.
Example query.
postgres=# select to_tsvector('english', 'Big cats eat fish on Mondays.')
               @@ phraseto_tsquery('english', 'eat fish on monday') as query;
 query
-------
 t

Note that the pluralisation and capitalisation of Mondays did not stop the match.
Use the to_tsvector function to create a parsed form of your content, which you can use for a GIN index.
postgres=# select to_tsvector('english', 'Big cats eat fish on Mondays.');
               to_tsvector
---------------------------------------------
 'big':1 'cat':2 'eat':3 'fish':4 'monday':6

Note how to_tsvector normalises the string (changing to lowercase, removing punctuation, removing plurals, and removing low value words like "on"). This means "eat fish if monday" would also match (since "if" is also a low value word). So you will need to add a second check using the LIKE operator if you only want an exact match. But this will run far less frequently than it would have without the tsvector GIN index.
So your query would now look like,
SELECT subcontent, content
FROM A
JOIN B ON (
    A.tsv_content @@ phraseto_tsquery(B.lang, B.subcontent)
    AND content LIKE '%' || subcontent || '%'
);

NB. phraseto_tsquery requires 9.6+


text:
Q: Get Row number of excel using ADO We are trying to get the row number of particular recordset retreived based on soome condtion. consider below table
Name    Id
abc     1
cde     2
efg     3

Now, how to get the row number or recordset number of employee "cde" (accrding to below code we need to get the result as 2). Any help on this please.
Const adOpenStatic = 3
Const adLockOptimistic = 3
Const adCmdText = &H0001
strSource="C:\Test.xls"
strConnection = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & strSource          & ";Extended Properties=""Excel 8.0;HDR=Yes;"";"
Set conn = CreateObject("ADODB.Connection")
Set objRecordSet = CreateObject("ADODB.Recordset")
conn.Open strConnection
objRecordset.Open "Select Name FROM [sheet1$] Where Id = 2", conn, adOpenStatic,     adLockOptimistic, adCmdText
msgbox objRecordset.GetString
conn.Close
Set conn = Nothing

A: The best way is to put a column in the Excel file that has the same data as the row number. Then query on that column. That is a fool-proof solution.
However, if for some reason you can't do that, then try this:
Const adOpenStatic = 3
Const adLockOptimistic = 3
Const adCmdText = &H1
Dim RowNumber
Dim SqlStmt

strSource = "C:\Temp\Test.xls"
strConnection = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & strSource & ";Extended Properties=""Excel 8.0;HDR=Yes;"";"
Set conn = CreateObject("ADODB.Connection")
Set objRecordset = CreateObject("ADODB.Recordset")
conn.Open strConnection

SqlStmt = "Select Name, Id FROM [sheet1$]"      ''-- you can optimize this query if your Id is in ascending order. e.g. "Select Name, Id FROM [sheet1$] Where Id <= 4"
objRecordset.Open SqlStmt, conn, adOpenStatic, adLockOptimistic, adCmdText
objRecordset.Find "Id = 4"
RowNumber = objRecordset!ID + 1  ''-- +1 for Header row.
conn.Close
Set conn = Nothing

MsgBox RowNumber


text:
Q: adding c++11 in makefile to remove the error to_string is not declared in this scope I suppose this question is asked in some other threads, I was getting the error while calling make: to_string is not declared in this scope. I found out I have to add c++11 in makefile. But I tried some options mentioned in several threads. Could you provide some solution here? Thanks

A: Adding -std=c++11 to CFLAGS will cause g++ to compile with the C++11 standard. Like this
CFLAGS=-std=c++11 -c -g -O3 -finline-functions -fstack-protector

However, as highlighted in comments the appropriate syntax for compiling C++ programs with a makefile is to use a rule like this
$(CXX) $(CPPFLAGS) $(CXXFLAGS) -c

where your C++ files use the suffix .cc [1]. Then you would add -std=c++11 to CXXFLAGS. The difference between CPPFLAGS and CXXFLAGS is [2]

CPPFLAGS is supposed to be for flags for the C PreProcessor; CXXFLAGS
  is for flags for the C++ compiler.

This would require some rewrites within your makefile, namely
CXX=g++
LD=g++
CXXFLAGS=-c -g -O3 -fstack-protector -I./Eigen

and rules from
$(CC) $(INCLUDE) $(CFLAGS) -c

to
$(CXX) $(CPPFLAGS) $(CXXFLAGS) -c

as above.
The $(INCLUDE) can also be removed from your linking command ($(LD)) as it is only needed during compile time. Your linking command can also be simplified to
ParEGOIteration13: ParEGOIteration13.o Utilities.o WeightVector.o SearchSpace.o DACE.o GeneticAlgorithm.o Matrix.o
    $(CXX) $? -o $@

by using the automatic variables [3]

*

*$? expands to all of the prerequisites

*$@ expands to the name of the target

I'll let you work out how to use the automatic variables in your compilation rules.
Note: I've removed -finline-functions as -O3 (and -O2) turn it on by default with gcc.


text:
Q: Find the volume enclosed by the paraboloid (triple integral) Find the volume enclosed by the paraboloid $x=y^2+2z^2$ and the plane $x=5$
To do this we take $$\int_0^5 \int_{-\sqrt{x}}^\sqrt{x} \int_{-\sqrt{\frac{x-y^2}{2}}}^{\sqrt{\frac{x-y^2}{2}}} \,\mathrm{d}z\,\mathrm{d}y\,\mathrm{d}x$$
Is this correct?
Then using cylindrical coordinates we use substitution $y=r\sin t$, $z=\frac{1}{\sqrt{2}}r\cos t$, so $\mathrm{d}z\,\mathrm{d}y=\frac{1}{\sqrt{2}}\mathrm{d}t\,\mathrm{d}r$, and the limits are $0 \leq r \leq \sqrt{x}$, $0 \leq t \leq 2\pi$, $0 \leq x \leq 5$. Is this correct also?


text:
Q: How to find a prime no without using my function chk prime as i wish to optimize my algo long long int chkPrime(long long int z)
{
    int i;

       if(z==1)
          return 0;

      if(z==2)
           return 1;

       for(i=2;i<=z/2;i++)
             if(!(z%i))
                     return 0;
    return 1;
}

A: If you want to check if a certain number is definitely prime, the fastest (i.e. polynomial runtime) deterministic algorithm is the AKS-test(Wikipedia) afaik.
If you want to create primes for a certain range, you should look at sieving(Wikipedia), or, as I would recommend download them as list from the internet (e.g. here for the first 10000).
The wikipedia article on sieving mentions two good probabilistic primality test, so I will not mention any more. The test does however only say whether a number is a prime with a large probability (so called probable primes).

A: Based on my comment above, here is a more efficient function, although OP wanted to know how to "without using my function".
#include<stdio.h>
#include<math.h>

int chkPrime(long long int z)
{
    long long int i, rootz;
    if (z <= 1)
        return 0;
    if (z == 2)
        return 1;
    if (z % 2 == 0)
        return 0;
    rootz = (long long int)sqrt((double)z);
    for (i=3; i<=rootz; i+=2)
        if (z % i == 0)
            return 0;
    return 1;
}

int main(void)
{
    long long int i;
    for (i=0; i<100; i++)
        if (chkPrime(i)) printf("%5lld ", i);
    return 0;
}

A: Here's what you can do:
1. Determine the prime numbers upto sqrt(MaxN) using seive at the beginning of your program.(you need to calculate this only once)
2. Then each time you call chkPrime do this :
   -- determine sqrt(z)
   -- check if the number can be divided with the primes upto sqrt(z)
   -- if can not be divided then z is a prime number otherwise it is not.

or, if you don't want to generate prime numbers at the beginning then do the following:
   1. determine sqrt(z)
   2. check if the number can be divided with 2
   3. if yes then it's not a prime otherwise goto 4
   4. check if the number can be divided with odd numbers from 3 to sqrt(z)
   5. if yes then it's not a prime otherwise it is a prime number


text:
Q: is there an alternative to fetch_field_direct() when the mysqlnd driver is not available? I was happy with the response I got here: How to fetch field type and value?. It was working fine, I could get the data types as easily as doing what was suggested:
$datatype = $result->fetch_field_direct($count)->type;
where $count was a number that got incremented withing the foreach loop
but then I got to experiment with PDO to prevent SQL injections, and everything was fine (after several bumps in the road, as I don't fully understand PDOs, I admit), until i decided to upload my code to the webserver and then I discovered they don't support the use of mysqld, meaning I can no longer use the get_result function
$result =  $stmt->get_result();
while I found a workaround (posted in the php reference comment section) for the get_result, I'm yet to found a replacement to the fetch_field_direct(), any idea how can I obtain the datatype? maybe the workaround code might help (it's above my level of understanding php, but does a great work to simulate the basic functionality of get_result(). As I can do:
$result = iimysqli_stmt_get_result($stmt);
$proceso = iimysqli_result_fetch_array($result);
...

foreach(array_keys($proceso) as $key){

$datatype = $result->fetch_field_direct($count)->type; // this is no longer working,
//I get error Fatal error: Call to undefined method iimysqli_result::fetch_field_direct()
// It used to work when $result was equal to $stmt->get_result();

... // example line
 echo "<input class='$mysql_data_type_hash[$datatype]' type='hidden' name='$key' value='$proceso[$key]'><br/>";
...

}

I wonder if it's possible have a iimysqli_result_fetch_field_direct() method to overcome not being able to use the standard one. If so, how? (where to begin at least)
Just to make it more clear: I want your help to know if there is a way to expand the workaround I found  in the php reference page so I can get the datatype of a field. Since otherwise, I'm afraid will have to ditch it, and work my way around the fact I can't use the  $stmt->get_result() functionality.
I've read a little  about using $stmt->bind_result(), but it seems a pain to use when one has a lot of fields to deal with, so I would like to avoid it (if possible of course), as the workaround (the code below) is already helping me to get the value (I only need to figure out the data type).

Workaround for get_result() (Not mine, I did not write it, and to be honest I don't fully understand it, but it workds), this is a direct copy of the comment:
<?php
class iimysqli_result
{
    public $stmt, $nCols;
}

function iimysqli_stmt_get_result($stmt)
{
    /**    EXPLANATION:
     * We are creating a fake "result" structure to enable us to have
     * source-level equivalent syntax to a query executed via
     * mysqli_query().
     *
     *    $stmt = mysqli_prepare($conn, "");
     *    mysqli_bind_param($stmt, "types", ...);
     *
     *    $param1 = 0;
     *    $param2 = 'foo';
     *    $param3 = 'bar';
     *    mysqli_execute($stmt);
     *    $result _mysqli_stmt_get_result($stmt);
     *        [ $arr = _mysqli_result_fetch_array($result);
     *            || $assoc = _mysqli_result_fetch_assoc($result); ]
     *    mysqli_stmt_close($stmt);
     *    mysqli_close($conn);
     *
     * At the source level, there is no difference between this and mysqlnd.
     **/
    $metadata = mysqli_stmt_result_metadata($stmt);
    $ret = new iimysqli_result;
    if (!$ret) return NULL;

    $ret->nCols = mysqli_num_fields($metadata);
    $ret->stmt = $stmt;

    mysqli_free_result($metadata);
    return $ret;
}

function iimysqli_result_fetch_array(&$result)
{
    $ret = array();
    $code = "return mysqli_stmt_bind_result(\$result->stmt ";

    for ($i=0; $i<$result->nCols; $i++)
    {
        $ret[$i] = NULL;
        $code .= ", \$ret['" .$i ."']";
    };

    $code .= ");";
    if (!eval($code)) { return NULL; };

    // This should advance the "$stmt" cursor.
    if (!mysqli_stmt_fetch($result->stmt)) { return NULL; };

    // Return the array we built.
    return $ret;
}
?>

A: This was quite simple after all (I guess I just had to have a break to see it)
The workaround found in the php help comments was missing two functions I needed
function iimysqli_result_fetch_assoc(&$result)
function iimysqli_result_fetch_field_direct(&$result, $i)
Here is my implementation of them:
 function iimysqli_result_fetch_field_direct(&$result, $i)
 {
    $metadata = mysqli_stmt_result_metadata($result->stmt);
    return mysqli_fetch_field_direct($metadata,$i);
 }

 function iimysqli_result_fetch_assoc(&$result)
 {
   $ret = array();
   $code = "return mysqli_stmt_bind_result(\$result->stmt ";
   for ($i=0; $i<$result->nCols; $i++)
   {
       $finfo = iimysqli_result_fetch_field_direct($result,$i) ;
       $name =  $finfo->name;

       $ret[$name] = NULL;
       $code .= ", \$ret['" .$name ."']";
   };
   $code .= ");";
   if (!eval($code)) { return NULL; };

   // This should advance the "$stmt" cursor.
   if (!mysqli_stmt_fetch($result->stmt)) { return NULL; };

   // Return the array we built.
   return $ret;
    }

I am not sure this is the optimal solution, but it is working so far for me :)


text:
Q: android LinearLayout scroll too deep I have layout which scrolls too high. It scrolls until reaches an end and even scrolls more up until last 4 lines visible.
So my page stays almost without text - it is too high..
There is my layout:
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent">

<include layout="@layout/title_bar" android:id = "@+id/title"/>
<ScrollView
    android:layout_width="fill_parent"
    android:layout_height="360dp"
    android:layout_below="@id/title"
    >
<TableLayout
    android:layout_width="wrap_content"
    android:layout_height="fill_parent"
    android:layout_gravity="center"
    >

     <TextView android:layout_width="fill_parent" android:layout_height="360dp"/>

   <!-- <TableRow>
        <TextView
            android:paddingBottom="20dp"
            android:layout_span="4"
            android:gravity="center_horizontal"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:textSize="16dp"
            android:text="@string/btn_system_setup"
            />
    </TableRow> -->

        <RadioGroup android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:gravity="left">
            <RadioButton
                    android:id="@+id/test_over_xdsl"
                    android:layout_width="wrap_content"
                    android:text="@string/test_over_xdsl"
                    />
            <RadioButton
                    android:id="@+id/test_over_shdsl"
                    android:layout_width="wrap_content"
                    android:text="@string/test_over_shdsl"
                    />

            <RadioButton
                    android:id="@+id/test_over_eth"
                     android:layout_width="wrap_content"
                    android:text="@string/test_over_eth"/>
        </RadioGroup>

    <TableRow
    >
        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="@string/ip_adress"
            />
        <EditText
            android:gravity="center_horizontal"
            android:layout_width="200dp"
            android:layout_height="wrap_content"
            android:singleLine="true"
            android:id="@+id/ip_adress"
            android:imeOptions="actionDone|flagNoExtractUi">
        </EditText>

        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="@string/netmask"
            android:paddingLeft="20dp"
        />

        <EditText
            android:gravity="center_horizontal"
            android:layout_height="wrap_content"
            android:singleLine="true"
            android:id="@+id/netmask"
            android:imeOptions="actionDone|flagNoExtractUi"
            android:layout_width="200dp">
        </EditText>

    </TableRow>

    <TableRow
    >
        <TextView
            android:text="@string/default_gateway"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
        />

        <EditText
            android:gravity="center_horizontal"
            android:layout_height="wrap_content"
            android:id="@+id/default_gateway"
            android:paddingRight="10dp"
            android:singleLine="true"
            android:imeOptions="actionDone|flagNoExtractUi"
            android:layout_width="200dp">
        </EditText>

        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
             android:paddingLeft="20dp"
             android:paddingRight="10dp"
            android:text="@string/primary_dns"
        />

        <EditText
            android:gravity="center_horizontal"
            android:layout_height="wrap_content"
            android:id="@+id/dns_server"
            android:singleLine="true"
            android:imeOptions="actionDone|flagNoExtractUi"
            android:layout_width="200dp">
        </EditText>

    </TableRow>

    <TableRow
    >
        <TextView
            android:text="@string/secondary_dns"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
        />

        <EditText
            android:gravity="center_horizontal"
            android:layout_height="wrap_content"
            android:id="@+id/secondary_dns_server"
            android:singleLine="true"
            android:imeOptions="actionDone|flagNoExtractUi"
            android:layout_width="200dp">
        </EditText>

    </TableRow>

    <RadioGroup android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:gravity="center">
            <RadioButton
                    android:id="@+id/emulated"
                    android:layout_width="match_parent"
                    android:text="@string/emulated"
                    />

            <RadioButton
                    android:id="@+id/through"
                     android:layout_width="match_parent"
                    android:text="@string/through"/>
        </RadioGroup>

    <RadioGroup
            android:id="@+id/dhcp_radiogroup"
            android:visibility="gone"
            android:paddingLeft="30dp"
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:gravity="center">
            <RadioButton
                    android:id="@+id/dhcp_disabled"
                    android:layout_width="match_parent"
                    android:text="@string/disable_dhcp"
                    android:checked="true"
                    />

            <RadioButton
                    android:id="@+id/dhcp_enabled"
                     android:layout_width="match_parent"
                    android:text="@string/enable_dhcp"/>
        </RadioGroup>

    <TableRow android:id = "@+id/start_stop"
                android:visibility="gone">
        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="@string/ip_adress_start"
            />
        <EditText
            android:gravity="center_horizontal"
            android:layout_width="200dp"
            android:layout_height="wrap_content"
            android:singleLine="true"
            android:id="@+id/ip_adress_start"
            android:imeOptions="actionDone|flagNoExtractUi">
        </EditText>

        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="@string/ip_adress_end"
            android:paddingLeft="20dp"
        />

        <EditText
            android:gravity="center_horizontal"
            android:layout_height="wrap_content"
            android:singleLine="true"
            android:id="@+id/ip_address_end"
            android:imeOptions="actionDone|flagNoExtractUi"
            android:layout_width="200dp">
        </EditText>

    </TableRow>

    <TableRow
    >
        <TextView
            android:text="@string/change_date_time"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
        />
       <TextView
            android:id="@+id/date_time"
            android:text=""
            android:layout_width="200dp"
            android:layout_height="wrap_content"
        />
        <Button
            android:text="@string/set_time_and_date"
            android:layout_column="1"
            android:id="@+id/setTimeButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">
        </Button>

    </TableRow>

    <TableRow
    >
        <TextView
            android:text="@string/change_language"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
        />
       <TextView
            android:id="@+id/language"
            android:text=""
            android:layout_width="200dp"
            android:layout_height="wrap_content"
        />
        <Button
            android:text="@string/set_time_and_date"
            android:layout_column="1"
            android:id="@+id/setLanguageButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">
        </Button>

    </TableRow>

    <TableRow
    >
        <TextView
            android:text="@string/change_country"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
        />
       <TextView
            android:id="@+id/country"
            android:text=""
            android:layout_width="200dp"
            android:layout_height="wrap_content"
        />
        <Button
            android:text="@string/set_time_and_date"
            android:layout_column="1"
            android:id="@+id/setCountryButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">
        </Button>

    </TableRow>

    <TableRow
    >
        <TextView
            android:text="@string/hardware_type"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
        />
       <TextView
            android:id="@+id/hardware_type_text"
            android:layout_width="200dp"
            android:layout_height="wrap_content"
        />

    </TableRow>

    <TableRow
    >
        <TextView
            android:text="@string/hardware_version"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
        />
       <TextView
            android:id="@+id/hardware_version_text"
            android:layout_width="200dp"
            android:layout_height="wrap_content"
        />

    </TableRow>

    <TableRow
    >
        <TextView
            android:text="@string/software_version"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
        />
       <TextView
            android:id = "@+id/software_version_text"
            android:text="@string/the_version"
            android:layout_width="200dp"
            android:layout_height="wrap_content"
        />

    </TableRow>

    <TableRow
    >
        <TextView
            android:text="@string/firmware_version"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
        />
       <TextView
            android:id = "@+id/firmware_version_text"
            android:text="@string/the_version"
            android:layout_width="200dp"
            android:layout_height="wrap_content"
        />
    </TableRow>
</TableLayout>
</ScrollView>

Now I suppose there will be easy solution suggested.


text:
Q: Get output of shell script and store to variable I have a shell command(I'm running it on python) and I want to get its output and store it in a variable. Can you guys help me on how this can be done?
This is my python code...
os.system("unzip -p'" +filepath+"' docProps/app.xml | grep -oP '(?<=\<Pages\>).*(?=\</Pages\>)'"

By the way what it does is it gets the number of page/s of a docx file. It's working but as I've said I don't know how to store it in a variable.
When I do this:
page_number = os.system("unzip -p'" +filepath+"' docProps/app.xml | grep -oP '(?<=\<Pages\>).*(?=\</Pages\>)'"

It doesn't return the right value.
Thank you so much in advance. I tried converting this to a sub-process.call but I also don't know how because I'm a beginner. Thanks again!

A: you can use subprocess to get the output
import subprocess
s=subprocess.Popen("unzip -p'{0}' docProps/app.xml | grep -oP '(?<=\<Pages\>).*(?=\</Pages\>)'".format(filepath),shell=True,stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
for line in s.stdout.readlines():
  print line
s.kill()

A: You can do this with the subprocess module in the Python Standard Library.
import subprocess

command = "unzip -p'" +filepath+"' docProps/app.xml | grep -oP '(?<=\<Pages\>).*(?=\</Pages\>)'"
completed_process = subprocess.run(command, shell=True, text=True, capture_output=True)
output = completed_process.stdout

Please note that if you use shell=True in subprocess.run() and the filepath input is not trusted (e.g. user-provided), you have a security problem, i.e., arbitrary code execution. The same goes for os.system().
See the official documentation for a possible solution using shlex.quote().


text:
Q: External JavaScript to hide/show menu not working I am new to JavaScript and stuck in the first program. When I use the internal JavaScript it is working but not from the external JavaScript file.
JavaScript is not working here. Here I want to use JavaScript to hide and show the menu item, the button in the last element is only for testing.
showMenu(){
  var x = document.getElementById('mainmenu');
  if(x.style.display == "none"){
    x.style.display="block";
  }
  else{
    x.style.display="none";
  }
}

css for the html
body{
  background-color: white;
  margin: 0;
  padding: 0;
}
#topcontact{
  background-color: teal;
  margin: -16px 0;
}
#topcontact p{
  color:white;
  text-align: center;
  padding:10px;
}

header{
  width:100%;
  background-color: white;
}
ul{
  flex-flow: right;
  margin: 0 auto;
  padding: 0;
  width: 80%;
}
ul li{
  display: inline-block;
  list-style: none;
  padding: 15px;
}
ul li:hover{
  background: lightgrey;
}
ul li a{
  text-decoration: none;
  text-transform: uppercase;
}
.toggle{
  width: 100%;
  padding: 10px 20px;
  background: #001f44;
  text-align: right;
  box-sizing: border-box;
  color:#fff;
  font-size: 30px;
  display: none;
}
@media (max-width: 768px){
  .toggle{
    display: block;
  }
  ul {
    width: 100%;
  }
  ul li{
    display: block;
    text-align: center;
  }
}

and this is my html file
<!DOCTYPE html>

    <meta charset="utf-8" name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
    <title>Welcome to JS page</title>
    <link rel="stylesheet" type="text/css" href="assets/css/style.css">
    <link rel="stylesheet" type="text/css" href="assets/css/font-awesome.min.css">

 Home

Services

Education Materials

About us

Contact us

    <button type="button" onclick="document.getElementById('buttonshowing').style.display='block'">Show Data</button>

you clicked show data

A: I think you have included the file incorrectly. You are missing a dot, which represents the current directory.
Use this:

and always declare a function with a function keyword:

function showMenu() {
  var x = document.getElementById('mainmenu');
  if (x.style.display == "none") {
    x.style.display = "block";
  } else {
    x.style.display = "none";
  }
};


text:
Q: How to get street view in google maps? I am developing an application in which i am using maps. I will get the coordinates from the address which the user enters, and display it in the map. But now i want to display only street view in the map.
I tried changing https://www.google.co.in/maps/place/....to https://www.google.co.in/maps/views/....But it did not work.
Can anyone please help me?
Thanks in advance.

A: Uri getmap = Uri.parse("google.streetview:cbll=29.9774614,31.1329645&cbp=0,30,0,0,-15");
Intent mapintent = new Intent(Intent.ACTION_VIEW, getmap);
mapintent.setPackage("com.google.android.apps.maps");
startActivity(mapintent);