text:
Q: How to integrate .Net 4.6 IdentityFramework Data Access Layer and .Net Core Web API I am developing the middle and back end of a .Net application whose Web API is built using .Net Core. However, the Data Access Layer and data persistence layer, as well as the business logic, are built in a project which is in .Net 4.6/EF6 (due to issues with migration management in .Net Core).
The architecture has Units of Work which manage business logic and live in the DAL (in EF6). Theoretically the Web API layer needs no direct access to the database; it should be able to work through the UoWs (which could just as easily be mocked, etc.) However, the only way I can see right now to get the UoWs instantiated properly is through a dependency injection chain that ultimately requires the (.Net Core) Web API to have access to the (EF6) ApplicationDbContext.
This is a problem because there are different versions of Identity Framework for EF6 and Core, and the Web API project is not happy to deal with my ApplicationUser object, which extends IdentityUser. Specifically, VS complains that The type 'IdentityUser' is defined in an assembly that is not referenced. You must add a reference to assembly 'Microsoft.AspNet.Identity.EntityFramework, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35. So far as I can tell, that's not a dependency that can be satisfied in Core (which has its own implementation of Identity).
I am aware of the MS tutorial for how to deal with solutions that combine EF6 and Core projects, however this doesn't address the conflicting Identity dependencies. I'd love to have the DAL project handle its own dependency injection, but per this answer, I understand that a class-library-type situation has no container that would allow DI to happen.
In EF6 project I define ApplicationUser as:
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.AspNet.Identity;

public class AppUser : IdentityUser<int, AppUserLogin, AppUserRole, AppUserClaim>{}

Over in the Web API (Core) project, I am attempting to inject it via:
    public class Startup
    {
        private readonly IConfiguration _config;

        public Startup(IConfiguration configuration)
        {
            _config = configuration;
        }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddScoped<AppDbContext>(_ => new AppDbContext());
            services.AddScoped<AppUserRepository<BaseFluentQuery<AppUser>>>()
        }
    }

where the BaseFluentQuery is a base class that provides a lot of the data-wrangling interface for the BL layer. I'm specifically getting the missing-reference error from the reference to AppUser, although I would also get an error if I replaced AppDbContext with IAppDbContext (which directly references the IdentityDbContext class).
Ideally I would be able to have a working project backended in EF6 with Identity, and a Core Web API that is blissfully ignorant of all of this. I'd be happy with a solution that resolves the conflicting Identity dependencies or one that organizes the DI better--or hey, convince me I can move to the Core version of the ORM!--but I'm just not finding the correct model out there.


text:
Q: Excel List Parse Table I have an excel sheet with a primary key in one column and a list of attributes (pipe delimited) in another. Here is an example:
pk1     a | b | c
pk2
pk3     b | d
pk4     e

This goes on for about 38k rows.
I want to create a cross reference table out of this data so that it looks more like this:
pk1     a
pk1     b
pk1     c
pk3     b
pk3     d
pk4     e

Is there an easy way to accomplish this?

A: With VBA this sub parsed the data in the format you provided. May require a little updating depending on columns structure.
Sub Parse()
    Dim thissheet As Worksheet
    Set thissheet = ActiveSheet

    Sheets.Add
    ActiveSheet.Range("A1").Value = "Header 1"
    ActiveSheet.Range("B1").Value = "Header 2"

    Dim pk As Long
    Dim carray() As String

    For x = 0 To thissheet.Range("A65535").End(xlUp).Row

    If InStr(1, thissheet.Range("B2").Offset(x, 0).Value, "|") > 0 Then
    'if cellvalue contains bar
    carray() = Split(thissheet.Range("B2").Offset(x, 0).Value, "|")
    For i = LBound(carray) To UBound(carray)
    ActiveSheet.Range("A2").Offset(pk, 0).Value = thissheet.Range("A2").Offset(x, 0).Value
    ActiveSheet.Range("B2").Offset(pk, 0).Value = Trim(carray(i))
    pk = pk + 1
    Next i
    Else
    'No Bar do this
    ActiveSheet.Range("A2").Offset(pk, 0).Value = thissheet.Range("A2").Offset(x, 0).Value
    ActiveSheet.Range("B2").Offset(pk, 0).Value = thissheet.Range("B2").Offset(x, 0).Value
    pk = pk + 1
    End If
    Next

    End Sub

redpajama_set_name: RedPajamaStackExchange


text:
Q: Checking Each Cart Heading Items For Specific Style Names I am in the process of developing an AB Test for an e-commerce cart page. We have a list of about 100 stylenames that we are not going to be accepting returns on.
We have messaging displayed on those particular styles' product display pages, but we would also like to have this message reinforced on the cart page if any product in the cart matches the list of stylenames that qualify.
I have started by creating an array variable of all qualified stylenames (shortened here for example). I then loop through each cart item heading tag & check the .text() of that element. IF the .text() matches one of the stylenames I am looking for, I would then want to go ahead and append the message below the cart item heading tag.
Here is the script I have written, however, I don't see the result expected when running this locally in my devtools snippet:

var styleList = ['Astawia Loafer','Another Style','So On','So Forth'];
var finalSaleMessage = 'Final sale! No returns on our best deals.'

function checkStyleName(value,arr){
    var result = false;

    for (var i = 0; i < arr.length; i++){
        var name = arr[i];
        if(name == value){
            result = true;
            break;
        }
    }
    return result;
}

$('.crt-heading--item').each(function(){
    if (checkStyleName($('.crt-heading--item').text(),styleList) == true) {
        // append the message
    }

})

Any input here from the community would be greatly appreciated. Please let me know if you would need further information.
Thanks!

A: The problem is that you go through all the elements of a certain class and don't refer to every single one of them.

var styleList = ['Astawia Loafer','Another Style','So On','So Forth'];
var finalSaleMessage = 'Final sale! No returns on our best deals.'

function checkStyleName(value,arr){
    var result = false;

    for (var i = 0; i < arr.length; i++){
        var name = arr[i];
        if(name == value){
            result = true;
            break;
        }
    }
    return result;
}
$('.crt-heading--item').each(function(){
    if (checkStyleName($(this).text(),styleList) == true) {
        // append the message
        //test
        alert($(this).text())
    }

})

Astawia Loafer

Astawia Loafer

3

So On

5

A: Can be simplified a little.
No need to send array everytime.
Usage of includes.
Looks like the text is in the format of BRAND PRODUCT_NAME CATEGORY. You may want to split or do something to get the PRODUCT_NAME.
Usage of this as pointed out by devmiguelopz

    var styleList = ['Astawia Loafer','Another Style','So On','So Forth'];
    var finalSaleMessage = 'Final sale! No returns on our best deals.'

    // OLD SUGGESTION
    /*
        $('.crt-heading--item').each(function(){
        if (styleList.includes($(this).text()) {
            // append the message
        }
*/
    // This will iterate on the elements
    $('.crt-heading--item').each(function(){
        // Iterate on the styleList
        var styleListLength = styleList.length;
        for(var i = 0, i < styleListLength; i++){
           // Check if the name has entry from styleList
           if($(this).text().includes(styleList[i])){
              // DO STUFF
           }
        }

})
// We re running a loop inside a loop in this case.
// There may be better ways of doing this with .some/.filter/.map

Check here for what .includes can do for you :   https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes


text:
Q: ClassNotFoundException for class BrowserView at runtime In Java project using Maven I add library for JxBrowser.
Program is compiling fine - with no errors, but when I try to run it in Intelij IDEA it returns error.
It shows when try to create BrowserView object(it is a class in lib package com.teamdev.jxbrowser.chromium.swing) and returned two errors NoClassDefFoundError and CLassNotFoundException and full message looks like :
java.lang.NoClassDefFoundError: com/teamdev/jxbrowser/chromium/swing/BrowserView
    at com.goodsoft.stockbox.jxbrowser.JxBrowser.<init>(JxBrowser.java:26)
    at com.goodsoft.stockbox.market.view.window.StockBoxWindowController.lambda$createMenuWindow$17(StockBoxWindowController.java:211)
    at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
    at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2348)
    at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
    at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
    at javax.swing.AbstractButton.doClick(AbstractButton.java:376)
    at javax.swing.plaf.basic.BasicMenuItemUI.doClick(BasicMenuItemUI.java:833)
    at javax.swing.plaf.basic.BasicMenuItemUI$Handler.menuDragMouseReleased(BasicMenuItemUI.java:943)
    at javax.swing.JMenuItem.fireMenuDragMouseReleased(JMenuItem.java:586)
    at javax.swing.JMenuItem.processMenuDragMouseEvent(JMenuItem.java:483)
    at javax.swing.JMenuItem.processMouseEvent(JMenuItem.java:429)
    at javax.swing.MenuSelectionManager.processMouseEvent(MenuSelectionManager.java:329)
    at javax.swing.plaf.basic.BasicMenuItemUI$Handler.mouseReleased(BasicMenuItemUI.java:879)
    at java.awt.Component.processMouseEvent(Component.java:6535)
    at javax.swing.JComponent.processMouseEvent(JComponent.java:3324)
    at java.awt.Component.processEvent(Component.java:6300)
    at java.awt.Container.processEvent(Container.java:2236)
    at java.awt.Component.dispatchEventImpl(Component.java:4891)
    at java.awt.Container.dispatchEventImpl(Container.java:2294)
    at java.awt.Component.dispatchEvent(Component.java:4713)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4888)
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4525)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4466)
    at java.awt.Container.dispatchEventImpl(Container.java:2280)
    at java.awt.Window.dispatchEventImpl(Window.java:2750)
    at java.awt.Component.dispatchEvent(Component.java:4713)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758)
    at java.awt.EventQueue.access$500(EventQueue.java:97)
    at java.awt.EventQueue$3.run(EventQueue.java:709)
    at java.awt.EventQueue$3.run(EventQueue.java:703)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:86)
    at java.awt.EventQueue$4.run(EventQueue.java:731)
    at java.awt.EventQueue$4.run(EventQueue.java:729)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:728)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
Caused by: java.lang.ClassNotFoundException: com.teamdev.jxbrowser.chromium.swing.BrowserView
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 45 more

How can I resolve it ?
When I type BrowserView browserView = new BrowserView() it is not highlighted, it means that lib was found in project resources.
pom.xml contains:
<dependencies>
    <dependency>
        <groupId>com.teamdev.jxbrowser</groupId>
        <artifactId>jxbrowser-mac</artifactId>
        <version>6.11.1</version>
    </dependency>
</dependencies>

<repositories>
    <repository>
        <id>com.teamdev.jxbrowser</id>
        <url>http://maven.teamdev.com/repository/products</url>
    </repository>
</repositories>

When compiling project, the library is downloaded successfully with no error.
EDIT
I work on OS X system and IntelliJ IDEA.
I add license.jar file in module settings - Dependencies tab, ask me about which type and I choose "classes" also it is setted to "Compile"
EDIT 2
I checked System.getProperty("java.class.path") and there is no .jar files to JxBrowser... But why ? When it is set up in module dependencies

A: SOLVED
In JxBrowser installation guide (JxBrowser Installation) there was no information about adding dependency as below
<dependency>
    <groupId>com.teamdev.jxbrowser</groupId>
    <artifactId>jxbrowser</artifactId>
    <version>${jxbrowser.version}</version>
</dependency>

