text:
Q: Is it possible to connect two wireless range extenders? Hello i have tplink tlwr 740n router and tlwa-850re range extender connected together but my house is surrounded with thick walls so even range extender is loosing signal.So i'm planning to buy another wireless range extender.My doubt is can i connect two wireless range extenders together??because router has qss/wps functionality so i connected one router with one range extender.Now i want to connect my second range extender with first range extender is it possible???

A: Go with powerline range extenders? I have 2 in my place and they work fine.
You just join whichever wifi is strongest in the area.
Most have a built in ethernet too, handy for wired connections.
This is a good scalable method.
You may have to change the IP of one of them, if the want a fixed IP, but you can normally configure that in the settings of the extender.
Oh, you can also unplug the extender and move to another outlet if you need to change location, very handy.


text:
Q: Jquery datatables. Array of rows of visible columns I'm trying to extract an array of rows from my datatable. My problem is that I have some fields of the json that populates the table that I don't show in the table. When I use
$('#myTable').DataTable().rows().data().toArray()

I get those fields that I don't need.
¿How can I get that array of the shown fields or columns?
Thanks in advance.

A: You need to use a selector-modifier.
$('#myTable').DataTable().rows({search:'applied'}).data().toArray();

-------------------------------------
EDIT
A possible way to accomplish what you are asking for is to check first what columns are visible. Then, process each result row and get only the fields you want.
var columns = $('#myTable').DataTable().columns().visible();
var rows = $('#myTable').DataTable().rows().data().toArray();
var result = []; // this array will contain only the visible fields of each row
for (var i = 0; i < rows.length; ++i) {
    var row = [];
    for (var j = 0; j < columns.length; ++j)
        if (columns[j]) // is visible
            row.push(rows[i][j]);
    result.push(row);
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Compare numeric values (using a threshold/tolerance) from two arrays with matching keys I need to compare database values with post values. If post values (decimal price) are within 2 cents threshold consider values equal. Result is array with 'real' difference. Arrays are consistent: same number of values, same keys.
$db_values =   array( "21" => 10.00, "22" => 20.00, "25" => 3.55);
$post_values = array( "21" => 9.98,  "22" => 20.01, "25" => 2.55 );

I'm trying to compare Absolute value to my tolerance value -- epsilon (Compare decimals in PHP)  and array_udiff:
function epsilon_compare ($v1,$v2)
{
 $epsilon = 0.02;
 $diff = abs($v1 - $v2);

   if ($diff <= $epsilon)
    {
            return 0;
      //echo "numbers are equal";
      } else {
         return 1;
             }
    }

 print_r(array_udiff($post_values, $db_values, "epsilon_compare"));

gives correct result: Array ( [25] => 2.55 )
but when i use different array I get wrong result eg:
   $db_values =   array( "21" => 10.00, "22" => 20.00, "25" => 3.55);
   $post_values = array( "21" => 8.00,  "22" => 20.01, "25" => 2.55 );

In this case it gives:
   Array ( [21] => 8 [22] => 20.01 [25] => 2.55 )

Key [22] => 20.01 is listed but it is within the threshold so it shouldn't be in result set.
I think I don't  fully understand array_udiff. thanks.

A: I don't think that udiff does what you think it does. If you print v1 and v2 it will give you the following:
v1: 20.01 v2: 9.98
v1: 2.55 v2: 20.01
v1: 20 v2: 10
v1: 3.55 v2: 20
v1: 9.98 v2: 10
v1: 9.98 v2: 20.01
v1: 20.01 v2: 20
v1: 20.01 v2: 2.55
v1: 2.55 v2: 3.55

It makes more comparisons than you think.
You probably need a piece of code that looks something like:
function compare_arrays($array1, $array2){
    $result = array();
    foreach($array1 as $value => $outcome){
        if(epsilon_compare($array1[$value], $array2[$value])){
            $result[$value] = $array2[$value];
        }
    }
    return $result;
}

A: http://docs.php.net/array_udiff:The user supplied callback function is used for comparison. It must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second. Your function always returns 1 if the elements are unequal which results in diffrent (wrong) comparisons decisions.

<?php
function epsilon_compare ($v1,$v2)
{
    $epsilon = 0.02;
    $diff = $v1 - $v2;
    return abs($diff)<=$epsilon ? 0 : $diff;
}

$db_values =   array( "21" => 10.00, "22" => 20.00, "25" => 3.55);
$post_values = array( "21" => 8.00,  "22" => 20.01, "25" => 2.55 );
print_r(array_udiff($post_values, $db_values, "epsilon_compare"));

prints
Array
(
    [21] => 8
    [25] => 2.55
)

edit: using array_udiff_assoc
$db_values = array ( "1" => 7.55, "2" => 5.45, "3" => 5.45, "4" => 64.45, "5" => 54.75, "6" => 30.40, "7" => 56.99, "8" => 10.90, "9" => 60.85, "11" => 3.25, "12" => 13.05, "13" => 5.45, "14" => 8.00, "15" => 5.45, "16" => 13.05, "17" => 4.35 );
$post_values = array ( "1" => 7.55, "2" => 5.45, "3" => 5.45, "4" => 64.45, "5" => 54.75, "6" => 30.40, "7" => 56.99, "8" => 10.90, "9" => 60.85, "11" => 3.25, "12" => 13.05, "13" => 2.45, "14" => 8.00, "15" => 5.45, "16" => 12.05, "17" => 2.34 );
print_r(array_udiff_assoc($post_values, $db_values, "epsilon_compare"));

prints
Array
(
    [13] => 2.45
    [16] => 12.05
    [17] => 2.34
)


text:
Q: Google Assistant API V2 userstorage I'm attempting to develop a Google Action with the Dialogflow v2 API
My function saves a value to userstorage as follows
def save_value(value):
res = {
  "fulfillmentText": "Set value to {}".format(int(value)),
  "payload": {
    "google": {
      "userStorage": str(value)
    }
  }
}
print ("Saved value")
response = jsonify(res)
return response

And I get the following back from testing in Dialogflow
{
  "fulfillmentText": "Set value to 36237269",
  "payload": {
    "google": {
      "userStorage": "36237269"
    }
  }
}

This works for the duration of session, I am able to use this in later intents via
 value = request_json['originalRequest']['data']['user']['userStorage']

However, the data is only stored for one session - if I invoke my action again, there is nothing saved.
Is this the correct way of using userstorage? Has anyone successfully used it with Python?
Failed "response"
{
  "responseMetadata": {
    "status": {
      "code": 10,
      "message": "Failed to parse Dialogflow response into AppResponse because of empty speech response",
      "details": [
        {
          "@type": "type.googleapis.com/google.protobuf.Value",
          "value": "{\"id\":\"816605a7-f7e0-4d37-a490-c84ff63fb7dd\",\"timestamp\":\"2018-11-08T17:18:49.422Z\",\"lang\":\"en-us\",\"result\":{},\"alternateResult\":{},\"status\":{\"code\":206,\"errorType\":\"partial_content\",\"errorDetails\":\"Webhook call failed. Error: 500 Internal Server Error\"},\"sessionId\":\"ABwppHHai3qsY2WPZWezmh9Q_bUF45aD51GbQ81sUDF7iSrRLA2m8KFgZ1ZYavnCv3fAckW1tcoJdydZTXQY5Nw\"}"
        }
      ]
    }
  }
}

Working "response"
{
  "conversationToken": "[]",
  "finalResponse": {
    "richResponse": {
      "items": [
        {
          "simpleResponse": {
            "textToSpeech": "Text"
          }
        }
      ]
    }
  },
  "responseMetadata": {
    "status": {
      "message": "Success (200)"
    },
    "queryMatchInfo": {
      "queryMatched": true,
      "intent": "047ad9d9-0180-47f9-88bd-e5ffc8936c08"
    }
  },
  "userStorage": "36237269"
}

Working "Request"
{
  "user": {
    "userId": "ABwppHE5H0FKrXKk8PjJyzZJ12OSMQcjxuT2NnfPAgLvai0UsfWEoYE8R_L8qLQdqY29sOnsZhQhE5G4XVVXiGs",
    "locale": "en-US",
    "lastSeen": "2018-11-08T17:18:16Z",
    "userStorage": "36237269"
  },
  "conversation": {
    "conversationId": "ABwppHE6BwK2zIBKxHA8hc9uBGumVgKbbNGHhRVFz7O6yrxxa1WJ_xtKNqhesj3EwNCVlestM-bF6tDWzZhqUXE",
    "type": "ACTIVE",
    "conversationToken": "[]"
  },
  "inputs": [
    {
      "intent": "actions.intent.TEXT",
      "rawInputs": [
        {
          "inputType": "KEYBOARD",
          "query": "when is the next bus"
        }
      ],
      "arguments": [
        {
          "name": "text",
          "rawText": "when is the next bus",
          "textValue": "when is the next bus"
        }
      ]
    }
  ],
  "surface": {
    "capabilities": [
      {
        "name": "actions.capability.MEDIA_RESPONSE_AUDIO"
      },
      {
        "name": "actions.capability.WEB_BROWSER"
      },
      {
        "name": "actions.capability.AUDIO_OUTPUT"
      },
      {
        "name": "actions.capability.SCREEN_OUTPUT"
      }
    ]
  },
  "isInSandbox": true,
  "availableSurfaces": [
    {
      "capabilities": [
        {
          "name": "actions.capability.WEB_BROWSER"
        },
        {
          "name": "actions.capability.AUDIO_OUTPUT"
        },
        {
          "name": "actions.capability.SCREEN_OUTPUT"
        }
      ]
    }
  ],
  "requestType": "SIMULATOR"
}

Failed "request"
{
  "user": {
    "userId": "ABwppHE5H0FKrXKk8PjJyzZJ12OSMQcjxuT2NnfPAgLvai0UsfWEoYE8R_L8qLQdqY29sOnsZhQhE5G4XVVXiGs",
    "locale": "en-US",
    "lastSeen": "2018-11-08T17:18:41Z"
  },
  "conversation": {
    "conversationId": "ABwppHHai3qsY2WPZWezmh9Q_bUF45aD51GbQ81sUDF7iSrRLA2m8KFgZ1ZYavnCv3fAckW1tcoJdydZTXQY5Nw",
    "type": "ACTIVE",
    "conversationToken": "[]"
  },
  "inputs": [
    {
      "intent": "actions.intent.TEXT",
      "rawInputs": [
        {
          "inputType": "KEYBOARD",
          "query": "when is the next bus"
        }
      ],
      "arguments": [
        {
          "name": "text",
          "rawText": "when is the next bus",
          "textValue": "when is the next bus"
        }
      ]
    }
  ],
  "surface": {
    "capabilities": [
      {
        "name": "actions.capability.WEB_BROWSER"
      },
      {
        "name": "actions.capability.MEDIA_RESPONSE_AUDIO"
      },
      {
        "name": "actions.capability.SCREEN_OUTPUT"
      },
      {
        "name": "actions.capability.AUDIO_OUTPUT"
      }
    ]
  },
  "isInSandbox": true,
  "availableSurfaces": [
    {
      "capabilities": [
        {
          "name": "actions.capability.WEB_BROWSER"
        },
        {
          "name": "actions.capability.SCREEN_OUTPUT"
        },
        {
          "name": "actions.capability.AUDIO_OUTPUT"
        }
      ]
    }
  ],
  "requestType": "SIMULATOR"
}


text:
Q: Mock class injection in spring not working as intended I recently started writing JUnits that require mocking methods and data. I was able to do this for another class and it worked but not sure why its not working for a current class I'm testing.
Basically what I try to do is.
1.Create a mock class for the class/method that I need to mock the data for.
2.Inject it to the class I'm testing via context.xml
3.When the method is called in the class I'm testing it should be the overridden one
public abstract class Service {
    public string methodA(String x, String y, String z) {
        return x;
    }
}

.
public class SchoolService extends Service{
    public String methodB(String input) {
        String data = methodA("Test", "Test", "Test");
        return data;
    }
}

.
public class MockService extends SchoolService{
    @Override
    public String methodA(String x, String y, String z) {
        return "OVERRIDE";
    }
}

.
context.xml

<bean id="SchoolService" class="com.xxx.xxxx.xxx.SchoolService" scope="prototype">
    <property name="SchoolService" ref="MockService"/>
</bean>

<bean id="MockService" class="com.xxx.xxxx.xxx.MockService"/>

If this works as what I intend it to do then when methodA is called inside MethodB it should return "OVERRIDE" instead of x.
I wrote this JUnit the same way as I did for the other class but somehow it is not working the same way. I'm suspecting its due it being a super class method, but not sure how I can fix it.
edit: adding my test class
public class SchoolServiceTest {
    SchoolService ss;

    @Test
    public string testSchoolService() {
        return ss.methodB("Test");
    }
}


text:
Q: How to read reference $ref of JSON file? {
  "description": "Something",
  "id": "abc.def.xyzjson#",
  "type": "object",
  "properties": {
    "triggerTime": {
      "description": "Something",
      "$ref": "abc.def.xyz.1.json#"
      "required": true
    },
    "customerId": {
      "type": "string",
      "description": "Something",
      "$ref": "abc.def.xyz.1.json#"
    },

..... many more keys........
I need to go into the $ref file location and lode that json into a map
Please help me out how to read.
Already I am able to read the main file like
File jsonInputFile = new File("location");
System.out.println("Keys : " + entry2.getKey());

A: You can try below code for getting the $ref value
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
public class Test{

    public static void main(String[] args) {
        JSONParser parser = new JSONParser();

        try {

            Object obj = parser.parse(new FileReader(
                    "File location"));
            JSONObject jsonObject = (JSONObject) obj;
            JSONObject properties = (JSONObject) jsonObject.get("properties");
            JSONObject triggerTime = (JSONObject) properties.get("triggerTime");
            String ref = (String) triggerTime.get("$ref");//You can load this file to a map if required.
            System.out.println(ref);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

output is

abc.def.xyz.1.json#


text:
Q: Calling a css rule from javascript Hi all I was wondering if it is possible through javascript to turn a .png that is accessed through css into a clickable link by call that css rule.
.calendar {
    background: transparent url("../cal_icon.png") no-repeat 94px 3px;
    background-repeat: no-repeat;
    margin-right: 2px;
}

This is my css rule that I would like to make my cal_icon.png clickable.
Is this possible?
Please forgive my ignorance in this matter.

A: As said in comments, you need to add click handler to the element, and css is just for styling
you can take a look at this fiddle, which uses jQuery (onLoad) http://jsfiddle.net/tq92z/
$('.calendar').click(function(){
    $(this).css('color','red');
})

there is a css expressions for IE, maybe something else for other browsers (but i can't remember anything now)
http://www.richnetapps.com/using_javascript_expressions_in_css/
but it's not a common practice to do dom manipulations with css


text:
Q: Qt Quick - What is the best way to animate an image transition while component state changes? With Qt Quick, I created a custom button which looks like that:

This button also contains several states (default, hover, pressed), and the transition between each states is animated. I found a way to animate each properties easily with the Qt Quick engine, except for the image one. Indeed, I want to animate the image transition, by performing a crossfade between states.
However I couldn't found a such animator for images. The only way I found was to add 3 images to my button, one for each states, and to animate their respective opacity.
Below is the code for my buttons:
Button
{
    property bool hoveredBtn: false
    property bool pressedBtn: false

    id: btAnimStateDemo
    height: 40
    anchors.right: parent.right
    anchors.rightMargin: 5
    anchors.left: parent.left
    anchors.leftMargin: 5
    anchors.top: parent.top
    anchors.topMargin: 290
    state: "DEFAULT"

    // the button background
    background: Rectangle
    {
        id: btAnimStateDemoBg
        anchors.fill: parent
    }

    // the button text
    Text
    {
        id: btAnimStateDemoText
        text: qsTr("A button showing animated states (default, hovered, pressed)")
        renderType: Text.NativeRendering
        font.bold: true
        horizontalAlignment: Text.AlignHCenter
        verticalAlignment: Text.AlignVCenter
        anchors.fill: parent
    }

    Image
    {
        id: btAnimStateDemoDefaultImage
        width: 30
        height: 30
        anchors.left: parent.left
        anchors.leftMargin: 5
        anchors.bottom: parent.bottom
        anchors.bottomMargin: 5
        anchors.top: parent.top
        anchors.topMargin: 5
        opacity: 1.0
        source: "Resources/Palette.svg"
    }

    Image
    {
        id: btAnimStateDemoHoverImage
        width: 30
        height: 30
        anchors.left: parent.left
        anchors.leftMargin: 5
        anchors.bottom: parent.bottom
        anchors.bottomMargin: 5
        anchors.top: parent.top
        anchors.topMargin: 5
        opacity: 0.0
        source: "Resources/Smile.svg"
    }

    Image
    {
        id: btAnimStateDemoPressedImage
        width: 30
        height: 30
        anchors.left: parent.left
        anchors.leftMargin: 5
        anchors.bottom: parent.bottom
        anchors.bottomMargin: 5
        anchors.top: parent.top
        anchors.topMargin: 5
        opacity: 0.0
        source: "Resources/Woman.svg"
    }

    // the component state array
    states:
    [
        State
        {
            name: "DEFAULT"
            PropertyChanges { target: btAnimStateDemoBg; color: "green"}
            PropertyChanges { target: btAnimStateDemoBg; radius: 4}
            PropertyChanges { target: btAnimStateDemoDefaultImage; opacity: 1.0}
            PropertyChanges { target: btAnimStateDemoHoverImage; opacity: 0.0}
            PropertyChanges { target: btAnimStateDemoPressedImage; opacity: 0.0}
        },
        State
        {
            name: "HOVERED"
            PropertyChanges { target: btAnimStateDemoBg; color: "red"}
            PropertyChanges { target: btAnimStateDemoBg; radius: 10}
            PropertyChanges { target: btAnimStateDemoDefaultImage; opacity: 0.0}
            PropertyChanges { target: btAnimStateDemoHoverImage; opacity: 1.0}
            PropertyChanges { target: btAnimStateDemoPressedImage; opacity: 0.0}
        },
        State
        {
            name: "PRESSED"
            PropertyChanges { target: btAnimStateDemoBg; color: "blue"}
            PropertyChanges { target: btAnimStateDemoBg; radius: 15}
            PropertyChanges { target: btAnimStateDemoDefaultImage; opacity: 0.0}
            PropertyChanges { target: btAnimStateDemoHoverImage; opacity: 0.0}
            PropertyChanges { target: btAnimStateDemoPressedImage; opacity: 1.0}
        }
    ]

    // the matching transitions between states
    transitions:
    [
        Transition
        {
            from: "*"; to: "DEFAULT"
            ColorAnimation { property: "color"; easing.type: Easing.Linear; duration: 1000 }
            NumberAnimation { properties: "radius, opacity"; easing.type: Easing.Linear; duration: 1000 }
        },
        Transition
        {
            from: "*"; to: "HOVERED"
            ColorAnimation { property: "color"; easing.type: Easing.Linear; duration: 1000 }
            NumberAnimation { properties: "radius, opacity"; easing.type: Easing.Linear; duration: 1000 }
        },
        Transition
        {
            from: "*"; to: "PRESSED"
            ColorAnimation { property: "color"; easing.type: Easing.Linear; duration: 1000 }
            NumberAnimation { properties: "radius, opacity"; easing.type: Easing.Linear; duration: 1000 }
        }
    ]

    // the mouse area which will apply the correct state in relation to the current mouse status
    MouseArea
    {
        anchors.fill: parent
        hoverEnabled: true

        onEntered: {btAnimStateDemo.state = "HOVERED"; btAnimStateDemo.hoveredBtn = true;}
        onExited: {btAnimStateDemo.state = btAnimStateDemo.pressedBtn ? "PRESSED" : "DEFAULT"; btAnimStateDemo.hoveredBtn = false;}
        onPressed: {btAnimStateDemo.state = "PRESSED"; btAnimStateDemo.pressedBtn = true;}
        onReleased: {btAnimStateDemo.state = btAnimStateDemo.hoveredBtn ? "HOVERED" : "DEFAULT"; btAnimStateDemo.pressedBtn = false;}
    }
}

The above code works well, and reaches the purpose I planned, but is a little complicated from my point of view. It would be wonderful if an animator like NumberAnimation or ColorAnimation would exist for the images, but I found none.
So my question is: Is there a simpler way to animate an image transition between component states than my above proposed solution? Do Qt Quick propose an animator to reach a such purpose?

A: Create a SpriteSheet that assigns states to each of the three frames then set the interpolate property to true to have it transition between the images.
Sprite Animations with SpriteSequence
SpriteSequence demonstrates using a sprite sequence to draw an animated and interactive bear. The SpriteSequence object defines five different sprites. The bear is initially in a still state:
      Sprite{
          name: "still"
          source: "content/BearSheet.png"
          frameCount: 1
          frameWidth: 256
          frameHeight: 256
          frameDuration: 100
          to: {"still":1, "blink":0.1, "floating":0}
      }

When the scene is clicked, an animation sets the sprite sequence to the falling states and animates the bear's y property.
  SequentialAnimation {
      id: anim
      ScriptAction { script: image.goalSprite = "falling"; }
      NumberAnimation { target: image; property: "y"; to: 480; duration: 12000; }
      ScriptAction { script: {image.goalSprite = ""; image.jumpTo("still");} }
      PropertyAction { target: image; property: "y"; value: 0 }
  }

At the end of the animation the bear is set back to its initial state.


text:
Q: Guardar valores na váriavel Guardar valores em uma variável vindo por GET
Exemplo:
$id = $_GET['id'];
$dados = array($id);

Dúvida:
Como guardar todos os ID? Pois eu irei usar esses ID para identificar qual produto foi selecionado.
Criei um carrinho de compras usando SESSION, ao clicar no produto, ele grava na session os dados dele, mas ao clicar no produto, eu estou verificando se o valor do produto é maior que o crédito que o usuário tem, se caso for maior ai ele vai para página para finalizar a compra, caso contrário, ele volta para a página de produtos, mas aparecerá ao usuário os produtos que ele selecionou, ou seja, coloquei um ícone de um VISTO em cima do produto. Mas para colocar esse ícone, eu estou verificando se a $_SESSION['idProduto'] é igual o id do produto

A: $_SESSION['var'] = array();

array_push($_SESSION['var'], '1'); // adiciona no array
array_push($_SESSION['var'], '2'); // adiciona no array
array_push($_SESSION['var'], '3'); // adiciona no array
array_push($_SESSION['var'], '4'); // adiciona no array

foreach($_SESSION['var'] as $key)
  echo $key.'<br>';

http://br.php.net/array_push

A: Recomendo que use sempre (int)  antes do $_GET['id'].
Como o id vem via url trata-se de uma string e desta forma com int vamos nos certificar que venhas sempre um número inteiro.
Use assim:
$id = (int) $_GET['id'];


text:
Q: Take a set $S$ which has 6 vectors, and $S$ is a subset of $\mathbb{R}^5$. Why is $S$ linearly dependent? I know that for a vector space $\mathbb{R}^5$, $\dim(\mathbb{R}^5)=5$ and thus a basis (b) (linearly independent and $span(b) = \mathbb{R}^5$) of $\mathbb{R}^5$ should have 5 vectors. I do not know how to link ideas together to understand why $S$ is linearly dependent? Thank you! :)

A: Let $v_1,v_2,v_3,v_4,v_5$ be a basis for $R^5$ and $u \in R^5$
If  $v_1,v_2,v_3,v_4,v_5$ forms a basis than there exists real numbers $c_i$ such that
$u=c_1v_1+c_2v_2+c_3v_3+c_4v_4+c_5v_5$
$u=c_1v_1+c_2v_2+c_3v_3+c_4v_4+c_5v_5 \Rightarrow u-(c_1v_1+c_2v_2+c_3v_3+c_4v_4+c_5v_5)=0$
As it can be seen, $v,v_1,v_2,v_3,v_4,v_5$ are linearly dependent because coefficient of $v$ is not $0$


text:
Q: Create attributes from unique values of another features classes category attribute with FME I have a table (say landuse polygons for example) structured as follows:
ID | landuse_category
---------------------
1  | woodland
2  | industry
3  | farmland
4  | woodland
5  | lake
6  | farmland
7  | industry
8  | lake

Now I would like to create attributes from the distinct values (farmland,industry,lake,woodland) of landuse_category to a table districts for example like
ID | farmland | industry | lake | woodland

I succeeded in obtaining the distinct values with a DuplicateFilter with key attribute landuse_category on the Unique port and then create a list of these unique values with a ListBuilder like

Since input data may vary, this is a generic task and thus the attribute values themselves should not be part of the process.
How to create attributes on another table using this list?

A: The simplest way to create the attribute is to use an AttributeManager and use the value of the landuse_category attribute as the name of the new attribute:

When you write that (and I'm using plain CSV format here) the results look like this:

I'm guessing this is what you're looking for. There are two things to consider though...
1) If you want a 0 (or null) value for the other fields, then you could expose those attributes (AttributeExposer) and map them to null (NullAttributeMapper).
2) I'm assuming the output schema is fixed (ie you know the fields are only going to be farmland, industry, lake, woodland). If you are not sure what the fields will be, then you would have to use a Dynamic writer. That's a bit more tricky (I was going to leave it out, but I figure it's worth documenting)...
2a) In the AttributeManager, also create attributes name (as a copy of landuse_category) and fme_data_type (set to your data type, I used fme_char(1))

2b) Add an Aggregator transformer. Set the Generate List option. Call the list attribute and add name and fme_data_type:

btw, you could use this instead of your method to get a schema definition. If you check the output of this you will see a schema defined as a list.
2c) We now need to get the schema definition onto all the features. Do this with a FeatureMerger transformer. Set it up like this with the requestor/supplier set to a constant value (like 1 in my case):

2d) Set the writer to Dynamic mode, using Schema from Schema Feature as the schema source:

Now you have a truly dynamic solution. If a landuse type changed (from farmland to agriculture perhaps) or a new landuse type was added (say urban) or one was deleted, then the workspace will operate automatically without needing to be edited.

A: I want to add another answer here, because I got a fix into the product that makes this easy to do (the first answer is still valid, but this is better).
The AttributePivoter transformer in FME is used for creating pivot tables. Once use of these is to flip the data so that row values become the column headers, which is what we want here.
So, set up a translation in FME, from CSV to CSV, and add an AttributePivoter transformer between the two tables:

Open the AttributePivoter parameters and set it up as follows:

*

*Group Rows By: ID

*Group Columns By: landuse_category

*Attribute to Analyze: landuse_category

*Pivot Summary Statistics Types: Count

*Row Group Summary Line Descriptor: Total

That will rearrange the data and create a schema for use. So, open the parameters for the writer Feature Type. Set:

*

*CSV File Name: The name you want for the output file

*Dynamic Schema Definition: Yes (check box)

*Schema Sources: "Schema From Schema Feature" (only that)

*Attributes to Remove: Grand Total (you'll need to type that in manually)

Go to the User Attributes tab and delete any attributes:

Change the delimiter character for the output (parameter in the Navigator window) if you wish, and you're good to go.
So just one transformer and a little dynamic schema setup. Much easier than FeatureMerger and Aggregator transformers. Because it relies on a small fix to FME, you'll need FME2018.1 or newer (officially that will release in a couple of days I believe) - else you'll end up with a Grand Total attribute that you can't get rid of.


text:
Q: Oracle ORDS Data Service PL/SQL Procedure cannot return more than 32767 Characters to CLOB Out parameter called from Python or Postman
*

*ORDS.DEFINE_HANDLER(

*
 p_module_name    => 'EMRPRJWSTV1.0',

*
 p_pattern        => 'getPriceConfigDetails',

*
 p_method         => 'GET',

*
 p_source_type    => 'plsql/block',

*
 p_mimes_allowed  => NULL,

*
 p_comments       => NULL,

*
 p_source         =>

9.'DECLARE
10.    o_json_clob                CLOB;
11.    v_appname                  VARCHAR2(1000);
15.BEGIN
16.    apps.XXOM_PRJWS_API_PKG.get_price_config_details(i_json_clob => :body_text, o_json_clob => o_json_clob);

*CREATE OR REPLACE PACKAGE BODY APPS.xxom_prjws_api_pkg
20.is

*PROCEDURE get_price_config_details(i_json_clob       CLOB,

*
                                  o_json_clob   OUT CLOB)

*is
24.dbms_lob.append(o_json_clob,to_clob('"item_type_code":"'|| l_line_rec_tbl(j).item_type_code||'",'));
25.dbms_lob.append(o_json_clob,to_clob('"line_number":"'|| l_line_rec_tbl(j).line_number||'",'));

I am calling above procedure from Python/Postman to get the value of o_json_clob, when the size is less than or equal to around 32767 then it is working fine but when size of o_json_clob is going more than 32767 then PL/SQL Procedure throws an error.
However same procedure works fine when called from Oracle SQL Developer. So how do I get value of this clob variable if the size is more than 32767 characters.


text:
Q: parsing a line of text into multiple values This can be very basic question ... I am working with Java.
I am parsing a file in one of my classes. Each line in the file has 3 arguments (currently). I want to use one generic collection to store all the values at once
something like List<String, String, String (and more args if needed)> list = new ..... The number of arguments might increase later.
I am creating arrays right now to separate out individual args but that is not a proper solution. How can I declare a collection like that?

A: use List<List<String>>
Using above collection you can have a List<String> on each index of the List.
To summarize it:
Each List<String> will correspond to a line in that file
and List<List<String>> will correspond to the entire file


text:
Q: How can I keep order of refactors using database refactoring software? I have been trying to use either Liquibase or DBDeploy. I'm more drawn toward Liquibase because of its non-SQL interface (I.E. I can just use JSON or Yaml changesets). However, there is a problem I have with both of these software.
Liquibase Workflow

*

*I create a master changelog. All it does is to includeAll a folder which contains small files with small changesets inside.

*I then create changesets, and prefix them with a number (E.G. a timestamp, or a simple integer like 1, 2, etc).

DBDeploy Workflow

*

*I just start making delta sql files, prefixed by the same strategy as number 2 above.

The problem
Well, the problem is so trivial I'm feeling stupid for asking it, but here it goes. Consider this scenario:

*

*I make a branch to work on my feature, say, adding orders to the system.

*My colleague, Bob, makes his own branch to add products to the system.

*When it comes time to merge, there is no telling whose changesets or delta sqls will run first. This may break the database.

Doesn't this happen to anyone? If so, what's the way to solve it in the PHP land?
Thanks.

A: (I only know liquibase - so my answer is valid only for liquibase)
As the includeAll doc states the files will be run in alphabetical order. So I'd expect that your numbering should be sufficient for the files to be in the right order.
However you will have to synchronize those numbers between you and Bob anyways to find out what has to run first.
We don't use includeAll though. We include files into the master changelog manually. So whoever wants to change the database has to take care of including this into the master changelog. If there are two changes the developer that comes last has to make sure to include/merge his changes at the right place in the master change log.
EDITED - to explain the include mechanism we use
Within development we just flunk the whole database and let liquibase create the database from scratch whenever we change anything (on our development database).
We always checkin the changeset file to our code repository. So with this we track everything that was done in development since we can checkout every version of the changeset and let liquibase create the database with it.
Only when development of the version we are working on (or the sprint) is done. Then we really let the changesets run und let them change the productive database.
Then this cycle is repeated again and again.
This way only the final db changes are tracked with liquibase and not all the tryouts that might take place during development.
During development you could end up changing a table multiple times because you try out different things. You add a column, then realize the whole thing will not work so you remove the column again and add another one. Why would you want to have all these changes in the databasechangelog ? Then it will fill up with unnecessary stuff - just like you were afraid of.
Hope this clears things up. But in the end you might have a total different development approach. So feel free to use liquibase just the way you need it.
There is no reason to fill the databasechangelog table with all the ideas during development. Only when we are done with development and release a version

A: I've used a couple of different migration frameworks - Liquibase, Rails, and something from the C# world called Tarantino. Each used a similar strategy, where changes were recorded in separate files. Each was on a small team (<= 5 developers).
Rails is the most dogmatic about how files are named, and is where I have had the most conflicts due to branches. Most of those conflicts were name based rather than logical conflicts in the database.
In projects using Liquibase, we used a master/include pattern, and developers did their work on branches. Because the file names had a 3 digit sequence numbers plus a brief description (i.e. 009-add-customer0index.xml) we did not have name conflicts. We avoided database level conflict mainly by just talking to each other - daily standups, etc.
We had similar experiences using Tarantino, although it just uses a directory full of files for its migrations. As with Liquibase, we adopted a naming convention that kept things in order. Even when two changesets had the same number, they would have different names, and 99.9% of the time, the order of those two changesets was not dependent on each other.
Just for a datapoint, the project that used Tarantino leveled off with about 400 changesets.


text:
Q: Unable to consume JSON array using Spring RestTemplate Am trying to populate a DTO from a published RESTful URL (simple HTTP GET) by using Spring's RestTemplate HTTP Client.
This is the content of the published JSON that I am trying to consume:
[{"startDate":"2017-01-29","cost":"$50000.00","id":1112,"name":"Porsche"},{"startDate":"2017-03-06","cost":"$27000.00","id":38626,"name":"BMW"}]

My DTO:
class DTO {
    private String startDate;
    private String cost;
    private String name;

    // Getters and Setters
}

My Response Object:
public class Response {
    private static final STRING = "http://www.sample.com/product";

    public static List<Object> getCampaigns() {
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<Object[]> responseEntity = (ResponseEntity) restTemplate.getForEntity(URL, Object[].class);
        Object[] objects = responseEntity.getBody();
        MediaType contentType = responseEntity.getHeaders().getContentType();
        HttpStatus statusCode = responseEntity.getStatusCode();
        return Arrays.asList(objects);
    }

    public void static main (String args []) {
        List<Object> dtos = getCampaigns();
        for (Object dto : dtos) {
            System.out.println(dto.toString());
        }
    }
}

Here's my pom.xml:
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.2.RELEASE</version>
</parent>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
    </dependency>

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>2.8.7</version>
    </dependency>

</dependencies>

When I run the main() method inside Response, I get the following exception:
00:24:14.191 [main] DEBUG org.springframework.web.client.RestTemplate - GET request for "http://www.sample.com/product" resulted in 200 (OK)
Exception in thread "main" org.springframework.web.client.RestClientException: Could not extract response: no suitable HttpMessageConverter found for response type [class [Ljava.lang.Object;] and content type [application/json;charset=utf-8]
    at org.springframework.web.client.HttpMessageConverterExtractor.extractData(HttpMessageConverterExtractor.java:109)
    at org.springframework.web.client.RestTemplate$ResponseEntityResponseExtractor.extractData(RestTemplate.java:917)
    at org.springframework.web.client.RestTemplate$ResponseEntityResponseExtractor.extractData(RestTemplate.java:901)
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:655)
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:613)
    at org.springframework.web.client.RestTemplate.getForEntity(RestTemplate.java:312)

What am I possibly doing wrong?

A: Try this
public class Response {
    private static final String URL = "http://www.sample.com/product";

    public static List<DTO> getCampaigns() {
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<DTO[]> responseEntity = restTemplate.getForEntity(URL, DTO[].class);
        DTO[] objects = responseEntity.getBody();
        MediaType contentType = responseEntity.getHeaders().getContentType();
        HttpStatus statusCode = responseEntity.getStatusCode();
        return Arrays.asList(objects);
    }

    public void static main (String args []) {
        List<DTO> dtos = getCampaigns();
        for (DTO dto : dtos) {
            System.out.println(dto.toString());
        }
    }
}

A: use this jackson library instead
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.8.7</version>
</dependency>


text:
Q: related to fluid mechanics and its velocity variation with respect to area of cross section of pipe through which it's flowing and height if water is drawn from a tank by two pipes of the same diameter and at the same depth such that one pipe ends at some height and the other reaches the ground in which pipe we can collect the water more faster?

A: Not sure about the efficiency, since we don't need to spend any energy to collect the water, so, I assume you want to compare the speed of water collection.
If the horizontal sections of the two pipes had the same length, the speed of collection from the short pipe would be greater, since extending the length of a pipe downward cannot speed it up beyond what is already provided by the gravity.
In addition, provided that the water is collected at the end of a pipe (not at the ground level), collecting from the short pipe will eliminate the initial delay it would take for the water to reach the ground.
If the horizontal section of the short pipe was substantially longer than the horizontal section of the long pipe, more data would be needed to answer this question definitively.


text:
Q: Error al registrar imagenes con MySQL y PHP Estoy intentanto registrar imagenes con PHP a una base de datos MySQL pero me genera un error al momento de enviar los datos. La tabla en la base de datos está apta para recibir imagenes por lo que no creo que ese sea el problema. No sé por qué no se está recibiendo la imagen como tal. Al momento de intentar registrar un archivo .txt por ejemplo el if check funciona bien y me devuelve un mensaje diciendo que ingrese una imagen, pero al ingresar la imagen me tira el error.
Dejo por acá el código y el error que me genera.
View
include_once "../Controller/LlavesControllerv2.php";
<form method="POST" enctype="multipart/form-data">
    <?php RegistrarLlaveController();?>

        Nombre de la llave
        <input class="form-control" id="txtNombre" type="text" name="txtNombre"/>

        Imagen
        <input class="form-control" id="image" type="file" name="image"/>

        <input class="submit-btn" id="btnRegistrarLlave" type="submit" value="Registrar" name="btnRegistrarLlave">

</form>

Model
include_once 'conexion.php';
function RegistrarLlave(){
    $instancia = AbrirBaseDatos();

    if(!empty($_POST['btnRegistrarLlave'])){
        if(!empty($_POST['txtNombre'])){
            $check = getimagesize($_FILES["image"]["tmp_name"]);
            if($check !== false){
                $nombre = $_POST['txtNombre'];
                $image = $_FILES['image']['tmp_name'];
                $imgContent = addslashes(file_get_contents($image));

                if (!empty($_FILES['image']['tmp_name'])) {
                    $imagen = addslashes(file_get_contents($_FILES['image']['tmp_name']));
                  } else {
                    $imagen = null;
                  }

                $llave = $instancia -> query("CALL SP_REGISTRAR_LLAVE($nombre, '$imagen');");

                if($llave > 0){
                    echo '
Se ha realizado el registro correctamente
';
                } else {
                    echo '
Ha ocurrido un error
';
                }

            } else {
                echo '
Por favor seleccione una imagen
';
            }

        } else {
            echo '
Debe ingresar un nombre
';
        }
    }

    CerrarBaseDatos($instancia);
}

Controller
function RegistrarLlaveController(){
    $registro = RegistrarLlave();
}

Error

TABLA Y SP, acá el nombre es un INT porque se recibe un numero como identificador de esa imagen.
CREATE TABLE LLAVES(
    LLAVE_ID INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
    LLAVE_NOMBRE INT NOT NULL,
    LLAVE_IMAGEN LONGBLOB NOT NULL

)ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

DELIMITER //
CREATE PROCEDURE SP_REGISTRAR_LLAVE(
NOMBRE INT,
IMAGEN LONGBLOB
)
BEGIN
    INSERT INTO LLAVES(LLAVE_NOMBRE, LLAVE_IMAGEN) VALUES (NOMBRE, IMAGEN);
END//


text:
Q: innerHTML not changing div output I'm trying to display a text area depending on what radio button the user clicks. When the "contest" function is commented out, the newsletter part works fine. But when the contest function is included, the newsletter does not work. I've tried debugging but I can't seem to find an issue. I've tried using different forms but it doesn't change the problem.
My HTML:

function newsletter() {
 var response = "";
 if(document.getElementById("yes").checked) {

  response += "
Enter Your Address:
";
  response += '<input type="text" id="address">
';

  var output = document.getElementById("isChecked");
  output.innerHTML = response;
 }
}

function contest() {
 var resp = "";
 if(document.getElementById("answer").value == "Y") {
  resp += "
Enter your credit card information to verify age ($0.00 charge)
";
  resp += "
";
  resp += '<input type="text" id="first4" size="4" maxlength="4">';
  resp += "-";
  resp += '<input type="text" id="second4" size="4" maxlength="4">';
  resp += "-";
  resp += '<input type="text" id="third4" size="4" maxlength="4">';
  resp += "-";
  resp += '<input type="text" id="fourth4" size="4" maxlength="4"';

  var out = document.getElementById("contestOutput");
  out.innerHTML = resp;
 }
}
body {background-color: pink; }

Magnificant Music!

Welcome Blue Note Records visitors! On this site, you can enter your information to recieve a card sent every month informing you about the lastest releases on your favorite record label, and a chance to enter a contest that could win you a brand new instrument of your choice!

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

Personal Information

    First Name:
    <input type="text" id="firstName">

    Last Name:
    <input type="text" id="lastName">

    Middle Initial
    <input type="text" id="middleInit">

   </fieldset>

   <fieldset>

Do you want to recieve a newsletter?

    <input type="radio" name="news" id="yes">Yes

    <input type="radio" name="news" id="no">No

    <button type="button" onclick="newsletter();">Submit</button>

   </fieldset>

   <fieldset>

Would you like to enter the contest for a brand new instrument of your choice (Y / N)? (18 yrs old minimum)

    <input type="text" size="1" id="answer">

    <button type="button" onclick="contest();">Submit</button>

   </fieldset>
  </form>

A: The answer, provided by @jcubic, was the error. Closing the tag fixed the error encountered.


text:
Q: Error in Linear Regression Model , it doesn't works on dataframes . How to fix this? I was trying to build a Linear Regression model from scratch. I was following a tutorial.
class LinearRegression:

    def __init__(self, learning_rate=0.001, n_iters=1000):
        self.lr = learning_rate
        self.n_iters = n_iters
        self.weights = None
        self.bias = None

    def fit(self, X, y):
        n_samples, n_features = X.shape

        # init parameters
        self.weights = np.zeros(n_features)
        self.bias = 0

        # gradient descent
        for _ in range(self.n_iters):
            y_predicted = np.dot(X, self.weights) + self.bias
            # compute gradients
            dw = (1 / n_samples) * np.dot(X.T, (y_predicted - y))
            db = (1 / n_samples) * np.sum(y_predicted - y)

            # update parameters
            self.weights -= self.lr * dw
            self.bias -= self.lr * db

    def predict(self, X):
        y_approximated = np.dot(X, self.weights) + self.bias
        return y_approximated

This works really good on inbuilt sklearn's dataset but gives an error when I try it on dataframe. In most cases the error is related to fit method and the shape of weights and bias. What is wrong ? Is there any better implementation available ?


text:
Q: What is the proper setup for PG user for web application We have a web app that detects if the DB does not exist and creates it.
Users like it, but my thought is that such user has too much privileges.
I would optimally propose to change the DB creation screen of the app to supply 2 sets of credentials - one that will be used for creating DB initially and not stored permanently (e.g. 'postgres' role)  and the other that will be used by the web app and stored in config file (e.g. 'webapp').
Furthermore, 'webapp' will need to be able to 1) add new and 2) modify existing tables, procedures, and functions (the web app automatically updates the schema as required)
So some of the questions I have are:

*

*What are some of the best practices in above scenario when using PostgreSQL 9.x?

*Should the DB created be owned by 'webapp' role or should it be owned by 'postgres' and I just grant 'webapp' the necessary privileges. In case of latter, would newly added objects be owned by 'webapp' and should I avoid that?

*What are some of the approaches users in community are currently using?

A: The best way, really, is for the web app to have no right to create or modify tables at all. It should only have the rights to do what it needs to do to perform its day to day functions, not administration.
In particular, the web app must not run as a superuser and should preferably not own the database or tables.
If the webapp has built-in administration functions for changing tables when it's upgraded, etc, it should do so via a separate set of credentials and allow you to be prompted to enter those credentials each time you perform an upgrade. Or let you create the file with the admin credentials, run the upgrade, and delete it again.
If you can't fix the webapp to use different credentials for schema changes, then it might as well be the owner of the database and tables. Just don't make it a superuser!
If you can fix the app so it uses different credentials for schema changes, then its regular non-schema-change user should not own the tables or database. It should have only CONNECT and TEMPORARY rights on the database, USAGE rights on the schema(s), and the required rights on each table GRANTed to it. Just don't forget to REVOKE ALL FROM public ON DATABASE mydb; and REVOKE ALL FROM public ON SCHEMA public;.


text:
Q: Lexical this and objects How can i extract the inner id? I know that it's possible to change the fat arrow function to standart function or instead of this.id to use obj.id.
But is there any other way to get the inner id while using the fat arrow function?
var obj = {
  id: 1,
  cool: () => {
    console.log( this.id );
  }
};
var id = 2;
obj.cool(); // 2

A: Arrow function does not create a new scope and uses parent constructor's scope. in this case parent is Windows constructor Function so this refers to window and there is no way except the ones you listed
var obj = {
  id: 1,
  cool() {
    console.log( this.id );
  }
};


text:
Q: Insert into with conditional constant I wanted to make something like:
insert into Table(a, b, c)
select a, b, 1 from OtherTable
where a > 0

But where c would be a value of an Enum based on a certain condition of the where clause.
I wish the final result would be something similar to (even if this doesn't work):
insert into Table(a, b, c)
select a, b, x from OtherTable, YetAnotherTable
where a > 0 AND (IF a=b THEN x = 'Enum1' ELSE x = 'Enum2' ENDIF)

Do you think something like this is possible in a single statement?

A: You could use a case expression:
insert into Table(a, b, c)
select a,
       b,
       CASE WHEN a = b THEN 'Enum1' ELSE 'Enum2' END
from OtherTable, YetAnotherTable
where a > 0


text:
Q: Php get url string value Hi all i am new in php and i have some question how to do that.
I have URL like this
http://localhost/royale/?lang=am

And I need to take "am"
I search and find this
$_SERVER['QUERY_STRING']

but it return "lang=am"

A: you can get the value as..
<?php
      $lang = $_GET['lang'];
      echo $lang;
?>

or if you are not sure about the value of parameter, then check it first by..
 <?php
      if(isset($_GET['lang'])){
         $lang = $_GET['lang'];
          echo $lang;
      }
 ?>

A: If all you want is the value of "lang", $lang = $_GET['lang']; // this is 'am'

A: how about:
// Check first if lang is on the URL query string
if (isset($_GET['lang'])) {
    // If so, then do what you want with $_GET['lang']
    $lang = $_GET['lang'];
    echo  $lang;
}

A: The parse_url with the parse_str function will take a URL string and create an associative array from the arguments
$parts = parse_url($url);
parse_str($parts['query'], $query);
echo $query['lang'];

Answer taken from here https://stackoverflow.com/a/11480852/3944304 (I tried linking to it before, but was told my answer was trivial)

A: I'm amazed that nobody has mentioned the article in the PHP docs about $_GET. This is what you are looking for, OP.
$_GET @ PHP docs


text:
Q: Is there an MVC /EF best practice design for UI workflow for CRUD of a new object with a simple 2 table master/detail database The scaffolding in Visual studio 2012 with MVC 4 and EF 5 provides for entry of individual records from separate controllers, but each edit and insert of related tables are separate.
What is the best practice in MVC for a single page that allows a user to enter both master and detail on the same form.  Do I have to manipulate objects in the controller or is there some way that EF can handle it for me?
Seems like a very basic requirement.

A: There's several ways to roll this, the easiest is probably just using ajax requests and partial views to load the child records.
Flow is basically create your master. Save it. Once saved, enabled entry of child records. When saved they simply are ajax post requests back to an MVC controller that saves the data and returns the most up to date JSON data. The javascript code that triggered your ajax call then in turn binds that new data to a list - either by manually creating the entry or using something like knockout.js
Read only display:
http://www.devcurry.com/2013/04/master-details-knockout-aspnet-mvc.html
CRUD operations:
http://code.msdn.microsoft.com/Detail-CRUD-Operations-fbe935ef


text:
Q: Electron - neutrino scattering effective Lagrangian The electron and neutrino can interact through an intermediary Z boson, via the Lagrangian:
$$ L= \frac{1}{2} \partial_\mu \phi_Z \partial^\mu \phi_Z - \frac{1}{2} m_Z ^2 \phi_Z ^2 -g_{\nu} \phi_Z \bar{\psi_\nu} \psi_\nu - g_e \phi_Z \bar{\psi_e} \psi_e .$$
Apparently one can come up with an expression for an effective Lagrangian using the path integral formalism by integrating over the bosonic degree of freedom and obtain the following expression:
$$L_{effective} = \frac{g_\nu g_e}{m_Z ^2} \bar{\psi_\nu} \psi_{\nu} \bar{\psi_e} \psi_e .$$
I don't know how to go about trying to prove this. I'm fairly new to the path integral formalism and I don't really have the intuition for this.
Which quantity should I start by looking at? I suspect something to do with the generating functional, but I'm not certain how to start.
EDIT: I suppose what I'm asking is this: forgetting for the moment the $e,\nu, Z$, how would one go about deriving an effective Lagrangian for a problem with 3 arbitrary particles interacting via a similar Lagrangian, at the appropriate energy scale?

A: Okay, let's give it a try. $SU(2)$ sector of Standard Model Lagrangian is rather involved, so we will take a look at something simpler. Neutron-proton interaction comes to my mind. In low energy limit it is mediated by a massive scalar particle — a pion. We will be very qualitative about this, in reality there are a lot of details.
Lagrangian will look something like this:
$$ \mathcal{L} = \frac12 \partial^\mu \pi \partial_\mu \pi - \frac12 m_\pi^2 \pi^2 - g \overline{\psi}\pi{\psi}+ \mathcal{L}_{Dirac} $$
Basically, what you are trying to do is the following:
$$ \mathcal{Z}_{eff} = \langle \mathcal{Z} \rangle_\pi  $$
i.e., produce an expression for the partition function that would look the same as fundamental one in the low energy limit. You should remember that partition function contains an exponent of the action which basically does the job of gluing all of the Lagrangian's operators in a more complicated ones. In the end, if you expand this exponent, you will get an infinite series of all possible interactions of the theory written explicitly. We won't do that, but we will imagine.
Among them there will be the operators we're hunting for:
$$ \hat{\mathcal{O}}_1 =\overline{\psi}(x) g \pi(x) \psi(x) $$
$$ \hat{\mathcal{O}}_2 =\overline{\psi}(x) g \pi(x) \psi(x) \cdot \overline{\psi}(x') g \pi(x') \psi(x') $$
As we are going to average over the scalar particle, we will assign its field a zero vacuum expectation such that by itself it won't contribute:
$$ \langle \hat{\mathcal{O}}_1 \rangle_\pi = \overline{\psi}(x) g \langle\pi(x)\rangle \psi(x) \approx 0 $$
which means that these particles won't be produced. Then,
$$ \langle \hat{\mathcal{O}}_2 \rangle_\pi = g^2 \overline{\psi}(x) \psi(x) \cdot \langle \pi(x) \pi(x') \rangle \cdot \overline{\psi}(x') \psi(x') $$
Here we got a well-known average — the propagator. For simplicity et's go into Fourier space from now on. Here is its Fourier transform:
$$ \tilde{S}_\pi (p) = \frac{1}{p^2 -m_\pi^2}$$
As the energy scale is too small to produce a real particle, we take the lowest order contribution from this operator, which will be
$$ \tilde{S}_\pi \approx -\frac{1}{m_\pi^2}$$
And our operator becomes
$$ \langle \hat{\mathcal{O}}_2 \rangle_\pi = -\frac{g^2}{m_\pi^2} \overline{\psi} \psi \overline{\psi} \psi $$
Next, by evaluating all higher-order averages of $\pi$ and rearranging the series, we can in principle gather a new exponent with an effective action.


text:
Q: Rendering more than one RadioButton.Group in react native cannot be treated separately in my application i have two arrays as follow:
const items =[
    {
        "id": 1,
        "groupId": 1,
        "name": "product1",
        "price": 10
    },
    {
        "id": 2,
        "groupId": 1,
        "name": "product2",
        "price": 10
    },
    {
        "id": 3,
        "groupId": 2,
        "name": "product3",
        "price": 10
    },
    {
        "id": 4,
        "groupId": 2,
        "name": "product4",
        "price": 10
    }
];

  const category = [
        {
            "name": "optional",
            "id": 1,
            "type": 1
        },
        {
            "name": "required",
            "id": 2,
            "type": 1
        },
    ]

So, what I am doing I take the category name from array category then after displaying the name of category I am rendering the item that belong to that category from the items array when category.id = items.groupId
I did the following to achieve that:
 {items.filter(product => product.groupId === category.id).map(b => {

   return (<View >
              <RadioButton.Group
                  key={b.groupId}
                  value={value}
                  onValueChange={value => { addToOrder(value) }}

                >
                <View>
                     <RadioButton.Item
                         key={b.id}
                         mode='android'
                         label={b.name}
                         value={b}
                      />
                       <Text>${b.price}</Text>
                 </View>
               </RadioButton.Group>
            </View>
        )
     })
 }

So the result was as expected it gave two groups of radio buttons

Results looks like:
[ ] refer to the circle of the button
optional
  - porduct1 $10  [ ]
  - porduct2 $10  [ ]

required
  - porduct3 $10  [ ]
  - porduct4 $10  [ ]

However,
the problem I am facing is that  when i check on of the item in the first group and then i check another item in the second group the value in first group is unchecked. I spent several hours trying to solve it but I'm unable to make it work.
the library for radioButtons is  RadioButton from 'react-native-paper';
I will appreciate any help. thanks


text:
Q: How do DNS servers work? I know that a domain name is resolved by a DNS server to an IP address, which is then used to reach the requested server. I'm slightly embarrassed that I don't know some of the details of how this works.

*

*In order for my computer to ask the DNS service to resolve a domain, the DNS server must be known by my computer. I never explicitly told my computer about any DNS servers, so how does it know which DNS server it should use? Is it the ISP that pushes this information to my computer somehow?

*For that matter, where are these DNS servers located? Does my ISP have some DNS servers running somewhere which are used by all it's (the ISP's) customers?

*The DNS server my computer uses must know all domains in order to be able to resolve them, how are it's records updated/maintained?

*Is there some central entity/registry/... that feeds a DNS server changes that have occurred?

*If I order a domain name somewhere, the seller has to establish a connection between an IP address and the domain name it sold to me. How are all DNS servers updated to know about this link? So in other words, what actions does the seller take to inform 'the internet' where this domain now points to?
I know this seems like a bunch of questions but I think they're just different aspects of the same story. Can somebody tell me how this all works together?

A: Your computer has a list of DNS servers that it can query for further information.  On a unix or linux system, this is stored in /etc/resolv.conf.  In Windows, it's configurable in your network settings.  Often, your DNS server will be supplied by your DHCP server, possibly along with other settings like default domain, proxy servers, etc.
The location of the DNS server you use doesn't matter much.  As long as your computer has an IP address and a working default route (i.e. you can ping the DNS server), you should be able to make DNS queries.
DNS servers don't have to know "all" domains.  They only need to know who is "authoritative", which it learns from a set of "root" servers.  Each DNS server has a list of "root" servers, and this list changes infrequently.  On one of my DNS servers, there are 18 root servers configured, and this configuration came when I installed the DNS server two years ago, and if the list of root servers has changed since then, enough of them are accessible that I haven't noticed it.
My DNS server, when asked to resolve a domain it doesn't know, makes a query to a root server to find out what other DNS server is authoritative for the domain.  The response it gets may contain additional "NS" records and be marked non-authoritative, in which case my DNS server knows that it has to "follow the chain" and make a new query to a new server.  Eventually, it finds a DNS server that provides authoritative information, and queries can be made that are not just NS records.  A (address) and MX (mail exchange) are of course the two most common.
Each TLD (top-level domain) like COM, NET, ORG, CA, UK, etc maintains its own registry of subdomains.  (A "subdomain" is any domain within another domain, so "example.com" is a subdomain within "com", and "com" is even a subdomain within ".", the "root".)  The rules for each registry apply only to the TLD it administers -- that is, there's a completely different set of criteria for each country-code TLD, and the "generic" TLDs are administered by different organizations with different policies.  But they all maintain DNS servers for their TLD, which, from a command line, you can see using basic DNS query tools:
[ghoti@pc ~]$ host -t ns ca.
ca name server c.ca-servers.ca.
ca name server e.ca-servers.ca.
ca name server z.ca-servers.ca.
ca name server a.ca-servers.ca.
ca name server f.ca-servers.ca.
ca name server sns-pb.isc.org.
ca name server j.ca-servers.ca.
ca name server k.ca-servers.ca.
ca name server tld.isc-sns.net.
ca name server l.ca-servers.ca.
[ghoti@pc ~]$ host -t ns info
info name server c0.info.afilias-nst.info.
info name server d0.info.afilias-nst.org.
info name server b2.info.afilias-nst.org.
info name server b0.info.afilias-nst.org.
info name server a2.info.afilias-nst.info.
info name server a0.info.afilias-nst.info.
[ghoti@pc ~]$

When you buy a domain from a registrar (of which there are many), that registrar submits information about the domain to the registry (of which there is just one per TLD).  It is the responsibility of each registry to maintain the list of registered domains within their TLD, and maintain the DNS servers that provide this info to other servers.

A: DNS server work as a protocol is a set of rule for exchanging data on internet within private network like TCP/IP protocol suit. It simply turns the user friendly domain into internet protocol. It may be any domain name purchased by site owner from any reliable domain provider such as domainia or else. Let's take a domain's example as "myweb.com" which in turn will be converted in IP like 71.12.252.1 that will be for computer to be recognized over the network.


text:
Q: Drag and Drop local file with autoIt and selenium i am trying to drag and drop a file from local machine to container area in my web application.
Html of the drop area

            Select file(s) and drag here to upload

My code
Driver.FindElement(By.XPath("//*[@class='abcde']")).click();
AutoIt.AutoItX.WinActive("Open");
AutoItX.Send(@"C:\Users\1234\Desktop\upp.txt");
Thread.Sleep(1000);
AutoItX.Send("{ENTER}");

Drag and Drop doesn't work with this code


text:
Q: Insert into one table, from two table without join I'm in Microsoft Sql Server
I have three table.
The first table have just a field with ID_CONTACT.
CREATE TABLE USERS_CONTACT(
 [ID_CONTACT] [int] NOT NULL PRIMARY KEY
)

The second table have a field with UNIQUE_CODE
CREATE TABLE TMP_UNIC_CODE_RECETTE(
 [UNIC_CODE] varchar(10)
)

I have a third table with two field:
> ID_CONTACT, UNIC_CODE

CREATE TABLE UNIC_CODE_RECETTE(
 [ID_CONTACT] [int] NOT NULL PRIMARY KEY,
 [UNIC_CODE] varchar(10)
)

This two table haven't join.
I need to push on the third table the ID_CONTACT and the UNIC_CODE randomly
I have try this:
INSERT INTO UNIC_CODE_RECETTE
(ID_CONTACT, UNIC_CODE)
SELECT ID, (SELECT REAC FROM TMP_UNIC_CODE_RECETTE )
FROM USERS_CONTACT

But it doesn't work.
Can you help me for the query ?
Thanks

A: You can't return more than one value from a subquery the way you are trying to use it. You can use top 1 to do that though, and if you order by newid() it will give you an seemingly random value.
insert into unic_code_recette (id_contact, unic_code)
select
    uc.id_contact
  , unic_code  = (
    select top 1
        unic_code
      from tmp_unic_code_recette
      order by newid()
      )
  from users_contact uc


text:
Q: R: Function for calculations based on column name I have a data frame which looks like this (just a subsample)
Year <- c(1990,1991,1992)
Country_1_v1 <- c(0.2,0.3,0.4)
Country_1_v2 <- c(0.6,0.5,0.1)
Country_2_v1 <- c(1.2,1.4,1.1)
Country_2_v2 <- c(1.7,1.3,1.2)

So, I have two columns (v1, v2) for both countries (i.e. 4 columns) over a specific time period. Now, I want to calculate v1/v2 for EVERY country. Since I have 25 countries I do not want to use mutate.
Is there a quick way to build a function that does it for me? I am not really familiar with functions and would appreciate any help!
Right now my column names are "'Country Name'.x" for v1 and "'Country Name'.y" for v2.
Thanks!

A: Transforming TO's vectors into a data frame:
dat <- data.frame(Year = c(1990,1991,1992),
                  Country_1_v1 = c(0.2,0.3,0.4),
                  Country_1_v2 = c(0.6,0.5,0.1),
                  Country_2_v1 = c(1.2,1.4,1.1),
                  Country_2_v2 = c(1.7,1.3,1.2))

You can then make use of tidyverse's flexible approach for pivoting. You need to create a template for that that tells us how you would want to transform the old variables into the new ones (I'm curious if there's a solution that can directly transform the data into pivot_longer without the template).
template <- data.frame(.name  = colnames(dat)[-1],
                       Country = c("Country_1", "Country_1", "Country_2", "Country_2"),
                      .value = c("v1", "v2", "v1", "v2"))

This looks like:
         .name   Country .value
1 Country_1_v1 Country_1     v1
2 Country_1_v2 Country_1     v2
3 Country_2_v1 Country_2     v1
4 Country_2_v2 Country_2     v2

So each of your original columns is split up into a) a country column and b) in two separate va and v2 columns.
Now you can do your calculation and transfer back to wide format.
library(tidyverse)
dat %>%
  pivot_longer_spec(template) %>%
  mutate(ratio = v1/v2) %>%
  pivot_wider(names_from = Country,
              values_from = c(v1, v2, ratio),
              names_glue = "{Country}_{.value}")

which gives:
# A tibble: 3 x 7
   Year Country_1_v1 Country_2_v1 Country_1_v2 Country_2_v2 Country_1_ratio Country_2_ratio
  <dbl>        <dbl>        <dbl>        <dbl>        <dbl>           <dbl>           <dbl>
1  1990          0.2          1.2          0.6          1.7           0.333           0.706
2  1991          0.3          1.4          0.5          1.3           0.6             1.08
3  1992          0.4          1.1          0.1          1.2           4               0.917

Note the columns are not in the same order as in the original data frame anymore. But this could be solved with a relocating pipe.


text:
Q: Prove Inverses not need be Unique if Associativity fails Let $M=\{x, y, z\}$ be a set and let $\circ$ be a binary operation on $M$ such that the identity element is $x$ and $y \circ y = x = y \circ z$. Prove that inverses need not be unique if associativity fails given the multiplication table below.
$x \circ x = x, x \circ y = y, x \circ z = z$
$y \circ x = y, y \circ y = x, y \circ z = x$
$z \circ x = z, z \circ y = x, z \circ z = x$

A: Associativity fails if you consider $ y \cdot z \cdot z$. We have $ (y \cdot z)\cdot z = x \cdot z = z$, but on the other hand $ y \cdot (z \cdot z) = y \cdot x = y$. So this is not a group, and inverses need not be unique.


text:
Q: How to prove that electric field on that base of hemispherical shell is perpendicular at all points? I'm asked about the direction of electric field at point $p_1$ and $p_2$
This is quite understandable that electric field points upwards at $p_1$ but I'm not able to digest that field at $p_2$ also points upwards
Is there any proof for this result that field at the base is upwards at all points

A: This feels a bit homework-like, so I'll just give some hints.  My answer also assumes that the hemispherical shell is uniformly charged, which wasn't stated explicitly.
Suppose there was a horizontal component to the field at $P_2$, pointing outwards from the center of the "base".  This would mean that if we took the hemisphere and inverted it (so that it was concave side down), there would still be a horizontal component to the field.  And if we put the original hemisphere and the inverted hemisphere together to form a full sphere, their combined field would have a horizontal component.
Why is this a contradiction?


text:
Q: Acces to Assets file in android application I have got a problem with my application.
I try to access the Assets folder and download some PDF files in a directory.
When i try the code on my galaxy S9 (API 28) it is working just fine.
But when i try the code on my Galaxy S2 tab (API24) nothing happen.
I use this code to access and download the pdf files :
        public void copyAssets(Context context)
        {
            DownloadComplete = false;
            Log.d("tag", "Here 1 ?");
            AssetManager assetManager = context.getAssets();
            Log.d("tag", "Here 2 ?");
            String[] files = null;
            Log.d("tag", "Here 3?");
            try
            {
                files = assetManager.list(resAventure + "/");
                Log.d("tag", "Here  4?");
            } catch (IOException e) {
                Log.d("tag", "Failed to get asset file list.", e);
            }
            if (files != null) for (String filename : files)
            {
                Log.d("tag", "Here 5?");
                InputStream in = null;
                OutputStream out = null;
                try {
                    Log.d("tag", "Here 6?");
                    in = assetManager.open(resAventure + "/" + filename);
                    out = new FileOutputStream(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Download/Escape/" + resAventure + "/" + filename);
                    copyFile(in, out);
                    Toast.makeText(getApplicationContext(), "Téléchargement effectué sur l'appareil", Toast.LENGTH_LONG).show();
                    DownloadComplete = true;

                } catch(IOException e) {
                    Log.d("tag", "Failed to copy asset file: " + filename , e);
                }
                finally
                {
                    if (in != null)
                    {
                        try
                        {
                            in.close();
                            in = null;
                        } catch (IOException e)
                        {
                            Log.d("tag", "Failed A", e);
                        }
                    }
                    if (out != null)
                    {
                        try {
                            out.flush();
                            out.close();
                            out = null;
                        } catch (IOException e)
                        {
                            Log.d("tag", "Failed B", e);
                        }
                    }
                }
            }
        }
        public  void copyFile(InputStream in, OutputStream out) throws IOException
        {
            byte[] buffer = new byte[1024];
            int read;
            while((read = in.read(buffer)) != -1){
                out.write(buffer, 0, read);
            }
        }

In API28 everything is OK. But in API24 i only have in the log :
D/ViewRootImpl@45de4c3[documents]: ViewPostImeInputStage processPointer 1
D/tag: Here 1 ?
Here 2 ?
Here 3?
D/tag: Here  4?
D/ViewRootImpl@45de4c3[documents]: ViewPostImeInputStage processPointer 0

Is there a difference between the two API for the ASSETS FOLDER ?
I don't understand why it's working only once...
Can somoene help me please ?

A: I have found it.
I replace :
     files = assetManager.list(resAventure + "/");
by
     files = assetManager.list(resAventure);


text:
Q: How to get SQL Server process ID with C# On my Windows Server 2008 I have local instance of SQL Server 2008 (or later 2012.) The server also has IIS configured to run ASP.NET web applications that connect to that SQL server to do basic SELECT, INSERT, UPDATE, DELETE operations.
I also have a Windows service application that I wrote in C# that runs on the same server. I want to add a function to it that checks CPU usage on the SQL Server process. I can do so knowing its PID.
My question is, how to get the process ID of the SQL Server process?

A: Try this
select SERVERPROPERTY('processid'),SERVERPROPERTY('productversion')

you can check in Task Manager as follow

A: Instead of PID just use Process.GetProcessesByName Method.

A: using System.Diagnostics;   //at the top of your class

Process[] processlist = Process.GetProcesses();
foreach(Process theprocess in processlist){
Console.WriteLine("Process: {0} ID: {1}", theprocess.ProcessName, theprocess.Id);
}

Hopefully that gets you started.

A: To get the process ids of SQL Server instances in C#
var ProcessId = Process.GetProcesses()
                        .Where(P => P.ProcessName == "sqlservr")
                        .Select(P => P.Id);


text:
Q: How can i export a chart and multiple rows from an excel sheet to pdf I have an organogram chart in excel and few rows based on which this organogram chart is constructed. Both the chart and data rows are in the same worksheet.
I need to get this chart printed on the upper half of the pdf and the data rows just below the chart.
I have figured out how to get both chart and data rows printed individually in the pdf but i am unable to figure out how to get the data rows printed below the chart on the same page.

A: Select everything you want to be exported. Select Right Click / Set Print Area. This way you should be able to export what you have selected explicitly.
If you have difficulty printing everything on one page, play around with Scaling properties on the Print Preview page and try exporting again.


text:
Q: Devise signin stopped working after upgrading devise(2.2.2 -> 3.2.4) and rails(3.2.13 -> 4.1.0) I just migrated my rails app from
Rails3.2.13/devise2.2.2 ---> Rails4.1.0/devise3.2.4

I made change in devise.rb
config.pepper --> config.secret_key

But now I am not able to login in my app using existing password. I have to reset password and after then everything works fine. I think this should be related to encryption done for the password.
What other change I need to do , so that users of my app can use existing password ?


text:
Q: .tmLanguage.json RegEx expression not working/leads to no syntax highlighting I want to highlight everything after "print" as a string, the problem is that this leads to no highlighting even though the regex, in theory, should work.
As an example replacing "match": with "begin":"somestring" and typing somestring into vscode, works.
This is the JSON for the specific section:
"afterprint": {
            "patterns": [
                {
                    "name": "string.quoted.double",
                    "match": "(?<=print)(?s)(.*$)"
                }
            ]
        }

regex101.com example/test

A: I have managed to get this working on my side by removing the (?s), I am unsure why this is the case, maybe a bug or restricted regex. Anyways it solves your question, as everything after print gets highlighted
"afterprint": {
            "patterns": [
                {
                    "name": "string.quoted.double",
                    "match": "(?<=print)(.*$)"
                }
            ]
        }

Just to mention, other regex hasn't worked for me as well in foo.tmLanguage.json I have still not solved this "mystery".


text:
Q: How to add an image to a Code Generated MSWord with C# I'm using this code to generate a word archive, this work fine:
public void AddParagraph(string text, string styleName = null)
{
  Paragraph paragraph = _document.Content.Paragraphs.Add();
  if (styleName != null)
  {
    paragraph.Range.set_Style(_document.Styles[styleName]);
  }
  paragraph.Range.Text = text;
  paragraph.Range.InsertParagraphAfter();
}

but I also need to add an image next to the generated paragraph, that image is a file in the documents path, any idea of how can I that?

A: I know you are using standard word libs. This will limit your ability to run on a machine that does not have MS office installed. I can highly recomend you to use NovaCode DocX
It is easy to use and very reliable as well. You can use the DocX.AddImage() for this purpose.
// Create a .docx file
using (DocX document = DocX.Create(@"Example.docx"))
{
  // Add an Image to the docx file
   Novacode.Image img = document.AddImage(@"Donkey.jpg");

   // Insert an emptyParagraph into this document.
   Paragraph p = document.InsertParagraph("", false);

  #region pic1
  Picture pic1 = p.InsertPicture(img.Id, "Donkey", "Taken on Omey island");

   // Set the Picture pic1's shape
   pic1.SetPictureShape(BasicShapes.cube);

   // Rotate the Picture pic1 clockwise by 30 degrees
   pic1.Rotation = 30;
    #endregion

   #region pic2
   // Create a Picture. A Picture is a customized view of an Image
   Picture pic2 = p.InsertPicture(img.Id, "Donkey", "Taken on Omey island");

   // Set the Picture pic2's shape
   pic2.SetPictureShape(CalloutShapes.cloudCallout);

  // Flip the Picture pic2 horizontally
   pic2.FlipHorizontal = true;
   #endregion

   // Save the docx file
   document.Save();
}// Release this document from memory.

Source


text:
Q: How to deal with expired URL links when using imread URL? I am working on the face scrub dataset, which has a long list of urls of pictures.
I used a for loop to fetch these photos. However, some of the urls had expired so my matlab code return an error saying 'Unable to determine the file format.' However I think the actual reason is that the url link does not have the image anymore. For example, one of the bad urls is:
http://www.gossip.is/administrator/components/com_n-myndir/uploads/16de47418d69b1c2991731dffaca8a78.jpg
How do I identify and ignore this error so my code can keep working on the rest of the list? I could use R instead if that make solving this problem easier.

A: You can implement a try/catch block to catch (original isnt'it) the error message and skip the image if the link is indeed broken.
When we use the following syntax:
try
   A = imread('http://www.gossip.is/cgi-sys/suspendedpage.cgi');

catch ME

 %// Just so we know what the identifier is.
      ME

end

Matlab first tries to read the image given by the url. If it can't, we ask it to catch the error message (MException actually) and perform some other appropriate action.
The thing is, we need to know what is the exact error message in order to recognize it in the try/catch block.
When I entered the above code, I got the following structure for ME:
 ME =

  MException with properties:

    identifier: 'MATLAB:imagesci:imread:fileFormat'
       message: 'Unable to determine the file format.'
         cause: {0x1 cell}
         stack: [2x1 struct]

Therefore, once we know the exact identifier generating the error we can use strcmp to look for it in the try/catch block. For instance with the following code:
clear
clc

try
   A = imread('http://www.gossip.is/cgi-sys/suspendedpage.cgi');
catch ME
   if strcmp(ME.identifier,'MATLAB:imagesci:imread:fileFormat')

       disp('Image link broken')

   end

   A = imread('peppers.png');
end

imshow(A);

Matlab displays 'Image link broken' and reads peppers.png, as expected.
Hope that helps!


text:
Q: How to split a cell on N number of words? I have a data frame with a column that contains long text, and I would like to split it every 30 words, creating the necessary new rows with exactly the same contents in the other columns. The character solution does not work as I need it to work, and that is why I am posting this different question.
df1<-data_frame(V1=c(1, 2, 3), V2=c('Red', 'Blue', 'Red'), text=c('Folly words widow one downs few age every seven. If miss part by fact he park just shew. Discovered had get considered projection who favourable. Necessary up knowledge it tolerably. Unwilling departure education is be dashwoods or an. Use off agreeable law unwilling sir deficient curiosity instantly. Easy mind life fact with see has bore ten. Parish any chatty can elinor direct for former. Up as meant widow equal an share least', 'Bringing unlocked me an striking ye perceive. Mr by wound hours oh happy. Me in resolution pianoforte continuing we. Most my no spot felt by no. He he in forfeited furniture sweetness he arranging. Me tedious so to behaved written account ferrars moments. Too objection for elsewhere her preferred allowance her. Marianne shutters mr steepest to me. Up mr ignorant produced distance although is sociable blessing. Ham whom call all lain like.', 'Did shy say mention enabled through elderly improve. As at so believe account evening behaved hearted is. House is tiled we aware. It ye greatest removing concerns an overcame appetite. Manner result square father boy behind its his. Their above spoke match ye mr right oh as first. Be my depending to believing perfectly concealed household. Point could to built no hours smile sense.Breakfast agreeable incommode departure it an. By ignorant at on wondered relation. Enough at tastes really so cousin am of. Extensive therefore supported by extremity of contented. Is pursuit compact demesne invited elderly be. View him she roof tell her case has sigh. Moreover is possible he admitted sociable concerns. By in cold no less been sent hard hill.' ))

I have tried the following:
df <- df1%>%
      mutate(text = strsplit(as.character(text), "\\W+{30}")) %>%
      unnest(text)

But it just doesn't work.

A: Here is one option with separate_rows and then paste it together
df1 %>%
   separate_rows(text) %>%
   group_by(V1) %>%
   group_by(V2, grp = ((row_number()-1) %/%30) + 1, add = TRUE) %>%
   summarise(text = paste(text, collapse= ' ')) %>%
   ungroup %>%
   select(-grp)

A: Try this, it worked for me.
str_match_all(text, "(?:\\w+\\W*){30}")


text:
Q: get returning null from coherence server I have some data in my cache database when I do a get on the cache DB, if the key contains alphabets and numbers or a combination of numbers I am able to get the data, if it is a single key with only numerals I am not able to retrieve the data even though I am able to view the data in list.
Map (ele): list
2222222 =
200:20:2:2:1:1:Thu Feb 02 00:00:00 2012:2:Thu Feb 02 00:00:00 2012:Thu Feb 02 00:00:00 2012

GC2 =
200:20:2:2:1:1:Thu Feb 02 00:00:00 2012:2:Thu Feb 02 00:00:00 2012:Thu Feb 02 00:00:00 2012

Map (ele): get GC2
 200:20:2:2:1:1:Thu Feb 02 00:00:00 2012:2:Thu Feb 02 00:00:00 2012:Thu Feb 02 00:00:00 2012

Map (ele): get 2222222
null

When I give only numerals in get, I am getting null.
Any ideas anyone?

A: I figured it out myself,if  we define the key to be of type String and it contains only numerals due to the internal working of the coherence server,it returns null.
in short
key defined as string - key contains alphanumeric - WORKS
key defined as string - key contains only alphabets - WORKS
key defined as string - key contains only numbers - DOES NOT WORK
so what I did was , before putting the data in the cache , I did a check on the key whether it contained only numbers using
if (code.matches("[0-9]+"))

If yes, then store the key as an integer, else store it as a string.
Now I am able to retrieve the values for all cases.
ANOTHER SOLUTION -
Instead of storing the key as an integer, even if it is a numeral stored as a string then while doing get
get \ 111
this retrieves the correct values too


text:
Q: Why does my bitmap on the canvas appear below the background drawable? I have a SurfaceView where I'm setting a background color and an image like so:
BitmapDrawable tiledBackground = new BitmapDrawable(BitmapFactory.decodeResource(getResources(), R.drawable.background));
tiledBackground.setTileModeX(Shader.TileMode.REPEAT);
tiledBackground.setColorFilter(0xaacceeff, PorterDuff.Mode.DST_OVER);
this.setBackgroundDrawable(tiledBackground);

I also have an animation thread where I'm drawing an image (successively adjusting its x coordinate so that it appears to move to the left). The background image is a transparent PNG and so some parts of it are transparent. It appears that the image I'm drawing from the thread appears below the background drawable on the SurfaceView. How can I have it appear on top of the background? I'm drawing the image like so:
private void doDraw(Canvas canvas) {
    canvas.drawColor(Color.BLACK);
    canvas.drawBitmap(missile, x, getHeight() - 95, paint);
    canvas.restore();
}

missile and paint are initialized in the constructor of the thread to:
missile = Bitmap.createBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.missile));
paint = new Paint();

A: Each call to doDraw should draw everything you want to be displayed, including the background.
// Add to initializer
tiledBackground = new BitmapDrawable(BitmapFactory.decodeResource(getResources(), R.drawable.background));
tiledBackground.setTileModeX(Shader.TileMode.REPEAT);
tiledBackground.setColorFilter(0xaacceeff, PorterDuff.Mode.DST_OVER);

private void doDraw(Canvas canvas) {
    canvas.drawColor(Color.BLACK);
    // Create a rectangle (just holds top/bottom/left/right info)
    Rect drawRect = new Rect();

    // Populate the rectangle that we just created with the drawing area of the canvas.
    canvas.getClipBounds(drawRect);

    // Make the height of the background drawing area equal to the height of the background bitmap
    drawRect.bottom = drawRect.top + tiledBackground.getBitmap().getHeight();

    // Set the drawing area for the background.
    tiledBackground.setBounds(drawRect);

    tiledBackground.draw(canvas);
    canvas.drawBitmap(missile, x, getHeight() - 95, paint);
    canvas.restore();
}


text:
Q: Generate .bat file for a spring project using maven in eclipse I have done project with spring and maven in eclipse. Now I want to run the application without eclipse means I want to run java.class file from .bat file. How can I do this?

A: If you want to create a .bat file, then you probably need to create a shaded jar containing all of your dependencies (an "Über Jar"). This is done with the mvn shade plugin by adding something like this to your pom.xml:
 <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-shade-plugin</artifactId>
    <version>2.1</version>
    <executions>
      <execution>
        <phase>package</phase>
        <goals>
          <goal>shade</goal>
        </goals>
        <configuration>
          <transformers>
            <transformer
              implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
              <mainClass>com.foo.bar.Main</mainClass>
            </transformer>
          </transformers>
        </configuration>
      </execution>
    </executions>
  </plugin>

Then, in your .bat file, you can execute your Java application using
java -jar myJarFile.jar

A: To create a .bat file for running your application you can use appassembler-maven-plugin which is exactly for such purposes. It can create .bat as well as .sh scripts to run your application. Furthermore you can pack the resulting files into a zip archive which contains your application with the scripts the needed libs as well as configuration files.

A: With the Maven goal package you get a runnable archive file. The way you run that file depends on the project. It could be a simple .jar file you can run with the JVM, it could be a .war file you have to deploy to a application server or even something entirely else. But mvn clean package would definitely be the first step to go.


text:
Q: listFiles not workig after exporting to jar I am working on a libgdx game using tiled to make the maps, in my level select screen I read in all the files in the map folder and count the files ending with .tmx to see how many level buttons I have to make.
All of this has been working fine but when I try to export the project to a jar using the intellij gradle dist command it just stops working.
I'm guessing it changes the path to the files or something when it's exporting it but I have no idea how to fix it.
Here is the code that reads the files
        new File("maps").listFiles(new FilenameFilter() {
        @Override
        public boolean accept(File dir, String name) {
            if (name.endsWith(".tmx")) {
                numberOfLevels++;
            }
            return true;
        }
    });

A: To access "maps" like that it may not be included within the jar file, but needs to be in the same directory as the jar is. With new File(...) you are accessing the PC's file system, which cannot find a "maps" file as it is compiled within the jar file

A: To count the number of .tmx files within the jar, try treating it as a zip and counting the number of files of interest, like so:
List<String> classNames = new ArrayList<String>();
ZipInputStream zip = new ZipInputStream(new FileInputStream("/path/to/jar/file.jar"));
int numberOfLevels=0;
for (ZipEntry entry = zip.getNextEntry(); entry != null; entry = zip.getNextEntry()) {
    if (!entry.isDirectory() && entry.getName().endsWith(".tmx")) {
        numberOfLevels++;
    }
}


text:
Q: PHP convert Array with SimpleXMLElement Object to XML I have an array with some SimpleXMLElement Objects inside and now i need to get a well formed XML for Ajax interaction, how can i do?
This is the array:
Array (
   [0] => SimpleXMLElement Object (
          [count] => 2
          [id] => 20
          [user_id] => 2
          [title] => Polo RL )
   [1] => SimpleXMLElement Object (
          [count] => 3
          [id] => 19
          [user_id] => 4
          [title] => tshirt fitch )
   [2] => SimpleXMLElement Object (
          [count] => 2
          [id] => 18
          [user_id] => 2
          [title] => Polo La Martina )
)

I would get this XML result:
<root>
    <record>
        <count>2</count>
        <id>20</id>
        <user_id>2</user_id>
        <title>Polo RL</title>
    </record>
    <record>
        <count>3</count>
        <id>19</id>
        <user_id>4</user_id>
        <title>tshirt fitch</title>
    </record>
    <record>
        <count>2</count>
        <id>18</id>
        <user_id>2</user_id>
        <title>Polo La Martina</title>
    </record>
</root>

A: I would use SimpleXMLElement's asXML method to output the XML of each object.So this:
$xml = <<<XML
<record>
    <count>2</count>
    <id>20</id>
    <user_id>2</user_id>
    <title>Polo RL</title>
<record>
XML;

$xml = new SimpleXMLElement($xml);

echo $xml->asXML();

Will output this:
<record>
    <count>2</count>
    <id>20</id>
    <user_id>2</user_id>
    <title>Polo RL</title>
<record>

So you can simply loop through your array outputing each elements xml to a variable like so:
$fullXml = '<root>';
foreach($arrXml as $xmlElement){
    $fullXml .= str_replace('<?xml version="1.0"?>', '',$xmlElement->asXML());
}
$fullXml .= '</root>';
echo $fullXml ;


text:
Q: Making vba userform with inputs and command button I made a macro (commandbutton), which is working (probably not the best solution, but it's working):
Private Sub CommandButton1_Click()
 Dim myval As Variant
 Dim ws As Worksheet
  myval = InputBox("Zadaj číslo riadku:")
  Set ws = ActiveSheet
If StrPtr(result) = 0 Then
 ElseIf myval = vbNullString Then
Else
  ws.Range("F3").Value = myval
End If
 ws.PrintOut From:=1, To:=1
End Sub

Now I want to make a USERFORM. I made this:

But now I'm stuck:

*

*I don't know how to make an input from textbox.
(there would be 3 inputs on Page1)

*Problem is the loop. I want to make a loop - input2 to input3. So for example: Input2.value = 1, Input3.value = 60, then I want a loop from 1 to 60.

A: A Textbox contains Text but a loop expect numbers. Try something like this:
Dim lngText1 as Long
Dim lngText2 as Long
Dim i as Long
If IsNumeric(Me.Controls("textbox2").Value) And isNumeric(Me.Controls("textbox3").Value) Then
  lngText1 = CLng(Me.Controls("textbox2").Value)
  lngText2 = CLng(Me.Controls("textbox3").Value)

  For i = lngText1 To lngText2
    'Your code
  Next i
Else
  MsgBox "Please insert numbers"
End If

A: Added an Exit Sub in case of error
Private Sub CommandButton1_Click()

  Dim lngText1 as Long
  Dim lngText2 as Long
  Dim i as Long

  If Not IsNumeric(Me.Controls("textbox2").Value) Or Not IsNumeric(Me.Controls("textbox3").Value) Then
    MsgBox "Please insert numbers"
    Exit Sub
  End If

  lngText1 = CLng(Me.Controls("textbox2").Value)
  lngText2 = CLng(Me.Controls("textbox3").Value)

  For i = lngText1 To lngText2
    'Your code
  Next i

End Sub


text:
Q: Derivation of Digamma function In the paper by Kraskov et al (2004) there is a rather large jump in calculations. I am wondering if someone could fill out the gap for the equation below (equation 17 in the paper):
$$
k\binom{N-1}{k}\int_0^1 p^{k-1} (1-p)^{N-k-1} \ln(p) dp = \psi(k) - \psi(N)
$$
where $\psi(x)$ is the dimgamma function.
Reference:
Kraskov, A., Stögbauer, H., & Grassberger, P. (2004). Estimating mutual information. Physical review E, 69(6), 066138.

A: \begin{align*}
\int_0^1 p^{k-1} (1-p)^{N-k-1} \ln(p) dp =& \int_0^1 p^{k-1} (1-p)^{N-k-1} \left(\lim_{t \to 0+} \frac{d}{dt} p^t\right)dp \\
=& \lim_{t \to 0+} \frac{d}{dt}\int_0^1 p^{k+t-1} (1-p)^{N-k-1} dp \\
=&  \lim_{t \to 0+} \frac{d}{dt} B(k+t,N-k)\\
=& \lim_{t \to 0+} \left[\psi(k+t)-\psi(n+t)\right]B(k+t,N-k)\\
=& \left[\psi(k)-\psi(N)\right]B(k,N-k)\\
=& \left[\psi(k)-\psi(N)\right]\frac{\Gamma(k)\Gamma(N-k)}{\Gamma(N)}\\
=& \left[\psi(k)-\psi(N)\right]\frac{(k-1)!(N-k-1)!}{(N-1)!}\\
=& \left[\psi(k)-\psi(N)\right]\frac{k!(n-k-1)!}{k(N-1)!}\\
=& \left[\psi(k)-\psi(N)\right]\frac{1}{k\binom{N-1}{k}}
\end{align*}
$$ \boxed{ k\binom{N-1}{k}\int_0^1 p^{k-1} (1-p)^{N-k-1} \ln(p) dp = \psi(k)-\psi(N)} $$


text:
Q: Mongodb php datetime filter not working properly I use mongo db with php I need a last 1 hour data. I implement as like bellow.
{
  "_id":{"$oid":"5ff42b30be00ec1eaf261db1"},
  "logtype":"syslog",
  "message":"Jan  4 06:51:56 4S-096 kernel: [70745743.387001] CPU7: Package temperature above threshold, cpu clock throttled (total events = 2955852254)",
  "node_id":875,
  "app_id":0,
  "send_to_slack":1,
  "created_date":{"$date":"2021-01-05T09:02:39.593Z"}
}

PHP CODE
$client = mongodb_connect();
$db     = $client->$db_name;
$col    = $db->selectCollection($collection_name);
$client->selectDatabase($db_name);

$criteria = array(
        "created_date" => [$gte=> new  \MongoDB\BSON\UTCDateTime(strtotime("-1 hour") * 1000)],
        "logtype" => $logType,
        "message" => trim($logdata),
        "node_id" => $node_id,
    );

$count = $col->count($criteria);

I need a count result. thanks in advance

A: I am not so familiar with PHP, but I think $client->$db_name is equal to $client->selectDatabase($db_name)
However -> does not work with variables, so $client->$db_name may fail.
Try this one:
$client = mongodb_connect();
$db     = $client->selectDatabase($db_name);
$col    = $db->selectCollection($collection_name);

$criteria = array(
        "created_date" => [ '$gte' => new MongoDB\BSON\UTCDateTime(strtotime("-1 hour") * 1000)],
        "logtype" => $logType,
        "message" => trim($logdata),
        "node_id" => $node_id,
    );

$count = $col->count($criteria);

I never used strtotime, maybe you have to skip  * 1000


text:
Q: Bootstrap Datepicker not allowing dd-mm-yyy <input class="datepicker" data-date-format="dd/mm/yyyy" data-val="true" data-val-date="The field Date must be a date." data-val-required="The Date field is required." id="Date" name="Date" type="text">

i have specified data-date-format="dd/mm/yyyy" as guided here.
https://github.com/eternicode/bootstrap-datepicker#example
The problem is it is not allowing dd/mm/yyyy format to pass through.
I am using asp.net mvc if it matters.

A: In your model, do you have the following dataannotation set for your field:
    [DataType(DataType.Date), DisplayFormat(NullDisplayText="", DataFormatString = " {0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
    [Column(TypeName = "Date")]
    public DateTime myDate { get; set; }

You should also have in your web.config under system.web:
<globalization culture="en-AU" uiCulture="en-AU" />

If you want to do client side validation, you should also include https://github.com/jquery/globalize
<script type="text/javascript" src="/content/scripts/globalize.js"></script>
<script type="text/javascript" src="/content/scripts/globalize.culture.en-AU.js"></script>

Finally, I create an EditorTemplate for Date fields:
/Views/Shared/EditorTemplates/date.cshtml:

@model DateTime
@Html.TextBox("", Model.ToShortDateString(), new { @class = "datepicker"})


text:
Q: Simplifying $\binom{n-k}{k} + \binom{n-k-1}{k-1}$ I am trying to find the formula for the number $g(n,k)$ which is the number of $k$-subsets of $[n]$ where no two elements are consecutive numbers in $[n]$ arranged in a circle.
I derived the following recursion
$$f(n,k) = f(n-1,k) + f(n-2, k-1) $$
where $f(n,k)$ is the number of ways to take $k$=subsets from $[n]$
and also the formula of $f(n,k)$ as following
$$f(n,k) = \binom{n-k+1}{k}$$
Also,
I derived following relation
$$g(n,k) = f(n-1,k) + f(n-3, k-1)$$
so that g(n,k) is just represented as
$$\binom{n-k}{k} + \binom{n-k-1}{k-1}$$
Is there ways to merge this two binomials given as summation?

A: A further simplification could be
$$\binom{n-k}{k} + \binom{n-k-1}{k-1}=\binom{n-k}{k} + \frac{k}{n-k}\binom{n-k}{k}=\frac{n}{n-k}\binom{n-k}{k}.$$

A: Well, you can always do something like
$$
\binom{n-k}{k} = \frac{(n-k)!}{k! (n-2k)!} = \frac{n-k}{k} \frac{(n-k-1)!}{(k-1)!(n-2k)!} = \frac{n-k}{k} \binom{n-k-1}{n-1},
$$ and then merge the two coefficients.

A: Or: $$\binom{n-k}{k} + \binom{n-k-1}{k-1}=\frac{n}{k}\binom{n-k-1}{k-1}=\frac{n}{k}\cdot \frac{(n-k-1)!}{(k-1)!(n-2k)!} \hspace{4.7cm} =\frac{n(n-k)!}{(n-k)\cdot k!(n-2k)!}=\frac{n}{n-k}\binom{n-k}{k}.$$