text:
Q: How to resolve an incomplete \iffalse error? I'm trying to create a multitude of 8x8 grids with a single random shaded box on each. This is for a classroom activity and I want a bunch of different grids and would rather not hard-code the random box for each one. I'm using the following code:
\begin{tikzpicture}[x=2.54cm, y=2.54cm]
    \foreach \y in {1,2,...,8}
    {
        \foreach \x in {1,2,...,8}
        {
            \ifthenelse{\x= \pgfmathparse{random(8)}\pgfmathresult \AND \y=\pgfmathparse{random(8)}\pgfmathresult}
            {\filldraw[draw=black,fill=lightgray] (\x,\y) rectangle (\x,\y) rectangle (1+\x,1+\y);}
            {\draw[black] (\x,\y) rectangle (\x,\y) rectangle (1+\x,1+\y);}
        }
    }
\end{tikzpicture}

And I get the error

Incomplete \iffalse; all text was ignored after line 51"

where line 51 is that close curly brace before the \end{tikzpicture}. I've looked around for a fix but haven't discovered one yet.

A: Just fleshing out David's comments.
\documentclass{standalone}
\usepackage{ifthen}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}[x=2.54cm, y=2.54cm]
\pgfmathtruncatemacro{\RandomX}{random(8)}
\pgfmathtruncatemacro{\RandomY}{random(8)}
    \foreach \y in {1,2,...,8}
    {
        \foreach \x in {1,2,...,8}
        {
            \ifthenelse{\x=\RandomX  \AND \y=\RandomY}
            {\filldraw[draw=black,fill=lightgray] (\x,\y) rectangle (\x,\y) rectangle (1+\x,1+\y);}
            {\draw[black] (\x,\y) rectangle (\x,\y) rectangle (1+\x,1+\y);}
        }
    }
\end{tikzpicture}
\end{document}

And @cfr is right, but this also works.

A: It seems easier to draw the grid first and then shade a random box as then you don't need to have a conditional statement. The following code defines a macro \RandomSquareInGrid that shades a random square in a square grid. By default, an 8x8 grid is drawn but there is an optional argument to change the grid size. When I ran the MWE below I got

but as the shaded square is chosen randomly the output should change.
Here is the code:
\documentclass{article}
\usepackage{tikz}
\parindent=0pt

