text:
Q: Clickable layout background I have a clickable Layout, defined as following:
<RelativeLayout
    android:id="@+id/Test"
    android:layout_width="match_parent"
    android:layout_height="45dp"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:clickable="true"
    android:orientation="vertical"
    android:background="@drawable/test_bg"
    >

and there is a selector used to change the background if it was clicked:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >

    <item android:drawable="@drawable/testclicked"
      android:state_selected="true" />

<item android:drawable="@drawable/test" />

</selector>

the problem is it doesn't work.. for buttons that works fine. What am I doing wrong?

A: You should use state_pressed instead of state_selected :
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
    <item
        android:drawable="@drawable/testclicked"
        android:state_pressed="true" />
    <item
        android:drawable="@drawable/test" />
</selector>


text:
Q: count total element inside parent div with jQuery Is there any way to count the total number of child div inside the main div with Jquery?
I want to count total div inside div with class form-group but this div should have
canvas. for example I want to return count for third div only since it has element canvas
and it has two canvas so it should return 2.
it has data-column="1" and data-column="2". if this div had 3 canvas in a row it would have
data-column="1", data-column="2" and data-column="3" for each div

*

*find the div that has element canvas

*count the total number of canvas with   class="form-group"
3rd div should return 2 and the 4th div should return 1 since the 3rd div has 2 canvas and
4th div has 1 canvas.

         Name
         <input class="form-control" type="text"/>

     Email Address
     <input class="form-control" type="text"/>

 //3rd div

             <canvas class="mycan-1" width="463" height="675"></canvas>

             <canvas class="mycan-2" width="463" height="675"></canvas>

 //4th div

             <canvas class="mycan-1" width="463" height="675"></canvas>

A:

$('div.form-group')
  .filter((idx, div) => $(div).find('canvas').length > 0)
  .each((idx, div) => {
    let that = $(div);
    let row = that.data('row');
    console.log('div row#' + row + ' canvas child amount:' + that.find('canvas').length);
  });

         Name
         <input class="form-control" type="text"/>

     Email Address
     <input class="form-control" type="text"/>

             <canvas class="mycan-1" width="463" height="675"></canvas>

             <canvas class="mycan-2" width="463" height="675"></canvas>

 //4th div

             <canvas class="mycan-1" width="463" height="675"></canvas>

A: You can do this:

$(".form-group").each(function() {
 const row = $(this).data("row");
console.log(
  "row",row,":", $("canvas",this).length)
});

// or

const $rows = $(".form-group").filter(function() {
  return $(this).find("canvas").length > 0
}) // here we have all the divs with canvas children
.map(function() {
   return $(this).data("row");
})
.get(); // here we have the array of data-row values from the divs with canvase children

console.log($rows)

      Name
      <input class="form-control" type="text" />

      Email Address
      <input class="form-control" type="text" />

//3rd div

      <canvas class="mycan-1" width="463" height="675"></canvas>

      <canvas class="mycan-2" width="463" height="675"></canvas>

//4th div

      <canvas class="mycan-1" width="463" height="675"></canvas>

redpajama_set_name: RedPajamaStackExchange


text:
Q: node.js with socket.io under debian 5 (lenny) exit with error I installed node.js with the instructions from node.js wiki. So I put the debian sid sources in my sources list and installed node. After that I installed npm with the curl cmd from wiki site. I installed socket.io with npm. Everything till this point works without any errors.
But when I try to start my server I get this error:
node.js:134
        throw e; // process.nextTick error, or 'error' event on first tick
        ^ Error: Cannot find module 'socket.io'
    at Function._resolveFilename (module.js:320:11)
    at Function._load (module.js:266:25)
    at require (module.js:348:19)
    at Object.<anonymous> (/root/sockets/trunk/socketio/server.js:8:8)
    at Module._compile (module.js:404:26)
    at Object..js (module.js:410:10)
    at Module.load (module.js:336:31)
    at Function._load (module.js:297:12)
    at Array.<anonymous> (module.js:423:10)
    at EventEmitter._tickCallback (node.js:126:26)

I dont have any ideas why this won't work? Could anybody help?

A: *

*Go to the project folder. This is the folder where you run node your_server.js.

*Run npm install socket.io. This will add a directory under this project folder named node_modules, where, unsurprisingly, modules for this project are.

*Run the server with node your_server.js. This time it will work ;).

Enjoy!

A: You can reference socket.io directly in your javascript file.
If you installed socket.io using npm install socket.io -g it should have installed socket.io in a node_modules directory under /usr/local/lib. So pick up socket.io from there.
So in your script, reference socket.io like below:
var io = require('/usr/local/lib/node_modules/socket.io');

Then run node /wherever_your_script_is/your_script.js
Cheers.
P.S. Not sure how npm worked in the past, but today the above would work ok, I just tried it to make sure.


text:
Q: Laravel and Angular: Update method not working I am new to this "Angular/Laravel" thing.
I am trying to make a simple todo app. Adding and deleting work, but updating doesn't.
I have a ng-repeat section, and inside every todo I have an input.
    <label class="css-label to-do-name" ng-hide="editingFormBoolean">
    <input class="css-checkbox" name="todo-checkbox-{{todo.id}}" type="checkbox" ng-model="todo.done">
    {{todo.name}}
    </label>

app.js factory called TasksData:
    update: function (id) {
        return $http.put('/tasks/' + id);
    },

app.js directive[link:]
-this is called when the input changes, I am using $watch element
TasksData.update(scope.todo.id);

TaskController.php:
public function update($id)
{
    $task = Task::find($id);

    $task->done = Input::get('todo-checkbox-'+$id);

    $task->save();
}

But the Input::get doesn't work. If I replace "Input::get('todo-checkbox-'+$id)" with true or false values, the hole thing works, the data is sent to the database and updated. If you know how to get this done, or know any other way to mark a todo as completed, I will be thankful.

A: update: function (id) {
    return $http.put('/tasks/' + id, {isDone: $scope.todo.done});
},

public function update($id)
{
    $task = Task::findOrFail($id);

    $task->done = Input::get('isDone');

    $task->save();
}


text:
Q: Unable to pause React audio import { useState } from "react";

function Music(){

  const [pauseToggle, setpauseToggle] = useState(false)

  const music = new Audio(require(`./Alan.mp3`));
  console.log(music);
  let isPlaying = false;

  const player = () => {
    pauseToggle ? setpauseToggle(false) : setpauseToggle(true);
    if(isPlaying){
      music.pause();
      isPlaying = false;
    }else{
      music.play();
      isPlaying = true;
    }
  }

  return(

      <button onClick={player}>{pauseToggle?"=":">"}</button>

  )

}

export default Music;

I'm unable to pause the audio. IInstead it gets played twice when I try to pause.
I tried to get help from this Unable to pause audio in Reactjs but it didn't help.
Any other solution for pausing audio file?

A: I believe the music variable should be stateful so it's retained across renders.
const [music] = useState(new Audio(require(`./Alan.mp3`)));

and isPlaying should probably be found by querying the Audio object (music) and/or updated by listening for play/pause state changes.

A: I'd simplify state to a single boolean: your audio is either playing or not, so there's no need for redundancy here. let isPlaying = false; isn't state, so it's not persistent across renders and doesn't do anything pauseToggle doesn't already achieve.
In fact, audio elements have a .paused property that makes the separate state boolean redundant, but for React rendering/lifecycle purposes the extra boolean is handy.
Since the audio is a side effect to the rendering, I'd make it a ref, then trigger play/pause functions based on when playing changes in a useEffect.
A bit of a bonus, but it's probably worth handling the onended event to set playing to false when the track ends, for starters.

const {useEffect, useRef, useState} = React;

const MusicPlayer = ({url}) => {
  const [playing, setPlaying] = useState(false);
  const audioRef = useRef(new Audio(url));

  useEffect(() => {
    const handler = () => setPlaying(false);
    audioRef.current.addEventListener("ended", handler);
    return () =>
      audioRef.current.removeEventListener("ended", handler)
    ;
  }, [audioRef.current]);

  useEffect(() => {
    audioRef.current[playing ? "play" : "pause"]();
  }, [playing]);

  return (

      <button onClick={() => setPlaying(!playing)}>
        {playing ? "=" : ">"}
      </button>

  );
};

const url = "https://upload.wikimedia.org/wikipedia/en/a/a9/Webern_-_Sehr_langsam.ogg";

ReactDOM.createRoot(document.querySelector("#app"))
  .render(<MusicPlayer url={url}/>);
button {
  font-size: 2em;
}

Putting the audio into a hook helps make it reusable and keeps your parent component clean:

const {useEffect, useRef, useState} = React;

const useAudio = url => {
  const [playing, setPlaying] = useState(false);
  const audioRef = useRef(new Audio(url));

  useEffect(() => {
    const handler = () => setPlaying(false);
    audioRef.current.addEventListener("ended", handler);
    return () =>
      audioRef.current.removeEventListener("ended", handler)
    ;
  }, [audioRef.current]);

  useEffect(() => {
    audioRef.current[playing ? "play" : "pause"]();
  }, [playing]);

  return [playing, setPlaying];
};

const MusicPlayer = ({url}) => {
  const [playing, setPlaying] = useAudio(url);

  return (

      <button onClick={() => setPlaying(!playing)}>
        {playing ? "=" : ">"}
      </button>

  );
};

const url = "https://upload.wikimedia.org/wikipedia/en/a/a9/Webern_-_Sehr_langsam.ogg";

ReactDOM.createRoot(document.querySelector("#app"))
  .render(<MusicPlayer url={url} />);
button {
  font-size: 2em;
}


text:
Q: How to access data of a filter query in firestore flutter? I want to search for the user from his mobile number. If the user found then show his other information like Name, Surname.

The search query is working fine. But I'm not able to access the data. Below is my function to get the result of the query. When I print the data its just prints [Instance of 'QueryDocumentSnapshot']
  getData() async {
    final QuerySnapshot result = await FirebaseFirestore.instance
        .collection('CommonData')
        .where(
          'Mobile_Number',
          isEqualTo: mobileNumber,
        )
        .get();
    final List<DocumentSnapshot> resultDocument = result.docs;

    print(resultDocument);
  }

A: Try this
getData() async {
  String mobile_number;
  String name;
  String surname;

  final QuerySnapshot result = await FirebaseFirestore.instance
      .collection('CommonData')
      .where(
        'Mobile_Number',
        isEqualTo: mobileNumber,
      )
      .get();
  result.docs.forEach((value) {
    mobile_number = value.data()['Mobile_Number'];
    name = value.data()['Name'];
    surname = value.data()['SurName'];
  });

  print("Mobile Number: " + mobile_number);
  print("Name: " + mobile_number);
  print("SurName: " + mobile_number);
}

A: Since you make the assumption that your DB does contain one and only one User per Mobile Number, you might want to enforce this assumption:
Future<Map<String, dynamic>> getData(String mobileNumber) async {
  return FirebaseFirestore.instance
      .collection('CommonData')
      .where(
        'Mobile_Number',
        isEqualTo: mobileNumber,
      )
      .get()
      .then((snapshot) => snapshot.docs.single.data())
      .catchError(
    (e) {
      if (e.message == 'No element') {
        print("Couldn't find User for Mobile Number $mobileNumber");
      } else if (e.message == 'Too many elements') {
        print("Found duplicate Users for Mobile Number $mobileNumber");
      }
      return null;
    },
    test: (e) => e is StateError,
  );
}


