text:
Q: Cocoapod compilation fails when loading .xib file I've pushed it to trunk. And then I did "pod install" to my own project, all files are downloaded (I can confirm it from Pods in my project). But it doesn't compile, it gives me this error
"Unable to run command 'StripNIB ABPhotoView.nib' - this target might include its own product."

A: Have found the solution. Follow below:
rather than adding a reference to the file in the s.source_files, I put it in the s.resources as shown below
s.resources = ["images/*.png", "classes/MyView.xib"]
For more details, https://github.com/bennyguitar/CollapseClick/issues/14

A: It's crazy! Used to have the same issue when had such podspec string

s.resources = "Project/**/*.{png,bundle,xib,nib}"

changing to

s.resource = "Project/**/*.{png,bundle,xib,nib}"

has solved the problem.

A: It seems the syntax has evolved, maybe since the new Cocoapods version (1.0)
When you create your pod with the template described here, your .podspec will contain some commented lines to include assets (like .png or .xib)
#  s.resource_bundles = {
#   'MyMarvelousComponent' => ['MyMarvelousComponent/Assets/*.png']
#  }

Just uncomment, change the .png with what you want to include, and move your files to Assets/ folder (because, this is the folder where they should be)
Note Cocoapods will automatically create a .bundle in the Products/ group, so if you need these assets in the example project, you'll need to select the right NSBundle first.

A: I had the same problem, when podspec file was incorrect. My mistake was that I didn't specify .h and .m extensions for source_files. Because of that .xib files were added twice. This is a correct example:
  s.source_files = 'YourTarget/Classes/**/*.{h,m}'

  s.resources = ['YourTarget/Classes/UIComponents/**/*.xib']

See https://guides.cocoapods.org/syntax/podspec.html#source_files


text:
Q: Loop through ArrayList I'm trying to loop through an ArrayList an get the current value of the loop instance.
public ArrayList<Double> getCurrent(double x) {

    ArrayList<Double> list = new ArrayList<>();

    list.add(x);

    ArrayList<Double> list1 = new ArrayList<>();

    double sum = 0;
    for (int i = 0; i < list.size(); i++) {
        sum += list.get(i);
        list1.add(sum);
    }

    return list1;

}

Here are my JSP file. Note the loop goes through my ArrayList history, and the values I want to parse into the new ArrayList from the method getCurrent(double x) takes ret.
<% for (history his : history) {

    double ret = his.getRet();
    double dep = his.getDeposit();
    String res = his.getRes();

    if (res.equals("Loss")) {
        ret = -dep;
         }

 %>

<%=his.getCurrent(ret) %>

<%} %>

This gives my an ArrayList which consist of the correct values, but NOT added with the previous values. The ArrayList now shows: [30.0, -5.0, 20.0] which is correct values. However, I want it to display: [30, 25, 45] so the values are added together with all previous values.

A: I believe what you want to do is to pass the double values to this function and then the function will return the list with the calculated values.
According to your code whenever the function is invoked a new Arraylist is declared every time. Thus there are no previous values, there. If you want the output to be like what you have mentioned then declare the list outside the function. Once it is outside there is no need to declared it again and again. It will retain all the previous values and when you will do your calculation it will give you your expected output.

A: I believe you want to get some but your declared variable is not final. Every function call will reset its value and you will not be able to get the required results. Furthermore, the statement:

    sum += list.get(i);

is not as much appropriate to all compilers and IDE's and this can cause runtime error and may contain garbage if not properly handled. I prefer using this modified code.

    Final double sum = 0;
    for (int i = 0; i < list.size(); i++) {
        sum = sum + list.get(i);
        list1.add(sum);
    }

redpajama_set_name: RedPajamaStackExchange


text:
Q: on adding folder items handle not allowing if statements AppleScript I am having trouble with running anything other than a dialog box within an on adding folder items handle. The code does not go through the if statements. Any help would be appreciated. Code is below:
on adding folder items to theAttachedFolder after receiving theNewItems
    set author to theNewItems
    if "blah" is in author then
        set theDialogText to "Blah in filename"
        display dialog theDialogText buttons {"Continue", "Close"} default         button "Close" with icon note
        set author to ""
    else if "lol" is in author then
        set theDialogText to "Lol in file name"
        display dialog theDialogText buttons {"Continue", "Close order"} default button "Close" with icon note
        set author to ""
    else if "ha" is in author then
        set theDialogText to "Ha is in file name"
        display dialog theDialogText buttons {"Continue", "Close"} default button "Close" with icon note
        set author to ""
    else if "omg" is in author then
        set theDialogText to "omg is in file name"
        display dialog theDialogText buttons {"Continue", "close"} default button "Close" with icon note
    end if
end adding folder items to

A: theNewItems is a list of alias specifiers. A comparison of this type with a string fails always.
You have to get the name of the item and you have to iterate the list of files
on adding folder items to theAttachedFolder after receiving theNewItems
    repeat with anItem in theNewItems
        tell application "System Events" to set fileName to name of anItem

        if "blah" is in fileName then
            set theDialogText to "Blah in filename"
            display dialog theDialogText buttons {"Continue", "Close"} default button "Close" with icon note
        else if "lol" is in fileName then
            set theDialogText to "Lol in file name"
            display dialog theDialogText buttons {"Continue", "Close order"} default button "Close" with icon note
        else if "ha" is in fileName then
            set theDialogText to "Ha is in file name"
            display dialog theDialogText buttons {"Continue", "Close"} default button "Close" with icon note
        else if "omg" is in fileName then
            set theDialogText to "omg is in file name"
            display dialog theDialogText buttons {"Continue", "close"} default button "Close" with icon note
        end if
    end repeat
end adding folder items to


text:
Q: QPalette does not change the background of the button I have the problem that the background of the button cannot be changed. Only the border is changed.
I assumed that some attribute prevented this. But I think I'm wrong on that point.
I've gone through the Qt documentation but can't find anything. I can only find examples on the internet that give me the same result. Is there a way to change the background?
Here is the code:
#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    //ui->pushButton->setAttribute(Qt::WA_SetPalette);
    //ui->pushButton->setAttribute(Qt::WA_SetStyle);

    ui->pushButton->setAutoFillBackground(true);
    ui->pushButton->setAttribute(Qt::WA_ShowModal);
    QPalette pal = ui->pushButton->palette();

    //pal.setColor(QPalette::Base, Qt::cyan);
    //pal.setBrush(QPalette::Base, Qt::cyan);
    pal.setColor(QPalette::Button, Qt::cyan);
    pal.setBrush(QPalette::Button, Qt::cyan);

    ui->pushButton->setPalette(pal);

    ui->pushButton->update();

    //ui->pushButton->setAttribute(Qt::WA_NoSystemBackground, true);

//    setAutoFillBackground(true);
//    QPalette pal2 = palette();
//    pal2.setBrush(QPalette::Button, Qt::cyan);
//    pal2.setColor(QPalette::ButtonText, Qt::cyan);
//    QApplication::setPalette(pal2);
}

A: As I test your code this is my result:

But you can change it By using StyleSheet instead of QPalette.
ui->pushButton->setStyleSheet(QString::fromUtf8("background-color: cyan;"));

A: Here's the code I use to set the background color of a QPushButton (or any QAbstractButton):
// @param btn button to change colors of
// @param bc new background color for button
// @param optTextColor if non-NULL, the new color to use for the
//                button's text label.  If NULL, this function
//                will choose either black or white (whichever
//                it thinks will be more readable)
void SetButtonColor(QAbstractButton * btn, const QColor & bc, const QColor * optTextColor = NULL)
{
   QPalette p = btn->QWidget::palette();
   p.setColor(QPalette::Button, bc);

   const QColor fc = GetContrastingTextColor(bc);
   p.setColor(QPalette::Active,   QPalette::ButtonText, optTextColor?*optTextColor:fc);
   p.setColor(QPalette::Inactive, QPalette::ButtonText, optTextColor?*optTextColor:fc);
   p.setColor(QPalette::Disabled, QPalette::ButtonText, optTextColor?*optTextColor:MixColors(fc, Qt::lightGray, 0.5f));
   btn->setPalette(p);
}

// Returns either Qt::white or Qt::black, whichever will make for more readable text
// in front of the passed-in background color
QColor GetContrastingTextColor(const QColor & c)
{
   const int darkThresh = 64;
   const int loneDelta  = 129;
   const int loneRed    = ((c.green()<darkThresh)&&(c.blue() <darkThresh)) ? loneDelta : 0;
   const int loneGreen  = 0;
   const int loneBlue   = ((c.red()  <darkThresh)&&(c.green()<darkThresh)) ? loneDelta : 0;
   return (std::max(c.red()-loneRed, std::max(c.green()-loneGreen, c.blue()-loneBlue)) >= 128) ? Qt::black : Qt::white;
}

// Returns a weighted average value between (v1) and (v2)
static int Mix(int v1, const int v2, float p)
{
   return (int) ((((float)v2)*p)+(((float)v1)*(1.0f-p)));
}

// Returns a weighted average value between (c1) and (c2)
QColor MixColors(const QColor & c1, const QColor & c2, float p)
{
   return QColor(Mix(c1.red(), c2.red(), p), Mix(c1.green(), c2.green(), p), Mix(c1.blue(), c2.blue(), p));
}


text:
Q: CodeIgniter Images Using CodeIgniter, I am trying to place several images onto my view page as follows
...
<?php foreach($results_found as $item): ?>

    <?php echo base_url();?>images/$item->img.jpg	?
    <?php echo $item->title ?>

...

but all this displays is the url for the images.
I've stored the names of the images in my database, hence my attempt to use $item->img to get access the name. The images are located in my root directory (htdocs\website_name\images)
Any help would be really appreciated. Thanks in advance

A: You need an image tag.  The CodeIgniter way to do it is:

  <img src="<?= base_url(); ?>images/<?= $item->img ?>.jpg" />
  <?php echo $item->title ?>

Try it, and check View -> Source to make sure the syntax of the image element reads like this once its been rendered into html:

A: You need an image element!!! Im not sure what your $item object looks like but try this

    <img src="/images/<?php echo $item->img ?>.jpg">
    <?php echo $item->title ?>


text:
Q: Convert the http response body to JSON format using Unirest C# I am using mashape api: https://market.mashape.com/montanaflynn/dictionary
Here's my code:
HttpResponse<RootObject> response = Unirest.get("https://montanaflynn-dictionary.p.mashape.com/define?word=irony")
    .header("X-Mashape-Key", "my mashape key")
    .header("Accept", "application/json")
    .asJson<RootObject>();

