text:
Q: Recursive Function In JavaScript for array of objects with different keys Need a recursive function  in javascript/jquery for below json object.
The key "impacted" is the leaf node at each level.
The  key "child" may have any number of levels which may have "impacted" nodes in it.
i want to merge the leaf nodes("impacted") at every level to child("child") node at the same level.
 It means child node at any level should have impacted data also at same level.
Input
{

    "Data": [{
        "id": 1745,
        "name": "Top Parent",
        "parentId": null,
        "child": [{
            "id": 1746,
            "name": "Sub Parent- child to Top Parent",
            "parentId": 1745,
            "child": [{
                    "id": 1747,
                    "name": "child to Sub Parent--One ",
                    "parentId": 1746
                },
                {
                    "id": 1748,
                    "name": "child to Sub Parent--two",
                    "parentId": 1746,
                    "child": [{
                        "id": 1749,
                        "name": "Child to two",
                        "parentId": 1748
                    }],
                    "impacted": [{
                        "id": 2471,
                        "name": "Leaf of two ",
                        "network": true
                    }]
                }
            ],
            "impacted": [{
                    "id": 2470,
                    "name": "Leaf of Sub Parent-1 ",
                    "network": true
                },
                {
                    "id": 2469,
                    "name": "Leaf of Sub Parent-1",
                    "network": true
                }
            ]
        }],
        "impacted": [{
            "id": 2468,
            "name": "Leaf Of Top Parent",
            "network": true
        }]
    }]
}

Expected Output
{
    "Data": [{
        "id": 1745,
        "name": "Top Parent",
        "parentId": null,
        "child": [{
                "id": 1746,
                "name": "Sub Parent- child to Top Parent",
                "parentId": 1745,
                "child": [{
                        "id": 1747,
                        "name": "child to Sub Parent--One ",
                        "parentId": 1746
                    },
                    {
                        "id": 1748,
                        "name": "child to Sub Parent--two",
                        "parentId": 1746,
                        "child": [{
                                "id": 1749,
                                "name": "Child to two",
                                "parentId": 1748
                            },
                            {
                                "id": 2471,
                                "name": "Leaf of two ",
                                "network": true
                            }
                        ]
                    },
                    {
                        "id": 2470,
                        "name": "Leaf of Sub Parent-1 ",
                        "network": true
                    },
                    {
                        "id": 2469,
                        "name": "Leaf of Sub Parent-1",
                        "network": true
                    }
                ]
            },
            {
                "id": 2468,
                "name": "Leaf Of Top Parent",
                "network": true
            }
        ]
    }]
}

It is OK even if we do not remove "impacted" key from object. But the data from "impacted" should be merged to "child" of same level.
I tried with following function..but getting duplicates at each level

repeatLoop(data){
    if(data && data.length){
        for(var i=0;i<data.length;i++){
       if(data[i].child && data[i].child.length && data[i].impacted && data[i].impacted.length){
                for(var k=0; k<data[i].impacted.length;k++){
                     data[i].child.push(data[i].impacted[k])
                     this.repeatLoop(data[i].child)
                }
         }
       }
     }
       return data
  }

Thanks in advance

A: The main issue with your code is that you call the function recursively inside a loop on k, while the recursive call does not depend on k at all, so it should not be called in that inner loop, but after it.
You could use this function:

class X {
    repeatLoop(data) {
        if (!Array.isArray(data)) return;
        for (var item of data) {
            this.repeatLoop(item.child);
            if (item.impacted) {
                item.child = (item.child || []).concat(item.impacted);
                delete item.impacted;
            }
        }
    }
}

// Sample input
var data = {
    "Data": [{
        "id": 1745,
        "name": "Top Parent",
        "parentId": null,
        "child": [{
            "id": 1746,
            "name": "Sub Parent- child to Top Parent",
            "parentId": 1745,
            "child": [{
                    "id": 1747,
                    "name": "child to Sub Parent--One ",
                    "parentId": 1746
                },
                {
                    "id": 1748,
                    "name": "child to Sub Parent--two",
                    "parentId": 1746,
                    "child": [{
                        "id": 1749,
                        "name": "Child to two",
                        "parentId": 1748
                    }],
                    "impacted": [{
                        "id": 2471,
                        "name": "Leaf of two ",
                        "network": true
                    }]
                }
            ],
            "impacted": [{
                    "id": 2470,
                    "name": "Leaf of Sub Parent-1 ",
                    "network": true
                },
                {
                    "id": 2469,
                    "name": "Leaf of Sub Parent-1",
                    "network": true
                }
            ]
        }],
        "impacted": [{
            "id": 2468,
            "name": "Leaf Of Top Parent",
            "network": true
        }]
    }]
};
// Call function
new X().repeatLoop(data.Data);
// Display mutated data:
console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }


text:
Q: changing background on JLabel shifts components The code I am using is:
public class Test extends JFrame implements ActionListener {

    private static final Color TRANSP_WHITE =
        new Color(new Float(1), new Float(1), new Float(1), new Float(0.5));
    private static final Color TRANSP_RED =
        new Color(new Float(1), new Float(0), new Float(0), new Float(0.1));
    private static final Color[] COLORS =
        new Color[]{TRANSP_RED, TRANSP_WHITE};
    private int index = 0;
    private JLabel label;
    private JButton button;

    public Test() {
        super();

        setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));
        label = new JLabel("hello world");
        label.setOpaque(true);
        label.setBackground(TRANSP_WHITE);

        getContentPane().add(label);

        button = new JButton("Click Me");
        button.addActionListener(this);

        getContentPane().add(button);

        pack();
        setVisible(true);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource().equals(button)) {
            label.setBackground(COLORS[index % (COLORS.length)]);
            index++;
        }
    }

    public static void main(String[] args) {
        new Test();
    }
}

When I click the button to change the labales color the GUI looks like this:
Before:

After:

Any ideas why?

A: You are giving the JLabel a background that is semi-transparent but you have specified that it is opaque. This means that Swing will not paint the components under it before it provides the JLabel with the Graphics object to use for drawing. The provided Graphics contains junk that it expects the JLabel to overwrite when it draws its background. However when it draws its background it is semi-transparent so the junk remains.
To fix the problem you need to create an extension of JLabel that is not opaque but has an overridden paintComponent method that will draw the background you want.
EDIT: Here's an example:
public class TranslucentLabel extends JLabel {
    public TranslucentLabel(String text) {
        super(text);
        setOpaque(false);
    }

    @Override
    protected void paintComponent(Graphics graphics) {
        graphics.setColor(getBackground());
        graphics.fillRect(0, 0, getWidth(), getHeight());
        super.paintComponent(graphics);
    }
}

A: Backgrounds With Transparency provides the solution you accepted, but also provides you with a solution you can use without extending JLabel, which might be of interest.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Airflow: Subdag Fails Without Scheduling Tasks or Generating Log I'm running into a situation with the airflow instance (version 1.8) I manage where I am seeing tasks which are Subdags fail, but the log for the failed task is either *** Task instance did not exist in the DB or no log at all. The tasks run daily, and only fail intermittently. The Subdag works most of the time, but fails occasionally and without explanation.
When I read through the logs from around the time of the failure, I'm seeing two things:

*

*No log explanation of why the Subdag failed
a. The database shows that the task has a End Date, but not a Start Date

*None of the tasks in the Subdag got scheduled

I've dug through the documentation, pulled the logs from the whole server, and upgraded the size (CPU, memory, and disk) of the server hosting the airflow logs. I'm guessing it has to do with a timeout, but can't seem to find where the issue is originating.

More details (one instance):

*

*Queued Dttm: 3:38:04

*Start Date: NULL

*End Date: 03:38:25

*Duration: NULL

*Try Number: 1 (no retries used)

Possible theory - fails when there are task scheduling deadlocks. Currently, the instances where it fails are ones where there are lots of equally prioritized parallel tasks. It's not giving that error message, but lacking other options I'm trying to identify patterns.

This appears to be related to issue #1473. If they're not the same, the symptoms are the same.


text:
Q: Exercise 7, Section 5.2 of Hoffman's Linear Algebra
Let $K$ be a commutative ring with identity. Show that the determinant function on $2 \times 2$ matrices $A$ over $K$ is alternating and $2$-linear as a function of the columns of $A$.

"As a function of columns of $A$" I assume it means we replace rows with columns in definition of alternative and $2$-linear.
My attempt: Let $A$ $=\begin{bmatrix} A_{11} & A_{12} \\ A_{21} & A_{22} \\ \end{bmatrix}$ $=[\alpha \text{ }\beta]\in M_2(K)$; $\alpha$, $\beta$ are columns of $A$. Fix first column. Let $c\in K$ and $\gamma$ be a column. Then $D([\alpha \text{ }\text{ }c\cdot \beta +\gamma])$ $=D(\begin{bmatrix} A_{11} & c A_{12}+A_{12}^\prime\\ A_{21} & c A_{22}+A_{22}^\prime \end{bmatrix})$ $=A_{11}\cdot (c A_{22}+A_{22}^\prime)$ $-$ $A_{21}\cdot (c A_{12}+A_{12}^\prime A_{21})$ $=c\cdot A_{11}A_{22}-c\cdot A_{21}A_{12}$ $+$ $A_{11}A_{22}^\prime -A_{21}A_{12}^\prime$ $=c\cdot (A_{11}A_{22}-A_{21}A_{12})$ $+$ $(A_{11}A_{22}^\prime -A_{21}A_{12}^\prime)$ $=c\cdot D([\alpha\text{ }\beta])+D([\alpha \text{ }\gamma])$. Similarly $D([c\cdot \alpha +\gamma \text{ }\text{ }\beta])$ $=c\cdot D([\alpha \text{ }\beta])+D([\gamma \text{ }\beta])$. Hence $D:M_2(K)\to K$ is $2$-linear as a function of column of $A$.
Let $B$ $=\begin{bmatrix} B_{11} & B_{11} \\ B_{21} & B_{21} \\ \end{bmatrix}$ $=[\beta \text{ }\beta]\in M_2(K)$; $\beta$ is column of $B$. Then $D(B)$ $=B_{11}B_{21}-B_{11}B_{21}$ $=0$. Let $A^\prime$ $= \begin{bmatrix} A_{12} & A_{11} \\ A_{22} & A_{21} \\ \end{bmatrix}$ $=[\beta \text{ }\alpha]$. Then $D(A^\prime)$ $=A_{12}A_{21}-A_{11}A_{22}$ $=-D(A)$. Hence $D$ is alternative. Is my proof correct?


text:
Q: Export data to a file using apex I have a requirement to

*

*Run SELECT query on custom object

*export the data to csv file

*Automate / schedule step-1 and step-2 .

I know how to achieve step-3, by using apex scheduler class. But I couldn't find anything on exporting data from apex code. We have been using Jitterbit, but now our client wants to get rid of it, and use only salesforce.

