Q: How to make a Ninja Form open up when you click on a bootstrap modal button (inside of a wordpress widget) I am using the following:
Ninja Version: 3.4.25 /
WordPress Version: 5.5 /
Bootstrap Version: 3 (or maybe 4)
I have a WordPress template based on bootstrap, and I am using the latest Ninja forms version.
I have created a Bootstrap button in a widget, that I want to open up a model window displaying my Ninja Contact form.
I have actually been successful with this setup with an older version of Ninja form.  But since the latest updates, they have changed all their form field names, and so now it won't work on my new site, because I am not using the correct field names.
If anyone knows what the old field name: "ninja_forms_display_form" is now, then you don't have to read the rest of my documentation.  I did try: "ninja_forms", but that didn't work either.
I will provide the coding I use on another site using the same template but using an older version of Ninja Forms (3.2.11).  This modal button does work, and can be seen on the sidebar's green  'contact us' button here:  www.oasisflighttraining.com.au/about-oasis-flying-school/
Here is the Sidebar Widgets code that uses the Bootstrap button:

    <button type="button" class="btn btn-success btn-lg" data-toggle="modal" data-target="#contactform">Contact Us</button>

And here is the code that creates the Bootstrap button (found at the bottom of my footer.php file just before the call to wp_footer function.

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

Contact Us

        <?php

            if( function_exists( 'ninja_forms_display_form' ) ){ ninja_forms_display_form( 1 ); }

        ?>

        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

The code referencing "ninja_forms_display_form" is the part that doesn't work on my new site with the latest version of Ninja Forms.  I know that field name has changed, but I can't figure out what to replace it with.
Can anyone give me some help figuring out how to make this bootstrap modal button work with my Ninja Form created with the updated version with new field names?
Thanks!

A: The  newer Ninja Forms can use shortcode, so I just changed this:
    <?php

        if( function_exists( 'ninja_forms_display_form' ) ){ ninja_forms_display_form( 1 ); }

    ?>

to this:
    <?php echo do_shortcode( '[ninja_form id=1]' ); ?>

(And as a public service advice.. just make sure that you don't have the bootstrap js pulled in twice, or the modal window won't stay displayed after you click the button.  I found that the bootstrap shortcode plugin added another bootstrap.js)


Q: Installed caret but still missing createDataPartition function in R I am new to R so I tried predicting using linear reg model and I am getting the error as shown in the image below, can you help me out?
Libraries included:
library(tidyverse)
library(ggplot2)
library(caret)
library(dplyr)
library(tidypredict)

png

A: Try running the library(caret) again, if the package is loaded, createDataPartition is there. If you still face the issue, check for Caret updates.


Q: Changing control group for Dunnett glht in multcomp I was wondering if anyone knows how to change between treatment groups for the control treatment for the Dunnett test in multcomp?  A control treatment is selected by the first treatment alphabetically/numerically.  I have several sets of data that I'd prefer not to go through editing if I can simply do it with code, plus I have two controls I'd like to compare my experimental treatments to.
For example, my "data"
TrtName Block   Trt X3dpi   X6dpi   X12dpi
Neg_ctrl    1   1   1   4   8
Neg_ctrl    1   1   1   3   8
Neg_ctrl    1   1   2   4   9
Neg_ctrl    2   1   1   3   9
Neg_ctrl    2   1   1   4   8
Neg_ctrl    2   1   1   5   9
TC_ctrl 1   2   2   5   9
TC_ctrl 1   2   2   5   9
TC_ctrl 1   2   1   4   9
TC_ctrl 2   2   1   3   7
TC_ctrl 2   2   2   4   9
TC_ctrl 2   2   2   3   8
D_112   1   3   0   1   5
D_112   1   3   0   1   4
D_112   1   3   1   2   5
D_112   2   3   0   2   5
D_112   2   3   1   1   3
D_112   2   3   1   2   4
D_332   1   4   0   1   5
D_332   1   4   0   2   5
D_332   1   4   1   2   4
D_332   2   4   0   2   5
D_332   2   4   1   3   6
D_332   2   4   2   4   7
J_045   1   5   2   5   9
J_045   1   5   2   5   8
J_045   1   5   1   4   8
J_045   2   5   2   5   9
J_045   2   5   1   5   8
J_045   2   5   1   3   8
J_185   1   6   2   5   8
J_185   1   6   1   4
J_185   1   6   2   4   8
J_185   2   6   0   3   9
J_185   2   6   2   5   9
J_185   2   6   2   4   9
J_185   2   6   1   3   8

Code I'm using:
FHBficFit3dpi <- aov(X3dpi~ TrtName, FHBficData)
set.seed(115)
FHBficDunnett3dpi <- glht(model = FHBficFit3dpi, linfct=mcp(TrtName="Dunnett"))
summary(FHBficDunnett3dpi)

Results:
    Simultaneous Tests for General Linear Hypotheses
Multiple Comparisons of Means: Dunnett Contrasts

Fit: aov(formula = X3dpi ~ TrtName, data = FHBficData)

Linear Hypotheses:
                  Estimate Std. Error t value Pr(>|t|)
D_332 - D_112 == 0      0.1667     0.3624   0.460   0.9873
J_045 - D_112 == 0      1.0000     0.3624   2.759   0.0390 *
J_185 - D_112 == 0      0.9286     0.3492   2.659   0.0489 *
Neg_ctrl - D_112 == 0   0.6667     0.3624   1.840   0.2534
TC_ctrl - D_112 == 0    1.1667     0.3624   3.219   0.0128 *
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
(Adjusted p values reported -- single-step method)

I realize changing the model to "X3dpi ~ Trt" would result in the correct comparison, but I'd like to compare each of the treatments to the TC_ctrl group as well.

A: Try this: change the order of the factors and put the group you want first:
FHBficData$TrtName<-factor(FHBficData$TrtName,levels=c("TC_ctrl","D_332","J_045","J_185","Neg_ctrl","D_112"),ordered=TRUE)
FHBficFit3dpi <- aov(X3dpi~ TrtName, FHBficData)
set.seed(115)
FHBficDunnett3dpi <- glht(model = FHBficFit3dpi, linfct=mcp(TrtName="Dunnett"))
summary(FHBficDunnett3dpi)

You'll get this:
     Simultaneous Tests for General Linear Hypotheses

Multiple Comparisons of Means: Dunnett Contrasts

Fit: aov(formula = X3dpi ~ TrtName, data = FHBficData)

Linear Hypotheses:
                        Estimate Std. Error t value Pr(>|t|)
D_332 - TC_ctrl == 0     -1.0000     0.3624  -2.759   0.0391 *
J_045 - TC_ctrl == 0     -0.1667     0.3624  -0.460   0.9873
J_185 - TC_ctrl == 0     -0.2381     0.3492  -0.682   0.9361
Neg_ctrl - TC_ctrl == 0  -0.5000     0.3624  -1.380   0.5114
D_112 - TC_ctrl == 0     -1.1667     0.3624  -3.219   0.0128 *
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
(Adjusted p values reported -- single-step method)


Q: 3ds max script make group by parents Hy!
I am not so well experienced with max script, but I have written/modified an exporter that can export single meshes, groups using the built in obj exporter.
Now I want to select parents(usually theese are not 3Dobjects) in hierarchy and convert them to groups with their parrents, and I have no idea how exatly I should do it.
Any suggestions maybe script code you know?
Thanks in advanced

A: You can get the parent of any object in the scene by using
myParent = $myObject.parent

And you can use the following line to get all of a parent's children:
myParent.children

so in combination with select and group methods, you can do the following:
myParent = $myObject.parent
select myParent
selectmore myParent.children
group (GetCurrentSelection() as array) name:"myGroup"

And now you have a group named myGroup containing a parent object and all of its children. With a little tinkering you can turn this into a method and also iterate through every object in your scene. Hope this helps you.


Q: C miscalculating distances I wrote some code in C to convert your distance to other distance units but it seems to mix up the numbers and miscalculate the result.
I use a Windows 10 laptop, but, I don't think it matters because I used an online compiler (GDB) to write the code. I really don't even know where is the problem.
#include <stdio.h>

int main ()
{
    float distance;
    char in_unit[20];

    printf("Enter your distance:\n");
    scanf("%f", &distance);

    printf("Enter the length unit of your distance.(C=centimeters, Ft=feet, Kg=kilometers, In=inches, M=miles, Mtrs=meters)\n");
    scanf("%s", in_unit);
    if (in_unit == "Cm");
    {
        printf("Your distance in feet is:%f", distance/30.48);
        printf("\nYour distance in kilometers is:%f", distance/100000);
        printf("\nYour distance in inches is:%f", distance/2.54);
        printf("\nYour distance in miles is:%f", distance/160934.4);
        printf("\nYour distance in meters is:%f", distance/100);
    }
    if (in_unit == "Ft")
    {
        printf("Your distance in centimeters is:%f", distance*30.48);
        printf("\nYour distance in kilometers is:%f", distance/3280.84);
        printf("\nYour distance in inches is:%f", distance*12);
        printf("\nYour distance in miles is:%f", distance/5280);
        printf("\nYour distance in meters is:%f", distance/3.281);
    }
    if (in_unit == "Kg")
    {
        printf("Your distance in centimeters is:%f", distance * 100000);
        printf("\nYour distance in feet is:%f", distance * 3280.84);
        printf("\nYour distance in inches is:%f", distance * 39370.079);
        printf("\nYour distance in miles is:%f", distance / 1.609);
        printf("\nYour distance in meters is:%f", distance * 1000);
    }
    if (in_unit == "In")
    {
        printf("Your distance in centimeters is:%f", distance*2.54);
        printf("\nYour distance in feet is:%f", distance/12);
        printf("\nYour distance in kilometers is:%f", distance/39370.079);
        printf("\nYour distance in miles is:%f", distance/63360);
        printf("\nYour distance in meters is:%f", distance/39.37);
    }
    if (in_unit == "M")
    {
       printf("Your distance in centimeters is:%f", distance*160934.4);
       printf("\nYour distance in feet is:%f", distance*5280);
       printf("\nYour distance in kilometers is:%f", distance*1.609);
       printf("\nYour distance in inches is:%f", distance*63360);
       printf("\nYour distance in meters is:%f", distance*1609.344);
    }
    if (in_unit == "Mtrs")
    {
       printf("Your distance in centimeters is:%f", distance*100);
       printf("\nYour distance in feet is:%f", distance*3.281);
       printf("\nYour distance in kilometers is:%f", distance/1000);
       printf("\nYour distance in inches is:%f", distance*39.37);
       printf("\nYour distance in miles is:%f", distance/1609.344);
    }
    return 0;
}

For example, this is one of the runs:
Enter your distance:
1
Enter the length unit of your distance. (C=centimeters, Ft=feet, Kg=kilometers, In=inches, M=miles, Mtrs=meters)
Kg
Your distance in feet is:0.032808
Your distance in kilometers is:0.000010
Your distance in inches is:0.393701
Your distance in miles is:0.000006
Your distance in meters is:0.010000


Q: ASP.NET MVC Uploading with Extra Data and Jquery I am following an example from another question for uploading with jQuery.
http://aspzone.com/tech/jquery-file-upload-in-asp-net-mvc-without-using-flash/
I would like to extend this a bit to add more data to the upload though, through other form elements. Any idea how this could be done?

A: The website you have linked to does a post of the form ajaxUploadForm using the jQuery ajaxForm function.  I would presume that extra input data will be included when you add input elements to the ajaxUploadForm form.
Try it out: change the markup to the following (borrowed from the site in question):

<form id="ajaxUploadForm" action="<%= Url.Action("AjaxUpload", "Upload")%>" method="post" enctype="multipart/form-data">
    <fieldset>
     <legend>Upload a file</legend>
     File to Upload: <input type="file" name="file" />(100MB max size)
     <input type="text" id="someOtherInputElement" value="Test" />
     <input id="ajaxUploadButton" type="submit" value="Submit" />
    </fieldset>
</form>


Q: iPhone to Mac Sync Over Wi-Fi I am writing an iPhone application and would like to sync data over Wi-Fi between the iPhone and a complementary Mac application which I will also be writing (much like what is accomplished with Things and 1Password). To provide specific context, I need to be able to upload a CSV file to the iPhone application, have the ability to edit the data on the iPhone, and then re-download that file to the computer.
I am familiar enough with the mechanics of parsing and editing the CSV file once on the iPhone, but I am unsure how to approach the Wi-Fi sync between the iPhone and Mac. Obviously this is possible, since other applications have achieved the same thing, but do I need to setup some kind of server on the iPhone (which the Mac can talk to) or maybe a server in the Mac-side application (which the iPhone can talk to).
Any suggestions would be greatly appreciated. Thanks in advance.

A: In my apps, I use CocoaHTTPServer to get local info into and off of the phone.  You run the server and out-of-the-box, it indexes all the files in the documents directory.
To do what you want, you will need to edit the code to return some other kind of data format (xml probably is the easiest) the call this from inside your app to get that data.  CocoaHTTPServer easily take POST right out of the box too, so you can post an xml response as well.
After thinking about it, CocoaHTTPServer is best run on the computer side behind the scenes.  the iphone can then send info to the computer where handling the code should be easier and you have more options.

A: On top of this you will want to look into Bonjour, it will allow the computer and the iphone to discover each other without too much difficulty. (ie by advertising their info on the network)


Q: How to reference a custom DLL from an uncompiled .NET webservice For various reasons I'll not go into I need to write my .NET webservice outside of Visual Studio. This in itself is not difficult and the following works fine...
<%@ WebService Language="C#" Class="TestHW" %>

using System;
using System.Web.Services;
using System.Xml.Serialization

[WebService(Namespace="http://www.mydomain.com/services")]
public class TestHW : WebService {
    [WebMethod()]
    public string Add(int a, int b) {
        return a + b;
    }
}

I need to reference a custom .NET DLL from this webservice, but I can't get the .asmx to find the DLL (which resides in the same directory). Google is difficult because everyone apparently wants to reference a webservice from a DLL not the other way around. Everything is targeting .NET 2.0.
using websvc; //DLL is websvc.dll with namespace websvc

gives the error...
CS0246: The type or namespace name 'websvc' could not be found (are you missing a using directive or an assembly reference?)

Thanks for your time.

A: finally found at How do I reference a component in an inline web service?
<%@ Assembly Name="MyAssembly" %>

or
<%@ Assembly Src="path/myFile.cs" %>

The name syntax is for compiled DLLs and the src syntax is for open code. The dll seems to need to be in a bin directory under the root.


Q: How to express IN (list of argument) in a query LINQ? How do you write a linq query to express this:
Select * from Table
where column IN (some values);

By some values, I mean ('Value1', 'Value2', 'value3', ...).
Thanks for helping

A: Assuming
var some_values = new [] { "Value1", "Value2", "value3" };

Then:
data.Where(x => some_values.Contains(x))

Or:
from x in data
where some_values.Contains(x)
select x;


Q: Pyfst install error I'm having trouble installing Pyfst, which is a Python wrapper for OpenFst. I've tried using
pip install pyfst

but always end up with an error about some "unordered_map" which can't be found. Here's part of the stack trace:
In file included from fst/_fst.cpp:321:

/usr/local/include/fst/symbol-table.h:26:10: fatal error: 'unordered_map' file not found

#include <unordered_map>

A: Figured out a solution...
Environment: Ubuntu Server 14.04
Build and install OpenFST:
mkdir openfst
cd openfst
wget http://www.openfst.org/twiki/pub/FST/FstDownload/openfst-1.5.0.tar.gz
tar zxf openfst-1.5.0.tar.gz
cd openfst-1.5.0
./configure
make
sudo make install

The Magic:
sudo CFLAGS="-std=c++0x" pip install pyfst

Hope this helps.

A: i also came across the problem，but i solved it easily!
https://github.com/UFAL-DSG/pyfst
You should install OpenFst first,then to install fst!For more details,look at the link above.


Q: How to access Weave DNS-Server from external? I use the Weave network plugin on a Docker-Swarm.
I created a docker network with a specific IP-Range, different from the default Weave Network, to which I route from my internal network.
To make the containers even better accessible I use weave to attach DNS names like containername.auto.mycompany.de. Now I want to access those from my company Network. The Problem is, that weave only allows access to the weave DNS from the local host.
Like on one of my swarm nodes i can do:
host foobar.auto.mycompany.de 172.17.0.1
Using domain server:
Name: 172.17.0.1
Address: 172.17.0.1#53
Aliases:

foobar.auto.mycompany.de has address 10.40.13.3
Host foobar.auto.mycompany.de not found: 3(NXDOMAIN)
Host foobar.auto.mycompany.de not found: 3(NXDOMAIN)

But I don't find a way to make the weave container accessible on one of the IP's from this (10.40.130/24) docker network or expose the port to the swarm node.
The only way I can think of, but don't like, is doing something like this:
iptables -t nat -A  DOCKER -p tcp --dport 53 -j DNAT --to-destination 172.17.0.1:53

(this does not work, it's just the idea)
Or tamper with the weave script to make it expose the port on start of the weave container.
Does anybody know of a better solution?

A: In fact setting the rules
iptables -A DOCKER -p tcp -m tcp --dport 53 -j DNAT --to-destination 172.17.0.1:53
iptables -A DOCKER -p udp -m udp --dport 53 -j DNAT --to-destination 172.17.0.1:53

does it. When I first tried that, I simply missed to see, that my request would have come from "outside" the server to work, not from inside to the loopback device.
Still not a pretty solution but it does the job. I'm looking forward to see better solutions from you guys.
(Bounty stands!)


Q: Create a file in the sdcard I'm trying to create a new file from a class that not implements an Activity. If I use the same code on a class that implements an activity the file is created but not if the class doesnt implement an activity. Whats wrong? Should I need the context? How can I do?
public class fileInfo {
File filename;
int indexfile;

public filesInfo(){
    indexfile = 0;

    String filepath = Environment.getExternalStorageDirectory().getAbsolutePath().toString() + "/MotionSensors/values.txt";
    filename = new File(filepath);

}

}
            ..
            }

A: What you have done above looks alright, but still if it doesn't work, then try this:
FileOutputStream fos = context.openFileOutput("filename", Context.MODE_PRIVATE);

This will create a file from non-activity class.


Q: how to read the data from excel sheet using two @Test in same class in testng selenium webdriver In this below example program, is it possible to use two @ test in one class,and then i have to fetch the data from excel sheet for both @ test in same excel sheet.is it possible?.two methods can be used in same class? one excel can contains both data's of two@ test?.please give me some ideas or example to be used two @ test in same class fetching data from excel sheet. I am waiting for reply.please help me...thanks in advance.
public class Test1 {
    @BeforeTest
    @Test(groups = { "" }, dataProvider = "getTestData", description = "")
    public void abc(String a, String b) {
    }

    @Test(groups = { "" }, dataProvider = "", description = "")
    public void abcd(String c, String d) {
    }

    @AfterMethod
    @DataProvider
    public Object[][] getTestData() {
        check = true;
        return TestUtil.getData(Sprint1xls, this.getClass().getSimpleName());
    }
}

A: Yes the above is possible. I still don't get it where is the problem statement. Did you try above? is it failing? if yes then what is the error?
1) Yes, You can have 2 @Test methods in one class using same data provider.
2) If in the same sheet if you are using same data for this tests then there is no problem at all. if there is different data for different test then in your data provider toggle between test data using method name.
Let me know if you need further help.