text:
Q: Torsion-free sheaf on etale site If $F$ is a sheaf on usual Zariski site of an integral scheme $X$ (each $O_U(U)$ is a domain), then it is called torsion-free if $F(U)$ is torsion-free $O_U(U)$ module for every $U\in X_{Zar}$.
Now how to define a torsion-free sheaf on the small etale site of a integral scheme? The problem is unlike the Zariski case, $O_U(U)$ are not integral domains ( reduced but not irreducible/connected) when $U \in X_{et}$. Moreover, this also shows that even the structure sheaf for $X_{et}$ is not torsion-free.
So my first guess was to define $F$ in $X_{et}$ as torsion-free if $F|_{X_{zar}}$ is torsion-free. However, it seems to me that I am making some mistake.


text:
Q: Change Slider bar position to the Right side i am fresher in android development. i know very well how to implement native sidebar menu. but my problem is i want this sidebar menu on the right side of the screen.
So is it possible? please help me.
Thanks in advance.

A: It is affected by layout_gravity.
If layout_gravity = start then navigation drawer will open left to right and if layout_gravity = end then it will open right to left.
<ListView
    android:id="@+id/adventuresRTL"
    android:layout_width="240dp"
    android:layout_height="match_parent"
    android:layout_gravity="end"
    android:background="#AAAAAA"
    android:choiceMode="singleChoice"
    android:divider="@android:color/transparent"
    android:dividerHeight="10dp" />


text:
Q: Select DIV using its ID + addition Using a div as selector is easy:

$('#test1').doSomething();

I want to target only another div, containing the same ID + _sub:

$('#test1').find( /* Same ID + "_sub" */ ).doSomething();

How can I do this? I know I can use .attr('id') to take #test1, but I do not how to extend this with _sub.
JS FIDDLE
Of course it would be easy to target the #test1_sub directly, but image I have 1000 divs counting up test1, test2, test3, etc. and want to use this inside of a function.

A: You do it like this
$('#test1' + "_sub").fadeOut();

Note the quotation-marks containing "_sub".
EDIT: In your answer, you made up an example where you had 100 divs with ids like test1, test2 and so on. Then you could select all elements with an id beginning with test. Like this:
$('*[id^="test"]').fadeOut();

A: Set a variable and chain: (CORRECTED)
var target = $(whatever test div you targetted).attr('id');
$('#'+target + "_sub").doSomething();

You said you were going to use it in a function, so it would be targettable this way for example. Lets say when you click #test1 a function will run on all subs based on the clicked test:
$('.testBoxes').click(function () {
   var target = $(this).attr('id');
   $('#'+target + "_sub").doSomething();
});

A: Here you can use start with selector to work with all ids.
jsFiddle

$(document).ready(function(){
$( "*[id^='test1']" ).fadeOut();
})

Test 1

 Test 1 Sub

Test 1 ASDF

 Test 1 sub342

Test 1 sdfsd

 Test 1 45645


text:
Q: Does every group have a finite index subgroup? Does every group have a finite index subgroup (besides the whole group)? I suspect the answer is no, but I haven't found an example.
What about finitely presented or generated groups? Or groups with torsion?
I tried something like taking a presentation and only selecting some of the generators, but I don't this works even if $G$ has torsion, since the other generators could interact in a complicated way. Perhaps if we could find a minimal presentation of a group with torsion containing (as a generator) a torsion element, then this would work, but I'm not sure why such a minimal presentation should exist.

A: The condition that a group has a nontrivial finite index subgroup is equivalent to the condition that it has a nontrivial finite quotient, and also equivalent to the condition that it acts nontrivially on some finite set (exercise).
As stated in the comments, $\mathbb{Q}$ is an easy example of a group with no nontrivial finite quotients (exercise), the point being that quotients of divisible groups are divisible but no nontrivial element of a finite group is divisible. If you want an example which is torsion then take $\mathbb{Q}/\mathbb{Z}$, which is still divisible.
Even assuming finitely presented does not help you: the Higman group is a finitely presented group with no nontrivial finite quotients.


text:
Q: Reboot system through cronjob I'm running a python script as the root user. (I know its not reccomended but in my case its ok.)
At the end of this script, based on some conditions I need to reboot the raspberry.
I have tried several codes but none actually reboots the machine. I have tried this at the end of my .py file:
os.system("shutdown -r now")
reboot
sudo reboot
os.system("reboot")

None of these reboots the raspberry. What is the proper code to reboot the system?

A: This should work:
import os
os.system('/sbin/shutdown -r now')

It's because cron jobs don't have environment, so you have to provide full path to the 'shutdown' program, otherwise the system can not find it.

A: Just this should work:
import os
os.system("shutdown /r")


text:
Q: Integrating Qt into legacy MFC applications We currently maintain a suit of MFC applications that are fairly well designed, however the user interface is beginning to look tired and a lot of the code is in need quite a bit of refactoring to tidy up some duplication and/or performance problems.  We make use of quite a few custom controls that handle all their own drawing (all written using MFC).
Recently I've been doing more research into Qt and the benefits it provides (cross-platform and supports what you might call a more "professional" looking framework for UI development).
My question is - what would be the best approach to perhaps moving to the Qt framework?  Does Qt play nice with MFC?  Would it be better to start porting some of our custom controls to Qt and gradually integrate more and more into our existing MFC apps? (is this possible?).
Any advice or previous experience is appreciated.

A: In my company, we are currently using Qt and are very happy with it.
I personnally never had to move a MFC-app into using the Qt framework, but here is something which might be of some interest for you :
Qt/MFC Migration Framework
Qt/MFC Migration Framework
It's part of Qt-Solutions, so this means you'll have to buy a Qt license along with a Qt-Solutions license. (edit: not any more)
I hope this helps !

A: (This doesn't really answer your specific questions but...)
I haven't personally used Qt, but it's not free for commercial Windows development.
Have you looked at wxWindows which is free? Nice article here. Just as an aside, if you wanted a single code base for all platforms, then you may have to migrate away from MFC - I am pretty sure (someone will correct if wrong) that MFC only targets Windows.
One other option would be to look at the Feature Pack update to MFC in SP1 of VS2008 - it includes access to new controls, including the Office style ribbon controls.

A: It's a tricky problem, and I suspect that the answer depends on how much time you have. You will get a much better result if you port your custom controls to Qt - if you use the QStyle classes to do the actual drawing then you'll end up with theme-able code right out of the box.
In general, my advice would be to bite the bullet and go the whole way at once. Sure, it might take  longer, but the alternative is to spend an age trying to debug code that doesn't quite play ball, and end up writing more code to deal with minor incompatibilities between the two systems (been there, done that).
So, to summarise, my advice is to start a branch and rip out all your old MFC code and replace it with Qt. You'll get platform independence (almost) for free, and while it will take a while, you'll end up with a much nicer product at the end of it.
One final word of warning: make sure you take the time to understand the "Qt way of doing things" - in some cases it can be quite different to the MFC approach - the last thing you want to do is to end up with MFC-style Qt code.

A: I have lead a team doing this kind of thing before (not MFC to QT but the principles should work).
First we documented the dialogs and what their inputs, controls and outputs were.  Also, we create several test cases especially for any clever logic inside the GUI.
Sometimes we had to refactor some business logic to provide a clean interface the GUIs but this is the way it should have been done in the first place tbh.
Now we had a list of GUIs, inputs, outputs, tests and an interface that the encapsulated GUI had to match.
We began, project by project, to create equivilant GUIs to the old ones.  Once we did that we could slot the GUI in where the old one was, rebuild and test it.  At first we tripped a lot but we soon worked out the common errors and fixed them.  We navigated (I think) 612 dialogs although there was a team of about a dozen of us working on it.


text:
Q: Ext JS Search possibility in MultiSelect ComboBox I want to know that how in ExtJS MultiSelect ComboBox i can search for a value. Like if i have entered 's' then a list of items starting with a must be displayed and the item selector should select if it matches with 's'.
This is the code i tried.....
    cbCfg = {
      name  : property.columnname,
      hideOnSelect  : false,
      triggerAction : 'all',
      mode      : 'local',
      width     : comboFieldSize,
      store     : new Ext.data.SimpleStore({
          id            : 0,
          fields        : ['strValue','strText'],
          data          : data
      }),
      listWidth     : 400,
      valueField        : 'strValue',
      displayField  : 'strText'
    };
    field       = new form.MultiCombo(cbCfg);

thnkz in advance,
just:-)

A: I assume that MultiSelect ComboBox extends functionality of Ext.form.ComboBox.
You could try going with triggerAction : 'query', which is the default - it should filter out non-matching entries. Although that could be a little bit counter-intuitive for the user.
Another possible approach is adding typeAhead : true property - should trigger suggesting suggestions based on the text entered by user.


text:
Q: Problem pushing a value into a list being called by a getter function I'm trying to push a value to a list. My list is inside a class that contains many lists, the class contains a function getList(int) that takes an integer and returns the list that it represents. e.g getList(6) will return list G. The class that cointains all lists is called "z". However, when I try to push a value using that: z.getList(6).push(value);
it will not push it into G. How can I write a line that pushes a value into a list that it is being called with a getter function?
Code that I have:
class Fila {
public:
    LList a,b,c,d,e,f,g,h,i,j;
//public:
    LList q;
    LList getList(int n);
};

LList Fila::getList(int n) {
    if(n==0){return a;}
    else if(n==1){return b;}
    else if(n==2){return c;}
    else if(n==3){return d;}
    else if(n==4){return e;}
    else if(n==5){return f;}
    else if(n==6){return g;}
    else if(n==7){return h;}
    else if(n==8){return i;}
    else {return j;}
}

