text:
Q: Using S3 as a geowebcache blob store I'm having difficulty setting up an S3 bucket as a blobstore through geowebcache.
I have installed geoserver 2.8.2 which has gwc 1.8.1
I am following the docs at http://geowebcache.org/docs/1.8.x/configuration/storage.html#amazon-simple-storage-service-s3-blob-store
My config for the blobstore (with names and keys removed):
  <backendTimeout>120</backendTimeout>
<blobStores>
    <S3BlobStore default="false">
        <id>S3Cache</id>
        <enabled>false</enabled>
        <bucket>bucketName</bucket>
        <prefix>gwc</prefix>
        <awsAccessKey>key</awsAccessKey>
        <awsSecretKey>secretkey</awsSecretKey>
        <maxConnections>50</maxConnections>
        <useHTTPS>true</useHTTPS>
        <useGzip>true</useGzip>
     </S3BlobStore>
</blobStores>

I have geoserver installed through tomcat7 so when I restart the service and watch my geoserver logs I get the following error:
2016-03-02 07:56:22,294 INFO [config.XMLConfiguration] - Configuration file validated fine.
2016-03-02 07:56:22,381 WARN [support.DisposableBeanAdapter] - Invocation of destroy method failed on bean with name 'geoServerLoader': java.lang.NullPointerException
2016-03-02 07:56:22,383 ERROR [context.ContextLoader] - Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'GeoSeverTileLayerCatalog' defined in URL [jar:file:/var/lib/tomcat7/webapps/geoserver/WEB-INF/lib/gs-gwc-2.8.2.jar!/geowebcache-geoserver-context.xml]: Cannot resolve reference to bean 'gwcXmlConfig' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'gwcXmlConfig' defined in URL [jar:file:/var/lib/tomcat7/webapps/geoserver/WEB-INF/lib/gs-gwc-2.8.2.jar!/geowebcache-core-context.xml]: Invocation of init method failed; nested exception is com.thoughtworks.xstream.converters.ConversionException: S3BlobStore : S3BlobStore
---- Debugging information ----
message             : S3BlobStore
cause-exception     : com.thoughtworks.xstream.mapper.CannotResolveClassException
cause-message       : S3BlobStore
class               : java.util.ArrayList
required-type       : java.util.ArrayList
converter-type      : com.thoughtworks.xstream.converters.collections.CollectionConverter
class[1]            : org.geowebcache.config.GeoWebCacheConfiguration
converter-type[1]   : com.thoughtworks.xstream.converters.reflection.ReflectionConverter
version : f22447f59ca37f72bfe6bc746d834b0e73e7c3fc/f22447f59ca37f72bfe6bc746d834b0e73e7c3fc

The error to myself looks like a module is missing, which it might be.  The documentation for the latest versions of geoserver and gwc indicated to me that s3BlobStore functionality is now included.  There used to be an s3 blob store community plugin, but I can't find the download for this, and it looked like this was simply a mod for the geoserver gui to setup an s3 blob where configuration could already be used.
Please could someone point me in the right direction, as to what I might be missing.
EDIT: I've installed Geowebcache 1.8.1 as a standalone, and the config loads correctly and the s3 blob shows in the blobstores.  Now if the integrated geowebcache is different to the standalone, how can you get the s3 functionality included?

A: Geoserver developer confirmed that there was an issue with the nightly build for the S3 plugin http://osgeo-org.1560.x6.nabble.com/geoserver-gwc-s3-plugin-td5253778.html
gwc-S3-plugin now available at http://ares.opengeo.org/geoserver/master/community-latest/
Downloaded, installed, and working as expected.


text:
Q: Have a file input form upload when a user clicks "open" I am wondering if this flow is possible:

*

*Click a button that says "Upload". It is styled very differently from the usual . It does not show the "No file selected" text.

*The usual file browser pops open. The user chooses a file to upload. They click the "open" button in the file browser.

*Upon clicking "open", the file browser is closed (like normal) and the file immediately begins uploading (unlike normal where it requires a submit).

*I detect when the file is finished uploading, and direct to another page.
Here is how I would try to implement it:

*

*Custom CSS on input button - this doesn't seem to hard.

*No changes needed

*Detect when the input value is changed. Once I detect that it has changed, trigger a submit.

*???? How can I detect when a file is finished uploading?

A: If you use a form submit, the file finished uploading when the (likely POST) request is complete.
To trigger the submit when the input value change, use form.submit() in JavaScript.
$('#file_input').change(function() {
    $(this).closest('form').submit();
});

Your server should send back the redirect as a response (e.g. status code 301, 302, 303, etc.).

A: Depends on how you are thinking to implement it. But here's what I did in one of my projects.
Step 1 Uploaded the file using Ajax :
upload file using jquery ajax
How to upload a file using jQuery.ajax and FormData
Google
Step 2 On upload finish, my server-side script returns a JSON - Depends on what server-side language you're using.
Step 3 I parse that json to see if the upload was successful and then take necessary steps

redpajama_set_name: RedPajamaStackExchange


text:
Q: selective routing through a VPN tunnel The problem: after establishing an IPsec VPN tunnel all traffic is routed to the remote endpoint, while I only need to route the packets destined to that internal network and still be able to access the internet on my local machine. Currently, when I enable the according VPN connection - all connectivity drops, meaning it's not possible to reach this machine over my LAN or access the internet through it (there is a restriction on the remote end for further WAN forwarding). So, only the VPN works in this case.
The topology: http://i.imgur.com/9HEru.png
I'm using OpenSwan on a Debian-based distro and also behind NAT (traversal enabled).
Here are the details of ipsec.conf:

version   2.0
config setup
    plutodebug="none"
    plutoopts="--perpeerlog"
    plutoopts="--interface=wlan2"
    dumpdir=/var/run/pluto/
    nat_traversal=yes
    virtual_private=%v4:10.196.0.0/17,%v4:!192.168.1.0/24
    oe=off
    protostack=netkey
conn z
      authby=secret
      keylife=1h
      pfs=yes
      auto=add
      phase2alg=aes128-sha1;modp1024
      keyingtries=3
      ikelifetime=8h
      type=tunnel
      left=192.168.1.76
      leftsubnet=0.0.0.0/0
      leftprotoport=0/0
      right=y.y.y.y
      rightsubnet=0.0.0.0/0
      rightprotoport=0/0

Here are partial details of ifconfig:

wlan0     Link encap:Ethernet  HWaddr 00:13:02:46:42:8d
            UP BROADCAST MULTICAST  MTU:1500  Metric:1
            RX packets:0 errors:0 dropped:0 overruns:0 frame:0
            TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
            collisions:0 txqueuelen:1000
            RX bytes:0 (0.0 B)  TX bytes:0 (0.0 B)
wlan2     Link encap:Ethernet  HWaddr 94:0c:6d:8d:28:0f
            inet addr:192.168.1.76  Bcast:192.168.1.255  Mask:255.255.255.0
            inet6 addr: fe80::960c:6dff:fe8d:280f/64 Scope:Link
            UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
            RX packets:125221 errors:0 dropped:0 overruns:0 frame:0
            TX packets:89332 errors:0 dropped:0 overruns:0 carrier:0
            collisions:0 txqueuelen:1000
            RX bytes:151498702 (151.4 MB)  TX bytes:18233148 (18.2 MB)

Here are the details of route -n:

Kernel IP routing table
  Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
  0.0.0.0         192.168.1.254   0.0.0.0         UG    0      0        0 wlan2
  169.254.0.0     0.0.0.0         255.255.0.0     U     1000   0        0 wlan2
  192.168.1.0     0.0.0.0         255.255.255.0   U     2      0        0 wlan2

As you can see - the machine is connected over WiFi on wlan2 and this is the interface that is taking part in the VPN setup. So, what would you suggest doing, in order to solve the problem of losing internet access after enabling the tunnel? Thank you.

A: This is the problem:

rightsubnet=0.0.0.0/0

with this line you tell openswan that the endpoint of the tunnel is "everything", so all packets are routed through the vpn.
Replace 0.0.0.0/0 with the network(s) you want to reach behind the gateway. The config on the client and server has to match, so edit both.