Q: How do I use a macro to expand a tuple to its members as function arguments? I have a function from an external library [1] like
fn set_color(r: f64, g: f64:, b: f64)

I would like to manage my colors in tuples like
let yellow = (1., 1., 0.);

I thought of a macro like:
macro_rules! rgb {
    ( $rgb:expr ) => { rgb.0, rgb.1, rgb.2 }
}

playground
and then
set_color(rgb!(yellow));

Unfortunately Rust then says: error: macro expansion ignores token ',' and any following.
How can I make this happen?

[1]: cairo::Context::set_source_rgb() and friends

A: You cannot do this. Rust macros are not C macros that perform dumb textual manipulation; Rust macros must result in valid Rust code and a, b, c is not valid.
The closest would be to pass in the function to the macro:
macro_rules! rgb {
    ($f:expr, $rgb:expr) => {
        $f($rgb.0, $rgb.1, $rgb.2)
    };
}

let white = (1., 1., 1.);
rgb!(set_color, white);


Q: With clean architecture do entities hold properties such a cursors? I have the following proto message
message ListGamesResponse{
    repeated Game games   =1;
    string nextCursor     =2;
    string previousCursor =3;
}

So I have an entity for Game for example. But here I run into a scenatio where I also have cursors. Does this mean that I should make models and entities for responses and requests? In some implementations of this architecture that I used for reference I don't see responses or requests in the domain layer.
How can I avoid having request and response entities in the domain layer? But still pass on the cursors?