void radixsort(Node *front, Node *back) {
    Fila z;
    Node *t=front;
    while(t){
        z.q.push(t->data);
        t=t->next;
    }
    for(int k=0;k<log(99)+1;k++){
        while(!z.q.empty()){ //anade a los bucket
            if(k==0){
                for(int l=0;l<10;l++){
                    if((z.q.front())%10==l){
                        z.getList(l).push(z.q.front()); //THIS LINE
                        break;
                    }
...

A: Change this
LList Fila::getList(int n) {

to this
LList& Fila::getList(int n) {

Your version isn't returning the list in your class, it's returning a copy of the list in your class. By changing the getList function to return a reference it does return (a reference to) the list in your class.


text:
Q: Is there a more pythonic way of combining duplicate objects in a list? I have a list of objects.  Each object is a unique instance, consisting of any combinations of names and values.  I want to combine objects with duplicate names into a new instance of the same class, whose value is a list of the values of all duplicates.  This is my very non-pythonic approach:
def normalise_repeatable_options(options):
    flat = {}
    for o in options:
        if isinstance(o, Option):
            flat.setdefault(o.long, []).append(o)

    # Ensure options stay in the order they were prescribed.
    parsed = []
    for o in options:
        if isinstance(o, Option):
            dups = flat.get(o.long)
            if dups:
                parsed.append(Option.combine(*tuple(dups)))
                del flat[o.long]
        else:
            parsed.append(o)

    return parsed

Update: The input and expected output from the function
input = [
    Option('-f', '--filter', 1, 'merge file'),
    Option('-f', '--filter', 1, 'merge anotherfile'),
    Argument(None, 'a'),
    Argument(None, 'b'),
    Argument(None, 'c')
]

output = [
    Option('-f', '--filter', 1, ['merge file', 'merge anotherfile']),
    Argument(None, 'a'),
    Argument(None, 'b'),
    Argument(None, 'c')
]

I have also included the Object.combine class method, just in case you wondered what that does:
@classmethod
def combine(class_, *opts):
    t = opts[0]
    if len(opts) == 1: return t
    return class_(t.short, t.long, t.argcount, [o.value for o in opts])

A: Without being able to test, about about something like this?
def normalise_repeatable_options(options):
    parsed = []
    flat = defaultdict(list)

    for o in options:
        if isinstance(o, Option):
            # For the first instance of this object, add a placemarker
            if o.long not in flat:
                parsed.append(o.long)

            flat[o.long].append(o)
        else:
            parsed.append(o)

    return [Option.combine(*tuple(flat[o])) if isinstance(o, str) else o for o in parsed]

This way, you build your parsed list, leave placemarkers for the Option objects to be replaced.  I'm assuming that none of the objects in your input list are of type str.

A: You can start here:
from collections import defaultdict

def normalise_repeatable_options(options):
    actual_options = [o for o in options if isinstance(o, Option)]
    non_options = [o for o in options if not isinstance(o, Option)]

    flat = defaultdict(list)
    for o in actual_options:
        flat[o.long].append(o)

    parsed = (
        # Make list of the non-options plus ...
        non_options +

        # a flattened lists of Options plus ...
        [Option.combine(*tuple(dups)) for dup in flat.values() if len(dup) > 1] +

        # a list of Options
        [value[0] for value in flat.values() if len(value) == 1]
    )
    return parsed

A: Try list comprehension :)
Not sure if this will work in your case, as I modify your code based on simple mapping of one code to another.
You get the flat by check isinstance, so you don't have to check it again.
There may be small errors in this code:
def normalise_repeatable_options(options):
    flat = {}
    parsed = []
    [flat.setdefault(o.long, []).append(o) if isinstance(o, Option)
     else parsed.append(o) for o in options]

    [parsed.append(Option.combine(*tuple(lst))) if len(lst) > 1
     else parsed.append(lst) for lst in flat.values()]

    return parsed


text:
Q: What is the proper terminology for these two types of multiplication? ((QUESTION REWORKED))
First question on this site, and I apologize if this question has been answered. I searched and searched and the fact I don't know the basic terminology is hindering me from finding the answer.
This question stems from a current programming issue I am attempting to detail to others. In one instance we have the secondary variables being added together and then multiplied against the main variable. While in the other scenario, each one is multiplied and updates the main variable before the next. So you get very different numbers, depending on if you add the secondary together before multiplying or if you do them one at a time.
The variables:
$$\begin{align*}
x&=100 \\
a &= 2 & b &= 3 \\
c &= 4 & d &= 5
\end{align*}$$
The first formula is:
$$y = d(c(b(a(x)))).$$
The second formula is:
$$y = x(a+b+c+d).$$
What is the proper math terminology for both types?
Any help would be appreciated.

A: I don't think there is specific terminology assigned to either form, rather the property is called the distributive property, and you are either adding first, or multiplying each term individually prior to adding.
Given your edits, the two different forms have nothing in common mathematically.
The first format indicates that $a$, $b$, $c$ and $d$ might be functions and each would perform an operation on the element inside the parentheses next to it.  However, as they are listed as being variables and as having specific values, the first form is simply an explicit "multiply in this order" command, while the second form is an explicit "add these before multiplying" command.
If you were to speak what is written in each formula, they might sound like this:
(1) "$d$ times multiplication of $c$ and multiplication of $b$ and multiplication of $a$ and multiplication of $x$."
(2) "$x$ times sum of $a$, $b$, $c$ and $d$."
Note that the first form might be shortened using "pi" notation:
$$x\prod_{i=0}^n a_i$$
Where $a_0 = a$, $a_1 = b$, $a_2 = c$, and $a_3 = d$.
If a, b, c and d are given as percentages, note that the formula $x*a*b*c*d$ is not a correct way to calculate the compounding effect.  Instead, it should be calculated like so:
$$x * {100 + a \over 100} * {100 + b \over 100} * {100 + c \over 100} * {100 + d \over 100}$$


text:
Q: Artin Rings, Noetherian Rings, and the Axiom of Choice It is a well-known fact that in ZF, the axiom of choice is equivalent to the statement that every commutative ring has a maximal ideal. On the other hand, for Noetherian rings, this is not necessary (either in the sense that it only requires dependent choice or that it requires no choice at all, depending on your definition of Noetherian). It can also be shown (in ZFC) that every Artin ring is Noetherian, and the proof of this fact in Atiyah-MacDonald essentially relies on the following two results:

*

*In an Artin ring, every prime ideal is maximal (proved without choice), and

*The nilradical of a ring is the intersection of all of the prime ideals in a ring (proved with choice).
Result 2. is equivalent to the statement that every Artin ring contains a prime ideal. To see this, note simply that given a non-nilpotent element $f$ in a ring $A$, there is a prime ideal of A not containing $f$ if and only if $A_f$ has a prime ideal. According to this answer, the fact that every commutative ring has a prime ideal is equivalent in ZF to the Boolean prime ideal theorem, so at least full choice is not necessary. Can this be weakened for Artin rings? Alternatively, is there another proof that Artin $\Rightarrow$ Noetherian that uses a weaker form of the axiom of choice (or no form of it)? Thank you.

A: Suppose $A$ is a nonzero artinian ring.  Then the collection of all nonzero (possibly improper) ideals of $A$ has a minimal element, say $I\subseteq A$.  Then $I$ has no nonzero proper submodules, and so is a simple $A$-module.  In particular, it must be cyclic (generated by any nonzero element) and the kernel of a surjection $A\to I$ will be a maximal ideal of $A$.
(Assuming "artinian" means "every nonempty collection of ideals has a minimal element", this does not use Choice.  Assuming "artinian" means "every descending sequence of ideals stabilizes", it uses only Dependent Choice.)


text:
Q: Setting column header text for a UITableView in iPhone How do I make a UITableView column header text, like a C#/.NET grid?
I make only records, but I can't set the UITableView column header text.
And I want proper formating in UITableView..

A: If I understood you correctly I think you need this
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section

A: That's because a table view is not a .Net grid. If you want to have grid-like layout in your tableview, look at iPhone Multiple Columns in UITableView or iPhone + UITableView with multiple columns


text:
Q: How to push to protected branches in a GitHub Action I have a GitHub Action workflow to create a new version and publish after merge to our master branch .However, master branch has a protection.1 solution that was tested successfully was to create PAT with admin permission then use that instead of the generated token by GitHub Action with limited permission, uncheck the "include administrators" on the branch protection rule. We don't want to uncheck the "include administrators" on the branch protection rule. please is there a way to solve this issue without changing anything on branch protection rules for your our master branch. thanks inadvance guys!!
steps:
      - uses: actions/checkout@v2
        with:
          fetch-depth: 0
          persist-credentials: false

      - name: Changelog Actions
        id: changelog
        uses: TriPSs/conventional-changelog-action@v3
        with:
          github-token: ${{ secrets.PAT_ACCESS }}

      - name: create releases
        uses: actions/create-release@v1
        if: ${{ steps.changelog.outputs.skipped == 'false'}}
        env:
          GITHUB_TOKEN: ${{ secrets.PAT_ACCESS }}
        with:
          tag_name: ${{ steps.changelog.outputs.tag }}
          release_name: ${{ steps.changelog.outputs.tag }}
          body: ${{ steps.changelog.outputs.clean_changelog }}

Error message generated when run with "include administrators" branch protection rule in place

remote: error: GH006: Protected branch update failed for refs/heads/master.
remote: error: At least 1 approving review is required by reviewers with write access.


text:
Q: Getting my calculator to take a new number after the equal button is pressed So I have been at this for a while now and still cannot get my calculator to do one final thing.
I got it thanks!
After I push the equal button or Tan, Sin, Cos or Mod buttons I want my calculator to take a new number. Basically as if nothing was in the textbox even though the answer is still there. Currently, all the numbers stay and the new number is added to the end. I do not want this to happen.
After the calculation, if I push a number button I want it to clear the screen and add the new number fresh. Below is my code that I have so far.
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }
    Double FirstNumber;
    string mathOperator = "";

    private void AddButton_Click(object sender, EventArgs e)
    {
        FirstNumber = Convert.ToDouble(DisplayTextBox.Text);
        mathOperator = "+";

        DisplayTextBox.Text = "";
        DisplayTextBox.Focus();

    }
    private void EqualButton_Click(object sender, EventArgs e)
    {
        Double SecondNumber;
        SecondNumber = Convert.ToDouble(DisplayTextBox.Text);

        switch (mathOperator)
        {
            case "+":
                DisplayTextBox.Text = (FirstNumber + SecondNumber).ToString();
                break;
            case "-":
                DisplayTextBox.Text = (FirstNumber - SecondNumber).ToString();
                break;
            case "*":
                DisplayTextBox.Text = (FirstNumber * SecondNumber).ToString();
                break;
            case "/":
                DisplayTextBox.Text = (FirstNumber / SecondNumber).ToString();
                break;
            default:
                break;
        }
    }

    private void button12_Click(object sender, EventArgs e)
    {
        FirstNumber = Convert.ToDouble(DisplayTextBox.Text);
        FirstNumber *= -1;
        DisplayTextBox.Text = FirstNumber.ToString();

    }

    private void ButtonMinus_Click(object sender, EventArgs e)
    {

        FirstNumber = Convert.ToDouble(DisplayTextBox.Text);
        mathOperator = "-";

        DisplayTextBox.Text = "";
        DisplayTextBox.Focus();

    }

    private void ButtonMultiply_Click(object sender, EventArgs e)
    {

        FirstNumber = Convert.ToDouble(DisplayTextBox.Text);
        mathOperator = "*";

        DisplayTextBox.Text = "";
        DisplayTextBox.Focus();

    }

    private void ButtonDivide_Click(object sender, EventArgs e)
    {

        FirstNumber = Convert.ToDouble(DisplayTextBox.Text);
        mathOperator = "/";

        DisplayTextBox.Text = "";
        DisplayTextBox.Focus();

    }

    private void ButtonMod_Click(object sender, EventArgs e)
    {
        FirstNumber = Convert.ToDouble(DisplayTextBox.Text);
        DisplayTextBox.Text = Math.Tan(FirstNumber).ToString();

    }

    private void Button1_Click(object sender, EventArgs e)
    {
        DisplayTextBox.Text = DisplayTextBox.Text + "1";
    }

    private void Button2_Click(object sender, EventArgs e)
    {
        DisplayTextBox.Text = DisplayTextBox.Text + "2";
    }

    private void Button3_Click(object sender, EventArgs e)
    {
        DisplayTextBox.Text = DisplayTextBox.Text + "3";
    }

    private void Button4_Click(object sender, EventArgs e)
    {
        DisplayTextBox.Text = DisplayTextBox.Text + "4";
    }

    private void Button5_Click(object sender, EventArgs e)
    {
        DisplayTextBox.Text = DisplayTextBox.Text + "5";
    }

    private void Button6_Click(object sender, EventArgs e)
    {
        DisplayTextBox.Text = DisplayTextBox.Text + "6";
    }

    private void Button7_Click(object sender, EventArgs e)
    {
        DisplayTextBox.Text = DisplayTextBox.Text + "7";
    }

    private void Button8_Click(object sender, EventArgs e)
    {
        DisplayTextBox.Text = DisplayTextBox.Text + "8";
    }

    private void Button9_Click(object sender, EventArgs e)
    {
        DisplayTextBox.Text = DisplayTextBox.Text + "9";
    }

    private void ButtonClear_Click(object sender, EventArgs e)
    {
        DisplayTextBox.Text = "";
        mathOperator = "";
    }

    private void ButtonOff_Click(object sender, EventArgs e)
    {
        Application.Exit();
    }

    private void ButtonTan_Click(object sender, EventArgs e)
    {
        FirstNumber = Convert.ToDouble(DisplayTextBox.Text);
        DisplayTextBox.Text = Math.Tan(FirstNumber).ToString();
    }

    private void ButtonSin_Click(object sender, EventArgs e)
    {
        FirstNumber = Convert.ToDouble(DisplayTextBox.Text);
        DisplayTextBox.Text = Math.Sin(FirstNumber).ToString();

    }

    private void ButtonCos_Click(object sender, EventArgs e)
    {
        FirstNumber = Convert.ToDouble(DisplayTextBox.Text);
        DisplayTextBox.Text = Math.Cos(FirstNumber).ToString();

    }

    private void Button0_Click(object sender, EventArgs e)
    {
        if (DisplayTextBox.Text.Length >= 1)
        {
            DisplayTextBox.Text = DisplayTextBox.Text + "0";
        }
        else
        {
            return;
        }
    }

    private void DecimalButton_Click(object sender, EventArgs e)
    {
        if (DisplayTextBox.Text.Contains("."))
        {
            return;
        }
        else
        {
            DisplayTextBox.Text = DisplayTextBox.Text + ".";
        }
    }
}

A: Add a Boolean variable to your class that represents a flag of whether or not an operation has  just completed or not, like this:
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }
    Double FirstNumber;
    string mathOperator = "";
    bool operationJustCompleted = false;

Initially, the value will be false, because nothing has happened when the calculator is first created.
Now, at the end of the equal button event handler, set the flag to true, like this:
private void EqualButton_Click(object sender, EventArgs e)
{
    // Logic for calculation

    operationJustCompleted = true;
}

Finally, in the event handlers for the number buttons, check to see if the operationJustCompleted flag is true, if so then clear the text and reset the operation just completed flag back to false; like this:
private void Button1_Click(object sender, EventArgs e)
{
    if(operationJustCompleted)
    {
        DisplayTextBox.Text = String.Empty;
        operationJustCompleted = false;
    }
    DisplayTextBox.Text = DisplayTextBox.Text + "1";
}

A: Add a state variable to your class. When true, and a number is selected, clear the display and set it false before writing the number.
When "=" is clicked, set it true.

A: Based on a brief review, seems like you need to introduce a variable that will keep track of the calculator's state, and then when "equal" button is pressed, set the state to calculated value.  Then, in the numeric buttons (0-9) you need to check the state variable and either append to or replace the display text.

A: Create this global variable...
private bool equationComplete = false;

Add this to the end of the Equals button...
equationComplete = true;

Add this to the beginning of each number button click...
if (equationComplete) DisplayTextBox.Text = "";

Add this to the end of each number button click event handler...
equationComplete = false;

A: Just like David Arno says, something like this:
    private void EqualButton_Click(object sender, EventArgs e)
    {
        ClearDisplayBeforeNextTextEntry = true;
    }

    private void Button1_Click(object sender, EventArgs e)
    {
        // New code
        ClearText();
        // Old code
        DisplayTextBox.Text = DisplayTextBox.Text + "1";
    }

    // Same for all other number buttons as above

    private void ClearText()
    {
        if (ClearDisplayBeforeNextTextEntry)
        {
            DisplayTextBox.Text = "";
            ClearDisplayBeforeNextTextEntry = false;
        }
    }


text:
Q: Speeding up R Loops in an EM algorithm implementation I am writing an implementation of the EM algorithm to estimate parameters in a GLMM in R. My model is $$y_{ij}|\alpha_i \sim Bin(1,p_{ij})\textrm{, where }logit(p_{ij}) =  \mu + \alpha_i \textrm{ and } \alpha_i \,\,iid \sim N(0,\sigma^2).$$ In other words, my data has a binary response that can be modeled with a fixed intercept, $\mu$, and a random effect, $\alpha_i$.
I am interested in performing EM for the sake of better robustness than I'd get through an ML or REML estimator like the ones used in lmer. My procedure for estimating $\mu$ and $\sigma^2$ goes as follows:

*

*Choose starting values for $\mu$ and $\sigma^2$ based on REML estimates.

*Using Metropolis-Hastings, randomly generate L $\alpha_i$ vectors.

*Compute the expectation for the log-likelihood for $\mu$ and $\sigma^2$ using the L simulated values of $\alpha_i$ in a pretty standard Monte Carlo scheme.

*Maximize the expectation in (3) wrt $\mu$ and $\sigma^2$.

*Use these maximize estimates as new starting values, and return to (1).

*Repeat k times. This produces two k-length vectors, $\bf{\mu}$ and $\bf{\sigma^2}$.

My concern is the following: speed. I have largely vectorized the procedure, but my program chokes takes awhile for values of L larger than 5,000 and k$\geq$100. I have determined that the slowest step is unfortunately Step 6. This could mean that any of the steps 1-5 are slow. I suspect that because of the slowdown with high L, the slowdown occurs during the M-step. My likelihood is separable wrt $\mu$ and $\sigma^2$ (no cross-products), so instead of one multivariate optimization, I am able to get by with two single-variable optimizations, which has sped up the computation.
Things I would like:

*

*Is there a way to compile R code? I call an intensive series of functions thousands of times. Variables are pre-allocated before assignments and functions are all vectorized, so I can't imagine many more gains in speed in those areas. Compiling the code would drastically improve my run time. My code is already written, so I'm very averse to converting it to C or C++.

*I have been using the optimize() function on the relevant parts of the log-likelihood to get the appropriate maximizations of $\mu$ and $\sigma^2$ at the given iteration. In MCEM problems in the mixed models framework, is there an algorithm or function that leverages the structure better than a general optimization routine that could give me better run times?

A: In case someone else is interested, digging into the issue, a friend of mine found a post from Dirk Eddelbuettel's blog about the R compiler added in 2.13.0. It did not give amazing speed increases because most of my functions were already vectorized and I only had a couple for-loops, but someone else may find it useful. The hope was to avoid writing the code in C or C++, and this compiler does that, though there are better options.
Thinking Inside the Box, Dirk Eddelbuettel, April 12, 2011.


text:
Q: Is it possible to zip the contents of a directory in C#? Im developing a c# application which has to zip all the content within a directory..
Is this possible?
thanks

A: Yes you can.DotNetZip supports adding a Directory to a zip file with the ZipFile.AddDirectory() methods.
To zip up an entire directory, recursively:
using (ZipFile zip = new ZipFile())
{
  zip.UseUnicode= true;  // utf-8
  zip.AddDirectory(@"MyFile");
  zip.Save(ZipFileToCreate);
}

A: See the documentation for class ZipFile at http://msdn.microsoft.com/en-us/library/system.io.compression.zipfile(v=vs.110).aspx.
UPDATE: This class is only available in .NET 4.5, which is not installed as part of Windows 7.  You would have to download it from Microsoft.

A: You can use also SevenZipSharp like so:
SevenZipCompressor compressor = new SevenZipCompressor();
compressor.CompressDirectory(...);


text:
Q: Using Gulp's browser-sync with MAMP in localhost testing environment I have searched around but no posts pinpointed the pitholes to avoid when using Gulp's BrowserSync with a localhost testing environment. So here is this post.
I am using gulp browser-sync, doing testing with MAMP. Right now I cannot get my browser-sync watch to work. I want to reload browser whenever I save my files.
Under MAMP settings,

*

*Apache port: 80

*Nginx port: 80

*MySQL port: 3306

gulpfile.js
var gulp = require('gulp');
var browserSync = require('browser-sync'); // create a browser sync instance.

//tasks for development
// Start browserSync server
gulp.task('browserSync', function() {
  browserSync({
    server: {
        baseDir: "app"
    },
    proxy: "localhost:8080" // can be [virtual host, sub-directory, localhost with port]
});

gulp.task('watch', ['browserSync'], function () {
  gulp.watch('app/*.{php,css,js}', browserSync.reload);
});

Since we are talking about MAMP here, my directory is in htdocs/test as shown below:

Also, my index.php file is inside /app
I am thinking I have made mistakes on many levels but right now any combination of my solutions doesnt seem to help and Ive spent hours on this. Any suggestions?

A: Finally got it to work.
var gulp        = require('gulp');
var browserSync = require('browser-sync').create();

gulp.task('default', function() {
    browserSync.init({
        proxy: "http://localhost/test/app"
    });
    gulp.watch("./app/*.php").on("change", browserSync.reload);
});

Few things to look out for that the documentation might not explicitly mention:

*

*Do not miss out .create and .init() as we are referring to an instance here.

*If you are using some test local server like MAMP, be careful to use 'proxy' instead of 'server'.

*Note the URL address I am using refers to the position of the index.php

*Lastly, '.on("change", browserSync.reload)' to RELOAD on CHANGE.

Hope my day spent on this saved you some time.

A: I was struggling with this and found an updated solution that works w/ both MAMP and custom local dev proxies.
In the gulpfile.js gulp.task( 'browser-sync', function() block I removed:
browserSync.init( cfg.browserSyncWatchFiles, cfg.browserSyncOptions );
and replaced with
browserSync.init({
        proxy: "your/local/dev/url/here"
    });

Hope that saves someone some time!


text:
Q: Call a javascrip function in a button's link option from Divi (wordpress theme) First of all, thank you in advance for any help you can give me.
I'm not a coder, at all.
I'm a photographer (https://lucky4shop.pt/portfolio/) that just happens to know a bit about Wordpress websites and can read css/html but I don't know how to code in any language.
That said, here's my problem...
I'm creating a Wordpress website with the Divi theme/builder for a restaurant that has 2 locations.
On the homepage, I created a button that activates a popup using a plugin called "Popups for Divi" that basically takes a section created by Divi Builder and makes it a popup.
The popup shows 2 buttons that come from an online ordering system called GloriaFood, each button for each restaurant.
The buttons are implemented through a shortcode.
When the user clicks one of the buttons, it shows the Menu that is created in GloriaFood but the popup doesn't go away unless the user clicks on the "X" to close it.
I'm trying to find a way for it to close automatically when the user selects one of the restaurants.
Divi Builder has an option to add a link to the code area that is created through the shortcode and I know that the popups plugin has a "hide function but I don't know how to implement that upon the action of a button click.
I'll leave some links here to relevant information:

*

*How the button is added: https://www.gloriafood.com/restaurant-ideas/add-online-ordering-button-wordpress

*Functions of the popup plugin: https://divimode.com/divi-popup/ (you have to scroll down to find them)

*Screenshot for the shortcodes

*Link option on the builder

*Advanced options of the "Code" Module, in case this helps


text:
Q: Программа должна создавать QR-code и сохранять его в виде картинки, но import qrcode

value = input('Value: ')
img = qrcode.make(value)

img.save('myqrcode.png')

после выполнения ничего не происходит

A: Как оказалось код работает.
import qrcode

value = input('Value: ')
img = qrcode.make(value)

img.save('myqrcode.png')  # 1 вариант сохраняет картинку в папке где находится скрипт
img.save('C:\\Users\\User\\Pictures\\qrcode.png') # 2 вариант сохраняет картинку в нужное место


text:
Q: node.js manage communication with the DB2 database how can i manage communication with the database in node.js?
is there any module that can i use??
i need to get adn store data from DB2 on IBM i.
At the moment i'm using Zend Framework but i want replace my php function to get store from database, to use javascript in server side with node.js
Is this a good idea? can someone give me advice if this way is efficent in terms of speed of access to the database??
i see a list of module as:  MongoDB, CouchDB and Redis but DB2 is supported? wich i can choose?
thanks!

A: I think you can use node-odbc module.
Today I succeed connecting to AIX5.3 DB2 server(V8.X) from linux machine(ubuntu 10.10) using node.js
I've installed and configured below...
1) node-odbc
2) unixODBC
3) db2 runtime client

A: Not sure if you are still looking for a solution. Thought would reply so that it will be useful for others who hit the thread.
As ryuken has mentioned you can setup node-odbc to talk to DB2 and it works fine. You can refer to the blog post "Using IBM DB2 from node.js" on configuring node.js with DB2 using node-odbc.
Thanks
Praveen


text:
Q: Django local variable 'form' referenced before assignment I m trying to make a form where user enter the state and weather of that location is given back
It was working fine untill I added cities = City.objects.all() in the code
from django.shortcuts import render
import requests
from  .models import City
def index(request):
        cities = City.objects.all() #return all the cities in the database
    url = 'http://api.openweathermap.org/data/2.5/weather?q={}&units=imperial&appid=ec2052730c7fdc28b89a0fbfe8560346'

    if request.method == 'POST': # only true if form is submitted
            form = CityForm(request.POST) # add actual request data to form for processing
    form.save() # will validate and save if validate

    form = CityForm()
    weather_data = []

    for city in cities:

            city_weather = requests.get(url.format(city)).json() #request the API data and convert the JSON to Python data types

            weather = {
            'city' : city,
            'temperature' : city_weather['main']['temp'],
            'description' : city_weather['weather'][0]['description'],
            'icon' : city_weather['weather'][0]['icon']
            }

            weather_data.append(weather) #add the data for the current city into our list

    context = {'weather_data' : weather_data, 'form' : form}
    return render(request, 'weathers/index.html', context)

UnboundLocalError at / local variable 'form' referenced before
  assignment Request Method: GET Request URL: http://127.0.0.1:8000/
  Django Version:
  2.2.1 Exception Type: UnboundLocalError Exception Value: local variable 'form' referenced before assignment Exception Location:
  C:\Users\Admin\Desktop\the_weather\weathers\views.py in index, line 12
  Python Executable:
  C:\Users\Admin\AppData\Local\Programs\Python\Python37-32\python.exe
  Python Version:
  3.7.3 Python Path: ['C:\Users\Admin\Desktop\the_weather',  'C:\Users\Admin\AppData\Local\Programs\Python\Python37-32\python37.zip',
  'C:\Users\Admin\AppData\Local\Programs\Python\Python37-32\DLLs',
  'C:\Users\Admin\AppData\Local\Programs\Python\Python37-32\lib',
  'C:\Users\Admin\AppData\Local\Programs\Python\Python37-32',
  'C:\Users\Admin\AppData\Roaming\Python\Python37\site-packages',
  'C:\Users\Admin\AppData\Local\Programs\Python\Python37-32\lib\site-packages']
  Server time: Fri, 24 May 2019 04:09:08 +0000

A: You need change:
    if request.method == 'POST': # only true if form is submitted
            form = CityForm(request.POST) # add actual request data to form for processing
    form.save() # will validate and save if validate
    form = CityForm()

to
       if request.method == 'POST': # only true if form is submitted
            form = CityForm(request.POST) # add actual request data to form for processing
            if form.is_valid():
                 form.save() # will validate and save if validate
                 # having form in same scope when there is a post request
       else:
           form = CityForm()

A: You are making mistake here
if request.method == 'POST': # only true if form is submitted
            form = CityForm(request.POST) # add actual request data to form for processing
    form.save() # will validate and save if validate

    form = CityForm()

If request is GET the it directly go to the form.save() before its assignment.
To solve this
if request.method == 'POST':
    form = CityForm(request.POST)
    form.save()

form = CityForm()


text:
Q: How to enable image caption plugin in CKeditor? I installed the enhanced image plugin for ckeditor, and place this code on my my page:
<script>
        CKEDITOR.replace( 'editor1', {
            config.extraPlugins: 'image2',
            height: 450
        } );
    </script>

The rich textarea no longer displays, except I use
<script>
CKEDITOR.replace( 'editor1' );
 </script>

Which does not  allow image caption functionality. What could be wrong?

A: Second argument in CKEDITOR.replace is config itself. That's why you should define it as follows:
CKEDITOR.replace( 'editor1', {
    extraPlugins: 'image2',
    height: 450
} );


text:
Q: Responsecode N/A in CodeCeption REST with Laravel I have a RESTful API that I want to test using codeception.
The REST module for codeception seems to be having trouble retrieving responsecode and contents.
Here is the full stack trace:
$ ./vendor/codeception/codeception/codecept run --debug Codeception PHP Testing Framework v1.8.0-dev Powered by PHPUnit 3.7.28 by Sebastian Bergmann.

Acceptance Tests (0) ------------------------ Modules: PhpBrowser, WebHelper
---------------------------------------------
---------------------------------------------

Api Tests (1)
--------------------------------------------------------------------- Modules: PhpBrowser, WebHelper, REST, ApiHelper, Laravel4
----------------------------------------------------------------------------------- Trying to verify that i can retrieve a vehicle (GetVehicleInfoCept.php)        Scenario:
* I am http authenticated "root","root"
* I send get "v1/voertuigen/62jtvg",   [Request] GET http://imac-van-maarten.local/voertuiginformatiemodule/public/v1/voertuigen/62jtvg [Response] {"provider":"A2SP","kenteken":"62JTVG","merk":"Seat","model":"IBIZA","primaire_kleur":"GRIJS","uitvoering_id":"241757001936","eerste_toelating":"20020828","laatste_tenaamstelling":"20130204","primaire_brandstof":"benzine"} [Headers] {"date":["Thu, 31 Oct 2013 09:00:28 GMT"],"server":["Apache\/2.2.23 (Unix) mod_ssl\/2.2.23 OpenSSL\/0.9.8y DAV\/2 PHP\/5.4.10"],"x-powered-by":["PHP\/5.4.10"],"set-cookie":["laravel_session=7427bb97beee80b7abcf2a632ba9ecf7; expires=Thu, 31-Oct-2013 11:00:28 GMT; path=\/; HttpOnly","laravel_session=7427bb97beee80b7abcf2a632ba9ecf7; expires=Thu, 31-Oct-2013 11:00:28 GMT; path=\/; httponly"],"cache-control":["no-cache"],"transfer-encoding":["chunked"],"content-type":["application\/json"]} [Status] 200
* I see response is json
* I see response code is 200  FAIL

-----------------------------------------------------------------------------------

Functional Tests (0) ------------------------ Modules: Filesystem, TestHelper, Laravel4
---------------------------------------------
---------------------------------------------

Unit Tests (0) ------------------------------ Modules: CodeHelper
---------------------------------------------
---------------------------------------------

Time: 464 ms, Memory: 18.25Mb

There was 1 failure:

--------- 1) Failed to verify that i can retrieve a vehicle in GetVehicleInfoCept.php Sorry, I couldn't see response code is 200: Failed asserting that 'N/A' matches expected 200.

Scenario Steps:
4. I see response code is 200
3. I see response is json
2. I send get "v1/voertuigen/62jtvg",
1. I am http authenticated "root","root"

FAILURES! Tests: 1, Assertions: 2, Failures: 1.

Clearly the response code is 200, but somehow it cannot retrieve the responsecode. What is going on here?


text:
Q: How to Java Map Stream multiple Condition from int Array to String Array Hi guys can u help me i have a problem here,
i have list book:
1.Math Rp.15.000
2.Sains Rp.18.000
3.Geologi Rp.16.000
4.Biologi Rp.12.000
The user enters the book number he chooses, then he got the array
int[] arrayNumberBookTake = {1,2,4};

Then I want to change the value of the array to a new value and it depends on the price in the list
int[] listBooktoPrice= Arrays.stream(arrayNumberBookTake).map(i -> i == 1 ? 15000 : i == 2 ? 18000 : i == 3 ? 16000 : i == 4 ? 12000 : i).toArray();

it working and the output of array listBooktoPrice :
[15000, 18000, 12000]

now i want to make a new array it convert from arrayNumberBookTake to an String
String[] nameBookTake = Arrays.stream(arrayNumberBookTake).map(i -> i == 1 ? "Math" : i == 2 ? "Sains " : i == 3 ? "Geologi" : i == 4 ? "Biologi" : i).toArray();

but that code not work, i want array nameBookTake like this:
{"Math", "Sains", "Geologi"}

array nameBookTake should depends from the array arrayNumberBookTake and match with list book on top.
I hope u guys understand what i means, thx u guys :)

A: Your last conditional ends with the parameter i. This is an int, not a String. Therefor the array is not uniform; adding ints to an Array of String is not permitted.
Solution: delete the last conditional surrounding "Biologi".
Furthermore, Java streams differ between primitives (like int) and objects (like String).
To convert the IntStream into the Stream of String, one can use mapToObj, and collect with passing the constructor of the String[] to toArray().
like so:
        String[] nameBookTake = Arrays.stream(arrayNumberBookTake)
                .mapToObj(i -> i == 1 ? "Math" : i == 2 ? "Sains " : i == 3 ? "Geologi" : "Biologi" )
                .toArray(String[]::new);

This answers your question.
However: as Andy Turner pointed out, using conditionals in this manner is a bad practice. Better practice is to use a switch, like so:
        String[] nameBookTake = Arrays.stream(arrayNumberBookTake)
                .mapToObj( i -> switch( i )
                        {
                            case 1 -> "Math";
                            case 2 -> "Sains";
                            case 3 -> "Geologi";
                            case 4 -> "Biologi";
                            default -> "Unknown book!";
                        } )
                .toArray(String[]::new);

Better still is to bundle the properties of a Book into its separate class, in this case an Enum, yielding a complete solution:
@Log4j2
public class Main
{
    public static void main( String[] args )
    {
        int[] arrayNumberBookTake = {1,2,4};
        int[] listBooktoPrice= Arrays.stream(arrayNumberBookTake)
                .map( i -> Books.values()[ i ].price )
                .toArray();

        String[] nameBookTake = Arrays.stream(arrayNumberBookTake)
                .mapToObj( i -> Books.values()[ i ].name  )
                .toArray(String[]::new);
    }
}

enum Books
{
    Math("Math", 15_000 ),
    Sains("Sains", 18_000 ),
    Geologi( "Geologi", 16_000 ),
    Biologi( "Biologi", 12_000 );

    String name;
    int price;

    Books( String name, int price )
    {
        this.name = name;
        this.price = price;
    }
}


text:
Q: How to see if PlayerInput action was performed? Unity, New Input System I'm using the new inptu system, and i want a way to see if an input action has been performed (only once, like GetButtonDown).
If I use ".ReadValue()", the if statement returns true not only once, but for as long as the "inventoryAction button" is held down.
    private void Awake()
    {
        playerInput = GetComponent<PlayerInput>();
        inventoryAction = playerInput.actions["Inventory"];
    }
    private void Update()
    {
         if (inventoryAction.ReadValue<float>() == 1)
         {
            Debug.Log("inventory key was pressed");
         }

    }

How do I only get the "performed" part in an if statement (with the new input system)? Is there something like GetButtonDown in the new input system?

A: Starting with version 1.1.1, actions have a WasPressedThisFrame method which basically does this.
The documentation(linked above) includes the following code snippet:

var fire = playerInput.actions["fire"];
if (fire.WasPressedThisFrame() && fire.IsPressed())
    StartFiring();
else if (fire.WasReleasedThisFrame())
    StopFiring();

As the code example shows, there are also WasReleasedThisFrame and IsPressed which are essentially GetButtonUp and GetButton, respectively.
Note that there are special considerations to make that make them behave differently than GetButtonX calls, especially where buttons release and press thresholds are substantially different, or where buttons are pressed and released multiple times in a frame.
1.1.1 IsPressed docs:

This method is different from simply reading the action's current float value and comparing it to the press threshold and is also different from comparing the current actuation of activeControl to it. This is because the current level of actuation might have already fallen below the press threshold but might not yet have reached the release threshold.
This method works with any type of action, not just buttons.
Also note that because this operates on the results of EvaluateMagnitude(), it works with many kind of controls, not just buttons. For example, if an action is bound to a StickControl, the control will be considered "pressed" once the magnitude of the Vector2 of the control has crossed the press threshold.
Finally, note that custom button press points of controls (see pressPoint) are respected and will take precedence over defaultButtonPressPoint.

1.1.1 WasPressedThisFrame docs:

This method is different from WasPerformedThisFrame() in that it is
not bound to phase. Instead, if the action's level of actuation (that
is, the level of magnitude -- see EvaluateMagnitude() -- of the
control(s) bound to the action) crossed the press threshold (see
defaultButtonPressPoint) at any point in the frame, this method will
return true. It will do so even if there is an interaction on the
action that has not yet performed the action in response to the press.
This method works with any type of action, not just buttons.
Also note that because this operates on the results of
EvaluateMagnitude(), it works with many kind of controls, not just
buttons. For example, if an action is bound to a StickControl, the
control will be considered "pressed" once the magnitude of the Vector2
of the control has crossed the press threshold.
Finally, note that custom button press points of controls (see
pressPoint) are respected and will take precedence over
defaultButtonPressPoint.