I generated the RootObject class using: http://json2csharp.com/
Here's my RootObject class code:
class Definition
{
    public string text { get; set; }
    public string attribution { get; set; }
}

class RootObject
{
    public List<Definition> definitions { get; set; }
}

When I run the above code I get the following error:
An unhandled exception of type 'System.InvalidCastException' occurred in unirest-net.dll
Additional information: Unable to cast object of type 'System.IO.MemoryStream' to type 'RootObject'.
Question: How can I resolve the error?

A: Try this. It must be placed in an asynchronous function:
static async Task<RootObject> GetRootInfo()
{
     HttpResponse<RootObject> response = await Unirest.get("https://montanaflynn-dictionary.p.mashape.com/define?word=irony")
    .header("X-Mashape-Key", "my mashape key")
    .header("Accept", "application/json")
    .asJsonAsync<RootObject>();

     return response.Body;
}


text:
Q: How can i change slickgrid header background color based on a condition? I am using a angular-slickgrid = 2.30.2 ,Angular 10, i am using styles.css where i am loading the slickgrid theme through bootstrap .sass file.
i have created a shared slickgrid component and using it in parent components wherever required.

*

*i want to change the slick grid header color based on a condition in my parent component.
For e.g if my variable value is true then show slickgrid header blue else red, how can i do that?

*i want to add bottom border for every third row in grid for only one screen/component which is using slick grid, how can I implement that.

i am new to slickgrid , please guide.

A: Please note that I'm the author of Angular-Slickgrid, there are already plenty of SO questions and answers on how to style SlickGrid, take for example these:

*

*Setting SlickGrid cell styling based on cell value

*how do I apply a class to the header cell for a column in slickgrid

*Angular SlickGrid align header text

*How to add a class to a cell in SlickGrid
and/or simply use the Column properties cssClass or headerCssClass from the Column interface. I added TypeScript types for everything in latest version which should give you enough indication of what you can try.
Also please remember that Angular-Slickgrid is a wrapper of SlickGrid, searching for SlickGrid will always provide you more result to your question searches
Lastly you're on an older version (2.x) that I no longer support, you should think about migrating eventually to get access to newer features and smaller builds, see Migration Guide 3.x and Migration Guide 4.x


text:
Q: Nested ASP.NET tabs I am trying to get a control tab inside another using ASP.NET and Ajax control toolkit , this is the code which i am using:
 <asp:TabContainer ID="TabContainer1" runat="server" ActiveTabIndex="0">
     <asp:TabPanel runat="server" HeaderText="Main tab" ID="TabPanel1">
        <ContentTemplate>
                <asp:TabPanel HeaderText="Nested tab" ID="TabPanel2" runat="server">
                        <ContentTemplate>
                            <asp:Button ID="Button1" runat="server" Text="Delete" />
                        </ContentTemplate>
                </asp:TabPanel>
        </ContentTemplate>
      </asp:TabPanel>
    </asp:TabContainer>

but i am getting an exception saying that :

"Object reference not set to an instance of an object."

I do not know what to do here, because my design needs to have a tab panel inside another one, is this possible ?

A: The nested <asp:TabPanel> should be in its own <asp:TabContainer>, that is probably what the exception is about: the object reference is probably the container, and it is not set to an instance since it's missing for the nested tab.
<asp:TabContainer ID="TabContainer1" runat="server" ActiveTabIndex="0">
  <asp:TabPanel runat="server" HeaderText="Main tab" ID="TabPanel1">
    <ContentTemplate>

      <%-- You need another container before you can add a nested tab --%>
      <asp:TabContainer ID="NestedContainer1" runat="server">
        <asp:TabPanel HeaderText="Nested tab" ID="TabPanel2" runat="server">
          <ContentTemplate>
            <asp:Button ID="Button1" runat="server" Text="Delete" />
          </ContentTemplate>
        </asp:TabPanel>
      </asp:TabContainer>
      <%-- End of the second container --%>

    </ContentTemplate>
  </asp:TabPanel>
</asp:TabContainer>


text:
Q: How to post actual primary keys of records from table and not indexes of an array in php Yii2 if I use select2 widget? My function inside controller is as follows:
public function actionProjects($id)
    {
        $model = $this->findModel($id);
        $projects = Project::find()->all();
        $projectIds = Yii::$app->request->post('projects');
        if (Yii::$app->request->isPost) {
            Yii::$app->session->setFlash('success');
            $model->unlinkAll('projects');
            if ($projectIds) {
                foreach ($projectIds as $projectId) {
                    $project = Project::findOne(abs((int)$projectId));
                    if ($project) {
                        $model->link('projects', $project);
                    }
                }
            }
        }
        print_r($projectIds);
        return $this->render('projects', ['projects' => $projects, 'model' => $model]);
    }

My view is as follows:
<?php
...
function sortArray($a, $b)
{
    return strcmp($a, $b);
}

$projects = ArrayHelper::map($projects, 'id', 'title');
usort($projects, 'sortArray');
?>

<?= Html::encode($this->title) ?>

        <?php $form = ActiveForm::begin(); ?>

            <?= Select2::widget([
                'name' => 'projects[]',
                'options' => ['placeholder' => 'Выберите проект...'],
                'language' => 'ru',
                'value' => array_keys(ArrayHelper::map($model->projects, 'id', 'title')),
                'data' => $projects,
                'pluginOptions' => [
                    'allowClear' => true,
                    'multiple' => true
                ],
            ]) ?>

            <?= Html::submitButton('Обновить', ['class' => 'btn btn-primary']) ?>

        <?php ActiveForm::end() ?>

When I select single or multiple items from select2, and click update button -  this code:
$projectIds = Yii::$app->request->post('projects');

posts array like this:  Array ( [0] => 0 [1] => 1 [2] => 2 )
the data sent to the server is the array of indexes of items and not actual indexes (primary keys) from the table. (I have 3 items in db table - their indexes are 5,6 and 7)
How to sent primary keys of selected items?  I cannot find hidden rat that causes my problem. It seems that everything is correct in code. But actually not.

A: The problem is in the usort() call. That function removes the indexes in your $projects array. You have to use uasort() instead which is designed to maintain indexes in associative arrays.


text:
Q: Struts 2 simple success page doesn't direct on class SampleAction I have followed a tutorial in youtube by  about struts I completely followed every step but I have a problem my program doesn't direct me to the class. I know that it doesn't direct because it does not show the message System.out.println("from execute");
Here is my code:
struts.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
    "http://struts.apache.org/dtds/struts-2.3.dtd">

<struts>
    <package name="default" extends="struts-default">
        <action name="sample" class="com.struts.sample.action.SampleAction">
            <result name="success">/success.jsp</result>
            <result name="error">/error.jsp</result>
        </action>
    </package>
</struts>

web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>Struts2Example</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>

    <filter>
        <filter-name>struts2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>

SampleAction.java:
package com.struts.sample.action;

public class SampleAction {

    public String execute(){

        System.out.println("from execute");
        return "success";
    }

}

success.jsp:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
success
</body>
</html>

I'm getting this output:
HTTP Status 404 - There is no Action mapped for namespace [/] and action name [getTutorial] associated with context path [/Struts2Example].

Type Status report:
message There is no Action mapped for namespace [/] and action name [getTutorial] associated with context path [/Struts2Example].

description The requested resource is not available.

This is my console:
Dec 13, 2013 11:40:46 AM org.apache.catalina.core.AprLifecycleListener init
INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: C:\Program Files\Java\jre7\bin;C:\windows\Sun\Java\bin;C:\windows\system32;C:\windows;C:\Program Files\Broadcom\Broadcom 802.11 Network Adapter\Driver;;C:\Program Files (x86)\Intel\iCLS Client\;C:\Program Files\Intel\iCLS Client\;C:\windows\system32;C:\windows;C:\windows\System32\Wbem;C:\windows\System32\WindowsPowerShell\v1.0\;C:\Program Files\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files (x86)\Intel\OpenCL SDK\2.0\bin\x86;C:\Program Files (x86)\Intel\OpenCL SDK\2.0\bin\x64;C:\Program Files\Lenovo\Bluetooth Software\;C:\Program Files\Lenovo\Bluetooth Software\syswow64;C:\Program Files\Lenovo Fingerprint Reader\;C:\Program Files\Lenovo Fingerprint Reader\x86\;C:\ProgramData\Lenovo\ReadyApps;C:\Program Files\TortoiseSVN\bin;.
Dec 13, 2013 11:40:47 AM org.apache.tomcat.util.digester.SetPropertiesRule begin
WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server:Struts2Example' did not find a matching property.
Dec 13, 2013 11:40:47 AM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-bio-8080"]
Dec 13, 2013 11:40:47 AM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["ajp-bio-8009"]
Dec 13, 2013 11:40:47 AM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 733 ms
Dec 13, 2013 11:40:47 AM org.apache.catalina.core.StandardService startInternal
INFO: Starting service Catalina
Dec 13, 2013 11:40:47 AM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet Engine: Apache Tomcat/7.0.42
log4j:WARN No appenders could be found for logger (com.opensymphony.xwork2.util.fs.DefaultFileManagerFactory).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
Dec 13, 2013 11:40:48 AM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-bio-8080"]
Dec 13, 2013 11:40:48 AM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-bio-8009"]
Dec 13, 2013 11:40:48 AM org.apache.catalina.startup.Catalina start
INFO: Server startup in 1711 ms

There should be something like "from execute" in the console because of this System.out.println("from execute"); but it does not go in the class
I don't know how to debug it anymore.

A: You have WEB-INF/class should be renamed to WEB-INF/classes. In the the package explorer right click on the folder name and choose rename or refactor/rename. If this doesn't work open a resource perspective and rename the folder name. After that clean and rebuild and redeploy the project.

A: what i did was to delete the saved jar in WEB-INF/lib i think my problems was because i had double jar one from the tutorial way and the other was because i had paste the same jar in the said folder.jar redundant my have cause my problem so if you have done the same delete the saved jar and rerun the program it will work for sure