A: In Clean Architecture we would clearly separate between entities which are part of your domain model and request/response objects which are passed to/from the application logic. The request/response objects would be specific to some particular application logic (use case interactor) while the entities are representing "central business rules" which apply to all the use case interactors.
For further explanation check out this article:
http://www.plainionist.net/Implementing-Clean-Architecture-Controller-Presenter/

A: you will need to have an entity of a collection of entities that has the cursors in it
for example

    message GamesList{
        repeated Game games   =1;
        string nextCursor     =2;
        string previousCursor =3;
    }

cause the entity you are dealing with on the domain layer is not just a list of games it's also the state of the list (offset, limit)


Q: jQuery: How do I sum a column of numbers with commas? I used the following function I found online and it works perfectly. However, when my user later asked for commas to be included in the numbers, it broke. It only adds the numbers preceding the comma.
Here is the function:
function sumOfColumns(tableID, columnIndex, hasHeader) {
            var tot = 0;
            $("#" + tableID + " tr" + (hasHeader ? ":gt(0)" : ""))
              .children("td:nth-child(" + columnIndex + ")")
              .each(function() {
                  tot += parseInt($(this).html());
              });

Do I need to stop the 'parseInt' piece?

A: I'm assuming that you mean that the numbers now have commas as a thousands-separator, like this:
1234567 = "1,234,567"

You can remove all of those commas before you call parseInt, like this:
tot += parseInt($(this).html().replace(',',''));


Q: Why is the lifetime of objects with explicit destructors extended? I have been learning C++ and programmed this out of curiosity:
#include <iostream>

class A {};

class B {
    public:
        ~B() {}
};

A get_a() {
    A a;
    std::cout << &a << '\n';

    return a;
}

B get_b() {
    B b;
    std::cout << &b << '\n';

    return b;
}

int main() {
    A a = get_a();
    std::cout << &a << '\n';

    B b = get_b();
    std::cout << &b << '\n';

    return 0;
}

I got this as the ouput:
0x61fedf
0x61ff0f
0x61ff0e
0x61ff0e

This implies that a new object is constructed in the case of A, but the lifetime of B is simply extended.
Can anyone explain this to me? I am currently writing a library and don't want to have any incorrect preconceptions.

A: This is most likely an optimization feature of your compiler. For example, when I compiled your code using CL (MSVC compiler) without any optimization option, I got the following results:

But turning on fast code option, resulted in a more optimized memory usage:

Commands for disabled and fast code options of CL, respectively:
>cl /OD app.cpp
>cl /O2 app.cpp

You should refer to your compiler documentations to figure out the optimization options.


Q: Modal closes after opening I have a a picture in my localhost website. I want to show the full size of it by using a modal. It is working well, the picture is shown, but the problem is the after clicking the show modal, it automatically closes after maybe 2 seconds. Why is that?

A: I've seen this problem pop up before. Are you including bootstrap.js and bootstrap-modal.js? If so, remove the include for bootstrap-modal.js. See if that helps :)


Q: How can I format primefaces progressbar's value to always show 2 decimal digits? I cannot find a way to make the primefaces progress bar to show two decimal digits.
I have googled primefaces progress bar but I couldn't find anything related to format the output value.
Here is the code.
<p:progressBar
    value="#{data.financingDataModel.mortgagePercentage}"
    styleClass="animated ui-soba-progress-bar " global="false" style="overflow:hidden">
</p:progressBar>

The mortgagePercentage type is Double.
I want it to show 60.00% instead of just 60%.

A: Can you try this:
  <p:progressBar
     value="#{data.financingDataModel.mortgagePercentage}"
     styleClass="animated ui-soba-progress-bar " global="false"
     style="overflow:hidden"
     labelTemplate="#{data.financingDataModel.mortgagePercentage}%">
  </p:progressBar>

I only add the `labelTemplate'. It is working on me in PF 7


Q: Limit width and height of image on input field Is it possible to limit the width and height of the pic on input field by using html, css and javascript/jquery? I'm trying to limit it for profile photo upload (need the photo to be a perfect square, e.g. 200x200, 300x300)

A: PHP has a function called getimagesize().
list($width, $height, $type, $attr) = getimagesize("img.jpg");

as can be seen in the documentation:
http://php.net/manual/en/function.getimagesize.php
So, just check the height and width before submitting to the database

A: You can check the height of width of the image by creating an image from the uploaded file.
$("#fileUploadForm").submit(function(e){
var window.URL = window.URL || window.webkitURL;
var fileInput = $(this).find("input[type=file]")[0],
    file = fileInput.files ? fileInput.files[0] : null;

if( file ) {
    var img = new Image();

    img.src = window.URL.createObjectURL( file );

    img.onload = function() {
        var width = img.naturalWidth,
            height = img.naturalHeight;

        window.URL.revokeObjectURL( img.src );

        if( width == height) {//perfect square
            this.submit();
        }
        else {
            //fail
        }
    };
}
});


Q: Issue with nuxt/auth For auth I do use nuxt-auth, when the login is successful, I want to redirect to the main page using this.$router.push('/'), then I get a response like blank page with the following message

2021

,

// for login
<template>

    <div
      class="container-login100"
      :style="{
        backgroundImage: 'url(' + require(`@/assets/login/images/bg-01.jpg`) + ')',
      }"
    >

        <form class="login100-form validate-form flex-sb flex-w">
           Login Admin

            Facebook

            <img :src="require(`@/assets/login/images/icons/icon-google.png`)" alt="GOOGLE" />
            Google

             Email

            <input v-model="auth.email" class="input100" type="email" name="email" />

             Password

             Forgot?

            <input v-model="auth.password" class="input100" type="password" name="pass" />

            Login

             Not a member?

             Register now

        </form>

</template>

store vuex index.js
export const getters = {
  isAuthenticated(state) {
    return state.auth.loggedIn
  },

  loggedInUser(state) {
    return state.auth.user
  }}
}

layout default.vue
<template>

    <Sidebar v-if="isAuthenticated" />

      <Navbar v-if="isAuthenticated" />
      <Nuxt />

</template>

// auth nuxt config
auth : {
  strategies: {
    local: {
      token: {
        property: 'token',
        required: true,
        type: 'Bearer'
      },
      user: {
        property: 'user',
        autoFetch: true
      },
      endpoints: {
        login: { url: '/sign/login', method: 'post' },
        logout: { url: '/sign/logout', method: 'post' },
        user: { url: '/sign/user-login', method: 'get' }
      }
    }
  }
}

base index ('/')
<template>

      <Logo />

Learn Nuxt

          Documentation

          GitHub

</template>

A: In your vuex store, the state parameter in your getter only has access to local state. You can't access the auth state the way you tried.
In a vuex module, a getter gets 4 arguments, namely local state, local getters, root state and root getters. So if you would rewrite your getters like this it would probably work:
export const getters = {
  isAuthenticated(state, getters, rootState) {
    return rootState.auth.loggedIn
  },

  loggedInUser(state, getters, rootState) {
    return rootState.auth.user
  }}
}

But I still think it is a bit redundant doing it like that. I would replace isAuthenticated with this.$auth.loggedIn in your default layout. The nuxt-auth module globally injects the $auth instance, meaning that you can access it anywhere using this.$auth.

A: I had same problem after authorizing user and redirect user to the home page.
After many tries and doing many works, the right config of auth in nuxt.config.js seemed like this:
auth: {
    strategies: {
      local: {
        scheme: 'refresh',
        token: {
          property: 'access_token',
          tokenType: false,
          maxAge: 60 * 60
        },
        refreshToken: {
          property: 'refresh_token',
          data: '',
          maxAge: 60 * 60
        },
        endpoints: {
          login: {
            url: 'url/of/token',
            method: 'urlMethod'
          },
          refresh: {
            url: 'url/of/refreshToken',
            method: 'urlMethod'
          },
          logout: false,
          user: false
        }
      }
    },
    cookie: false,
    redirect: {
      login: '/login/page',
      logout: '/login/page',
      callback: false,
      home: '/home/page'
    }
  },

Note that I didn't have any refreshToken property, but I should set it as empty string in config to be able to work with nuxt/auth!
Hope I could help


Q: how to replace special characters from mysql string there is a table in mysql database and it has strings, datatype is text, and the data which is inserted is as below
HELLO+THIS+IS+OFFER!!%+HURRY!!%0ACall+US+NOW%
How do I remove % and + special characters from this string, it looks like encoded string.
Best Regards
CJ

A: Below mysql function removes special characters from a string:
DROP FUNCTION IF EXISTS replacespecialchars;
DELIMITER |
CREATE FUNCTION replacespecialchars( str CHAR(255) ) RETURNS CHAR(255) DETERMINISTIC
BEGIN
  DECLARE i, len SMALLINT DEFAULT 1;
  DECLARE ret CHAR(255) DEFAULT '';
  DECLARE c CHAR(1);
  SET len = CHAR_LENGTH( str );
  REPEAT
    BEGIN
      SET c = MID( str, i, 1 );
      IF c REGEXP '[[:alnum:]]' THEN
        SET ret=CONCAT(ret,c);
      END IF;
      SET i = i + 1;
    END;
  UNTIL i > len END REPEAT;
  RETURN ret;
END |
DELIMITER ;


Q: FreeMarker error: For "-" left-hand operand: Expected a number, but this has evaluated to a string I am trying to compute sum of values in map and print line of "-"s (the length of this line should be sum-1).
This is the code of my function:
<#function getSeparatorLine map>
    <#if !map?has_content>
        <#return "">
    </#if>
    <#local borderLength = 0>
    <#list map?keys as item>
        <#local borderLength = borderLength + item + 1>
    </#list>
    <#return ""?right_pad(borderLength - 1, "-")>
</#function>

I get a freemarker error saying:
ERROR freemarker.runtime - Error executing FreeMarker template
freemarker.core.NonNumericalException: For "-" left-hand operand: Expected a number, but this has evaluated to a string (wrapper: f.t.SimpleScalar):
==> borderLength  [in template "negative_events_report.template" at line 38, column 27]

Any suggestions?

A: item is a string, so borderLength + item + 1 actually does string concatenation instead of arithmetical addition. Assuming map contains numerical values, you should write map?values, not map?keys.


Q: Leetcode C++ for loop condition The error comes from one Leetcode test case for this problem. I copy my solution so that the particular test case will break.
class Solution {
public:
    vector<vector<int>> threeSum(vector<int>& nums) {
        vector<vector<int>> res;
        sort(nums.begin(), nums.end());

        for (int i = 0; i < nums.size() - 2; i++) {
            cout << "nums.size(): " << nums.size() << endl;
            if (i > 0 && nums[i] == nums[i-1])
                continue;
            int left = i + 1, right = nums.size() - 1;
            while(left < right) {
                int s = nums[i] + nums[left] + nums[right];
                if (s > 0) right--;
                else if (s < 0) left++;
                else {
                    res.push_back({nums[i], nums[left], nums[right]});
                    while(left + 1 < right && nums[left] == nums[left+1]) left++;
                    while(right - 1 > left && nums[right] == nums[right-1]) right--;
                    left ++; right--;
                }
            }
        }

        return res;
    }
};

Last executed input []
I'm confused because in this case, since nums is an empty vector, nums.size() should be 0, and since i < nums.size() - 2 = -2 is not met, the for loop shouldn't be executed but somehow I got a runtime error. Could someone please explain why this breaks? Thanks in advance!

A: nums.size() return a unsigned value,-2 cause overflow.
(int)nums.size()-2 can solve it.

A: The problem is that the size() function returns an unassigned int, and you're comparing it to i, which is a signed int.
Turn this line...
for (int i = 0; i < nums.size() - 2; i++) {

Into this...
for (int i = 0; i < ((int)nums.size()) - 2; i++) {

And here's a link to someone else with a similar problem, if you wanna read more about other solutions...
What is wrong with my For loops? i get warnings: comparison between signed and unsigned integer expressions [-Wsign-compare]


Q: Git pull origin [branch name] vs git checkout -t origin/[branch name] I do jobs in local server and push them to the branch. after that, I would like to pull the branch from remote repository to webserver. When I would like to bring the jobs updated on the branch into the web server, which command on the following is correct?
git pull origin [branch name]

vs.
git checkout -t origin/[branch name]

The job I've done on branch is now totally different with the main one. I do not want any merge branch to main so now the job on branch is like other project, nothing to do with the original project on the main. let me call the jobs I've done on the branch 'B project'. I would like to manage B project only on the branch and original one still on main.
Is that a good idea? Or is there a better way for this plan?

A: You could use separate branches for each feature. I personally use a hierarchy similar to below.
/
|---features
    |--- A
    |--- B

That would result in /features/A and /features/B branches respectively. That way you could work on your features on separate branches and use main branch as stable version of your application.
After your last edit, I would definitely recommend the solution below.
Or a better solution for entirely different jobs, you could use git-worktree command.
git worktree add [-b <new-branch>] <path> [<the branch/tree you want to base this worktree>]

This is the best I could from what I've understand from your question.

A: For my understanding, you have a main project and a different project which is based on the main, while being significantly different.
If that's the case, I would have different repositories for the two, so to keep them more maintainable.
The main repo will stay as it is, while on the second one we want to add the main repo as a remote origin.
To do that let's first:

*

*Create a new repo at github

*Clone the main repo locally if not done already

You can then add the main repo as a remote origin:

*git remote rename origin upstream

*git remote add origin URL_TO_MAIN_GITHUB_REPO

*git push origin master
Now you can work with it just like any other github repo.
To pull in patches from upstream, simply run git pull upstream master && git push origin master.
To underline I would follow this solution if you have two different projects based on some common changes, as branches works well for features / patches you would then want to merge to master once they are completed.
If, on the other hand, you simply have the same project with different features, then @Deniz da King solution is great.


Q: Excel Vba dictionary not looped

I have this code that is supposed to iterate through my folder and add the file names into the dictionary, however after adding my extraction code inside this for loop, only data from the last file in the folder will be extracted because everytime it collects data from the next file, it will overwrite the row and column "A2:M2" and not continue adding on.
UPDATED
Public Dict As Object
Sub EEE()

    Application.ScreenUpdating = False
    Application.EnableEvents = False
    Application.Calculation = xlCalculationManual
    Application.DisplayStatusBar = False

Dim oFSO As Object, oFolder As Object, ofile As Object

Set oFSO = CreateObject("Scripting.fileSystemObject")
Set oFolder = oFSO.GetFolder("C:\Users\Desktop\file\")

If Dict Is Nothing Then
Set Dict = CreateObject("Scripting.Dictionary")
    Dict.Add Key:="filename", Item:=ofile
End If

For Each ofile In oFolder.Files
    If Not Dict.Exists(oFSO.GetBaseName(ofile)) Then

    Dim basePath As Variant
    basePath = "C:\Users\Desktop\file\"

             Dim baseFolder As Scripting.Folder
        With New Scripting.FileSystemObject
            Set baseFolder = .GetFolder(basePath)
        End With

            Dim file As Scripting.file
            For Each file In baseFolder.Files

            Dim a As Range

        Dim wkbData As Workbook
            Set wkbData = Workbooks.Open(file.path)

        Dim wksData As Worksheet
            ActiveSheet.Name = "Book1"
            Set wksData = wkbData.Worksheets("Book1") ' -> Assume this file has only 1 worksheet

            Dim LastRow As Long
                LastRow = wks.Range("A" & wks.Rows.count).End(xlUp).row + 1

            wks.Cells(LastRow, 6).value = file.Name

        Set a = wksData.Columns("A:A").Find("  test1234         : ", LookIn:=xlValues)
        If Not a Is Nothing Then
        wks.Cells(LastRow, 1) = Split(a.value, ":")(1)
        End If

                wkbData.Close False

                Range("A:M").EntireColumn.AutoFit
                Range("A1").AutoFilter

        Debug.Print "A: " & oFSO.GetBaseName(ofile)
        Dict.Add oFSO.GetBaseName(ofile), 1
                Next file

    Else
        'skip
        Debug.Print "E: " & oFSO.GetBaseName(ofile)

    End If

Next ofile

        Application.ScreenUpdating = True
        Application.EnableEvents = True
        Application.DisplayStatusBar = True

End Sub


Q: Print To Zebra Printer TLP 3842 How can I print to Zebra Printer TLP 3842 using EPL Programming? The printer doesn't support Zebra Printer Language (ZPL) and I am using PrintDocument(). I been on this problem for two weeks and can't figure it out. This what I have so far in my code, that actually runs the printer:
private System.ComponentModel.Container Components;
    private System.Windows.Forms.Button PrintButton;
    private Font PrintFont;
    private StreamReader StreamToPrint;

    private void PrintButton_Click(Object Sender, EventArgs e)
    {
        try
        {
            StreamToPrint = new StreamReader("C:\\Users\\jcabrera\\Desktop\\MyFile.txt");
            //string ZPL_STRING = "^XA^LL440,^FO50,50^A0N,50,50^FDTesting Zebra Printer^FS^XZ";

            // ZPL Command(s)

            try
            {
                PrintFont = new Font("Arial", 10);
                PrintDocument PD = new PrintDocument();
                PD.PrintPage += new PrintPageEventHandler(this.PD_PrintPage);
                PD.Print();

            }
            finally
            {
                StreamToPrint.Close();
            }
        } catch(Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

    private void PD_PrintPage(object Sender, PrintPageEventArgs ev)
    {
        float linesPerPage = 0;
        float yPos = 0;
        int count = 0;
        float leftMargin = ev.MarginBounds.Left;
        float topMargin = ev.MarginBounds.Top;
        string line = null;

        // Calculate the number of lines per page.
        linesPerPage = ev.MarginBounds.Height /
           PrintFont.GetHeight(ev.Graphics);

        // Print each line of the file.
        while (count < linesPerPage &&
           ((line = StreamToPrint.ReadLine()) != null))
        {
            yPos = topMargin + (count *
               PrintFont.GetHeight(ev.Graphics));
            ev.Graphics.DrawString(line, PrintFont, Brushes.Black,
               leftMargin, yPos, new StringFormat());
            count++;
        }

        // If more lines exist, print another page.
        if (line != null)
            ev.HasMorePages = true;
        else
            ev.HasMorePages = false;
    }

    private void InitializeComponent()
    {
        this.Components = new System.ComponentModel.Container();
        this.PrintButton = new System.Windows.Forms.Button();

        this.ClientSize = new System.Drawing.Size(504, 381);
        this.Text = "Print Example";

        PrintButton.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
        PrintButton.Location = new System.Drawing.Point(32, 110);
        PrintButton.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
        PrintButton.TabIndex = 0;
        PrintButton.Text = "Print the file.";
        PrintButton.Size = new System.Drawing.Size(136, 40);
        PrintButton.Click += new System.EventHandler(PrintButton_Click);
        this.Controls.Add(PrintButton);
    }

Using Windows Application project.

A: You need to add RawPrinterHelperClass to your project, and then print like this
string ZPL_STRING = "^XA^LL440,^FO50,50^A0N,50,50^FDTesting Zebra Printer^FS^XZ";
RawPrinterHelper.SendStringToPrinter("PrinterName", ZPL_STRING)

C# Class
https://github.com/andyyou/SendToPrinter/blob/master/Printer/RawPrinterHelper.cs


Q: Creating a hard link to partial file contents in linux I have fileA, which has a size of 200 MB. Now I want to create a hardlink to fileA, named fileB, but I only want this file point to the first 100 mb of fileA. So basically I need fileB to point to the same data blocks, but with a different length. It doesn't necessarily have to be a real hardlink it could be a virtual file proxying contents.
I was thinking about duplicating the Inode somehow and changing the length, but I presume this could cause filesystem coherency issues (when datablocks move around etc.). Is there any linux tool or user-level system call that could let me do this?

A: You cannot do this directly in the manner you are talking about. There are filesystems that sort of do this. For example LessFS can do this. I also believe that the underlying structure of btrfs supports this, so if someone put the hooks in, it would be accessible at user level.
But, there is no way to do this with any of the ext filesystems, and I believe that it happens implicitly in LessFS.
There is a really ugly way of doing it in btrfs. If you make a snapshot, then truncate the snapshot file to 100M, you have effectively achieved your goal.
I believe this would also work with btrfs and a sufficiently recent version of cp you could just copy the file with cp then truncate one copy. The version of cp would have to have the --reflink option, and if you want to be extra sure about this, give the --reflink=always option.

A: Adding to @Omnifarious's answer:
What you're describing is not a hard link.  A hard links is essentially a reference to an inode, by a path name.  (A soft link is a reference to a path name, by a path name.)  There is no mechanism to say, "I want this inode, but slightly different, only the first k blocks".  A copy-on-write filesystem could do this for you under the covers.  If you were using such a filesystem then you would simply say
cp fileA fileB && truncate -s 200M fileB

Of course, this also works on a non-copy-on-write filesystem, but it takes up an extra 200 MB instead of just the filesystem overhead.
Now, that said, you could still implement something like this easily on Linux with FUSE.  You could implement a filesystem that mirrors some target directory but simply artificially sets a maximum length to files (at say 200 MB).
FUSE
FUSE Hello World

A: Maybe you can check ChunkFS. I think this is what you need (I didn't try it).


Q: deserialize json without property name .Net I'm using JSON.NET to deserialize response from HTTP, but I'm stuck with an issue. That's because the response sending results wthout property names
i have something like this
{"people":{"jack":{"condition":"good","version":"1.0.5"},"jim":{"condition":"bad","version":"1.0.5"}},"hede":14,"hodo":"apple"}
how can I put this in a class.
not: json result can have more than jack and jim when i paste as a class it creates jim and jack classes. bob and mike will come soon.
sorry bro. i was just writing my effort but my daughter woke up. went to send her to bed back. what I mean is, after searching "good" in dictionaries i want to go back and find "jack".
var values = from value in dictioanries.values
where value.condition ="good"
select new { value.condition, value.version }

ok here I searched the dictionaries, there are 2 of them(jack and jim) i want to know under which dictionary i found "good"

A: You don't have a class as much as you have a dictionary of string and objects. If you do the following, you should be able to deserialize properly:
public class PeopleResponse
{
  public Dictionary<string, Info> people { get; set; }
  public string hede { get; set; }
  public string hodo { get; set; }
}

public class Info
{
  public string condition { get; set; }
  public string version { get; set; }
}

From there, you should be able to do:
var results = JsonConvert.DeserializeObject<PeopleResponse>("{myJSONGoesHere}");

Edit: Based on your updated question, if you would like to get the names of all whose condition is "good," you can do the following (assuming your deserialized object is called results:
var goodStuff = from p in results.people
                where p.Value.condition.ToLower() == "good"
                select p.Key;

You could, of course, just get p instead of p.Key, which would return the entire key/value pair.


Q: Manually upload symbols to Azure DevOps We are running an Azure DevOps Server on premise.
We use the git repos and the artifacts nuget feed for our project.
Currently we do our builds (for the nugets) manually without the pipelines and upload the nugets later.
If we would use the pipelines the "Index sources and publish symbols" task would place the symbols to a file share.
So I have two questions:
Is there a way to upload the symbols manually (e.g. via CLI like we can with the nugets)?
Anywhere a documentation how the URL of the file share would look like on an on premise server? All examples I found so far only show dev.azure.com

A:
Is there a way to upload the symbols manually (e.g. via CLI like we can with the nugets)?

The answer is yes.
You could use the push both primary and symbol packages at the same time using the below command. Both .nupkg and .snupkg files need to be present in the current folder:
nuget push MyPackage.nupkg -source

And publish to a different symbol repository, or to push a legacy symbol package that doesn't follow the naming convention, use the -Source option:
nuget push MyPackage.symbols.nupkg -source https://nuget.smbsrc.net/

Please refere the document for some more details:
Publishing a symbol package
Publishing a legacy symbol package

Anywhere a documentation how the URL of the file share would look like
on an on premise server?

You could check the document Index Sources & Publish Symbols task:


Q: How to export a SSHA-256 password in LDAP I want to export a password from a database where the scheme for saving passwords is SSHA-256. The password of the database looks like {"salt", crypt("pass"+"salt")} and here is an example: WbwTWc,BFWTku+j6Up2XovqmpNFATe4g9aEWWW1shFysmzx/QY{SHA-256}.
Now I want to copy this password to my Open LDAP server. I have already copied SHA-256 password in the LDAP by using {SHA-256}+"Encrypted Password" and it worked fine.
Could anyone please help me out how can I import this SSHA-256 password to my LDAP server. Any help will be highly appreciated and thanks in advance.

A: What LDAP server is this? If it supports SSHA-256, then the same style i.e. {SSHA-256}+"Encrypted Password" should work.


Q: jquery-autocomplete does not work with my django app I have a problem with the jquery-autocomplete pluging and my django script. I want an easy to use autocomplete plugin. And for what I see this (http://code.google.com/p/jquery-autocomplete/) one seems very usefull and easy. For the django part I use this (http://code.google.com/p/django-ajax-selects/) I modified it a little, because the out put looked a little bit weired to me. It had 2 '\n' for each new line, and there was no Content-Length Header in the response. First I thought this could be the problem, because all the online examples I found had them. But that was not the problem.
I have a very small test.html with the following body:

<form action="" method="post">

Tag list:
<input id="id_tag_list" name="tag_list" maxlength="200" type="text" />

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

And this is the JQuery call to add autocomplete to the input.
function formatItem_tag_list(row) {
    return row[2]
}
function formatResult_tag_list(row) {
    return row[1]
}

$(document).ready(function(){
    $("input[id='id_tag_list']").autocomplete({
        url:'http://gladis.org/ajax/tag',
        formatItem: formatItem_tag_list,
        formatResult: formatResult_tag_list,
            dataType:'text'
    });
});

 When I'm typing something inside the Textfield Firefox (firebug) and Chromium-browser indicates that ther is an ajax call but with no response. If I just copy the line into my browser, I can see the the response. (this issue is solved, it was a safety feature from ajax not to get data from another domain)
For example when I am typing Bi in the textfield, the url "http://gladis.org/ajax/tag?q=Bi&max... is generated. When you enter this in your browser you get this response:
4|Bier|Bier
43|Kolumbien|Kolumbien
33|Namibia|Namibia

Now my ajax call get the correct response, but there is still no list showing up with all the possible entries. I tried also to format the output, but this doesn't work either. I set brakepoints to the function and realized that they won't be called at all.
Here is a link to my minimum HTML file http://gladis.org/media/input.html
Has anybody an idea what i did wrong. I also uploaded all the files as a small zip at http://gladis.org/media/example.zip.
Thank you for your help!
[Edit]
here is the urls conf:
(r'^ajax/(?P<channel>[a-z]+)$', 'ajax_select.views.ajax_lookup'),

and the ajax lookup channel configuration
AJAX_LOOKUP_CHANNELS = {
    # the simplest case, pass a DICT with the model and field to search against :
    'tag' : dict(model='htags.Tag', search_field='text'),
}

and the view:
def ajax_lookup(request,channel):
    """ this view supplies results for both foreign keys and many to many fields """

    # it should come in as GET unless global $.ajaxSetup({type:"POST"}) has been set
    # in which case we'll support POST
    if request.method == "GET":
        # we could also insist on an ajax request
        if 'q' not in request.GET:
            return HttpResponse('')
        query = request.GET['q']
    else:
        if 'q' not in request.POST:
            return HttpResponse('') # suspicious
        query = request.POST['q']

    lookup_channel = get_lookup(channel)

    if query:
        instances = lookup_channel.get_query(query,request)
    else:
        instances = []

    results = []
    for item in instances:
        results.append(u"%s|%s|%s" % (item.pk,lookup_channel.format_item(item),lookup_channel.format_result(item)))

    ret_string = "\n".join(results)
    resp = HttpResponse(ret_string,mimetype="text/html")
    resp['Content-Length'] = len(ret_string)
    return resp

A: You probably need a trailing slash at the end of the URL.
Also, your jQuery selector is wrong. You don't need quotes within the square brackets. However, that selector is better written like this anyway:
$("input#id_tag_list")

or just
$("#id_tag_list")

A: Separate answer because I've just thought of another possibility: is your static page being served from the same domain as the Ajax call (gladis.org)? If not, the same-domain policy will prevent Ajax from being loaded.

A: As an aside, assuming your document.ready is in your Django template, it would be a good idea to utilize the {% url %} tag rather than hardcoding your URL.
$(document).ready(function(){
    $("input[id='id_tag_list']").autocomplete({
        url:'{% url my_tag_lookup %}',
        dataType:'text'
    });
});

This way the JS snippet will be rendered with the computed URL and your code will remain portable.

A: I found a solution, but well I still don't know why the first approach didn't worked out. I just switched to a different library. I choose http://bassistance.de/jquery-plugins/jquery-plugin-autocomplete/. This one is actually promoted by jQuery and it works ;)


Q: update gmail contacts C# exception I am trying to update gmail contacts info
Contact updatedContact = contact.Contact;
updatedContact.Content = "Contact information for " + contact.Contact.Name.FullName;
Uri feedUri = new Uri(ContactsQuery.CreateContactsUri("default"));
RequestSettings rs2 = new RequestSettings("CreateContacts", username, password);
ContactsRequest cr = new ContactsRequest(rs2);
Contact createdContact = cr.Update(updatedContact);

but I got that exception
"execution of request failed http://www.google.com/m8/feeds/contacts/"mail"/full/..."

any ideas?

A: It's an issue with your machine running the code, it may work on other machines.
If you are behind a proxy, here is an article on how to setup properly with proxies:
http://code.google.com/apis/gdata/articles/proxy_setup.html

A: I find the reason of the exception
there is no problems appears when names are updated like that
contact.Name.FullName = value;

but when update phone numbers like that the above exception appears
contact.Phonenumbers.Add(new Google.GData.Extensions.PhoneNumber(value));

it appears that gmail return the same exception regardless of what error had happened, how can I understand that from just "execution of request failed", that is quite annoying.
I hope they add some details, though I do not know what is wrong in updating phone numbers like that.


Q: Git push/clone not working using HTTPS without any sort of firewall/proxy only in Ubuntu Git push when using HTTP gives this
fatal: unable to access 'https://github.com/something.git/':
       Failed to connect to github.com port 443: Network is unreachable

While git clone gives this
fatal: unable to access 'http://github.com/something.git/':
       Failed to connect to github.com port 80: Network is unreachable

The same works on Windows using HTTP on same machine and on Ubuntu using SSH.
I tried looking at git config files but couldn't achieve anything.
I can access it via browser and HTTP remote for Heroku doesn't work too.
I tried purging and installing again but it made no difference.
ping github.com works; if that makes a difference
This is a personal computer at home directly connected to router and I have not enabled any firewall consciously.


Q: Getting notified about iframe loading I am developing an extension where I need to get notified whenever an iframe is loaded and ready. I used page-mod but I don't get the expected output. This is my code:
var data = require("sdk/self").data;
var pageMod = require("sdk/page-mod");

pageMod.PageMod({
 include: ['*'],
 contentScriptFile: data.url("pageNavData.js"),
 contentScriptWhen: "ready",
 attachTo: ["frame"],
 onAttach: function(worker) {
  worker.port.on("gotElement", function(elementContent) {
    console.log(elementContent);
  });
 }
});

And pageNavData.js is:
self.port.emit("gotElement", document.location.href);

Can anybody see what is wrong with this?

A: The problem here is that the "gotElement" message is emitted before the listener is attached.
You can fix it with:
setTimeout(_ => self.port.emit("gotElement", document.location.href));

Afaict you don't need the contentScript, just do what you wanted to do in the onAttach handler.


Q: What should i do to get "telegram private group ids" new way I want to create new bot that print users first name in telegram groups.
So it could be easily done in public groups but in private groups I need its id so I have to add bot to private groups and then what should I do?
I want to do it in Python or Pyrogram also I am not interested to use telegram API like this:
https://api.telegram.org/bot<token>/getUpdates

because I can not use it when I am using Python-telegram bot library.
The main problem is how am I suppose to get private group ids after I add the bot to it?

A: simply make the bot an admin in the targeted group, then the bot will be able to read messages from the group, thus you'll get the id
Or disable privacy mode from BotFather, check the link below:
https://core.telegram.org/bots#privacy-mode


Q: Recursively move folders/files within subfolders to its parent I have a high level folder (call it 'level 0'), which contains a hundred or so subfolders ('level 1'), and within those subfolders consist of lower level subfolders and files ('level 2'). I need to dynamically move every file and folder from 'level 2' to its level 1 subfolder (or relatively speaking - its parent).
To better visualize:

Master folder
├ Parent folder 1
│ ├─ Subfolder A
│ │  ├─ File A
│ │  └─ File B
│ ├─ Subfolder B
│ │  ├─ File C
│ │  └─ File D
│ ├─ File E
│ └─ File F
.
. ... many folders more ...
.
└─ Parent folder 134
   ├─ Subfolder CS
   │  ├─ File AGF
   │  └─ File ARH
   ├─ File ROQ
   └─ File JGL

I need to move everything from any subfolders' content within its parent folder. As above, you can see that there may be some files already in the parent folder (e.g. Files E, F) and they should stay put.
Objective:

Master folder
├─ Parent folder 1
│  ├─ File A
│  ├─ File B
│  ├─ File C
│  ├─ File D
│  ├─ File E
│  └─ File F
├─ Parent folder 119
│  ├─ File AZA
│  ├─ File AZB
│  ├─ File AZC
│  └─ File AZD
... and so on

The challenge here is that there are over a hundred of these parent folders beneath the master folder and all have different names. The subfolders within the parent folders also have different names as well.
I've tried approaching this using Get-ChildItem then with a 'ForEach' attempting to assign the child item (i.e. folder) as a variable and then performing another Get-ChildItem recursive and moving all content to the parent, but I'm getting nowhere and if any movement, it seems to be referring back to C:\Windows\ folder.
Note [sorry, correction Not*] literal code, but the approach, I'm thinking of:
$master = "\\data\Master"
gci $master | foreach {
    $parent = $_
    gci ... | Move-Item -Destination $parent
}

A: I did try to make something for you. This will move everything from level2 folder to the level1 folder. Pls try it, and let me know how its working.
$master = "C:\Temp\Level0\"
Get-ChildItem $master | ForEach-Object {
    $dest = ($_.fullname)+"\"
    $Loc = (Get-ChildItem $_.FullName | Select-Object -ExpandProperty fullname)+"\*"
    Move-item -Path $Loc -Destination $dest
}

A: This should do what you want. It will however not move any files with the same filename to the parent folder if the filename has already been used.
$FilePath = Read-Host "Enter FilePath"
$FileSource = Get-ChildItem -Path $FilePath -Directory

foreach ($Directory in $FileSource)
{
    $Files = Get-ChildItem -Path $Directory -File

    foreach ($File in $Files){
        Move-item -Path $File.Fullname -Destination $FilePath
    }
}

Hope that is of some use.


Q: Docker NodeJS Azure ServiceBus Service Lock Timeout Apart from changing "Lock Duration" setting in Azure Portal, I want to know how to set the timeout value/ renew lock mechanism. (Better to handle unknown long running tasks)

var azure = require('azure-sb'),
    serviceBusService = azure.createServiceBusService("Endpoint=XXX");
serviceBusService.receiveQueueMessage(MESSAGE_QUEUE_NAME, { isPeekLock: true }, function(error, lockedMessage){
... task running longer than "Lock Duration" ...
}

When finish, there is error and the message is moved to Deadletter Queue:

Error: 404 - The lock supplied is invalid. Either the lock expired, or
  the message has already been removed from the queue.

A: You can try and use renewLockForMessage to extend the lock.
Hope it helps!


Q: Why R/W transition mid-file in rb+ mode fails unless I use fseek(fp,0,SEEK_CUR)?Why it works at end of file? I had never realized this.I could have very well assumed subconsciously as a hard fact that I can transition between reading and writing on an existing file opened it update mode,just like that.But two questions on SO(1,2) drove me skeptical and I decided to try it out.Here's what I find:
In the first program,prog1,I work on a file source.txt which only has the line Lethal weapon.I read the first world Lethal using fscanf() and intend to write " musket" right after that expecting to get Lethal musket.But it simply fails, and I still get the original content Lethal weapon at the end of the write operation.But in that first program,if I insert the line fseek(fp,0,SEEK_CUR), the write operation works fine and I get Lethal musket.I notice that fseek(fp,0,SEEK_CUR) serves no purpose other than call fseek() just for the sake of it,as there is no net seeking at all.
But in the second program,prog2,the same scenario doesn't need thatfseek(fp,0,SEEK_CUR) statement.To be exact,in the second program,in contrast to reading to middle of file as in first program, here I read to the end of file,and then start writing there.Here the write is successful even without using fseek(fp,0,SEEK_CUR) and I get the desired content Lethal weapon sale.
Question: Why can't we transition from read to write mode in the middle of the file and what difference fseek(fp,0,SEEK_CUR) makes to get it working?And at the same time, why the same transition works without any fuss if we read to end of file and write there?Why fseek(fp,0,SEEK_CUR) is not needed in second case?How advisable is my use of fseek(fp,0,SEEK_CUR) to make the write successful in the first program?Any better alternative?
Two questions on SO seem to have addressed the same issue to some extent,but since they were based more on seeking explanation of excerpts from texts/books,the answers oriented towards them doesn't seem to address what I intend to know in precise terms.
//PROG1

#include <stdio.h>

int main ()
{
    FILE *fp=fopen("D:\\source.txt","r+");
    char arr[20],brr[50];
    fscanf(fp,"%s",arr);
    printf("String is %s\n",arr);
    //fseek(fp,0,SEEK_CUR);  //Doesn't work without it
    fprintf(fp," musket");
    rewind(fp);
    fgets(brr,50,fp);
    printf("New string is %s",brr);
    fclose(fp);
}

Output:
1) Without fseek() --   Lethal weapon
2) With fseek()    --   Lethal musket
//PROG2

#include <stdio.h>

int main ()
{
    FILE *fp=fopen("D:\\source.txt","r+");
    char arr[20],brr[50];
    fgets(arr,20,fp);
    printf("Initial line is %s\n",arr);
    fprintf(fp," sale"); //writes to end of file
    rewind(fp);
    printf("New string is %s",fgets(brr,50,fp));
    fclose(fp);
}

Output without fseek():  --  Lethal weapon sale

A: Actually, it looks like a bug in your libc implementation.
File I/O streams are usually a libc abstraction over the file descriptor based binary I/O implemented by the OS kernel. So any strange behaviour shall be attributed to your specific libc quirks.
Since you're apparently using Windows, that may be the source of your problems. What is the compiler you're using?
There is no such problem with GCC 4.6.1 and glibc-2.13 on Ubuntu 11.10.


Q: how to disable zoom slider through excel vba? I am looking to disable zoom slider in excel worksheet. I have looked around but couldn't find a solution to it. There are some solutions pointing to setting the zoom to a defined value but none of them caters to disabling the zoom option itself.
Any help would be much appreciated.
I am adding the code I have put in ThisWorkbook to disable most of the visible option on worksheet.
Private Sub Workbook_Activate()

Application.ScreenUpdating = False
Application.ExecuteExcel4Macro "SHOW.TOOLBAR(""Ribbon"",False)"
Application.DisplayFormulaBar = False
Application.DisplayStatusBar = Not Application.DisplayStatusBar
ActiveWindow.DisplayWorkbookTabs = False
Application.ScreenUpdating = True

End Sub

Private Sub Workbook_Deactivate()
Application.ScreenUpdating = False
Application.ExecuteExcel4Macro "SHOW.TOOLBAR(""Ribbon"",True)"
Application.DisplayFormulaBar = True
Application.DisplayStatusBar = True
Application.ScreenUpdating = True
ActiveWindow.DisplayWorkbookTabs = True
End Sub

Private Sub Workbook_Open()
Application.ScreenUpdating = False
'Hide list of sheets
Call hide_sheets
Windows(1).WindowState = xlMaximized
ActiveWindow.DisplayGridlines = False
Application.ExecuteExcel4Macro "SHOW.TOOLBAR(""Ribbon"",False)"
Application.DisplayFormulaBar = False
Application.DisplayStatusBar = Not Application.DisplayStatusBar
ActiveWindow.DisplayWorkbookTabs = False
ActiveWindow.Zoom = 100

'Lock cells in the UI sheet
ThisWorkbook.Sheets("UI").ScrollArea = "A1:t46"

'Hide scroll bar
With ActiveWindow
    .DisplayHorizontalScrollBar = False
    .DisplayVerticalScrollBar = False
End With

Application.ScreenUpdating = True
welcomeScreen.Show 0

End Sub

Some screen shots of the problem I am facing. I am currently using some makeshift arrangement by loading the maximized version userform on workbook opening. So the slider is hidden.

A: There doesn't appear to be a way to disable zoom completely or specifically the slider after looking around. If you're main mission is to avoid someone clicking on the zoom slider I would probably go with hiding the statusbar all together.
Application.DisplayStatusBar = False

A: To hide the zoom slider alone you can do so by editing the registry key
HKEY_CURRENT_USER\Software\Microsoft\Office\15.0\Excel\StatusBar
by setting ZoomSlider value to 0
Anyway, i don't think this can be achieved using VBA even with SaveSetting.
You can try write a .reg file to change the target key and VBA-load it. I'm not sure if this can be done but even if it works the user will still to have click Yes in a system prompt to allow the key to be loaded into registry.
And even when the user click Yes to allow the .reg file to load and change the registry key, Excel status bar doesn't refresh to show/hide the ZoomSlider, until Excel is restarted.
In short, hiding zoom slider alone using VBA doesn't seem to be achievable.


Q: Use of regex to validate home address I'm new at regex and I'm trying to create some validation process using regex. I'm checking if the given home address or location address is valid. I'm also validating other values using regex but they all work just fine, but this one only checks the first character entered. Try entering other special characters at any part of the value, the function will return true.
I'm only allowing letters, numbers, periods, commas, and whitespace.
Here's the code [Excluded the working code and regex]:

document.querySelector(".review-input").addEventListener("click", reviewSubmittedForm);

function runValidationForAddress(stringToBeChecked) {
  var regex = /^[a-zA-Z0-9\\,\\.\s]/g;
  if (regex.test(stringToBeChecked) === true) {
    //Valid
    console.log("String is valid.");
    return true;
  }
  else {
    //Invalid
    console.log("String is invalid! Please re-enter");
    return false;
  }
}

function reviewSubmittedForm() {
  var addressInput = document.querySelector(".address-input");
  if (runValidationForAddress(addressInput.value) === true) {
    console.log("Pass");
  }
  else {
    console.log("Denied");
  }
}
<input type="text" class="address-input" value="1600 Amphitheatre Parkway">
<input type="button" class="review-input" value="Submit">

After submitting, try to copy and paste this other location addresses:

@1600 Amphitheater Parkway

1600 @Amphitheatre $Parkway

1600 #Amphitheatre Parkway

A: Use ^[\w\s ,.]+$ for your validation.
You can check it online at https://regex101.com/r/q6LoSE/4.


Q: Unique comparable points at Java TreeSet Having a very simple example of Java code:
import java.util.*;

class Point implements Comparable<Point>{

   float x, y;

   Point(float x_, float y_) { x = x_; y = y_; }

   int compareTo(Point p_) { println(dist(x, y, p_.x, p_.y)); return dist(x, y, p_.x, p_.y) < 1E-4 ? -1 : 1; }

   float dist(float x0_, float y0_, float x1_, float y1_) { return sqrt(pow(x1_ - x0_, 2) + pow(y1_ - y0_, 2)); }

}

public static void main(String[] args){

   TreeSet<Point> tp = new TreeSet<Point>();

   tp.add(new Point(0.125, 0.5));
   tp.add(new Point(0.-125, 0.25));
   tp.add(new Point(0.15, -0.75));
   tp.add(new Point(0.125, 0.5));

   System.out.println(tp);

}

And I've thought that every point would be unique, while there is a distance checking and if it's below epsilon code should remove duplicate.
But it's not work right keeping the fourth entry despite the fact that it is a duplicate of the first entry.
My intention is to get a set of unique points (vectors).

A:
This is so because the Set interface is defined in terms of the equals operation, but a TreeSet instance performs all element comparisons using its compareTo (or compare) method, so two elements that are deemed equal by this method are, from the standpoint of the set, equal. The behavior of a set is well-defined even if its ordering is inconsistent with equals; it just fails to obey the general contract of the Set interface.

https://docs.oracle.com/javase/7/docs/api/java/util/TreeSet.html
In other words, The TreeSet class does not maintain the uniqueness of its elements via the equals method but with the compareTo method of the class implementation, if the class implements Comparable, or with the compareTo of the given Comparator.
As others have pointed out in the comments, if you want to maintain uniqueness among your Points by their coordinates, you should override the equals and hashCode methods, as the general hashcode contract states and utilize a HashSet to store your Points.
In the following snippet, I've updated your class by implementing the equals, hashCode and toString methods to show how only three elements are printed instead of four.
public class Point implements Comparable<Point> {

    double x, y;

    public Point(double x, double y) {
        this.x = x;
        this.y = y;
    }

    // ... your implementation ...

    @Override
    public boolean equals(Object obj) {
        if (obj == null) return false;
        if (obj == this) return true;
        if (obj.getClass() != getClass()) return false;
        Point other = (Point) obj;
        return x == other.x && y == other.y;
    }

    @Override
    public int hashCode() {
        return Objects.hash(x, y);
    }

    @Override
    public String toString() {
        return String.format("(%g;%g)", x, y);
    }

    public static void main(String[] args) {
        HashSet<Point> tp = new HashSet<>();

        tp.add(new Point(0.125, 0.5));
        tp.add(new Point(0. - 125, 0.25));
        tp.add(new Point(0.15, -0.75));
        tp.add(new Point(0.125, 0.5));

        System.out.println(tp);
    }
}


Q: AOT Compilation fails. Angular2 RC6 - Function call not supported - RouterModule.forChild(ROUTES) Environment:

Windows 10, IntelliJ 2016.2, node

*

*Angular version: 2.0.0-rc.6

*Language: [all | TypeScript X.X | ES6/7 | ES5]
Typescript ES6

*Node (for AoT issues): node --version =
Node 4.4.7, NPM 3.10.6
The AOT compiler fails, complaining about a function call or lamba reference. The only one is RouterModule.forChild(ROUTES), but previously it was able to compile with this reference. I dont see how the app can work without the imported component.
// /**
//  * Angular 2 decorators and services
//  */
// // import { BrowserModule } from '@angular/platform-browser'
//
import { CommonModule } from '@angular/common';
import { BrowserModule } from '@angular/platform-browser';
import { RouterModule } from '@angular/router';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
//
import { ROUTES } from './detail.routes';

/*
 * Shared Utilities & Other Services
 */
import { Logging } from '../services/utility.service';

/**
 * Imported Components
 */
import { DetailComponent } from './detail.component';

@NgModule({
   declarations: [// Components / Directives/ Pipes
      DetailComponent],
   imports: [CommonModule, BrowserModule, FormsModule, RouterModule.forChild(ROUTES),]
})

export class DetailModule {

   constructor() {
      if (Logging.isEnabled.light) { console.log('%c Hello \"Detail\" component!', Logging.normal.lime); }
   }
}

The error is
Error: Error encountered resolving symbol values statically. Function calls are not supported. Consider replacing the function or lambda with a reference to an exported function, resolving symbol DetailModule in C:/Source/POC/Microservice.Poc/src/app-components/+detail/index.ts, resolving symbol DetailModule in C:/Source/POC/Microservice.Poc/src/app-components/+detail/index.ts
    at simplifyInContext (C:\Source\POC\Microservice.Poc\node_modules\@angular\compiler-cli\src\static_reflector.js:473:23)
    at StaticReflector.simplify (C:\Source\POC\Microservice.Poc\node_modules\@angular\compiler-cli\src\static_reflector.js:476:22)
    at StaticReflector.annotations (C:\Source\POC\Microservice.Poc\node_modules\@angular\compiler-cli\src\static_reflector.js:61:36)
    at _loop_1 (C:\Source\POC\Microservice.Poc\node_modules\@angular\compiler-cli\src\codegen.js:53:54)
    at CodeGenerator.readFileMetadata (C:\Source\POC\Microservice.Poc\node_modules\@angular\compiler-cli\src\codegen.js:66:13)
    at C:\Source\POC\Microservice.Poc\node_modules\@angular\compiler-cli\src\codegen.js:100:74
    at Array.map (native)
    at CodeGenerator.codegen (C:\Source\POC\Microservice.Poc\node_modules\@angular\compiler-cli\src\codegen.js:100:35)
    at codegen (C:\Source\POC\Microservice.Poc\node_modules\@angular\compiler-cli\src\main.js:7:81)
    at Object.main (C:\Source\POC\Microservice.Poc\node_modules\@angular\tsc-wrapped\src\main.js:30:16)
Compilation failed

Why is RouterModule.forChild(ROUTES) making AOT compilation fail, when over here at this repo, it works fine with AOT compilation?

A: The problem was solved by switching from RC6 builds to the github builds:
This:
  "@angular/compiler-cli": "github:angular/compiler-cli-builds",
  "@angular/common": "2.0.0-rc.6",
  "@angular/compiler": "2.0.0-rc.6",
  "@angular/core": "2.0.0-rc.6",
  "@angular/forms": "^2.0.0-rc.6",
  "@angular/http": "2.0.0-rc.6",
  "@angular/platform-browser": "2.0.0-rc.6",
  "@angular/platform-browser-dynamic": "2.0.0-rc.6",
  "@angular/platform-server": "2.0.0-rc.6",
  "@angular/router": "3.0.0-rc.2",

Was changed to
"@angular/common": "github:angular/common-builds",
  "@angular/compiler": "github:angular/compiler-builds",
  "@angular/compiler-cli": "github:angular/compiler-cli-builds",
  "@angular/core": "github:angular/core-builds",
  "@angular/forms": "github:angular/forms-builds",
  "@angular/http": "github:angular/http-builds",
  "@angular/platform-browser": "github:angular/platform-browser-builds",
  "@angular/platform-browser-dynamic": "github:angular/platform-browser-dynamic-builds",
  "@angular/platform-server": "github:angular/platform-server-builds",
  "@angular/router": "github:angular/router-builds",
  "@angular/tsc-wrapped": "github:angular/tsc-wrapped-builds",

And it compiles fine now.