Be sure to read the documentation for your version for more information.


text:
Q: RewriteRule not redirect properly I am formating the redirect of my site URL using this.
I got a problem on redirecting properly.
CASE 1:
RewriteEngine on

RewriteRule ^([a-zA-z0-9_-]*)$  user/profile.php?id=$1 [L,NC]
RewriteRule ^([a-zA-z0-9_-]*)/([a-zA-z0-9_-]*)$  user/profile.php?id=$1&page=$2 [L,NC]

The code is alright when accessing the profile page, the actual url is (user/profile.php)
http://thisismysite.com/1234567

however I can't access the main index, it is still redirect to (user/profile.php)
http://thisismysite.com
CASE 2:
RewriteEngine on

RewriteRule ^([a-zA-z0-9_-]*)$/  user/profile.php?id=$1 [L,NC]
RewriteRule ^([a-zA-z0-9_-]*)/([a-zA-z0-9_-]*)$  user/profile.php?id=$1&page=$2 [L,NC]

in this case, I can access the main index and the profile but I need to add '/' at the end
http://thisismysite.com/1234567/

But I don't want the backslash to appear at the end?
What should I do?
Thanks

A: For case 1 replace * with + so your rule looks like this:
RewriteRule ^([a-zA-z0-9_-]+)$  user/profile.php?id=$1 [L,NC]
That should take care of being able to see the index but still redirecting to the user profiles when you have a profile url.