text:
Q: Tinting Image Processing on Android I tried to follow Image Processing – Tint Color (Yet Another) Tutorial, but I don't understand some of the code. I know only one thing that the degree effects number of tone colors. Could you please explain it to me?
The following is the code that I don't understand:
                int index = y * width + x;
                int r = ( pix[index] >> 16 ) & 0xff;
                int g = ( pix[index] >> 8 ) & 0xff;
                int b = pix[index] & 0xff;
                RY = ( 70 * r - 59 * g - 11 * b ) / 100;
                GY = (-30 * r + 41 * g - 11 * b ) / 100;
                BY = (-30 * r - 59 * g + 89 * b ) / 100;
                Y  = ( 30 * r + 59 * g + 11 * b ) / 100;
                RYY = ( S * BY + C * RY ) / 256;
                BYY = ( C * BY - S * RY ) / 256;
                GYY = (-51 * RYY - 19 * BYY ) / 100;

A: Essentially, this bit of code is changing the color of each of the RBG channels in the image. I'll break it down line by line.
            int r = ( pix[index] >> 16 ) & 0xff;
            int g = ( pix[index] >> 8 ) & 0xff;
            int b = pix[index] & 0xff;

The bit of code above just gets the native red, blue, and green values.
            RY = ( 70 * r - 59 * g - 11 * b ) / 100;
            GY = (-30 * r + 41 * g - 11 * b ) / 100;
            BY = (-30 * r - 59 * g + 89 * b ) / 100;

These are fed back in later, but note that RY will be mostly red, BY mostly blue, and GY will be a blend of green and red. One key feature is that all 3 multipliers add up to 0, thus preserving the neutrality of the correction (The image won't get brighter). GY actually doesn't matter, as it is not used anywhere else in the code.
            Y  = ( 30 * r + 59 * g + 11 * b ) / 100;
            RYY = ( S * BY + C * RY ) / 256;
            BYY = ( C * BY - S * RY ) / 256;
            GYY = (-51 * RYY - 19 * BYY ) / 100;

Again, just applying a formula to get the desired tinting effects. S and C are Sin and Cos values for an angle passed into the function as it is called. The tint is a function of the angle passed. At angle 0, the image will be the closest to normal colors, as the angle is changed, it will tend to change red to blue, blue to red, and green will be some combination of the two, mostly depended on the red.


text:
Q: Making image thumbnail smaller I am having image sharing application where users upload images and I take thumbnails of these images...how ever , everything is working fine but sometimes the image thumbnail(600 * 800) size is almost 1 mb which is very huge is there anyway to modify the image resolution or something to make the size like..100 kb or something . this is my code .
    Bitmap bmp = new Bitmap(Width, Height);
            System.Drawing.Graphics gr = System.Drawing.Graphics.FromImage(bmp);
            gr.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            gr.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
            gr.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
            gr.PixelOffsetMode = PixelOffsetMode.HighQuality;

            System.Drawing.Rectangle rectDestination = new System.Drawing.Rectangle(0, 0, Width, Height);
            System.Drawing.Size rs = new System.Drawing.Size();
            rs.Height = Height;
            rs.Width = Width;
            gr.DrawImage(originalImage, new Rectangle(new Point(0, 0), rs), 0, 0,     originalImage.Width, originalImage.Height, GraphicsUnit.Pixel);
            string thumbnailPath = string.Concat(pathToSaveIn, thumbnailName);
            bmp.Save(thumbnailPath);
            gr.Dispose();

A: The image resizing code looks OK (at first glance). However, you're saving the image in bitmap format, which is lossless -- hence the large size of the file.
You probably want to use JPEG instead for a thumbnail: for photographs, etc., this gives good compression.
This may help:
    public void SaveImage(Bitmap image, string filename)
    {
        long quality = 80L;  // adjust as appropriate

        var qualityEncoder = Encoder.Quality;

        using (var encoderParameter = new EncoderParameter(qualityEncoder, quality))
        using (var encoderParams = new EncoderParameters(1))
        {
            encoderParams.Param[0] = encoderParameter;
            var jpegEncoder = GetEncoder(ImageFormat.Jpeg);
            image.Save(filename, jpegEncoder, encoderParams);
        }
    }

    private static ImageCodecInfo GetEncoder(ImageFormat format)
    {
        ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders();

        return codecs
            .Where(codec => codec.FormatID == format.Guid)
            .FirstOrDefault();
    }

A: This looks like .NET.  Scott Hanselman had a good blog post on this.  Essentially a review of a package on NuGet that helps with this.
http://www.hanselman.com/blog/NuGetPackageOfWeek11ImageResizerEnablesCleanClearImageResizingInASPNET.aspx

A: Try System.Drawing.Image.GetThumbnailImage. I haven't used it myself, but looks like it might work.


text:
Q: MySQL: Can the table comment length be increased? I read the MySQL comment length questions on StackOverflow here:

*

*Table comment length in MySQL

*How to increase mysql table comments length?
The first link suggests that it can be done and the second suggests it cannot.
I don't know why there is this limitation as the comments are very useful. Imagine if there was a limit of 60 characters for your programs.
I wrote about this on my site and have some snapshots to the phpMyAdmin and Dbforge MySQL IDEs: http://mysql.tutorialref.com/mysql-table-comment-length-limit.html
Is there a way to change this in phpMyAdmin or perhaps even on the CLI?
There is a bug commit report from MySQL on this particular problem (follow the first StackOverflow link). It seems to state that the length problem is fixed.
I have MySQL 5.1.42.

A: No it cannot in the question you link to there is a patch for version 6.0 that increases it to 2048 chars.
But that's only for 6.0 and only if you compile your own source.


text:
Q: Spring exception-type-router in a chain I have the following chain in Spring:
<int:chain input-channel="errorRecoveryChannel">
  <int:transformer ref="exceptionLogger" method="logError"/>
  <int:transformer ref="errorHandlerTransformer" method="handleError"/>
  <int:header-value-router header-name="onErrorDestinationQueueChannel"
                           default-output-channel="reprocessOutChannel">
     <int:mapping value="dlqMessageOut" channel="dlqMessageOut"/>
  </int:header-value-router>
</int:chain>

And I have a class that throws a DemoClientNotAssociatedWithLiveClientDropMessageError custom exception.
Will something like this work?
<int:chain input-channel="errorRecoveryChannel">
  <int:transformer ref="exceptionLogger" method="logError"/>
  <int:exception-type-router>
     <int:mapping exception-type="com.iggroup.mis.gateway.errorhandling.DemoClientNotAssociatedWithLiveClientDropMessageError"
             channel="nullChannel"/>
  </int:exception-type-router>
  <int:transformer ref="errorHandlerTransformer" method="handleError"/>
  <int:header-value-router header-name="onErrorDestinationQueueChannel"
                           default-output-channel="reprocessOutChannel">
     <int:mapping value="dlqMessageOut" channel="dlqMessageOut"/>
  </int:header-value-router>
</int:chain>

Or do I have to add the exception-type-router outside the chain?

A: So I have found the answer by myself. Turns out the exception-type-router needs to be out of the chain. Here's the solution:
<int:exception-type-router input-channel="errorChannel" default-output-channel="errorRecoveryChannel">
  <int:mapping exception-type="com.iggroup.mis.gateway.errorhandling.DemoClientNotAssociatedWithLiveClientDropMessageError"
               channel="nullChannel"/>
</int:exception-type-router>

<int:chain input-channel="errorRecoveryChannel">
  <int:transformer ref="exceptionLogger" method="logError"/>
  <int:transformer ref="errorHandlerTransformer" method="handleError"/>
  <int:header-value-router header-name="onErrorDestinationQueueChannel"
                           default-output-channel="reprocessOutChannel">
     <int:mapping value="dlqMessageOut" channel="dlqMessageOut"/>
  </int:header-value-router>
</int:chain>

The way it was before, I got the following exception:
java.lang.IllegalStateException: Failed to load ApplicationContext
at org.springframework.test.context.CacheAwareContextLoaderDelegate.loadContext(CacheAwareContextLoaderDelegate.java:99)
at org.springframework.test.context.DefaultTestContext.getApplicationContext(DefaultTestContext.java:101)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:109)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:75)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:331)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:213)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:290)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:292)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:233)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:87)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:176)
at org.junit.runner.JUnitCore.run(JUnitCore.java:157)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:78)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:212)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:68)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.integration.handler.MessageHandlerChain#4': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: All handlers except for the last one in the chain must implement the MessageProducer interface.
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1554)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:539)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:706)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:762)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:125)
at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:60)
at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.delegateLoading(AbstractDelegatingSmartContextLoader.java:102)
at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.loadContext(AbstractDelegatingSmartContextLoader.java:248)
at org.springframework.test.context.CacheAwareContextLoaderDelegate.loadContextInternal(CacheAwareContextLoaderDelegate.java:64)
at org.springframework.test.context.CacheAwareContextLoaderDelegate.loadContext(CacheAwareContextLoaderDelegate.java:91)
... 28 more

Caused by: java.lang.IllegalArgumentException: All handlers except for the last one in the chain must implement the MessageProducer interface.
at org.springframework.util.Assert.isTrue(Assert.java:65)
at org.springframework.integration.handler.MessageHandlerChain.configureChain(MessageHandlerChain.java:140)
at org.springframework.integration.handler.MessageHandlerChain.onInit(MessageHandlerChain.java:116)
at org.springframework.integration.context.IntegrationObjectSupport.afterPropertiesSet(IntegrationObjectSupport.java:133)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1613)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1550)
... 43 more


text:
Q: Jquery ajax call going to php script and not reloading page I have a simple page which allows users to add language ids to items. The page loads up a list of records, by doing an ajax call. All the records are loaded into a div as a list.
Each list item is a form, so when the user inputs the lang id, they press update and the ajax call goes off, updates the database and reloads the list with the records, minus the one just updated.
The jquery call, works on page load, but if you submit a form item, it goes to the php script instead of reloading within the page you submitted on.
Any ideas why the initial call loads 'in page' but the form submit does not. Also is using a form per record a good idea or is there a better way to do it with jquery.
The original php script (sort_language.php) which does the ajax call

Records by title

    Waiting for records to load....

Here is the php script which created the list and updates the db.
//get lang post variables if they exist
$eng_id = $_POST['eng'];
$cym_id = $_POST['cym'];
//debug - check post values are correct visually
echo 'eng' . $eng_id . ' cym ' . $cym_id;