text:
Q: osx 10.9 monitor arrangement issue, laptop is the larger display Tiered of these strange issues, why my MacBook 10.9 ( started with .1 now I'm at .5 ) think that my laptop monitor is the external desktop monitor ?
The laptop has a high resolution and everything, and the desktop display has huge fonts ..
This is not a signal issues or anything, i see both screens just fine.
(1)
When going to the System Preferences -> Display -> Arrangement, I click on the bigger-wide screen blue box and both monitors flash with red square. while clicking on the small blue box - only the desktop display has the red square ...
(2) At work - it works just fine, but at home ( Sumsung SyncMaster B2430 ) it happens...
Google didn't help ...
I'll give it a shot here ... :/ thanks in advance.

A: Replacing the VGA cable entirely helped ... strange, because it works just fine on another PC ...
Read some post which says that Mac has some profile for every cable, changing the cable, creates a new profile.


text:
Q: Excel export does not work only on Chrome browser Client: Chrome Version 41.0.2272.89 m
ContentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
Excel export used to work till last Chrome update. It works well on Firefox and IE. When I hit export, a file with no extension downloads. If I manually change extension of this file to .xlsx then it opens in excel.

A: For now, adding ".xlsx" extension to file name helped. Please leave comment in case of a better solution. Thanks.
public virtual ActionResult Download(string fName) {
    var fileStream = Session[fName] as MemoryStream;
    Session[fName] = null;
    return File(fileStream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "ExcelExport.xlsx");
}


text:
Q: Unit packagekit.service is masked When I update my system using apt update or try to install a new package with aptitude or apt, I receive this error :
Error : GDBus.Error:org.freedesktop.systemd1.UnitMasked : Unit packagekit.service is masked.

I tried this Cannot restart samba, samba.service is masked. This does not fix my problem. I also researched but can't find anything about this problem.
When I run the commands:
 Unit unit.service does not exist, proceeding anyway.

I use Ubuntu Budgie 17.10 - 64 Bit.

A: Try the following commands in a terminal:
sudo systemctl unmask packagekit.service
sudo systemctl start packagekit.service

Then reboot.


text:
Q: How to declare a template function taking a template template parameter with a known template argument type? I have the following two functions:
class Leaf {...};
void SpitLeaves(std::string & sdata, std::vector<Leaf> const & leaves);
void SpitLeaves(std::string & sdata, std::set<Leaf> const & leaves);

The definition of these functions is identical.
It's an obvious candidate for templatizing the function.
However, despite a search, I cannot figure out how to properly declare the template function.  From https://stackoverflow.com/a/4697356/368896 and others, I have tried signatures such as:
template <template<typename> class T>
void SpitLeaves(std::string & sdata, T<Leaf> const & leaves)
{...}

However, this gives a compiler error at the point I attempt to instantiate the template function:
std::string leaves_str;
std::vector<Leaf> leaves;
SpitLeaves<std::vector>(leaves_str, leaves);

... The error (VS 2013) is 'SpitLeaves' : template parameter list for class template 'std::vector' does not match template parameter list for template template parameter 'T'.
How do I properly declare the above template function?

A: In C++11, you can use a variadic template template parameter:
template <template<typename...> class T>
void SpitLeaves(std::string & sdata, T<Leaf> const & leaves)

Now the compiler won't care how many template parameters can be taken by T, as long as T<Leaf> can be instantiated.
If you actually want to support a container with zero or more extra explicit template parameters, such as a custom allocator, you can do so:
template <template<typename...> class T, typename... TX>
void SpitLeaves(std::string & sdata, T<Leaf, TX...> const & leaves)

A: You can go with:
template<typename Container>
void SpitLeaves(std::string & sdata, Container const & leaves) { ... }

Call it like this:
std::vector<Leaf> leaves;
SpitLeaves("leaves", leaves); // template argument not necessary

The problem with your template template approach is that containers may take more than just one argument. For example vector takes two: the type of elements to store and the allocator to use. So in order to work you need this:
template< template<typename,typename> class T, typename A >
void SpitLeaves(std::string & sdata, T<Leaf,A> const & leaves) { ... }

If you use a generic type Container, you can just use the container and the compiler will complain if it is not compatible with your function.

A: std::vector and std::set have more than 1 template argument.
So you should use something like:
template <template<typename...> class C, typename ... Args>
void SpitLeaves(std::string & sdata, const C<Leaf, Args...>& leaves)

An other approach is to take the container, and use SFINAE to restrict to correct type:
template <typename C>
typename std::enable_if<std::is_same<Leaf, typename C::value_type>::value>::type
SpitLeaves(std::string & sdata, const C& leaves)


text:
Q: My java class implementation of XOR encryption has gone wrong I am new to java but I am very fluent in C++ and C# especially C#. I know how to do xor encryption in both C# and C++. The problem is the algorithm I wrote in Java to implement xor encryption seems to be producing wrong results. The results are usually a bunch of spaces and I am sure that is wrong. Here is the class below:
public final class Encrypter {

    public static String EncryptString(String input, String key)
    {

        int length;
        int index = 0, index2 = 0;
        byte[] ibytes = input.getBytes();
        byte[] kbytes = key.getBytes();
        length = kbytes.length;
        char[] output = new char[ibytes.length];
        for(byte b : ibytes)
        {
            if (index == length)
            {
                index = 0;

            }
            int val = (b ^ kbytes[index]);
            output[index2] = (char)val;
            index++;
            index2++;
        }

        return new String(output);
    }
    public static String DecryptString(String input, String key)
    {
        int length;
        int index = 0, index2 = 0;
        byte[] ibytes = input.getBytes();
        byte[] kbytes = key.getBytes();
        length = kbytes.length;
        char[] output = new char[ibytes.length];
        for(byte b : ibytes)
        {
            if (index == length)
            {
                index = 0;

            }
            int val = (b ^ kbytes[index]);
            output[index2] = (char)val;
            index++;
            index2++;
        }

        return new String(output);
    }
}

A: Strings in Java are Unicode - and Unicode strings are not general holders for bytes like ASCII strings can be.
You're taking a string and converting it to bytes without specifying what character encoding you want, so you're getting the platform default encoding - probably US-ASCII, UTF-8 or one of the Windows code pages.
Then you're preforming arithmetic/logic operations on these bytes. (I haven't looked at what you're doing here - you say you know the algorithm.)
Finally, you're taking these transformed bytes and trying to turn them back into a string - that is, back into characters. Again, you haven't specified the character encoding (but you'll get the same as you got converting characters to bytes, so that's OK), but, most importantly...
Unless your platform default encoding uses a single byte per character (e.g. US-ASCII), then not all of the byte sequences you will generate represent valid characters.
So, two pieces of advice come from this:

*

*Don't use strings as general holders for bytes

*Always specify a character encoding when converting between bytes and characters.

In this case, you might have more success if you specifically give US-ASCII as the encoding.  EDIT: This last sentence is not true (see comments below). Refer back to point 1 above! Use bytes, not characters, when you want bytes.

A: If you use non-ascii strings as keys you'll get pretty strange results. The bytes in the kbytes array will be negative. Sign-extension then means that val will come out negative. The cast to char will then produce a character in the FF80-FFFF range.
These characters will certainly not be printable, and depending on what you use to check the output you may be shown "box" or some other replacement characters.


text:
Q: ESO basic game: what are the regions I can't access? Got a bunch of treasure maps and it's annoying how it's not immediately clear which I have access to from the base game. I don't buy any additional dlc as a rule of thumb.
I think Murkmire, Vvardenfell and Hew's Bane are off limits and I can ditch those treasure maps. Any others? Pet hate games that try to lead you into blocked content like that, same with jewelry crafting.

A: A fully correct answer depends on when you bought the game.
For example, if you bought the base game after the Summerset release in May 2018, then these are the zones you would have to purchase as Crown Store DLC:

*

*Gold Coast

*Imperial City

*Morrowind/Vvardenfell

*Murkmire

*Orsinium/Wrothgar

*Clockwork City

*Hew's Bane

You can find out which zones are separate purchases by going to the Crown Store and looking at the DLC.


text:
Q: layoutSubviews or constraints? I'm new to programming with Xcode (and Obj-C or Swift) and my question is:
Are there any disadvantages to using layoutSubviews and then programmatically positioning the controls instead of just applying constraints to the controls when they are created?
In my case I have a view with 80 UILabels that get positioned and sized equally in a 16x5 grid
I did have a working view made with interface builder but there were a LOT of constraints to get the layout I wanted and it slowed down the entire view controller

A: Bottom line - do what's fast. I'd tend toward the programmatic approach in something like that. Then again, you'd probably be better off doing a CollectionView, and letting the layout be handled by that. The FlowLayout will handle a grid no problem.


text:
Q: Deleting original photos from iPhone I am out of space on my iPhone, and want to delete photos after moving them to a laptop folder.
I can't do this from the Photos app, because the iCloud update seems to have hung on either a corrupt image file or one that is so big it takes more than ten hours to upload.
I thought the solution would be to Browse them with GraphicConverter but not only is something keeping it from viewing all photos, it is showing the originals of photos that have been edited on the iPhone (along with the edited version.)
I would like for the originals of edited photos to go away.  If I hit "Done" instead of "Cancel," that means I like my edits and have NO reason to waste space on the original.
Is there some arcane secret way to get rid of the pre-edit version?
I cleared out the deleted items on the phone, so that's not where they're coming from.

A: Use Image Capture to access the photos on your iPhone, move them to your laptop, then delete them. You can even delete the photos from the iPhone from within Image Capture itself.


text:
Q: Cluster shared disk available checked failed I'm doing sql cluster and I'm getting the following error:-

cluster shared disk available checked failed error

And with the following warnings below thereby preventing me from continuing the installation

*

*Microsoft cluster service(MSCS)

*Cluster verification error

*Window firewal.

A: I know its quite an old question, but I stumbled on this while doing cluster configuration myself. Now when I found the reason for such issue I thought I should post it here so that people like me could find the solution.
So the reason this validation fails at the time of SQL server cluster Installation that the only shared disk drive configured in windows cluster gets added by default in quorum, due to which the disk can not be shared (that's what SQL server thinks, also try running windows server cluster validation that will also fail).
So to overcome this problem make sure that shared drive is not added before configuring the windows cluster.
the order of installation should be

*

*Install Windows Cluster on all the nodes (Ignore storage validation)

*Configure iSCSI drive on all nodes

*Add iSCCI drive in Windows cluster

*Install SQL server cluster (by this time the SQL validation failure should not appear)

I followed the following post which has all steps individually documented
https://sqlserverscribbles.com/2013/06/17/how-to-install-cluster-in-windows-2008-and-windows-2012/


text:
Q: Jquery - dynamically add fields and multiplication of the values This is my code below.
One can dynamically add fields by clicking 'Add More' button & also can remove the fields if required.
I need to multiply input values and to get the Grand Total of the results of multiplication of successive fields.
How can i achieve this in Jquery?

    <form name="form" >

    <select name="size[]" id="box1">
    <option value="20">20</option>
    <option value="35">35</option>
    <option value="50">50</option>
    <option value="100">100</option>
    </select>
    x
    <input name="qty[]" id="box2"  type="text" value="" />
   = <input name="multiply[]" id="answer" type="text" value="" />
       Add More

        <input type="submit" value="Submit" />
        </form>

        Grand Total: 0.00

Click here for Working Example!

A: So here is what you must do:
1) Instead of using id attribute, it would be better to use class attribute for easier jQuery..

<select name="size[]" id="box1" class="box1">
<option value="20">20</option>
<option value="35">35</option>
<option value="50">50</option>
<option value="100">100</option>
</select>
x
<input name="qty[]" id="box2" class="box2" type="text" value="" />
= <input name="multiply[]" id="answer" class="answer" type="text" value="" />

Note: Don't forget to change your Add More function..
2) Here is how you calculate the total, that is triggered by either changing the <input> or <select>

function calTotal(){
    var total = 0;
    $(".my-form .text-box .answer").each(function(){
        total += Number($(this).val());
    });
    $(".GrandTotal").text("");
    $(".GrandTotal").text(total);
}
$(".my-form").on('input', '.box2', function(){
    var total_row = $(this).val();
    total_row *= $(this).siblings(".box1").val();
    $(this).siblings(".answer").val(total_row);
    calTotal();
});
$(".my-form").on('change', '.box1', function(){
    var total_row = $(this).val();
    total_row *= $(this).siblings(".box2").val();
    $(this).siblings(".answer").val(total_row);
    calTotal();
});

Check out this Fiddle..


text:
Q: Why are png files not appearing in html I have a logo that i am trying to make appear in my html page. For some reason it wont appear on my webpage. When i loud my webpage all i see is a square box with an x on it were the picture should be.

  <img src="/images/DigitalMonster-logo.png" />

That is the code im using to have the picture display from my hard drive. Any reason why it wont show up on my website? Also if you need the full html code let me know i will provide it thankyou.

A: You need to check if the web navigator is getting the image back, if you are using chrome press ctrl+shift+i and go to Network tab, than reload your page if you are getting status 200 for /images/DigitalMonster-logo.png that means that the web navigator is receiving the image but not showing it,
if status is 404 that means that the path to the image is incorrect

A: Path /images/DigitalMonster-logo.png assumes you have images directory in very top of Document Root (absolute path).  if you will change /images/DigitalMonster-logo.png to images/DigitalMonster-logo.png, this will assume your images directory is in current working directory, (relative path).

A: Check this steps its working for me:

*

*Right click on the image and select properties

*Then if you find an option "unblock" then click on it
(sometimes computer blocks some images, hence on the google chrome or internet explorer it won't display)

*Check the following details are correct
a)syntax of html
b)path name
c)file name
d)extension of image

sample syntax:

Example:
Here
"E" is the drive name
"Web_development" is the folder name
"baby" is image name
"png" is extension name
I think "/" is not correct
try this: "\" symbol