A: For add / at the end
RewriteRule ^([a-zA-z0-9_-]*)/$  user/profile.php?id=$1 [L,NC]


text:
Q: jQuery Selector as Function Parameter In the following code I attempt to pass a jQuery listView selector to the function "makeObject" as a parameter. The problem I'm having is that the code doesn't recognize the .listview method of the selector in the function "createList".
I'd like a solution that does simply pass in a string and reconstruct the selector inside
the called function.

A: Don't you just want to rather do this:
    $("#testList").append('
item 3
')

Or
    function makeObject(selector) {
         $(selector).append('
item 3
')
    }


text:
Q: Pandas Series partial Replacement Let's say I have a state column in pandas dataframe like this:
This is sample data. Actual may differ.
df = pd.DataFrame({"state": ["Uttar Pradesh", "Jammu & Kashmir", "Jammu&Kashmir", "Puducherry"]})

Now task is to change Jammu & Kashmir to Jammu and Kashmir and Puducherry to Pondicherry
So I create a dictionary for this
STATE_MAP_DICT = {
    "jammu&kashmir": "Jammu and Kashmir",
    "orissa": "Odisha",
    "orrissa": "Odisha",
    "puducherry": "pondicherry",
    "damananddiu": "Dadra and Nagar Haveli"
}

then
df['state'] = df["state"].astype(str).str.replace(' ','').str.lower().replace(STATE_MAP_DICT)

Expectation :
["Uttar Pradesh", "Jammu and Kashmir", "Jammu and Kashmir", "pondicherry"]

Output :
["uttarpradesh", "Jammu and Kashmir", "Jammu and Kashmir", "pondicherry"]  # Uttar Pradesh
Changed since i used replace() and lower()
Is there any way to resolve this?

A: Just add the following entries to your dictionary:
{
  'pondicherry': 'Pondicherry',
  'uttarpradesh' 'Uttar Pradesh'
}

Alternatively, use a custom function instead of str:
def f(s):
  s2= s.replace(' ', '').lower()
  if s2 in STATE_MAP_DICT:
    return STATE_MAP_DICT[s2]
  return s

df['state'] = df["state"].apply(f)

A: You can use map and fillna methods.
df["state"] = df["state"].astype(str).str.replace(' ','').str.lower().map(STATE_MAP_DICT).fillna(df["state"])

Output:
    state
0   Uttar Pradesh
1   Jammu and Kashmir
2   Jammu and Kashmir
3   pondicherry

A: You can use numpy.where and check if value exists in dictionary keys after replacement and making strings lower. If so, we wanna replace it, if not - we leave it without changes:
import numpy as np

val = df["state"].str.replace(' ','').str.lower()

df['state'] = np.where(val.isin(STATE_MAP_DICT.keys()),
                       val.replace(STATE_MAP_DICT),
                       df['state']
                       )

Output:
                state
0       Uttar Pradesh
1   Jammu and Kashmir
2   Jammu and Kashmir
3         pondicherry


text:
Q: find connected components of filtered graph How can I calculate the connected components of a filtered graph using BGL?  I've created a working filter that checks against a custom vertex property called "alive" and returns only the "living" vertices but connected_components chokes on the filtered_graph .  I think it has something to do with the fact that the filtered graph has non-contiguous vertex ids and therefore an operator[] that was defined is now no longer defined but I'm not sure why or how to code around it.
typedef boost::adjacency_list<boost::hash_mapS, boost::vecS, boost::undirectedS, VertexProperties> Graph;
typedef boost::property_map<Graph, ::vertex_alive_t>::type AliveMap;

template <typename AliveMap>
struct vertex_is_alive {
  vertex_is_alive() { }
  vertex_is_alive(AliveMap alive) : m_alive(alive) { }
  template <typename Vertex>
  bool operator()(const Vertex& v) const {
    return boost::get(m_alive,v) == STILL_ALIVE_CODE;
  }
  AliveMap m_alive;
};

Graph G;
//generate G...
int N = boost::num_vertices(G);
vector<int> component(N);
int num = boost::connected_components(G, &component[0]);
//do something with component and play around with vertex_alive statuses...this part works fine.
vertex_is_alive<AliveMap> filter(boost::get(::vertex_alive_t(), G));
boost::filtered_graph<Graph, vertex_is_alive<AliveMap> > fG (G, filter);
int num = boost::connected_components(fG, &component[0]);
//this makes it choke

The error messages that I get are (removing the genealogy):
/usr/local/include/boost/property_map/property_map.hpp:354:56: error: no match for 'operator[]' in '((const boost::vec_adj_list_vertex_property_map<boost::adjacency_list<boost::hash_mapS, boost::vecS, boost::undirectedS, boost::property<vertex_alive_t, unsigned int> >, boost::adjacency_list<boost::hash_mapS, boost::vecS, boost::undirectedS, boost::property<vertex_alive_t, unsigned int> >*, unsigned int, unsigned int&, vertex_alive_t>&)pa)[k]'
/usr/local/include/boost/property_map/property_map.hpp:354:56: note: candidate is:
In file included from /usr/local/include/boost/graph/adjacency_list.hpp:245:0,
                 from main.cpp:1:
/usr/local/include/boost/graph/detail/adjacency_list.hpp:2465:24: note: Reference boost::vec_adj_list_vertex_property_map<Graph, GraphPtr, ValueType, Reference, Tag>::operator[](boost::vec_adj_list_vertex_property_map<Graph, GraphPtr, ValueType, Reference, Tag>::key_type) const [with Graph = boost::adjacency_list<boost::hash_mapS, boost::vecS, boost::undirectedS, boost::property<vertex_alive_t, unsigned int> >; GraphPtr = boost::adjacency_list<boost::hash_mapS, boost::vecS, boost::undirectedS, boost::property<vertex_alive_t, unsigned int> >*; ValueType = unsigned int; Reference = unsigned int&; Tag = vertex_alive_t; boost::vec_adj_list_vertex_property_map<Graph, GraphPtr, ValueType, Reference, Tag>::key_type = unsigned int]
/usr/local/include/boost/graph/detail/adjacency_list.hpp:2465:24: note:   no known conversion for argument 1 from 'const boost::detail::edge_desc_impl<boost::undirected_tag, unsigned int>' to 'boost::vec_adj_list_vertex_property_map<boost::adjacency_list<boost::hash_mapS, boost::vecS, boost::undirectedS, boost::property<vertex_alive_t, unsigned int> >, boost::adjacency_list<boost::hash_mapS, boost::vecS, boost::undirectedS, boost::property<vertex_alive_t, unsigned int> >*, unsigned int, unsigned int&, vertex_alive_t>::key_type {aka unsigned int}'

A: You should use boost::filtered_graph > fG (G, boost::keep_all(), filter);. The signature for the filtered graph is filtered_graph<Graph, EdgePredicate, VertexPredicate> so you were using your vertex filter as an edge one. The last line in your error implies that boost::get(m_alive,x) requires that x be a vertex descriptor (unsigned int) and it was being passed an edge descriptor (const boost::detail::edge_desc_impl<boost::undirected_tag, unsigned int>).


text:
Q: Sync single accounts calendar I have added 2 accounts in Outlook. For Ex. consider them as 'A' and 'B'. My problem is that the calendar events from the account B are automatically synchronized to calendar events in A, So every time I will have to delete the calendar events of B in A.
How can I stop synchronizing B's calendar in A ? I would like to view them by their corresponding accounts ?

*

*Account A is Office 365 account

*Account B is IMAP account(of Gmail).

*MS Outlook version: 2013.

A: Disabling the auto-sync option on exchange admin center will help.
Here is the reference link


text:
Q: Select previous 5 tweets based on one timestamp I have a tweets table that looks like this:
tweet_id          tweet_text       user_id    created_at
1 6.127048e+17      asfasfadsfdas       1       2015-06-21 16:33:13
2 6.128451e+17      adsgfasdgg          1       2015-06-22 15:33:13
4 6.132484e+17      adgfdasgfadg        2       2015-06-20 17:33:13
5 6.132562e+17      adgfdagfdag         2       2015-06-19 18:33:13
6 6.132867e+17      adgfdagfdhgfd       3       2015-06-21 19:33:13

I also have a similar table called allTweets, which includes all the tweets from all the users. It has these columns:
tweet_id          tweet_text       user_id    created_at

I want to loop over tweets$tweet_id and find the previous 5 tweets from allTweets which belongs to the corresponding user_id.
For example, the first tweet in tweets belongs to user_id 1 and was created_at 2015-06-21 16:33:13. I have to find out the previous 5 tweets which belongs to user_id 1 from allTweets based on this timestamp.

A: Let me reiterate my understanding of what you are asking. You need to:

*

*Iterate over each row of table "tweets" (which I am assuming is a
dataframe).

*For every row, check the user_id and the created_at
    time.

*Then go to table "allTweets" and for the particular user_id, find out the top 5 tweets that are just earlier than the time given by "created_at" for that user in step 2.

Here's one way to go about this:

*

*Split dataframe tweets based on user_id.
tweetsList <- split(tweets, tweets$user_id)
This should get your data in this format:
$1
[1] tweet_id          tweet_text       created_at
1 6.127048e+17      asfasfadsfdas      2015-06-21 16:33:13
2 6.128451e+17      adsgfasdgg         2015-06-22 15:33:13

$2
[1] tweet_id          tweet_text       created_at
4 6.132484e+17      adgfdasgfadg       2015-06-20 17:33:13
5 6.132562e+17      adgfdagfdag        2015-06-19 18:33:13

*Now, for each list element, you need to find the top 5 entries from
dataframe allTweets that are just smaller than the respective values
of "created_at" variable.
-Sort allTweets data frame by "created_at" column.
    * allTweets <- allTweets[order(allTweets$created_at)]
-Define a function that takes a vector as input and returns the 5 entries that we need from allTweets.
    * gimme5 <- function(x){tail(allTweets[x["created_at"] > allTweets$created_at, ])}
-Since this function only works on vectors, and our list is a list of dataframes, we will need to progressively subset and apply on each row of our dataframes.
    * apply(*dataframe*, 1, gimme5) #*dataframe* is for each component dataframe in our list
-Finally, we will want to apply our previous command for each dataframe component of our list. Thus, we want to apply it to tweetsList[["1"]], tweetsList[["2"]] etc. This will generate the dataframe component of the code above.
    * lapply(tweetsList, function(x) apply(x, 1, gimme5))


text:
Q: Unexpected results when using @extend for themes I'm refactoring some of my Sass code and I came across a weird issue. My code currently looks like this:
// household
$household_Sector: 'household';
$household_BaseColor: #ffc933;

// sports
$sports_Sector: 'sports';
$sports_BaseColor: #f7633e;

// the mixin to output all sector specific css
@mixin sector-css($sector_Sector,$sector_BaseColor) {

    .sector-#{$sector_Sector} {
        &%baseColor {
            background-color: $sector_BaseColor;
        }
    }

}

// execute the mixin for all sectors
@include sector-css($household_Sector, $household_BaseColor);
@include sector-css($sports_Sector, $sports_BaseColor);

.product-paging {
    h2 {
        @extend %baseColor;
    }
}

DEMO
The compiled result looks like this:
.product-paging h2.sector-household {
  background-color: #ffc933;
}

.product-paging h2.sector-sports {
  background-color: #f7633e;
}

But what I need is this:
.sector-household.product-paging h2 {
  background-color: #ffc933;
}

.sector-sports.product-paging h2 {
  background-color: #f7633e;
}

What I don't understand is why my placeholder (&%baseColor) isn't attached to the parent selector (&%baseColor) as I added the ampersand right in front of it?
Is this maybe a bug when combining & and %? Is there another solution on how to achieve what I want?
EDIT
Alright I figured out why this isn't possible. Anyway is there a workaround for what I'd like to achieve?

A: Extends, as you've already discovered, can get rather messy.  I would go about solving your problem by using an @content aware mixin in combination with global variables (this uses mappings, which are part of 3.3... you can do it with lists of lists, but it's a little less elegant):
$base-color: null; // don't touch
$accent-color: null; // don't touch