function create_list() {
//generate html list
$html .='
';

    //grab records from DB which have not been updated with language value to display
    if (!$query = mysql_query("SELECT `id`, `title-245` FROM `records` WHERE `catalog_lang-040` = 'eng' ORDER BY `title-245`")) {
        echo mysql_error();
    }
    //generate each item in list as a form
    //set form id to rec
    while($row = mysql_fetch_array($query))
    {
        $html .= '
<form action="ajax/lang_api.php" method="post" id="rec">' . $row['title-245'] . ' <input type="text" name="cym" size="3" /><input type="hidden" name="eng" id="eng" value="' . $row['id'] . '" /> <input type="submit" value="submit" /></form>

        ';
    }

$html .= '
';
//return the html to be used
return $html;
}

//if eng and cym ids are submitted then update DB, otherwise just return the html required.
//check value is set using isset
if (isset($eng_id) && isset($cym_id)) {

if (!is_numeric($eng_id)) { $rehtml= 'Invalid English ID'; }
if (!is_numeric($cym_id)) { $rehtml= 'Invalid Welsh ID'; }

//sql to go here to update db ith language value

//and then get new list to output.
  echo create_list();
//post undefined so just return list (for first page load/refresh)
}else{
// output the html
  echo create_list();
}

Probably missing something obvious, but first time playing with jquery/js.
And here is the HTML list that is created by lang_api.php, this loads into the records div replacing "waiting for records to load" in sort_language.php
eng417 cym 21

<form action="ajax/lang_api.php" method="post" id="rec">18th - 19th century ballads collection , 18th - 19th century,  <input type="text" name="cym" size="3" /><input type="hidden" name="eng" id="eng" value="417" /> <input type="submit" value="submit" /></form>

<form action="ajax/lang_api.php" method="post" id="rec">1st The Queen's Dragoon Guards Collections , 1685 -,  <input type="text" name="cym" size="3" /><input type="hidden" name="eng" id="eng" value="1001" /> <input type="submit" value="submit" /></form>

<form action="ajax/lang_api.php" method="post" id="rec">Aberconway Library , 20th century -,  <input type="text" name="cym" size="3" /><input type="hidden" name="eng" id="eng" value="101" /> <input type="submit" value="submit" /></form>

<form action="ajax/lang_api.php" method="post" id="rec">Aberfan Disaster Archive , Mainly 1966 -,  <input type="text" name="cym" size="3" /><input type="hidden" name="eng" id="eng" value="303" /> <input type="submit" value="submit" /></form>

<form action="ajax/lang_api.php" method="post" id="rec">Abergavenny Local History Collection , Prehistory to the present day,  <input type="text" name="cym" size="3" /><input type="hidden" name="eng" id="eng" value="1030" /> <input type="submit" value="submit" /></form>

<form action="ajax/lang_api.php" method="post" id="rec">Alister Hardy Religious Experience Archive , 1924 -,  <input type="text" name="cym" size="3" /><input type="hidden" name="eng" id="eng" value="1042" /> <input type="submit" value="submit" /></form>

<form action="ajax/lang_api.php" method="post" id="rec">Almanacs Collection , 1700 - 1850,  <input type="text" name="cym" size="3" /><input type="hidden" name="eng" id="eng" value="740" /> <input type="submit" value="submit" /></form>

<form action="ajax/lang_api.php" method="post" id="rec">Ammanford Local Studies Collection , 1880s -,  <input type="text" name="cym" size="3" /><input type="hidden" name="eng" id="eng" value="939" /> <input type="submit" value="submit" /></form>

<form action="ajax/lang_api.php" method="post" id="rec">Anderson Collection , 17th - 20th century,  <input type="text" name="cym" size="3" /><input type="hidden" name="eng" id="eng" value="407" /> <input type="submit" value="submit" /></form>