A: If you're concerned about time or memory limits, use a batch class. This is how I would perform the export of a potentially unknown size (10k+ records).
global class X implements Database.Batchable<SObject>, Database.Stateful {
    string[] Lines;

    global Database.QueryLocator start(Database.BatchableContext bc) {
        lines = new String[0];
        return Database.getQueryLocator( your-query-here );
    }
    global void execute(Database.BatchableContext bc, SObject[] scope) {
        for(Sobject record: scope) {
            String line = '';
            // build your csv line here
            lines.add(line);
        }
    }
    global void finish(Database.batchablecontext bc) {
        String finalResults = String.join(lines, '\n');
        lines = null; // Free temp memory to avoid heap errors
        // proceed to send attachment by email
    }
}

The best performance I've gotten for a synchronous export (that is, a direct query, plus processing about 30 fields per record) is about 5,000 records before a CPU timeout exception, so if this is a concern, definitely go with a batch. If you're confident that you can beat the timeout, you could perform the query and translation directly in the scheduler class itself without resorting to a batch.


text:
Q: How to use useLayoutEffect hook Code here:
const insets = useSafeAreaInsets()
const { params} = useRoute()
const [isLoading, setIsLoading] = useState(true)
const [isError, setIsError] = useState(false)
const [info, setInfo] = useState(INITIAL_INFO)
const [isMarked As Favorite, setIsMarked As Favorite] = useState(false)
const { favorites } = useSelector((state) => state. favorites)
useLayoutEffect (() => {
  navigation.setOptions({
    headerTitle: params.title,
    headerRight: () => (
      <Icon
        name={isMarked As Favorite ? 'heart': 'heart-outline'}
        size={20}
        color={isMarked As Favorite ? colors.primary : colors.black}
        style={headerIconStyle}
        onPress={() => {
          if (isMarked As Favorite) {
            dispatch (removeFromFavorite({ ...params?.item }))
            setIsMarkedAs Favorite(false)
            return
          }
          dispatch (addToFavorite({ ...params?.item }))
        }}
      />
    )
  })
}, [navigation, params, info, dispatch, isMarked As Favorite])

I have headerRight in useLayoutEffect hook.  I want to re-render it on the basis of state change.
How can i do that ?
I have passed state as dependency array in useLayoutEffect hook but it's not working.
But My icon in headerRight is not re-rendering.


text:
Q: How to use a flag to restart an action in a Thread? I tried using a volatile boolean to act as a flag to stop/start/restart the action in the thread, however it does not work. It just keeps on going forever and never terminates. Any help on how to properly do this or why my code does not work will be greatly appreciated. Thanks in advance.
public class thread {

    public static int i = 0;
    private static Thread print = null;
    private static printThread runnable = null;

    public static void main(String[] args) {
        runnable = new printThread();
        print = new Thread (runnable);
        print.start();

        System.out.println("Starting");
        runnable.begin();
        if(i > 5)
        {
            runnable.terminate();
        }

        i = 10;
        runnable.begin();
        if(i > 15)
        {
            runnable.terminate();
        }
    }

    public static final void print()
    {
        System.out.println(i);
        i++;
    }

    public static final class printThread implements Runnable {
        private volatile boolean running = false;

        public void terminate() {
            running = false;
        }

        public void begin() {
            running = true;
        }

        public boolean isRunning() {
            return running;
        }

        public void run() {
            while(true)
            {
                if(running)
                {
                    print();
                }

                else
                {

                }
            }
        }
    }
}

A: In your code while loop execution never ends. You could introduce 2 states: terminated and waiting to simulate threads start/pause/restart/stop. However, even if you pause the Thread it will be running, just different branch of code will be executed inside while loop.
Please, see the code snippet below
public static final class printThread implements Runnable {
    private volatile boolean waiting = false;
    private volatile boolean terminated = false;

    public void terminate() {
        terminated = true;
    }

    public void pause() {
        waiting = true;
    }

    public void restart() {
        waiting = false;
    }

    public void run() {
        while(!terminated) {
            if(waiting) {
                //the thread is paused
            } else {
                //the thread is running
            }
        }
    }
}

A:
however it does not work. It just keeps on going forever and never terminates.

In your run() method of your thread, you aren't watching for the value of your  volatile boolean running field.  It probably should be something like:
    public void run() {
        while(!running) {
            print();
            // you might want a short Thread.sleep(10); here to stop the spinning
        }
    }

However, as @Anton points out, once your thread terminates, it can't be restarted without some other flag.  See his answer.
Also, you are sharing i between the main thread and the your printing thread.  That also needs to be volatile so it can be properly shared.  Since you are incrementing it in multiple threads, you should use an AtomicInteger for that.
 public static AtomicInteger i = new AtomicInteger();
 ...
 if (i.get() > 5) ...
 ...
 i.set(10);
 ...
 i.incrementAndGet();

Couple of other comments:

*

*Be careful of static fields.  print and runnable should be defined only inside of the main(...) method to restrict access.

*Classes should begin with an uppercase letter so it should be PrintThread.

*Actually, because PrintThread isn't a thread, it should be PrintRunnable or maybe even better, Printer.


text:
Q: Scale of knowledge and fact base for an expert system I am new to development of expert systems.I have started programming with clips a few simple codes like animal identification,mini version of mycin etc.I want to increase the knowledge and fact base(to a million facts) for my programs so i was wondering if there was any Database management system to make this process easier.I would like to know how to implement this in general.

A: Out of the box, the only mechanism for editing and loading rules/facts is through text files. CLIPS can be integrated with other languages so it's possible to add alternate means for storing and editing your rules/facts, you'd just have to write the code to integrate the pieces.