$sections:
    ( household:
        ( base-color: #ffc933
        , accent-color: white
        )
    , sports:
        ( base-color: #f7633e
        , accent-color: white
        )
    );

// the mixin to output all sector specific css
@mixin sector-css() {
    @each $sector, $colors in $sections {
        $base-color: map-get($colors, base-color) !global;
        $accent-color: map-get($colors, accent-color) !global;
        &.sector-#{$sector} {
            @content;
        }
    }
}

.product-paging {
    @include sector-css() {
        h2 {
            background-color: $base-color;
        }
    }
}

Output:
.product-paging.sector-household h2 {
  background-color: #ffc933;
}

.product-paging.sector-sports h2 {
  background-color: #f7633e;
}

Update:  Since you want to guarantee that the sector class is always at the top, you just need to switch around a little.
@mixin sector-css() {
    @each $sector, $colors in $sections {
        $base-color: map-get($colors, base-color) !global;
        $accent-color: map-get($colors, accent-color) !global;
        .sector-#{$sector} {
            @content;
        }
    }
}

@include sector-css() {
    &.product-paging {
        h2 {
            background-color: $base-color;
        }

        h3 {
            background-color: #CCC;
        }

        h2, h3 {
            color: $accent-color;
        }
    }
}


text:
Q: Android back button and onResume() I have a "main" activity with a button that starts a second activity using:-
var intent = new Intent(Context, typeof(EditFormActivity));
Context.StartActivity(intent);