A: "Any ideas why the initial call loads 'in page' but the form submit does not."
Because your code tells exactly to do so. In your server side code, you generate a bunch of form elements that are regular html forms, not bound to jQuery or ajax in any way. So when you press on any submit button, it will do what's expected from an html form: do a post, and replace your current page with the server's response.
"Also is using a form per record a good idea or is there a better way to do it with jquery."
It could work, if you bind all form elements' submit to an ajax call - but I would not call this a very elegant solution. I'd rather use a single jquery ajax post bound to all buttons having a certain class, like
$("button.recordsubmit").live("click", function() { // ajax submit code });

and generate these buttons on the server side instead of forms. Also, you should consider not reloading the whole records div, but target the individual record divs, so only the changed content would be replaced.

A: You have a couple of problems here:

*

*I would not recommend the approach you took of creating a form for each
. since you can latch to any event on any element you can just put a simple button and bind a click event to it.

*The reason you are failing is because jquery.submit() is a helper method (as well as click,hover etc.) and those methods only bind to elements that exist on the page when it loads. You on the other hand, add the elements dynamically, so what you need to use is live or on:
$('button').on('click',function(){//do your stuff});

look at jquery.on() and jquery.live()
EDIT:
First time you load the page, there is no need for an ajax call, just create it in php.
When the user clicks a button you can use the jquery.load() method to replace the entire list, for that you need to wrap the list in a div:

....

and then using jquery:
$('button').on('click',function()
    $('#listWrapper').load('ajax/lang_api.php',data_json);
});

This will automatically call the php script and replace the lsit inside the div with the list returned from php script.


text:
Q: Show/Hide checkbox based on user choice from option list salesforce I have a form to add new user, inside that form I have a field where user pick from two values in option list and based on his choice I want to hide/show checkbox field.
So its goes like this:
     <template>
    <lightning-record-edit-form object-api-name="Student__c">
        <lightning-messages>
        </lightning-messages>
        <lightning-input-field field-name="Name" onchange={handleFieldChange}>
        </lightning-input-field>
        <lightning-input-field field-name="First_name__c" onchange={handleFieldChange}>
        </lightning-input-field>
        <lightning-input-field field-name="Last_name__c" onchange={handleFieldChange}>
        </lightning-input-field>
        <lightning-input-field field-name="Email__c" onchange={handleFieldChange}>
        </lightning-input-field>
        <lightning-input-field field-name="Phone__c" onchange={handleFieldChange}>
        </lightning-input-field>
        <lightning-input-field field-name="Address__c" onchange={handleFieldChange}>
        </lightning-input-field>
        <lightning-input-field field-name="EMSO__c" onchange={handleFieldChange}>
        </lightning-input-field>
        <lightning-input-field field-name="TypeOfStudy__c" onchange={handleFieldChange}>
        </lightning-input-field>
        <template if:true={showBonus}>
            <lightning-input-field field-name="Payer__c" onchange={handleFieldChange}>
            </lightning-input-field>
        </template>
<lightning-button class="slds-m-top_small"
                          variant="brand"
                          name="save"
                          label="Save from createRecord"
                          onclick={saveForm}>
        </lightning-button>
    </lightning-record-edit-form>
</template>

So TypeOfStudy__c is a option list, inside that list I have two values: Full-time - Part-time.
So if user select part-time the checkbox Payer__c should be displayed, otherwise is hidden.
I know In standard HTML I can assign for each option from the list value and then pass that value to the JS and based on value show/hide checkbox, but I got values from salesforce here, I'm not setting them manually, How I can access to user choice?
JS:
    import { LightningElement, wire, api, track } from 'lwc';
import { createRecord } from 'lightning/uiRecordApi';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import CONTACT_OBJECT from '@salesforce/schema/Student__c';

export default class Poc extends LightningElement {
    @track contactRecord = {};

    handleFieldChange(e) {
        this.contactRecord[e.currentTarget.fieldName] = e.target.value;
    }

    get showBonus() {
        return this.contactRecord != null && this.contactRecord.TypeOfStudy__c=== 'Part-Time';
    }

    saveForm() {
        // if(this.validated())
        console.log('Contact for save => ', JSON.stringify(this.contactRecord));
        createRecord({ apiName: CONTACT_OBJECT.objectApiName, fields: this.contactRecord })
            .then(contact => {
                this.dispatchEvent(
                    new ShowToastEvent({
                        title: 'Success',
                        message: 'Contact created from saveForm => ' + contact.id,
                        variant: 'success'
                    })
                );
            })
            .catch((error) => {
                this.dispatchEvent(
                    new ShowToastEvent({
                        title: 'Error creating record',
                        message: error.body.message,
                        variant: 'error'
                    })
                );
            });
    }

}

And when I choose Part-Time checkbox doesnt appear

A: You can add <template if:true={someExpression}> around your <lightning-input-field field-name="Bonus__c" to show/hide it conditionally.
Unlike Aura and Visualforce - this expression will have to be "simple". No math or complex logic in it. It'll have to be a plain class variable (like your this.contactRecord) or a getter
JS
get showBonus() {
    return this.contactRecord != null && this.contactRecord.TypeOfUser__c === 'Part-Time';
}

HTML
<template if:true={showBonus}>
    <lightning-input-field field-name="Bonus__c" onchange={handleFieldChange}>
    </lightning-input-field>
</template>

(I used "===" so it has to be exact match, case sensitive etc)
P.S. Remember that this is just an UI thing, crafty user can tweak it. Do a server-side check too like a validation rule


text:
Q: Zend Framework 2 : let's do it or no? This is the kind of question which occur when you check Zend framework homepage at the moment : First beta release is available since mid october '11.
As a fervent Zend framework user, i'm wondering when i should start upgrading, they also warn us that next ZF release 1.12 will help us in the process ot upgrading, but as i want to start a big project, not sure what's the safest path, any thought ?

A: If you have many projects that use ZF and don't mind deploying two versions, I'd recommend upgrading a smaller or less critical project to it. If you only have the one big new project that you'll be working on, there's more risk. You'll have to weigh the benefits against that risk.
Consider how soon this new project needs to go live. If you will be working on it in development for months, most likely all the kinks will be worked out of ZF 2 in that time. By going with the newer version which will obviously be released eventually, you're saving yourself the hassle of upgrading later. The code will be cleaner by starting fresh on ZF 2, and it most likely has many new features to shorten your development time. Of course, you'll have to spend some time learning them which offsets the gains slightly.
Finally, as Poelinca mentioned, you'll be helping out the community by testing it in a real world application. This is, after all, the point of releasing beta software. Given that even "release" software has bugs and goes through revisions, I think you're pretty safe jumping to ZF 2 sooner rather than later.

A: The source is freely available so the risk is proportional to your knowledge of ZF2 and your ability to fix issues that arise. For some, ZF2 is good to go today. Others need to wait until ZF2 for Dummies 2nd Edition is published.

A: I'd stay with ZF1 for running projects and wait for some latter beta to switch the smaller ones. ZF2 is far from big-project-production-safe version. And for bigger things I would wait at least for some RC.
You can use ZF2B1 for smaller projects with shorter lifespan. Or for things like your personal webpage. Even from Beta1 there are for example some serious changes to how the modules work to be in Beta2. It would take a great amount of time and effort to keep a big application up to date with current development status.


text:
Q: Multiple controllers for same resource based on user's Role I'm having trouble designing this role (or permission) based application, when it comes to figuring out how to handle actions that differ per use role.
For instance, our controller is App\ResourceController, and we will be editing the resource. There are 2 roles: admin and user. The admin is allowed to edit every field of the resource, while the user is restricted to some of them.
I'm struggling figuring out the best approach between implementing a single controller that will handle both cases, or routing the request to a different controller for the same resource (like App\Admin\ResourceController, App\User\ResourceController).
The issue with the single controller approach, is that it isn't just showing a different form (with restricted fields) based on role, but also validating different fields and more. The controller's body would pretty much look like a big if-else statement.
Is multiple controller the correct approach, or is there a different one using permissions instead of roles?

A: In general your choice should be for maintainability and simplicity. In the case you describe it seems that the added complexity from trying to combine the controllers will not be worth the added complexity in the long run.
That being said, making the practical choice between the approaches described depends on the number of elements that differ for user and admin. If that number is small, then the added complexity may be worthwhile.
If you are using an object-oriented environment a third option might be to have the App\Admin\ResourceController inherit from App\User\ResourceController.

A: This will largely depend on the MVC framework you are using. The ASP.NET MVC framework in .NET, for example, has a permissions system built in (called roles). You could use one controller with multiple methods:
public class ResourceController : Controller
{
    [Authorize(Roles = "User")]
    public ActionResult CreateAsUser()
    {
        // ...
    }

    [Authorize(Roles = "User")]
    [HttpPost]
    public ActionResult CreateAsUser(ResourceModel model)
    {
        // ...
    }

    [Authorize(Roles = "Admin")]
    public ActionResult CreateAsAdmin()
    {
        // ...
    }

    [Authorize(Roles = "Admin")]
    [HttpPost]
    public ActionResult CreateAsAdmin(ResourceModel model)
    {
        // ...
    }
}

Most fully featured MVC frameworks will have some kind of role based permissions system built in that you can use. Really, your next step is identifying the MVC framework you are using (or decide which one to use now that you know it needs role based permissions) and do some research on how to implement those permissions.


text:
Q: Meteor Cordova App: how to run different code on iOS or Android We need different code to run on iOS or Android.
One way to do this would be to have different code in the package run at the outset (before all of the code runs) in the package files.
Meteor.isCordova allows the determination of whether on Cordova or browser.
How is it possible to determine, within Cordova, whether on iOS or Android.
Here is some code that doesn't work because Platform.isIOS() is not (yet) defined at this stage:
if (Meteor.isCordova && Platform.isIOS()) {
    Meteor.startup(function () {
        console.log('Using plugin for iOS');
    });
} else {
        console.log('Using plugin for Android');
}

This is not the same question asked here:
PhoneGap - Detect device type in phonegap
because the point is to detect this earlier in the process of a Meteor build (and also not using PhoneGap itself).  The answers provided there do not work in the current context.

A: Within Cordova you can use the Cordova Device Plugin to retrieve information about the device you are running on.
Once installed, you would use
device.platform

to determine which platform you are running on.
Example:
if (device.platform === 'Android') {
    // Android only code
}

if (device.platform === 'iOS') {
    // iOS only code
}

A: Template.registerHelper('ios',function(){
  return ( navigator.userAgent.match(/(iPad|iPhone|iPod)/g) ? true : false );
});
And another for Android:

Template.registerHelper('android',function(){
  return navigator.userAgent.toLowerCase().indexOf("android") > -1;
});

THEN
Blaze._globalHelpers.ios()
Blaze._globalHelpers.android()

A: In the end, the best answer for this situation for us was to create two separate server instances of the app: one for ios and android.  We then pointed the cordova version of the app on each type of device to the appropriate server instance and url (ios.server.com, android.server.com).  They both pointed to the same Mongo database so all of the user information etc ends up in the same place.
This is not the most elegant solution, but it worked.  Working through making the packages compatible with both platforms would ultimately probably be a better outcome, and we may do that, but this allowed us to get up and running.
This has the small side benefit of separating the load to the two instances and thus making it easy to handle the two situations separately and control and monitor their load separately through different server instances, etc.

A: Create merges folder in main directory of the project(not in www) and inside it create iphone/android folders. Then add files that are platform depend and cordova will copy it when build your app.
If you have the same files in www directory you shoud create the new files with the same path for example merges/android/js/controllers/myController.js will replace the file for specific folder into www/js/controllers/myController.js
Note: If you want to replace only one function for example in the all file this can be done but is more tricky. To do this you should use Cordova Hooks. Read about them and create a script that will copy the specific parts of code into the files you want...


text:
Q: How to align text left in centered object I've got the following code:

A text

The text-align:left; isn't working. I've also tried margin: 0px auto; and that also didn't work.
Please help me...

A: Apply display: block on span

.body span{margin-left:5px;text-align:left; display: block;}

A text

A: Please try following code:

A text

However  tag is deprecated in HTML5 bcz it is related with alignment of content for which its better to use CSS..
A better approach is as follows:

    A text

.body {
    text-align: center;
}
.body span {
    text-align: left;
    margin-left: 5px;
    display: block;
}

A: I would not use a SPAN in this case, I would use a DIV or a P. A SPAN element is not for showing lots of content and you can not put other block elements inside the SPAN otherwise it won't validate. I only say that because I misused the SPAN element for years by myself ;).


text:
Q: Basin of attraction Let $$g(x)=\frac{2}{5}x^3-\frac{7}{5}x$$. The fixed points are 0 and $$\sqrt6$$. There is a period-2 orbit of 1 and -1. The critical points are $$\sqrt\frac{7}{6}$$
a. calculate the Schwarzian derivative
$$sg(x)=\frac{-144x^2-84}{(6x^2-7)^2}$$<0 for all x
b.The point$$x0=\sqrt{7/6}$$ belongs to the basin of attraction of which orbit? What about $$-\sqrt{7/6}$$?
I have no idea what to do for part b...


text:
Q: How to properly pass struct pointer from C# to C DLL I need to export function from C DLL. Here is example that I have written
typedef struct tag_struct {
  unsigned char first;
  unsigned char second;
} st_struct;

__declspec(dllexport) unsigned char Func( st_struct *ptr )
{
    return ptr->first + ptr->second;
}

Here is C# code that I'm using to import described above function.
using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace ImportTest
{
    [Serializable]
    [StructLayout(LayoutKind.Sequential)]
    public class st_struct
    {
        public byte first;
        public byte second;
    }

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            st_struct x = new st_struct();

            x.first = 1;
            x.second = 2;

            byte result = Func(ref x);
        }

        [DllImport("MarshalTest.dll")]
        protected static extern byte Func(ref st_struct inputs);
    }
}

My problem is that return value of Func is not 3 as it should be (1 + 2).
I am using debugger to see values inside DLL - they are different (not 1 and 2 that I provided).
Function returns proper value whan I change C# code like that:
public Form1()
{
    InitializeComponent();

    st_struct x = new st_struct();

    x.first = 1;
    x.second = 2;

    byte result = Func(x);
}

[DllImport("MarshalTest.dll")]
protected static extern byte Func(st_struct inputs);

Problem disappears when I remove ref. But I don't understand why.
Could you please explain that?

A: You might be thinking that the ref keyword is required in order to passing parameter by reference. But since st_struct is defined as a reference type (class is reference type), so the parameter is passed by reference, not by value. You don't need the ref keyword.
If st_struct were defined as struct, you may find it work when you use the ref keyword.

A: As @kennyzx mentions, since your st_struct is a class, it is already a reference type and will be passed as a pointer. I suspect throwing a ref onto that will give you a double pointer, which doesn't make much sense when mixing managed and unmanaged code. The marshaller can possibly handle that and create a new object for you if the pointer changes, but it seems like a sketchy thing to do.
So, when passing the class without ref, it works as expected (the C code gets a pointer). If you change it to a struct, passing it without ref should pass it on the stack and passing it with ref will pass it as a pointer.
Using struct seems like the obvious choice in your case, as it can be passed directly (the CLR just needs to pin it and pass a pointer). Using class I suspect will involve more marshalling.


text:
Q: Reformat wide Excel table to more SQL-friendly structure I have a very wide Excel sheet, from Column A - DIE (about 2500 columns wide), of survey data. Each column is a question, and each row is a response. I'm trying to upload the data to SQL and convert it to a more SQL-friendly format using the UNPIVOT function, but I can't even get it loaded into SQL because it exceeds the 1024-column limit.
Basically, I have an Excel sheet that looks like this:

But I want to convert it to look like this:

What options do I have to make this change, either in Excel (prior to upload) or SQL (while circumventing the 1024 column limit)?

A: I have had to do this quite a bit.  My solution was to write a Python script that would un-crosstab a CSV file (typically exported from Excel), creating another CSV file.  The Python code is here: https://pypi.python.org/pypi/un-xtab/ and the documentation is here: http://pythonhosted.org/un-xtab/.  I've never run it on a file with 2500 columns, but don't know why it wouldn't work.

A: R has a very specific function call in one of it's libraries. You can also connect, read, and write data with R into a database. Would suggest downloading R and Rstudio.
Here is a working script to get you started that does what you need:
Sample data:
df <- data.frame(id = c(1,2,3), question_1 = c(1,0,1), question_2 = c(2,0,2))
df

Input table:
  id question_1 question_2
1  1          1          2
2  2          0          0
3  3          1          2

Code to transpose the data:
df2 <- gather(df, key = id, value = values)
df2

Output:
   id        id values
1  1 question_1      1
2  2 question_1      0
3  3 question_1      1
4  1 question_2      2
5  2 question_2      0
6  3 question_2      2

Some helper functions for you to import and export the csv data:
# Install and load the necessary libraries
install.packages(c('tidyr','readr'))
library(tidyr)
library(readr)

# to read a csv file
df <- read_csv('[some directory][some filename].csv')

# To output the csv file
write.csv(df2, '[some directory]data.csv', row.names = FALSE)

A: Thanks for all the help. I ended up using Python due to limitations in both SQL (over 1024 columns wide) and Excel (well over 1 million rows in the output). I borrowed the concepts from rd_nielson's code, but that was a bit more complicated than I needed. In case it's helpful to anyone else, this is the code I used. It outputs a csv file with 3 columns and 14 million rows that I can upload to SQL.
import csv

with open('Responses.csv') as f:
    reader = csv.reader(f)
    headers = next(reader)  # capture current field headers
    newHeaders = ['ResponseID','Question','Response']  # establish new header names
    with open('PythonOut.csv','w') as outputfile:
        writer=csv.writer(outputfile, dialect='excel', lineterminator='\n')
        writer.writerow(newHeaders)  # write new headers to output

        QuestionHeaders = headers[1:len(headers)]  # Slice the question headers from original header list
        for row in reader:
            questionCount = 0  # start counter to loop through each question (column) for every response (row)
            while questionCount <= len(QuestionHeaders) - 1:
                newRow = [row[0], QuestionHeaders[questionCount], row[questionCount + 1]]
                writer.writerow(newRow)
                questionCount += 1


text:
Q: Create a Master DE of Subscribers in a Child BU Hangup: We have four separate "master DE's" being imported from IT into our marketing child business unit, each segmenting customers a different way. There is overlap between the four.
Goal: Create one unified Master DE for the marketing child BU that has subscriber status and engagement, which can then be joined with other DE's as necessary. I'm able to make one that pulls in the entire enterprise list, but that mixes HR with marketing and is not ideal.
There was a previous question with the same goal, but it was never fully answered.
Retrieve All subscribers related to a child BU only
Update: Would it be easier to add the engagement data on each of the four individual DE's directly instead?

A: Sounds to me like you need an automation in each business unit (with staggered schedules) to update a shared data extension.
In an Enterprise 2.0 account, subscribers are shared across all business units.  The platform only keeps track of unsubscribes per business unit.  So the concept of business unit membership is convoluted, because it's technically "all" unless they've opted out at the business unit level.
For those subscribers who've been sent an email, you can determine BU-level subscriber status using an automation like this in the parent BU.

*

*Assign all subscribers to all business units

*Mark unsubscribes per business unit

I'd suggest maintaining a centralized BU status DE in shared and joining your Master DEs to it in order to retrieve the BU status.
The "and engagement" part is generally very heavy lift, since you'll have to aggregate it by subscriber using a series of queries in each BU.


text:
Q: ifstream buffer limit/overflow? C++ (_cnt?) For some odd reason, when my file gets too big in bytes, this error occurs where it stops reading in the correct data. It's as if the buffer stops taking in data at a certain point.
I simplified my code as much as possible to determine the problem, but I've come to realization that it isn't my code, but perhaps a buffer somewhere?

If my file is 14,034 bytes and I run this simple code:
ifstream inFile("text.txt"); //File is 14,034 bytes
char test;

while(inFile >> test) //This will stop looping at about the 768 - 769 loop
    cout << test;

If I force it to go further with a for loop, the results are the same:
ifstream inFile("text.txt"); //File is 14,034 bytes
char test;

for(int count = 0; count < 14034; ++count) //The loop will continue until the
    test = inFile.get();                   //end, but for whatever reason,
    cout << test;                          //inFile stops at 768 - 769 again

NOW: if I use the same code, but for a smaller file(say 900 bytes), I don't seem to have
that problem.
EXACT SAME CODE, JUST DIFFERENT FILE SIZE
ifstream inFile("text.txt"); //File is 900 bytes
char test;

while(inFile >> test) //This loop will continue to the 900th loop without
    cout << test;     //problems.

EXACT SAME CODE, JUST DIFFERENT FILE SIZE
ifstream inFile("text.txt"); //File is 900 bytes
char test;

for(int count = 0; count < 900; ++count) //The loop will continue until the
    test = inFile.get();                 //end (900) without problems.
    cout << test;

I've searched for my problem all over Google, and haven't been able to find a solution. The only other thread I found with a similar problem is this one:
fopen - can't write more than 16K?
But even then, no one really understood what they were talking about - so the question was technically unanswered.

A: It looks like you want to read the file in binary mode, which you can do as follows:
std::ifstream file("test.txt", std::ios::binary);
char byte;
while(file.read(&byte, 1)){
    // Do something with byte
}


text:
Q: how to give timestamp in range query Elasticsearch In Elastic-search range query , timestamp is in this 2019-08-28T08:57:04.749Z formate, when execute the following query it throws a error  "Unrecognized chars at the end of [2019-08-28T08:57:04.749Z- 1h]. how  can we minus 1 hr in lte value?
  {
 "query": {
 "range" : {
    "@timestamp" : {
        "gte": "2015-03-20T01:21:00.01Z",
        "lte": "2015-03-20T01:12:00.04Z-1h"

      }
   }
 }

A: The right way to do it is by adding a double pipe, like this:
{
 "query": {
 "range" : {
    "@timestamp" : {
        "gte": "2015-03-20T01:21:00.01Z",
        "lte": "2015-03-20T01:12:00.04Z||-1h"

      }
   }
 }

However, you should note that your query won't return anything, because the to date is earlier than the from date.


text:
Q: Java FX : Change the color of one unique letter in Label Everything is in the title, I need to highlight one letter in a label (the letter highlighted is not everytime the same)
it is like in old games when you enter your name with up/down arrows, the letter you are changing is highlighted.
Is there anyway to do this ?
I could change to something else if label doesn't fit my need, but I have no clue on how to do this.
I read about CSS in Javafx but I don't get everything yet.

A: In Java 8 you can use a TextFlow, or use the RichTextFX third-party library.

A: I can't say for sure that there isn't some way to accomplish this with CSS trickery, but I'm not aware of any. If I were you, I would develop my own custom Node that either extends or composes HBox() (or class with similar left to right flow) and takes care of managing multiple labels to support your use case. Such a class could possibly represent each character with its own label instance, or perhaps just by using left, highlight and right labels, where left or right are empty when the left-most or right-most character are labeled, respectively. Your class could then define properties for the font, size, color etc, and a separate color to be applied to the 'highlighted' label.


text:
Q: Get the identifying header from a table with rowspans and column spans Assuming I have a table with column and row spans I am looking for a way to find the header that uniquely identifies a cell.
For this table:

table {
  border-collapse: collapse;
 }

 table, td, th {
   border: 1px solid gray;
 }

      col1
      col2
      col3

      col4

      col5
      col7

      value
      value1
      value2
      value3

https://jsfiddle.net/j3kqrpt0/
I would like to get the following header

col5
col5
col3
col7

A: Basically, all you have to do is -

*

*Inside table, create thead element, which stands for table head

*Create new table row - tr, which is going to be filled with column headers that you need

*And lastly, add those th (table header) elements that you need.

Then, in the body of the table you go the same way, just with different elements:

*

*Create tbody element

*Create tr element

*Fill tr with table data - td
Here is the code snippet.

table, th, td {
  border: 1px solid;
}

   col5
   col5
   col3
   col7

   value
   value1
   value2
   value3


text:
Q: Detect JSON exist I have question about chechking file exists.
I have this piece of code.
function fileExists(url) {
  if (url) {
    var req = new XMLHttpRequest();
    req.open('GET', url, false);
    req.send();
    console.log("exists");
    return true;
  } else {
    console.log("no exists");
    return false;
  }
}

But it says me that file is exists. But it doesn't exists. In fact on my URL is 404 error XML file. Is possible somehow detect if requested URL is JSON? I need to return true only if checked file is JSON.
Thank you

A: Since this is a synchronous request, you can just try to parse the responseText you get back and if it fails to parse, you know it's  not JSON:
        var res = req.responseText;
        try {
             res = JSON.parse(res);
             console.log('json', res);
        } catch (e) {
             console.log('not json')
        }

If it were not a synchronous request, this would work:
If you look at the XMLHttpRequest docs, you'll see that in order to receive data back from an XMLHttpRequest, you need to add a callback function:
xhr.onreadystatechange = function() {//Call a function when the state changes.
    if(this.readyState == XMLHttpRequest.DONE && this.status == 200) {
        // Request finished. Do processing here.
    }
}

If you wanted to check if your request is JSON, you could do this:
xhr.onreadystatechange = function() {//Call a function when the state changes.
    if(this.readyState == XMLHttpRequest.DONE && this.status == 200) {
        var res = this.responseText;
        try {
             JSON.parse(res);
             console.log('json', res);
        } catch (e) {
             console.log('not json')
        }
    }
}


text:
Q: .SD subsetting and accessing column in the parent's data.table I would like find 10 years returns in a data.table:
DT <- data.table( year = 2000:2020, price = 0:20 )

For sequencial years above (2000, 2001, 2002, ...) I can just lag the price series by 10 and divide (remembering to add the NAs):
DT[ , list( year, return = c( rep(NA,10), price[ 11:.N ]/price[ 1:(.N-10) ] - 1 ) ) ]

The problem arises if the years are not sequencial, i.e. 2002 is missing. Lagging will missalign the years, so I'd like to explicitly match year variable by subsetting the data.table like this.
DT[ , list( year, return = .SD[ year == ( year* + 10 ) ]$price/price - 1 ) ]

In the example, year is suppose to refer to the column in .SD, while year* is referring to the year column in DT. The code above doesn't work obviously since year* is not valid. Replacing year* get("year") doesn't work. I would like to replace year* with something that would accomplish this.
Edit: So eddi comment suggests I that I can create the parent's version of year using:
DT[ , { year.parent = year; list( year, .SD[ year == (year.parent + 10) ]... ) } ]

The answer is correct, but my code example wouldn't work as I intended. Back to using merge!
Thanks!


text:
Q: Question regarding two transistors How do I start with this question?
There are 2 transistors which are more complicated and I have no clue on how to start working on it.

The transistors shown in the figure below operate in the active region and have \$ \beta=100\$ and \$V_{BE}=0.7\$ V. Determine \$I_C\$ and \$V_{CE}\$ for each transistor.

simulate this circuit – Schematic created using CircuitLab

A: The 1.43M resistor will provide you Q1 Base-Emitter current (and then Ic), with which you can determinate Q2 Base voltage. Then, Ic and Vce for each transistor is straight ahead.


text:
Q: remove-duplicates produces numbers that haven't been in the original list in NetLogo I'm creating a list out of the patch variable "geb-id" (a 7-digit integer number) with the following line:
set geb-id-list [geb-id] of patches with [geb-id >= 0 AND residents != 0]

When I look at the produced list, all looks fine. Then I'm using
set geb-id-list remove-duplicates geb-id-list

to remove the duplicates, as there are several patches with the same geb-id but I only want one geb-id per list. The list now doesn't contain any duplicates anymore, but some of the numbers have turned into random floating point numbers and I cannot trace back where these numbers suddenly came from (I checked the source data and they don't contain any floating point numbers).
For example:
The list with duplicates:
[ 133349 133349 133351 133351 133351 133360 133360 133360 133375 133375 133375 ]

The list without duplicates:
[ 133349 133351 133360 209587.61538461538 133915.6666666667 1518018.2 133375 ]

The floating point numbers that appear in the list without duplicates do not appear in the original list (even when removing the digits after the comma).
Here is the list with with the geb-id's as a csv file.

A: I think your source data does have floating point values in it.  When I use your provided CSV and run this code:
extensions [csv]

to check-floats
  let values-2d csv:from-file "geb-id-list.csv"
  let values map [ r -> item 0 r ] values-2d
  let nums filter [ v -> v != "NaN" ] values
  let floats filter [ n -> floor n != n ] nums
  show floats
end

The check-floats outputs [2079045.4999999998 2111524.956521739 862483.9473684211 361412.1111111111 1278359.6666666667 2111602.5 1564756.1249999998 2111443.4285714286 2150385.3333333335 134019.9090909091 2111560.285714286 2111643.75 133585.33333333334 134012.2 133580.00000000003 1518018.2 133915.6666666667 1452081.6666666665 133894.57142857145 ... ].
If you are loading in those geb-id's from an external source and you are sure there are no floats in that source data, then something in your NetLogo model code must be altering them to that format before you try to use remove-duplicates on them.  If you can't discover how the floats are getting in there, posting more of your model's code could help someone find the cause.


text:
Q: PHP Function with MySQL Query Table I have table which is populated with the results of a MySQL query. I need to insert an additional column into the table as a PHP function which generates a string based on the values of a field in the query (I think this is how the problem needs to be tackled). Is this possible? I've attempted setting the column as a variable and calling on that variable in the function (which isn't set as a user defined function in this code), but I must have done something wrong because the table did not populate at all.
$query1 = "SELECT `rank`.`term`,
                    `rank`.`acadplan`,
                    `rank`.`projlvl`, `rank`.`gpa`,
                    (SELECT COUNT(gpa) FROM `rank1`
                    WHERE `rank1`.`term` = '{$term}'
                        AND `rank1`.`acadplan`='{$acadplan}'
                        AND `rank1`.`projlvl`='{$projlvl}'
                        AND `rank1`.`gpa` > `rank`.`gpa`) + 1 AS 'ranking',
                FROM `rank`
                    WHERE `rank`.`term` ='{$term}'
                        AND `rank`.`acadplan`='{$acadplan}'
                        AND `rank`.`projlvl`='{$projlvl}'
                ORDER BY `rank`.`gpa` DESC";

$result = mysqli_query($query1);
    echo "
";
        echo "Term	";
        echo "Plan	";
        echo "Level	";
        echo "GPA	";
        echo "Rank	";
        echo "NEWCOL	";
    echo "<col width = '125'>";
    echo "<col width = '125'>";
    echo "<col width = '125'>";
    echo "<col width = '125'>";
    echo "<col width = '125'>";
    echo "<col width = '250'>";

$num_rows = mysqli_num_rows($result);

This is the function which needs to be executed:
if ($num_rows <=24) {
    switch ($num_rows) {
        case ($rank >=1 and $rank <=3):
            echo "1-3";
            break;
        case ($rank >=4 and $rank <=6):
            echo "4-6";
            break;
        case ($rank >=7 and $rank <=9):
            echo "7-9";
            break;
        case ($rank >=10 and $rank <=12):
            echo "10-12";
            break;
        case ($rank >=13 and $rank <=15):
            echo "13-15";
            break;
        case ($rank >=16 and $rank <=18):
            echo "16-18";
            break;
        case ($rank >=19 and $rank <=21):
            echo "19-21";
            break;
        case ($rank >=22 and $rank <=24):
            echo "22-24";
            break;
        }
    } elseif ($num_rows >=25 and $num_rows <=50) {
        echo "greater than 24";
    } elseif ($num_rows >=51 and $num_rows <=100) {
        echo "greater than 50";
    } elseif ($num_rows >=101 and $num_rows <=150) {
        echo "greater than 100";
    } elseif ($num_rows >=151 and $num_rows <=260) {
        echo "greater than 150";
    }
}