only for different systems (as Windows, Mac, Linux), but not to main lib.


text:
Q: How to find the pdf of difference of r.v How do I calculate the pdf for the following case?  In general, if we have 2 r.v. $x,y$ which are normal, then the pdf of the difference of 2 r.v. which are Gaussian will also be Gaussian, I think with mean $\mu_Z = \mu_x - \mu_y$ and variance $\sigma^2_Z = \sigma^2_x + \sigma^2_y$.
Based on this premise, how to find the pdf from a Gaussian Mixture model (GMM). The time series $Z$ has the pdf $f_Z$ which is GMM distribution. The time series contains 2 r.v $x,y$.  So, both the r.v. together constitute a GMM. Considering that there are only 2 mixtures.
I have observations of multivariate time series $Z_i = {[x_i,y_i]}_{i=1}^n$ where $x,y$ are the random variables. The pdf of $Z$ is Gaussian mixture model (GMM). The parameters of the GMM model are learnt through Expectation Maximization.   How to get the functional form for the pdf $f(d_i) = f(x_i-y_i)$ where $d_ i = x_i-y_i$. Thank you for help.

A:
How do I calculate the pdf for the following case? The pdf of the difference of 2 r.v. which are Gaussian will also be Gaussian, I think with mean $\mu_D =\mu_X −\mu_Y$   and variance $\sigma^2_D =\sigma^2_X +\sigma^2_Y\;$.

Yes.   Now you have a Gaussian random variable with given mean and variance.
$$D\sim \mathcal{N}(\mu_X −\mu_Y, \sigma_X^2+\sigma_Y^2)$$
So the pmf of that Normal Distribution is: $$\color{blue}{\boxed{\color{black}{f_D(d)=\dfrac {\mathsf {\large e}^{\displaystyle-(d-\mu_D+\mu_D)/(2\sigma_X^2+2\sigma_Y^2)}}{\sqrt{2\pi(\sigma_X^2+\sigma_Y^2)}}}}}$$

By substitution into:  $Z\sim\mathcal{N}(\mu_D, \sigma_D) \iff f_D(d)=\dfrac{\mathsf e^{-(d-\mu_D)/2\sigma_D^2}}{\sigma_D\sqrt{2\pi}}$


text:
Q: Qt, Unable to get QLabel dimmensions to correctly scale a QPixmap to its fully fit QLabel So I'm trying to scale an Image to fully fit a label from top to bottom.  The problem is the outputs from the labels width, and height is not pixel values so I'm not sure how to correctly go about this.  Here's my code.
void MainWindow::drawPixmap()
{
    int labelWidth = ui->picLabel->width();
    int labelHeight = ui->picLabel->height();

    if(labelWidth <= labelHeight){
        pixMap = this->pixMap.scaledToWidth(labelWidth);
        ui->picLabel->setPixmap(pixMap);
    }
    else{
        pixMap = this->pixMap.scaledToHeight(labelHeight);
        ui->picLabel->setPixmap(pixMap);
    }
}

Here's a visual of my problem, the black box is a border around the label box.  I'm trying to get the image in the center to have its top and bottom touch the black box on respective sides.

Thanks for any help!

A: The problem could be when you calling this function. If you have called this function prior to making the label visible, then the size of the label could be incorrect after the label becomes visible.
Also, think about what happens when the label resize (if ever). You will still have to update the size of pixmap.
If your label is never going to change size, try calling it after the label has become visible.
Alternatively, try setting QLabel::setScaledContents(true)
If both the above doesn't work, try installing an eventFilter on the label to get the label's size change event, in there, you could do your above code
MainWindow::MainWindow()
{
     ....
     ui->picLabel->installEventFilter(this);
}

bool MainWindow::eventFilter(QObject* object, QEvent* event)
{
    bool res = Base::eventFilter(object, event);
    if (object == ui->picLabel && event->type() == QEvent::Resize)
    {
        int labelWidth = ui->picLabel->width();
        int labelHeight = ui->picLabel->height();

        if(labelWidth <= labelHeight){
            pixMap = this->pixMap.scaledToWidth(labelWidth);
            ui->picLabel->setPixmap(pixMap);
        }
        else{
            pixMap = this->pixMap.scaledToHeight(labelHeight);
            ui->picLabel->setPixmap(pixMap);
        }
    }
    return res;
}


text:
Q: On Diffie-Hellman key exchange The book I am reading, explains the algorithm as follows:

*

*2 people think of 2 public "n and g" numbers both are aware of.

*2 people think of 2 private "x and "y" numbers they keep secret.

Exchange happens as illustrated

I put together the following python code to see how this works and .... it does not. Please help me understand what am i missing:
 #!/usr/bin/python

 n=22 # publicly known
 g=42 # publicly known

 x=13 # only Alice knows this
 y=53 # only Bob knows this

 aliceSends = (g**x)%n
 bobComputes = aliceSends**y
 bobSends = (g**y)%n
 aliceComputes = bobSends**x

 print "Alice sends    ", aliceSends
 print "Bob computes   ", bobComputes
 print "Bob sends      ", bobSends
 print "Alice computes ", aliceComputes

 print "In theory both should have ", (g**(x*y))%n

 ---

 Alice sends     14
 Bob computes    5556302616191343498765890791686005349041729624255239232159744
 Bob sends       14
 Alice computes  793714773254144

 In theory both should have  16

A: You forgot two more modulos:
>>> 5556302616191343498765890791686005349041729624255239232159744 % 22
16L
>>> 793714773254144 % 22
16

A: Roman is right. However, you'd better have a look at pow() three arguments function. Much faster and third argument is modulus

A: For two people
#!/usr/bin/python
p=141301# publicly known
g=5728435 # publicly known
x=76435 # only Alice knows this
y=37846 # only Bob knows this
aliceSends = (g**x)%p
aliceComputes = (bobSends**x)%p
bobSends = (g**y)%p
bobComputes = (aliceSends**y) %p
bobSends = (g**y)%p
bobComputes = (aliceSends**y) %p
print ("Alice sends    ", aliceSends )
print ("Bob computes   ", bobComputes )
print ("Bob sends      ", bobSends)
print ("Alice computes ", aliceComputes)