text:
Q: How can I dynamically load Perl modules and use their functions? I'm trying to switch some use statements in my code to require for modules I only use if certain conditions are met (e.g. the program might be loaded 1,000 times between times those modules are needed), in order to lower the overhead and improve the execution speed of my program (I've been using Devel::NYTProf to profile my code and some modules were adding significant execution time even when I didn't use them in a certain session).
I've run into an issue where the script dies on load because symbols aren't defined (that won't be defined until that module is imported). Is there a way to tell Perl that the symbols will be imported at runtime? A simple example: I only want to use Data::Dumper if I call a routine that triggers it:
sub dataDumper {
    require Data::Dumper;
    Data::Dumper->import;
    say STDERR Dumper @_;
}

However, calling Dumper on that third line causes an exception. I can work around that by referring to Data::Dumper->Dump instead. However, a similar issue with LWP::UserAgent proves a bit sticker because LWP::UserAgent imports HTTP::Request. I haven't come up with a variation of my $request = new HTTP::Request GET => $params->{'url'}; that avoids throwing an exception.
Assuming I can that to work, is there any reason why this approach is a bad idea? Am I losing any sort of optimizations by not loading these modules at compile time? On a module like LWP, it seems like an easy call -- I just don't use it much. I'm a bit more confused on whether to try to dynamically switch between (for example) Text::Textile and Text::MultiMarkdown (I usually only need one per execution.

A: In sub calls, parens around arguments can only be omitted for declared subs.
say STDERR Dumper(@_);

Note that prototypes on subs you load this way will be ignored.

There is no problem with the second line as it doesn't involve a sub call. Method calls aren't affected.
$ perl -M5.010 -e'
   if ($ARGV[0]) {
      require LWP::UserAgent;   # or HTTP::Request
      my $request = new HTTP::Request GET => "https://stackoverflow.com";
   }

   say "ok";
' 0
ok

$ perl -M5.010 -e'
   if ($ARGV[0]) {
      require LWP::UserAgent;   # or HTTP::Request
      my $request = new HTTP::Request GET => "https://stackoverflow.com";
   }

   say "ok";
' 1
ok

As such, class modules are particularly useful here. Consider a plugin model in complicated cases.

Am I losing any sort of optimizations by not loading these modules at compile time?

Constants need to be replaced slower function calls which can't be folded.
$ perl -MO=Concise,-exec -M5.010 -e'
   use constant FOO => 2;
   say 2 + FOO;
'
...
2  <;> nextstate(main 188 -e:3) v:{,fea=1
3  <0> pushmark s
4  <$> const[IV 4] s/FOLD
5  <@> say vK
...

$ perl -MO=Concise,-exec -M5.010 -e'
   say 2 + FOO();
   require constant; import constant FOO => 2;
'
...
2  <;> nextstate(main 2 -e:2) v:{,fea=1
3  <0> pushmark s
4  <$> const[IV 2] s
5  <0> pushmark s
6  <#> gv[*FOO] s/EARLYCV
7  <1> entersub[t2] sKS/TARG
8  <2> add[t3] sK/2
9  <@> say vK
...

A: Use fully qualified names and don't import anything.
sub dataDumper {
    require Data::Dumper;
    say STDERR Data::Dumper::Dumper(@_);
}

However, a similar issue with LWP::UserAgent proves a bit sticker because LWP::UserAgent imports HTTP::Request.

The terminology in this statement is wrong. LWP::UserAgent doesn't import anything. In fact, it has no import method at all. It loads HTTP::Request, by useing it. So perl will switch to compile time at the point LWP::UA is required, compile it, and load HTTP::Request, HTTP::Response and HTTP::Date (and a few others), all explicitly without importing anything into LWP::UserAgent's namespace either.

$request = new HTTP::Request GET => $params->{'url'};

I can't reproduce this blowing up if HTTP::Request hasn't been loaded. If it doesn't get executed, it won't error.
if (0) {
    HTTP::Request->new(GET => '/foo');
    new HTTP::Request GET => '/foo';
}

This is fine. You should of course use the first form, and not the indirect object notation, because it's ambiguous, but it makes no difference.
If you were to use HTTP::Request::Common, which imports GET and POST et al to quickly generate HTTP::Requests, you can also just require it at runtime, and then use the fully qualified name.
if ($make_web_request) {
  require LWP::UserAgent;
  require HTTP::Request::Common;

  my $ua = LWP::UserAgent->new;
  $ua->request(HTTP::Request::Common::GET('https://example.org'));
}

Am I losing any sort of optimizations by not loading these modules at compile time?

No. If your code is started a lot of times, and goes lots of different paths, then loading things only if you need them is totally fine to do. It makes very little real difference. Perl switches between compile time and run time for every single require anyway. Generally that's not a penalty at all.

A: I do something similar, but like this. Somehow the state makes this a lot faster even though require won't load it a second time:
sub something {
    state $rc = require Foo;
    ...
    }

If I want to import things
sub something {
    state $rc = do { require Foo; Foo->import };
    ...
    }

Remember what use actually is:
BEGIN {
    require Foo;
    Foo->import(...);
    }

The BEGIN merely does that at compile time. If you do all the same steps later, you end up in the same place (just later).


text:
Q: Observer/Dealloc errors and crash with unseen UIViewController I have a UIViewController which has objects perform a series of tasks on background threads as it appears, and it's registered as an observer to them. When they get called for the first time, it stops being an observer.
I realised I could save user time if these tasks were performed before the view controller is shown, so I initialized it and called a method which ran these tasks.
Then I started getting errors along the lines of:
An instance [insance] of class [class name] was deallocated while key value observers were still registered with it.

How can I prevent this from happening? If i show the view controller straight away, this works no problem.

A: I'd recommend, that you add a call [notificationCenter removeObserver: self] in method dealloc of those classes, which you intend to use as observers, as it is the last chance to unregister an observer cleanly.


text:
Q: Error running 'app': No target device found
٠٧:٤٨ ص   Plugin Error: Plugin "Android WiFi ADB" is incompatible (supported only in IntelliJ IDEA).
٠٧:٤٨ ص   * daemon not running; starting now at tcp:5037
٠٧:٤٨ ص   * daemon started successfully
٠٧:٥٠ ص   Error running 'app': No target device found.
٠٧:٥٠ ص   Error running 'app': No target device found.
٠٧:٥٧ ص   Executing tasks: [:app:assembleDebug] in project C:> \Users\Mmsk4\AndroidStudioProjects\MyApplication
٠٧:٥٧ ص   Gradle build failed in 28 s 633 ms

A: There is no need for plugin. You can achieve the same without plugin. The setup is one time.
Android | WiFi adb keeps disconnecting in android studio
Go, through this post. It has full guide to run app through wifi adb.


text:
Q: How to intercept the TAB key press to focus on a check box which becomes enabled after TAB key was pressed? When we press the TAB key we change the focus to the next control in the given tab order. In my case when I click on a check box (say X) then after pressing Tab button the control is going on a text field instead of going on next check box (say Y) which was previously disabled and became enabled after the tab button was pressed. I want the control to move to the Check box Y. Thanks.
I have following code but it is not running when I'm pressing Tab Button:
        if (((e.KeyCode == Keys.Tab && !e.Shift) || e.KeyCode == Keys.Enter)  && _resultsGrid.ActiveCell != null)
        {
            if (_resultsGrid.ActiveCell.IsInEditMode && (_resultsGrid.ActiveCell == lastEditableCell || e.KeyCode == Keys.Enter))
            {
                DateTime tempDateTime = DateTime.Today;
                if (!(_resultsGrid.ActiveCell.Column.DataType.ToString() == "System.DateTime" && !System.DateTime.TryParse(_resultsGrid.ActiveCell.Text, out tempDateTime)))
                {
                    if (_resultsGrid.ActiveCell.Text == "" && (_resultsGrid.ActiveCell.Column.DataType == typeof(System.Int16) ||
                        _resultsGrid.ActiveCell.Column.DataType == typeof(System.Int32) ||
                        _resultsGrid.ActiveCell.Column.DataType == typeof(System.Int64) ||
                        _resultsGrid.ActiveCell.Column.DataType == typeof(System.Decimal)))
                        _resultsGrid.ActiveCell.Value = 0;
                    else
                        _resultsGrid.ActiveCell.Value = _resultsGrid.ActiveCell.Text;
                }
                _returnKeyClickedToSaveRow = true;
                FireSaveEvent();
                if (!_saveFailed)
                {
                    if (e.KeyCode == Keys.Tab)
                    {
                        _checklastkey = true;
                        _resultsGrid.PerformAction(UltraGridAction.CommitRow);
                    }
                    else
                    {
                        _resultsGrid.PerformAction(UltraGridAction.CommitRow);
                        _resultsGrid.PerformAction(UltraGridAction.DeactivateCell);
                    }
                }
                _returnKeyClickedToSaveRow = false;
                this._entityDS.AcceptChanges(); //EAMNET-9811
            }
        }

A: There is a property each control has which is called TabIndex. You can assign the next control which gets focused on TAB key using this property. For example If Control1 has TabIndex 1 and Control2 has TabIndex 2, after pressing TAB key on Control1, Control2 would be focused.
P.S. As TabIndex is a property in each Control, You can also dynamically decide on next control to get focused wherever you want by changing TabIndex's.


text:
Q: Using Swift classes in playground I'm playing with Swift; I downloaded https://github.com/FahimF/SQLiteDB and, when called from .swift file it runs fine ..I connect and get query results as:
        let db = SQLiteDB.sharedInstance()
        if let data = db.query("SELECT * FROM squadre") {
            for row in data {
                println(row["nome"]?.asString())
            }
        }

I would like to do the same thing in a playground but cannot use SQLiteDB inside the playground ... I get a:

"Use of unresolved identifier SQLiteDB"

Which is the way to use custom classes from playground?

A: you must integrate SQLiteDB in the Playground Projekt.


text:
Q: Reload one controller from another controller Angular js I am new to Angular js.I have seen the similar question, but I dont understand that.
I have 2 controllers
userControllers.controller('RatingCtrl', function($scope,$http,$rootScope,$route)
userControllers.controller('otherProfileCtrl', function ($scope, $routeParams, $rootScope, $http, $location, $window, $timeout,$uibModal, $compile)

RatingCtrl and otherProfileCtrl, this two modules are inter-related. My need is that, I have reload RatingCtrl from otherProfileCtrl using $route.reload();.Is there is any way to do this without uisng service?plz help

A: You could pass events from one controller to another in order to achieve this. You would then do something like:

var app = angular.module('myApp', []);

app.controller('firstController', ['$scope', '$rootScope',
  function($scope, $rootScope) {

    $scope.text = 'Initial text';
    $scope.changeText = function(message) {
      $scope.text = message;
    };

    $rootScope.$on('customEvent', function(event, message) {
      $scope.changeText(message);
    });

  }
]);

app.controller('secondController', ['$scope',
  function($scope) {

    $scope.message = 'Message from second controller';

    $scope.sendEvent = function() {
      $scope.$emit('customEvent', $scope.message)
    };

  }
]);

This is the fist controller:

{{text}}

This is the second controller:

    <input type="text" ng-model="message" />

    <button ng-click="sendEvent()">Send message</button>

Here, the firstController listens to events propagated to the $rootScope, and the secondController sends the message. That is the functionality that you are looking for.
That being said, you would be much better off implementing shared behaviour in a service, since keeping track of all your custom events can be particularly tough.
Hope this helps.


text:
Q: PHP/MYSQL:Carry out UPDATE within SELECT query There are many questions on SO about this but I cannot find one that quite meets my situation.
I want to use the values in some fields/columns of a table to set the value of a third field/column
In other words something like:
table races
athleteid|difficulty|score|adjustedscore

$sqlSelect = "SELECT athleteid,difficulty,score FROM races";
$res = mysql_query($sqlSelect) or die(mysql_error());
while ($row = mysql_fetch_array($res)){

$adjustedscore=difficulty*score;

$sqlupdate = "UPDATE race, set adjustedscore = '$adjustedscore' WHERE athletes = 'athletes'";
$resupdate = mysql_query($sqlupdate);

}

My understanding, however, is that MYSQL does not support update queries nested in select ones.
Note, I have simplified this slightly.  I am actually calculating the score based on a lot of other variables as well--and may join some tables to get other inputs--but this is the basic principal.
Thanks for any suggestions

A: You can run:
UPDATE `races`
SET `adjustedscore` = `difficulty` * `score`
WHERE `athleteid` IN (1, 2, 3, ...)

A: First of all, as previous commentators said, you should use PDO instead of mysql_* queries.
Read about PDO here.

When you'll get data from DB with your SELECT query, you'll get array. I recommend you to use fetchAll() from PDO documentation.
So, your goal is to save this data in some variable. Like you did with $row.
After that you'll need to loop over each array and get your data:
foreach($row as $r) {
    //We do this to access each of ours athlete data
    $adjustedscore= $row[$r]["difficulty"]* $row[$r]["score"];
    //Next row is not clear for me...
    $query = "UPDATE race SET adjustedscore = '$adjustedscore' WHERE athletes = 'athletes'";
    And to update we use PDO update prepared statement
$stmt = $dbh->prepare($query);
     $stmt->execute();
   }


text:
Q: Implementation of object-oriented analysis patterns in a relational database I have recently started reading Martin Fowler's "Analysis Patterns" in an attempt to improve my data modelling skills and I find the book really interesting and enlightening as far as object-oriented approaches are concerned. However, although I think I understand how most of the patterns would translate into a relational database schema, I fail to see how to implement them in a realistic way.
For example, implementing the "Measurement" pattern (chapter 3.4) in a (non object-)relational database would require:

*

*1 table to store Persons.

*1 table to store Measurements for a Person (N-1 relationship).

*1 table to store the Quantity of a Measurement (1-1 relationship).

*1 table to store the Phenomenon Types that may characterise a Measurement (1-N relationship).

In an RDBMS all this amounts to several sort operations to realise joins and to a large number of records that need to be joined, especially if we're storing lots of Persons and lots of Measurements for each Person. I suspect it would not perform well.
The question, I suppose, is whether I am correct in my "suspicion" and if someone could point me to the right direction in terms of books or other sources that discuss the implementation of such analysis patterns to relational databases.
Thank you very much in advance,
Nico

A: That's not complicated. From an Entity-Relationship modelling perspective, you're describing what sounds like 4 entities:

*

*Person

*Measurement

*Quantity

*Phenomenon Type

And a few relationships between them:

*

*Each Person has zero-to-many Measurements; each Measurement measures one-and-only-one Person.

*Each Measurement has one-and-only-one Quantity; Each Quantity is of one-and-only-one Measurement.

*Each Measurement describes one-and-only-one Phenomenon Type; each Phenomenon Type has zero-to-many Measurements.

So...4 tables and 3 relationships in the database.
The model so described is probably incorrect, though: Assuming that he 1:1 relationship between Measurement and Quantity is mandatory — each Measurement has a single Quantity; each Quantity describes a single Measurement — is a smell.
Relationships with 1:1 cardinality are often (usually?) an indication that the two entities involved are really partial views of the same underlying logical entity. The model should be refactored to a single entity carrying all the attributes. Doing that refactoring brings you down to 3 tables and 2 relationships. Note, however, that this is not necessarily true with optional unary relationships (0:1).
Either way, that's nothing, provided the physical database design implementing the logical entity model has proper covering indices.
The thing with a properly normalized model is that you typically have many narrowish tables: narrow tables mean more rows per data page and thus faster seeks. One can always denormalize if there is an actual performance problem due to the database design. If you start with a denormalized model, once you've got a live database with gigabytes of data in it, putting into proper form gets difficult and time consuming.

A: I do not know the book you mention. Hence, I do not understand the difference between "measurement" and "quantity". I am assuming that "Measurement" would be the related to the act of measuring, i. e. contain the date and time of the measurement, and "quantity" is the value measured, like 180 for the height of a person in centimeters.
For analysis using relational databases, a star schema is a common approach: You would have one central fact table containing the quantities, and foreign keys to the dimension tables like Date, Phenomenon, and Person.


text:
Q: What does this hyper reference link lead to? I am parsing a HTML file and I noticed that there is one element that reads:
<a id="someID" class="someClass" href="#" style="someStyle">

Can I please ask what this href="#" lead to?

A: It doesn't go anywhere. This is a common placeholder for links that are implemented using Javascript. Another popular style is href="javascript:void(0)"; void() is a function that does nothing. Finally, the Javascript function that's run when you click on it could use event.preventDefault() to prevent the normal action of following the link. But you should still put a placeholder in the href, so that when the user hovers over the link it won't show a target in the browser's status line.

A: I generally use '#' to a trigger a JavaScript which works with CSS or page layout. In whole, its just a way to make a dead-link(not leading to any page) which you can use to call various webpage activites like JS or CSS.


text:
Q: Atom xml read with C# I don't know about this much at all, I have built-in page that contains a gridview to describe daily input data separated into columns from different authors, it looks like an excel file. And there is an Atom link at the bottom.
If I click on one row's link especially the author of the post, I will be directed to the author's property page in which there will be name, current work done, and how much he has written his book (50/70 80% called status etc), I wonder how can I read in this information and display it in another view of a related application; that is I know the feed's URL only, I really have no clue how that can be done. Thank you for any help.

A: I haven't tried to use the DataContractSerializer with specialized XML formats, but the XmlSerializer lets you set what is an attribute and what is an element. It is the easiest method as far as I am concerned because you can make a nice object model and use it to read any XML.  Here is a PARTIAL example of reading an atom feed.  You will need to perform an HttpWebRequest to get the XML (which is pretty straight forward) then use the XmlSerializer to deserialize the feed.
[XmlType(TypeName = "feed", Namespace = "http://www.w3.org/2005/Atom")]
public class Feed
{
    [XmlElement(ElementName = "title")]
    public string Title { get; set; }

    [XmlElement(ElementName = "updated")]
    public DateTime? Updated { get; set; }

    [XmlElement(ElementName = "id")]
    public string Id { get; set; }

    [XmlElement(ElementName = "link")]
    public Link Link { get; set; }

    [XmlElement(ElementName = "entry")]
    public List<Entry> Entries { get; set; }

    public Feed()
    {
        Entries = new List<Entry>();
    }
}

public class Entry
{
    [XmlElement(ElementName = "title")]
    public string Title { get; set; }

    [XmlElement(ElementName = "updated")]
    public DateTime? Updated { get; set; }

    [XmlElement(ElementName = "id")]
    public string Id { get; set; }

    [XmlElement(ElementName = "link")]
    public Link Link { get; set; }

    [XmlElement(ElementName = "summary")]
    public string Summary { get; set; }
}

public class Link
{
    [XmlAttribute(AttributeName = "href")]
    public string Href { get; set; }
}

Here is a working sample to write/read the feed:
class Program
{
    static void Main(string[] args)
    {
        Feed feed = new Feed();
        feed.Title = "Exmple Feed";
        feed.Updated = DateTime.Now;
        feed.Link = new Link { Href = "http://example.org/" };

        feed.Entries.Add(
        new Entry
        {
            Title = "Atom-Powered Robots Run Amok",
            Link = new Link { Href = "http://example.org/2003/12/13/atom03" },
            Updated = DateTime.Now,
            Summary = "Some text."
        });

        XmlSerializer serializer = new XmlSerializer(typeof(Feed), "http://www.w3.org/2005/Atom");

        using (StreamWriter sw = new StreamWriter("c:\\testatom.xml"))
        {
            serializer.Serialize(sw, feed);
        }

        using (StreamReader sr = new StreamReader("c:\\testatom.xml"))
        {
            Feed readFeed = serializer.Deserialize(sr) as Feed;
        }
    }
}

A: The best starting point would be to use the SyndicationFeed, which maps to the Atom 1.0 and RSS 2.0 standard. Everything you need for a basic implementation should be available to you:
XmlReader reader = XmlReader.Create("http://localhost/feeds/serializedFeed.xml");
SyndicationFeed feed = SyndicationFeed.Load(reader);

// Feed title
Console.WriteLine(feed.Title.Text);

foreach(var item in feed.Items)
{
    // Each item
    Console.WriteLine("Title: {0}", item.Title.Text);
    Console.WriteLine("Summary: {0}", ((TextSyndicationContent)item.Summary).Text);
}

Perhaps if you have some custom requirements, or want to handle the RSS data differently than this standard, then Doug's answer would be the way to go.

Useful references:

*

*https://msdn.microsoft.com/en-us/library/system.servicemodel.syndication.syndicationfeed(v=vs.110).aspx

*https://msdn.microsoft.com/en-us/library/bb412174%28v=vs.110%29.aspx


text:
Q: How to Reference Defined Values I have a javascript file that is attempting to reference a previously defined value, but the container of the value is null:
if (typeof (myNamespace) == "undefined") { myNamespace = {}; }

myNamespace.myClass = {
    myConstants: {
        value: "someValue",
    },

    something : {
        values: [myNamespace.myClass.myConstants.value] // Errors here
    }
};

I thought JavaScript executed in a top down manner, so the myNamespace.myClass.myConstants.value should be already be defined when the something.values[] is getting populated.

A: At the point your expression myNamespace.myClass.myConstants.value is evaluated, the value of myNamespace.myClass is still undefined. Until the whole object initializer expression is evaluated, the assignment doesn't happen.
The upshot of this is that there's no way to make internal cross-references from inside an object initializer expression. You have to split it out into a separate assignment.
myNamespace.myClass = {
    myConstants: {
        value: "someValue",
    },

    something : {
        values: []
    }
};

myNamespace.myClass.something.values.push(myNamespace.myClass.myConstants.value);


text:
Q: Moving git repos to new URI: handling submodules Our dev team has been compelled for several times to move git repositories to a new hosting service (from GitHub cloud to on-premise BitBucket, then to BitBucket with different URIs, and soon to on-premise GitLab).
Now for the current SW versions, submodules can be handled by changing the submodule's URIs.
However, we also need to be able to build old software releases  for new customers with possibly new toolchains, and checking out those old versions would cause problems because the old URIs are still there.
To be able to build old software releases with new build configurations, we have a kind of "meta build repository" on top of the software.
But obviously, old software releases will still have their outdated submodule URIs.
We are for sure not the first ones to encounter such a scenario. However I couldn't find any good-practice approaches the tackle the problem.
I think that a solution might be to use the "meta build repo" to configure + "inject" (override) the committed repository URIs. A drawback would be that the "release checkouts" would be "dirty".

*

*Is this a viable approach?

*Are there better approaches that I didn't manage to find out?
I thought that cmake's ExternalProject() or dependency management (e.g. with Conan.io) might be helpful (instead of using git submodules), but also those functions/tools would probably suffer from previously checked-in URIs (except those are handled in the "meta build repo").
I'm aware that there are options to rewrite the git history and thus change all the submodule URIs retrospectively, but would rather avoid that because I'm not aware of all the consequences that e.g. changed commit hashes are introducing.

A: For my projects, I use relative references for submodules. This generally works if the all repos are always on the same domain. For example, instead of ssh://git@server/proj/repo, I would use ../repo for a submodule in the same project or ../proj/repo for a submodule on the same server but in a different project.
This will only work if the repos are being moved server-to-server or project-to-project, but will not work if the individual repos are being renamed or moved between projects in some cases.  Although, since it looks like you are just relocating from server-to-server, it may work.

A: As Jonathon mentions it would make sense to see if you can use relative references for your submodules. Doing this going forward will help you in the future if you ever need to change your hosting provider again, or the URL for your repo changes.
You should consider if it's possible to rewrite your entire history to reflect these changes. You can take a look at git filter-repo (https://github.com/newren/git-filter-repo/) and possible git rebase -pi.
Rewriting your entire history is risky, and there are many pitfalls, but the general idea would be to, change the submodule path every time a submodule have been added, assuming that you carry over the history for all the submodules.
It would be worth investigating if it's possible to already there start using relative references.


text:
Q: Best way currently to create an ansible inventory from terraform I have a long list of machines, all of which are a little different in functionality in a system.  I'd like to organize these machines and add to a hosts inventory file automatically so I can run ansible and manage inventory.  Are there good solutions out there for this?
I think ansible hosts should looks something like...
[webservers]
someip
someip
[integration]
someip
someip

etc..
After asking the question, I currently am researching output vars and using those to render a template from a file.

A: For multi severs:
File inventory.tf
data  "template_file" "k8s" {
    template = "${file("./templates/k8s.tpl")}"
    vars {
        k8s_master_name = "${join("\n", azurerm_virtual_machine.k8s-master.*.name)}"
    }
}

resource "local_file" "k8s_file" {
  content  = "${data.template_file.k8s.rendered}"
  filename = "./inventory/k8s-host"
}

File k8s.tpl
[kube-master]
${k8s_master_name}

final result
[kube-master]
k8s-master-01
k8s-master-02
k8s-master-03

A: I figured it out.
data "template_file" "dev_hosts" {
  template = "${file("${path.module}/templates/dev_hosts.cfg")}"
  depends_on = [
    "aws_instance.dev-api-gateway",
    "aws_instance.dev-api-gateway-internal",
    ....
  ]
  vars {
    api_public = "${aws_instance.dev-api-gateway.private_ip}"
    api_internal = "${aws_instance.dev-api-gateway-internal.private_ip}"
  }
}

resource "null_resource" "dev-hosts" {
  triggers {
    template_rendered = "${data.template_file.dev_hosts.rendered}"
  }
  provisioner "local-exec" {
    command = "echo '${data.template_file.dev_hosts.rendered}' > dev_hosts"
  }
}

Then create a template in the file referenced earlier
Contents of example dev_hosts.cfg
[public]
${api_public}

[private]
${api_internal}

A: Since Terraform 0.12+ there is templatefile function that comes handy, especially if you need to populate host groups:
# generate inventory file for Ansible
resource "local_file" "hosts_cfg" {
  content = templatefile("${path.module}/templates/hosts.tpl",
    {
      kafka_processors = aws_instance.kafka_processor.*.public_ip
      test_clients = aws_instance.test_client.*.public_ip
    }
  )
  filename = "../ansible/inventory/hosts.cfg"
}

Where hosts.tpl template file (future Ansible inventory) may look like this:
[kafka_broker_hosts]
%{ for ip in kafka_processors ~}
${ip}
%{ endfor ~}

[test_client_hosts]
%{ for ip in test_clients ~}
${ip}
%{ endfor ~}

End result:
[kafka_broker_hosts]
18.224.140.239
18.224.140.234

[test_client_hosts]
3.21.134.83

A: This worked for me on aws ec2:
main.tf:
resource "aws_instance" "instance" {
  for_each      = toset(["ingress-01", "node-01", "node-02", "master-01" ])
  ami           = "ami-0c239ecd40dcc174c"
  instance_type = "t2.micro"

  tags = {
    Name = "${each.key}"
  }
}

resource "local_file" "inventory" {
  content = templatefile("inventory.tmpl", { content = tomap({
    for instance in aws_instance.instance:
      instance.tags.Name => instance.public_dns
    })
  })
  filename = format("%s/%s", abspath(path.root), "inventory.yaml")
}

template (inventory.tmpl):
all:
  children:
    ingress:
      hosts:
%{ for content_key, content_value in content }
%{~ if length(regexall("ingress", content_key)) > 0 ~}
        ${content_key}:
          ansible_host: ${content_value}
%{ endif ~}
%{~ endfor ~}
    master:
      hosts:
%{ for content_key, content_value in content }
%{~ if length(regexall("master", content_key)) > 0 ~}
        ${content_key}:
          ansible_host: ${content_value}
%{ endif ~}
%{~ endfor ~}
    nodes:
      hosts:
%{ for content_key, content_value in content }
%{~ if length(regexall("node", content_key)) > 0 ~}
        ${content_key}:
          ansible_host: ${content_value}
%{ endif ~}
%{~ endfor ~}

cat inventory.yaml
all:
  children:
    ingress:
      hosts:
        ingress-01:
          ansible_host: ec2-xx-xx-xx-xx.eu-central-1.compute.amazonaws.com
    master:
      hosts:
        master-01:
          ansible_host: ec2-xx-xx-xx-xx.eu-central-1.compute.amazonaws.com
    nodes:
      hosts:
        node-01:
           ansible_host: ec2-xx-xx-xx-xx.eu-central-1.compute.amazonaws.com
        node-02:
           ansible_host: ec2-xx-xx-xx-xx.eu-central-1.compute.amazonaws.com

A: Our approach is slightly different. We define a Terraform Module (terraform-null-ansible) which calls ansible anytime we want to run a playbook on a host by using a dynamic inventory.
https://github.com/cloudposse/terraform-null-ansible
This is a very terraform-centric approach but leads to very clean integration. Plus, by calculating the checksum of the playbook, we only call the ansible provisioner when the playbook has changed.
Usage is quite easy:
module "web_provisioner" {
   source    = "git::https://github.com/cloudposse/terraform-null-ansible.git?ref=tags/0.3.8"

   arguments = ["--user=ubuntu"]
   envs      = ["host=${aws_instance.web.public_ip}"]
   playbook  = "../ansible/playbooks/test.yml"
   dry_run   = false
}

More docs are on the GitHub README.md

A: My approach: from template to inventory file, use template_file to render the content and use local_file to output a file.
template file:
## file inventory.tpl

[frontend]
${bastion_pub_ip}

[all:vars]
ansible_ssh_private_key_file = ${key_path}
ansible_ssh_user = ubuntu

render and output:
## file inventory.tf

data "template_file" "inventory" {
    template = "${file("./test/inventory.tpl")}"

    vars {
       bastion_pub_ip = "${element(azurerm_public_ip.bastion.*.ip_address, count.index)}"
       key_path = "~/.ssh/id_rsa"
    }
}

resource "local_file" "save_inventory" {
  content  = "${data.template_file.inventory.rendered}"
  filename = "./myhost"
}

It works for single server, if you have a list, I don't find a proper way to do it.

A: This worked for me:
data "template_file" "ansible_inventory" {
  template = "${file("${path.module}/hosts.tmpl")}"

  vars = {
    public_ips = "${join("\n", aws_instance.public_instance.*.public_ip)}"
  }
}

resource "local_file" "hosts" {
  filename = "${path.module}/hosts"

  content = data.template_file.ansible_inventory.rendered
}


text:
Q: Ubuntu LiveUSB boots to black screen after grub I have a LiveUSB with Ubuntu 18.04 which I want to use to install Ubuntu onto my laptop, a Lenovo Yoga 720-13IKB Signature Edition currently running Windows 10. Whenever I try to boot my laptop to the liveusb, I can see the screen that has "Try Ubuntu without installing", "Install Ubuntu", and others, but the screen just goes black and stays black permanently.
I know this can't be because of a faulty LiveUSB because I can use it on other computers and it works perfectly well.
I've tried all of the suggestions for how to fix it I can find online. I've tried adding in either nomodeset or nomodeset nolapic into the boot options, as well as a few other tweaks there that people recommended, placing it before, instead of, or after the quiet splash. I've tried every UEFI tweak I can find (secure boot off, SATA controller as either RAID or AHCI, legacy mode, etc.). I've tried everything listed here, but none of it seems to work for me.
What other problems exist that could potentially cause it to not advance past a black screen? I'm starting to suspect it's some hardware or firmware issue specific to my computer, so anyone with experience on my specific model would be greatly appreciated.

A: I just solved my issue. In the UEFI settings, under Boot, there is a setting which needs to be chanced. The setting defaults to UEFI, but you have to change it to Legacy Mode.


text:
Q: Why does VB have more LINQ keywords than C#? Why does VB have more LINQ keywords than C#?

A: The VB team decided to create more language extensions than the C# team did (in terms of keywords that translate to standard query operators).  I chalk this up to different teams having different design goals.
Fortunately both languages have full access to all of the standard query operators that are available so there is no loss of functionality.

A: If i remember correctly the only 4 keywords that are available to VB.Net and not C# via the query syntax are

*

*Distinct

*Skip / Skip While

*Take / Take While

*Aggregate
VB.Net added these keywords because we felt it would be valuable to our users.  We envisioned query syntax being a primary way VB.net users would use LINQ and wanted to enable as many scenarios as possible via the syntax.
I do not know why C# left these out.  My speculation is that they didn't feel the scenario justified the cost especially considering the feature is still available via extension methods.
EDIT Added Aggregate and a few others (thanks Dario and Chris!)

A: Check if you have Menu
Tools > Options > Text Editor > C# -> Statment Completation -> Hide advanced members

unckecked, if this is check means you have members hidden from you. This is created by VS Team for help and simplify tasks to newbies.

A: One keyword that is semi-"LINQ"d to LINQ that C# has that VB doesn't have is yield.


text:
Q: $P$ is a probability function assigns probability $p(0Let $(\Omega ,A ,P)$ be a probability space,where $A$ is the sigma field of all subsets of $\Omega$ and $P$ is a probability function that assigns probability $p(0<p<1)$ to each point set of $\Omega$.Show that $\Omega$ must have a finite number of points.
I dont know, perhaps, I am citing an example. If $\Omega$ is infinite and uncountable, suppose the real line $\mathbb{R}$, the we shall take $A$ as the class of all Borel sets of $\mathbb{R}$
But I don't how to prove the problem rigorously.

A: We must have $p|\Omega| = 1 $, hence $p = {1 \over |\Omega|}$.


text:
Q: How to fix error on handling PanGestureRecognizer when called from another class? I want to add PanGestureRecognizer to UIView of UIViewController. I'm dividing view on nine equal parts and create an UIViews by them. Also I added PanGestureRocgnizer on every part. When I call it in another class where I need it it works fine but when I touch on the screen in some part to start handle method for PangestureRecognizer I get the Error: [UIView handlePanGestureRocognizer:]: unrecognized selector sent to instance 0x17de2ee0. This is my code:
#import "CustomGestureRecognizer.h"

@implementation CustomGestureRecognizer
@synthesize arrayOfPatternsForComparison;
@synthesize arrayOfSubviews;
@synthesize arrayOfPanGestureRecognizers;

- (void)initialize:(UIView *)view {
    arrayOfPatternsForComparison = [[NSMutableArray alloc] init];
    arrayOfSubviews = [[NSMutableArray alloc] init];
    arrayOfPanGestureRecognizers = [[NSMutableArray alloc] init];

    [self createPatternsForComparison];
    [self splitScreenInParts:view];
    [self setPanGestrueRecognizersOnEveryPartOfTheScreen];
}

- (void)createPatternsForComparison {

}

- (void)splitScreenInParts:(UIView *)view {
    CGSize onePart = CGSizeMake(view.frame.size.width/3, view.frame.size.height/3);
    CGFloat x_positionOfPart = 0;
    CGFloat y_positionOfPart = 0;

    for (NSUInteger j=0; j<3; j++) {
        for (NSUInteger i=0; i<3; i++) {
            UIView *_view = [[UIView alloc] initWithFrame:CGRectMake(x_positionOfPart, y_positionOfPart, onePart.width, onePart.height)];

            [[_view layer] setBorderWidth:1.0];
            [[_view layer] setBorderColor:[UIColor redColor].CGColor];

            x_positionOfPart += onePart.width;
            [arrayOfSubviews addObject:_view];
            [view addSubview:_view];
        }
        y_positionOfPart += onePart.height;
        x_positionOfPart = 0;
    }

}

- (void)setPanGestrueRecognizersOnEveryPartOfTheScreen {
    for (UIView *view in arrayOfSubviews) {
        UIPanGestureRecognizer *panGestureRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:view action:@selector(handlePanGestureRocognizer:)];
        [[panGestureRecognizer view] setTag:[arrayOfSubviews indexOfObject:view]];
        [view addGestureRecognizer:panGestureRecognizer];
    }
}

- (void)handlePanGestureRocognizer:(UIPanGestureRecognizer *)sender {
    NSLog(@"%d", [[sender view] tag]);
}

@end

and in another class of UIViewController I called it like this:
- (void)viewWillAppear:(BOOL)animated {
    CustomGestureRecognizer *cgr = [[CustomGestureRecognizer alloc] init];
    [cgr initialize:[self view]];
}

How to fix this? Thanks for your answers.

A: Because cgr is released when you call it.
You have to create a var CustomGestureRecognizer *cgr in  .h and then:
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    cgr = [[CustomGestureRecognizer alloc] init];
    [cgr initialize:[self view]];
}

And then change this line
UIPanGestureRecognizer *panGestureRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:view action:@selector(handlePanGestureRocognizer:)];

to
UIPanGestureRecognizer *panGestureRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePanGestureRocognizer:)];

A: The problem is with this line.
UIPanGestureRecognizer *panGestureRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:view action:@selector(handlePanGestureRocognizer:)];

Here you are passing the target as "view" which is here a subview. The target should be a viewController object like "self" or any other viewController object.
And also here you are just creating 9 views (I think in NSObject subclass) and adding to an array, but those are not added to any view as sub views. For this you can return that array to your viewController, and there add pan gesture to those views with self as target. Then it'll work.

A: I solved it by adding var *CustomGestureRecognizer cgr in .h of another class like anhtu said and change
UIPanGestureRecognizer *panGestureRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:view action:@selector(handlePanGestureRocognizer:)];