When I tap the phone's "back" button from the second activity, I was surprised to see that the "main" activity's OnCreateView() gets called. I was under the impression that only its OnResume() method would be called. What am I missing?
(I'm still new to Android so it's probably my misunderstanding of the Activity lifecycle).
Edit
I neglected to mention that the events are in a fragment that Resides in the main activity. Apologies for the confusion.

A: The onCreateView is not really part of the Activity Lifeycle. But onResume() is.
You must have made a confusion with onCreate().
EDIT:
The onCreateView of a fragment is called when the activity starts and when it resumes. No, the onResume() method won't be the only one called. This happens because when you pause your activity, the fragment is detached from it. So when you resume the activity, the fragment has to be re-attached and this causes the call of onCreateView.
Here's the fragment lifecycle for you to understand how it works:

A: Method onCreateView() is part of fragment's lifecycle, not activity's lifecycle.
Fragment does not need to be destroyed to call onCreateView().
Check this for managing fragment's lifecycle.


text:
Q: How to override regular expression within the range of strings that satisfies another regular expression I want to find regular expression for double quoted string.For that I have simply put the following expression
\".*\"

But the problem is if some strings that match with another regular expression come within double quotes the above expression will not match with it.
For eg: If we want to give particular color for double quoted string that also contains strings (for eg: keyword or number, providing different color for keywords and numbers) that matches with another regular expression will not give the expected result.ie, if a keyword or number appears within double quotes it will take the color of keyword or number itself instead of taking color of double quoted string.How can I resolve this?Is there any way to override regular expression within another expression?

A: "[^"]+"|\d+

Try your regex this way.Put "" quote regex the first with other regexes after it piped along.This way "" will be consumed first and rest of the regex will not apply over it.See demo.
https://regex101.com/r/rU8yP6/2


text:
Q: How can I debug the Modx "mxCalendar" extra? I hope someone is here, who is familiar with the cms Modx.
I installed the extra "mxCalendar" and my button "Create New Calendar Item" is not working. I click on it and nothing happens.
Can you help me?

A: mxCalendar is not actively maintained anymore. Which MODX version are you using? mxCalendar does not work in MODX 2.3 and up, according to this list.
I suggest to use another calendar system like integrating Google Calendar or use regular resources and add some date/time tv's to work with dates. It really depends on how you want to use the calendar. Think about questions like:

*

*Do I need (auto) recurring events?

*Can an event occupy multiple days?

If both questions are anwsered with 'yes', than it could become technically very complex in my experience. The best way to go is embedding Google Calendar, or it's API.


text:
Q: Difference between Outlook.MailItem.EntryID and Mapi32.dll MessageID I need to do some functionality from outlook VBO. Let say i'm downloading attachments from the outlook.mailitem. So I do save those files by prepending OutLook.MailItem.EntryID where EntryID is unique for each Email.
Now, I have another functionality or application that uses Mapi32.dll and that need to access the Files. So I used the MessageID property to get the files, but the problem is when I retrieve MessageID property from the Mapi32.dll it returns something like AAAAAKHslFt5unxKlnJ80RmsEX8HAEYxSGm4YvNPlCN7Kj9X/A8AAAAAAQwAAEYxSGm4YvNPlCN7Kj9X/A8AAOy+SWQAAA
but the EntryID from Outlook is 1DCBEE7832C89149AFAEBC41B53EAB85
I think both EntryID and MessageID are same, but is that encrypted from MapiEx? How can I decrypt it to get original EntryID ? Or is there any other common property between Outlook.MailItem object and Mapi32.dll MailMessage object that I can use to share information between two tool ?

A: The former looks like a base64 encoded entry id. The latter looks weird - entry ids usually start with 4 binary 0's (eight "0"s in the hex notation).


text:
Q: How to add property on an object power apps I'm trying to build an app with power apps, I created a form where I collect data and then create a new object to store it in a collection, the problem is that i need to be able to modify the properties of that object and I can't.
I'm using Set() to create the object with all the properties already filled, like this :
Set(newObj, {property1: value, property2: value, property3: value; ...})

But whenever I try to Patch it to modify or add properties it does not work, nothing is added or modified
I'm doing Patch like this :
Patch(newObj, {newProperty: value, propertyToModify: value})

Do you know what i'm doing wrong ?

A: You cannot add any new property to your object with Patch.
With patch you can only add rows to this object and not change the definition of you object by adding new property.
with set you have defined your object with property1,property2 and property3.
You will have to define your object completely in set.
so it will be like
Set(newObj{property1: value, property2: value, property3: value; newProperty: value, propertyToModify: value})