This is the table:
while($row = mysqli_fetch_array($result))
    {
    echo "
";
    echo "" . $row['term'] . "	";
    echo "" . $row['acadplan'] . "	";
    echo "" . $row['projlvl'] . "	";
    echo "" . $row['gpa'] . "	";
    echo "" . $row['ranking'] . "	";
    echo "
";
    }
echo "
";

A: What about a solution like this one:
 function someFunction($rank, $num_rows) {
     if ($num_rows <=24) {
        switch (true) {
            case ($rank >= 1 AND $rank <=3):
                return "1-3";
            case ($rank <=6):
                return "4-6";
            case ($rank <=9):
                return "7-9";
            case ($rank <=12):
                return "10-12";
            case ($rank <=15):
                return "13-15";
            case ($rank <=18):
                return  "16-18";
            case ($rank <=21):
                return "19-21";
            case ($rank <=24):
                return "22-24";
        }
    } elseif ($num_rows >=25 and $num_rows <=50) {
         return "greater than 24";
    } elseif ($num_rows >=51 and $num_rows <=100) {
        return "greater than 50";
    } elseif ($num_rows >=101 and $num_rows <=150) {
        return "greater than 100";
    } elseif ($num_rows >=151 and $num_rows <=260) {
        return "greater than 150";
    }
    return "";
}