target to self like Dev said.


text:
Q: d3 v4 Stacked to Grouped Bar Chart from CSV Reference Mike Bostick's Stacked to Grouped Bar Chart example, I am modifying it to work with a CSV file.  I have been working on this for a couple weeks and have looked through countless examples on Stack Overflow and elsewhere and am stumped.
The stacked bar chart works.
Stacked Bar Chart:

When I transition to a grouped bar chart I am only having issues referencing the key or series that is stacked or grouped.  Right now all the rectangles display on top of each other instead of next to each other.
Grouped Bar Chart:

In the function transitionStep2() I want to multiply by a number corresponding to the series or key. I am currently multiplying by the number 1 in this function as a placeholder  .attr("x", function(d) { return x(d.data.Year) + x.bandwidth() / 7 * 1; }).
<!DOCTYPE html>

<form>
  <input type="radio" name="mode" style="margin-left: 10" value="step1" checked>1
  <input type="radio" name="mode" style="margin-left: 20" value="step2">2
</form>

<svg id = "bar" width = "500" height = "300"></svg>

And the csv file:
Year,A,B,C,D
1995,60,47,28,39
1996,29,56,99,0
1997,30,26,63,33
1998,37,16,48,0
1999,46,49,64,21
2000,78,88,81,57
2001,18,11,11,64
2002,91,76,79,64
2003,30,99,96,79