For three or more people
#!/usr/bin/python
p=141301# publicly known
g=5728435 # publicly known
x=76435 # only Alice knows this
y=37846 # only Bob knows this
z=23# only carol knows this
aliceSends = (g**x)%p
bobSends = (aliceSends**y)%p
carolComputes=(bobSends**z)%p
bobSends2=(g**y)%p
carolSends=(bobSends2**z)%p
aliceComputes=(carolSends**x)%p
carolSends2=(g**z)%p
aliceSends2=(carolSends2**x)%p
bobComputes=(aliceSends2**y)%p
print ("Alice computes ga and sends it to Bob.",aliceSends)
print ("Bob computes (ga)b = gab and sends it to Carol.",bobSends)
print ("Carol computes (gab)c = gabc and uses it as her secret.",carolComputes)
print ("Bob computes gb and sends it to Carol.",bobSends2)
print ("Carol computes (gb)c = gbc and sends it to Alice.",carolSends)
print ("Alice computes (gbc)a = gbca = gabc and uses it as her  secret.",aliceComputes)
print ("Carol computes gc and sends it to Alice.",carolSends2)
print ("Alice computes (gc)a = gca and sends it to Bob.",aliceSends2)
print ("Bob computes (gca)b = gcab = gabc and uses it as his
secret.",bobComputes)


text:
Q: Retain select dropdown value after an ajax refresh This could be a repetitive question but please bare me. I have a dropdown as below,
I select the option yellow, I have onclick which would do an operation and this does an ajax call. So after the ajax call the dropdown is defaulted back to red option instead of staying on yellow. I am still learning jquery
<select onChange="this.options[this.selectedIndex].onclick();>
<option value="red" onclick="">red</option>
<option value="yellow" onclick="">yellow</option>
<option value="blue" onclick="">blue</option>
<option value="green" onclick="">green</option>
</select>

Thanks in advance

A: A rough example as to how you achieve this:
// before ajax
var selected_item = $('select').val(); // use a better selector

// do some ajax
$.ajax({
    url: '/',
    data: {
        foo: 'bar'
    }
    success: function(data) {

        // update the select
        $('select').html(data);

        // reapply the originally selected element
        $('select').val(selected_item);

    }
});

A: try this:
$('input[value=red]').ajaxSuccess(function(){
   $(this).prop('selected', true)
})


text:
Q: Comparison between two longs doesn't work as expected this will be a simple question (or at least i think). I have to compare a Long object to a long primitive.
My code simplified:
long primitiveLong = 285825645621;
Long objectLong = new Long(285825645621);

if(primitiveLong == objectLong.longValue()){
    System.out.print("They are equals");
}

I expected that it would have worked, but it didn't, can someone explain me why?
Thanks in advance.
EDIT
Ok, i did a mistake using explicit numbers, i'll put here my code:
long identifier = mMarkers.get(marker);
long currentId = item.getId().longValue();

if (currentId==identifier)
    System.out.print("They are equals");

In debug

EDIT 2
It was an IDE (Android Studio) bug in debug mode, i tried on another IDE and it worked well with same code. So thanks to everyone for the answers, but the problem was another, that i couldn't expect.

A: First this must should give you compile error because compiler think of 285825645621 as an Integer but it is larger than int, so you need to change your code like this:
long primitiveLong = 285825645621l; //add and l at the end of your number so compiler know that it is a long not an int
Long objectLong = new Long(285825645621l); //do the same thing here

if(primitiveLong == objectLong.longValue()){
    System.out.print("They are equals");
}

and this will print : They are equals

A: You can use your literal value still this limit 285825645
If you are using beyond the limit you will get compile error

long primitiveLong = c;
            Long objectLong = new Long(285825645);

            if(primitiveLong == objectLong.longValue()){
                System.out.print("They are equals");
            }


text:
Q: Proofs using linear congruences We have just covered solving linear congruences, and I am confused about how to use them in proofs. I understand that the linear congruence $$cx \equiv b \pmod m$$ has a unique solution $\bmod m$ if $\gcd(c,m) = 1$, but a general approach to problems escapes me.
Sample Questions

Prove that if $x^2 \equiv n \pmod {65}$ has a solution, then so does $x^2 \equiv -n \pmod {65}$.
Show that if $n \equiv 7 \pmod 8$, then $n$ is not the sum of three squares.

My Work
For the first one, $x^2 \equiv n \pmod {65}$ implies that $65 | (x^2 - n)$, so (I believe) that means that $n = b^2$ for some $b$, so $65 | (x^2 - b^2)$. We proved a result that said that if $a^2 \equiv b^2 \pmod p$ for some prime $p$, then $a \equiv b$ or $a \equiv - b \pmod p$. However, I don't think that is the right track to go down here because $65$ is not prime, and I'm unsure about assuming $n = b^2$ for some $b$.
For the second one, suppose to the contrary that $n = a^2 + b^2 + c^2$ for some $a, b, c$. Then $n \equiv 7 \pmod 8$ implies that $8 | (n - 7)$ so $n = 8k + 7$ for some $k$. So substituting in gives me $a^2 + b^2 + c^2 = 8k + 7$, and I'm unsure how to proceed from here.

A: Hint  $\rm(1)\ \ \ x^2 \equiv n,\,\ y^2\equiv -1\:\Rightarrow\: -n\equiv x^2y^2\equiv (xy)^2.\ $ But $\rm\:mod\ 65\!:\ {-}1 \equiv 64\equiv (\_ )^2.$
$\rm(2)\ \ mod\ 4\!:\ x^2\!+\!y^2\!+\!z^2 \equiv\, 3\:\Rightarrow\:x,y,z\:$ odd, by $\rm\:odd^2\equiv 1,\ even^2\equiv 0.\:$ Therefore we deduce  $\rm\phantom{(2)\ \ } mod\ 8\!:\ x^2\!+\!y^2\!+\!z^2\equiv\:7\:\Rightarrow\:x,y,z\:$ odd $\rm\:\Rightarrow\:x^2\!+\!y^2\!+\!z^2\equiv 3,\:$ by $\rm\:odd^2\!\equiv\{\pm1,\pm3\}^2\equiv 1.$

A: For the first question, note that $65=5 \cdot 13$ and $x^2 \equiv -1$ has solutions mod 5 and mod 13. Note also that solutions of $x^2 \equiv n \bmod 65$ also give solutions mod 5 and mod 13. Combine those.
For the second question, note that squares are congruent to 0, 1, or 4, mod 8. But you cannot sum three numbers from this list to get 7 mod 8.


text:
Q: Will the new Twitter framework work for iOS 4.3 Will the new Twitter API (framework) included in iOS 5 work for iOS 4.3 and above ?

A: It does not work for iOS4.3 as it has been included with iOS5 and later only.

A: Unfortunately you will have to use mgtwitterengine with oath. This will be compatible with most iOS versions. Apples api is only for iOS5.
http://mobile.tutsplus.com/tutorials/iphone/twitter-api-iphone/


text:
Q: Codeigniter query with alias and number as column I would like to replace column name with numbers in codeigniter
It does work well with letters but not with numbers
$this->db->select ('Observation.id_observation as 1');
            $this->db->from ( 'Observation' );
            $this->db->join ( 'Enregistrement', 'Enregistrement.id_observation =
             Observation.id_observation' , 'left' );
            $this->db->where('Observation.id_parcelle', $id_parcelle);
            $this->db->where('Observation.id_observateur', $user_id);
            $this->db->where('Observation.date_observation >=', $date_start);
            $this->db->where('Observation.date_observation <=', $date_end);
            return $this->db->get()->result();

A: You can try this:
$this->db->select ("Observation.id_observation as '1'");
Hope It will work.

A: You can set alias name as string so you need to give within single quotes otherwise you will get syntax error
                $this->db->select ('Observation.id_observation as `1`',FALSE);
                $this->db->from ( 'Observation' );
                $this->db->join ( 'Enregistrement', 'Enregistrement.id_observation =
                 Observation.id_observation' , 'left' );
                $this->db->where('Observation.id_parcelle', $id_parcelle);
                $this->db->where('Observation.id_observateur', $user_id);
                $this->db->where('Observation.date_observation >=', $date_start);
                $this->db->where('Observation.date_observation <=', $date_end);
                return $this->db->get()->result();

OR
$var = '1';
$this->db->select ('Observation.id_observation as `'.$var.'`',FALSE);

OR
 $query=$this->db->query('SELECT Observation.id_observation as "1" FROM Observation LEFT JOIN Enregistrement ON Enregistrement.id_observation =
   Observation.id_observation WHERE Observation.id_parcelle = '.$id_parcelle.' AND Observation.id_observateur = '.$user_id.' AND Observation.date_observation >= "'.$date_start.'" AND Observation.date_observation <= "'.$date_end.'" ');
    return $query->result();

A: Try the following
$this->db->select ('Observation.id_observation as `1`');

This will generate query as
Select `observation` as `1`....

From the Docs

Identifiers may begin with a digit but unless quoted may not consist solely of digits.

A: This is what i had to do in the controller ! I very don't like this solultion but it does work:
$conn = new mysqli($servername, $username, $password, $dbname);
                // Check connection
                if ($conn->connect_error) {
                    die("Connection failed: " . $conn->connect_error);
                }
                $sql = "SELECT
                Observation.id_observation as '0',
                Observation.checkseries as '1'
                FROM Observation
                LEFT JOIN Enregistrement ON Enregistrement.id_observation = Observation.id_observation
                WHERE
                Observation.id_parcelle = '$parcellecultures->id_parcelle'
                AND Observation.id_observateur = '$user'
                AND Observation.date_observation >= '$date_start'
                AND Observation.date_observation <= '$date_end'
                ";
                //echo $sql;
                $result = $conn->query($sql);

                //print_r($result);exit;
                $conn->close();

I still look for another solution ....


text:
Q: Outputting XML with JQuery/AJAX script I have an RSS file, and I'm trying to use JQuery to read though the file and print the contents to an HTML page.
The RSS file looks like this:
<contents>
   <item>
     <title>Title</title>
     <author>Author</author>
     <description>Description</description>
   </item>
   <item>
     <title>Title</title>
     <author>Author</author>
     <description>Description</description>
   </item>
</contents>

My JQuery code so far looks like this and I SOLVED IT MYSELF, so cancel the question, and here's the solution:
$(document).ready(function(){

   $.ajax({
      url: 'file.rss',
      dataType: "xml",
      success: parseXML,
      error: function(){alert("Error: Something is wrong");}
    });

  function parseXML(document){

  $(document).find('content').each(function(){
     $(this).find('item').each(function(){
     var author =  item.find('author').text();
     var description = item.find('description').text();

     var output = description + title + author;
      $(#div).html(output);

But the output isn't what I want!  I want the code to loop through every entry in the RSS feed and each entry out separately, like this:
Title, Author
Description

Title, Author
Description

Instead, what's happening is that I'm getting all the titles and authors together, like this:
Title, Title
Author, Author
Description, Description

I am not sure what I'm doing wrong.


text:
Q: $validator->fails() not working properly for every record Laravel 5.2 The auth script was working fine few days ago but now its not working properly. $validator is working fine for old email records in database but not for new email.
Here is the code for login in AuthController.php:
   public function login(\Illuminate\Http\Request $request)
{
    $rules = [
        /*'email'    => 'required|email|unique:users,email',*/
        'email'    => 'required|email|exists:users,email',
        'password' => 'required',
    ];

    $input = Input::only('email', 'password');

    $validator = Validator::make($input, $rules);
    //return $input['email'];
    if ($validator->fails()) {
        /*$failedRules = $validator->failed();
        return $failedRules;*/

        /*if(isset($failedRules['email']['exists'])) {
            return 'dont exists';
        }*/
       return Redirect::to('/login')->withInput()->withErrors($validator);

    }

    $rules = [
        'hcptch' => 'required|hiddencaptcha',
    ];

    if($this->validate($request,$rules)){
        return Redirect::to('/login')->withInput()->withErrors($validator);
    }

    $credentials = [
        'email'     => Input::get('email'),
        'password'  => Input::get('password'),
        'confirmed' => 1,
    ];

    if (!Auth::attempt($credentials)) {

        //old_password login
        $user = User::where('email', Input::get('email'))->get();
        /*$user2 = \DB::table('users')->select('name')->where('email', Input::get('email'))->get();
        return $user[0]->password;*/
        if(md5(strtolower(Input::get('password'))) == $user[0]->old_password){
            $user[0]->password = Hash::make(Input::get('password'));
            $user[0]->old_password = null;
            $user[0]->save();

            if (!Auth::attempt($credentials)) {
                Session::flash('message', 'Welcome back!');
                return Redirect::home();
            }
        }

        return Redirect::back()
            ->withInput()
            ->withErrors(
                [
                    'password' => 'We were unable to sign you in. Incorrect Password',
                ]
            );
    }
    Session::flash('message','Welcome back!');

    return Redirect::home();
}

Login.blade.php
  <form id="form-login" class="form-horizontal" role="form" method="POST" action="{{ url('/login') }}">

LOGIN

          {!! csrf_field() !!}

has('email') && !strpos(Request::fullUrl(), 'register') ? ' has-error' : '' }}">
             Email

         {!! Form::text('email',old('email'),['class'=>'form-control']) !!}
                @if ($errors->has('email') && !strpos(Request::fullUrl(), 'register'))

                  {{ $errors->first('email') }}

         @endif

has('password') && !strpos(Request::fullUrl(), 'register') ? ' has-error' : '' }}">
     Password

        {!! Form::password('password',['class'=>'form-control']) !!}
         @if ($errors->has('password') && !strpos(Request::fullUrl(), 'register'))

                {{ $errors->first('password') }}

       @endif
       @if ($errors->has('hcptch') && !strpos(Request::fullUrl(), 'register'))

             {{ $errors->first('hcptch') }}

        @endif

          <button type="submit" class="btn btn-red font-av-heavy pull-left g-recaptcha" data-sitekey="6Le8jRoUAAAAABrE1Dpxo6ZZev4zeYKlk43eDf62" data-callback="loginOnSubmit">Login</button>

               Forgot Password?

       {{ HiddenCaptcha::render() }}
  </form>

The code is still working fine for old email records but throwing an error for new email addresses "The selected email is invalid." I have been trying for several hours to figure out what is the problem but not getting any clue. Please help me where I am doing it wrong or missing something. Thank you


text:
Q: Is there any Office Web Apps Server Api available? I want to allow user to be able to edit office documents online within the web application.
I have come to know that I can do it easily by installing Web App Server
But it requires a separate isolated server for installing it. Or I need to install it on virtual machine.
I was wondering if is there any api available (which already have Web App Server installed on it), which I can use directly with my web application to fulfill my requirement?.

A: The web-based Office document editing is achieved by implementing MS-WOPI protocol. The protocol consists of three parties - a WOPI Server (app serving the files...typically your app or SharePoint), a WOPI Client (Office Web Apps) and a client browser.

Unless you want to implement your own WOPI client (which should be possible but I haven't seen anyone trying to go that path) you have to use Office Web Apps or its younger brother Office Online Server.


text:
Q: Present custom View Controller in Storyboard? I am trying the following:
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard_iPhone" bundle:nil];
    CustomVC *vc = [[CustomVC alloc] init];
    vc = [storyboard instantiateViewControllerWithIdentifier:@"weddingDateViewController"];
    [vc setModalTransitionStyle:UIModalTransitionStyleCrossDissolve];
    [self vc animated:YES];

I have build a view controller in my storyboard and have linked a custom class to it (CustomVC). When I run this code to present the view controller the screen fades to black and I see nothing. However, in my storyboard, if I remove the link to my custom class and run this code it fades in normally and I see the view controller I made in my storyboard.
The trouble is I need that custom class to be used. It's a fresh custom class with no changes made to it.

A: Go to CustomVC.h and remove the loadView method


text:
Q: Exception thrown at 0x0131EB06 Visual Studio Im quite new at Directx, and I wanted to test a simple direct2d application that draws a circle in a window. I am using Visual Studio Professional. When ever I run my program called D2D Test Engine with Local Windows Debugger, i get these errors:
Exception thrown at 0x0140EB06 in D2D Test Engine.exe: 0xC0000005: Access violation reading location 0x00000008.
Exception thrown at 0x0140EB06 in D2D Test Engine.exe: 0xC0000005: Access violation reading location 0x00000008.
Exception thrown at 0x0140EB06 in D2D Test Engine.exe: 0xC0000005: Access violation reading location 0x00000008.

I can't figure out what is wrong with my program.
Here is my code:
#include <Windows.h>
#include "Graphics.h"
Graphics* graphics;
LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
if (uMsg == WM_DESTROY) {
    PostQuitMessage(0);
    return 0;
}
graphics->BeginDraw();
graphics->ClearScreen(0.0f, 0.0f, 0.5f);
graphics->DrawShape(100, 100, 50, 1.0f, 0.0, 0.0, 1.0);
graphics->EndDraw();
return DefWindowProc(hwnd, uMsg, wParam, lParam);
}
int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE prevInstance, LPWSTR cmd, int nCmdShow) {
WNDCLASSEX windowclass;
ZeroMemory(&windowclass, sizeof(WNDCLASSEX));
windowclass.cbSize = sizeof(WNDCLASSEX);
windowclass.hbrBackground = (HBRUSH) COLOR_WINDOW;
windowclass.hInstance = hInstance;
windowclass.lpfnWndProc = WindowProc;
windowclass.lpszClassName = "MainWindow";
windowclass.style = CS_HREDRAW | CS_VREDRAW;
RegisterClassEx(&windowclass);
RECT rect = { 0, 0, 800, 600 };
AdjustWindowRectEx(&rect, WS_EX_OVERLAPPEDWINDOW, false, WS_EX_OVERLAPPEDWINDOW);
HWND windowHandle = CreateWindowEx(WS_EX_OVERLAPPEDWINDOW, "MainWindow", "D2D Test Engine", WS_OVERLAPPEDWINDOW, 0, 0, rect.right - rect.left,      rect.bottom - rect.top, NULL, NULL, hInstance, 0);
    if (!windowHandle) {
        return -1;
    }
    graphics = new Graphics();
    if (graphics->Init(windowHandle) == false) {
        delete graphics;
        return -1;
    }
    ShowWindow(windowHandle, nCmdShow);
    MSG message;
    while (GetMessage(&message, NULL, 0, 0)) {
        DispatchMessage(&message);
    }
    return 0;
}

next file:
#pragma once
#include <Windows.h>
#include <d2d1.h>
class Graphics
{
ID2D1Factory* factory;
ID2D1HwndRenderTarget* renderTarget;
public:
Graphics();
virtual ~Graphics();
bool Init(HWND windowHandle);
void BeginDraw() {renderTarget->BeginDraw();}
void EndDraw() {renderTarget->EndDraw();}
void ClearScreen(float r, float g, float b);
void DrawShape(float x, float y, float radius, float r, float g, float b, float a);
};

next file:
#include "Graphics.h"
#include <d2d1.h>
#include <Windows.h>
Graphics::Graphics()
{
factory = NULL;
renderTarget = NULL;
}
Graphics::~Graphics()
{
if (factory) {
    factory->Release();
}
if (renderTarget) {
    renderTarget->Release();
}
}
bool Graphics::Init(HWND windowHandle) {
HRESULT res = D2D1CreateFactory(D2D1_FACTORY_TYPE_MULTI_THREADED, &factory);
if (res != S_OK) {
    return false;
}
RECT rect;
GetClientRect(windowHandle, &rect);
res = factory->CreateHwndRenderTarget(D2D1::RenderTargetProperties(), D2D1::HwndRenderTargetProperties(windowHandle, D2D1::SizeU(rect.right, rect.bottom)), &renderTarget);
if (res != S_OK) {
    return false;
}
return true;
}
void Graphics::ClearScreen(float r, float g, float b) {
renderTarget->Clear(D2D1::ColorF(r, g, b));
}
void Graphics::DrawShape(float x, float y, float radius, float r, float g, float b, float a) {
ID2D1SolidColorBrush* brush;

renderTarget->CreateSolidColorBrush(D2D1::ColorF(r, g, b, a), &brush);
renderTarget->DrawEllipse(D2D1::Ellipse(D2D1::Point2F(x, y), radius, radius), brush, 3.0f);
brush->Release();
}

When i dont call BeginDraw(), ClearScreen, DrawShape, and EndDraw a window comes up and it runs fine, so i think it has to do with them.

A: Seems, that you have problem with WM_CREATE message.
This message is send when CreateWindowEx called.
Graphics* graphics = NULL; // it's better to zero pointer in C++.

Simple solution - set graphics to null and check it in WindowProc function.
LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
    if (uMsg == WM_DESTROY) {
      PostQuitMessage(0);
      return 0;
   }

   if (graphics) {
     graphics->BeginDraw();
     graphics->ClearScreen(0.0f, 0.0f, 0.5f);
     graphics->DrawShape(100, 100, 50, 1.0f, 0.0, 0.0, 1.0);
     graphics->EndDraw();
   }
   return DefWindowProc(hwnd, msg, wParam, lParam);
}

A: I figured out the answer. I am pretty new at this directx stuff, and i was using a tutorial to build this. what I needed to do was put all the functions i was calling in a if statement. here is what i did:
if (uMsg == WM_PAINT) {
    graphics->BeginDraw();
    graphics->ClearScreen(0.0f, 0.0f, 0.5f);
    graphics->DrawShape(100, 100, 50, 1.0f, 0.0, 0.0, 1.0);
    graphics->EndDraw();
}

sorry for all the trouble, im new to this.


text:
Q: Cannot Install package MICE in R I have an issue to install MICE package. I got an error message:

I downloaded Rtools, but the problem still remains. Do you know how to deal with it? Thank you

A: After reviewing the documentation, I realize that I have to install Rtools to download the packages. I found https://www.youtube.com/watch?v=h2IPWVXaUuU is very useful to explain how to download Rtools and make it recognizable in R.


text:
Q: Laravel/Ajax: selecting a row with a different id but same group_id shows a different value To explain my title, this is my table, it has multiple rows with the same group_id but different id

Here are those same rows in my output: (I added their id beside the names to show the value)

My problem is that when I click on for instance, the edit button on the first row id=41 group_id=1, my text fields show the values for id=1 group_id=1
Another screenshot below, the modal (edit button on id=41). I added text fields for id and group_id to show which row is retrieved from the table. As you can see, it outputs the row of id=1 Codes are further down.

Routes:
use App\Http\Controllers\Frontend\BBRCategoryConfigurationController;

Route::get('/bbr-group-configuration-edit/{id}', [BBRGroupConfigurationController::class,'edit']);

Controller: (my table is retrieved from HmsBbrGroup)
public function edit($id) {
    $group_edit = HmsBbrGroup::find($id);
    if ($group_edit)
    {
        return response()->json([
            'status'=>200,
            'group_edit'=>$group_edit,
        ]);
    }
    else
    {
        return response()->json([
            'status'=>404,
            'message'=>'Group Not Found',
        ]);
    }
}

Ajax:
        $(document).on('click','.edit_group',function (e) {
            e.preventDefault();
            $(".save_button").removeClass("add_group").addClass("update_group");
            var g_id = $(this).val();
            console.log(g_id);
            $('#group_form').modal('show');
            $.ajax({
                type: "GET",
                url: "/clinical/bbr-group-configuration-edit/"+g_id,
                success: function (response) {
                     console.log(response);
                    if(response.status == 404) {
                        $('#success_message').html("");
                        $('#success_message').addClass('alert alert-danger');
                        $('#success_message').text('response.message');
                    } else {
                        $('#id').val(response.group_edit.id);
                        $('#group_id').val(response.group_edit.group_id);
                        $('#group_name').val(response.group_edit.group_name);
                        $('#group_description').val(response.group_edit.group_description);

                        $('#effective_start_datetime').val(response.group_edit.effective_start_datetime ? 'active' : 'inactive').change();
                        $('#group_type_id').val(response.group_edit.group_type_id).change();
                    }
                }
            });
        });

Forms:
   <input type="text" id="id" class="id">
   <input type="text" id="group_id" class="group_id">
   <input type="text" id="group_name" class="group_name" placeholder="Group Name">
   <textarea id="group_description" class="group_description" placeholder="Group Description">
   <select id="effective_start_datetime" class="effective_start_datetime">
   <select id="effective_start_datetime" class="effective_start_datetime">

Things to note:

*

*I am trying to retrieve the right row so I made my route get the id:
/bbr-group-configuration-edit/{id}

*What my ajax does is to show the values of the row in the modal (3rd screenshot), specifically in the else statement

*It could have something to do with my controller $group_edit = HmsBbrGroup::find($id); but I cannot figure out why it takes the first (or lowest) value id within the same group_id
I explained in detail everything that has been done so far, hope I can get some help with my issue. Thanks for reading.
TLDR: wrong row is shown when retrieving from the table (edit form)


text:
Q: Python Nested For and While Unexpected Behaviour While writing some code I notice something strange, if you take this code:
data = ['a','b','c','d','e']
print("start", len(data))
while(len(data) > 0):
  print("while", len(data))
  for i in data:
    print("for", i)
    del data[data.index(i)]
print("end", len(data))

If I execute it, it returns:
('start', 5)
('while', 5)
('for', 'a')
('for', 'c')
('for', 'e')
('while', 2)
('for', 'b')
('while', 1)
('for', 'd')
('end', 0)

This is not what I expected to happen, this is what i thought would happen:
('start', 5)
('while', 5)
('for', 'a')
('for', 'b')
('for', 'c')
('for', 'd')
('for', 'e')
('end', 0)

It's both running the list out of order (which is annoying but that wholly unexpected) and running more than one while loop. As I said in the brackets then list returning out of order is not really the problem its the multiple while loops cycles that confused me. Can someone explain why this is happening? A solution would be pleasant too.
Here is a link to the demo code on trinket.io: https://trinket.io/python/46f433793d


text:
Q: How to convert PDF to text file in iTextSharp I have to retrieve text from PDF file. But using the following code I only get empty text file.
for (int i = 0; i < n; i++)
{
    pagenumber = i + 1;
    filename = pagenumber.ToString();
    while (filename.Length < digits) filename = "0" + filename;
    filename = "_" + filename;
    filename = splitFile + name + filename;
    // step 1: creation of a document-object
    document = new Document(reader.GetPageSizeWithRotation(pagenumber));
    // step 2: we create a writer that listens to the document
    PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(filename + ".pdf", FileMode.Create));

    // step 3: we open the document
    document.Open();

    PdfContentByte cb = writer.DirectContent;
    PdfImportedPage page = writer.GetImportedPage(reader, pagenumber);
    int rotation = reader.GetPageRotation(pagenumber);
    if (rotation == 90 || rotation == 270)
    {
        cb.AddTemplate(page, 0, -1f, 1f, 0, 0, reader.GetPageSizeWithRotation(pagenumber).Height);
    }
    else
    {
        cb.AddTemplate(page, 1f, 0, 0, 1f, 0, 0);
    }
    // step 5: we close the document

    document.Close();
    PDFParser parser = new PDFParser();
    parser.ExtractText(filename + ".pdf", filename + ".txt");
}

What am I doing wrong and how should I extract text from PDF?

A: using System;
using System.IO;
using System.Linq;
using System.Text;
using iTextSharp.text.pdf;
using iTextSharp.text.pdf.parser;

namespace Pdf2Text
{
    class Program
    {
        static void Main(string[] args)
        {
            if (!args.Any()) return;

            var file = args[0];
            var output = Path.ChangeExtension(file, ".txt");
            if (!File.Exists(file)) return;

            var bytes = File.ReadAllBytes(file);
            File.WriteAllText(output, ConvertToText(bytes), Encoding.UTF8);
        }

        private static string ConvertToText(byte[] bytes)
        {
            var sb = new StringBuilder();

            try
            {
                var reader = new PdfReader(bytes);
                var numberOfPages = reader.NumberOfPages;

                for (var currentPageIndex = 1; currentPageIndex <= numberOfPages; currentPageIndex++)
                {
                    sb.Append(PdfTextExtractor.GetTextFromPage(reader, currentPageIndex));
                }
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception.Message);
            }

            return sb.ToString();
        }
    }
}

A: For text extraction with iTextSharp, take a current version of that library and use
PdfTextExtractor.GetTextFromPage(reader, pageNumber);

Beware, there was a bug in the text extraction code in some 5.3.x version which has meanwhile been fixed. Make sure, therefore, that you're using a current 5.5.x version.

A: //call Create_pdf() function when Done button pressed;

EditText et_Text=findViewById(R.id.EditText);

String projectname="MyPdf";

public  void Create_pdf(){
    Document doc =new Document();
    String outPath= Environment.getExternalStorageDirectory()+"/"+projectname+".pdf";
    try {
       PdfWriter.getInstance(doc, new FileOutputStream(outPath));
       doc.open();
       doc.add(new Paragraph(et_Text.getText().toString()));
       doc.close();
    } catch (DocumentException e) {
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
}


text:
Q: How to add a dropdown menu with Logout option using ant d in React typescript Here is the sample code, i have a avatar and onclick of it i want to show a small dropdown with logout option and possibly username.
import { Avatar, Layout } from 'antd';

 <StyledAvatar size="small"> {initials} </StyledAvatar>

 const StyledAvatar = styled(Avatar)`
  margin-left: ${({ theme }: { theme: Theme }) => theme.paddings.small}px;
  color: black;
  background-color: white;
  font-weight: bold;
`;

A: <Dropdown
  overlay={menu}
  trigger={["click"]}
  placement="bottomLeft"
>
  <div onClick={e => e.preventDefault()}>
    <Avatar size="large" icon={<UserOutlined />} />
  </div>
</Dropdown>

We put the avatar component inside the Dropdown component.


text:
Q: How do I link libxml2 with zlib1 on Windows? I need to compile libxml2 32-bit and 64-bit binaries for my TeamSpeak 3 plugin because I could not find a dll/lib 64-bit download. When I use my compiled libxml2.dll as a dependency in a command prompt application, it works just fine. However, when I try to use it as a dependency in TeamSpeak 3, the program immediately crashes on launch. Specifically it crashes on this line:
https://github.com/NobleUplift/TeamSpeak3WebsitePreview/blob/master/ts3websitepreview/plugin.c#L148
This is my batch script for compiling libxml2 on Windows:
@ECHO OFF
CALL "C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\bin\vcvars32.bat"
CD libxml2-2.9.4\win32
nmake clean
cscript configure.js compiler=msvc zlib=true prefix=D:\Repos\libxml2\release include=D:\Repos\libxml2\dll\include lib=D:\Repos\libxml2\dll\bin debug=yes
nmake
nmake install
cd ../..

The downloaded libxml2.dll on the left works. Compiled libxml2.dll is on the right. I've tried using the zlib flag, and I put my zlib headers in the include directory and the dll/lib in the lib directory, but I can't get it to link in the DLL.

A: Well, I dunno whats wrong with yours, but here's how we compile the release version:
set TARGET_DIR=.\release_vc100
cscript configure.js compiler=msvc cruntime=/MD debug=no iconv=no legacy=no vcmanifest=no prefix=%TARGET_DIR% || exit /B 1
nmake /f Makefile.msvc clean || exit /B 1
nmake /f Makefile.msvc MSVC_VERSION=vc100 || exit /B 1
nmake /f Makefile.msvc install || exit /B 1

I guess you don't want iconv=no, but I'll note I explicitly specify /MD for the dynamic link release msvcrt and debug=no as well as passing MSVC_VERSION=vc100 to the make step.
I also note you pass zlib=truewhen the options seem to take yes|no - and I do think 'true' will not interpeted as 1, but as 0. (!= yes)
Looking at your depwalker output again, I somehow suspect your missing MSVC_VERSION switch may actuall be a problem, because depwalker lists a missing LIBiconv.dll and that naming scheme (LIB prefix for dynamic object) is a *nix thing as far as I understand this.)
As for your erro line -- dll load failed -- both depwalker screenshots show missing dependency DLL files:

*

*Left side: iconv.dll and zlib1.dll are muissing

*Right side: LIBiconv.dll is missing. (But I think there is no libiconv.dll on Windows, so there must be some wrong linker settings (??).

I also pass the makefile explicitly, but that may just
be a leftover from a prior version where we tried some customized makefiles.
Side note: Debug version as:
cscript configure.js compiler=msvc cruntime=/MDd debug=yes iconv=no legacy=no vcmanifest=no prefix=%TARGET_DIR% || exit /B 1


text:
Q: Running a .bat file on several servers I am currently trying to run a .bat file on around 150 servers. I can get the script to run through as if there's no issues - the .bat copies to the servers, however it does not seem to be executing at all.
Running on windows 2012 servers mainly.
#Variables
$servers = "D:\Apps\Davetest\servers.txt"
$computername = Get-Content $servers
$sourcefile = "D:\Apps\Davetest\test.bat"
#This section will install the software
foreach ($computer in $computername)
{
    $destinationFolder = "\\$computer\C$\Temp"
    <#
       It will copy $sourcefile to the $destinationfolder. If the Folder does
       not exist it will create it.
    #>

    if (!(Test-Path -path $destinationFolder))
    {
          New-Item $destinationFolder -Type Directory
    }
    Copy-Item -Path $sourcefile -Destination $destinationFolder
    Invoke-Command -ComputerName $computer -ScriptBlock {Start-Process 'c:\Temp\test.bat'}

}

I am looking for it to run the .bat once it hits the servers and currently it only seems to be copying over.

A: That's because Start-Process immediately returns. Use the -Wait Parameter.
Start-Process -FilePath 'c:\Temp\test.bat' -NoNewWindow -Wait -PassThru

microsoft:

-PassThru
Returns a process object for each process that the cmdlet started. By default, this cmdlet does not generate any output.
-Wait
  Indicates that this cmdlet waits for the specified process and its descendants to complete before accepting more input. This parameter suppresses the command prompt or retains the window until the processes finish.

-PassThru returns you a process object, where you can check the ExitCode parameter:
$p = Start-Process -FilePath your_command -ArgumentList "arg1", "arg" -NoNewWindow  -Wait -PassThru
if ($p.ExitCode -ne 0) {
   throw "Failed to clone $buildItemName from $buildItemUrl to $($tmpDirectory.FullName)"
}

As an alternative to Start-Process you could also use Invoke-Expression which will return you the stdout of the console.
To check if Invoke-Expression was successful you can use:
 $output = Invoke-Expression $command
 if ((-not $?) -or ($LASTEXITCODE -ne 0)) {
        throw "invoke-expression failed for command $command. Command output: $output"
 }


text:
Q: "it is rusted" or "it has rusted" or "it has been rusted"? Are they correct? or what are differences among these sentenses?
  it is rusted.
  it has rusted.
  it has been rusted.

A: The phrase 'It is rusted' (or 'rusty') means that something has rust on its surface.
'It has rusted' = it has developed rust on its surface (so the general meaning is much the same).
'It has been rusted' could mean that something was formerly rusty but has since been cleaned.


text:
Q: How to convert Module & Function from VB.NET to c# I'm totally new in c#, I wrote my code in VB.NET before but I'm trying to use c# to re-develop my program and as a lesson for learning c#. I tried long time but still can't get a proper conversion from VB.NET to c# , can anyone help me to convert as I will more easier to understand c#, thank you !
This is my code from VB.NET
Module GetStaffList

Dim Url As String
Dim CorpID As String
Dim Secret As String
Const ErrCode As String = """errcode"":0,""errmsg"":""ok"""

Function Token(CorpID As String, Secret As String) As String

    CorpID = "wwe1f80304633b3"
    Secret = "Ev7_oVNNbTpzkfcZ_QhX9l0VjZnAQ"

    Dim http = CreateObject("MSXML2.ServerXMLHTTP")
    Url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" & CorpID & "&corpsecret=" & Secret
    http.Open("get", Url, False)
    http.send()

    If http.Status = 200 Then
        Token = http.responseText
    End If

    If InStr(Token, "access_token") > 1 Then
        Token = Split(Token, ",")(2)
        Token = Split(Token, ":")(1)
        Token = Replace(Token, """", "")
        MainPage.TxtToken.Text = Token
    Else
        Token = ""
    End If

End Function

And below is what I trying convert to c# but still hard to do
namespace SC_System

{
    class MSG
    {
        const string ErrCode = "\"errcode\":0,\"errmsg\":\"ok\"";
    public void Token(string CorpID, string Secret)
    {
        var http = CreateObject("MSXML2.ServerXMLHTTP");
        string Url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" + PDC.CorpID + "&corpsecret=" + PDC.Secret +"";
        HttpWebRequest GetUrl = (HttpWebRequest)WebRequest.Create(Url);
        HttpWebResponse ResponseUrl = (HttpWebResponse)GetUrl.GetResponse();
        if (ResponseUrl.StatusCode == HttpStatusCode.OK)
        {
            Console.WriteLine(ResponseUrl.StatusDescription);
            ResponseUrl.Close();
        }

    }

    private object CreateObject(string v)
    {
        throw new NotImplementedException();
    }
}

}

A: In VB, a Function returns some value. In your code it returns a string

*

*Function Token(CorpID As String, Secret As String) As String
becomes
string Token(string CorpID, string Secret){
  // do something...and then
  return "some string value";
}

and needs to return some string value. The function name doesn't infer a variable of the same name (Token) as the return value

*a Sub doesn't return anything so:
Sub Token(CorpID As String, Secret As String)
becomes void in c#
void Token(string CorpID, string Secret)
Hopefully should get you going...

A: This translates the working parts of the original VB:
internal static class GetStaffList
{
    //this doesn't seem to be used right now
    internal const string ErrCode = "\"errcode\":0,\"errmsg\":\"ok\"";

    internal static void Token(string CorpID, string Secret)
    {
        CorpID = CorpID ?? "wwe1f80304633b3";
        Secret = Secret ?? "Ev7_oVNNbTpzkfcZ_QhX9l0VjZnAQ";

        string token;
        using (var wc = new WebClient())
        {
            token = wc.DownloadString($"https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={CorpID}&corpsecret={Secret}");
        }
        if (token.Contains("access_token"))
        {
            token = token.Split(",")[2].Split(":")[1].Replace("\"", "");
            MainPage.TxtToken.Text = token;
        }
        else
        {
            token = "";
        }
    }
}

But you're probably better off actually returning a value, and not updating the UI, as was only hinted at in the VB method:
internal static string Token(string CorpID, string Secret)
{
    CorpID = CorpID ?? "wwe1f80304633b3";
    Secret = Secret ?? "Ev7_oVNNbTpzkfcZ_QhX9l0VjZnAQ";

    string token;
    using (var wc = new WebClient())
    {
        token = wc.DownloadString($"https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={CorpID}&corpsecret={Secret}");
    }
    if (token.Contains("access_token"))
    {
        return token.Split(",")[2].Split(":")[1].Replace("\"", "");
    }
    return "";
}

And then you'd call it like this:
string token = GetStaffList.Token(null, null);
if (!string.IsNullOrEmpty(token))
{
    MainPage.TxtToken.Text = token;
}

Never have your utility methods or classes directly update the UI.
In the same vein, it's better to write the VB like this:
Public Module GetStaffList

    Const ErrCode As String = """errcode"":0,""errmsg"":""ok"""

    Public Function Token(Optional CorpID As String = Nothing, Optional Secret As String = Nothing) As String

        CorpID = If(CorpID,"wwe1f80304633b3")
        Secret = If(Secret,"Ev7_oVNNbTpzkfcZ_QhX9l0VjZnAQ")

        Dim token As String
        Using wc As New WebClient()
            token = wc.DownlaodString(string.Format("https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={0}&corpsecret={1}", CorpID, Secret))
        End Using

        If token.Contains("access_token") Then
            Return token.Split(",")(2).Split(":")(1).Replace("""", "")
        End If
        Return ""
    End Function
End Module

Finally, you should consider using an actual JSON parser to extract the token value you need from the download result. The Split() method is notorious for gotchas with this kind of thing, and actually tends to be slower than a dedicated parser.


text:
Q: asp.net MVC 3 DateTime linq I have a table of events, I need a linq query that will return all events from a certain month and year, not day.
something like
var monthquery = from c in db.events
                  where c.startdate.month == DateTime(MonthValue, Year Value)
                  select c;

I just don't know the syntax. What do I put in instead of MonthValue to get July, for instance?
Thanks in advance

A: Instead of MonthValue, you can put the integer that represents the month ...
var monthquery = from c in db.events
                  where c.startdate.month == IntegerThatRepresentTheMonth
                  && C.startDate.Year == IntegerThatRepresentTheYear
                  select c;


text:
Q: Class and Function in PHP

Link to popup

the top code is my index, where in you can see a Link to a popup link
and when you click that a simple form will rise, the form has 2 textbox and one submit button this is the code for the form popupex.php

<title>Form</title>

<?php
print"<form action='func.php?add/inside_add' method='post'>";
?>
<input type='text' name='ok'>

<input type='text' name='notok'>

<input type='submit'>
</form>

Question: why the code in my func.php is not running? simply because of error? and can some explain the error and also give solution?
this is my func.php
<?php
function goback()
{
window.history.go(-1);
}

class add{
    function inside_add(){

    goback();
    }
}
?>

what im hoping in this function , is when i click the button in my popupex.php it will go back in the form popupex.php. thx

A: The code you provided is a javascript function window.history.go(-1)
use header('Location:' . $_SERVER['HTTP_REFERER']); for PHP to return to the previous page.


text:
Q: If $G$ is a group whereby $(a\cdot b)^{i} =a^i\cdot b^i$ for three consecutive integers $i$ for all $a, b \in G$, show $G$ is abelian. If $G$ is a group in which $(a\cdot b)^{i} =a^i\cdot b^i$ for three consecutive integers $i$ for all $a, b \in G$, show that $G$ is abelian.
Proof: Let $x$ be the smallest of the 3 consecutive integers. Then, we have
$(1)(a\cdot b)^{x} =a^x\cdot b^x$,
$(2)(a\cdot b)^{x+1} =a^{x+1}\cdot b^{x+1}$ and
$(3)(a\cdot b)^{x+2} =a^{x+2}\cdot b^{x+2}$.
Using $(2)$ and multiplying $a^{-1}$ on the left and $b^{-1}$ on the right, we get $baba...ba = a^{x}b^{x}(4)$ whereby there are $x$ number of $a$ and $x$ number of $b$ on both sides.
Using $(1)$ and multiplying both sides on the right by $ab$, we have $\overbrace{abab...ab}^{(x+1)ab} = (a^{x}b^{x})ab (5)$.
Substitute $(4)$ into $(5)$, we get $\overbrace{ab...ab}^{(x+1)ab} =\overbrace{ba...ba}^{(x)ba}ab(6)$.
Using $(3)$ and multiplying $a^{-1}$ on the left and $b^{-1}$ on the right, we get $\overbrace{ba...ba}^{(x+1)ba} = a^{x+1}b^{x+1} = \overbrace{abab...ab}^{(x+1)ab}(7)$.
Combining $(6)$ and $(7)$, and multiply $a^{-1}b^{-1}...a^{-1}b^{-1}$ on the left, we get $ab = ba$. Hence $G$ is abelian.

A: Use $\backslash$overbrace{below}^{above}, as in (right click and select to see LaTeX commands):
$$
\overbrace{a\ldots a}^{27}
$$
The proof looks fine to me.


text:
Q: Moving Data between Controllers and Models - Codeigniter Best Practices Sorry for the simple question but let's say that I'm using Ion-Auth with Codeigniter to distinguish between logged-in and not logged-in users.
And I have a simple custom Controller that captures the user's ID as such:
class MY_Controller extends CI_Controller {
     function __construct() {
        parent::__construct();
        global $data;
            if($this->ion_auth->logged_in()){
            $data['logged'] = True;
            $data['uid'] = $this->ion_auth->get_user_id();
            $data['username'] = $this->ion_auth->get_username();
        }

        //User is Not Logged in
        else{
            $data['logged'] = False;
        }
    }
}

Then with any of my regular controller I want to spit out a page for logged-in users and not logged-in users as such...
if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Welcome extends MY_Controller {
        {
        global $data;
            if($data['logged']) {
                $this->load->view('logged_in', $data);
                }
            else{
                $this->load->view('not_logged_in', $data);
            }
        }
}

My question is how should I go about passing the uid to my models? Some of the models are called by the default CI controller that don't call the $this->ion_auth->get_user_id(); function. Should I go into those default controllers and pass the uid to the models or should I call the function $this->ion_auth->get_user_id(); directly within the model?
I apologize for any confusion, I just have a mess of controllers and models that need or don't need the user_id and am trying to avoid having to hard-code each one.

A: You don't need to load the library in the MODEL, MODELS are always called from the CONTROLLERS so you just have to load the Libraries in the Controller, and the functions will be available in the models called from him
So the code
$this->ion_auth->get_user_id()

will work in all models loaded by the controller

A: You can do either.
I try hard to send the user_id to the model within an array (just as you have). It makes the models cleaner and easier to read for me.
eg:
  $data['uid'] = $this->ion_auth->get_user_id();
  $model_results = $this->some_model->get_data($data);

But if you want you can access it via the CI instance
Start the model with
function __construct()
{
    parent::__construct();

    $ci =& get_instance();

}

and then I can access the user_id as follows:
 $user_id = $CI->ion_auth->get_user_id();


text:
Q: NGINX url rewrite to relative not working I am trying to use url rewrite in NGINX, but it doesn't work. Currently am using IP address to access the site.
rewrite ^/mytest/(.*)?.html$ /mytest.html?$1 last;
However, when I add the absolute URL, then it does.
rewrite ^/mytest/(.*)?.html$ http://xx.xxx.xxx.xxx/mytest.html?$1 last;
I would like to use relative url so that the url doesn't change and remain as it is.
The entire nginx config ...
http {
include       /etc/nginx/mime.types;
default_type  application/octet-stream;

access_log  /var/log/nginx/access.log  main;

sendfile        on;
keepalive_timeout  65;

index   index.php index.html index.htm;

server {
    listen       80;
    server_name  xx.xxx.xxx.xxx;
    root         /export/www/mysite/htdocs;

    rewrite ^/mytest/(.*)?.html$ mytest.html?$1 last;

    location / {
        index index.php index.html index.htm;
        if (!-e $request_filename) { rewrite ^(.+)$ /index.php last; }
            try_files $uri $uri/ index.php;
    }

    error_page  404              /404.html;
    location = /40x.html {
    }

    location ~ \.php$ {
        root    /export/www/mysite/htdocs;
        proxy_pass   http://127.0.0.1;
        try_files $uri =404;
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass   unix:/var/spool/phpfpm.sock;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
        include        fastcgi_params;
    }

    try_files $uri $uri/ @handler;
    expires off;

    ## Static conetnt cache
    location ~* \.(?:ico|css|js|gif|jpe?g|png)$ {
       expires 30d;
    }

    location  /. { ## Disable .htaccess and other hidden files
        return 404;
    }

location @handler {
        rewrite / /index.php;
    }

    location ~ .php/ {
        rewrite ^(.*.php)/ $1 last;
    }

    location ~ .php$ {
        if (!-e $request_filename) { rewrite / /index.php last; } ## Catch 404s that try_files miss

        expires        off; ## Do not cache dynamic content

        fastcgi_pass   unix:/var/spool/phpfpm.sock;
        fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
        include        fastcgi_params; ## See /etc/nginx/fastcgi_params
    }
}

}


text:
Q: django - copy header from admin to all templates So what I want to do is add the django admin header within my own base template for my project. I copied over the base.html from admin templates to my project. Can I somehow put {% block header %} tags within base.html and then call it within my own base template for my project?
{% block header %}

    {% block branding %}{% endblock %}

    {% if user.is_active and user.is_staff %}

        {% trans 'Hi,' %}

        {% filter force_escape %}{% firstof user.first_name user.username %}{% endfilter %}.
        {% block userlinks %}
            {% url 'django-admindocs-docroot' as docsroot %}
            {% if docsroot %}
                {% trans 'Documentation' %} /
            {% endif %}
            {% trans 'Change password' %} /
            {% trans 'Log out' %}
        {% endblock %}

    {% endif %}
    {% block nav-global %}{% endblock %}

{% endblock %}

A: All templates that extend from 'base.html' would contain the content inside {% block header %} and {% endblock %}, as long as they do not override the block or its ancestors(by removing the {% block header %}...{% endblock %} part).
If there are templates that do not extend from base.html, you could put the code into their common base, or use something like inline tag or inclusion tags
Also, for the code to work properly for authenticated users, you need to ensure there is user variable in context: normally it's already there, or you need to re-enable "django.contrib.auth.context_processors.auth" if you've removed it before, check the doc

A: I ended up extending my main template from the admin 'base.html' template and going from there. A little messy but it works


text:
Q: Find lexicographically smallest string with given hash value [Competitive Coding] I encountered the following problem for which I couldn't quite find the appropriate solution.

The problem says for a given string having a specific hash value, find the lowest string (which is not the same as the given one) of the
    same length and same hash value (if one exists). E.g. For the
    following value mapping of alphabets: {a:0, b:1, c:2,...,z:25}
    If the given string is: ady with hash value - 27. The
    lexicographically smallest one (from all possible ones excluding the
    given one) would be: acz

Solution approach I could think of:
I reduced the problem to Coin-Change problem and resorted to finding all possible combinations for the given sum. Out of all the obtained solutions, I sort them up and find the lowest (or the next smallest if the given string is smallest).
The problem however lies with finding all possible solutions (even in a DP approach) which might be inefficient for larger inputs.
My doubt is:
What solution strategy (possibly even Greedy) could give a better time complexity than above?

A: I cannot guarantee that this will give you a lower complexity, but a couple of things:1 you don't need to check all the space, just the space of lexicographic value less than or equal to the given string. 2: you can formulate it as an integer programming problem:
Assuming your character space is the letters, and each letter is given its number index[0-25] so a corresponds to 0, b to 1 and so forth. let x_i be the number of letters in your string corresponding to index i. You can formulate your problem as:
min sum_i(wi*xi)
st xi*ai = M
xi>=0,
sum_i(xi)=n
sum_i(wi*xi)<= N
xi integer

Where wi= 26^i, ai is equal to hash(letter(i)), n is the number of letters of the original string, N is the hash value of the original string. This is an integer programming problem so you can try plugging it to a solver. The original problem is very similar to subset sum problem with fixed subset size (where the hash values are the elements you are summing over, and the subset size is the length of the string) so you might also want to take a look at that, although as you will see from the answer it is a complicated problem.


text:
Q: How to record screen for browser in webdriverIO? I have been trying to record screen using different npm packages but I am unable to record the screen when the test is running on the browser.

A: Maybe it will help:
https://github.com/praveenprasannan/wdio-video-recorder
Also you can use Selenoid (https://aerokube.com/selenoid/latest/): your tests will be running inside docker-containers. About video-recording:
https://aerokube.com/selenoid/latest/#_video_recording


text:
Q: Determine when caret reaches the end of input box I have found this question which provides a solution to compute the exact position of the caret in a text or input box.
For my purposes, this is overkill. I only want to know when the caret is at the end of all the text of an input box. Is there an easy way to do that?

A: In all modern browsers:
//input refers to the text box
if(input.value.length == input.selectionEnd){
    //Caret at end.
}

The selectionEnd property of an input element equals the highest selection index.

A: <script>
input = document.getElementById('yourinputfieldsid');
if(input.selectionEnd == input.selectionStart && input.value.length == input.selectionEnd){
//your stuff
}
</script>

This checks to see if the caret actually is at the end, and makes sure that it isn't only because of the selection that it shows an end value.

A: You don't specify what you want to happen when some text is selected, so in that case my code just checks whether the end of the selection is at the end of the input.
Here's a cross-browser function that wil work in IE < 9 (which other answers will not: IE only got selectionStart and selectionEnd in version 9).
Live demo: http://jsfiddle.net/vkCpH/1/
Code:
function isCaretAtTheEnd(el) {
    var valueLength = el.value.length;
    if (typeof el.selectionEnd == "number") {
        // Modern browsers
        return el.selectionEnd == valueLength;
    } else if (document.selection) {
        // IE < 9
        var selRange = document.selection.createRange();
        if (selRange && selRange.parentElement() == el) {
            // Create a working TextRange that lives only in the input
            var range = el.createTextRange();
            range.moveToBookmark(selRange.getBookmark());
            return range.moveEnd("character", valueLength) == 0;
        }
    }
    return false;
}


text:
Q: Optimized detection of which regex in a list matches an input Suppose I have a list of regexes, like so:

*

*File ".*" not found

*Out of memory

*You do not have permission to perform this action

*Network connection to [^ ]* failed

*Unrecognized command: .*

*....

(In practice, the list will be maybe 100 items long for my use case, and will periodically have items added to it.)
Given an input, I want to quickly (say, minimal worst-case runtime, although I'm open to other measures of "quickly," as well as approximate guarantees thereof) determine which of the above, if any, my input matches.  (If there are multiple matches, let's say we can return the index of any match.  Or, if it helps, we can also require that the regexes on the initial list be mutually exclusive.)
So for instance if I don't care about performance I could just write something like this (pseudocode):
for(int i = 0; i < expressions.length; i++)
{
  if(expressions[i].matches(input) { return i; }
}

return NO_MATCH;

However, for the list above, one could write something considerably more efficient, e.g.
switch(input[0])
{
  case 'F':
    return expression[0].match(input) ? 0 : NO_MATCH;

  case 'O':
    return expression[1].match(input) ? 1 : NO_MATCH;

  // ...
}

Of course, depending on the nature of the items in the list, switching on the first character might not be the way to go.  I would like something that takes as input a list of regexes as above and outputs an optimized algorithm for determining which item, if any, matches.
This seems similar to a number of commonly dealt-with problems, such as:

*

*lexer and parser generation

*regex tries

*building a state machine to recognize a regular language

However, at least as far as I can tell (and maybe I'm missing something), there's no straightforward way to use tools designed for the above to get what I want here.


text:
Q: json_decode returns null when I try to decode the response from youtube api So I try to create a oauth connection with youtube api but I have a problem with decoding the response. My problem is here:
public function getCallbackUrl($code)
{

    // Grab the returned code and extract the access token.
    $this->params = [
        'code'          => $code,
        'client_id'     => '#####',
        'client_secret' => '####',
        'redirect_uri'  => '######',
        'grant_type'    => 'authorization_code'
    ];

    // Get access token
    $command = 'curl --data "' . http_build_query($this->params) . '" https://accounts.google.com/o/oauth2/token';
    exec($command, $resultToken);
    $resultToken = json_decode($resultToken[0]);

After I make the exec $resultToken returns like this:
array(5) { [0]=> string(1) "{" [1]=> string(93) " "access_token" : "###########"," [2]=> string(26) " "token_type" : "Bearer"," [3]=> string(21) " "expires_in" : 3599" [4]=> string(1) "}" }

But when I try to json_decode to obtain an array: $resultToken = json_decode($resultToken[0]);
I get a result NULL
Can anyone explain to me why please? Any help is welcomed, thank you for your time!
var_dump($resultToken[0]) = NULL;

A: You are trying to decode a value which is not valid JSON. Verify whether your API request is returning the correct response. From the documentation:

NULL is returned if the json cannot be decoded or if the encoded data is deeper than the recursion limit.

On a side note, you are using a system call to invoke cURL. Consider using the native PHP cURL extension or a proper library.


text:
Q: Change language in Mac App Store My Mac app only has Chinese localization (due to its special purpose). Currently "Language: English" is shown in the Information column in its Mac App Store page (see the screenshot below). How to change this Language to Chinese (or some other languages)?

A: Open the App Store and then scroll down. In the bottom right corner, click on a flag- you'll find the country/language options there! :)


text:
Q: Clipped scope's bounding box In the following example, I \clip out a 3x3 rectangle of an image. I'd expect the resulting scope to have a bounding box of 3x3, so the two text nodes should line up with the extent of the clipped picture. Instead, the (0,0) and (3,3) labels show up where I would expect them if I didn't clip the image.
\documentclass[margin=3mm,tikz]{standalone}
\usepackage{tikz}
\usepackage{mwe}

\begin{document}

\begin{tikzpicture}

\begin{scope}
  \clip (9, 5) rectangle ++ (-3,-3);
  \node[anchor=south west,inner sep=0] at (0,0)
    {\includegraphics[width=0.9\textwidth]{example-image.jpg}};
\end{scope}

\draw (0,0) node{(0,0)};
\draw (3,3) node{(3,3)};

\end{tikzpicture}

\end{document}

How do I clip the scope so that its bounding box goes from (0,0) to (3,3) while keeping the same contents as currently? I.e. I'd like this:

(Note that this is a simplified example. In my real use case, there is a lot of drawing happening (and no images involved) in the scope, so this has nothing to do with using an image)

A: Maybe you would find use as bounding box syntax interesting. And then use a scope with shifting the coordinate system.

\documentclass[border=3.14mm,tikz]{standalone}

\begin{document}
    \begin{tikzpicture}
        \begin{scope}
        \clip (6,2) rectangle (9,5);
        \node[anchor=south west,inner sep=0] at (0,0)
            {\includegraphics[width=0.9\textwidth]{example-image.jpg}};
        \useasboundingbox (6,2) rectangle (9,5);
        \end{scope}
        \begin{scope}[xshift=6cm,yshift=2cm]
            \draw[red] (0,0) grid (3,3);
            \path (0,0) node{(0,0)};
            \path (3,3) node{(3,3)};
        \end{scope}
    \end{tikzpicture}
\end{document}

EDIT
If you want to use your clip as bounding box (and not type it once more), you can define your clip like a reusable path:
\documentclass[border=3.14mm,tikz]{standalone}

\begin{document}
    \begin{tikzpicture}
        \def\clipbox{(6,2) rectangle (9,5)} % <--- Define here
        \begin{scope}
        \clip \clipbox; % <--- Use here
        \node[anchor=south west,inner sep=0] at (0,0)
            {\includegraphics[width=0.9\textwidth]{example-image.jpg}};
        \useasboundingbox \clipbox; % <--- And use there
        \end{scope}
        \begin{scope}[xshift=6cm,yshift=2cm]
            \draw[red] (0,0) grid (3,3);
            \path (0,0) node{(0,0)};
            \path (3,3) node{(3,3)};
        \end{scope}
    \end{tikzpicture}
\end{document}

A: As already mentioned by @SebGlav, it seems that you are looking for a combination of two commands clip (which defines which part of the image is visible) and shift (which changes the origin).
To simplify this double command, you can define a new clip and shift style that does the job.
\documentclass[tikz,border=7pt]{standalone}
\tikzset{
  % usage in scope style: clip and shift={path}
  clip and shift/.code = {
    \clip #1 (current path bounding box.south west)
      coordinate (clip and shift origin);
  },
  clip and shift/.append style = {shift={(clip and shift origin)}}
}
\begin{document}
  \begin{tikzpicture}

    \fill[red] (9,5) circle(3pt) node[above right]{(9,5)};
    \fill[red] (7,2) circle(3pt) node[below left]{(7,2)};

    \begin{scope}[clip and shift={(9,5) rectangle +(-2,-3)}]
      \node[anchor=south west,inner sep=0] at (0,0)
        {\includegraphics[width=0.9\textwidth]{example-image.jpg}};

      \fill[blue] (0,0) circle(3pt) node[above right]{(0,0)};
      \fill[blue] (2,3) circle(3pt) node[below left]{(2,3)};
    \end{scope}
  \end{tikzpicture}
\end{document}

EDIT: The code was adapted to fit @cactus requests from comments.


text:
Q: css issue "even height to all the child element in a container" when i click the click button the container 4 overlaps on container 3 its my scenario
Issue :
 i had made even height to container 1, container 2, contianer 3 by the display:flex i can't achieve it to the container 4, since i used position:absolute for the container 4.
the container which contain the max-content will be the min-height, so with respect to it all the container should have equal height.
solution can be done by jquery or by css
WORK DONE : http://jsfiddle.net/vasanthanvas/wxab9Ldn/14/
Current output

expected output

A: Since you are using Zurb Foundation and want to match the heights of all div elements, maybe you can try it by using their helper class "equalizer".
All the docs and examples are here - http://foundation.zurb.com/docs/components/equalizer.html.

A: Check working DEMO : http://jsfiddle.net/wxab9Ldn/16/
Add below script.
JQUERY
$(document).ready(function () {
    var evenH = 0;
    $('.row .small-4').each(function(){
        var getH = $(this).outerHeight();
        if(getH > evenH)
            evenH = getH;
    });
    $('.row .small-4').css({'height':evenH});
});

A: put this in your css section
#main {height: auto;margin:100px 0 0 0;position:relative;display:flex}
    button{padding:0;display:block;position:absolute;right:0px;z-index:111;height:100%}
    .popUp{position:absolute;right:-33.33%}
    .pollSlider{background:rgba(0,0,0,0.5);}
    h1{font-size:24px;}
    .row{width:700px:display:table;height:auto;background:rgba(0,0,0,0.1);}
    .small-4,.pollSlider,.first,.second,.delet{display:table-cell;height:100%;overflow:hidden;
    }


text:
Q: How To Overflow Text Above Divs - Even if Parent Div Is 0% Width I'm using Bootstrap 4, and I have three divs horizontally stacked in a row. The three divs are of varying percentage widths. Often the center div is 0%.
However, I want to display text from that 0% div every single time, no matter what. I can not seem to get the text within that div to
a) Show up above the other divs in every situation
b) Center the text so that the overflow extends equally from the center of the 0% div.
I'd really prefer to not have to do this using a left/right positioning, because the width of the text is variable.
Here's the code:

32.34 in.

And here is a BootPly:
https://www.bootply.com/IurHhOsuf5
Is there a way to make this text stay on top?
Here's an image of what it's currently doing:
Before
And here's what it should look like:
After
Thanks everybody!

A: Why not use Progress Bar from Bootstrap4?

32.34 in.

Couple key points here:

*

*You need to use z-index to make the text go on top of the progress bars.

*By default, progress bar's flex direction is set to column. In order to center the text, you need to set align-items: center;. Or you can use bootstrap class align-items-center.

demo: https://jsfiddle.net/davidliang2008/aq9Laaew/290113/


text:
Q: How to clear the div(contenteditable) area with js? I send some data and I wanna clear the content-editable div area.
The vaule of the div is empty but in the screen there is a text left.
It is a SPA Vue.js project.

<input type="text" v-model="contents" style="display: none;">

export default {
  data: function(){
        return {
          (...)
          formShow: false,
          contents: '',
          innerContent:'',
          (...)
        }
      },
  methods: {
    (...)
    formToggle(){
        this.stampShow= false
        this.stampAreaShow= false
        this.contents = ''
        this.innerContent = this.contents
        this.formShow = !this.formShow
      },
    createNotify(){
      (...)
      else if(!this.stampAreaShow&&this.contents&&!this.uploadedImage) {//text only
          axios.post('/create_notify', {notify_type: 'text',contents: this.contents}).then((res)=>{
            if (res.data != null){
              alert("メッセージ送信完了!")
              this.formToggle();
              this.fetchNotifies();
            }
          }, (error) =>{
            console.log(error)
          })
        }
    }

A: okay, it was about ''.
If I change (this.contents = '') into (this.contents = ""), it works.
But I don't know why...
What's the difference between single quotation and double quotation?


text:
Q: Moving the div on scroll with pure javascript I want an image inside div to be moving vertically down whenever a user scrolls. It has to end only at the end of the page. Have used the below script solution from the another post, however it doesn`t help.
HTML

CSS:
#wrapper {
    position: absolute;
}
.image {
    width: 560px;
    height: 700px;
}

Script:
window.onscroll = function (e) {
  var vertical_position = 0;
  if (pageYOffset)//usual
    vertical_position = pageYOffset;
  else if (document.documentElement.clientHeight)//ie
    vertical_position = document.documentElement.scrollTop;
  else if (document.body)//ie quirks
    vertical_position = document.body.scrollTop;
console.log( vertical_position);
  var your_div = document.getElementById('wrapper');
  your_div.top = (vertical_position + 200) + 'px';//200 is arbitrary.. just to show you could now position it how you want
}

What is that I am doing wrong here?? Verfying this further, though I could get the console value vertical_position I can`t really move the div using the below code.
var your_div = document.getElementById("wrapper");
  your_div.top = 400 + 'px';
Is there any other best way to deal with Moving html elements with DIV? Any articles which explains? I am really new to this. Please help me out.
Adding style before the top, worked. However looks like the style applies only once as it moves only once as I scroll. Any ideas.

A: One small miss, it should be style.top:
your_div.style.top = (vertical_position + 200) + 'px';

A: Replace
var your_div = document.getElementById('wrapper');
your_div.top = (vertical_position + 200) + 'px';//200 is arbitrary.. just to show you could now position it how you want

with
$("#wrapper").css("top",(vertical_position + 200) + 'px');


text:
Q: Weird characters in MPI_File_write I copied the following example from  Using MPI-2: Advanced Features of the Message-Passing Interface but the output file is just weired characters. I tried to change the data types from int to char but the output is still the same. I tried to open the open the outputfile with different programs like Notepadqq and gedit. I tried also to open the file with different file formats and adding null pointer to the end of the file through process zero but the results are still weired characters.
/* example of parallel MPI write into a single file */
#include <stdio.h>
#include "mpi.h"
#define BUFSIZE 100

int main( int argc, char **argv )

{
    int i, MyRank, NumProcs, buf[BUFSIZE];
    MPI_File TheFile;
    MPI_Status status;

    MPI_Init(&argc, &argv);
    MPI_Comm_rank(MPI_COMM_WORLD, &MyRank);
    MPI_Comm_size(MPI_COMM_WORLD,&NumProcs);
    for (i=0; i<BUFSIZE; i++)
        buf[i]=MyRank*BUFSIZE+i;
    MPI_File_open(MPI_COMM_WORLD, "testfile",MPI_MODE_CREATE|MPI_MODE_WRONLY,MPI_INFO_NULL, &TheFile);
    MPI_File_set_view(TheFile,MyRank*BUFSIZE*sizeof(int),MPI_INT,MPI_INT,"native",MPI_INFO_NULL);
    MPI_File_write(TheFile,buf,BUFSIZE,MPI_INT,MPI_STATUS_IGNORE);
// THis is my trial
    if(MyRank == 0){
        char nullChar = '\0';
        MPI_File_write(TheFile, & nullChar , 1 , MPI_CHAR ,MPI_STATUS_IGNORE );
    }

    MPI_File_close(&TheFile);
    MPI_Finalize();
    return 0;
}

A: Because you are opening a binary file and you expect to see meaningful characters (not gonna happen). Look here for the difference between binary and text files. You can always read the data with MPI_File_read().


text:
Q: How to run child_process.exec correctly on an ajax request? There is a server, that I have an access to, but do not have ownership on. It serves a node js / express application on a default port 3000. There are several scripts, that are usually run either manually from the terminal or by cron job. What I want to do is to have a button on the client-side and make an ajax request to a certain route and execute a node js command with inline arguments. For example:
node script.js 123
All routes are set and working. I have a CliController file that handles requests and has to run the command above. Currently I am using the following code:
cp.exec(`node script.js ${ip}`, function (err, stdout, stderr) {
      if (err) {
         console.log(err);
      }
      console.log(stdout);
      console.log(stderr);
 });

The script.js file is in root folder of the project, but the project itself was built by using express-generator and is being served using node bin/www command. There is a service/process on the server that runs nodemon to restart this project if it fails as well. Therefore I do not have access to output of that particular process.
If I run the command above in the terminal (from the root folder of the project, to be precise), it works fine and I see the output of the script. But if I press the button on the webpage to make a request, I am pretty sure that the script does not execute, because it has to make an update to database and I do not see any changes. I also tried to use child_process.spawn and child_process.fork and failed to get it working.
I also tried to kill nodemon and quickly start the project again to the see console output. If I do this, everything works.
What am I doing wrong ?

A: The process invoked may be in a blocking state, hence the parent script is simply waiting for the children process to terminate, or return something.
We can avoid this behaviour right into the shell command, by adding & (ampersand control operator) at the end.
This makes a command running in the background. (Notice, you can still control the children(s) process using the PID's and POSIX signals, this is another subject, but very related and you might find it very handy pretty soon).
Also notice that killing/stopping the parent script will also kill the children(s). This can be avoided using nohup.
This is not linked to JavaScript or node.js, but to bash, and can be used with anything in the shell.
cp.exec(`node script.js ${ip} &`, function (err, stdout, stderr) {
      if (err) {
         console.log(err);
      }
      console.log(stdout);
      console.log(stderr);
 });

Bash reference manual


text:
Q: Extract particular elements from xml I implemented XML parsing in my iOS app, but I'm having problems with the following file :
<?xml version="1.0" encoding="UTF-8"?>
<AllJobs>
    <Mainjobs>
     <job1 name="simple">
     <Group name="one">
        <item name>"itemone"</item name>
        <item name>"itemtwo"</item name>
        <item name>"itemthree"</item name>
      </Group>
      <Group name="two">
        <item name>"itemfour"</item name>
        <item name>"itemfive"</item name>
        <item name>"itemsix"</item name>
      </Group>
    </job1>
    <job2 name="medium" />
    </job2>
    <job3 name="hard" />
    </job3>
    </Mainjobs>
</AllJobs>

I am trying to parse the item names that are "itemfour, itemfive, itemsix" and displaying them in a tableview :
<Group name="two">
    <item>"itemfour"</item>
    <item>"itemfive"</item>
    <item>"itemsix"</item>
</Group>

I am parsing like this but it is retrieving all the items names in every group tag :
-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict {

    if([elementName isEqualToString:@"Alljobs"]){
        jobNameArray=[[NSMutableArray alloc]init];

    } else if ([elementName isEqualToString:@"Mainjobs"]) {
        //  self.itemDict = [[NSMutableDictionary alloc] init];
        object=[[parseObject alloc]init];
        dict=[[NSMutableDictionary alloc] init];
    } else if ([elementName isEqualToString:@"Group"]) {
        if ([str isEqualToString:@"Two"]) {
            currentElement=nil;
            currentElement=[[NSMutableString alloc]init];
        }
    } else if([elementName isEqualToString:@"item"]) {
        str=[attributeDict objectForKey:@"name"];
        NSLog(@"the attribute string is %@",[attributeDict objectForKey:@"name"]);
    }
}

-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
    if(string) {
        [currentElement appendString:string];
        NSLog(@"  the element00000000%@", currentElement);
    }
}

-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:    (NSString *)namespaceURI qualifiedName:(NSString *)qName {

    if([elementName isEqualToString:@"Mainjobs"]){
        NSLog(@"the array count is %i",[jobNameArray count]);
    } else if([elementName isEqualToString:@"Job1"]) {

    }

    if([elementName isEqualToString:@"</item>"]) {
        NSLog(@"element ---------%@",elementName);

        [jobNameArray addObject:str];
    }
}

A: XML tag names cannot have spaces.
The results involving <item name> are undefined.


text:
Q: Visual Studio 2015 freezes when debugging a cpp code I've installed Visual Studio 2015 Enterprise. I'm trying to create a c++ OpenGL project, however, it always freezes when I'm debugging(ctrl + f5). I've tried to write a simple program that prints text to the screen and it still freezes. The build completes successfully, projects in C# don't freeze as well. When I'm trying to run the cpp project VS freezes completely and I have to kill the process, running the .exe directly freezes the explorer..
I haven't found any solution to that kind of problem in the web, and I was hoping that someone here will know what to do..
Thanks :)

A: Try setting a breakpoint on the very first line of your main, click on debug and see if it gets to the breakpoint. If it does, try stepping through until you see what is causing your freeze.

A: I had exactly the same problem as you. Turns out my Avast anti-virus was causing the issue. I disabled it and now it's working.
I found the answer from this question:
Visual Studio 2015 freezes when finished building