And then the table:
while($row = mysqli_fetch_array($result))
{
    echo "
";
    echo "" . $row['term'] . "	";
    echo "" . $row['acadplan'] . "	";
    echo "" . $row['projlvl'] . "	";
    echo "" . $row['gpa'] . "	";
    echo "" . $row['ranking'] . "	";
    echo "" . someFunction($row['ranking'], $num_rows) . "	";
    echo "
";
}
echo "
";

Edit:
You can use PHP in HTML tags like that:
<?php echo $row['ranking']; ?>

I find it preferrable way to use PHP values in my views. Of course strictly business logic should be separated if possible and not put in HTML tags.


text:
Q: Add JPanel to contentPane within actionListener I'm trying to add a JPanel to my JFrame within an actionListener method, but it appears only after the second click on the button. This is a portion of my code where panCours is a JPanel and ConstituerData the targeted JFrame  :
addCours.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent arg0) {
            panCours.setBounds(215, 2, 480, 400);
            panCours.setBorder(BorderFactory.createTitledBorder("Saisir les données concernant le cours"));
            ConstituerData.this.getContentPane().add(panCours);
        }
    });

I don't understand why it doesn't appear as soon as I click on the button. Any explanation and help about how to fix this ?

A: You'll need to add a call to repaint(); (as well as probably revalidate();) to get the JPanel to show immediately. A basic example demonstrating your problem (and the solution) below;
public class Test {

    public static void main(String[] args) {
        final JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout(null);

        JButton button = new JButton("Test");
        button.setBounds(20, 30, 100, 40);
        button.addActionListener(new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent e) {
                JPanel panel = new JPanel();
                panel.setBackground(Color.red);
                panel.setBounds(215, 2, 480, 480);
                frame.add(panel);
                frame.revalidate(); // Repaint here!! Removing these calls
                frame.repaint(); // demonstrates the problem you are having.

            }
        });

        frame.add(button);
        frame.setSize(695, 482);
        frame.setVisible(true);

    }
}

The above said, (as suggested by others) it's only right that I recommend against the use of a null layout in future. The swing layouts are a little awkward to begin with, but they will help you a great deal in the long run.

A: the answer can be found in the following snippet:
you need to revalidate() the contentPane, not repaint the frame. you can add any panel you want to the contentpane like this. if you declare contentPane as a private field you dont need your getContentPane() call. contentPane is global so it can be reffered to directly from anywhere within the class.
be careful about NullPointerExeptions which can be thrown if you refer to it before initialising.
public class testframe extends JFrame {

private JPanel contentPane;

/**
 * Launch the application.
 */
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                testframe frame = new testframe();
                frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

/**
 * Create the frame.
 */
public testframe() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    contentPane = new JPanel();
    setContentPane(contentPane);

    JButton btnNewButton = new JButton("New button");
    btnNewButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            JPanel a = new JPanel();
            contentPane.add(a);
            contentPane.revalidate();
        }
    });
    contentPane.add(btnNewButton);
}

}


text:
Q: When adjoining a new sort that is supposed to model the powerset of the original domain of discourse, what is the appropriate notion of embedding? Edit. This question hasn't generated much interest so far. Any suggestions for improvement would be much appreciated, so please leave a comment. Best wishes.

Often, we begin with a first-order theory $(T,L)$ and then adjoin a 'sort of all subsets' to obtain a bigger theory $(T',L').$ My concern is this. I want to know that if we're working in the bigger theory $(T',L')$ and we prove a theorem in the language of $L$, then this theorem can be deduced from $T$ alone.
Lets consider the issue in more detail.
By the term first-order theory, let us mean an ordered pair $(T,L)$ where $L$ is a (many-sorted) first-order language, and $T$ is an arbitrary (not necessarily deductively closed) subset of $L$.
Now consider a first-order theory $(T,L)$ with a single sort $X$. We can obtain a new first-order theory $(T',L')$ by adding

*

*a new sort $\mathcal{P}(X)$

*a membership relation $\in\; : X \rightarrow \mathcal{P}(X),$

*an axiom of extensionality for the elements of $\mathcal{P}(X)$

*and a comprehension* schema.

Now presumably, the inclusion map $f : L \rightarrow L'$ is some sort of an embedding (not just of the languages, but more importantly, of the theories). What is the appropriate notion of embedding for this situation, and how do we know that $f$ has the property of interest? By proving that $f$ is indeed an embedding in the appropriate sense, we should be able to deduce as an immediate corollary that if we're working in the bigger theory $(T',L')$ and we prove a theorem in the language of $L$, then this theorem can be deduced from $T$ alone.
*The comprehension schema can be stated as follows. For all natural numbers $n$ and $m$ and all formulae $$\varphi(a_0,\cdots,a_n,A_0,\cdots,A_m,y)$$ in the language $L'$, we take the following as an axiom.