A: The example you're referring has linear values to group the chart into and so .attr("x", function(d, i) { return x(i) + x.bandwidth() / n * this.parentNode.__data__.key; }) works fine.
In your case, the columns/keys is not a linear scale but an ordinal value set that you have to set a scale for:
Refer simple d3 grouped bar chart
To do that i.e. set up a ordinal scale, here's what can be done:
var x1 = d3.scaleBand();
x1.domain(keys).rangeRound([0, x.bandwidth()]);

So this new scale would have a range of the x scale's bandwidth with the domain of ["A", "B", "C", "D"]. Using this scale to set the x attribute of the rects to group them:
.attr("x", function(d) {
  return x(d.data.Year) + x1(d3.select(this.parentNode).datum().key);
})

where d3.select(this.parentNode).datum().key represent the column name.
Here's JSFIDDLE (I've used d3.csvParse to parse the data but I'm sure you'll get the point here. It's just the x attribute you need to reset.
Here's a Plunkr that uses a file.
Here's a code snippet as well:

  var svg = d3.select("#bar"),
    margin = {top: 20, right: 20, bottom: 20, left: 20},
    width = +svg.attr("width") - margin.left - margin.right,
    height = +svg.attr("height") - margin.top - margin.bottom,
    g = svg.append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")");

  var x = d3.scaleBand()
    .rangeRound([0, width])
    .padding(0.08);

 var x1 = d3.scaleBand();

  var y = d3.scaleLinear()
    .range([height, 0]);

  var color = d3.scaleOrdinal()
    .range(["#7fc97f", "#beaed4", "#fdc086", "#ffff99"]);