\newcommand\RandomSquareInGrid[1][8]{%
  \begin{tikzpicture}[scale=0.2,x=2.54cm, y=2.54cm]
    \foreach \x in {0,...,#1} {% draw the grid
      \draw(\x,0) -- ++(0,#1);
      \draw(0,\x) -- ++(#1,0);
    }
    \pgfmathsetmacro\xrnd{random(#1)}% choose a random square to shade
    \pgfmathsetmacro\yrnd{random(#1)}
    \draw[fill=lightgray](\xrnd,\yrnd) rectangle ++ (-1,-1);
  \end{tikzpicture}%
}
\begin{document}

  \RandomSquareInGrid \quad
  \RandomSquareInGrid \quad
  \RandomSquareInGrid

  \RandomSquareInGrid[4] \quad
  \RandomSquareInGrid[10]

\end{document}

Actually, rather than drawing the grid by "by hand", as I have done, one should perhaps use the tikz grid command. Note that I have added scale=0.2 only to make it easier to see the output.


text:
Q: Google automl translate with tags I have created a custom Model with Google AutoML. And I would like to use some "tags" such has  and make sure it doesn't get translated by Google AutoML. I expect that these tags would be copied as is in the target language at the corresponding place. `
Is there such a feature? I didn't find anything in their documentation.
Example:
The dog is walking <tag> outside.  --- >  Le chien marche <tag> dehors.

A: I finally found the answer.
You first need to specify "text/html" as mime_type in your request.
And you need to put any text you want to keep as is between these tags:
(you can use any of the two ways)
Your text

Your text

redpajama_set_name: RedPajamaStackExchange


text:
Q: Bootstrap Drop down menu is not working its supposed to be drop down the menus  but its not working
properly
I can't figure it out what i did mistake to this code
Here is my code !!!

                Web Revert

            Menu Items

Home

About

Contact

Works

                        Our Profile

Portfolio

Web Team

Founder Mamber

            Right Aligns

Settings

Logout

help needed

A: have you tried linking this first?


text:
Q: Android: Programmatically calculate Listview Font Metrics I have a String and I need to truncate the string such that it fits on one line in a ListView.
Can anyone point me in the right direction?

A: You need to specify that in the XML of your list item row file.
These are the attributes you need to play with on your TextView;
android:singleLine="true"
android:maxLength="someLengthofCharacters(int)"
android:ellipsize="end"  //if you want an ellipse to be appended to the end of your String

EDIT: Try this approach to set the max character length of your TextView programmatically
TextView tv = new TextView(this);
int maxLength = 10;
InputFilter[] fArray = new InputFilter[1];
fArray[0] = new InputFilter.LengthFilter(maxLength);
tv.setFilters(fArray)

and set single line to true by using
TextView.setSingleLine or TextView.setLines(1)


text:
Q: Dual boot: Black screen after purple screen with logo I have Ubuntu 14.04 installed along Windows 8.1 running with GRUB2 in a MSI GE60, i7 with an nVidia GeForce GTX card.
Out of the blue, today when I try to run Ubuntu, after the purple screen with the Ubuntu logo and the loading animation, I'm just shown a black screen. Nothing loads.

*

*I tried entering TTY7, but I couldn't

*I tried running failsafeX, but I got the "fatal error, screen not found" error.

*I tried this solution for the above error, but it didn't work

*I tried this, and this, but didn't work neither.

What else could it be?


text:
Q: Dropwizard thread count going 3k making application responses slow Facing issues related to thread after checking thread profiler in New Relic
98% sun.misc.Unsafe.park(boolean, long) :native
    89% java.util.concurrent.locks.LockSupport.parkNanos(java.lang.Object, long) :215
        88% java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.awaitNanos(long) :2078
            86% org.eclipse.jetty.util.BlockingArrayQueue.poll(long, java.util.concurrent.TimeUnit) :392
                 86% org.eclipse.jetty.util.thread.QueuedThreadPool.idleJobPoll() :563
                    86% org.eclipse.jetty.util.thread.QueuedThreadPool.access$800(org.eclipse.jetty.util.thread.QueuedThreadPool) :48
                        86% org.eclipse.jetty.util.thread.QueuedThreadPool$2.run() :626
                            86% java.lang.Thread.run() :745
Screenshot also attached.

The functionality is build using Dropwizard java framework for emmiting messages through websockets using Jedis(https://github.com/xetorthio/jedis/wiki/Getting-started). Emitting of messages is done asynchronously using runAsync().
Actually we have 2 stacks stack1 and stack2 both have same configurations. Where stack1 is performing very well in serving both web requests as well as this funcitonality at rpm around 20k but stack2 is taking too much time which is dedicately used for serving only this functionality at only 5k rpm. Stack2  thread count spike goes 2000 to 3000 while stack1 not showing such spike at the same time of analysis.
We are using AWS EC2 instances of type m4.large. Please help me if I may be doing something in wrong way.


text:
Q: design wavy background in react-native I am new to react native and starting to learn UI design.
I am trying to create wavy background (as in the bottom portion of first card or pink section of the third card) shown in the below image. I searched in multiple react native packages, but haven't found something that implements this.
My question is that

*

*if this type of background design is possible to implement by using some react native packages or the background image has to be designed like
this in some image editing application (like adobe photoshop)?

*if this is possible by some react native packages, then any library recommendation or working code will be helpful for me.
Thanks in advance.
Image Source: Google

A: You could use this package and draw your wavy background with SVG, or set uri of your SVG.
Following code is sample wavy background in React Native
import SvgUri from 'react-native-svg-uri';

export const WavyBackground = () => (
  <View>
    <SvgUri
      width="200"
      height="200"
      source={{uri:'custom wavy svg url here'}}
    />
  </View>
);


text:
Q: can somebody explain what " self.preorder_print(self.root, "")[:-1] " line is doing here inside the print_tree function? I understand slice notation. But need some help here.
Below code traverses and prints a binary tree. Can somebody explain what self.preorder_print(self.root, "")[:-1] line is doing here inside the print_tree function?
class Node(object):
    def __init__(self, value):
        self.value = value
        self.left = None
        self.right = None

class BinaryTree(object):
    def __init__(self, root):
        self.root = Node(root)

    def search(self, find_val):
        return self.preorder_search(self.root, find_val)

    def print_tree(self):
        return self.preorder_print(self.root, "")[:-1]

    def preorder_search(self, start, find_val):
        if start:
            if start.value == find_val:
                return True
            else:
                return self.preorder_search(start.left, find_val) or self.preorder_search(start.right, find_val)
        return False

    def preorder_print(self, start, traversal):
        if start:
            traversal += ("-" + str(start.value))
            traversal = self.preorder_print(start.left, traversal)
            traversal = self.preorder_print(start.right, traversal)
        return traversal

A: the [:-1] is a slice notation, it allow to take a subsection of those object that implement it, the use is as follow [start:end:step] start is the initial position you want to start taking elements, likewise end is where to stop, if negative it would count that many position from the end, useful if you don't know how long is the object, step allow to skip elements if different than one and/or take it in reverse if negative, each one can be omitted, in which case they take appropriates default values
for example
>>> "123"[:-1]
'12'
>>>

is to remove the last element, so in your case as preorder_print return a string, with the [:-1] it remove the last character
here you can find more about slice notation


text:
Q: Next.js Updating Json (or database) on Click Event Overview
I need to run server side code during a click event within the next.js framework.
I'm brand new to node, react, and next.js. I've always coded from scratch using PHP and JS. I want to be able to work with a team and build sites faster, so I thought it was a good idea to learn react. Next.js was the most appealing variation of react because it's seo friendly and great for single page webapps.
I'm stumped right now because nobody that I've seen online has talked about XHR post requests with triggers. They mainly talk about 'generating static pages' which is far from what I need to accomplish.
I've been researching this for days now to no avail so hopefully someone on here can help a noob out. I feel like this should be much more obvious. Please explain for someone with a heavy PHP background.
The Application
I'm making a simple task tracking application to teach myself next.js. To simulate a database, I'm fetching and saving to JSON files.
The first issue I ran into was with const fs = require('fs').promises;.
I could load json data using let tasks = require('./dtaTask.json'), but I could not update JSON files because 'fs' could not be used once the page was loaded.
I then learned about the getServerSideProps() method, allowing for 'fs' to be used by js.
I put my mgrTask code into the getServerSideProps() method which fixed the 'fs' issue.
I can send json data through the server, but I cannot send the object to update the json data later via a button press.
I know I could simply read the file using fetch, but I don't want to just read the file. I need to update it, and I need the object to be reusable for future query's.
Requirements
Page Load:

*

*An object (mgrTask) is loaded that allows for the querying and updating of the database (JSON for testing).

*All current tasks are fetched from the database using mgrTask and loaded into memory using an array.

Delete Trigger:

*

*Task is removed from the client's browser.

*mgrTask is either created again or called from page load.

*mgrTask removes the task from the array when given the taskID.

*mgrTask updates the database using the array in memory.

(firstpost.js) Page Code
import { Header } from '../../export/components/Header'
import { GenButton } from '../../export/components/genButton'
import { Task } from '../../export/components/tasks/Task'
import { useState } from 'react'
import { mgrTask } from '../../export/components/tasks/mgrTask'

export default function firstpost({ dtaTasks }) {
  const [tasks, setTasks] = useState(dtaTasks.getAll())

  // Delete Task
  function deleteTask(taskID) {
    console.log('delete ' + taskID)
    setTasks(tasks.filter((task) => task.taskID !== taskID ))
    dtaTasks.delete(taskID)
  }

  return (

        <Task tasks={tasks} deleteTask={deleteTask} />

      <GenButton className="centered" text='Home' href='/' />

  )
}

export async function getServerSideProps() {
  var dtaTasks = []
  dtaTasks = mgrTask

  return {
    props: {
      dtaTasks
    }
  }
}

(mgrTask.js) Database Table Manager Code
const fs = require('fs').promises;
let tasks = require('./dtaTask.json')

export const mgrTask = {
  getAll: () => tasks,
  getById: id => tasks.find(x => x.id.toString() === id.toString()),
  find: x => tasks.find(x),
  create,
  update,
  delete: _delete
};

function create(task) {
  // generate new user id
  task.id = tasks.length ? Math.max(...tasks.map(x => x.id)) + 1 : 1;

  // set date created and updated
  task.dateCreated = new Date().toISOString();
  task.dateUpdated = new Date().toISOString();

  // add and save task
  tasks.push(task);
  saveData();
}

function update(id, params) {
  const task = tasks.find(x => x.id.toString() === id.toString());

  // set date updated
  task.dateUpdated = new Date().toISOString();

  // update and save
  Object.assign(task, params);
  saveData();
}

// prefixed with underscore '_' because 'delete' is a reserved word in javascript
function _delete(taskID) {
  // filter out deleted task and save
  tasks = tasks.filter(x => x.taskID.toString() !== taskID.toString());
  saveData();
}

function saveData() {
  fs.writeFileSync('data/tasks.json', JSON.stringify(tasks, null, 4));
}

A: Next.js has post request api support.
Attach the post request to a function that the button calls. Include a api directory in the pages folder. Create a file for handling the post request that includes mgrTask. Send the needed data to mgrTask to handle the database update.
Function Btn Calls
  async function updateTasks(allTasks) {
    const response = await fetch('../api/tasks.js', {
      method:'POST',
      body: {allTasks},
      headers: {
        'Content-Type': 'application/json',
      },
    })
    const res = await response
    console.log(res)
  }

Post Handling API
import { mgrTask } from '../../export/components/tasks/mgrTask'

export default function handler(req, res) {
  if (req.method === 'POST') {
    mgrTask.saveData(req.body.allTasks)
    res.status(201).json({ updatePage: 'if you need data from the server' })
  }
}

https://nextjs.org/docs/api-routes/introduction


text:
Q: how to search specific epoch format timestamp in wireshark in Wireshark it provides a few options to display the time.
but I just want to see the epoch Unix timestamp, is anyone know how to display this? there are a few options for showing the absolute timestamp but not for epoch Unix timestamp.
also, if possible, how can use the display filter to display the data with a specific timestamp?
thanks,

A: Probably the easiest way to add a column for Epoch Time is to open a capture file, expand the Frame details in the Packet details pane, then right-click on the Epoch Time field and choose, "Apply as Column".  You can then drag & drop the column to your preferred location.
You can also add it through the "Edit -> Preferences -> Columns" dialog.  Click the + button to add a new column, rename the title to "Epoch Time", set the Type to "Custom" and the Fields to "frame.time_epoch" (no quotes).  Drag & drop the column to the order in the list you prefer.
how can use the display filter to display the data with a specific timestamp?
Whether you add a column to display it or not, you can always apply a display filter for the field.  For example, frame.time_epoch == 1603985924.375120000.  You can type it manually in the display filter text box or right-click on the field in the packet details pane and choose, "Apply [or Prepare] as Filter".  Preparing the filter allows you to construct more complicated filters by appending more filters until you've constructed the entire filter of interest.  This might be useful in this case when filtering packets that fall within a specific time range, e.g., (frame.time_epoch >= 1603985924.375120000) && (frame.time_epoch <= 1603985933.427006000).


text:
Q: Splitting a string into chunks of a certain size Suppose I had a string:
string str = "1111222233334444";

How can I break this string into chunks of some size?
e.g.,  breaking this into sizes of 4 would return strings:
"1111"
"2222"
"3333"
"4444"

A: It's not pretty and it's not fast, but it works, it's a one-liner and it's LINQy:
List<string> a = text.Select((c, i) => new { Char = c, Index = i }).GroupBy(o => o.Index / 4).Select(g => new String(g.Select(o => o.Char).ToArray())).ToList();

A: I recently had to write something that accomplishes this at work, so I thought I would post my solution to this problem. As an added bonus, the functionality of this solution provides a way to split the string in the opposite direction and it does correctly handle unicode characters as previously mentioned by Marvin Pinto above. So, here it is:
using System;
using Extensions;

namespace TestCSharp
{
    class Program
    {
        static void Main(string[] args)
        {
            string asciiStr = "This is a string.";
            string unicodeStr = "これは文字列です。";

            string[] array1 = asciiStr.Split(4);
            string[] array2 = asciiStr.Split(-4);

            string[] array3 = asciiStr.Split(7);
            string[] array4 = asciiStr.Split(-7);

            string[] array5 = unicodeStr.Split(5);
            string[] array6 = unicodeStr.Split(-5);
        }
    }
}

namespace Extensions
{
    public static class StringExtensions
    {
        /// Returns a string array that contains the substrings in this string that are seperated a given fixed length.
        /// <param name="s">This string object.</param>
        /// <param name="length">Size of each substring.
        ///     <para>CASE: length > 0 , RESULT: String is split from left to right.</para>
        ///     <para>CASE: length == 0 , RESULT: String is returned as the only entry in the array.</para>
        ///     <para>CASE: length < 0 , RESULT: String is split from right to left.</para>
        /// </param>
        /// <returns>String array that has been split into substrings of equal length.</returns>
        /// <example>
        ///
        ///         string s = "1234567890";
        ///         string[] a = s.Split(4); // a == { "1234", "5678", "90" }
        ///
        /// </example>
        public static string[] Split(this string s, int length)
        {
            System.Globalization.StringInfo str = new System.Globalization.StringInfo(s);

            int lengthAbs = Math.Abs(length);

            if (str == null || str.LengthInTextElements == 0 || lengthAbs == 0 || str.LengthInTextElements <= lengthAbs)
                return new string[] { str.ToString() };

            string[] array = new string[(str.LengthInTextElements % lengthAbs == 0 ? str.LengthInTextElements / lengthAbs: (str.LengthInTextElements / lengthAbs) + 1)];

            if (length > 0)
                for (int iStr = 0, iArray = 0; iStr < str.LengthInTextElements && iArray < array.Length; iStr += lengthAbs, iArray++)
                    array[iArray] = str.SubstringByTextElements(iStr, (str.LengthInTextElements - iStr < lengthAbs ? str.LengthInTextElements - iStr : lengthAbs));
            else // if (length < 0)
                for (int iStr = str.LengthInTextElements - 1, iArray = array.Length - 1; iStr >= 0 && iArray >= 0; iStr -= lengthAbs, iArray--)
                    array[iArray] = str.SubstringByTextElements((iStr - lengthAbs < 0 ? 0 : iStr - lengthAbs + 1), (iStr - lengthAbs < 0 ? iStr + 1 : lengthAbs));

            return array;
        }
    }
}

Also, here is an image link to the results of running this code: http://i.imgur.com/16Iih.png

A: Why not loops?  Here's something that would do it quite well:
        string str = "111122223333444455";
        int chunkSize = 4;
        int stringLength = str.Length;
        for (int i = 0; i < stringLength ; i += chunkSize)
        {
            if (i + chunkSize > stringLength) chunkSize = stringLength  - i;
            Console.WriteLine(str.Substring(i, chunkSize));

        }
        Console.ReadLine();

I don't know how you'd deal with case where the string is not factor of 4, but not saying you're idea is not possible, just wondering the motivation for it if a simple for loop does it very well?  Obviously the above could be cleaned and even put in as an extension method.
Or as mentioned in comments, you know it's /4 then
str = "1111222233334444";
for (int i = 0; i < stringLength; i += chunkSize)
  {Console.WriteLine(str.Substring(i, chunkSize));}

A: This should be much faster and more efficient than using LINQ or other approaches used here.
public static IEnumerable<string> Splice(this string s, int spliceLength)
{
    if (s == null)
        throw new ArgumentNullException("s");
    if (spliceLength < 1)
        throw new ArgumentOutOfRangeException("spliceLength");

    if (s.Length == 0)
        yield break;
    var start = 0;
    for (var end = spliceLength; end < s.Length; end += spliceLength)
    {
        yield return s.Substring(start, spliceLength);
        start = end;
    }
    yield return s.Substring(start);
}

A: You can use morelinq by Jon Skeet. Use Batch like:
string str = "1111222233334444";
int chunkSize = 4;
var chunks = str.Batch(chunkSize).Select(r => new String(r.ToArray()));

This will return 4 chunks for the string "1111222233334444". If the string length is less than or equal to the chunk size Batch will return the string as the only element of IEnumerable<string>
For output:
foreach (var chunk in chunks)
{
    Console.WriteLine(chunk);
}

and it will give:
1111
2222
3333
4444

A: Personally I prefer my solution :-)
It handles:

*

*String lengths that are a multiple of the chunk size.

*String lengths that are NOT a multiple of the chunk size.

*String lengths that are smaller than the chunk size.

*NULL and empty strings (throws an exception).

*Chunk sizes smaller than 1 (throws an exception).

It is implemented as a extension method, and it calculates the number of chunks is going to generate beforehand. It checks the last chunk because in case the text length is not a multiple it needs to be shorter. Clean, short, easy to understand... and works!
    public static string[] Split(this string value, int chunkSize)
    {
        if (string.IsNullOrEmpty(value)) throw new ArgumentException("The string cannot be null.");
        if (chunkSize < 1) throw new ArgumentException("The chunk size should be equal or greater than one.");

        int remainder;
        int divResult = Math.DivRem(value.Length, chunkSize, out remainder);

        int numberOfChunks = remainder > 0 ? divResult + 1 : divResult;
        var result = new string[numberOfChunks];

        int i = 0;
        while (i < numberOfChunks - 1)
        {
            result[i] = value.Substring(i * chunkSize, chunkSize);
            i++;
        }

        int lastChunkSize = remainder > 0 ? remainder : chunkSize;
        result[i] = value.Substring(i * chunkSize, lastChunkSize);

        return result;
    }

A: Simple and short:
// this means match a space or not a space (anything) up to 4 characters
var lines = Regex.Matches(str, @"[\s\S]{0,4}").Cast<Match>().Select(x => x.Value);

A: I know question is years old, but here is a Rx implementation. It handles the length % chunkSize != 0 problem out of the box:
   public static IEnumerable<string> Chunkify(this string input, int size)
        {
            if(size < 1)
                throw new ArgumentException("size must be greater than 0");

            return input.ToCharArray()
                .ToObservable()
                .Buffer(size)
                .Select(x => new string(x.ToArray()))
                .ToEnumerable();
        }

A: This is based on @dove solution but implemented as an extension method.
Benefits:

*

*Extension method

*Covers corner cases

*Splits string with any chars: numbers, letters, other symbols

Code
public static class EnumerableEx
{
    public static IEnumerable<string> SplitBy(this string str, int chunkLength)
    {
        if (String.IsNullOrEmpty(str)) throw new ArgumentException();
        if (chunkLength < 1) throw new ArgumentException();

        for (int i = 0; i < str.Length; i += chunkLength)
        {
            if (chunkLength + i > str.Length)
                chunkLength = str.Length - i;

            yield return str.Substring(i, chunkLength);
        }
    }
}

Usage
var result = "bobjoecat".SplitBy(3); // bob, joe, cat

Unit tests removed for brevity (see previous revision)

A: Using regular expressions and Linq:
List<string> groups = (from Match m in Regex.Matches(str, @"\d{4}")
                       select m.Value).ToList();

I find this to be more readable, but it's just a personal opinion. It can also be a one-liner : ).

A: public static IEnumerable<IEnumerable<T>> SplitEvery<T>(this IEnumerable<T> values, int n)
{
    var ls = values.Take(n);
    var rs = values.Skip(n);
    return ls.Any() ?
        Cons(ls, SplitEvery(rs, n)) :
        Enumerable.Empty<IEnumerable<T>>();
}

public static IEnumerable<T> Cons<T>(T x, IEnumerable<T> xs)
{
    yield return x;
    foreach (var xi in xs)
        yield return xi;
}

A: Best , Easiest and Generic Answer :).
    string originalString = "1111222233334444";
    List<string> test = new List<string>();
    int chunkSize = 4; // change 4 with the size of strings you want.
    for (int i = 0; i < originalString.Length; i = i + chunkSize)
    {
        if (originalString.Length - i >= chunkSize)
            test.Add(originalString.Substring(i, chunkSize));
        else
            test.Add(originalString.Substring(i,((originalString.Length - i))));
    }

A: static IEnumerable<string> Split(string str, int chunkSize)
{
   IEnumerable<string> retVal = Enumerable.Range(0, str.Length / chunkSize)
        .Select(i => str.Substring(i * chunkSize, chunkSize))

   if (str.Length % chunkSize > 0)
        retVal = retVal.Append(str.Substring(str.Length / chunkSize * chunkSize, str.Length % chunkSize));

   return retVal;
}

It correctly handles input string length not divisible by chunkSize.
Please note that additional code might be required to gracefully handle edge cases (null or empty input string, chunkSize == 0).

A: static IEnumerable<string> Split(string str, double chunkSize)
{
    return Enumerable.Range(0, (int) Math.Ceiling(str.Length/chunkSize))
       .Select(i => new string(str
           .Skip(i * (int)chunkSize)
           .Take((int)chunkSize)
           .ToArray()));
}

and another approach:
using System;
using System.Collections.Generic;
using System.Linq;

public class Program
{
    public static void Main()
    {

        var x = "Hello World";
        foreach(var i in x.ChunkString(2)) Console.WriteLine(i);
    }
}

public static class Ext{
    public static IEnumerable<string> ChunkString(this string val, int chunkSize){
        return val.Select((x,i) => new {Index = i, Value = x})
                  .GroupBy(x => x.Index/chunkSize, x => x.Value)
                  .Select(x => string.Join("",x));
    }
}

A: Six years later o_O
Just because
    public static IEnumerable<string> Split(this string str, int chunkSize, bool remainingInFront)
    {
        var count = (int) Math.Ceiling(str.Length/(double) chunkSize);
        Func<int, int> start = index => remainingInFront ? str.Length - (count - index)*chunkSize : index*chunkSize;
        Func<int, int> end = index => Math.Min(str.Length - Math.Max(start(index), 0), Math.Min(start(index) + chunkSize - Math.Max(start(index), 0), chunkSize));
        return Enumerable.Range(0, count).Select(i => str.Substring(Math.Max(start(i), 0),end(i)));
    }

or
    private static Func<bool, int, int, int, int, int> start = (remainingInFront, length, count, index, size) =>
        remainingInFront ? length - (count - index) * size : index * size;

    private static Func<bool, int, int, int, int, int, int> end = (remainingInFront, length, count, index, size, start) =>
        Math.Min(length - Math.Max(start, 0), Math.Min(start + size - Math.Max(start, 0), size));

    public static IEnumerable<string> Split(this string str, int chunkSize, bool remainingInFront)
    {
        var count = (int)Math.Ceiling(str.Length / (double)chunkSize);
        return Enumerable.Range(0, count).Select(i => str.Substring(
            Math.Max(start(remainingInFront, str.Length, count, i, chunkSize), 0),
            end(remainingInFront, str.Length, count, i, chunkSize, start(remainingInFront, str.Length, count, i, chunkSize))
        ));
    }

AFAIK all edge cases are handled.
Console.WriteLine(string.Join(" ", "abc".Split(2, false))); // ab c
Console.WriteLine(string.Join(" ", "abc".Split(2, true))); // a bc
Console.WriteLine(string.Join(" ", "a".Split(2, true))); // a
Console.WriteLine(string.Join(" ", "a".Split(2, false))); // a

A: List<string> SplitString(int chunk, string input)
{
    List<string> list = new List<string>();
    int cycles = input.Length / chunk;

    if (input.Length % chunk != 0)
        cycles++;

    for (int i = 0; i < cycles; i++)
    {
        try
        {
            list.Add(input.Substring(i * chunk, chunk));
        }
        catch
        {
            list.Add(input.Substring(i * chunk));
        }
    }
    return list;
}

A: I took this to another level.  Chucking is an easy one liner, but in my case I needed whole words as well.  Figured I would post it, just in case someone else needs something similar.
static IEnumerable<string> Split(string orgString, int chunkSize, bool wholeWords = true)
{
    if (wholeWords)
    {
        List<string> result = new List<string>();
        StringBuilder sb = new StringBuilder();

        if (orgString.Length > chunkSize)
        {
            string[] newSplit = orgString.Split(' ');
            foreach (string str in newSplit)
            {
                if (sb.Length != 0)
                    sb.Append(" ");

                if (sb.Length + str.Length > chunkSize)
                {
                    result.Add(sb.ToString());
                    sb.Clear();
                }

                sb.Append(str);
            }

            result.Add(sb.ToString());
        }
        else
            result.Add(orgString);

        return result;
    }
    else
        return new List<string>(Regex.Split(orgString, @"(?<=\G.{" + chunkSize + "})", RegexOptions.Singleline));
}

Results based on below comment:
string msg = "336699AABBCCDDEEFF";
foreach (string newMsg in Split(msg, 2, false))
{
    Console.WriteLine($">>{newMsg}<<");
}

Console.ReadKey();

Results:
>>33<<
>>66<<
>>99<<
>>AA<<
>>BB<<
>>CC<<
>>DD<<
>>EE<<
>>FF<<
>><<

Another way to pull it:
List<string> splitData = (List<string>)Split(msg, 2, false);

for (int i = 0; i < splitData.Count - 1; i++)
{
    Console.WriteLine($">>{splitData[i]}<<");
}

Console.ReadKey();

New Results:
>>33<<
>>66<<
>>99<<
>>AA<<
>>BB<<
>>CC<<
>>DD<<
>>EE<<
>>FF<<

A: static IEnumerable<string> Split(string str, int chunkSize)
{
    return Enumerable.Range(0, str.Length / chunkSize)
        .Select(i => str.Substring(i * chunkSize, chunkSize));
}

Please note that additional code might be required to gracefully handle edge cases (null or empty input string, chunkSize == 0, input string length not divisible by chunkSize, etc.). The original question doesn't specify any requirements for these edge cases and in real life the requirements might vary so they are out of scope of this answer.

A: How's this for a one-liner?
List<string> result = new List<string>(Regex.Split(target, @"(?<=\G.{4})", RegexOptions.Singleline));

With this regex it doesn't matter if the last chunk is less than four characters, because it only ever looks at the characters behind it.
I'm sure this isn't the most efficient solution, but I just had to toss it out there.

A: Starting with .NET 6, we can also use the Chunk method:
var result = str
    .Chunk(4)
    .Select(x => new string(x))
    .ToList();

A: Changed slightly to return parts whose size  not equal to chunkSize
public static IEnumerable<string> Split(this string str, int chunkSize)
    {
        var splits = new List<string>();
        if (str.Length < chunkSize) { chunkSize = str.Length; }
        splits.AddRange(Enumerable.Range(0, str.Length / chunkSize).Select(i => str.Substring(i * chunkSize, chunkSize)));
        splits.Add(str.Length % chunkSize > 0 ? str.Substring((str.Length / chunkSize) * chunkSize, str.Length - ((str.Length / chunkSize) * chunkSize)) : string.Empty);
        return (IEnumerable<string>)splits;
    }

A: An important tip if the string that is being chunked needs to support all Unicode characters.
If the string is to support international characters like , then split up the string using the System.Globalization.StringInfo class. Using StringInfo, you can split up the string based on number of text elements.
string internationalString = '';

The above string has a Length of 2, because the String.Length property returns the number of Char objects in this instance, not the number of Unicode characters.

A: I think this is an straight forward answer:
public static IEnumerable<string> Split(this string str, int chunkSize)
    {
        if(string.IsNullOrEmpty(str) || chunkSize<1)
            throw new ArgumentException("String can not be null or empty and chunk size should be greater than zero.");
        var chunkCount = str.Length / chunkSize + (str.Length % chunkSize != 0 ? 1 : 0);
        for (var i = 0; i < chunkCount; i++)
        {
            var startIndex = i * chunkSize;
            if (startIndex + chunkSize >= str.Length)
                yield return str.Substring(startIndex);
            else
                yield return str.Substring(startIndex, chunkSize);
        }
    }

And it covers edge cases.

A: static List<string> GetChunks(string value, int chunkLength)
{
    var res = new List<string>();
    int count = (value.Length / chunkLength) + (value.Length % chunkLength > 0 ? 1 : 0);
    Enumerable.Range(0, count).ToList().ForEach(f => res.Add(value.Skip(f * chunkLength).Take(chunkLength).Select(z => z.ToString()).Aggregate((a,b) => a+b)));
    return res;
}

demo

A: Here's my 2 cents:
  IEnumerable<string> Split(string str, int chunkSize)
  {
     while (!string.IsNullOrWhiteSpace(str))
     {
        var chunk = str.Take(chunkSize).ToArray();
        str = str.Substring(chunk.Length);
        yield return new string(chunk);

     }

  }//Split

A: In a combination of dove+Konstatin's answers...
static IEnumerable<string> WholeChunks(string str, int chunkSize) {
    for (int i = 0; i < str.Length; i += chunkSize)
        yield return str.Substring(i, chunkSize);
}

This will work for all strings that can be split into a whole number of chunks, and will throw an exception otherwise.
If you want to support strings of any length you could use the following code:
static IEnumerable<string> ChunksUpto(string str, int maxChunkSize) {
    for (int i = 0; i < str.Length; i += maxChunkSize)
        yield return str.Substring(i, Math.Min(maxChunkSize, str.Length-i));
}

However, the the OP explicitly stated he does not need this; it's somewhat longer and harder to read, slightly slower.  In the spirit of KISS and YAGNI, I'd go with the first option: it's probably the most efficient implementation possible, and it's very short, readable, and, importantly, throws an exception for nonconforming input.

A: I've slightly build up on João's solution.
What I've done differently is in my method you can actually specify whether you want to return the array with remaining characters or whether you want to truncate them if the end characters do not match your required chunk length, I think it's pretty flexible and the code is fairly straight forward:
using System;
using System.Linq;
using System.Text.RegularExpressions;

namespace SplitFunction
{
    class Program
    {
        static void Main(string[] args)
        {
            string text = "hello, how are you doing today?";
            string[] chunks = SplitIntoChunks(text, 3,false);
            if (chunks != null)
            {
                chunks.ToList().ForEach(e => Console.WriteLine(e));
            }

            Console.ReadKey();
        }

        private static string[] SplitIntoChunks(string text, int chunkSize, bool truncateRemaining)
        {
            string chunk = chunkSize.ToString();
            string pattern = truncateRemaining ? ".{" + chunk + "}" : ".{1," + chunk + "}";

            string[] chunks = null;
            if (chunkSize > 0 && !String.IsNullOrEmpty(text))
                chunks = (from Match m in Regex.Matches(text,pattern)select m.Value).ToArray();

            return chunks;
        }
    }
}

A:     public static List<string> SplitByMaxLength(this string str)
    {
        List<string> splitString = new List<string>();

        for (int index = 0; index < str.Length; index += MaxLength)
        {
            splitString.Add(str.Substring(index, Math.Min(MaxLength, str.Length - index)));
        }

        return splitString;
    }

A: I can't remember who gave me this, but it works great.  I speed tested a number of ways to break Enumerable types into groups.  The usage would just be like this...
List<string> Divided = Source3.Chunk(24).Select(Piece => string.Concat<char>(Piece)).ToList();

The extention code would look like this...
#region Chunk Logic
private class ChunkedEnumerable<T> : IEnumerable<T>
{
    class ChildEnumerator : IEnumerator<T>
    {
        ChunkedEnumerable<T> parent;
        int position;
        bool done = false;
        T current;

        public ChildEnumerator(ChunkedEnumerable<T> parent)
        {
            this.parent = parent;
            position = -1;
            parent.wrapper.AddRef();
        }

        public T Current
        {
            get
            {
                if (position == -1 || done)
                {
                    throw new InvalidOperationException();
                }
                return current;

            }
        }

        public void Dispose()
        {
            if (!done)
            {
                done = true;
                parent.wrapper.RemoveRef();
            }
        }

        object System.Collections.IEnumerator.Current
        {
            get { return Current; }
        }

        public bool MoveNext()
        {
            position++;

            if (position + 1 > parent.chunkSize)
            {
                done = true;
            }

            if (!done)
            {
                done = !parent.wrapper.Get(position + parent.start, out current);
            }

            return !done;

        }

        public void Reset()
        {
            // per http://msdn.microsoft.com/en-us/library/system.collections.ienumerator.reset.aspx
            throw new NotSupportedException();
        }
    }

    EnumeratorWrapper<T> wrapper;
    int chunkSize;
    int start;

    public ChunkedEnumerable(EnumeratorWrapper<T> wrapper, int chunkSize, int start)
    {
        this.wrapper = wrapper;
        this.chunkSize = chunkSize;
        this.start = start;
    }

    public IEnumerator<T> GetEnumerator()
    {
        return new ChildEnumerator(this);
    }

    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }

}
private class EnumeratorWrapper<T>
{
    public EnumeratorWrapper(IEnumerable<T> source)
    {
        SourceEumerable = source;
    }
    IEnumerable<T> SourceEumerable { get; set; }

    Enumeration currentEnumeration;

    class Enumeration
    {
        public IEnumerator<T> Source { get; set; }
        public int Position { get; set; }
        public bool AtEnd { get; set; }
    }

    public bool Get(int pos, out T item)
    {

        if (currentEnumeration != null && currentEnumeration.Position > pos)
        {
            currentEnumeration.Source.Dispose();
            currentEnumeration = null;
        }

        if (currentEnumeration == null)
        {
            currentEnumeration = new Enumeration { Position = -1, Source = SourceEumerable.GetEnumerator(), AtEnd = false };
        }

        item = default(T);
        if (currentEnumeration.AtEnd)
        {
            return false;
        }

        while (currentEnumeration.Position < pos)
        {
            currentEnumeration.AtEnd = !currentEnumeration.Source.MoveNext();
            currentEnumeration.Position++;

            if (currentEnumeration.AtEnd)
            {
                return false;
            }

        }

        item = currentEnumeration.Source.Current;

        return true;
    }

    int refs = 0;

    // needed for dispose semantics
    public void AddRef()
    {
        refs++;
    }

    public void RemoveRef()
    {
        refs--;
        if (refs == 0 && currentEnumeration != null)
        {
            var copy = currentEnumeration;
            currentEnumeration = null;
            copy.Source.Dispose();
        }
    }
}
/// Speed Checked.  Works Great!
public static IEnumerable<IEnumerable<T>> Chunk<T>(this IEnumerable<T> source, int chunksize)
{
    if (chunksize < 1) throw new InvalidOperationException();

    var wrapper = new EnumeratorWrapper<T>(source);

    int currentPos = 0;
    T ignore;
    try
    {
        wrapper.AddRef();
        while (wrapper.Get(currentPos, out ignore))
        {
            yield return new ChunkedEnumerable<T>(wrapper, chunksize, currentPos);
            currentPos += chunksize;
        }
    }
    finally
    {
        wrapper.RemoveRef();
    }
}
#endregion

A: class StringHelper
{
    static void Main(string[] args)
    {
        string str = "Hi my name is vikas bansal and my email id is bansal.vks@gmail.com";
        int offSet = 10;

        List<string> chunks = chunkMyStr(str, offSet);

        Console.Read();
    }

    static List<string> chunkMyStr(string str, int offSet)
    {

        List<string> resultChunks = new List<string>();

        for (int i = 0; i < str.Length; i += offSet)
        {
            string temp = str.Substring(i, (str.Length - i) > offSet ? offSet : (str.Length - i));
            Console.WriteLine(temp);
            resultChunks.Add(temp);

        }

        return resultChunks;
    }
}

A: Modified (now it accepts any non null string and any positive chunkSize) Konstantin Spirin's solution:
public static IEnumerable<String> Split(String value, int chunkSize) {
  if (null == value)
    throw new ArgumentNullException("value");
  else if (chunkSize <= 0)
    throw new ArgumentOutOfRangeException("chunkSize", "Chunk size should be positive");

  return Enumerable
    .Range(0, value.Length / chunkSize + ((value.Length % chunkSize) == 0 ? 0 : 1))
    .Select(index => (index + 1) * chunkSize < value.Length
      ? value.Substring(index * chunkSize, chunkSize)
      : value.Substring(index * chunkSize));
}

Tests:
  String source = @"ABCDEF";

  // "ABCD,EF"
  String test1 = String.Join(",", Split(source, 4));
  // "AB,CD,EF"
  String test2 = String.Join(",", Split(source, 2));
  // "ABCDEF"
  String test3 = String.Join(",", Split(source, 123));

A: Based around other posters answers, along with some samples of useage:
public static string FormatSortCode(string sortCode)
{
    return ChunkString(sortCode, 2, "-");
}
public static string FormatIBAN(string iban)
{
    return ChunkString(iban, 4, "  ");
}

private static string ChunkString(string str, int chunkSize, string separator)
{
    var b = new StringBuilder();
    var stringLength = str.Length;
    for (var i = 0; i < stringLength; i += chunkSize)
    {
        if (i + chunkSize > stringLength) chunkSize = stringLength - i;
        b.Append(str.Substring(i, chunkSize));
        if (i+chunkSize != stringLength)
            b.Append(separator);
    }
    return b.ToString();
}

A: Using the Buffer extensions from the IX library
    static IEnumerable<string> Split( this string str, int chunkSize )
    {
        return str.Buffer(chunkSize).Select(l => String.Concat(l));
    }

A: This can be done in this way too
        string actualString = "1111222233334444";
        var listResult = new List<string>();
        int groupingLength = actualString.Length % 4;
        if (groupingLength > 0)
            listResult.Add(actualString.Substring(0, groupingLength));
        for (int i = groupingLength; i < actualString.Length; i += 4)
        {
            listResult.Add(actualString.Substring(i, 4));
        }

        foreach(var res in listResult)
        {
            Console.WriteLine(res);
        }
        Console.Read();

A: If necessary to split by few different length:
For example you have date and time in specify format stringstrangeStr = "07092016090532"; 07092016090532 (Date:07.09.2016 Time: 09:05:32)
public static IEnumerable<string> SplitBy(this string str, int[] chunkLength)
    {
        if (String.IsNullOrEmpty(str)) throw new ArgumentException();
        int i = 0;
        for (int j = 0; j < chunkLength.Length; j++)
        {
            if (chunkLength[j] < 1) throw new ArgumentException();
            if (chunkLength[j] + i > str.Length)
            {
                chunkLength[j] = str.Length - i;
            }
            yield return str.Substring(i, chunkLength[j]);
            i += chunkLength[j];
        }
    }

using:
string[] dt = strangeStr.SplitBy(new int[] { 2, 2, 4, 2, 2, 2, 2 }).ToArray();

A:         List<string> chunks = new List<string>();
        var longString = new string('s', 3000);
        var chunkLength = 1273;
        var ratio = (double)longString.Length / chunkLength;
        var countOfChunks = Convert.ToByte(Math.Round(ratio, MidpointRounding.ToPositiveInfinity));

        for (byte i = 0; i < countOfChunks; i++)
        {
            var remainingLength = longString.Length - chunkLength * i;
            if (chunkLength > remainingLength)
                chunks.Add(longString.Substring(i * chunkLength, remainingLength));
            else
                chunks.Add(longString.Substring(i * chunkLength, chunkLength));
        }

A:         public static List<string> DevideByStringLength(string text, int chunkSize)
    {
        double a = (double)text.Length / chunkSize;
        var numberOfChunks = Math.Ceiling(a);

        Console.WriteLine($"{text.Length} | {numberOfChunks}");

        List<string> chunkList = new List<string>();
        for (int i = 0; i < numberOfChunks; i++)
        {
            string subString = string.Empty;
            if (i == (numberOfChunks - 1))
            {
                subString = text.Substring(chunkSize * i, text.Length - chunkSize * i);
                chunkList.Add(subString);
                continue;
            }
            subString = text.Substring(chunkSize * i, chunkSize);
            chunkList.Add(subString);
        }
        return chunkList;
    }

A: Try this:
    public static string[] Split(string str, int chunkSize)
    {
        return Enumerable.Range(0, str.Length / chunkSize)
            .Select(i => str.Substring(i * chunkSize, chunkSize)).ToArray();
    }

A: for (int i = 0; i <= Convert.ToInt32(Math.Truncate(Convert.ToDecimal(_string.Length / _chunkSize))); i++)
{
    var _currentChunk = _string.Substring(i * _chunkSize, Math.Min(_chunkSize, _string.Length - i * _chunkSize));
    //do something with current chunk
}


text:
Q: Need help splitting a string into two separate integers for processing I am working on some data structures in java and I am a little stuck on how to split this string into two integers. Basically the user will enter a string like '1200:10'. I used indexOf to check if there is a : present, but now I need to take the number before the colon and set it to val and set the other number to rad.  I think I should be using the substring or parseInt methods, but am unsure. The code below can also be viewed at http://pastebin.com/pJH76QBb
import java.util.Scanner;  // Needed for accepting input

 public class ProjectOneAndreD
 {
    public static void main(String[] args)
    {
        String input1;
        char coln = ':';
        int val=0, rad=0, answer=0, check1=0;

        Scanner keyboard = new Scanner(System.in);  //creates new scanner class
        do
        {
            System.out.println("****************************************************");
            System.out.println("             This is Project 1. Enjoy!              ");     //title
            System.out.println("****************************************************\n\n");

            System.out.println("Enter a number, : and then the radix, followed by the Enter key.");
            System.out.println("INPUT EXAMPLE:  160:2   {ENTER} ");     //example

            System.out.print("INPUT:  ");               //prompts user input.
            input1 = keyboard.nextLine();       //assigns input to string input1

            check1=input1.indexOf(coln);

            if(check1==-1)
            {
                System.out.println("I think you forgot the ':'.");

            }
            else
            {
                System.out.println("found ':'");

            }
        }while(check1==-1);
    }
 }

A: Substring would work, but I would recommend looking into String.split.
The split command will make an array of Strings, which you can then use parseInt to get the integer value of.
String.split takes a regex string, so you may not want to just throw in any string in it.
Try something like this:
"Your|String".split("\\|");, where | is the character that splits the two portions of the string.
The two backslashes will tell Java you want that exact character, not the regex interpretation of |. This only really matters for some characters, but it's safer.
Source: http://www.rgagnon.com/javadetails/java-0438.html
Hopefully this gets you started.

A: You knew where : is occurs using indexOf. Let's say string length is n and the : occurred at index i. Then ask for substring(int beginIndex, int endIndex) from 0 to i-1 and i+1 to n-1. Even simpler is to use String::split

A: make this
    if(check1==-1)
    {
        System.out.println("I think you forgot the ':'.");

    }
    else
    {
     String numbers [] = input1.split(":"); //if the user enter 1123:2342 this method

     //will
     // return array of String which contains two elements numbers[0] = "1123" and numbers[1]="2342"
    System.out.print("first number = "+ numbers[0]);
    System.out.print("Second number = "+ numbers[1]);
    }


text:
Q: Ubuntu 18.04 (GUI) cannot create a directory - nothing comes up on right click I just made the step from "4flags" to Ubuntu on my desktop. Managed to install OS ( Ubuntu 18.04), have my WiFi running, installed Flash on Firefox (CLI ), I can NOT create ANY directory via GUI in any of my HOME directories. I could create a file ( to PDF ) that sits alone in my Documents directory, but when clicking my right mouse (in Documents dir) to create a new one... nothing happens.
It doesn't matter if I click right or left button, once or twice, there is no response. I do NOT get the options to create anything. I have the OS only the second day, not going to do it through CLI yet, there must be some simple reason for it, like having (NOT) the rights on my PC to write or create folders. Where can I check this? What could it be? Thanks.


text:
Q: Multiplication of matricees This is an example in Serge Lang "Introduction to Linear Algebra", page 48. I try to multiply these two $2$x$3$ and $3$x$2$ matrices but fail to obtain the result as mentioned in the text.
I have:
$
\left( \begin{array}{cc}
2 & 1 & 5\\
1 & 3 & 2
\end{array} \right)
%
\left( \begin{array}{c}
3 & 4 \\
-1 & 2 \\
2 & 1
\end{array} \right)
=\left( \begin{array}{c}
15 & 30 \\
4 & 2
\end{array} \right)
$
Serge's result is, however:
$
\left( \begin{array}{cc}
2 & 1 & 5\\
1 & 3 & 2
\end{array} \right)
%
\left( \begin{array}{c}
3 & 4 \\
-1 & 2 \\
2 & 1
\end{array} \right)
=\left( \begin{array}{c}
15 & 15 \\
4 & 2
\end{array} \right)
$
Where did I do wrong?

A: Hint:
$$\left(\begin{array}{}\color{blue }2&\color{red }1&\color{green }5\end{array} \right)  \cdot \left(\begin{array}{}\color{blue }4\\ \color{red }2 \\ \color{green }1\end{array} \right)=\color{blue }{2\cdot 4}+\color{red }{1\cdot 2}+\color{green }{5\cdot 1}=\color{blue }8+\color{red }2+\color{green }5=15$$

A: We have
$$\left( \begin{array}{cc}
\color{red}{2} & \color{red}{1} & \color{red}{5}\\
1 & 3 & 2
\end{array} \right)
%
\left( \begin{array}{c}
3 & \color{red}{4} \\
-1 & \color{red}{2} \\
2 & \color{red}{1}
\end{array} \right)
=\left( \begin{array}{c}
15 & \color{red}{15} \\
4 & 12
\end{array} \right)$$
that is $2\cdot 4+1\cdot 2+5\cdot 1=8+2+5=15$.

A: My answer is a different. Notice the entry $a_{22}$ in the result.


text:
Q: Two-way communication between parent directive and child directive in AngularJS I need to pass in a value from the parent directive to the child directive, update it, then pass it back. When I pass in the parent function, and create a two-way binding, I get the error:

scope.updateItem is not a function

How can I accomplish this?
Parent directive template:

   <custom-phrases item-to-update="item" update-item="updateItem"></custom-phrases>

Parent Directive JavaScript:
angular
  .module('app')
  .directive('itemlist',
    function($rootScope, $state) {
      return {
        restrict: 'EA',
        templateUrl: 'directives/cms/itemlist/itemlist.tpl.html',
        scope: {
        },
        link: function(scope, element) {
          // This will be called from child directive with updated item
          scope.updateItem = function(item) {
            console.log('Updating item from itemlist', item);
          };
        },
      };
    });

Child Directive JavaScript:
angular
  .module('app')
  .directive('customPhrases',
    function($rootScope) {
      return {
        restrict: 'AE',
        scope: {
          itemToUpdate: '=',
          updateItem: '=',
        },
        templateUrl: 'directives/cms/customPhrases/custom_phrases_directive.tpl.html',
        link: function(scope, element) {

          // do stuff to scope.itemToUpdate...
          // then pass it back to parent directive
          scope.updateItem(scope.itemToUpdate);
          ...

Note: I've also tried & to bind a function:

   <custom-phrases item-to-update="item" update-item="updateItem(item)"></custom-phrases>

Then in child directive, changed this to:
scope: {
  itemToUpdate: '=',
  updateItem: '&',
},

If I console log scope.updateItem I get

TypeError: scope.updateItem is not a function

A: index.html
<!DOCTYPE html>

    <meta charset="utf-8" />
    <title>Nested Directives</title>

    <link rel="stylesheet" href="./../../../lib/bootstrap/css/bootstrap.min.css">

            <my-tabs>

      <my-pane title="Home">

Home Page

This is a simple hero unit, a simple jumbotron-style component for calling extra attention to featured content or information.

Learn more

      </my-pane>

      <my-pane title="Login">

        <form class="form-horizontal">

            Email

              <input type="email" class="form-control" id="inputEmail3" placeholder="Email">

            Password

              <input type="password" class="form-control" id="inputPassword3" placeholder="Password">

              <button type="submit" class="btn btn-default">Sign in</button>

        </form>

      </my-pane>

    </my-tabs>

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

app.directive('myTabs', function() {
  return {
    restrict: 'E',
    transclude: true,
    scope: {},
    controller: function MyTabsController($scope) {
      var panes = $scope.panes = [];

      $scope.select = function(pane) {
        angular.forEach(panes, function(pane) {
          pane.selected = false;
        });
        pane.selected = true;
      };

      this.addPane = function(pane) {
        if (panes.length === 0) {
          $scope.select(pane);
        }
        panes.push(pane);
      };
    },
    templateUrl: 'my-tabs.html'
  };
})
.directive('myPane', function() {
  return {
      // ^^ prefix means that this directive searches for the controller on its parents
    require: '^^myTabs',
    restrict: 'E',
    transclude: true,
    scope: {
      title: '@'
    },
    link: function(scope, element, attrs, tabsCtrl) {
      tabsCtrl.addPane(scope);
    },
    templateUrl: 'my-pane.html'
  };
});

my-pane.html

{{title}}

my-tabs.html

      {{pane.title}}


text:
Q: lando gets its mysql database docker service killed with no error I have a lando service for my WordPress development. It's mainly a LAMP that uses a mariaDB container for the database.
After starting the lando app, and at random intervals 5 minutes, an hour, the docker mariaDB container gets killed and I can't find any error on the docker container log.
If I run docker logs with the database container id I get:
2021-03-30T09:43:33.099754Z 0 [Note] Event Scheduler: Loaded 0 events
2021-03-30T09:43:33.101884Z 0 [Note] /opt/bitnami/mysql/bin/mysqld: ready for connections.
Version: '5.7.29'  socket: '/opt/bitnami/mysql/tmp/mysql.sock'  port: 3306  MySQL Community Server (GPL)
/launch.sh: line 11:    38 Killed                  /opt/bitnami/scripts/mysql/entrypoint.sh /opt/bitnami/scripts/mysql/run.sh

I don't know how to troubleshoot that further. I was not doing anything out of the ordinary at the moment. Not big queries nor big loads in any way. If I do lando stop && lando start the database works again but it eventually fails again.
One curious thing I noted is that if I do lando info before and after the database crushing I get this:
Before:
  { service: 'database',
    urls: [],
    type: 'mysql',
    healthy: true,
    internal_connection: { host: 'database', port: '3306' },
    external_connection: { host: '127.0.0.1', port: '51771' },
    healthcheck: 'bash -c "[ -f /bitnami/mysql/.mysql_initialized ]"',
    creds: { database: 'wordpress', password: 'wordpress', user: 'wordpress' },

After:
{ service: 'database',
    urls: [],
    type: 'mysql',
    healthy: true,
    internal_connection: { host: 'database', port: '3306' },
    external_connection: { host: '127.0.0.1', port: true },
    healthcheck: 'bash -c "[ -f /bitnami/mysql/.mysql_initialized ]"',
    creds: { database: 'wordpress', password: 'wordpress', user: 'wordpress' },

Note the port changes from a random port (51771) expected, to "true"
Is there any other log I can check?
What is causing my database to get killed?
Thanks


text:
Q: Application working on emulator but crashed on phone WP8 At start I'm sorry for my English is poor. And this is the only place where i solved the problem.
I have a problem with my application. I write and test it on emulator in VisualStudnio 2012 and It work fine. But when I add aplication in WindowsPhone store and I get to phone. It crashed. I think that problem is in geolocator or something with GPS, because when i use function where my it don't use gps it work. Everywhere where i use geolocator_geopositionchanged it break down and app is terminate. in one of application page i use map control but i gave token and application id but only in class where i use map.
       private void maping_Loaded(object sender, RoutedEventArgs e)
   {
     Microsoft.Phone.Maps.MapsSettings.ApplicationContext.ApplicationId = "id";
     Microsoft.Phone.Maps.MapsSettings.ApplicationContext.AuthenticationToken = "token";
   }

Do you have any sugestion or advices?
if you want watching app  there is a link
http://www.windowsphone.com/pl-PL/store/app/opencaching/06bce1e1-16ef-4ebf-ac53-23b4c725f78b
I have geolocator in a few class it's one of them
Geolocator code
 if (!tracking)
  {
    gps = new Geolocator();
    gps.DesiredAccuracy = PositionAccuracy.High;
    gps.ReportInterval = 100;
    gps.PositionChanged += geolocator_PositionChanged;
  }
  else
  {
    gps.PositionChanged -= geolocator_PositionChanged;
    gps = null;
  }
  tracking = !tracking;

Geoposition changed code
 void geolocator_PositionChanged(Geolocator sender, PositionChangedEventArgs args)
{
        double distance = 0;
        distance = point.GetDistanceTo(new GeoCoordinate(args.Position.Coordinate.Latitude, args.Position.Coordinate.Longitude));

        string asa = Convert.ToInt64(distance).ToString();
        if (asa != null)
        {
          Dispatcher.BeginInvoke(() =>
          {

            TBodleglosc.Text = asa +"m";
            navi.Rotation = 180 + Kierunek(point.Latitude, point.Longitude, args.Position.Coordinate.Latitude, args.Position.Coordinate.Longitude);

          });

        }

}

A: Debug on your device. If that cannot repro, setup a Beta Test app and use that to distribute the app back to yourself for debugging. Sometimes signing breaks things.

A: I debug at lumia 920 and I have a  problem with convert.toDouble
because there are was , i have . and vice versa
I think that it's connected with phone language
 because in english emulator and Ertay Shashko phone who debug it yesterday it's working fine.
At now application work at phone but doesn't at emulator.
but if i change settings on location and language  apps work but I can't debug because visual studio have error
It's weird .....


text:
Q: What did Gandalf actually try as passwords for Moria's gates? In The Fellowship of the Ring, when the party was at the gates of Moria, Gandalf  tries to open the doors by speaking bespoke paswords. The password is actually "Mellon " but he tries various other phrases first.
What was the first password he tried?
It's possible that this is only in the movie version, as it's been quite a while since i read the book.

A: Elvish gate open now for us; doorway of the Dwarf-folk listen to the word of my tongue.
In the book, Gandalf says "Annon edhellen, edro hi ammen! Fennas nogothrim, lasto beth lammen!",

He stepped up to the rock again, and lightly touched with his staff the silver star in the middle beneath the sign of the anvil.
Annon edhellen, edro hi ammen!
Fennas nogothrim, lasto beth lammen!
he said in a commanding voice. The silver lines faded, but the blank grey stone did not stir.
The Lord of the Rings - Book II Chapter 4 - "A Journey in the Dark"

This is not translated within the book itself, but in Tolkien's unfinished linguistic companion volume to The Lord of the Rings, Tolkien glosses it as "Elvish gate open now for us; doorway of the Dwarf-folk listen to the word of my tongue", and breaks it down word-for-word.

S annon edhellen edro hi ammen!
fennas nogothrim lasto beth lammen
An (impromptu) verse invocation by Gandalf.
"Elvish gate open now for us; doorway of the Dwarf-folk listen to the word of my tongue."
S annon "gate"
S edhellen, adj. ' elvish' from edhel 'Elf. [S edhel is probably related to, or connected with, Q Elda, the specific name of the Western branch of the Quendi; but it was used in S. as a general name for all Elves (since the name Quendi had gone out of use in Sindarin).]
S edro, imperative of Sindarin verb edra- "open (out)."
S hi 'now'.
S ammen "for us"
S fennas "doorway." Cf. fen, door (in Fen Hollen, vol. Ill, 99).
S nogothrim: of the Dwarf-people.
S nogoth, pl. "dwarves", pl. of nogon, a dwarf; nogoth-rim 'dwarf-folk'.
Rare, possibly nonce-formation of Gandalf's. The usual generic plural or race-name was Naugrim.
S lasto, imperative of S lasta-, listen. [Q lasta-, √LAS-.]
S beth, mutated (as object immediately after verb) for peth, word = Q quetta [√QUET- 'say'].
S lammen "(of) my tongue." S lam 'tongue' = Q lambe.
S -en, possessive suffix of 1st person sg. (cf. Q lambenya 'my tongue').
"Words, Phrases and Passages in Various Tongues in The Lord of the Rings", Parma Eldalamberon #17

Elsewhere, Tolkien has also glossed the two words "fennas nogothrim" as "gateway (of) dwarf-folk".

I have often had questions about the grammatical features appearing in the Sindarin fragments. There is no time for answering these. But I might mention the ending -ath. ... is not a genitive inflexion as some have guessed. In S. the simple genitive was usually expressed by placing the genitival noun in adjectival position (in S. after the primary noun). So Vol. I, p. 319, Ennyn Durin Aran Moria, "doors (of) Durin King (of) Moria"; Vol. Ill, p. 41, Ernil i Pheriannath, "Prince (of) the Halflings"; Vol. I, p. 320, Fennas nogothrim, "gateway (of) dwarf-folk."
The Road Goes Ever On

A: The Film
According to the Fellowship of the Ring script at Council of Elrond, in the film Gandalf first tries:

Annon Edhellen, edro hi ammen! (Gate of the Elves, open now for me!)

Then:

Fennas Nogothrim, lasto beth lammen. (Doorway of the Dwarf-folk, listen to the word of my tongue.)

Followed by:

Ando Eldarinwa…a lasta quettanya, Fenda Casarinwa… (Gate of Elves…listen to my word, Threshold of Dwarves…)

The Book
In the book, Gandalf first tries:

Annon edhellen, edro hi ammen!
Fennas nogothrim, lasto beth lammen!

Later attempts:

Many times he repeated these words in different order, or varied them. Then he tried other
  spells, one after another, speaking now faster and louder, now soft and slow. Then he spoke many single words of Elvish speech. Nothing happened. The cliff towered into the night, the countless stars were kindled, the wind blew cold, and the doors stood fast.
Again Gandalf approached the wall, and lifting up his arms he spoke in tones of command and rising wrath. Edro, edro! he cried, and struck the rock with his staff. Open, open! he shouted, and followed it with the same command in every language that had ever been spoken in the West of Middle-earth. Then he threw his staff on the ground, and sat down in silence.

It should probably be mentioned that in the book, 'Mellon' is Gandalf's idea (inspired by something Merry said) whereas in the film 'Mellon' is Frodo's idea.


text:
Q: Determine whether 271 is invertible modulo 2018, and if so find an inverse a. Here is the question I'd greatly appreciate help on:
(a) Use the Euclidean Algorithm to compute gcd ($2018, 271$) and use that to find integers $x$ and $y$ so that gcd ($2018, 271$) =
$2018x + 271y$.
I've done this part. gcd($2018, 271$) = $1$ = $2018 * 56 + 271 * (-417)$
$(x = 56, y = -417)$
(I will edit in all of the algorithm's steps if needed!)
I'm having trouble with part (b):
(b) Use part (a) to determine whether $271$ is invertible modulo $2018$, and if it is invertible, find an inverse a of $271$ modulo
$2018$ so that $0 < a < 2018$. Explain why your answer is an inverse of $271$ modulo $2018$ using the definition of an inverse
modulo n.
I know that $271$ is invertible modulo $2018$ if and only if there exists an integer $t$ so that $271 * t ≡ 1 (mod 2018)$, and that t is an inverse of $271$ modulo $2018$.
However, I just got this from class lecture and don't really know what this means on a conceptual level, and how to apply it to this question.
Thank you.

A: We have $$1=2018(56)+271(-417)$$
Hence
$$1\equiv 2018(56)+271(-417) \pmod{2018}$$
$$1\equiv 271(-417) \pmod{2018}$$
Hence $-417  \equiv 2018-417\pmod{2018}$ is its inverse.


text:
Q: Why is my code not iterating? Why is my code not working as expected? The others (departmentName, employeeName and statusDescription) are working (shown below)
int countRow = 1;
//Query for account status
var query = from emp in db.EmployeeDetails
            join stat in db.Status on emp.statusId equals stat.statusId
            join dep in db.Department on emp.departmentId equals dep.departmentId
            where emp.employeeName == name
            select new { emp, stat, dep };
foreach (var q in query)
{

    Console.WriteLine("{0,-3} | {1,-10} | {2,10}\t\t | {3,10}",
       countRow,
       q.dep.departmentName,
       q.emp.employeeName,
       q.stat.statusDescription);
    Console.WriteLine("-----------");
    countRow++;// <---------not adding: output keeps printing 1
}

It's working but my countRow is constantly having a value of 1
Right now, my output looks like this:
No.      Dep             Name      Status
1        Finance         John      Present
1        Education       Mary      Present
1        Recreational    Tom       Absent

What I'm looking for is this:
No.      Dep             Name      Status
1        Finance         John      Present
2        Education       Mary      Present
3        Recreational    Tom       Absent

UPDATE:
It appears my "query" (in foreach var q in query) has a count value of 1. I suppose this is the cause of my issue. Does anyone know how I can fix this?

A: It seems like you're posting the results of multiple queries.
Your original query looks for a specific name (emp.employeeName == name) which yields, probably, a single result. The results you posted have multiple names in them, which means you're running this query more than once (maybe in an enclosing loop?). Each query initializes countRow to 1, so you get the same number every time.
If you had multiple employees with the same name, you'd see numbers other than 1. As the comments suggest, try to find the enclosing loop and move the countRow = 1 initializer there.


text:
Q: Where Clause with And & Or I am trying to add an Or clause to my where statement and could use a little help.
Here's what I have:
  Where
  W.Insured_Id = P.Insured_Id and
  P.Insured_Id = I.Insured_Id and
  I.Insured_Id = IU.Insured_Id and
  p.expiration_date > to_date ('30-Apr-2014','dd-mm-yyyy') and
  p.expiration_date < to_date ('16-Dec-2014','dd-mm-yyyy') or
  p.expiration_date > to_date ('15-Dec-2013','dd-mm-yyyy') and
  p.expiration_date < to_date ('01-May-2014','dd-mm-yyyy') and
  p.annual_premium < '1000' or
  p.expiration_date > to_date ('15-Dec-2014','dd-mm-yyyy') and
  p.expiration_date < to_date ('01-Jan-2015','dd-mm-yyyy') and
  p.annual_premium < '1000'

I am trying to return all policies between May 1st and December 15 and only the policies that have less than 1000 in premium for the remainder of the year.
Let me know if I can provide more information.
Thank you for your help!!!

A: You need to surround OR clauses with bracketes and use between brackets:

(... OR ...) and (... OR ...) ...

A: So, this is a bit confusing because your code suggests you're trying to do something very different than what you're asking. To accomplish what you've asked, you'll want to do something along the lines of :
Where
W.Insured_Id = P.Insured_Id and
P.Insured_Id = I.Insured_Id and
I.Insured_Id = IU.Insured_Id and
p.expiration_date > to_date ('15-Dec-2013','dd-mm-yyyy') and
p.expiration_date < to_date ('01-May-2014','dd-mm-yyyy') and
p.annual_premium < '1000'

Which should return all the records between 12/15/2013 and 05/01/2014 with annual_premium < 1000. The code you included could be modified to work using parentheses thusly:
Where
W.Insured_Id = P.Insured_Id and
P.Insured_Id = I.Insured_Id and
I.Insured_Id = IU.Insured_Id and
(
    (
        p.expiration_date > to_date ('30-Apr-2014','dd-mm-yyyy') and
        p.expiration_date < to_date ('16-Dec-2014','dd-mm-yyyy')
    )
    or
    (
        p.expiration_date > to_date ('15-Dec-2013','dd-mm-yyyy') and
        p.expiration_date < to_date ('01-May-2014','dd-mm-yyyy')
    )
    or
    (
        p.expiration_date > to_date ('15-Dec-2014','dd-mm-yyyy') and
        p.expiration_date < to_date ('01-Jan-2015','dd-mm-yyyy')
    )
    or
    (
        p.expiration_date > to_date ('15-Dec-2014','dd-mm-yyyy') and
        p.expiration_date < to_date ('01-Jan-2015','dd-mm-yyyy')
    )
)
and p.annual_premium < '1000'

However, that's going to include a bunch of records compared to what you requested. Simplified, this code works out to being the same as this, due to overlapping dates:
Where
W.Insured_Id = P.Insured_Id and
P.Insured_Id = I.Insured_Id and
I.Insured_Id = IU.Insured_Id and
p.expiration_date > to_date ('15-Dec-2013','dd-mm-yyyy') and
p.expiration_date < to_date ('01-Jan-2015','dd-mm-yyyy') and
p.annual_premium < '1000'


text:
Q: Install Ubuntu on Mac Mini through a USB pen drive I have a Mac Mini with Intel Core Solo processor.
The HD of this computer was formerly part of a PC, and so Windows XP was installed on it. I've successively moved the hard disk from PC to a Mac. All works pretty well, Windows XP starts without any problem. I would now install Ubuntu on this Mac. Alas the DVD drive is out of service, and so I have to find alternatives.
I've thinked to use a pen drive and start installation from this device.
Anyone have experience in this and can tips the best?

A: You can download a ubuntu .iso image from ubuntu.com.
Then you can go to pendrivelinux.com and download the usb installer.
That program will install ubuntu to the usb drive. Once that is done, you have to boot from the usb drive.
You can do this by entering into your bios. I dont know how to do this on a mac, but i know on hp computers, you press f9.
Then once you boot into your usb, it will ask you if you want to install or try ubuntu; Select try ubuntu.
The usb will do it's thing. Then test ubuntu and make sure you like it and all the drivers are working correctly.
Then if you would like to install, click the install icon on the desktop. The steps after are self explanatory. Ubuntu will guide you through the install, and will ask you to reboot after the installation has finished
Thats it, your done. Enjoy ubuntu

A: You need iso file of linux distro and burn it to usb key with unetbootin. Than you will probably need to select usb key as first bootable device in BIOS or boot menu whatever mac has.

A: Blogger is right. You should use Unetbootin to do the trick. http://sourceforge.net/projects/unetbootin/files/UNetbootin/575/unetbootin-mac-575.zip/download
You can download the ubuntu iso with unetbootin, or download it by yourself. you select your flashdrive's letter and you're good to go.


text:
Q: How is dot product defined for higher dimensions? I am specifically interested in the case of 2D (matrices). I am reading a research paper which says that I should find the dot product of matrix A and its transpose and subtract it from the identity matrix.
$AA^T - I$
From the matrix library I am using the dot product comes out to be a single number?
Can anyone explain why it would be a matrix?
Thanks.

A: It's sort of weird for the paper to call the operation "dot product" because that name is usually reserved for the dot product of two vectors. What the paper is talking about, I believe, is simply the standard matrix multiplication which, if the matrix is a single column, is the same as the dot product.
So yeah, to describe the formula
$$AA^T-I$$
I would say you simply take the product of $A$ and $A^T$ and subtract $I$.


text:
Q: how to get value from select without refresh? I made a CGPA-SGPA calculator and I cannot get the value with refresh.
When I refresh and check the value it get feed
but not getting value without refresh.

var credit_1001 = document.querySelector('#credit_1001')
var grade_1001 = document.querySelector('#grade_1001')
var credit_1002 = document.querySelector('#credit_1002')
var grade_1002 = document.querySelector('#grade_1002')
var credit_1003 = document.querySelector('#credit_1003')
var grade_1003 = document.querySelector('#grade_1003')
var credit_1004 = document.querySelector('#credit_1004')
var grade_1004 = document.querySelector('#grade_1004')
var credit_1008 = document.querySelector('#credit_1008')
var grade_1008 = document.querySelector('#grade_1008')
var credit_1009 = document.querySelector('#credit_1009')
var grade_1009 = document.querySelector('#grade_1009')
//btn and result S1
var btn_check = document.querySelector('#check_s1')
var result_s1 = document.querySelector('#result_s1')

//btn click S1
var total_s1_credit = parseInt(credit_1001.value) + parseInt(credit_1002.value) + parseInt(credit_1003.value) + parseInt(credit_1004.value) + parseInt(credit_1008.value) + parseInt(credit_1009.value)
var got_s1_marks = parseInt(credit_1001.value) * parseInt(grade_1001.value) + parseInt(credit_1002.value) * parseInt(grade_1002.value) + parseInt(credit_1003.value) * parseInt(grade_1003.value) + parseInt(credit_1004.value) * parseInt(grade_1004.value) + parseInt(credit_1008.value) * parseInt(grade_1008.value) + parseInt(credit_1009.value) * parseInt(grade_1009.value)
btn_check.addEventListener('click', () => {

    result_s1.innerText = " S1 SGPA " + got_s1_marks / total_s1_credit
    console.log("S1 Total Credit = " + total_s1_credit)
    console.log("S1 Got Marks = " + got_s1_marks)
    console.log("S1 SGPA = " + result_s1.innerText)
})

A: You need to get the values for your calculation inside of the click handler, right now you get them before the click, and then use (the old values) when the click happens
btn_check.addEventListener('click', () => {
    //btn click S1
    var total_s1_credit = parseInt(credit_1001.value) + parseInt(credit_1002.value) + parseInt(credit_1003.value) + parseInt(credit_1004.value) + parseInt(credit_1008.value) + parseInt(credit_1009.value)
    var got_s1_marks = parseInt(credit_1001.value) * parseInt(grade_1001.value) + parseInt(credit_1002.value) * parseInt(grade_1002.value) + parseInt(credit_1003.value) * parseInt(grade_1003.value) + parseInt(credit_1004.value) * parseInt(grade_1004.value) + parseInt(credit_1008.value) * parseInt(grade_1008.value) + parseInt(credit_1009.value) * parseInt(grade_1009.value)
    result_s1.innerText = " S1 SGPA " + got_s1_marks / total_s1_credit
    console.log("S1 Total Credit = " + total_s1_credit)
    console.log("S1 Got Marks = " + got_s1_marks)
    console.log("S1 SGPA = " + result_s1.innerText)
})


text:
Q: SOAP Faults  in http response not visible I have one issue. I've generated a WS server from a wsdl and i'm am trying to understand the exceptions handiling. Basically in the WSDL is defined a custom exception called Throwable_Exception. Now I've tired to test the fault in the SOAP response and it work and thats the result:
 <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
   <soap:Body>
      <soap:Fault>
         <faultcode>soap:Server</faultcode>
         <faultstring>TEST Custom Exception</faultstring>
      </soap:Fault>
   </soap:Body>
 </soap:Envelope>

The text in the "faultstring" tag is the messagge that i've thrown in the exception.
Now my goal its to send in the response this kind of informations:

*

*A readable messagge about the exception

*The exception thrown from the server

*eventually the details about the exception

I've seen on an guide from Oracle that the SOAP fault envelope should be like this:
<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
   <S:Body>
      <S:Fault xmlns:ns4="http://www.w3.org/2003/05/soap-envelope">
         <faultcode>S:Server</faultcode>
         <faultstring>Your name is required.</faultstring>
         <detail>
            <ns2:MissingName xmlns:ns2="http://examples/">
               <message>Your name is required.</message>
            </ns2:MissingName>
            <ns2:exception xmlns:ns2="http://jax-ws.dev.java.net/"
 class="examples.MissingName" note="To disable this feature, set
 com.sun.xml.ws.fault.SOAPFaultBuilder.disableCaptureStackTrace system
 property to false">
               <message>Your name is required.</message>
               <ns2:stackTrace>
                  <ns2:frame class="examples.HelloWorld" file="HelloWorld.java"
  line="14" method="sayHelloWorld"/>
  ...
               </ns2:stackTrace>
            </ns2:exception>
         </detail>
      </S:Fault>
   </S:Body>
</S:Envelope>

The thing is that in my code as you see, it doesn't show the "detail" tag. You guys know how to show this kind of information in the SOAP response?
public String myMethod(String field1, String field2) throws Throwable_Exception {

        LOG.info("Executing operation myMethod");

        try {

            java.lang.String _return = "";

            List<String> testExceptions = new ArrayList<>();

            testExceptions.get(0);
            return _return;

        } catch (IndexOutOfBoundsException ex) {
            throw new Throwable_Exception("TEST Custom Exception", ex.getCause());
        }

        //throw new Throwable_Exception("Throwable...");
    }

In the impl class I've tried to force an IndexOutOfBoundsException as well and tried to use this constructor:
public Exception(String message, Throwable cause) {
        super(message, cause);
    }

and I thought that this approach could resolve the issue but apparently not.
Note: the WS is deployed on WildFly18.

A: for everyone still looking for the answer I've understood that basically if you have an xsd schema, you have to define the complex type of your  exception detail. For example:
  <xs:complexType name="YourCustomException">
    <xs:sequence>
      <xs:element name="exName" type="xs:string" minOccurs="0"></xs:element>
      <xs:element name="exMessage" type="xs:string" minOccurs="0"></xs:element>
      <xs:element name="exDetails" type="xs:string" minOccurs="0"></xs:element>
    </xs:sequence>
  </xs:complexType>

in Java your going to have the class from this complexType and his exception class. In the exception class you have to bring an attribute of the complexType (if you generate the classes with CXF or some other tools everything is taken care of) and you have to figure your preferred way for instanciate the complexType in your customException so in the SOAP Fault the "detail" tag is populated.
Example of the CustomException in Java:
@WebFault(name = "YourCustomException", targetNamespace = "http://serviceendpoint/")
public class YourCustomException_Exception extends Exception {

    private it.your.package.YourCustomException YourCustomException;

    public YourCustomException_Exception() {
        super();
    }

    public YourCustomException_Exception(String message) {
        super(message);
    }

    public YourCustomException_Exception(String message, java.lang.Throwable cause) {
        super(message);
        this.YourCustomException = new YourCustomException();
        this.YourCustomException.setExName(cause.getClass().getName());
        this.YourCustomException.setExMessage(cause.getMessage());
        this.YourCustomException.setExDetails(cause.getLocalizedMessage());

    }
}

example of the ComplexType in Java:
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "YourCustomException ", propOrder = {
    "exName",
    "exMessage",
    "exDetails"
})
public class YourCustomException {

    protected String exName;
    protected String exMessage;
    protected String exDetails;

    public String getExName() {
        return exName;
    }

    public void setExName(String exName) {
        this.exName = exName;
    }

    public String getExMessage() {
        return exMessage;
    }

    public void setExMessage(String exMessage) {
        this.exMessage = exMessage;
    }

    public String getExDetails() {
        return exDetails;
    }

    public void setExDetails(String exDetails) {
        this.exDetails = exDetails;
    }

}

SOAP Fault in the response forcing an IndexOutOfBounds in the method called:
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
   <soap:Body>
      <soap:Fault>
         <faultcode>soap:Server</faultcode>
         <faultstring>Error in your method</faultstring>
         <detail>
            <ns2:YourCustomException xmlns:ns2="http://serviceendpoint/">
               <exName>java.lang.IndexOutOfBoundsException</exName>
               <exMessage>Index: 0, Size: 0</exMessage>
               <exDetails>Index: 0, Size: 0</exDetails>
            </ns2:YourCustomException >
         </detail>
      </soap:Fault>
   </soap:Body>
</soap:Envelope>

Hope this helps.


text:
Q: Fast counting semaphore on Windows? First of all, I know that it can be implemented with a mutex and condition variable, but I want the most efficient implementation possible.
I would like a semaphore with a fast-path when there's no contention. On Linux this is easy with a futex; for example, here's a wait:
if (AtomicDecremenIfPositive(_counter) > 0) return; // Uncontended
AtomicAdd(&_waiters, 1);
do
{
    if (syscall(SYS_futex, &_counter, FUTEX_WAIT_PRIVATE, 0, nullptr, nullptr, 0) == -1) // Sleep
    {
        AtomicAdd(&_waiters, -1);
        throw std::runtime_error("Failed to wait for futex");
    }
}
while (AtomicDecrementIfPositive(_counter) <= 0);
AtomicAdd(&_waiters, -1);

and post:
AtomicAdd(&_counter, 1);
if (Load(_waiters) > 0 && syscall(SYS_futex, &_counter, FUTEX_WAKE_PRIVATE, 1, nullptr, nullptr, 0) == -1) throw std::runtime_error("Failed to wake futex"); // Wake one

At first I thought for Windows to just use NtWaitForKeyedEvent(). The problem is it's not a direct substitution because it doesn't atomically check the value at _counter before going into the kernel, and so can miss the wake from NtReleaseKeyedEvent(). Worse, then NtReleaseKeyedEvent() would block.
What's the best solution?

A: Windows has native semaphores with CreateSemaphore. Until and unless you have some kind of documented performance problem doing it the normal way, you shouldn't even consider optimizations that are fragile or hardware-specific.

A: I think something like this should work:
// bottom 16 bits: post count
// top 16 bits: wait count
struct Semaphore { unsigned val; }

wait(struct Semaphore *s)
{
retry:
    do
        old = s->val;
        if old had posts (bottom 16 bits != 0)
            new = old - 1
            wait = false
        else
            new = old + 65536
            wait = true
    until successful CAS of &s->val from old to new

    if wait == true
        wait on keyed event
        goto retry;
}

post(struct Semaphore *s)
{
    do
        old = s->val;
        if old had waiters (top 16 bits != 0)
            // perhaps new = old - 65536 and remove the "goto retry" above?
            // not sure, but this is safer...
            new = old - 65536 + 1
            release = true
        else
            new = old + 1
            release = false
    until successful CAS of &s->val from old to new

    if release == true
        release keyed event
}

edit: that said, I'm not sure this would help you a lot.  Your thread pool usually should be big enough that a thread is always ready to process your request.  This means that not only waits, but also posts will always take the slow path and go to the kernel.  So, counting semaphores are probably the one primitive where you do not really care about a userspace-only fastpath.  Stock Win32 semaphores should be good enough.  That said, I'm happy to be proven wrong!

A: I vote for your first idea, e.g critical section and condition variable. Critical section is fast enough and it does use interlocked operation before it goes to sleep.  Or, you can experiment with  SRWLocks instead of critical section. Condition variables (and SRWLocks) are very fast - their only problem is that there are no conditions on XP, but maybe you do not need to target this platform .

A: Qt has all kinds of things like QMutex, QSemaphore which are implemented in spirit like what you presented in your question.
Actually, I would suggest replacing the futex stuff with the usual OS-provided synchronization primitives; it should not matter much since that is the slow path anyway.


text:
Q: Drawing vertical lines in between icons Hello people am new to front end web development and still learning. I need to add two vertical lines in between three icons, please help me out.
This is what I've done so far:

.photo {
  background-image: url(photo.jpg.jpg);
  width: 100%;
  height: 500px;
  background-size: cover;
  color: hsla(325, 50%, 50%, 0.6);
}

h1 {
  text-align: center;
  padding-top: 15%;
}

.p {
  text-align: center;
  color: #FFCA28;
  padding-top: 0.5%;
  color: hsla(325, 50%, 50%, 0.6);
}

.Request {
  width: 200px;
  height: 100px;
  border-radius: 25px;
  font-size: 25px;
  color: #fff;
  line-height: 100px;
  text-align: center;
  background: #d50000;
  float: center;
  margin-left: 22em;
  margin-top: 2em;
}

.q {
  float: right;
  padding: 2%;
}

.j {
  text-align: center;
  color: grey;
  border-radius: 50%;
  width: 100%;
  height: 100%;
}

.content-wrap {
  display: flex;
  justify-content: space-between;
  position: relative;
}

.icon1 {
  width: 6rem;
  height: 6rem;
  font-size: 4rem!important;
  /* !important is here just to override SO styles*/
  color: #777;
  border: 2px solid #777777;
  border-radius: 50%;
  padding: 1rem;
  text-align: center;
  line-height: 6rem!important;
  /* !important is here just to override SO styles*/
}
<!DOCTYPE html>

  <title> JAMES UFONDU</title>
  <link rel="stylesheet" type="text/css" href="style.css">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

    Products Community Talk to Sales Request Demo En

 MANAGE YOUR CONDOMINIUM THE BETTER WAY

 Use Evercondo to communicate, manage, organize, measure and optimize your day-to-day operations.

Request Demo

 How does Evercondon Work ?

Eliminate the chaos in your day-to-day management tasks

A: I added the
 tag between the icons

<!DOCTYPE html>

         <title> JAMES UFONDU</title>
         <link rel="stylesheet" type="text/css" href="style.css">
         <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

        Products Community Talk to Sales  Request Demo  En

 MANAGE YOUR CONDOMINIUM THE BETTER WAY

 Use Evercondo to communicate, manage, organize, measure and optimize your day-to-day operations.

Request Demo

 How does Evercondon Work ?

Eliminate the chaos in your day-to-day management tasks

A: Wrap i tag in span and add this tyle
.contentwrap span {
      border-right: 1px solid black;
      display: inline-block;
      padding-right: 18px;
      margin-right: 15px;
    }

photo {
  background-image: url(photo.jpg.jpg);
  width: 100%;
  height: 500px;
  background-size: cover;
  color: hsla(325, 50%, 50%, 0.6);
}

h1 {
  text-align: center;
  padding-top: 15%;
}

.p {
  text-align: center;
  color: #FFCA28;
  padding-top: 0.5%;
  color: hsla(325, 50%, 50%, 0.6);
}

.Request {
  width: 200px;
  height: 100px;
  border-radius: 25px;
  font-size: 25px;
  color: #fff;
  line-height: 100px;
  text-align: center;
  background: #d50000;
  float: center;
  margin-left: 22em;
  margin-top: 2em;
}

.q {
  float: right;
  padding: 2%;
}

.j {
  text-align: center;
  color: grey;
  border-radius: 50%;
  width: 100%;
  height: 100%;
}

.content-wrap {
  display: flex;
  justify-content: space-between;
  position: relative;
}

.icon1 {
  width: 6rem;
  height: 6rem;
  font-size: 4rem!important;
  /* !important is here just to override SO styles*/
  color: #777;
  border: 2px solid #777777;
  border-radius: 50%;
  padding: 1rem;
  text-align: center;
  line-height: 6rem!important;
  /* !important is here just to override SO styles*/
}

.contentwrap span {
  border-right: 1px solid black;
  display: inline-block;
  padding-right: 18px;
  margin-right: 15px;
}
<!DOCTYPE html>

  <title> JAMES UFONDU</title>
  <link rel="stylesheet" type="text/css" href="style.css">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

    Products Community Talk to Sales Request Demo En

 MANAGE YOUR CONDOMINIUM THE BETTER WAY

 Use Evercondo to communicate, manage, organize, measure and optimize your day-to-day operations.

Request Demo

 How does Evercondon Work ?

Eliminate the chaos in your day-to-day management tasks


text:
Q: If $f$ is a differentiable function such that $f(x)=f(-x)$, how can I prove that $f'(0)=0$ using solely the limits definition of differentiability? Struggling to get to grips with how to go about this question:
"Let $f:\mathbb{R}\to\mathbb{R}$ be a differentiable function such that $f(x) = f(−x)$ for all $x$. Show, just using the definition of differentiability, that
$f'(0) = 0$."
It is obvious that $f(x)$ cannot be below $0$ given the conditions above, the function will be symmetric (mirrored in $y$-axis).
We know that $f$ is differentiable and therefore that:
$$f'(x) = \lim\limits_{h \to 0} \frac{f(x+h)-f(x)}{h}$$
Would the proof be as simple as substituting $x = 0$ and making $f(x+h) = f(0)$ as $h$ tends to $0$ ?
I appear to be missing some crucial steps here.

A: $$f'(x)=\lim_{h\to0}\frac{f(x+h)-f(x)}{h}$$
As $f$ is differentiable, put $x=0$,
$$f'(0)=\lim_{h\to0}\frac{f(h)-f(0)}{h}$$
Let $k=-h$. Then,
$$f'(0)=\lim_{k\to0}\frac{f(-k)-f(0)}{-k}$$
$$f'(0)=-\lim_{k\to0}\frac{f(k)-f(0)}{k}=-f'(0)$$
Thus,
$$f'(0)=0$$

A: Firstly, note that if $\lim_{x \to 0} g(x)$ exists, then it equals $\lim_{x \to 0} g(-x)$. This is because the image of $g(x)$ and $g(-x)$ is the same in the interval $(-\delta, \delta)$. Hence
$$L = f'(0) = \lim_{x \to 0} \frac{f(x) - f(0)}{x} = \lim_{x \to 0} \frac{f(x) - f(0)}{-x} = -L \Longrightarrow L =0$$

A: $$f'(-x)=\lim_{h\to 0}\left(\frac{f(-x+h)-f(-x)}{h}\right)=\lim_{h\to 0}\left(\frac{f(x-h)-f(x)}{h}\right)=-\lim_{h\to 0}\left(\frac{f(x-h)-f(x)}{-h}\right)=-f'(x)$$
It should be clear from the definition of the limit that taking the limit as h goes to zero or as -h goes to zero is the same thing.


text:
Q: Chosen's "Multiple Select" I have just discovered Chosen. The library is somewhat large, especially that I am only interested in the "Multiple Select" feature.
Is there a way to build a slimer Chosen just for "Multiple Select"?

A: Do you mean the facebook like tab completion multiple select type feature? If so ... there are a number of tutorials on line for writing your own. The only way I can imagine you can 'slim down' Chosen is not to! I took a look at the source and it appears to me that the 'multi select' aspect is pretty core to Chosen's functionality. I'm not sure you'd get much out of that route.
If you want to write your own, here is a tutorial you could follow to get write functionality you want:

*

*How to write a facebook like multiselect
Alternately you could check out some other libraries. I found a couple:

*

*FCBKcomplete - only 11k!

*Proto!MultiSelect - bigger :(

*jQuery tokenInput - flexible looking.

*TextExtJS - cool kid approved - is it small? dunno.

'Somewhat large' is a subjective term, but to me the 18k sounds pretty slim for the minified version of Chosen. Plus its the one I've used, and have been happy with. However - other libraries abound, so...happy hunting!


text:
Q: not able to open System setting after upgrade to Ubuntu 14.04 I have upgraded my system from Ubuntu 12.04 to Ubuntu 14.04.
After upgrade I am not able to open System Settings
I ran the below command on terminal
gnome-control-center

Below is the output for above command

(unity-control-center:19276): Gdk-ERROR **: The program
  'unity-control-center' received an X Window System error. This
  probably reflects a bug in the program. The error was 'BadRequest
  (invalid request code or no such operation)'.   (Details: serial 179
  error_code 1 request_code 157 (GLX) minor_code 19)   (Note to
  programmers: normally, X errors are reported asynchronously;    that
  is, you will receive the error a while after causing it.    To debug
  your program, run it with the GDK_SYNCHRONIZE environment    variable
  to change this behavior. You can then get a meaningful    backtrace
  from your debugger if you break on the gdk_x_error() function.)
  Trace/breakpoint trap

Can anyone please help to solve this issue
Thanks in advance

A: As seen at www.ubuntu.com, do these commands
`ubuntu-support-status

cat /etc/dpkg/dpkg.cfg.d/multiarch

dpkg --print-foreign-architectures

sudo grep -R proxy /etc/apt/*

grep proxy  /etc/environment

echo $http_proxy

echo $ftp_proxy

grep proxy /etc/bash.bashrc

grep proxy ~/.bashrc

cat /etc/apt/apt.conf

sudo fuser -vvv /var/lib/dpkg/lock

sudo fuser -vvv /var/cache/apt/archives/lock

cat /etc/lsb-release

uname -a

sudo rm /var/lib/apt/lists/lock

sudo rm  /var/cache/apt/archives/lock

sudo rm /var/lib/dpkg/lock

sudo cp -arf /var/lib/dpkg /var/lib/dpkg.backup

sudo mv /var/lib/dpkg/status /var/lib/dpkg/status-bad

sudo cp /var/lib/dpkg/status-old /var/lib/dpkg/status  ||  sudo cp /var/backups/apt.extended_states.0 /var/lib/dpkg/status

sudo mv /var/lib/dpkg/available /var/lib/dpkg/available-bad

sudo cp /var/lib/dpkg/available-old /var/lib/dpkg/available

sudo rm -rf /var/lib/dpkg/updates/*

sudo rm -rf /var/lib/apt/lists

sudo rm /var/cache/apt/*.bin

sudo mkdir /var/lib/apt/lists

sudo mkdir /var/lib/apt/lists/partial

LANG=C;sudo apt-get clean

LANG=C;sudo apt-get autoclean

sudo dpkg --configure -a

sudo dpkg --clear-avail

LANG=C;sudo apt-get -f install

LANG=C;sudo apt-get --fix-missing install

LANG=C;sudo apt-get --purge autoremove

LANG=C;sudo apt-get --fix-missing update -o APT::Cache-Limit=100000000

LANG=C;sudo apt-get update -o APT::Cache-Limit=100000000 && sudo apt-get dist-upgrade

find /etc/apt -name '*.list' -exec bash -c 'echo -e "\n$1\n"; cat -n "$1"' _ '{}' \;`

and send the output status to me via a comment. Then if that doesn't work, it may be very simple as to just do
sudo apt-get install ubuntu-desktop to fix installed Ubuntu programs.


text:
Q: Create a matrix ( mx n) with gaussian random distribution How to create a Matlab matrix (m x n) with random Gaussian distribution of numbers 0 and 1, when the number of 1's is a% and number of 0 is (100-a)%?
for example in one dimension that is "00000010001001011010111011101111111111111110110101001010010001000000" but I want 2D matrix such that there is a lot of "1" in the center of the matrix and there is a lot of "0" in the border of the matrix (change 1 to 0 with Gaussian distribution from center to border).
The definition of Gaussian matrix can be found here

A: Okay, it seems you're wanting the probability of having a 1 at any point to be governed by some sort of gaussian function.
1) Create a 2D gaussian function (e.g. using fspecial), scaled between 0 and 1.
2) Create a 2D random matrix of the same size (using rand).
3) Create an output matrix containing zeros and set it to one wherever the random value is lower than the gaussian.
myoutput(r<g) = 1;

Finding a gaussian which gives you your desired overall probability is another matter.


text:
Q: How can I grant access to videos to authorized users only? For example, only paying users should be allowed to view a video.
There is a plugin for that or is it all written from scratch?

A: The authlogic and devise are two popular authentication mechanisms. Either could be used to restrict access to particular actions based on logged-in status.
If you need a finer-grained authorization system, cancan provides a permissions system.
There are others, but these are quite popular.