For all $(a_0 : X)(\cdots)(a_n : X)$ and all $(A_0 :
 \mathcal{P}(X))(\cdots)(A_m : \mathcal{P}(X))$, there exists $Y :
 \mathcal{P}(X)$ such that for all $x : X$ we have $$x \in Y
 \Leftrightarrow \varphi(a_0,\cdots,a_n,A_0,\cdots,A_m,y).$$

A: The definition you are looking for is conservative extension.
I think the easiest way to show that $T'$ is a conservative extension of $T$ is to note that every model $\mathcal{M}$ of $T$ can be extended to a model $\mathcal{M}'$ of $T'$ in the obvious way (by setting $\mathcal{P}(X)$ to be the usual powerset). In the wikipedia article I linked to, this is called a model theoretic conservative extension. It follows that $T'$ is a conservative extension of $T$ using the completeness theorem for first order logic.
Something to note about this construction is that it is not always as useful as you might think. For example, you might expect that if $T$ is Peano arithmetic $\mathbf{PA}$, then $T'$ is second order arithmetic $\mathbf{Z}_2$. This is not the case, and in fact $\mathbf{Z}_2$ is definitely not conservative over $\mathbf{PA}$.

A: There's not a special name for the embedding; in this case $L$ is just a subset of $L'$ so there's not even much need to talk about "embedding".  There is one piece of terminology; we say that $T'$ is conservative over $T$ if, for every sentence $\phi \in L$, if $\phi$ is provable in $T'$ then it is provable in $T$.
In most cases of interest, the second-order theory with full comprehension will not be conservative over the original theory. Usually we have to weaken the comprehension scheme to fix this. For example, the second-order theory conservative over PA is known as $\mathsf{ACA}_0$, and is obtained by extending the language and then adding comprehension and induction axioms for all arithmetical formulas (formulas that do not quantify over sets).
Somewhat similarly, NBG set theory is a second-order extension of ZFC set theory, and NBG is conservative over ZFC for sentences in the language of ZFC. But NBG does not have full comprhension, it only has comprehension for formulas that do not quantify over classes. If we add full comprehension we obtain something like Morse-Kelly set theory which is no longer conservative over ZFC.
In general, the choice of the right comprehension scheme to get conservativity is delicate. If you add no additional axioms than the second-order extension is conservative over the original, but not useful for proving any new theorems. If you add too many comprehension axioms, the new theory is likely to be too strong. So some amount of context-specific proof is required for each result to show that a particular amount of comprehension is still conservative over the original theory.


text:
Q: iOS 14 widget onAppear / didAppear event? Is there any technique to re-render iOS 14 widget content when I scroll to my home screen (contain my widget)?

To clarify, this is Home screen of iOS 14 where you can place any
widget on. It's not the today extension that appeared in the very left
Home screen.

I haven't found any document about this technique! All I know is using Timeline to schedule the rendering, and refreshWidget(widgetKindHere)
Currently, I'm using IntentTimelineProvider to make updating schedule, keep my stock widget up to date frequently for every 30 minutes
But as I can see the TradingView's widget:
When I scrolled to my home screen contain its widget, the last updated info on the widget changed from 12:00pm to 2:55pm (current)
-> That mean they did not update their widget from 12pm to 2:30pm, until I scrolled to the Home screen contain the widget, a few seconds later, it get updated at 2:55pm
How can TradingView did that?

A: This is not about detecting onAppear/onDisappear events. What you observe is the smart behaviour of Smart Stacks. Usually related with the use of TimelineEntryRelevance.
Every TimelineEntry has a TimelineEntryRelevance. The relevance is required, however, the default implementation is provided.
struct SimpleEntry: TimelineEntry {
    var date: Date
    var relevance: TimelineEntryRelevance?
}

let entry = SimpleEntry(date: Date(), relevance: 0.1)

Why relevance is important? It is used by Smart Stacks to display the most relevant widget, i.e., the one with the most relevant information.
From Welcome to Design Great Widgets:

Another feature we've created is Smart Stacks. These let you add
several different widgets into a single location and quickly flick
between the different widgets inside. But what is really powerful is
that smart stacks dynamically change and adapt to how you use them.
Based on your behavior and context, a smart stack will automatically
rotate to show you the most relevant widget at a given time. [emphasis added]

From Add configuration and intelligence to your widgets:

You want your widget to be surfaced when you have timely information
relevant to the people using your app, like when you know there is a
thunderstorm coming, but not when you're just updating the temperature
regularly.
For example, if someone frequently launches your weather app to check
on the weather, the system can instead surface your widget with that
information to provide quicker access to what they're looking for.
The second is based on relevant information from your app. So, for
example, if a thunderstorm is happening, your widget can inform the
system that it has a highly relevant update, and the system will
consider surfacing your widget to the top of the stack.

Useful links:

*

*Welcome to Design Great Widgets

*Add configuration and intelligence to your widgets

*Widgets Code-along, part 2: Alternate timelines


text:
Q: Moving buildings in water layer into Buildings layer using MapInfo? I am using MapInfo.
I mistakenly vectorised some building on my water layer, is there any way I can fix this by moving the buildings in the water layer into the Buildings layer?
It was so tedious and doing it all over is not desirable.

A: The simplest way to do this is to make your Buildings layer editable.  Then, select the buildings from the Water Layer.  Then copy the buildings (CTRL-C) and paste (CTRL-V).  Because your buildings layer is editable, they will paste into that layer.
Save the Buildings layer.
Then, you can delete the buildings from the Water layer.


text:
Q: how to change Session ID for each request in ASP.Net I have Created ASP.Net,C# web application. I would like to get the new Session id for each time requesting a web page.And assign the Session id value to a label.Hence, i tried following,
            string sessionId = System.Web.HttpContext.Current.Session.SessionID;
            LblSessionvar.Text = Convert.ToString(sessionId);

now, the problem is it shows same Session Id each time when i run the Web Application,it does not change the Session ID.
( i have tried with  cookieless session it works nice and it changes Session ID as i expected but,i would like to achieve this with Cookies).

A: Call;
Session.Abandone();

and
Response.Cookies("ASP.NET_SessionId").Expires = DateTime.Now.AddYears(-30)

This will may help you; By the way, why do you need sessionId?


text:
Q: Is there any way to get array of child association ids while using 'include' option to query in 'Sequelize'? I have a model called A, and it has many B. when I query A from mysql, I want to have something like this
{ a: { b_ids: [1, 2, 3] } }

my current code looks like this:
A.findOne({
    where: {id: id},
    include: [
      {
        model: B,
        attributes: [
          'id'
        ]
      }
})

and i get { a: { bs: [{id: 1}, {id: 2}, {id: 3}] } }, is there any way that I can return an array of child association ids instead of an array of object?


text:
Q: How do I solve a recurrence relation of the type $a_{n+1} = K(n)a_{n} + P(n)a_{n-1}$ where $K(n)$ and $P(n)$ are rational functions? I've been stuck on a problem for days now and was able to boil it down to this recurrence relation. I researched a bit about ways to solve it -- generating functions, characteristic polynomials, homogenous and non-homogenous recurrence relations -- but couldn't find a method of tackling this specific one. Any tips, solutions, or suggestions would be welcomed. Thanks.
Edit: As made clear in the comments, treating the functions as any rational function is too general to solve. The specific problem I am solving requires $K(n) = (2n+5)/(n+2)$ and $P(n) = (n+1)(n+3)^2/(n+2)$
Edit #2: As requested, $a_1 = 5 ; a_2 = 33 ; a_3 = 168$

A:
$a_{n+1} = \dfrac{2n+5}{n+2} a_{n} + \dfrac{(n+1)(n+3)^2}{n+2} a_{n-1}$

Rewriting $\,2n+5 = (n+3)^2 - (n+2)^2\,$:
$$
\quad\quad a_{n+1} = \frac{(n+3)^2 - (n+2)^2}{n+2} a_{n} + \frac{(n+1)(n+3)^2}{n+2} a_{n-1}
\\ \iff\quad\quad a_{n+1} + (n+2) a_n = \frac{(n+3)^2}{n+2} \big(a_n + (n+1) a_{n-1}\big)
$$
With $\,b_n = a_{n} + (n+1) a_{n-1}\,$, this telescopes to:
$$
\require{cancel}
b_{n+1} = \frac{(n+3)^2}{n+2} \,b_n = \frac{(n+3)^2}{\bcancel{n+2}} \,\frac{(n+2)^{\bcancel{2}}}{n+1}  \, b_{n-1} = \dots = (n+3)\,\frac{(n+3)!}{2} \, b_0
$$
Once $\,b_n\,$ is determined, what's left to solve is the simpler recurrence:
$$
a_{n} + (n+1) a_{n-1} = b_n \quad\iff\quad \frac{a_n}{(n+1)!} = -\frac{a_{n-1}}{n!} + \frac{b_n}{(n+1)!}
$$

A: Based on the result by 2 False I suppose we can set $a_n=(n+1)!\ b_n$
This results in $$(n+2)^2b_{n+1}=(2n+5)b_n+(n+3)^2b_{n-1}=0$$
Applying now the idea by dxiv leads to an easier relation
$$(n+2)^2(b_{n+1}+b_n)=(n+3)^2(b_n+b_{n-1})$$
So we can set $c_n=b_n+b_{n-1}$ and get
$$c_{n+1}=\frac{(n+3)^2}{(n+2)^2}c_n$$
This is telescopic as well and $c_n=(n+3)^2\,C$
The equation $b_{n+1}+b_n=0$ has root $-1$

*

*general solution of homegeneous equation is $\alpha(-1)^n$

*RHS is $(n+3)^2\,C\,(1)^n$ so a particular solution is of the same degree $2$ as RHS.

Conducting the calculation gives $\frac 12C(n+2)(n+3)$.
In the end $$a_n=(n+1)!\Big(\alpha(-1)^n+\beta(n+2)(n+3)\Big)$$
We now have to apply initial conditions $a_1=5$ and $a_2=33$ and we find
$\begin{cases}-2\alpha+24\beta=5\\6\alpha+120\beta=33\end{cases}\iff\begin{cases}\alpha=\frac 12\\\beta=\frac 14\end{cases}$

$$a_n=(-1)^n\frac{(n+1)!}{2}+\frac{(n+3)!}{4}$$

Verification: $a_3=-\frac{4!}{2}+\frac{6!}{4}=-\frac{24}{2}+\frac{720}{4}=-12+180=168\ \checkmark$