var csv = 'Year,A,B,C,D\n1995,60,47,28,39\n1996,29,56,99,0\n1997,30,26,63,33\n1998,37,16,48,0\n1999,46,49,64,21\n2000,78,88,81,57\n2001,18,11,11,64\n2002,91,76,79,64\n2003,30,99,96,79';

var data = d3.csvParse(csv), columns = ["A", "B", "C", "D"];

data.forEach(function(d) {
    for (i = 1, t = 0; i < columns.length; ++i) t += d[columns[i]] = +d[columns[i]];
    d.total = t;
});

  var keys = columns;

  x.domain(data.map(function(d) { return d.Year; }));
  x1.domain(keys).rangeRound([0, x.bandwidth()]);
  y.domain([0, d3.max(data, function(d) { return d.total; })]).nice();
  color.domain(keys);

  g.append("g")
    .selectAll("g")
    .data(d3.stack().keys(keys)(data))
    .enter().append("g")
      .attr("fill", function(d) { return color(d.key); })
    .selectAll("rect")
    .data(function(d) { return d; })
    .enter().append("rect")
      .attr("x", function(d) { return x(d.data.Year); })
      .attr("y", function(d) { return y(d[1]); })
      .attr("height", function(d) { return y(d[0]) - y(d[1]); })
      .attr("width", x.bandwidth());

  rect = g.selectAll("rect");

  d3.selectAll("input")
    .on("change", changed);

  function changed() {
    if (this.value === "step1") transitionStep1();
    else if (this.value === "step2") transitionStep2();
  }

  function transitionStep1() {
    rect.transition()
      .attr("y", function(d) { return y(d[1]); })
      .attr("x", function(d) { return x(d.data.Year); })
      .attr("width", x.bandwidth())
      .attr("stroke", "green");
  }

 function transitionStep2() {
    rect.transition()
      .attr("x", function(d) {
       return x(d.data.Year) + x1(d3.select(this.parentNode).datum().key);
     })
      .attr("width", x.bandwidth() / 7)
      .attr("y", function(d) { return y(d[1] - d[0]); })
      .attr("stroke", "red");
  }
<!DOCTYPE html>

<form>
  <input type="radio" name="mode" style="margin-left: 10" value="step1" checked>1
  <input type="radio" name="mode" style="margin-left: 20" value="step2">2
</form>

<svg id = "bar" width = "500" height = "300"></svg>

Hope something helps. :)

A: You have to pass the index of the key to the individual rectangles and use this index to multiply with the reduced bandwith. If you also use the length of the keys array (instead of 7) you are CSV column count independent. You need to put the declaration of keys variable outside the d3.csv handler.
You forgot to stroke the initial rects green.

A: I updated your examples so that it works,
see https://jsfiddle.net/mc5wdL6s/84/
  function transitionStep2() {
    rect.transition()
     .duration(5500)
      .attr("x", function(d,i) {
        console.log("d",d);
        console.log("i",i);
      return x(d.data.Year) + x.bandwidth() / m / n * i; })
      .attr("width", x.bandwidth() / n)
      .attr("y", function(d) { return y(d[1] - d[0]); })
      .attr("height", function(d) { return y(0) - y(d[1] - d[0]); })
      .attr("stroke", "red");
  }


text:
Q: Keeping track of the output columns in sklearn preprocessing How do I keep track of the columns of the transformed array produced by sklearn.compose.ColumnTransformer? By "keeping track of" I mean every bit of information required to perform a inverse transform must be shown explicitly. This includes at least the following:

*

*What is the source variable of each column in the output array?

*If a column of the output array comes from one-hot encoding of a categorical variable, what is that category?

*What is the exact imputed value for each variable?

*What is the (mean, stdev) used to standardize each numerical variable? (These may differ from direct calculation because of imputed missing values.)

I am using the same approach based on this answer. My input dataset is also a generic pandas.DataFrame with multiple numerical and categorical columns. Yes, that answer can transform the raw dataset. But I lost track of the columns in the output array. I need these information for peer review, report writing, presentation and further model-building steps. I've been searching for a systematic approach but with no luck.

A: The answer which had mentioned is based on this in Sklearn.
You can get the answer for your first two question using the following snippet.
def get_feature_names(columnTransformer):

    output_features = []

    for name, pipe, features in columnTransformer.transformers_:
        if name!='remainder':
            for i in pipe:
                trans_features = []
                if hasattr(i,'categories_'):
                    trans_features.extend(i.get_feature_names(features))
                else:
                    trans_features = features
            output_features.extend(trans_features)

    return output_features

import pandas as pd
pd.DataFrame(preprocessor.fit_transform(X_train),
            columns=get_feature_names(preprocessor))

transformed_cols = get_feature_names(preprocessor)

def get_original_column(col_index):
    return transformed_cols[col_index].split('_')[0]

get_original_column(3)
# 'embarked'

get_original_column(0)
# 'age'

def get_category(col_index):
    new_col = transformed_cols[col_index].split('_')
    return 'no category' if len(new_col)<2 else new_col[-1]

print(get_category(3))
# 'Q'

print(get_category(0))
# 'no category'

Tracking whether there has been some imputation or scaling done on a feature is not trivial with the current version of Sklearn.


text:
Q: My Microdata doesn't validate: "The itemprop attribute was specified, but the element is not a property of any item." I'm trying to validate a webpage with some Microdata in the Schema.org format, but I get a lot of errors of the type:

The itemprop attribute was specified, but the element is not a property of any item.

This is the general structure of my markup:

    <meta itemprop="productID" content="XYZ0001" />
    <meta itemprop="name" content="Product XYZ" />

            Foo
            1197

            Bar
            Blah blah

I'm using ProductModel and additionalProperty since the page entity doesn't have a more suitable predefined type (yet). Am I making any obvious mistakes in the markup?

A: If you specify itemprop on an element, there must be a parent element with itemscope.
Unless you have such a parent element not shown in the snippet, this is likely the line that gives the error:

I assume you want to convey that this ProductModel is the main entity of the web page, so you could specify:

(Or one of the more specific sub-types, if applicable, e.g., ItemPage.)


text:
Q: Validate files/archives against database - Are derived clases the correct way? I'd like to validate files or entries inside archives (zip, 7z,...) against a database by Crc32.
If files are unknown, delete them. If files need to be renamed, rename them, and so on...
this is the structure that i have implemented so far:
public class FileBase
{
    public FileBase() { }

    public string FullName { get; set; }
    public string Name => Path.GetFileName(FullName);
    public string FileNameWithoutExtension => Path.GetFileNameWithoutExtension(FullName);
    public string DirectoryName => Path.GetDirectoryName(FullName);
    public string Extension => Path.GetExtension(FullName);
    public string Crc { get; set; }
    public DateTime? LastWriteTime { get; set; }
}

public class FileModel : FileBase
{
    public FileModel() { }

    public void MoveTo(string target)
    public void Delete()
}

public class ArchiveModel : FileModel
{
    public ArchiveModel() { }

    public HashSet<ArchiveFileModel> Entries{ get; private set; }

    public Dictionary<string, Stream> Extract(List<ArchiveFileModel> entries)
    public void Compress(Dictionary<string, Stream> fileStreams)
    public void Modify(ArchiveInfoFile entry, string targetName)
}

public class ArchiveFileModel : FileBase
{
    public ArchiveFileModel() { }

    public int Index { get; set; }
    public ArchiveModel Parent { get; set; }
}