A: If the images folder is in the same directory as your html file then your path will be images/DigitalMonster-logo.png instead of /images/DigitalMonster-logo.png

A: *

*Open your image in web browser

*Copy image path from web browser

*Paste it in your code(inside src)


text:
Q: When to use Depth-first search So I want to sort a range of numbers so that the sum of every sequential number is a squared number (4,9,16,25,...) I was told I should use Depth first search but am unable to implenment it correctly, especialy the backtracking part. Is this the correct way to do this, what am I not seeing, doing wrong? Is DFS even the correct way to do this?
class Node:                         #Define node Object
    def __init__(self, value):
        self.value = value         #Node "Name"
        self.adjacentNodes=list()  #Node Neighbours

#Set limit
limit=16
squares=list() #list for squared numbers in rang smaller than 2Xlimit
tree=list() #Tree containing nodes
path=list() #current path taken

def calculate(limit):   #Population control legal squares
    for i in range(1,(limit+1)):
        i=i*i
        if i<(limit+limit):
            squares.append(i)

calculate(limit)    #Populate squares list

for a in range(1,(limit+1)): #creating the nodes
    newnode=Node(a)
    for s in squares:
        legalsum=s-a
        if legalsum>0 and legalsum<limit and legalsum!=a: #zero and lower can't play,keeping non-exiting nodes out of node.adjacentNodes, don't connect to selve.
            newnode.adjacentNodes.append(legalsum)  #Add adjacentnode
    tree.append(newnode)    #add newborn to tree

for b in range(0,limit):
    print tree[b].value,tree[b].adjacentNodes #Quick checkup
#Now the tree is build and can be used to search for paths.
'''
Take a node and check adjnodes
is it already visited? check path
yes-> are all nodes visited (loop over tree(currentnode).adjnodes) Maybe use len()
        yes->pop last node from path and take other node -> fear for infinte loops, do I need a current node discard pile?
        no -> visit next available adje node next in line from loop got from len(tree.adjn)
no-> take this as node and check adj nodes.

'''
def dfs (node):
    path.append(node)
    #load/check adjacent nodes
    tree[node].adjacentNodes
    for adjnode in tree[node-1].adjacentNodes:
        if adjnode in path:
            #skip to next adj node
            continue

        else:
            print path #Quick checkup
            dfs(adjnode)
dfs(8)    # start with 8 since 1-16 should be {8,1,15,10,6,3,13,12,4,5,11,14,2,7,9,16}

A: I have no idea what you are talking about with the squares but here are some problems
def dfs (node):
    #always assume the path starts with this node
    path=[node]
    if node == GoalState: return path #we win!!
    #load/check adjacent nodes
    #this line did nothing `tree[node].adjacentNodes`
    for adjnode in tree[node-1].adjacentNodes:
    # if adjnode in path: ****this will never be true, lets eliminate it
    #         #skip to next adj node
    #        continue

    #   else:
            subpath = dfs(adjnode)
            if subpath and subpath.endswith(GoalState):
               return path + subpath #return solution

    #if we get here there is no solution from this node to the goal state


text:
Q: get form values from one php "echo" to the other i want get the values of form in other php file but i am getting only one input value as the name are same in loop....How to get all the input values with the same name or if i have to change the name tell me how? and how to get it in other php file
<?php

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

    //getting values of number of MCQ questions and true/false questions
    $mcq = $_POST['mcq'];
    $truefalse = $_POST['truefalse'];
    $number = 1;

    echo '<form action="finalquestions.php" method="post">';

    //loop to get inputs of mcq as many as the user posted
    for($i=1;$i<=$mcq;$i++){
        echo 'Question:'.$number.'<input type="text" name="question1" />

';
        echo '<input type="radio" name="radio1"> <input type="text" name="radiooptions" />

              <input type="radio" name="radio1"> <input type="text" name="radiooptions" />

              <input type="radio" name="radio1"> <input type="text" name="radiooptions" />

              <input type="radio" name="radio1"> <input type="text" name="radiooptions" />
';
        echo '

';
        $number++;
    }

    //loop to get inputs of truefalse as many as the user posted
    for($i=1;$i<=$truefalse;$i++){
        echo 'Question:'.$number.' <input type="text" name="question2" />

';
        echo '<input type="radio" name="question2">True

              <input type="radio" name="question1">False
';
        echo '

';
        $number++;
    }
}

?>

<!DOCTYPE html>

<title>WebQuiz Generator</title>

<input type="submit" name="submit" value="Generate Quiz" />

</form>


text:
Q: Cast operator in C : () or (int)? I'm reading The C Programming Language II and in the operator precedence table they show the cast operator as (type), so it make me bothered.

Is the cast operator just () like a function operator or it includes the types as a whole like (int), (float) ...?
And if so, does it mean that I can declare a new operator by myself with typedef?

A: Type-casting is done through (type), where type is either a native type like int or char *, or a type-alias created through typedef.
Function-calling is done through the () operator.
They might look similar, but are very different, and are of course placed at different places. For example (type) expression is a type-cast, while expression() is a function call. You can of course combine the cast and the call operators like (type) expression() which means that you call a function and then cast the returned value of the function.
If you're wondering about the last, the mixed casting and call expression, it's because function calling have higher operator precedence than casting, so the call will happen first.

A: C is a bit confusing here, as there are several operators that use the same syntax but have different meaning depending on context. To make things even worse, the same syntax could be used for things that aren't even operators. This is particularly true for (), which is used all over the C language.
() could mean one of the following:

*

*A parenthesized expression. This is a so-called primary expression, which is the fancy word for basic stuff that make precedence over all operators.

*The cast operator. There is only one cast operator for all types. You cannot re-define the meaning of operators in C (but you can in C++, through operator overloading).

*The function call operator.

*Part of a compound literal declaration.

*Or it could be part of a statement, a function declaration, function-like macro declaration/call, part of certain variable declarations etc etc. It is simply part of the core language syntax and appears here and there.

A: This is used for calling the function and declaring function for type casting also.
Function example:
public void show(){
  printf("this is function");
}

... in type casting
float a= 1.22;
in b = (int)a;

A: () is only valid in combination with a function name before it, is is a function call expression (an empty one, meaning you call the function with no parameters)
Like this:
#include <stdio.h>

int main(void)
{
int bar = foo(); // foo is called with no parameters
printf("bar:%d",bar);
return 0;
}

int foo(void) {
return 3;
}

Casting however is done by using a Type expression inside brackets (either a native type or one defined via typedef), like for instance in this:
#include <stdio.h>

int main(void) {
int foo = (int) 19.21;
printf("foo = %d", foo); // Will print 19 because 19.21 (double literal) was cast to int
return 0;
}


text:
Q: If $a>b>0$, find the minimum value of $a+\cfrac{1}{(a-b)b}$ If $a>b>0$, find the minimum value of $a+\cfrac{1}{(a-b)b}$
I am clueless on how to simplify the expression $a+\cfrac{1}{(a-b)b}$.
My book gives as a hint to rewrite the given expression so that there's an $a-b$ in a numerator ,which can be then canceled with the denominator when AM-GM is applied,however I don't see how to do that.

A: Let $a-b=c$. So we are looking at $b+c+\frac{1}{cb}$. By AM/GM this is $\ge 3$. The value $3$ is attained when $b=c=1$.
Remark: If we don't want to introduce $c$, we can rewrite our expression as $(a-b)+b+\frac{1}{(a-b)b}$. This feels less natural.


text:
Q: CakePhp 3 - save associated model failed and ended in mysql error i have a question about saving associated data with CakePhp 3. Unfortunately I can't figure out what's the problem is. My scenario is very easy. I want to save the following request-data:
$data = [
    'name' => 'article 1',
    'comments' => [
        (int) 0 => [
            'description' => 'comment 1'
        ]
    ]
]

In this case. I want to save a new article-entity with a new comment-entity. So for both entities it's a new record in the table. So there's is the articles-table and a comments-table where each comment has a connection to the article-table.
ArticlesTable.php
    $this->hasMany('Comments', [
        'foreignKey' => 'article_id'
    ]);

CommentsTable.php
$this->belongsTo('Articles', [
    'foreignKey' => 'article_id',
    'joinType' => 'INNER'
]);

Patched Article
$article = $this->Articles->patchEntity($article, $data, [
    'associated' => [
        'Comments'
    ]
]);

Debug Print - Patched Article
object(App\Model\Entity\Article) {

    'name' => 'article 1',
    'comments' => [
        (int) 0 => object(App\Model\Entity\Comment) {

            'description' => 'comment 1',
            '[new]' => true,
            '[accessible]' => [
                '*' => true
            ],
            '[dirty]' => [
                'description' => true
            ],
            '[original]' => [],
            '[virtual]' => [],
            '[errors]' => [],
            '[invalid]' => [],
            '[repository]' => 'Comments'

        }
    ],
    '[new]' => true,
    '[accessible]' => [
        '*' => true
    ],
    '[dirty]' => [
        'name' => true,
        'duration' => true,
        'comments' => true
    ],
    '[original]' => [],
    '[virtual]' => [],
    '[errors]' => [],
    '[invalid]' => [],
    '[repository]' => 'Articles'

}

SQL Error:

Error: SQLSTATE[42000]: Syntax error or access violation: 1064 You
  have an error in your SQL syntax; check the manual that corresponds to
  your MySQL server version for the right syntax to use near 'description,
  created, modified) VALUES (3, 'comment 1', '2017-05-22 20:36:59', '2017-05-22
  20:3' at line 1

SQL Query:
BEGIN
INSERT INTO articles (name, created, modified)
VALUES
  (
    'article 1', '2017-05-22 20:36:59',
    '2017-05-22 20:36:59'
  )
INSERT INTO comments (
  article_id, description, created, modified
)
VALUES
  (
    3, 'comment 1', '2017-05-22 20:36:59', '2017-05-22 20:36:59'
  )
ROLLBACK

Here's super detailed all the stuff what I'm doing. I am just confused cause as far as I remember this is the way how I normally do it all the time in Cakephp 3. Sorry to ask such a simple question. I just can't figure it out. So do I miss something here? Can someone see my fault?

A: You shouldn't need to write SQL queries for simple entity insertion in cakephp3, please have a look at https://book.cakephp.org/3.0/en/orm/saving-data.html
In your articles add action you should use $this->Articles->save();
if $this->request->is('post') {

    $article = $this->Articles->newEntity($this->request->data());

    $this->Articles->save($article);

}


text:
Q: Message Queue slow performance I am writing a message queue, but it is functioning slow, the method processFile taking too much time, and files get stuck in queue for long time. How to avoid it.
    System.out.println("Message Reader Started....");
    do
    {
        String directoryPath = "C:\\Queue";
        int fileCount = new File(directoryPath).list().length;
        if (fileCount < 1) {
            System.out.println("Files Not Present");
        }
        else
        {
            File[] file = new File(directoryPath).listFiles();
            String firstFile = file[0].getAbsolutePath();
            processFile(firstFile);
        }
    } while (true);

A: have you tried using concurrency for this? its an apt problem for concurrent processing. Assuming that file processing is a mutually exclusive action:

*

*the do while loop in main Thread finds the file to read

*process file is delegated to an executor thread for processing

*and after processing (I am assuming reading the file) the processing of the contents can again be done in parallel. Its like read first 1000 lines and delegate to a thread to process.

You need to design it in a better way to run fast. A single threaded read and process list of files is bound to run slow.

A: Your main issue is possibly CPU usage used for scanning the folder.
You should add Thread.sleep(100); at the end of the loop to give the system some time to breathe.
The issue you want to have resolved is obviously the processFile() method. You should do as it was commented by @Nazgul and implement it in it's own class with a Runnable interface.
To limit the amount of threads running, place the filename in a List or Queue and implement a Thread working on the List. You can add as many worker threads as your system can handle. The queue should be synchronized, so that you can safely remove items from multiple threads at the same time.

A: You wrote an endless loop, so why do you worry how long a single iteration takes?
You're needless reading the directory twice per iteration. Assuming your processFile removes the file processed (and possible another thread or process adds some files, but deletes none), you don't need to read the directory in each iteration.
Read it once and process all files found. If there's none, then re-read the directory. If there's still none, then you may terminate or sleep for a while (or consider watching the directory, but this is a bit more complicated and probably not necessary).
I'd strongly suggest to improve your loop before you start playing with treads (then use ExecutorService as suggested).


text:
Q: What are the roots of the word "manger"? In Marxist Economics: A Popular Introduction to The Three Volumes of Karl Marx's Das Kapital," Ernest Untermann says this about the origin of a word:

The old English word manger, a term synonymous with "dealer," is
  descended from an old Aryan root meaning "to deceive," and it requires
  no deep penetration to realize that the cattle and horse trader of
  primitive times is the forbear of the modern horse swappers.

This is a pretty remarkable statement, but there isn't any reference, and I couldn't find any supporting evidence that this is true online. I'm also guessing "manger" may have been a typo and he meant "manager," that would make more sense in the topic of the book, but even then I'm not sure, so I figured this would be a good place to ask. This book was published in 1907 in Chicago. Would appreciate if anyone can help suss out if what this might mean or if there's any truth in these statements.
Thanks.

A: To begin with, I should note that when Untermann says the word is descended from an Aryan root, he is referring to what we would nowadays call Indo-European. The Aryan languages are a sub-branch of the Indo-Aryan or Indo-Iranian languages, one of the main branches of Indo-European; but back then, it was sometimes used for the family as a whole.
It seems almost certain that he is talking not about the word manger (a trough for horses or cattles), nor manager, but rather monger, which does indeed mean a dealer or a salesman.
The Old English word for a monger was not quite manger as Untermann put it, but rather mangere, at least in all the dictionaries I've been able to find it in, such as Bosworth's. It's quite possible manger was a known variant as well, though.
Manger does not have an altogether certain etymology further back than Proto-Germanic, where it originates in the verb *(ga-)mangō(ja)n-. Etymonline and Wiktionary both connect this verb to the Latin noun mangō 'dealer, (slave) trader', connected to mangōnium 'displaying of wares', which in turn they suppose was borrowed from Ancient Greek μάγγανον (mánganon), which refers to a "means of charming or bewitching others".
This is a somewhat roundabout etymology, hinging on the notion that traders trying to trick their customers by embellishing and cheating with their wares goes back to antiquity. I do believe this is true, but there is no actual evidence that it gave rise to this development of meanings here.
Another possibility is that given in Guus Kroonen's Etymological Dictionary of Proto-Germanic, which takes *(ga-)mangōjan- to be a derivation from the abstract noun *ga-manga- from the weak verb *mangjan- 'mingle, mix', which is not attested outside Northwest European (that is, Germanic and Balto-Slavic).
The development here would be:

*

*Base verb *mang-jan- meaning 'mix, mingle'

*From that was derived an abstract noun *ga-mang-a- meaning 'mixing, mingling, multitude of things or people mixed together' (Old English 'multitude, assembly, crowd, marketplace', Middle Dutch 'mingling together, company'; Modern English among is from Old English on ġemang 'in assembly/crowd')

*From that was derived a weak verb *(ga-)mang-ō-jan- meaning something along the lines of 'go and do that thing you do in crowds/assemblies/marketplaces'. In Dutch, this meant 'mingle, exchange, argue'; in Old Norse (manga) and Old English (ġe-mangian), it meant 'barter, trade, deal'.

*From that verb was derived an agent noun with the productive ending -ere, i.e., (ġe-)mangere 'dealer, tradesman'.

This development is definitely more plausible, speaking in purely formal terms: each step of the development is fairly clearly visible, and the only part that is not an obvious semantic extension is going from 'crowd/assembly' to 'bartering/trading', but this development has many typological parallels elsewhere. The Ancient Greek ἀγορά (agorá), equivalent to the Roman forum, for example, originally meant 'assembly', but the word was used as the basis for derivations such as ἀγοράζω (agorázō) meaning 'trade, buy'.
The only trouble with this explanation is that it leaves Latin mangō unexplained. The Latin form is remarkably similar to the Germanic forms, but it may actually just be coincidence. The fact that Latin mangō not only means 'slave trader' (thence 'trader' in general) but also 'furbisher, polisher' might indicate that it really does come from the Greek word. Polishing something up is one way of 'cheating' to make it look better.
If Robert Beekes' Etymological Dictionary of Greek is to be believed, and in this case I do think it is, μάγγανον has many traits of what Beekes calls 'pre-Greek': Ancient Greek words that clearly share a great many traits and characteristics with each other, but look decidedly non-Indo-European—presumably words taken in from one or more unknown substrate languages spoken in the Balkans when the Greeks arrived there.
In particular, one frequently observed pattern is that the same root may show up in parallel derivations with its final consonant prenasalised and voiced or plain and aspirated. In this case, that would connect μάγγανον to μηχανή (mēkhanḗ) 'machine, mechanic'. Μάγγανον has a plethora of meanings, of which some are more focused on the aspect of deceiving, enchanting, bewildering, etc.; and others focus on the implement used to deceive, enchant, bewilder, etc.
If μάγγανον and μηχανή are indeed connected, they probably do come from a root that meant something like 'trick, ruse'—but there is nothing to suggest that this is an Indo-European root. It looks much more like a 'pre-Greek' root.

So in conclusion, I would say the answer is that Untermann's statement is not backed up by the facts we have available now.
The most likely scenario is that monger comes from a root meaning 'intermix, mingle' (possibly Indo-European in origin, but only attested in the Germanic and Balto-Slavic branches). The 'deceive' root which he mentions is almost certainly not an Indo-European root, but a 'pre-Greek' substrate root, and though it is deceptively similar to the Germanic root, they are not related.
Writing in 1907, however, Untermann would have had no way of knowing this. Many of the pieces of evidence which have led to this conclusion were not available at that time, and at the time he wrote, his statement would almost certainly represent the communis opinio of historical linguistics.

A: My guess is that this comes from the Italian word "maneggiare" which mainly relates to training horses. Derived from the Latin word "manus" meaning hand, or guiding hand.
So a "manager" would be someone who provides a guiding hand to others around them, to direct them


text:
Q: How to show the Person column image in bigger size? The default image size of the Person column type is quite small. How to show that in bigger size?

A: You can change the src of the Image tags created by Sharepoint. You will see that the URL of the image has a parameter for size.
Just run this script on page load; this will change the URL of all the person images -
  window.addEventListener('load',function(){
    $("img.ms-peopleux-userImg").each(function () { var src = $(this).attr('src'); src = src.replace('SThumb', 'LThumb').replace('size=S', 'size=M'); $(this).attr('src', src); });

});


text:
Q: Update column value from one position to another position based on indexed Hi I want to update the columns of table from one position to another position. Suppose I have 100 rows in which I want to update the fields from position 50 - 90 with one number. Example: category with id 2 should be updated from starting row 50 to last row 90.
I tried below mysql query:
Update table set category = 2 limit 50, 40

This gives an error. Any other way please.

A: Unfortunately you can not use a range LIMIT in an UPDATE query but you can use table joins.
Try something like this:
UPDATE `table` `t1`
INNER JOIN (SELECT `id` FROM `table` WHERE `category`='2' LIMIT 50, 40) `t2` ON `t2`.`id`=`t1`.`id`
SET [YOUR CUSTOM SET]

Note: If you have a specific order, you can specify that in the INNER JOIN SELECT query.

A: Use for-loop with this query
update user
SET username=(select * from (select username FROM user WHERE id=6) A), second_field=(select * from (select second_field FROM user WHERE id=6) B)
WHERE id=5;

In your case :
update category
    SET category_name=(select * from (select category_name FROM category WHERE id=50) A), category_value=(select * from (select category_value FROM category WHERE id=50) B)
    WHERE id=49;

update category
    SET category_name=(select * from (select category_name FROM category WHERE id=51) A), category_value=(select * from (select category_value FROM category WHERE id=51) B)
    WHERE id=50;

    .
    .
    .

update category
    SET category_name=(select * from (select category_name FROM category WHERE id=90) A), category_value=(select * from (select category_value FROM category WHERE id=90) B)
    WHERE id=89;


text:
Q: How do I dynamically add and position CheckBox elements in WPF? I started making a WinForms application to display a grid of 4×4×4 checkboxes, representing a real-life 43 grid of LEDs.
This is what it looks like right now:

I want to convert this to an WPF app, so that I can use the transparency option of  the WPF Checkbox, to make the non-selected layer [there will be 4 layers] of checkboxes slightly transparent, to give it a more true 3D feeling.
I am new to WPF and I have tried to nest 2 elements in the main Window [for example, 2 grids to slightly overlap the position, by maybe 20 pixels, so that they would appear to be 3d-staggered], but it simply won't let me do that, and only lets me add a child grid inside the original grid.
TLDR: How can I dynamically create lots of checkboxes while giving them absolute pixel positions?
My current working WinForms C# code:
int spacing = 25;
int zero = 0;
    for (int z = 1; z <= 4; z++)
            {
                List<string> zString = new List<string>();
                for (int y = 1; y <= 4; y++)
                {
                    for (int x = 1; x <= 4; x++)
                    {

                        int pixel_x = zero + ((x - 1) * spacing);
                        int pixel_y = (zero - 4) + ((y - 1) * spacing);

                        //int id = ((y - 1) * 4) + x;

                        CheckBox box = new CheckBox();
                        box.CheckStateChanged += new System.EventHandler(checkBox2_CheckedChanged);
                        box.Tag = id;
                        zString.Add(id.ToString());
                        //box.Text = id.ToString();
                        box.BackColor = Color.Transparent;
                        //box.
                        box.AutoSize = false;
                        box.Size = new Size(20, 20);
                        box.Padding = new Padding(3);
                        box.Location = new Point(pixel_x, pixel_y);

                        this.Controls.Add(box);
                        id++;
                    }
                }
          zero += 25;
          }

A: Consider using an ItemTemplate ( or DataTemplate) to establish how each item will look within your viewmodel's collection.
Example:
<ListBox Width="400" Margin="10"
         ItemsSource="{Binding Source={StaticResource myTodoList}}">
   <ListBox.ItemTemplate>
     <DataTemplate>
       <StackPanel>
         <TextBlock Text="{Binding Path=TaskName}" />
         <TextBlock Text="{Binding Path=Description}"/>
         <TextBlock Text="{Binding Path=Priority}"/>
       </StackPanel>
     </DataTemplate>
   </ListBox.ItemTemplate>
 </ListBox>

A: I would use multiple UniformGrids stacked on top of each other inside a regular grid (so they overlap). Each UniformGrid would have its Top and Left margins offset by a specific amount.
The item source of each UniformGrid would be bound to a list of Boolean properties on your view model for each "layer".

A: You can try this. Use a Canvas inside your Window.
<Window x:Name="myWindow1" x:Class="WpfApplication1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    >
<Canvas x:Name="canvas" >
    </Canvas>

Unlike Location available in Windows Forms, you can use Margin to set the position
    int spacing = 100;
int zero = 0;
for (int z = 1; z <= 4; z++)
{
    List<string> zString = new List<string>();
    for (int y = 1; y <= 4; y++)
    {
        for (int x = 1; x <= 4; x++)
        {

            int pixel_x =  zero + ((x - 1) * spacing);
            int pixel_y =  zero + ((y - 1) * spacing);

            CheckBox box = new CheckBox();
            Canvas.SetLeft(box, pixel_x);
            Canvas.SetTop(box, pixel_y);

            this.canvas.Children.Add(box);
        }
    }

    zero = zero + 50;
}


text:
Q: How to get Campaign Summary in Facebook Graph API I am trying to get the summary from multiple campaigns from the facebook graph api. I already managed to get a filtered view, so i just get the Campaigns i need:
I am able to get the reach and impression data by platform for every Campaign, but if i sum it up, its not the same result as marked in the screenshot.
https://graph.facebook.com/v14.0/act_BUSINESS_ID/campaigns?fields=name,id,status,objective,insights{impressions}&filtering=[{field: "id",operator:"IN", value: ['CAMPAIGN_ID1"','CAMPAIGN_ID2"']}]

Is it possible to get the reach and impression Data as a summary and breakdowned by platform like in the Screenshot?

A: So, finally i got the right way!
The call should look like this:
act_Accunt_id/insights?breakdowns=publisher_platform&fields=ad_id,clicks,unique_clicks,cpm,impressions,reach,spend&default_summary=true&date_preset=maximum&filtering=[{field: "campaign.id",operator:"IN", value: ['ID1','ID2']},{"field":"publisher_platform","operator":"CONTAIN","value":"facebook"}]

I just came up with also filtering by publisher_platform and thats it!
You can filter any campaign field and as long, as you set the default_summary and the date_preset values correctly, the numbers are exact.


text:
Q: PHP GD - crop image around any given point I have the following script that successfully crops and image at the center point using php's gd:
list($source_width, $source_height, $source_type) = getimagesize($img_path);

define('IMAGE_WIDTH', 200);
define('IMAGE_HEIGHT', 300);

$ratio = $source_width / $source_height;
$desired_aspect_ratio = IMAGE_WIDTH / IMAGE_HEIGHT;

if ($ratio > $desired_aspect_ratio) {
    $temp_height = IMAGE_HEIGHT;
    $temp_width = ( int ) (IMAGE_HEIGHT * $ratio);
} else {
    $temp_width = IMAGE_WIDTH;
    $temp_height = ( int ) (IMAGE_WIDTH / $ratio);
}

$x = ($temp_width - IMAGE_WIDTH) / 2;
$y = ($temp_height - IMAGE_HEIGHT) / 2;

$cropped = imagecreatetruecolor(IMAGE_WIDTH, IMAGE_HEIGHT);
imagecopy(
    $cropped,
    $temp,
    0, 0,
    $x, $y,
    IMAGE_WIDTH, IMAGE_HEIGHT
);

Instead of this for the center:
$x = ($temp_width - IMAGE_WIDTH) / 2;
$y = ($temp_height - IMAGE_HEIGHT) / 2;

on my site users can select the 'main focus' of the image, in which i will crop the image around that. The focus will be supplied as a percentage. I already have the percentage and a way for the customer to select this, i just need to then take these values and crop around them. Can this be done? For example if i wanted my image to be cropped around the point as in the diagram below:

A: The below function should do what you want.

*

*passing only the first argument will output what you have now: the middle of the source image cropped to 200px/200px.

*the second and third arguments allow you to specify the X/Y percent coordinates for the centre of the crop, as you want.

*the fourth and fifth arguments allow you to set the size of the cropped image.

(Note that this assumes PNG, but you should be able to adapt it easily enough for other formats, if needed.)
function crop($file, $cropX = 50, $cropY = 50, $cropW = 200, $cropH = 200)
{
    $src = imagecreatefrompng($file);
    $dest = imagecreatetruecolor($cropW, $cropH);

    list($src_w, $src_h) = getimagesize($file);

    // calculate x/y coordinates for crop from supplied percentages.
    $src_x = (($src_w / 100) * $cropX) - ($cropW / 2);
    $src_y = (($src_h / 100) * $cropY) - ($cropH / 2);

    imagecopy($dest, $src, 0, 0, $src_x, $src_y, $src_w, $src_h);

    imagedestroy($src);

    return $dest;
}

Example usage (setting the crop focus of X to 70%):
$img = crop('test.png', 70);
header('Content-type: image/png');
imagepng($img);
imagedestroy($img);


text:
Q: show dbs command is not working in windows CMD I have installed mongo DB in my windows machine and even set the path in the environmental variables
when I type mongo I got the following output

when I type mongod I got the following output

And for some reason show DBS does not work in the cmd

is there any way I can solve this issue. Any help would be appreciated. Thank you

A: You are executing  show dbs in Windows command line and on a nfs location.
You have to execute the query in mongo shell. Open mongo shell and execute show dbs
Mongo shell is different and mongo server is different. In your first image you started mongo daemon using mongod. It starts a server in the default port 27017.
In the this image, you are executing the command which is not mongo shell.
To start mongo shell and other options, Refer


text:
Q: How are usually denoted functions whose derivative is absolutely continuous? Given a real interval $I$, are there standard name and notation for the vector space
$\{f\in C^1(I)\,:\,f'\,\mathrm{is}\,\mathrm{absolutely}\,\mathrm{continuous}\}$?
I would guess $C^1_{a.c.}$ but I'm not sure if it is a widely used notation or if it requires to be defined explicitely.
And what about the spaces $\{f\in C^n(I)\,:\,f^{(n)}\,\mathrm{is}\,\mathrm{absolutely}\,\mathrm{continuous}\}$?


text:
Q: How to make a basic external data fetch using Next.js and import component into another I have the code below in pages/github and when I go to localhost:3000/github the code executes as expected. I get JSON data.
function GithubAPI(props) {
  // Render posts...
  return (
{props.data.name}
)
}

// This function gets called at build time
export async function getStaticProps() {
  // Call an external API endpoint to get posts
  const res = await fetch('https://api.github.com/repos/vercel/next.js')

  const data= await res.json()
  console.log(data)

  return {
    props: {
      data,
    },
  }
}

export default GithubAPI

When I import this component into another component I get problems.
pages/about
import GithubAPI from './github'
function About(props) {
    console.log(props)

  return (

About

       <GithubAPI/>  {/* TypeError: Cannot read property 'name' of undefined */}

  )
}

export default About

I do not know how the developers of Next.js expect us to structure our code so  that we can make these kinds of API calls and still export our components for import into other components. How am I expected to do this?

A: You cannot run getStaticProps/getServerSideProps in any non-page components. One must prop pass instead.


text:
Q: Where is the following reasoning wrong? I have read in following paper "OPTIMIZATION FOR PRODUCTS OF CONCAVE FUNCTIONS" that if $f_1(x)$ $f_2(x)\cdots f_n(x)$ are positive concave functions in some interval $[a,b]$ then their product $h(x)=f_1(x)f_2(x)\cdots f_n(x)$ has following property.

1- There exist points $\alpha$ and $\beta$ with $a\leq \alpha \leq\beta\leq b$ such that $h$ is strictly increasing on $[a,\alpha)$, constant on $(\alpha,\beta)$ and strictly decreasing on $(\beta,b]$.
In my thinking this means that $h(x)$ can not have isolated maxima in $[a,b]$ (due to the conditions described for the derivative). However I have seen some examples where the function can have more than one maxima and the sign of the derivative also changes more than once. Can anybody please explain me where I am wrong in understanding this.

A: The first function first increases up to the unique global maximum on $[0,1]$ and then it decreases. It does not have multiple maxima that are isolated.

For the second example $h(x)=(1-x)(1-x^2)$, the unique global maximum on $[0,1]$ is $0$ and it is a decreasing function on $[0,1]$.
Edit: I have included the graph of the first function.


text:
Q: phpunit doesn't work on sublime text 3 In my Sublime Text 3 PHPUnit doesn't work. Bundle has installed correctly but plugin is inactive. Has anyone resolved the problem?
Thanks in advance.
Regards.

A: At the time of writing, there is a working ST3 version in the develop branch:
https://github.com/stuartherbert/sublime-phpunit/tree/develop
I got it to work by cloning the develop branch into my {ST3}/Packages folder and then restarting ST3.
At the time when I installed the plugin (a couple of months ago), the ST3 compatible version of sublime-phpunit was not available through Package Control, which is why I installed it with git.
Hope this helps!


text:
Q: Google Apps Script Javascript string length not as expected function test(){
  var log=(typeof Logger=='undefined')?console:Logger;
  log.log(" ¡¢£¤¥¦§¨©ª«¬®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ".length);
}

The code prints 127.0 in Google Apps Script, but returns 128 in Chrome browser and Nodejs!

A: This is a known bug in Rhino, the JS engine that Google Apps Script uses. It doesn't correctly process "soft hyphen" character 0xAD when it's entered directly in a string; the character just gets lost. Your string contains it within "¬®". To simplify the example,
"ab".length

(with a soft hyphen between a and b) returns 3 in browsers but 2 in GAS.
A workaround, if you must use soft hyphen in strings, is to escape it like "a\u00ADb"
"a\u00ADb" === "ab"

evaluates to true in browsers, and to false in GAS.
This discussion, currently offline but available from Google cache, refers to this bug.   I quote it below

Subject: Re: Rhino eats strange characters
Hi Richard,
for me this clearly looks like a bug in Rhino where I'm able to
reproduce it. I'll try to prepare a patch for Rhino for this problem.
Please open an issue in HtmlUnit to be sure that it doesn't get lost
(and to be sure that I've correctly identified the root cause).
Cheers,
Marc.
--
Web: http://www.efficient-webtesting.com
Blog: http://mguillem.wordpress.com
Richard Eggert wrote:

I recently attempted to use HtmlUnit to load pages that have been
  "compressed" using HTMLZip (http://www.htmlzip.com/) and found that
  HtmlUnit horribly mangles the output. Since HTMLZip claims to work
  properly in every major browser (and I'll take their word for it), I
  figure this is a bug in HtmlUnit, since it is supposed to mimic the
  behavior of "normal" browsers.
Examining the source code of a page generated by HTMLZip, I found that
  HTMLZip uses JavaScript strings that contain unprintable characters
  without escaping them. When I replaced all the unprintable characters
  with their corresponding \x escape sequences, HtmlUnit was able to
  process the page. However, HtmlUnit was not able to process pages in
  which multiple layers of HTMLZip compression had been applied.
I then did an experiment in which I created a very simple ISO-8859-1
  HTML document that contained just a SCRIPT tag that declared a variable
  "x" that was assigned a string containing the characters 0 through 255,
  escaping only the white space and quotation characters (to avoid syntax
  errors). I ran it through HtmlUnit and examined the value of the "x"
  variable. I found that every character was preserved intact EXCEPT for
  the 0xAD character, which corresponds to the Unicode SHY "soft hyphen"
  character in ISO-8859-1. The character was just plain missing from the
  string!
In order to narrow down where the 0xAD was getting dropped, I used a
  ScriptPreProcessor to capture the script before it was passed to Rhino.
  I examined the captured script and found that the 0xAD was still present
  in the text, which indicates to me that the character is being dropped
  by Rhino and not by the HTML parser.
Should I submit a bug report for this? Also, can anyone think of a
  quick workaround? Off the top of my head, all I can think of would be
  to write a ScriptPreProcessor that automatically converts the SHY
  character to an escape sequence, but without actually parsing the
  script, I could end up escaping characters that appear outside of string
  literals.
Rich Eggert
  Member of Technical Staff
  Proteus Technologies, LLC


text: Q: ASUS G75VW WinFlash Utility BIOS will not let me boot up my drives Not sure exactly what I did wrong, but I had just installed Windows 7 on my computer, and was about to update the BIOS of my ASUS G75VW laptop using the Win-flash Utility program on their support website. After doing this, my computer restarted and booted into the BIOS(Now I believe it's completely written over all of my files and drive) and it only allows me to change the settings from the BIOS, and delete Boot Options(Which it shows none). I'm completely baffled on how I can get my things back, if only to try and install Windows 7(along with all the drivers for ASUS) again.


text: Q: Download Package Documents Using NPM After spending months in js/ts/nodejs developing I am wondering that there is no document file to review code signature in packages. I have searched for a way to download a document file in NPM but haven't found any command. Is there any way to download a document file in NPM?


text:
Q: Focus method of Run (in a FlowDocument) is not working Code:
TextPointer navigator = flowDocViewer.Document.ContentStart;

// While we are not at end of document
while (navigator.CompareTo(flowDocViewer.Document.ContentEnd) < 0)
{
   // Get text pointer context
   TextPointerContext context = navigator.GetPointerContext(LogicalDirection.Backward);

   Run run = navigator.Parent as Run;
   if (run != null)
   {
      if (run.Text.Equals(currentText))
      {
         if (run.IsFocused == false)
         {
            run.GotFocus += run_GotFocus;
            run.LostFocus += run_LostFocus;
            run.Focus();
         }
      }
   }

And:
void run_LostFocus(object sender, RoutedEventArgs e)
{
   ((Run)sender).LostFocus -= run_LostFocus;
   ((Run)sender).Background = Brushes.Transparent;
}

void run_GotFocus(object sender, RoutedEventArgs e)
{
   ((Run)sender).GotFocus -= run_GotFocus;
   ((Run)sender).Background = Brushes.White;
}


text:
Q: java.util.zip.ZipException: duplicate entry error here's my build.gradle dependencies part :
 `
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')

compile 'com.android.support:appcompat-v7:23.0.0'
compile files('libs/google-play-services.jar')

compile files('libs/android-async-http-1.4.9.jar')
compile 'cz.msebera.android:httpclient:4.3.6'
compile 'com.google.android.gms:play-services-location:7.+'

and my error is :
Error:Execution failed for task ':app:packageAllDebugClassesForMultiDex'.

java.util.zip.ZipException: duplicate entry: com/google/android/gms/auth/UserRecoverableAuthException.class

what's the cause of the error ??

A: You are adding google-play-services twice in your gradle file.
compile files('libs/google-play-services.jar')
compile 'com.google.android.gms:play-services-location:7.+'

Remove the following line from your build.gradle file.
compile files('libs/google-play-services.jar')

A: you need use multidex in project link


text:
Q: Is there a practical way to create/inject some visible interference into a nearby AC mains? I have this 230 to 6V rms step-down transformer. I use it to observe the mains voltage.
But recently I needed to create some interference or spike in the mains. So I first tried the following:
I used a filterless power strip. I coupled the transformer's primary side to one of the sockets of the power strip. And at the adjacent socket I plugged a heat gun. I sometimes very randomly saw some tiny fluctuation and that disappeared.
My approach was to see the interference from the nearby AC socket. What type of load would create a visible interference or spike? Or is there any other practical way to achieve this. I want to create a spike or interference by a load and observe that from a nearby AC socket via a scope and a transformer.
More over is there a safe way to observe the Line to earth or neutral to earth voltage on scope? I mean if I use the transformer secondary for the line can I connect the scope ground to the mains earth safely?

A: Any powerline communication device does exactly that: inject a signal on top of the power signal, and extract that at the other end. It works.
The fact that you don't see much with an oscilloscope just means you're using the wrong instrument.
Try the following:

*

*use a dimmer for resistive loads (for incandescent lamps, i.e. the cheapest dimmers you find).

*set it to a medium dim

*attach a large load, e.g. a hot plate, toaster, large lamp, whatever, close to the maximum rating of your dimmer

*use the transformer, plugged into the outlet you want to observe, only as a source for the trigger of your oscilloscope

*use that trigger signal to trigger the oscilloscope, observing a capacitive divider: two (high-voltage, medium to small value!!) capacitors of two different sizes in series between live and neutral of the power outlet you want to test.

What does a cheap dimmer do? Typically, it's a phase-fired controller, which means it always turns on the load (like you, flipping a switch) at the same phase (i.e. angle) of the grid voltage.
That's awesome, because a powerline system has different properties, depending on which phase you look at it.
Now, your transformer might not even have the bandwidth to notice the high-frequency noise caused by switching on, but your capacitive divider definitely has – in fact, it should act as kind of a high-pass filter.
By triggering the oscilloscope with your transformer, you make the grid phases take a "fixed position" on your oscilloscope screen. That's immensely helpful, since now your switching noise will also always get a fixed position (since the switching always happens at the same phase), and be much easier to spot.
Compare load with and without dimmer, and with no load and dimmer at all. Then start playing around with the dimming ratio.

simulate this circuit – Schematic created using CircuitLab

A: For EMC testing to meet standards, a so-called CDN (coupling-decoupling network) or LISN (Line Impedance Stabilization Network) is used. You may be able to find schematics and instructions for making such a network. I have built LISNs (for measuring noise created by circuits) from such information and they worked fine for pre-compliance testing.
Here is the internal schematic of a commercial device. As you can see it's a decoupling network on the mains input and a coupling network on the other side to allow injection of signals.

As far as creating nasty noise without any fancy equipment, I've found a classic 100/140W Weller soldering gun to be a good informal source of noise (photo from Amazon.com). Certainly they are better used for creating noise than for soldering for 99% of electronics purposes.

A: You could use a 230 v relay (SPDT or greater) wired as a buzzer. One coil lead is wired through the NC and Common, the other lead straight to mains. The inductive kick-back from the coil should give you some good rough spikes. You can adjust the contact clearance and the spring tension to minimize excess noise.


text:
Q: Elegant solution to count rolling two dice? I am trying to count how many times I'll get the same results in each role of two dice in 100 times in R .I used
werFun <-  function() {
 return(sample(1:6,2,TRUE))
}
count <- 0
matResult <- matrix(0,100,2)
for (i in 1:nrow(matResult)) {
  matResult[i,] <- werFun()
   if(matResult[i,1]==matResult[i,2]){
    count=count+1
 }
}
print(count)

Is there an elegant solution  ? .

A: Try this
matResult <- matrix(replicate(100,sample(1:6,2,TRUE)),ncol = 2,byrow = T)
nrow(matResult[matResult[,1]==matResult[,2],])

Another solution which will also work for n dice.
sum(apply(matResult,1,var)==0)

A: To formalize my comments, you can simulate rolls with sample and repetitions with replicate. Combine the two, and you get a matrix. If you transpose and coerce that matrix to a data.frame, you can call table on it, which will neatly show you exactly what rolls you got:
set.seed(47)    # for reproducibility

table(data.frame(t(replicate(100, sample(1:6, 2, TRUE)))))
##    X2
## X1  1 2 3 4 5 6
##   1 3 0 4 5 2 1
##   2 2 5 0 1 5 2
##   3 1 3 3 0 3 3
##   4 3 4 1 3 3 7
##   5 6 0 3 1 4 3
##   6 3 3 4 2 7 0

If you want the diagonal, where the dice are equal to each other, grab it by wrapping the call in diag:
diag(table(data.frame(t(replicate(100, sample(1:6, 2, TRUE))))))
## 1 2 3 4 5 6
## 3 0 4 7 2 5

Sum it, and you'll get the number of rolls where the dice are equal:
sum(diag(table(data.frame(t(replicate(100, sample(1:6, 2, TRUE)))))))
## [1] 18

Note that it's resampling each time you call it, so numbers will vary unless you set the number generator seed.

A: You can count the times on the go if you don't really need the matrix to store all the rolling history, which could potentially save time and memory for you:
sum(sapply(1:100, function(i) {vec <- werFun(); vec[1] == vec[2]}))

Which should be essentially the same simulation process as you did. With that being said, the counter part can be simplified if you have the matResult already:
count = sum(matResult[,1] == matResult[,2])


text:
Q: Edit git's commit comment I have a little prepare-commit-msg hook script that does some basic timekeeping for me. It does some sums based on a few metrics and tells me how much time went into the current commit. This is for internal use and should not end up in the commit message.
What it currently does is inject a line like this.
# Time since last timed commit: ...

My problem with prepare-commit-msg is this line ends up in the actual commit message. I have to manually delete it each time or it'll be client-visible.
Ideally it would featured in the block that reads:
# Please enter the commit message for your changes. Lines starting
# with '#' will be ignored, and an empty message aborts the commit.

But how do I print data in there?


text:
Q: android- How to differentiate the Emulator and Device Programatically In My application one button is there. if you click on that button we are getting current Location. Based on this current Location i am doing some operations. In device it is working properly. But in emulator we are not getting the current Location thats why i am using the Some default Latitude and Longitude values for emulator. But i want to differentiate the emulator and device. It means we are running in the device means it takes the geocode locations. suppose we are running in the emulator means it takes the default latitude and longitude values. How to implement it pro-grammatically. can anybody help me.
thanks

A: See http://commonsware.com/blog/Android/2010/05/27/identifying-emulator-android-2.2.html.
Say Thank you, @CommonsWare.

A: I had exactly the same problem with the digital compass. I have solved it by writing and using the method below:
public static boolean areOrientationSensorsAvailable(Context ctx) {
    final SensorManager manager = (SensorManager) ctx.getSystemService(Context.SENSOR_SERVICE);
    final List<Sensor> sensorsMagnet = manager.getSensorList(Sensor.TYPE_MAGNETIC_FIELD);
    final List<Sensor> sensorsAccel  = manager.getSensorList(Sensor.TYPE_ACCELEROMETER);

    return (sensorsMagnet.size() != 0) && (sensorsAccel.size() != 0);
}

This would work for you as well: if there's no sensor you are on the emulator.
This is not "clean" (not suitable for a released application I mean) but this is fine for testing.


text:
Q: How to hide TabPane content on Tab clicked in JavaFX Here is a code:
package tabpane;

import javafx.application.*;
import javafx.geometry.*;
import javafx.scene.*;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.stage.*;

public class HideShowTabContentOnClicked extends Application {

    public static void main(String[] args) {

        launch(args);
    }

    private BorderPane createContent() {

        BorderPane borderPane = new BorderPane();

        TabPane tabPane = new TabPane();
        tabPane.setSide(Side.LEFT);

        StackPane stackPane = new StackPane();
        stackPane.setStyle("-fx-background-color: lightblue");
        stackPane.setMinWidth(200);

        Tab firstTab = new Tab("First");
        firstTab.setClosable(false);
        firstTab.setContent(stackPane);
        firstTab.selectedProperty().addListener((observable, oldValue, newValue) -> {
            if (!newValue) {
                firstTab.setContent(null);
            } else {
                firstTab.setContent(stackPane);
            }
        });

        Tab secondTab = new Tab("Second");
        StackPane stackPane2 = new StackPane();
        stackPane2.setStyle("-fx-background-color: yellow");
        secondTab.setContent(stackPane2);
        secondTab.setClosable(false);

        secondTab.selectedProperty().addListener((observable, oldValue, newValue) -> {
            if (!newValue) {
                secondTab.setContent(null);
            } else {
                secondTab.setContent(stackPane2);
            }
        });

        StackPane center = new StackPane();
        center.setStyle("-fx-background-color: cyan");

        borderPane.setCenter(center);

        tabPane.getTabs().addAll(firstTab, secondTab);
        borderPane.setLeft(tabPane);
        return borderPane;
    }

    @Override
    public void start(Stage stage) throws Exception {

        stage.setScene(new Scene(createContent()));
        stage.setMaximized(true);
        stage.show();
    }
}

Here I tried to solve a problem by using selectedProperty() by setting content to null, but it doesn't working, I want to make Tab like toggle button so that when I click on it showed and hide TabPanes content.
Before

And when clicked

As an example I want to implement TabPane like Intellij IDEA Tool Buttons (like "Project", "Structure" Tool Buttons etc).

A: If you are going to keep your content into StackPane, you can bind stackPane.visibleProperty() with toggleButton.selectedProperty():
stackPane.visibleProperty()
             .bind(Bindings.when(toggleButton.selectedProperty())
                           .then(false)
                           .otherwise(true)
             );

in this exampl: toggleButton.isSelected() --> !stackPane.isVisible() and !toggleButton.isSelected() --> stackPane.isVisible(),
or listen ToggleButton's events:
// toggleButton.setOnAction(e ->{                      //new .setOnAction() -> Override previous
toggleButton.addEventHandler(ActionEvent.ACTION, e ->{ //can add any quantity for your needs
        if(toggleButton.isSelected())
             stackPane.setVisible(false);
        else stackPane.setVisible(true);
    });

But the problem is instead of toggle button I want to use Tab, so that it behaves like toggle button. i.e. when click "First Tab" in my example code if content visible it should be invisible and vice versa. I mean only tabs should be shown

I found solution.Tab does not have click-handler... but
Tab tab = new Tab();
tab.setContent(stackPane);
Label lable = new Label("Label");    //create Label
tab.setGraphic(lable);               //set Lable as Graphic to Tab
lable.setOnMouseClicked(event ->{    //setOnMouseClicked, for example
        if(stackPane.isVisible()){
            stackPane.setVisible(false);
        }else{
            stackPane.setVisible(true);
        }
});

, you can use Label(for example) as Tab-text and add setOnMouseClicked()-handler to Label. You can use any Node with Handler/ActionListener -> It's up to you.
For example, you can use CheckBox to show/hide StackPane, and Tab text (you can combine FXML and Java-code to produce graphics):

Tab tab = new Tab("Tab2");          //Tab with Text
tab.setContent(stackPane);
CheckBox checkBox = new CheckBox(); //create CheckBox
tab.setGraphic(checkBox);           //set CheckBox as Graphic to Tab
stackPane.visibleProperty()
            .bind(Bindings.when(checkBox.selectedProperty())
                    .then(false)
                    .otherwise(true)
            );

or
@FXML
private Tab tab;
// ...
tab.setGraphic(checkBox);
// ...

A: I have came up with this solution:
AtomicReference<Tab> currentTab = new AtomicReference<>(tabPane.getSelectionModel().getSelectedItem());
AtomicReference<Tab> lastTab = new AtomicReference<>(null);
tabPane.setOnMouseReleased(event -> {
    // Check if current node is actually tab
    Node n = event.getPickResult().getIntersectedNode();
    while (n != null && !(n.getStyleClass().contains("headers-region"))) {
        n = n.getParent();
    }
    if (n == null)
        return;

    lastTab.set(currentTab.get());
    currentTab.set(tabPane.getSelectionModel().getSelectedItem());

    if (currentTab.get() == lastTab.get()) {
        // Hide
        tabPane.setPrefSize(28, 28);
        //tabPane.getSelectionModel().clearSelection(); // notify selection model
        currentTab.set(null);
    } else {
        // Show
        tabPane.setPrefSize(-1,-1);
        currentTab.set(tabPane.getSelectionModel().getSelectedItem());
    }
});

First of all, I have added mouse event to the tabPane. Inside this mouse event, check if node under cursor is actually Tab node. If it is, do some logic to identify what user is trying to do: hide or show. Hiding is a bit tricky, so I ended up with setting preferred size of TabPane to 28 px wide.
I have also tried to notify selection model with an empty newValue:
tabPane.getSelectionModel().clearSelection();

But this it is not working properly. Calling select(-1) should call clearSelection(), but behavior is different somehow.
When I select another tab after calling clearSelection(), selection model handler called with oldValue == null, that possibly does not update internal index and tab does not swithes to selected one.


text:
Q: Sum all list-elements to new list I have an old list and I want to sum up every single element to a new list:
    lst_old = [1, 2, 3, 4, 5]
    lst_new = [1, 3, 6, 10, 15]

Is there an elegant way to implement that in Python 3 with short and fast code? Apart from sum() which only prints last element I couldn't find a proper solution for my problem.

A: You can use itertools.accumulate, eg:
from itertools import accumulate

lst_old = [1, 2, 3, 4, 5]
lst_new = list(accumulate(lst_old))
# [1, 3, 6, 10, 15]

A: itertools.accumulate as mentioned by Jon Clements is the best way to do. However, in case you want an explicit way to do it, here goes:
lst_old = [1, 2, 3, 4, 5]
sum = 0
lst_new = []
for item in lst_old:
    sum += item
    lst_new.append(sum)

Main advantage of this is, you can wrap it in a function and if there is any transform or validation need to be performed, can be added.
For example, lets say you want to stop the function keep going after a limit, the following will help:
def accumulate_items(lst_old, limit=0):
    sum = 0
    output_list = []
    for item in lst_old:
        sum += item
        output_list.append(sum)
        if limit and sum > limit:
            break
    return output_list

The flexibility will be limitless if there is any transformation or operation need to be done here. Have a pre-condition that need to be set? Go ahead. Have a post-condition that need to be tested? Go ahead. Pretty huge list and wanted a generator based solution just like the itertools.accumulate? Go ahead. Need to add a validation or exception handling? Go ahead.
However, no transformation and simply accumulate? The previous answer is the best. Using sum with list indices is pretty slow as the order of complexity sky rockets.

A: You can take the sum of a slice of a list using listname[start:end], with both start and end as optional arguments (defaulting to the beginning and end of the list):
lst_old = [1, 2, 3, 4, 5]
lst_new = []

for i, num in enumerate(lst_old):
    index = i+1
    var = sum(lst_old[:index])
    print(var)
    lst_new.append(var)


text:
Q: Can Galleria be used with ajax data? I really need some help here!
I have a page with images in groups of 1, 2, or 3. I click on an image and the class gets sent to some jquery ajax stuff to get the id(mysql) then this gets sent to a php file to build the html for the images to display on a div in my page. This bit works OK, but I'm trying to use the galleria plugin to show the image that  haave been sent, but it just act like galleria is not there! If I hardcode some images in the dive. galleria works as it should!
here is my project.js file
// whenever a link with category class is clicked
$('a.project').click(function(e) {
// first stop the link to go anywhere
e.preventDefault();
// you can get the text of the link by converting the clicked object to string
// you something like 'http://mysite/categories/1'
// there might be other methods to read the link value
var linkText = new String(this);
// the value after the last / is the category ID
var projectvalue = linkText.substring(linkText.lastIndexOf('/') + 1);
// send the category ID to the showprojects.php script using jquery ajax post method
// send along a category ID
// on success insert the returned text into the shownews div
$.post('../inc/showprojects.php', {project: projectvalue}, function(data) {
$('#shownews').html(data);
});

});

This is my showproducts.php file
<?php
include 'connect.php';
// if no project was sent, display some error message
if(!isset($_POST['project'])) {
die('No project has been chosen');
}
// cast the project to integer (just a little bit of basic security)
$project = (int) $_POST['project'];
// this will be the string that you will return into the shownews div
$returnHtml = '';
$q = "SELECT * FROM projects WHERE id='$project'";
if($r = mysql_query($q)) {
// construct the html to return
while($row = mysql_fetch_array($r)) {
    $returnHtml .= "";
    $returnHtml .= "";
    $returnHtml .= "";
}
}
// display the html (you actually return it this way)
echo $returnHtml;
?>

This is how I'm calling galleria on the div
// Load the classic theme
Galleria.loadTheme('../galleria/themes/classic/galleria.classic.min.js');
// Initialize Galleria
$('#shownews').galleria();

Can anyone help me out?
Thanks

A: try this one
    // whenever a link with category class is clicked
    $('a.project').click(function(e) {
    // first stop the link to go anywhere
    e.preventDefault();
    // you can get the text of the link by converting the clicked object to string
    // you something like 'http://mysite/categories/1'
    // there might be other methods to read the link value
    var linkText = new String(this);
    // the value after the last / is the category ID
    var projectvalue = linkText.substring(linkText.lastIndexOf('/') + 1);
    // send the category ID to the showprojects.php script using jquery ajax post method
    // send along a category ID
    // on success insert the returned text into the shownews div
    $.ajax({url:'../inc/showprojects.php',
            type:'POST' ,
            method,async:false ,
            data:{project: projectvalue},
            success:function(data) {
                 $('#shownews').html(data);
        }});
Galleria.run('#shownews');

});

A: I think, you need to call Galleria.run after recieve data from php
EDIT: ugly way - destroy gallery, if already running before inserting new images into div
if($('#shownews').data('galleria')){$('#shownews').data('galleria').destroy()} //destroy, if allready running
$.post('../inc/showprojects.php', {project: projectvalue}, function(data) {
    $('#shownews').html(data);
    Galleria.run('#shownews');
});

and remove $('#shownews').galleria();
EDIT 2: use Galleria's .load api to load new data
// whenever a link with category class is clicked
$('a.project').click(function(e) {
    // first stop the link to go anywhere
    e.preventDefault();
    // you can get the text of the link by converting the clicked object to string
    // you something like 'http://mysite/categories/1'
    // there might be other methods to read the link value
    var linkText = new String(this);
    // the value after the last / is the category ID
    var projectvalue = linkText.substring(linkText.lastIndexOf('/') + 1);
    // send the category ID to the showprojects.php script using jquery ajax post method
    // send along a category ID
    // on success insert the returned text into the shownews div
    $.post('../inc/showprojects.php', {project: projectvalue},
        function(data) {
            $('#shownews').data('galleria').load(data);
        },"json"
    );
});

PHP
<?php
include 'connect.php';
// if no project was sent, display some error message
if(!isset($_POST['project'])) {
    die('No project has been chosen');
}
// cast the project to integer (just a little bit of basic security)
$project = (int) $_POST['project'];
// this will be data array that you will return into galleria
$returnData = array();
$q = "SELECT * FROM projects WHERE id='$project'";
if($r = mysql_query($q)) {
    // construct datat object to return
    while($row = mysql_fetch_array($r)) {
        $returnData[] = array('image'=>$row['filename']);
        $returnData[] = array('image'=>$row['filename1']);
        $returnData[] = array('image'=>$row['filename2']);
    }
}
// return JSON
echo json_encode($returnData);
?>

Galleria init:
(Gallery will be empty until you will load data into it)
// Load the classic theme
Galleria.loadTheme('../galleria/themes/classic/galleria.classic.min.js');
// Initialize Galleria
Galleria.run('#shownews');

A: Try loading galleria after the ajax request has successfully completed. By doing this jquery waits until ShowNews has been rendered and then runs galleria.
$.ajax(
    {
        type: "POST",
        url:'../inc/showprojects.php',
        data:{project: projectvalue},
        success: function(data)
        {
            $('#shownews').html(data);
        },
        complete: function()
        {
           Galleria.loadTheme('../galleria/themes/classic/galleria.classic.min.js');

           $('#shownews').galleria();
        }
    });

I use this method whenever i gather the image data from a remote source. Hope this helps!

A: I tried this answer and other answers on the web and nothing worked. Then I moved galleria-1.3.5.min.js to the parent page and it worked. What an amazingly simple solution!


text:
Q: How do I reference a text file from an Azure WebJob? I'm creating a web job on Azure that is going to be a c# console application (.exe).  Inside this program I need to read a text file from the file system.  Is there a way to include the text file I need in the executable? Where do I put the file and how do I reference it?
I also don't want anyone (via the website) be able to access the file.

A: Just deploy the text file alongside the executable, and you'll be able to open it in the current folder.
If deploying the WebJob from Visual Studio, make sure to mark the text file's properties as 'Copy if newer' to make sure it gets deployed.

A: Follow instead of putting a file location in the value as parameter
just put this as I show you here

*

*Put it in Appconfig file for path as

*to copy this text file into your bin/debug folder to

*Make zip folder as usual, put that test file int "debug.zip"


text:
Q: Display an image in a Image container in WPF I am trying to display an image in an WPF Image container
string imageContent = ((DataRowView)dgQuestions.SelectedItem)["QuestionImage"].ToString();
if (imageContent.Length >= 5)
{
    byte[] data = (byte[])((DataRowView)dgQuestions.SelectedItem)["QuestionImage"];
    ImageSourceConverter imgConv = new ImageSourceConverter();
    imageSource = (ImageSource)imgConv.ConvertFromString(data.ToString());
}

The last line of the above code generates the following error

object reference not set to an instance of an object

I'm not bothered with how the datagrid displays the image as the user will never see the it.
This is how I am filling the grid:
SqlCommand cmd = new SqlCommand();
cmd.Connection = Con;
cmd.CommandText = "getQuizQuestions";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("@quizid", SqlDbType.Int)).Value = quizId;
cmd.ExecuteNonQuery();
SqlDataAdapter daSubject = new SqlDataAdapter(cmd);
DataSet dsSubject = new DataSet();
daSubject.Fill(dsSubject, "QuizSubject");
dgQuestions.ItemsSource = dsSubject.Tables[0].DefaultView;

A: Set a breakpoint and validate data isn't null. Also, why don't you set the image source as the byte[] instead of using a ToString():
public BitmapImage ImageFromBuffer(Byte[] bytes)
{
    MemoryStream stream = new MemoryStream(bytes);
    BitmapImage image = new BitmapImage();
    image.BeginInit();
    image.StreamSource = stream;
    image.EndInit();
    return image;
}

public Byte[] BufferFromImage(BitmapImage imageSource)
{
    Stream stream = imageSource.StreamSource;
    Byte[] buffer = null;
    if (stream != null && stream.Length > 0)
    {
        using (BinaryReader br = new BinaryReader(stream))
        {
            buffer = br.ReadBytes((Int32)stream.Length);
        }
    }

    return buffer;
}


text:
Q: The name 'model' does not exist in current context - Only on one page at one variable So this "The name 'model' does not exist in current context" error is pretty common. However, I might have a different kind of cause.
In my view I use multiple model.variablename variables. However on one line it doesn't work:
@Html.PasswordFor(model => model.Pw, new { @value = Model.Pw})

As were
@Html.TextBoxFor(model => model.Email)

Just works.
I've tried many, if not all, possible solutions. Nothing worked. However, to exclude it here's part my webconfig (main):
<appSettings>
    <add key="webpages:Version" value="3.0.0.0" />
    <add key="webpages:Enabled" value="false" />
  </appSettings>

And the webconfig in my Views folder:
<configuration>
  <configSections>
    <sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">

    </sectionGroup>
  </configSections>

  <system.web.webPages.razor>
    <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
    <pages pageBaseType="System.Web.Mvc.WebViewPage">
      <namespaces>
        <add namespace="System.Web.Mvc" />
        <add namespace="System.Web.Mvc.Ajax" />
        <add namespace="System.Web.Mvc.Html" />
        <add namespace="System.Web.Routing" />
        <add namespace="System.Web.Optimization" />
        <add namespace="WingLok" />
      </namespaces>
    </pages>
  </system.web.webPages.razor>

I'm using ASP.NET version 4.6, MVC5, Visual Studio 2012 and Razor 3.0 on a Windows 10 computer, to make all information complete.

A: @model won't work.
The reason you place @ in front is if you are using C# syntax e.g.
Html.InputFor(model => model.Name, new { class = "something" }
will fail because class is a reserved word. So you need:
Html.InputFor(model => model.Name, new { @class = "something" }
which is correct. Now, based on that logic, the Razor compiler is looking for an object instance named model to parse this:
@Html.PasswordFor(model => model.Pw, new { @value = @model.Pw})
Side-note, I don't think you need @ in front of value.
It cannot find any instance named model so it errors.
In the lambda for @Html.PasswordFor(model => model.Pw,.... the model is an argument that exists in the context of that labda expression. It is not available elsewhere on that line of code. Hence the reason why you are getting the error.
To fix the problem, try
@Html.PasswordFor(model => model.Pw, new { @value = Model.Pw})
The variable Model should be available everywhere in the Razor file. Model is the actual viewmodel that has been passed to the view itself.
EDIT:
Here is some code I tried which works fine for me
ViewModel
public class HomeIndexViewModel
{
    public string Name { get; set; }
}

Controller
public class HomeController : Controller
{
    public ActionResult Index()
    {
        var viewModel = new HomeIndexViewModel();

        viewModel.Name = "Hello World!";

        return View(viewModel);
    }
}

Razor View
@model WebApplication1.Controllers.HomeIndexViewModel

@Html.TextBoxFor(model => model.Name, new { data_name = Model.Name })

When I view the web page, I see a input box with "Hello World!" in it. Also, here's the HTML for that field:
<input data-name="Hello World!" id="Name" name="Name" type="text" value="Hello World!">
As you can see, my custom data attribute data-name has also been populated correctly.


text:
Q: Using enums for switch case in Java I am implementing a simple switch case which will switch on an Enum value. Following is the code
ScheduleType scheduleType = ScheduleType.valueOf(scheduleTypeString);

switch (scheduleType) {

       case ScheduleType.CRON_EXPRESSION:
                    System.out.println("Cron");
                    break;
}

But I am getting the following error in my IDE:
The qualified case label ScheduleType.CRON_EXPRESSION must be replaced with the unqualified enum constant CRON_EXPRESSION

Can somebody explain why do I get this error and what's wrong with the code.
I know the right way to do is to remove the ClassName, but why do I need to do that?
Because generally in comparisons I do use it like for example in equals and all.
Thanks

A: Leave off the class name. case ScheduleType.CRON_EXPRESSION: should be case CRON_EXPRESSION: instead.
Or in other words, ScheduleType.CRON_EXPRESSION must be replaced with the unqualified enum constant CRON_EXPRESSION.

A: Mike has explained the how part.
I shall attempt to explain the why part.
The switch case would make sense only if you compare enums of the same type.
Comparing enums of type E1 with that of E2 doesn't make sense.
There was a bug which was raised to request for this feature which touches upon this.


text:
Q: How to use Go Gin in vercel serveless functions? How to make a single file to handle all the routes for the vercel serverless function?
By default it uses the inbuilt handler is there any way to use the gin module to do the same ?
package handler

import "github.com/gin-gonic/gin"

/* get the post data and send the same data as response */

func Hi(c *gin.Context) {
    c.JSON(200, gin.H{
        "message": "Hello World!",
    })
}

A: If I correctly understood your question, you just need to create struct Handler and make a method "InitRoutes" returning router with all handleFuncs
handleFuncs also should be methods of Handler
For example:
type Handler struct {
    // here you can inject services
}

func NewHandler(services *service.Service) *Handler {
    return &Handler{}
}

func (h *Handler) InitRoutes() *gin.Engine {
    router := gin.New()

    auth := router.Group("/group")
    {
        auth.POST("/path", h.handleFunc)
        auth.POST("/path", h.handleFunc)
    }

    return router
}

After that you should inject it into your httpServer
srv := http.Server{
        Addr:           ":" + port,
        Handler:        Handler.InitRoutes(),
        MaxHeaderBytes: 1 << 20,
        ReadTimeout:    10 * time.Second,
        WriteTimeout:   10 * time.Second,
    }

srv.ListenAndServe()