text:
Q: How to delete directory using java after uploading files to Remote Server? My problem is need to transfer files from one remote server to another remote server (may be FTP/SFTP) but there is no direct method to transfer files from one remote server to another.
That's why I am downloading files from server to local temp.
After uploading to local to another server. After uploading I need to remove local temp folder but the files and the folder is not deleted.
Can you please help us in this regard?
My code is
    package FTPTransfer;

    import java.io.BufferedOutputStream;
    import java.io.FileOutputStream;
    import java.io.OutputStream;
    import java.io.PrintWriter;
    import java.io.File;
    import java.util.Calendar;

    import org.apache.commons.net.PrintCommandListener;
    import org.apache.commons.net.ftp.FTP;
    import org.apache.commons.net.ftp.FTPClient;
    import org.apache.commons.net.ftp.FTPFile;
    import org.apache.commons.net.ftp.FTPReply;

    import com.jcraft.jsch.*;

    public class FtpToSftp
    {
         JSch sftp=null;
         ChannelSftp channelSftp=null;
         Channel channel=null;
         FTPClient ftp = null;
         Session session=null;
         String SFTP_ROOT="/Mahesh/";
         String FTP_ROOT="/Mahesh/";
         String Local_Dir="./Temp/";
         int count=0;

public void ftpconnect(String host, String user, String pwd) throws Exception{

        ftp = new FTPClient();
ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));

                int reply;
                ftp.connect(host);

                if(ftp.isConnected())
                    System.out.println("FTP Connected");

                reply = ftp.getReplyCode();
                if (!FTPReply.isPositiveCompletion(reply)) {
                    ftp.disconnect();
                    throw new Exception("Exception in connecting to FTP Server");
                }

                ftp.login(user, pwd);
                ftp.setFileType(FTP.BINARY_FILE_TYPE);
                ftp.enterLocalPassiveMode();

            }

            public void sftpconnect(String host, String user, String pwd) throws Exception{
                sftp=new JSch();
                session=sftp.getSession(user,host,22);
                session.setPassword(pwd);
                 java.util.Properties config = new java.util.Properties();
                 config.put("StrictHostKeyChecking", "no");
                 session.setConfig(config);
                session.connect();
                if(session.isConnected())
                    System.out.println("SFTP Session Connected");
                channel = session.openChannel("sftp");
                channel.connect();

                 if(channel.isConnected())
                      System.out.println("SFTP Channel Connected");
                    channelSftp=(ChannelSftp)channel;

            }

            public void downloadFromFTP()throws Exception {

                File f=new File(Local_Dir);
                if(!f.exists())
                f.mkdir();

                FTPFile[] files = ftp.listFiles(FTP_ROOT);
                  count=0;
                  OutputStream outputStream=null;
                for (FTPFile fname : files) {
                 if (fname.getType() == FTPFile.FILE_TYPE) {
                     System.out.println(fname.getName());

                     File downloadFile = new File(Local_Dir+ fname.getName());
                     outputStream = new BufferedOutputStream(new FileOutputStream(downloadFile));
                     boolean success = ftp.retrieveFile(FTP_ROOT+fname.getName(), outputStream);
                     if(success)
                         count++;
                     else
                         downloadFile.delete();
                 }
                }

                if(count==files.length)
                    System.out.println("Files Downloaded Successfully");
                System.out.println("count:"+count+"files length:"+files.length);
                outputStream.close();

            }

            public void uploadToSFTP() throws Exception{

                Calendar cal = Calendar.getInstance();
                    int year = cal.get(Calendar.YEAR);
                    int month = cal.get(Calendar.MONTH)+1;//0 based
                    String foldername=month+""+year+"/";
                    String fullDirPath=SFTP_ROOT+foldername;

                    SftpATTRS attrs=null;
                    try{
                    attrs=channelSftp.lstat(fullDirPath);
                    }
                    catch(Exception e){

                    }
                     if(attrs==null)
                     {
                    channelSftp.mkdir(fullDirPath);
                    channelSftp.cd(fullDirPath);
                     }

                count=0;
                File f1 = new File(Local_Dir);
                  File list[] = f1.listFiles();
                 for(File fname  : list) {
                       System.out.println(fname);
                     channelSftp.put(fname+"", fullDirPath+fname.getName(), ChannelSftp.OVERWRITE);
                      }

                  if(count==f1.length())
                    System.out.println("Files Uploaded Successfully");

            }

       public FtpToSftp() throws Exception{

           System.out.println("Connecting to FTP");
           ftpconnect("10.219.28.110", "webteam", "web$123");
           System.out.println("Connecting to SFTP");
           sftpconnect("10.219.29.61","root" , "leo$123");

           downloadFromFTP();

           if(ftp.logout()){
               ftp.disconnect();
                System.out.println("FTP connection closed");
             }
           uploadToSFTP();
           channelSftp.disconnect();
               }

        public static final void main(String[] args)
        {

            try{
                    FtpToSftp fs=new FtpToSftp();
                    File file=new File(fs.Local_Dir);
                   if(file.isDirectory())
                   {
                       File[] files = file.listFiles();
                       for (File f : files)
                        {
                             String fname=f.getName();
                             boolean success=f.delete();
                             if(success)
                                System.out.println(fname+" file deleted from local");
                        }
                   }
                   if(file.delete())
                       System.out.println("Temp folder deleted from local");

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

        } // end main

    }

A: You can use Apache FTPClient to do this and all other common commands needed with FTP.
Example to delete a folder:
FTPClient client = new FTPClient();
client.connect(host, port);
client.login(loginname, password);
client.removeDirectory(directoryPathOnServer);
client.disconnect();

A: Here is a code snippet that deletes all the contents of the directory and the directory itself..
private void deleteDirectory(String path,FTPClient ftpClient) throws Exception{
    FTPFile[] files=ftpClient.listFiles(path);
    if(files.length>0) {
        for (FTPFile ftpFile : files) {
            if(ftpFile.isDirectory()){
                logger.info("trying to delete directory "+path + "/" + ftpFile.getName());
                deleteDirectory(path + "/" + ftpFile.getName(), ftpClient);
            }
            else {
                String deleteFilePath = path + "/" + ftpFile.getName();
                logger.info("deleting file {}", deleteFilePath);
                ftpClient.deleteFile(deleteFilePath);
            }

        }
    }
        logger.info("deleting directory "+path);
        ftpClient.removeDirectory(path);

}

A: If you want to delete an directory in your system
This is an part of example:
File x=new File("C:\Users\satyamahesh\folder");
String[]entries = x.list();
for(String s: entries){
    File currentFile = new File(x.getPath(), s);
    currentFile.delete();
}

Then your folder is deleted.
If you want test it success or don't success to download a folder
Please test Ad Fundum's answer.

A: Example to delete a folder: (@SatyaMahesh In this part your code is incorrect and this code used NIO is correct.):
File downloadFile = new File(Local_Dir+ fname.getName());
outputStream = new BufferedOutputStream(new FileOutputStream(downloadFile));
boolean success = ftp.retrieveFile(FTP_ROOT+fname.getName(), outputStream);
if(success)
  count++;
else{
  Path path = Paths.get("data/subdir/logging-moved.properties");
  try {
    Files.delete(path);
  } catch (IOException e) {
    //deleting file failed
    e.printStackTrace();
  }
}

Then your folder is deleted.


text:
Q: How do I store user data from a Tkinter GUI form? I tried adding a text file to store all the data by building a function that opens and writes data to the file, the code seems to run but no data is getting added to the text file.
Here is the tkinter code.
name = StringVar()
email = StringVar()
usn = StringVar()

namelabel = ttk.Label(frame_content, text='Name',font=('Poppins', 10))
namelabel.grid(row=0, column=0, sticky='sw', padx=(2,10))
entry_name = ttk.Entry(frame_content, width=30, font=('Poppins', 10), textvariable=name)
entry_name.grid(row=1, column=0)

emaillabel = ttk.Label(frame_content, text='Email',font=('Poppins', 10))
emaillabel.grid(row=0, column=1, sticky='sw', padx=10)
entry_email = ttk.Entry(frame_content, width=30, font=('Poppins', 10), textvariable=email)
entry_email.grid(row=1, column=1, padx=10)

usnlabel = ttk.Label(frame_content, text='USN',font=('Poppins', 10))
usnlabel.grid(row=0, column=2, sticky='sw')
entry_usn = ttk.Entry(frame_content, width=30, font=('Poppins', 10), textvariable=usn)
entry_usn.grid(row=1, column=2)

feedbacklabel = ttk.Label(frame_content, text='Feedback', font=('Poppins', 10))
feedbacklabel.grid(row=2, column=0, sticky='sw', pady=5)
textfeedback = Text(frame_content, width=94, height=15, font=('Poppins', 10))
textfeedback.grid(row=3, column=0, columnspan=3)

def submit():
    print('Name:{}'.format(name.get()))
    print('USN:{}'.format(usn.get()))
    print('Email:{}'.format(email.get()))
    print('Feedback:{}'.format(textfeedback.get(1.0, END)))
    messagebox.showinfo(title='Submit', message='Thank you for your Feedback')
    entry_name.delete(0, END)
    entry_email.delete(0, END)
    entry_usn.delete(0, END)
    textfeedback.delete(1.0, END)

def open_file():
    name_info = name.get()
    email_info = email.get()
    usn_info = usn.get()
    feed_info = textfeedback.get(1.0, END)

    data_file = open("data.txt", 'w')
    data_file.write(name_info)
    data_file.write(email_info)
    data_file.write(usn_info)
    data_file.write(feed_info)
    data_file.close()

submitbutton = ttk.Button(root, width=25, text='Submit', command=lambda: [submit(), open_file()])
mainloop()

A: EDIT
Your mistake can be at
submitbutton = ttk.Button(root, width=25, text='Submit', command=lambda: [submit(), open_file()])

Call open_file() function first, then call submit() function, like:
submitbutton = ttk.Button(root, width=25, text='Submit', command=lambda: [open_file(), submit()])


text:
Q: Where to put methods (non get and set) in java project to be Spring MVC compliant working on a java Spring project, my group is conflicting between Delphi and Java approach I believe regarding methods location. (Read: http://www.gbengasesan.com/fyp/5/ch5.htm#Classes -> where I see Delphi seems to regroup methods in one class).
For instance, we have some classes including User, Invoice, Debt, etc.
So as a User has a List of Invoices, how is this correct to put all methods (except getter and setter) regarding a single Invoice in the User class ?!
I can't figure out. In my opinion, methods such as "create invoice" (that would execute the constructor at least, because some 'set methods' would complete the object afterwards), "modify invoice" or "delete invoice" should belong to Invoice class.
Just the same idea for methods around User creation, modification, deletion or password recovery (could be simple get method that one) would then belong to User class and so on for the rest of the app.
Also should we only have getters and setters (besides constructors) as long as we didn't get into the full Spring model. I hope i was clear enough.

A: In spring mvc we use service/business layer for those. User, invoice and debt has its own POJOs which will only have simple definition of data.
If you want to find all invocies belongs to one user. Or debts belong to one user those goes to debts service layer or POJOs which has getDebts. or Service layer which has function like getDebst(long user Id) which will bring user related data.
you can see more details in https://medium.com/stackavenue/why-to-use-service-layer-in-spring-mvc-5f4fc52643c0 or https://www.baeldung.com/testing-the-java-service-layer