I now create a list of type FileBase which contains FileModels or ArchiveModels (based on file extension) to loop though every file and validate against database.
The downsite of this, for every needed action (MoveTo, Delete, Extract, Compress, Modify) I need to cast the base class objects into derived class objects (which I feel is bad practise):
var fileList = new List<FileBase>;
.
.
.
foreach (file in fileList)
{
    If (file is ArchiveFileModel)
    {
        var archive = file as ArchiveFileModel;
        archive.Compress(....
        ...
    }
}

and so on....
Does anyone have any other ideas to solve this usecase?


text:
Q: cache and jQuery.get I have a mobile app using cache via manifest file working and being in cache very well.
How can I get to information on the server. jQuery.post works no issues but jQuery.get will not because the browser just checks the local CACHE. Is there away of to make .get work.
Putting a random key after ? has zero effect. Is this something browsers willjust not allow going forward?


text:
Q: How to add an authorization header to a DOM form element? I am trying to upload a file to a server, and have my DOM element setup as such:
        _uploadForm = document.createElement("form");

        _uploadForm.method = "POST";
        _uploadForm.action = "#";

        if(_isBrowser.IE)
            _uploadForm.encoding = "multipart/form-data";
        else
            _uploadForm.enctype = "multipart/form-data";

My server requires an http basic authorization header. How can I pass that through this DOM element?

A: Your javascript client is going to have to add headers when submitting the form.
I am not sure which javacript client lib you are using, but things like angular do allow you to set default headers or even have interceptors that can add headers before sending.
        var req = {
 method: 'POST',
 url: 'http://example.com',
 headers: {
   'Content-Type': undefined,
   'Authorization':  'your-scheme your-token-perhaps'
 },
 data: { test: 'test' }
}

A: DOM elements have nothing to do with authorization, they're just the internal browser's representation of the various html tags. Authorization is demanded by the server - if the page is in a protected area, then the server will demand credentials, and that has nothing to do with the form itself.

A: The easiest way is to serve the upload form and the upload handler from the same folder, and use .htaccess to force Basic authentication for both. Then the browser automatically requests credentials when the upload form is loaded, and the credentials would be sent automatically with the upload (I believe).
However, your best bet is not to use HTTP Basic authentication at all. It sends passwords in clear text on every request unless you're using SSL, and in general, it is a hassle to use.
If you insist on using Basic, I believe it can be done with ActionScript (compiled to an SWF). I also know a way to set an Authorization header on an AJAX call, but you can't upload a file with an AJAX call, and the browser does not remember Authorization headers sent via an AJAX call.


text:
Q: Angular, How can I show 10 as 10.00 I have a textbox and I want to show the value the user enters with 2 decimals,
ex. if user entered 10, then I will show 10.00 in the text box.
<input type="number" class="form-control"/>

It's simple like this, I tried to use watch but am not sure about the method that am going to use in order to reach the required.
Do we have anyway to use currency filter inside a textbox input ?

A: Try this:
<input type="number" step="0.01" ...>

The step attribute is actually for the amount of increment/decrement by up and down buttons but it also happens to set the resolution of the number to a certain number of digits after the decimal in floating point numbers.

A: Would a filter work? You might want to work in some kind of delay so that the form lets the user finish typing before converting the number, but this works (minus the delay):
    <!doctype html>
    <html ng-app="numFilterExample">
        <head>
            <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
            <script>
                angular.module('numFilterExample',[])
            .controller('NumberFilterController', ['$scope','numberFilter',function($scope,numFilter){
                $scope.change = function(){
                    $scope.num = numFilter($scope.num,2);
                };
            }]);
        </script>
    </head>
    <body>
        <div ng-controller="NumberFilterController">
            <input ng-model='num' ng-change="change()" />
        </div>
    </body>
</html>


text:
Q: matplotlib.pyplot.annotate() : place a text on subplot with 'axes fraction' coordinates I have some trouble with matplotlib.pyplot.annotate() when I use big numbers in the horizontal axis, for example doing time series with time data in "seconds since epoch" where the data will reach 10^9.
Here is an example:
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt

import os.path

import random

import calendar

save_path='my_path'

fig,ax=plt.subplots(2,sharex=True)
fig.set_size_inches(6,5)

a=int(calendar.timegm((2009,1,1,0,0,0)))
b=int(calendar.timegm((2009,2,1,0,0,0)))
x=xrange(a,b,(b-a)/100)
#x=xrange(0,b-a,(b-a)/100)

y=[random.random() for i in x]
z=[random.random() for i in x]

ax[0].scatter(x,y)
ax[1].scatter(x,z)

for sub in ax:
    sub.set_xlim(x[0],x[-1])

ax[0].annotate('test',(0.1,0.1),textcoords='axes fraction')
ax[1].annotate('test',(0.9,0.9),textcoords='axes fraction')

fig.savefig(os.path.join(save_path,'test.png'),bbox_inches='tight')
plt.close()

With x=xrange(a,b,(b-a)/100)
I get:

While with x=xrange(0,b-a,(b-a)/100)
I get:

I don't understand why the first case doesn't work but the second case works as expected, I just reduced the numbers basically.
I have no problems if I use 'data' coordinates though.


text:
Q: Method not allowed Flask Whenever I press my submit button for my file to go to that file page I get a method not allowed, I thought it was an issue with not has POST and GET but I do. Essentially this line isn't working in my code
     if request.method == 'POST':
        return redirect(url_for('files()'))

views.py
class HView(BaseView):
    route_base = "/home"

    @expose('/test')
    @appbuilder.app.route('/test', methods=['GET', 'POST'])
    def test(self):
        if request.method == 'POST':
            return redirect(url_for('files()'))
        else:
            return render_template(blah)

index.html
    {% extends "appbuilder/base.html" %}
{% block title %}Title{% endblock %}

{% block content %}

Bucket List

          Bucket Name
          Created

        {% for bucket in buckets %}

          {{ bucket['Name'] }}
          {{ bucket['CreationDate'] | datetimeformat }}

                <form class="select-bucket" action="{{ url_for('HView.test')}}" method="post">
                    <input type="hidden" name="bucket" value="{{ bucket['Name'] }}"/>
                    <button type="submit" class="btn btn-primary btn-sm">

                    </button>
                </form>

        {% endfor %}

{% endblock %}

A: Try specifying the method in @expose
Ex:
class HView(BaseView):
    route_base = "/home"

    @expose('/test', methods=['GET', 'POST'])
    def test(self):
        if request.method == 'POST':
            return redirect(url_for('files()'))
        else:
            return render_template(blah)


text:
Q: Running SQL server 2005 and 2008 on same machine? Running SQL server 2005 and 2008 on same machine ? Is this possible/practicable ?
It's only for developers and not very resource intensive - is there anyone out there who's done it ?
Would be interested to hear of experiences or known gotchas.
(I realise we could use a VM but I'm talking about running it within the same machine)
thanks
R.

A: Doing it right now. I have SQL 2005 and two SQL 2008 instances running.
It's easy to do. Just install SQL Server 2005, and when it asks you which instance, make sure you choose "Named Instance", and give it a name you will remember (such as, I dunno, SQL2005?).
Then, install SQL Server 2008. Same thing when it comes to the instance - make sure it's a named instance (Say, SQL2008). In your Services control panel you will see all the SQL stuff duplicated, but it will have the instance name after each entry (SQL2005/SQL2008).
When you need to connect, you connect to machine\instance, so you would connect to localhost\SQL2005 or localhost\SQL2008 as the server name, and off you go.
It is definitely memory intensive, so you might choose to disable them if you're not using them right at the moment. Under idle with nothing happening right after bootup they're using about 150mb each.

A: Yes, it's doable and practical. We even have that situation in production with clustered servers. Our biggest issue has been with SSIS. If both versions are installed, you'll need to make sure to specify the path to the right dtexec based on what version the package is.


text:
Q: How to Set an Image as Background in Next.js? I have two components:

*

*LoginLayout which should is high order comp for Login component

*Login component is page
I need to make the login page have an image as the background.
I tried achieving this through CSS and it does not work.
Here is LoginLayout comp:
export default ({ children, title }) => (

// I tried to add background: url(.../img)) to this login-layout class

      <title>Login to Tex</title>

{children}

);

How can this be achieved in Next.js?

A: Make sure you have your CSS attached to your component, as @Deano mentioned.
import './style.css';

If you use CSS modules import like this instead:
import styles from './MyStyles.module.css';

export default ({ children, title }) => (

      <title>Login to Tex</title>

{children}

);


text:
Q: BackHandler Navigation in Drawer Navigator and Main Stack Navigator in React Navigation I am not being able to get the backHandler (Hardware Back Button on Android) to work with my Drawer and Stack Navigation on React-Navigation
The back button works perfectly on the homepage screen and but it stops working once i navigate to next screen wether the screen is in the drawer screen or in the stack.
Here is my both Drawer and MainStackNavigator.
Note: Combining the two didn't work for me as both of them are not part of a component and I am using redux in my app
Anyone has any idea how this could be resolved?
DrawerNavigatior
const DrawerNavigator = createDrawerNavigator(
  {
    Homep: Homepage,
    Home: HomeScreen,
    Shop: ShopScreen,
    Order: OrdersScreen,
    Wishlist: WishlistScreen,
    Search: SearchScreen,
    Profile: ProfileScreen,
    ShoppingBag: ShoppingBagScreen,

  },

MainStackNavigator

const MainStackNavigator = createStackNavigator(
  {
    Drawer: { screen: DrawerStackNavigator },
    CategoryProductGrid: { screen: CategoryProductGridScreen },
    Settings: { screen: SettingsScreen },
    Contact: { screen: ContactUsScreen },
    EditProfile: { screen: EditProfileScreen },
    ShippingAddress: { screen: ShippingAddressScreen },
    LocList: { screen: LocationList },
    ShippingMethod: { screen: ShippingMethodScreen },
    PaymentMethod: { screen: PaymentMethodScreen },
    AddACard: { screen: AddACardScreen },
    Checkout: { screen: CheckoutScreen },
    Bag: { screen: ShoppingBagScreen },

  },

I am using BackHander event listener as follows
  componentDidMount() {
    this.backHandler = BackHandler.addEventListener('hardwareBackPress', this.handleBackPress);
  }

  componentWillUnmount() {
    this.backHandler.remove()
  }

  handleBackPress = () => {

    Alert.alert(
      'Exit App',
      'Exiting the application?',
      [
        {
          text: 'Cancel',
          onPress: () => console.log('Cancel Pressed'),
          style: 'cancel'
        },
        {
          text: 'OK',
          onPress: () => BackHandler.exitApp()
        }
      ],
      {
        cancelable: false
      }
    );
    return true;

  };

A: Wohoo, after a week of searching and trying different ways
The solution was really simple, I had to move the drawer navigation and put it all under the MainstackNavigator so the Return back hardware button will work properly


text:
Q: Getting a UITableView to refresh users after one begins a live stream The landing page for an app I am working on has a place holder avatar named after the application that is present when no user is actively live streaming (using the Red5 Pro streaming framework for this).
However when someone does begin to stream, I want it to automatically refresh the tableview and display the new user's avatar. What I've written so far kind of works, but not entirely. When someone begins livestreaming the placeholder avatar does disappear, but the user that's streaming's avatar doesn't appear.
If I close the app and reopen it, then it is displayed correctly. Here's my code in Swift 3, what am I doing wrong? Should the call to refresh be moved out of ViewDidLoad? Am I using Dispatch Queue incorrectly? Thanks
import UIKit
import Firebase

class HomeController: UIViewController, UITableViewDataSource,     UITableViewDelegate, cellDelegate {

@IBOutlet var tableView: UITableView!
var stream: String!
var top: [SSStream] = []
var recent: [SSStream] = [SSStream()]
var trending: [SSStream] = [SSStream()]
var ref: FIRDatabaseReference!

override func viewDidLoad() {
    navigationItem.title = "Swiffshot"
    navigationController?.navigationBar.isTranslucent = false
    let settings = UIButton(frame: CGRect(x: 0, y: 0, width: 20, height: 20))
    settings.setImage(#imageLiteral(resourceName: "Settings"), for: .normal)
    settings.addTarget(self, action: #selector(settingsPressed), for: .touchUpInside)
    navigationItem.leftBarButtonItem = UIBarButtonItem(customView: settings)
    let friends = UIButton(frame: CGRect(x: 0, y: 0, width: 23, height: 20))
    friends.setImage(#imageLiteral(resourceName: "AllFriends"), for: .normal)
    friends.addTarget(self, action: #selector(friendsPressed), for: .touchUpInside)
    navigationItem.rightBarButtonItem = UIBarButtonItem(customView: friends)

    let nib = UINib(nibName: "MainHeader", bundle: Bundle.main)
    tableView.register(nib, forHeaderFooterViewReuseIdentifier: "MainHeader")

    ref = FIRDatabase.database().reference()

    if !SSContact.shared.active {
        performSegue(withIdentifier: "fromMainToAuth", sender: self)
    }

    SSContact.shared.load() { SSContact.shared.propertyCheck(self) { } }

//        SSContact.shared.subscribeToTop(pulse: { (streams) in
//            self.top.removeAll()
//            self.top.append(contentsOf: streams)
//            self.tableView.reloadSections(IndexSet(integer: 0), with:     .automatic)
//        })

    ref.child("streams").observe(.value, with: { (snapshot) in

        print("I ran")

        self.top.removeAll()
        if let userData = snapshot.value as? NSDictionary {
            for stream in userData {
                let newStream = SSStream()
                newStream.username = stream.key as! String
                print("Found stream \(stream.key as! String)")
                newStream.isPrivate = !((stream.value as! NSDictionary)["public"] as! Bool)
                newStream.views = (stream.value as! NSDictionary)["views"] as! Int
                newStream.isEnabled = true
                self.top.append(newStream)
            }
        }
        if self.top.isEmpty {
            print("No Streams Found")
            self.top.append(SSStream())
        }
        DispatchQueue.main.async {
            self.tableView.reloadSections(IndexSet(integer: 0), with: .automatic)
            self.tableView.reloadData()
        }
    })
}

func cellGotPressed(_ stream: String) {
    self.stream = stream
    performSegue(withIdentifier: "toPlayer", sender: self)
}

func settingsPressed() {
    performSegue(withIdentifier: "toSettings", sender: self)
}

func friendsPressed() {
    performSegue(withIdentifier: "fromMainToExpandable", sender: self)
}

func cameraTapped() {
    performSegue(withIdentifier: "toRed", sender: self)
}

func cellTapped() {
    print("Cell Tapped")
}

// MARK: Segue

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "toPlayer" {
        let player = segue.destination as! VideoPlayerViewController
        player.isSubscribing = true
        player.stream = stream
    }
}

// MARK: Table View Functions

func numberOfSections(in tableView: UITableView) -> Int {
    return 3
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 1
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    if indexPath.section == 0 {
        let cell = tableView.dequeueReusableCell(withIdentifier: "big") as! CategoryRow
        cell.section = indexPath.section
        cell.top = top
        cell.delegate = self
        cell.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(cameraTapped)))
        return cell
    } else {
        let cell = tableView.dequeueReusableCell(withIdentifier: "small") as! CategoryRow
        cell.section = indexPath.section
        cell.recent = recent
        cell.trending = trending
        cell.delegate = self
        return cell
    }
}

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    if section == 0 {
        return nil
    } else {
        let cell = self.tableView.dequeueReusableHeaderFooterView(withIdentifier: "MainHeader")
        let header = cell as! MainHeader
        if section == 1 {
            header.fillHeader("RECENT")
        } else if section == 2 {
            header.fillHeader("Trending + Now")
        } else {
            print("Unknown Section")
        }
        return header
    }
}

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    if indexPath.section == 0 {
        return 300
    } else {
        return 100
    }
}

func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    if section == 0 {
        return 0
    } else {
        return 50
    }
}

func tableView(_ tableView: UITableView, estimatedHeightForHeaderInSection section: Int) -> CGFloat {
    return 50
}
}

A: I realized what I needed to do. I needed to set the
ref.child("streams").observe

in the call to Dispatch.Queue. By setting the reference before dispatch was called, the program wasn't syncing properly. It should be like this:
DispatchQueue.main.async {
ref.child("streams").observe(.value, with: { (snapshot) in
        self.tableView.reloadSections(IndexSet(integer: 0), with: .automatic)
        self.tableView.reloadData()
    }
})


text:
Q: Unable to extract specific field from Json response I used to simply populate the list of EmployeeIds from the following the Json response:
{\r\n \"EmployeeId\": [\r\n  201812345,\r\n 201812346,\r\n 201812347, \r\n}

into my collection by
var resultSet = await response.Content.ReadAsAsync<EmployeeIds>();

However recently the server response has changed to:
{
 "httpStatus": 200,
 "queryID": "getIds",
 "statustext": [
 "ResultCode: OK"
 ],
"rowsReturned": 228,
"dataset": "[\r\n {\r\n  \"EmployeeId\": 20181234\r\n  }, \r\n {\r\n
\"EmployeeId\": 20181234\r\n  },\r\n {\r\n  \"EmployeeId\": 20181234\r\n
}\r\n]"
}

I am now unable to extract the EmployeeId values from this Json. I have tried to deserializing the response by:
var jsonresult=await response.Content.ReadAsStringAsync();
var deserializedjsonobject = JObject.Parse(jsonResult);
var Ids= deserializedjsonobject["dataset"]

but the value  results for ids  is always:
"[\r\n {\r\n  \"EmployeeId\": 20181234\r\n  }, \r\n {\r\n \"EmployeeId\": 20181234\r\n  },\r\n {\r\n  \"EmployeeId\": 20181234\r\n }\r\n]

Thanks

A: dataset is a serialized json string. You will need to deserialize this after deserializing the outer object.
var jsonresult = await response.Content.ReadAsStringAsync();
var deserializedjsonobject = JObject.Parse(jsonResult);
var Ids = JArray.Parse(deserializedjsonobject["dataset"]);

A: Thanks for everyone input. The issue that I did not pay attention to was that the fact that dataset": "[XXXXX]" was wrapped in double quote and hence was coming back as string. I contacted the provider and they fixed the problem


text:
Q: javascript onclick alert not working I have an auto-generated form which submits data using ajax as shown below in joomla CMS:
Please note that i cannot make any modifications to this form else it will not submit data anymore. Also the composer_965292549 changes every time the page loads.
<form name="dc_submit" autocomplete="off" class="form-horizontal" action="/demo?controller=posts&task=reply" method="post">
First name: <input type="text" name="fname">
<input type="submit" value="Submit" onclick="discuss.reply.submit('composer_965292549');return false;">
</form>

Now i want to add a javascript alert and here's the code
<script type="text/javascript">
function discuss.reply.submit()
{
  alert("his");
  }
</script>

Now, this javascript alert doesn't work. Replacing discuss.reply.submit() with discuss() tends to do the trick but if i do that, the data never reaches the database. I can't replace that. Please suggest.

A: What exists is that is based off an object
discuss = discuss || {};
discuss.reply = discuss.reply || {}
discuss.reply.submit = function() {
   alert("xxx");
}

or if the code already exixts, you can just override it
discuss.reply.submit = function() {
   alert("xxx");
}

This will override the default function. Meaning, it will not do what it did before. If you still want this to be called you can copy the old one and call it.
var _org = discuss.reply.submit;
discuss.reply.submit = function() {
   alert("xxx");
   _org.apply( this, arguments );
}

A: The function name is discuss.reply.submit. This is not a valid function name, see this stackoverflow post on variable names, the same rules apply. A good function name would be onDiscussReplySubmit.

A: Your function name implies a structure such as
 var discuss ={ "reply" : { "submit" : function(){alert("his");}}}

This is an object not a function name. Either change your function name or make an object.

A: First, you can't use dots on JS function names.
<script type="text/javascript">
function discussReplySubmit(x)
{
  alert(x);
}
</script>

Second, if you don't wanna to have the form submited, them replace submit with a button:
<input type="button" value="Submit" onclick="discussReplySubmit('composer_965292549')" />

Finally, if you want to submit the form don't use onclick event on submit button, use the OnSubmit event of Form:
<form name="dc_submit" autocomplete="off"
    class="form-horizontal" action="/demo?controller=posts&task=reply"
    method="post" OnSubmit="discussReplySubmit('composer_965292549')">
    First name: <input type="text" name="fname">
    <input type="submit" value="Submit" />
</form>


text:
Q: Can I have an alias of function inside the same library in Elixir? Say I have the definition of a function:
def rename(src, dst) do
   <do rename>
end

inside of my Elixir library, can I then create within the same library:
alias rename, as: mv

so that when users can use both the rename and mv functions in my library ?

A: If your method accepts arguments:
You would also need to specify the arguments in defdelegate:
defmodule MyModule do
  def awesome_func(term, opts \\ []) do
    # Do Something
  end

  defdelegate badass_func(term, opts \\ []), to: __MODULE__, as: :awesome_func
end

A: The simplest approach I can think of is via defdelegate
iex(1)> defmodule Foo do
...(1)>   def foo, do: :foo
...(1)>
...(1)>   defdelegate bar, to: __MODULE__, as: :foo
...(1)> end

iex(2)> Foo.foo
:foo
iex(3)> Foo.bar
:foo

Note that this defines another function bar/0 which invokes foo/0.

A: The correct answer as of Elixir 1.11 is no, you can't have aliases for functions.
The defdelegate does not create an alias, but instead, it creates another function that calls the function for which you wanted an alias.


text:
Q: Removal of List from Pandas DataFrame     ProArticle                                          Vector

0   Iran jails blogger 14 years An Iranian weblogg...   [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, ...
1   UK gets official virus alert site A rapid aler...   [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, ...
2   OSullivan could run Worlds Sonia OSullivan ind...   [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, ...
3   Mutant book wins Guardian prize A book evoluti...   [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, ...
4   Microsoft seeking spyware trojan Microsoft inv...   [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, ...

The above is the data.head() snippet from a vectorized news article.
type(data.Vector[0]) is list
I need to use KMeans clustering on this Vectorized data, but the lists won't let me.
data.Vector.shape is 179, and data.Vector[0].shape is 8868.
How can I remove the list, or if I can't, then how can I use it to cluster the given data? Perhaps I could get a dataframe in the following way to start, followed by running PCA on it.
Expected Output looks like this:

A: What it seems that you want to do, is to create a 2D numpy array out of a Pandas column that contains lists of numbers. In most cases you can treat a Pandas column as a list or 1-dimensional Numpy array. here, you can use vstack to stack the separate lists as rows:
>>> df = pd.DataFrame({
...     "ProArticle": ["a", "b", "c", "d"],
...     "Vector": [[0, 0], [1, 1], [2, 2], [3, 3]]
... })
>>> vs = np.vstack(df.Vector)
>>> vs
array([[0, 0],
       [1, 1],
       [2, 2],
       [3, 3]])

So this results in an array that you can use directly with sklearn's KMeans:
>>> kmeans = KMeans(n_clusters=2)
>>> kmeans.fit_predict(vs)
array([1, 1, 0, 0], dtype=int32)

If you still want to have the intermediate result as a Pandas dataframe, you can use apply to create Pandas series of each list; according to apply's documentation this results in a DataFrame:
>>> df.Vector.apply(pd.Series)
   0  1
0  0  0
1  1  1
2  2  2
3  3  3

You can then get the same Numpy array by accessing the .values member of the resulting DataFrame. However, this is by far slower than the vstack solution, 1 milliseconds versus 25.4 microseconds on my machine.


text:
Q: Makefile ignore segfault I am trying to use GNU Make to automatically convert a set of .mmpz files to .ogg files using lmms. There's currently a bug in lmms that causes it to segfault after producing the output file, leading make to spit out errors. Adding a - before the rule forces make to ignore the error and prevents it from removing the output file, but error messages are still produced. I've tried the following:
-@lmms -r $(MPPZDIR)/$*.mmpz -f ogg -o $(OGGDIR)/$*.ogg
-@lmms -r $(MPPZDIR)/$*.mmpz -f ogg -o $(OGGDIR)/$*.ogg 2> /dev/null
-@lmms -r $(MPPZDIR)/$*.mmpz -f ogg -o $(OGGDIR)/$*.ogg || true

which all produce something along the lines of
/bin/sh: line 1:  3325 Segmentation fault      (core dumped) lmms -r resources/mmpz/song.mmpz -f ogg -o content/music/song.ogg 2> /dev/null
Makefile:28: recipe for target 'content/music/song.ogg' failed
make: [content/music/song.ogg] Error 139 (ignored)

Considering that the segfault is expected and does not indicate a failure to produce the output file, is there a way to hide this error until the bug is fixed?
make -i also still seems to output the errors.

A: define EXPECTED_FAIL
if ! { $1 ; } 2>$@.temp; then \
    echo EXPECTED FAILURE: ; cat $@.temp; \
fi
endef

<target>: <prerequisites>
    $(call EXPECTED_FAIL, lmms -r $(MPPZDIR)/$*.mmpz -f ogg -o $(OGGDIR)/$*.ogg )