text:
Q: Extract html and wordpress shortcodes into array of objects I am working a headless Wordpress site with Nuxt as my front end.
The site has thousands of articles which have shortcodes. I am getting all the page data via graphql and I render content using v-html and it is all working great, but the shortcodes obviously only render as plain text.
They are mostly very simple shortcodes so I am going to create Vue components to replace them using
<component :is="someshortcode">

What I need to do is split my html up into an array of objects I can use to render the parts of the page as html or a component depending what it is.
I imagine the best way to do this is with regex which is where I am stumped.
Let's say I have the following html with some shortcodes

Lorem ipsum dolor sit amet

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus facilisis elit ante. Vivamus semper dui eget justo viverra facilisis. Etiam ut leo fermentum, sagittis mauris nec, placerat lorem.

Lorem ipsum dolor sit amet

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus facilisis elit ante. Vivamus semper dui eget justo viverra facilisis. Etiam ut leo fermentum, sagittis mauris nec, placerat lorem.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus facilisis elit ante. Vivamus semper dui eget justo viverra facilisis. Etiam ut leo fermentum, sagittis mauris nec, placerat lorem.

[someshortcode attr1="value1" attr2="value2"]

Lorem ipsum dolor sit amet

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus facilisis elit ante. Vivamus semper dui eget justo viverra facilisis. Etiam ut leo fermentum, sagittis mauris nec, placerat lorem.

Lorem ipsum dolor sit amet

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus facilisis elit ante. Vivamus semper dui eget justo viverra facilisis. Etiam ut leo fermentum, sagittis mauris nec, placerat lorem.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus facilisis elit ante. Vivamus semper dui eget justo viverra facilisis. Etiam ut leo fermentum, sagittis mauris nec, placerat lorem.

[someshortcode attr1="value1" attr2="value2"]

Lorem ipsum dolor sit amet

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus facilisis elit ante. Vivamus semper dui eget justo viverra facilisis. Etiam ut leo fermentum, sagittis mauris nec, placerat lorem.

Lorem ipsum dolor sit amet

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus facilisis elit ante. Vivamus semper dui eget justo viverra facilisis. Etiam ut leo fermentum, sagittis mauris nec, placerat lorem.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus facilisis elit ante. Vivamus semper dui eget justo viverra facilisis. Etiam ut leo fermentum, sagittis mauris nec, placerat lorem.

What I want to do is return an array of objects as follows
[
    {
        type: 'html',
        content: `
Lorem ipsum dolor sit amet

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus facilisis elit ante. Vivamus semper dui eget justo viverra facilisis. Etiam ut leo fermentum, sagittis mauris nec, placerat lorem.

Lorem ipsum dolor sit amet

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus facilisis elit ante. Vivamus semper dui eget justo viverra facilisis. Etiam ut leo fermentum, sagittis mauris nec, placerat lorem.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus facilisis elit ante. Vivamus semper dui eget justo viverra facilisis. Etiam ut leo fermentum, sagittis mauris nec, placerat lorem.
`
    },
    {
        type: 'shortcode',
        content: `[someshortcode attr1="value1" attr2="value2"]`
    },
    {
        type: 'html',
        content: `
Lorem ipsum dolor sit amet

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus facilisis elit ante. Vivamus semper dui eget justo viverra facilisis. Etiam ut leo fermentum, sagittis mauris nec, placerat lorem.

Lorem ipsum dolor sit amet

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus facilisis elit ante. Vivamus semper dui eget justo viverra facilisis. Etiam ut leo fermentum, sagittis mauris nec, placerat lorem.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus facilisis elit ante. Vivamus semper dui eget justo viverra facilisis. Etiam ut leo fermentum, sagittis mauris nec, placerat lorem.
`
    },
    {
        type: 'shortcode',
        content: `[someshortcode attr1="value1" attr2="value2"]`
    },
    {
        type: 'html',
        content: `
Lorem ipsum dolor sit amet

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus facilisis elit ante. Vivamus semper dui eget justo viverra facilisis. Etiam ut leo fermentum, sagittis mauris nec, placerat lorem.

Lorem ipsum dolor sit amet

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus facilisis elit ante. Vivamus semper dui eget justo viverra facilisis. Etiam ut leo fermentum, sagittis mauris nec, placerat lorem.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus facilisis elit ante. Vivamus semper dui eget justo viverra facilisis. Etiam ut leo fermentum, sagittis mauris nec, placerat lorem.
`
    },
]

This is the basis of what I need, I will then be able to further break the shortcodes down by getting the properties etc.
What would be the best way of going about this? Is regex the best way?

A: You could use a DOM Parser and iterate the toplevel elements of the DOM. If such an element is a text node and it has the shortcode format, then create a separate object for it in the output array, otherwise get the HTML for the iterated element and accumulate it while it is not a shortcode, and finally output it as an object:

const html = `
Lorem ipsum dolor sit amet

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus facilisis elit ante. Vivamus semper dui eget justo viverra facilisis. Etiam ut leo fermentum, sagittis mauris nec, placerat lorem.

[someshortcode attr1="value1" attr2="value2"]

Lorem ipsum dolor sit amet

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus facilisis elit ante. Vivamus semper dui eget justo viverra facilisis. Etiam ut leo fermentum, sagittis mauris nec, placerat lorem.

[someshortcode attr1="value1" attr2="value2"]

Lorem ipsum dolor sit amet

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus facilisis elit ante. Vivamus semper dui eget justo viverra facilisis. Etiam ut leo fermentum, sagittis mauris nec, placerat lorem.
`;

const {body} = new DOMParser().parseFromString(html, 'text/html');
let content = "";
const arr = [];
for (const child of [...body.childNodes]) {
    if (child.nodeType === 3 && child.textContent.trim()[0] == "[") {
        if (content) arr.push({ type: "html", content });
        content = "";
        arr.push({ type: "shortcode", content: child.textContent.trim() });
    } else {
        content += (child.outerHTML ?? child.textContent);
    }
}
if (content) arr.push({ type: "html", content });
console.log(arr);


text:
Q: What is the nature of Christmas observance in the Potterverse? Every winter, Hogwarts students return home and celebrate Christmas with their families. However, given their extensive use of magic, it does not seem likely they'd understand Christianity the way muggles would.
How and why do wizards observe Christmas?

A: I believe that most every culture in the world has been shown to celebrate this day. In history, cultures that believed in magic, like the Celts, also celebrated a holiday with themes similar to Christmas.  The holiday celebrated by various cultures was a celebration of the time when the Sun being out will begin taking up more and more of the day. Since it's historically been observed by most every culture, there's no reason that wizards wouldn't also celebrate it, regardless that they called it christmas instead of Yule.
Additionally, from a sociological perspective, they inherited their culture from muggles and  generally people stick to what they were raised with.

A: In my opinion, its to ensure that the muggles and the wizards have their schedule in sync to prevent any curiosity between muggle and wizard.
For instance, if a neighbor sees that another neighbor's kid doesn't have a winter vacation, questions will pop up.  Investigations and the works, until the Wizards are exposed.
So basically its just make the kids seem normal to the muggle world.

A: Simply because wizards seem to actually believe in Jesus
The fact that wizards do things that once were being considered diabolic by the Catholic Church does not necessarily mean that they do not believe in God.
We can see cases that wizard priests appear in the books (e.g. the pastor at Dumbledore's funeral, the priest that married Bill and Fleur), and are very alike to the ones that British and the American people are used to in their everyday lifes. That logically points to that wizards also believe in Jesus, or in some variation of Him and the three predominant christianic dogmas (Western Catholic, Eastern Orthodox and British).
Although that celebrating Christmas in order to be "in-sync" with the Muggles is a good point, there's no sense in exchanging gifts, decorating trees and having dinners just for suspision avoidance.
Maybe there is a part of the British Church that operates in the wizard community secretly and their hypothetical change of heart to the beliefs and the condemns of the Dark Ages' "Witch Hunt" can be paralleled to the modernization that happened on the sexual direction of the priests (gay marriage, homosexual priests etc) that once were considered deadly sins and sicknesses.

A: Assuming that the stories told about Jesus in the Bible are accurate, Jesus may have been a wizard. There is good reason that he would have been revered among wizards, because he did things that none of them could do.  For example:

*

*He was able to transfigure food

*He resurrected

While performing magic in front of muggles is frowned of today, that wouldn't have been taboo in Jesus's day, because the International Statute of Wizarding Secrecy wasn't adopted until 1692.

A: Many people (or Muggles, in this case) who generally do not believe in the supernatural or in anything of that sort still believe in God and Jesus. Why would wizards/witches be any different? They may see Jesus as a wizard, and his powers might seem similar to those of a wizard on the surface, but that does not necessarily mean that he is not the son of God or that he was a prophet. Wizards can celebrate Christmas for the same reasons as muggles.

A: Perhaps they are celebrating Yule, which is what the Christmas holiday is based off of. Yule is a celebration of winter solstice and would seem like a natural fit for witches and wizards to celebrate.
Perhaps the wizarding community adopted the name of Christmas as it seemed less conspicuous to muggles (even though Yule is now a recognized holiday) when they went through a Christianization. We don't actually see anything about what wizards/witches do on Christmas other than have a tree inside their house (a Yule tradition) and exchanging of gifts. We aren't given other clues as to any rituals or spiritual traditions that would say if they are Christian or not.

A: I believe it is similar to the real world, where (at least in Europe) people who are not very religious still celebrate Christmas to some degree.
As other people mentioned, in the ancient times people celebrated the winter solstice and later Christmas was established by Christianity. In the XX century people in western Europe became less and less religious, some calling themselves atheists or agnostics, some just didn't visit church too often. But still these people followed some Christmas traditions like decorating a Christmas tree, singing carols, giving themselves gifts or having a festive meal. We still can find some Christmas decorations in public places like shopping malls and radio stations keep playing themed songs. We can tell that Christmas has become a secular holiday for the whole societies: for some
people it has a religious dimensions, some people are just having some rest and fun.
The religion is never mentioned across Harry Potter books, but it doesn't imply that magic society is 100% atheist. It is possible that some of the wizards are religious, but it is not explicitly shown in the canon. Most of them may just follow the tradition and enjoy the occasion to spend some time with family. Probably there are some wizards who don't celebrate Christmas at all (I can't imagine Voldemort singing carols or preparing a pudding).
As for Hogwarts, it seems that Christmas is a good opportunity to have a longer break, allowing students and teachers to visit their families they don't see for most of the year and to have some rest in the middle of a school year. It is also an occasion to have some social integration for the lonely employees and students staying at Hogwarts, satisfying their emotional need for belongingness, providing some substitute of the family.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is $\{u_i(x) = |x-\lambda_i|, i=1,n : \lambda_i \ne \lambda_j, \forall i \ne j \}$ linearly dependent? Is $\{ u_i(x) = |x-\lambda_i|, i=1,n : \lambda_i \ne \lambda_j, \forall i \ne j \}$ linearly dependent?
I know there's something to do with $\sum_{i=1}^n {k_i u_i(x)} = 0$, but it's kind of messy.
Could you give any hint? Thank you in advanced.

A: Hint: For any $i$ observe that all the terms except $k_iu_i$ are differentiable at $\lambda _i$. If $k_i \neq 0$ you get the  contradiction that the sum $0$ is not differentiable at $\lambda _i$!.


text:
Q: Есть ли способы оптимизации этого кода? Доброго времени суток.
Я новенький в JS и, соответственно в реакте. Хотел у вас уточнить, есть ли возможность сделать код данного компонента "чище"? Прошу прощения, если вопрос или его постановка некорректны.
Перед Вами представлено ниже навигационное меню. Оно должно в зависимости от location.pathname выдавать различные наборы навигационных кнопок.
Всего кнопки 3 штуки:

*

*переход на главную страницу

*Переход на страницу модерации

*Переход на страницу администратора

Как пример вывода набора кнопок на странице, кнопка перехода на главную страницу не должна отображаться, если пользователь находится на главной странице.
import React from 'react';
import { useSelector } from 'react-redux';
import { Link, useLocation } from 'react-router-dom';
import classes from './Navbar.module.css';

export default function Navbar() {
  const location = useLocation();
  const isChanged = useSelector((state) => state.shiftReducer.isChangedData);

  return (

          {location.pathname !== '/' ? (

              <Link to="/" className={'nav_button'}>
                На главную
              </Link>

          ) : null}

          {location.pathname !== '/moderation' ? (

              <Link to="/moderation" className={'nav_button'}>
                Изменить график
              </Link>

          ) : null}

          {location.pathname !== '/admin' ? (

              <Link to="/admin" className={'nav_button'}>
                Управление
              </Link>

          ) : null}

  );
}

A: Чтобы не копировать одинаковые элементы, вы можете сделать map по массиву. Попробуйте вынести информацию по роутам в массив с объектами например:
  export default function Navbar() {
  const location = useLocation();
  const isChanged = useSelector((state) => state.shiftReducer.isChangedData);

  const routes = [
    { route: '/', child: 'На главную' },
    { route: '/moderation', child: 'Изменить график' },
    { route: '/admin', child: 'Управление' },
  ]

  return (

        {routes.map((el) => {
          return location.pathname !== el.route
            ?

              <Link to="/" className={'nav_button'}>
                {el.child}
              </Link>

            : null
        })}

  );
}


text:
Q: Start a python script in `screen` on boot? I want to be able to start a python script when I boot, but I want to be able to see lines which have been printed during the program. I have been able to put the line "sudo python /path/to/file.py" into /etc/rc.local but of course I can't then see the output.
Is it possible to put some kind of line in there to start the program in a screen terminal and which I can then access when I SSH in? - maybe something along the lines of...
screen sudo python /path/to/file.py

A: If you wish to use screen, use something like:
screen -dmS yourscreenname sudo python /path/to/file.py

from rc.local to run your program on detached screen. Next, after boot you can attach to it by
screen -r yourscreenname

from root account.
Alternativly - if you only wish to have logs from your program - maybe simpler is redirect output to syslog? for example:
sudo python /path/to/file.py|logger

If you wish also redirect standard errror output, don't forget about 2>&1:
sudo python /path/to/file.py 2>&1 |logger


text:
Q: Display current week in react-native I need to display the current week of the month in the following format in react-native:

(Week 2: 05.10 - 11.10) (example of week 2 of current month)

What would be some suggestions as how to achieve this? I know that there are packages such as momentjs to build this but would like some examples of how to achieve this
any help is appreciated!

A: You can adapt the code below.  I say "adapt" because you haven't specified when your week starts (Sunday or Monday?) or how you want to count which week within the month it is (i.e. is week #1 the first full week?  The code below assumes so).
Anyway, by clicking the "Run Code Snippet" button, you'll see what it does, including some intermediate steps, which are there to illustrate where the values are coming from, and therefore what you might want to "adapt" for your needs.

//get the first day of week and last day of week, borrowed from https://stackoverflow.com/a/64529257/1024832 above
const getWeek = (date = new Date()) => {
  const dayIndex = date.getDay();
  const diffToLastMonday = (dayIndex !== 0) ? dayIndex - 1 : 6;
  const dateOfMonday = new Date(date.setDate(date.getDate() - diffToLastMonday));
  const dateOfSunday = new Date(date.setDate(dateOfMonday.getDate() + 6));
  return [dateOfMonday, dateOfSunday];
}

//get week number w/in the month, adapted from https://stackoverflow.com/a/57120367/1024832
const getWeekNumber = () => {
  let todaysDate = moment(moment.now());
  let endOfLastMonth = moment(todaysDate).startOf('month').subtract(1, 'week');
  let weekOfMonth = todaysDate.diff(endOfLastMonth, 'weeks');
  return weekOfMonth;
}

//capture/log some steps along the way
const [Monday, Sunday] = getWeek();
console.log("First/Last of week as Date Objects: ", Monday, Sunday);
let Monday_formatted = moment(Monday).format("DD.MM");
let Sunday_formatted = moment(Sunday).format("DD.MM");
console.log(Monday_formatted, "-", Sunday_formatted);
console.log("Week #:", getWeekNumber());

//set the DIV content
document.getElementById("datehere").innerText = `(Week ${getWeekNumber()}):  ${Monday_formatted} - ${Sunday_formatted}`;

A: Here's an answer as a function which returns the current week's Monday and Sunday in an array:

getWeek = (date = new Date()) => {
  const dayIndex = date.getDay();

  const diffToLastMonday = (dayIndex !== 0) ? dayIndex - 1 : 6;
  const dateOfMonday = new Date(date.setDate(date.getDate() - diffToLastMonday));
  const dateOfSunday = new Date(date.setDate(dateOfMonday.getDate() + 6));

  return [dateOfMonday, dateOfSunday];
}

const [Monday, Sunday] = getWeek();

console.log(Monday, Sunday);

The response is two valid date objects. You can also pass a date object for the function to get Monday and Sunday of that date's week (e.g. getWeek(new Date(0));
But when you want to parse those dates, you should gain better knowledge of Date Object.


text:
Q: Android : Tween animation: Moving an ImageView I have a problem with tween animation in android , I try to move an ImageView item from center of screen to top of screen but after end of transform ImageView returns to first position! I use this code:
   <?xml version="1.0" encoding="utf-8"?>
       <translate
        xmlns:android="http://schemas.android.com/apk/res/android"
         android:interpolator="@android:anim/bounce_interpolator"
         android:fromYDelta="0%"
         android:toYDelta="-1500%"
         android:duration="3000"
         android:startOffset="3000">
         </translate>

private void RunAnimations() {

    Animation animation = AnimationUtils.loadAnimation(this, R.anim.move_up_maxname);
    animation.reset();
    ImageView maxName = (ImageView) findViewById(R.id.imageView1);
    maxName.clearAnimation();
    maxName.startAnimation(animation);
}

Can anyone help me?
Thanks

A: You need to take a look at setFillAfter:

If fillAfter is true, the transformation that this animation performed will persist when it is finished.

A: Use AnimationListener and in onAnimationEnd() change the position of ImageView(Last point).
animation.setAnimationListener(new AnimationListener() {

   public void onAnimationStart(Animation anim)
   {};

   public void onAnimationRepeat(Animation anim)
   {};

   public void onAnimationEnd(Animation anim)
   {
     //Change imageview position using LayoutParameters
   };
});

A: add line
   animation.setFillAfter(true);


text:
Q: Why does Firefox 4 absolutely position fieldset legends differently than other browsers? Why does Firefox 4 absolutely position fieldset legends differently than other browsers?
Test page:
<!DOCTYPE html>

        <meta charset="utf-8"/>
        <title>Test</title>

            <form method="POST" action="test" id="testForm">
                <fieldset>
                    <legend>Test</legend>
                    Test:<input type="text" id="test" name="test" value=""/>
                </fieldset>

                <input type="submit" value="Test"/>
            </form>

Notice that in Opera 11.10 Build 2092, Chrome 11.0.696.65, Safari 5.0.4 (7533.20.27), and Windows Internet Explorer 9, they display the legend on the left, overlapping the fieldset border.
In Firefox 4.0.1, I have to change the top and left properties to get a similar effect. For example, within the style tag of the test page, uncomment this CSS:
                /* Firefox */
                /*top: -20px;
                left: -25px;*/

A: legend elements are quirky and weird. That being said, if all the other browsers do the same thing, then Firefox should do the same thing.
There's already a bug report here describing the issue in detail: https://bugzilla.mozilla.org/show_bug.cgi?id=450418
A workaround is to add a wrapper div inside the fieldset and move the padding to that.
Your unchanged code: http://jsbin.com/ivedo4
Fixed code: http://jsbin.com/ivedo4/2
I tested it with the same browsers (not identical versions, but close) you listed in your question, and the rendering was consistent.
My code doesn't look quite right in IE8, but yours is broken in exactly the same way.


text:
Q: How to detect if any of the elements in the child component are touched in the Parent component I have got a parent component and it has 3 child components inside it. Inside the Parent component I have a save button.
My requirement is that if any of the elements or variables in any of the child components are touched then only I want the 'save' button in the parent component to be enabled.

Parent Component

   <child-component1>
   </child-component1>
   <child-component1>
   </child-component1>
   <child-component1>
   </child-component1>
   <button type="submit" [disabled]="!isSaveButtonDisabled">
   Save
   </button>

Inside the parent component ts file.
public ischildComponentOneFormModified: boolean = false;
public ischildComponentTwoFormModified: boolean = false;
public ischildComponentThreeFormModified: boolean = false;

get isSaveButtonDisabled(): boolean {
  if (
    this.ischildComponentOneFormModified ||
    this.ischildComponentTwoFormModified ||
    this.ischildComponentThreeFormModified
  ) {
    return true;
  } else {
    return false;
  }
}

Any inputs or suggestions on how do i achieve this ?

A: What you may want to use is an EventEmitter in your child component. When something changes (or component is "touched") then you emit from the child component and listen in your parent.
CHILD HTML
You have to configure how the touchDetected() method gets fired from your child component. There are several ways to accomplish this. Here is one example.

Hello, World!

CHILD CLASS
class ChildComponent {

   @Output() onChange: EventEmitter<any> = new EventEmitter<any>();

   touchDetected() {
     this.onChange.emit(true);
   }

}

PARENT HTML
<child-component (onChange)="listenForChildChange($event)" ></child-component>

PARENT CLASS
class ParentComponent {

   listenForChildChange(event:any) {
      this.ischildComponentFormModified = event;
   }

}


text:
Q: Global exception handling in Struts 2 How can I implement a global exception handler for Apache Struts 2?
I'm using annotations (with struts.property) and NOT struts.xml.
I have got it to work for action-classes (at class and method level) but I would like something more global like a stand-alone class.
Can I for example use the ExeptionHandler from Struts 2? Hard to find documentation and examples.
Any ideas?

A: You can map exceptions to result that calls the action that would handle the exception.
<global-results>
    <result name="exception" type="chain">
        <param name="actionName">exceptionHandler</param>
        <param name="namespace">/</param>
    </result>
</global-results>
<global-exception-mappings>
    <exception-mapping exception="java.lang.Exception" result="exception" />
</global-exception-mappings>

References:

*

*Exception Configuration

*Result Configuration


text:
Q: Collection of linear functions Let $X$ be a Banach space. Let $\{Y_\alpha\}_\alpha$ be normed spaces.
Let $\{T_\alpha:X\rightarrow Y_\alpha\}_\alpha$ be an infinite collection of bounded linear functions.
Is there a way to create one linear $T:X\rightarrow Y$ for some normed space $Y$ that will contain all the information about the collection $\{T_\alpha\}$?
My problem is with finding a way to define a suitable $Y$ and a norm for it.

A: This is a partial answer. Denote $Y=\bigoplus_\infty\{Y_\alpha:\alpha\in\mathcal{A}\}$. Then we define
$$
\pi_\alpha:T\to Y_\alpha: y\mapsto y_\alpha
$$
$$
T:X\to Y:x\mapsto\bigoplus_\infty\{\Vert T_\alpha\Vert^{-1} T_\alpha(x):\alpha\in\mathcal{A}\}
$$
In this case $T\in\mathcal{B}(X,Y)$ with $\Vert T\Vert\leq 1$. Unfortunately $T$ allows us to recover only $\Vert T_\alpha\Vert^{-1} T_\alpha$, not $T_\alpha$. Indeed
$$
\Vert T_\alpha\Vert^{-1} T_\alpha(x)=(\pi_\alpha\circ T)(x)
$$
We need some tricky method to store values $\Vert T_\alpha\Vert$ for all $\alpha\in\mathcal{A}$ in $Y$. I think we need to enlarge it by some direct sum of normed spaces which can allow us to recover this values.


text:
Q: WIX illegal character in path I have error

Illegal character in path

when i try to build my WIX.Setup. I could locate the the problem at following components
  <Component Id="C.Cef.Common.BrowserSubprocess.Core" Guid="{5603fa71-5739-4513-9cba-793a6f6d29ce}">
    <File Id="CefSharp.BrowserSubprocess.Core.dll"    Source="$(var.Path.Cefsharp.Commonx64)\CefSharp.BrowserSubprocess.Core.dll" KeyPath="yes" Checksum="yes"/>
  </Component>
  <Component Id="C.Cef.Common.BrowserSubprocessexe" Guid="{5b0b77cd-7787-4c8a-b388-8042d179a788}">
    <File Id="CefSharp.BrowserSubprocess.exe"       Source="$(var.Path.Cefsharp.Commonx64)\CefSharp.BrowserSubprocess.exe" KeyPath="yes" Checksum="yes"/>
  </Component>
  <Component Id="C.Cef.Common.Core"                 Guid="{98a016a2-50cb-4fdb-ae50-46f7f35ac270}">
    <File Id="CefSharp.Core.dll"                    Source="$(var.Path.Cefsharp.Commonx64)\CefSharp.Core.dll" KeyPath="yes" Checksum="yes"/>
  </Component>
  <Component Id="C.Cef.Common.CefSharp"             Guid="{a181bbed-fc28-41c8-868d-8c1dd62dbc46}">
    <File Id="CefSharp.dll"                         Source="$(var.Path.Cefsharp.Commonx64)\CefSharp.dll" KeyPath="yes" Checksum="yes"/>
  </Component>

If I remove them it is working.
  <?define Path.Cefsharp.Commonx64 =              "$(var.Path.Packages)\CefSharp.Common.55.0.0\CefSharp\x64 ?>

Where is the illegal character?

A: Quotes are only a sometimes-required syntax for the value in a preprocessor define.
Since you are missing the trailing quote that you must have intended, the leading one is considered to be part of the value!
<?define Path.Cefsharp.Commonx64 =
  "$(var.Path.Packages)\CefSharp.Common.55.0.0\CefSharp\x64 ?>

I used the candle -p switch to find this out.

A: I don't have terribly much experience with WIX syntax, but according to the documentation the File element needs an exclamation point when identifying payload via named binder paths:
<Component Id="C.Cef.Common.BrowserSubprocess.Core" Guid="{5603fa71-5739-4513-9cba-793a6f6d29ce}">
    <File Id="CefSharp.BrowserSubprocess.Core.dll"  Source="!(var.Path.Cefsharp.Commonx64)\CefSharp.BrowserSubprocess.Core.dll" KeyPath="yes" Checksum="yes"/>
</Component>

Hope this helps!
Source - WIX docs (general)


text:
Q: Selenium IDE testing on maps(Open Layers) I am working on testing an application with open layers maps using Selenium IDE. I researched a lot about clicking on the specific point on the map but I couldn't do it. Can you please provide me some start on this.
Thanks in advance.
Regards,
Rakesh

A: if you don't want to change the open layers code from Selenium IDE you can run your own javaScript functions by using "runScript" as a command and write your javaScript code into the target field (don't use comments as everything is written in one line).
use the following script to fire a mousedown, mouseup and if you need a click event on the map:
var mousedownEvent = document.createEvent('MouseEvents');

mousedownEvent.initMouseEvent('mousedown', true, true, window, 0, 0, 0, yourX, yourY, false, false, false, false, 0, null);

// creates an element from where the clickEvent can be fired
// instead of using pixel you can also refer to your dom-Element by id
document.elementFromPoint(16,118).dispatchEvent(mousedownEvent);

var mouseupEvent = document.createEvent('MouseEvents');

mouseupEvent.initMouseEvent('mouseup', true, true, window, 0, 0, 0, yourX, yourY, false, false, false, false, 0, null);

// same element
document.elementFromPoint(16,118).dispatchEvent(mouseupEvent);

// in some cases a click event needs to be fired as well


text:
Q: Solving $x'=Ax$ for 2x2 matrix with repeated eigenvalues I am trying to find the general solution to the system $x' = Ax$. Here,
$$ A = \begin{pmatrix}
1 & -3\\
3 & -5
\end{pmatrix} $$
Finding the eigenvectors and eigenvalues, I found the eigenvalue of $-2$ to correspond to the eigenvector $  \begin{pmatrix}
1\\
1
\end{pmatrix} $
I am confused about how to proceed to finding the final solution here. Any guidance is greatly appreciated!

A: You have a deficient matrix and need to find a generalized eigenvector.
You have a double eigenvalue of $\lambda_{1,2} = -2$.
Solve for $v_2$ using the row-reduced-echelon-form (RREF) of $$[A-\lambda I]v_2 = [A + 2I]v_2 = v_1 = \begin{pmatrix} 1 \\ 1 \end{pmatrix}$$
Spoiler

 $$v_2 = \begin{pmatrix} \dfrac{1}{3} \\ 0 \end{pmatrix}$$


text:
Q: Defined variable showing NameError when it is used with .click() actually I am trying to built a bot, but getting an unusual error that my fbb_btn is not defined and showing NameError in cmd.
from selenium import webdriver
from time import sleep

from secrets import username, password

class Webot:
    def __init__(self):
        self.driver=webdriver.Chrome()

    def login(self):
        self.driver.get('https://tinder.com')

        sleep(2)

        fbb_btn= self.driver.find_element_by_xpath('//*[@id="content"]/div/div[1]/div/div/main/div/div[2]/div[2]/div/div/span/div[2]/button')

        fbb_btn.click()

fbb_btn.click()
  Traceback (most recent call last):
    File "", line 1, in
  NameError: name 'fbb_btn' is not defined

A: By seeing your error, it seems that the xpath which you have mentioned to find the object for "fbb_btn" is not able to find the button through code.
Try to write xpath using the attributes. You can search how to write dynamic xpath using attributes to overcome this issue.
This is the reason it is giving error as 'fbb_btn' is not defined as the value is set as "None" because given xpath is not found on webpage.

A: I think you are giving wrong x-path,
there is no element with that x-path at facebook.com
there is a x-path only up-to '//*[@id="content"]/div/div1/div/div'
X-path for log in button : //*[@id="u_0_4"]
X-path for sign in button : //*[@id="u_0_13"]


text:
Q: Merging dataframes that are outputs from a for loop in r I have a big dataframe like this (only showing the first three columns):
dataframe is called chr22_hap12
2 1 3
2 1 3
2 1 3
2 1 2
2 2 1
2 2 1

I would like to get the proportion of each number (ones, twos and threes in that order) for every column and store it in a dataframe.
This is what I have so far:
for (i in 1:3 ) {

  length(chr22_hap12[,i]) -> total_snps
  sum(chr22_hap12[,i]==1,na.rm=FALSE) -> counts_ancestry_1
  sum(chr22_hap12[,i]==2,na.rm=FALSE) -> counts_ancestry_2
  sum(chr22_hap12[,i]==3,na.rm=FALSE) -> counts_ancestry_3

  (counts_ancestry_1*100)/total_snps -> ancestry_1_perc
  (counts_ancestry_2*100)/total_snps -> ancestry_2_perc
  (counts_ancestry_3*100)/total_snps -> ancestry_3_perc

  haplo_df[i] = NULL

  haplo_df[i] = c(ancestry_1_perc,ancestry_2_perc,ancestry_3_perc)
  as.data.frame(haplo_df[i])
}

I get these erros: after trying to set haplo_df[i] = NULL

Error in haplo_df[i] = NULL : object 'haplo_df' not found

and after
haplo_df[i] = c(ancestry_1_perc,ancestry_2_perc,ancestry_3_perc)

Error in haplo_df[i] = c(ancestry_1_perc, ancestry_2_perc,
  ancestry_3_perc) :    object 'haplo_df' not found

and again with as.data.frame(haplo_df[i])

object 'haplo_df' not found

My desire output should look like this:
0.00    66.66  50.0
100.00  33.33  33.33
0.00    0.00   16.66

A: You need to define the resulting matrix before the loop and then cbind the new result to that matrix.
# define the data.frame before the loop.
haplo_df <- NULL
for (i in 1:3 ) {
  length(chr22_hap12[,i]) -> total_snps
  sum(chr22_hap12[,i]==1,na.rm=FALSE) -> counts_ancestry_1
  sum(chr22_hap12[,i]==2,na.rm=FALSE) -> counts_ancestry_2
  sum(chr22_hap12[,i]==3,na.rm=FALSE) -> counts_ancestry_3

  (counts_ancestry_1*100)/total_snps -> ancestry_1_perc
  (counts_ancestry_2*100)/total_snps -> ancestry_2_perc
  (counts_ancestry_3*100)/total_snps -> ancestry_3_perc

  # bind the new result to the existing data
  haplo_df <- cbind(haplo_df , c(ancestry_1_perc,ancestry_2_perc,ancestry_3_perc))
}
# return the result
haplo_df
##       [,1]     [,2]     [,3]
##  [1,]    0 66.66667 33.33333
##  [2,]  100 33.33333 16.66667
##  [3,]    0  0.00000 50.00000

Instead you could also just use apply and table, e.g.
apply(chr22_hap12, 2, function(x) 100*table(factor(x, levels=1:3))/length(x))
##     V1       V2       V3
##  1   0 66.66667 33.33333
##  2 100 33.33333 16.66667
##  3   0  0.00000 50.00000

A: My one liner
sapply(df, function(x){prop.table(table(x))*100})

A: Here's an alternative approach.
Sample data:
set.seed(23)
y <- 1:3
df <- data.frame(a = sample(y, 10, replace = TRUE),
                 b = sample(y, 10, replace = TRUE),
                 c = sample(y, 10, replace = TRUE))
#df
#   a b c
#1  2 3 2
#2  1 3 1
#3  1 2 1
#4  3 1 3
#5  3 3 2
#6  2 1 3
#7  3 2 3
#8  3 2 3
#9  3 3 1
#10 3 2 3

Calculate percentages:
newdf <- as.data.frame(t(do.call(rbind, lapply(df, function(z){
  sapply(y, function(x) (sum(z == x) / length(z))*100)
}))))

#newdf
#    a   b   c
#1 0.2 0.2 0.3
#2 0.2 0.4 0.2
#3 0.6 0.4 0.5

A: Try:
mydf
  V1 V2 V3
1  2  1  3
2  2  1  3
3  2  1  3
4  2  1  2
5  2  2  1
6  2  2  1

ll = list()
for(cc in 1:3) {
    dd = mydf[,cc]
    n1 = 100*length(dd[dd==1])/nrow(mydf)
    n2 = 100*length(dd[dd==2])/nrow(mydf)
    n3 = 100*length(dd[dd==3])/nrow(mydf)
    ll[[length(ll)+1]] = c(n1, n2, n3)
}
ll
[[1]]
[1]   0 100   0

[[2]]
[1] 66.66667 33.33333  0.00000

[[3]]
[1] 33.33333 16.66667 50.00000

> t(do.call(rbind, ll))
     [,1]     [,2]     [,3]
[1,]    0 66.66667 33.33333
[2,]  100 33.33333 16.66667
[3,]    0  0.00000 50.00000


text:
Q: Unable to set the value and submit using getElementsByName What I am trying to accomplish is to populate the text box (name of "reason") with the word "TEST" using Tampermonkey.
(I'm very new to using Tampermonkey & Javascript so please be patient with me.)
I am having an issue where the text box isn't populating with the word "TEST" and isn't submitting automatically.
Would you be able to provide assistance?
Let me know if you need anything.
This is my Tampermonkey code:
function ClickURL() {
  var FillF = document.getElementsByName("reason");
  FillF[0].value = "TEST";
  FillF.submit();
}

This is the source of the webpage:

<input class="" type="text" name="reason" required="required" title="">

Edit: Removed unnecessary code


text:
Q: Transfer field data from Contract to Custom object field I want to transfer some of the field data from Contract to Service TimeCard (Custom object) field.
The same field in both the object. Once the contract is created and under that when the service timecard record is generated the (Daily rate and Daily rate offset) data will automatically transfer from Contract to my custom object field.
I had applied the below code.
trigger servicecontract on Contract (after insert) {

list<SFDC_Service_Timecard__c> memberInsertList = new list<SFDC_Service_Timecard__c>();

for (Contract cont : Trigger.new) {

    SFDC_Service_Timecard__c stc = new SFDC_Service_Timecard__c();

    stc.Daily_Rate__c = cont.Daily_Rate__c;
    stc.Offsite_Daily_Rate__c = cont.Daily_Rate_Offsite__c;

    memberInsertList.add(stc);
}
insert memberInsertList;

}


text:
Q: Multiple inserts at a time I have requirement to insert around 2500-3000 rows of data inside a table at a time. I need to do this for both MySQL and SQL Server. So the possible solutions I found is

*

*Writing cfquery inside cfloop.

*Using cfloop inside cfquery to generate sql statement like INSERT INTO tbl VALUES((),(),()) . But the problem with this
syntax is it can only insert 1000 records at a time not more than that. I need more.

Can anyone suggest me Whats the best way to handle this kind of situations?

A: When you are dealing with thousands of records, small incremental delays start adding up quickly. Inserting this number of rows one by one will take considerably more time than issuing a BULK INSERT statement for several reasons like increased network traffic, internal database actions, etc.
I am going to assume that you are receiving your data in a file. In that case, these are the general steps you would need to take:

*

*Validate the data. VERY IMPORTANT. Even if you are receiving data from a trusted source in a trusted environment, files can easily be corrupted, truncated, or damaged in many ways. They can also contain discrepancies due to the small but sometimes significant differences between server versions (SQL Server 2000 vs 2008) or vendors (your source might be an Oracle database).

*Issue a BULK INSERT statement, assuming you are using SQL Server 2005 or newer. I think there are some differences in the way the command works between 2005 and newer versions, so check the syntax before trying it.

*Depending on your configuration and anything else you might need, you may want to update the index(es) on the table, or even recreate them. Again, this depends on how big the table is and your needs. This part of the process will potentially take the longest and may even take the table offline but your users will be very grateful that you did it.

It pays to plan the whole insertion process carefully so that you do not disrupt normal business activities and continue to provide the best service and availability.
As a closing thought, you should run tests using different methods. One-by-one vs bulk to make sure you are getting the best performance. I believe, however, that you'll always find that batches or bulk insertions are the way to go. The reason they added that capability into the Transact-SQL language is performance. This will save network bandwidth, resources, and time.

A: In SQL Server (at least 2008 and above) you can insert multiple rows at one time through a single INSERT statement:
INSERT INTO mytable (column1, column2) VALUES (value1, value2), (value3, value4);

I don't know if there is a limit (such as 1000) on the number of rows that can be inserted at once, but I agree with @RhysJones that you might want to limit to, say, 100 rows at a time in case an error is encountered - this will make it much easier to spot the error and correct it.
Since you're using ColdFusion, my recommendation would be to loop over the rows of the external file 100 at a time:
 <cfquery name="q_insert_rows">
    INSERT INTO mytable ( column1, column2, column3 )
    VALUES
    <cfloop query="external_data" startrow="#startrow#" endrow="#endrow#">
        ( <cfqueryparam cfsqltype="CF_SQL_VARCHAR" value="#value1#" />
        , <cfqueryparam cfsqltype="CF_SQL_VARCHAR" value="#value2#" />
        , <cfqueryparam cfsqltype="CF_SQL_VARCHAR" value="#value3#" /> )
        <cfif currentRow NEQ endrow> , </cfif>
    </cfloop>
 </cfquery>

The <cfquery> block above should be put inside a loop:
<cfloop from="1" to="#external_data.recordCount#" step="100" index="startrow">
    <cfset endrow = min(startrow + 99, external_data.recordCount) />
    ...
</cfloop>

If you want the whole thing to fail if one insert fails, then wrap the above loop in <cftransaction>.

A: You've tagged this with MySQL, so I'm presuming that you're using MySQL. I've had experience with this sort of issue as well, where we were importing our HR information from an external database. I found that it was significantly faster to validate the data, store it in a CSV file, and import that using the LOAD DATA INFILE syntax.

A: If possible, use a more appropriate tool to solve this problem instead of hammering away at it with ColdFusion.
SQL Server has the ability to directly import the contents of a spreadsheet.

Once connected to Sql Server 2005 Database, From Object Explorer Window, right click on the database which you want to import table into. Select Tasks -> Import Data. This is a simple tool and allows you to 'map' the incoming data into appropriate table. You can save the scripts to run again when needed.

You should be able to create a function in SQL Server that you can call from ColdFusion, passing in the location of the spreadsheet on your server (in a non-web-accessible folder, of course).
For MySQL, as Paul Rowe already stated, use the LOAD DATA INFILE syntax. Another SO answer suggests using the Windows based HeidiSQL to craft the statement via a UI to get the correct mappings.

A: Just don't use the multi-values version of INSERT. Use 1 INSERT statement per row, i.e.
INSERT INTO tbl VALUES(...);
INSERT INTO tbl VALUES(...);
INSERT INTO tbl VALUES(...);


text:
Q: Export and import resharper 6.0 settings I've recently installed resharper 6.0. It took my long time to set up everything as I wanted. Now I want to export all this settings to another computer. I've tried this aproach without any success (might be because the computers use different versions of visual studio?). Then I found this in this answer. But RSM works for r# 5. I started reading to see if there is going to be RSM for r# 6.0 and there will not be because in r# 6.1 some settings management options are included. But I'm stick with r# 6.0.. Is there any way I can transfer my settings from one PC to another?

A: Now you may want to update to ReSharper 6.1 where the management of settings are improved including an export and import feature.

A: You didn't explain what you meant by "without any success".

*

*Were you able to find the folders and copy the files?

*Were there files already in the target directory? (If there weren't, you probably had the wrong directory.)

*Did you diff the old and new files as a sanity check? (This would be especially important since you're apparently expecting this to work even when the two machines aren't running the same version of Visual Studio. There could easily be differences in the file format across VS versions.)

*Did you make sure to close Visual Studio before copying the files?

*Did you just copy files in ReSharperVersion\VisualStudioVersion, or did you also copy the files in the vAny directory?

At any rate, if you really can't copy the global settings files, and if you can't install 6.1 (why not? it's a free upgrade from 6.0), I think your only other option is to export and import your coding-style settings by going to ReSharper > Options > Languages > Common > Code Style Sharing. That won't get all the ReSharper settings, but it will get some of the most important ones.


text:
Q: css postioning a box in between of its parent This is my code snippet :
Html

        Additional Comments :

        balallalalalallalalalala

        jaslnflkasnlsnlksanlknslnwkin

        lknlkanfklnlk

CSS:
div {
    color:white;
}
.app-cont {
    background: black;
    width: 90%;
    padding-top: 2.5px;
    padding-bottom: 2.5px;
    margin-bottom: 5px;
    -moz-border-radius: 5px;
    border-radius: 5px;
}
.app-head {
    background: #484848;
    width: 25%;
    margin-bottom: auto;
    display: inline-block;
    border-top-right-radius:2px;
    -moz-border-top-right-radius:2px;
    border-bottom-right-radius:2px;
    -moz-border-bottom-right-radius:2px;
}
.app-main {
    display: inline-block;
    text-align: justify;
}

demo
It works till i dont add enough content on the div with class app-main. But when i add enough content in the div the div with class app-head gets to the bottom.
While i want it in the middle.
How can i do this ?

A: Just add vertical align style.
.app-head,.app-main{
    vertical-align:middle;
}

You can use it on inline-block elements to position near other inline-block elements or near inline elements.

A: Well I wasn't sure entirely what the goal was, but if I understood you correctly, you wanted to keep the block holding the additional comments text in the middle of the text to the right?
I've updated your fiddle to see if I've got the solution you need: Updated Fiddle
I've positioned .app-head absolutely, and used a top:50% and a negative margin to keep it centred vertically. You also have to give .app-cont a relative position for this to work, and the comments section needs a left-margin slightly greater than the width of .app-head.
Anyway, hope that helps!

A: I did some other changes as well..
http://jsfiddle.net/Ues8Q/4/
..but the main idea is this:
Outer container has: position: relative;
The thing you want to center has: position: absolute; left: 0px; top: 50%; margin: -exactly half of the height of this element; height: whatever it is;
and requirement is that the element you want to center has fixed height...


text:
Q: PHPExcel Multi Sheet Loop Issue I'm developing a small class that will allow you to pass queries and it will create a worksheet for each query.
FYI: This class is still in development and I will be reducing down into smaller functions.
My issue is that for some reason my sheet increment is off and I cant figure out where to put it.
I am calling my class like this:
$ex2 = new ExportToExcel2('Somefile');
$ex2->AddSheet('Sheet1', 'Select * from Division;');
$ex2->AddSheet('Sheet2', 'Select * from Zone');
$ex2->ExportMultiSheet();

I should have two tabs, "Sheet1" and "Sheet2". This is how my sheet ends up looking. All the data is on Sheet1 and Worksheet.

Here is my class:
class ExportToExcel2 {

    public $AllSheetData = [];
    protected $SheetData = [];
    protected $PHPExcel = '';
    protected $FileName = '';

    function __construct($_filename) {
        $this->FileName = $_filename;
        $this->PHPExcel = new PHPExcel;
    }

    public function AddSheet($_WorkSheetName, $_Query) {
        $this->SheetData['Sheet_Name'] = $_WorkSheetName;
        $this->SheetData['Query'] = $_Query;
        $this->AllSheetData[] = $this->SheetData;
        unset($this->SheetData);
    }

    public function ExportMultiSheet() {

        $Result='';
        $count=0;
        $this->PHPExcel->setActiveSheetIndex(0);
        foreach($this->AllSheetData as $subarray)
        {

            foreach($subarray as $key => $value)
            {

                if($count>0)
                {
                    $this->PHPExcel->createSheet($count);
                    $this->PHPExcel->setActiveSheetIndex($count);
                }

                if($key == 'Query') {

                    $Result = dbQuery($value);

                    //set header row
                    $row = 1; // 1-based index
                    $row_data = sqlsrv_fetch_array($Result, SQLSRV_FETCH_ASSOC);
                    $col = 0;
                    foreach(array_keys($row_data) as $key) {
                        $this->PHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, $row, $key);
                        $col++;
                    }

                    //set body rows
                    $row2 = 2;
                    while($row_data = sqlsrv_fetch_array($Result, SQLSRV_FETCH_ASSOC)) {
                        $col2 = 0;

                        foreach($row_data as $key=>$value) {
                            $this->PHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col2, $row2, $value);
                            $col2++;
                        }
                        $row2++;
                    }

                    $count++;
                }
                if($key =='Sheet_Name')  {
                    $this->PHPExcel->getActiveSheet()->setTitle($value);
                }

                //set all columns to align left
                $this->PHPExcel->getDefaultStyle()->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_LEFT);

                //show gridlines?
                $this->PHPExcel->getActiveSheet()->setShowGridlines(true);

                //set columns a through z to auto width
                for($col = 'A'; $col !== 'Z'; $col++) {
                    $this->PHPExcel->getActiveSheet()
                        ->getColumnDimension($col)
                        ->setAutoSize(true);
                }
            }

        }

        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="01simple.xls"');
        header('Cache-Control: max-age=0');
        $objWriter = PHPExcel_IOFactory::createWriter($this->PHPExcel, 'Excel2007');
        $objWriter->save('php://output');

        exit;
    }
}

Any ideas on where to place my $count++?
Solved, Here is the finished class(until its not finished again)
class ExportToExcel2 {

    public $AllSheetData = [];
    protected $SheetData = [];
    protected $PHPExcel  = '';
    protected $FileName  = '';

    function __construct($_filename) {

        $this->FileName = $_filename;
        $this->PHPExcel = new PHPExcel;

        //clean the output buffer before download
        ob_clean();
    }

    public function AddSheet($_WorkSheetName, $_Query) {
        $this->SheetData['Sheet_Name'] = $_WorkSheetName;
        $this->SheetData['Query'] = $_Query;
        $this->AllSheetData[] = $this->SheetData;
        unset($this->SheetData);
    }

    public function ExportMultiSheet($_ExportType='xls') {
        if(!empty($this->AllSheetData)) {
            $count=0;$Result='';
            $this->PHPExcel->setActiveSheetIndex(0);
            foreach($this->AllSheetData as $subarray) {

                if($count>0){
                    $this->PHPExcel->createSheet(null);
                    $this->PHPExcel->setActiveSheetIndex($count);
                }
                $count++;
                foreach($subarray as $key => $value) {

                    if($key == 'Query') {
                        $Result = dbQuery($value);
                        $this->SetHeaderCells($Result);
                        $this->SetbodyCells($Result);

                    }
                    if($key =='Sheet_Name')  {
                        $this->PHPExcel->getActiveSheet()->setTitle($value);
                    }

                }
            }

            $this->ExportType($_ExportType);
        }
    }

    public function ExportSingleSheet($_Query, $_ExportType='xls') {
        $Result = dbQuery($_Query);
        $this->SetHeaderCells($Result);
        $this->SetBodyCells($Result);
        $this->SetProperties();
        $this->ExportType($_ExportType);
    }

    private function ExportType($_ExportType) {
        if($_ExportType=='xls') {
            $this->DownloadXLS();
        }
        else if($_ExportType=='csv') {
            $this->DownloadCSV();
        }
    }

    private function SetProperties() {

        //set all columns to align left
        $this->PHPExcel->getDefaultStyle()->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_LEFT);

        //show gridlines?
        $this->PHPExcel->getActiveSheet()->setShowGridlines(true);

        //set columns a through z to auto width
        for($col = 'A'; $col !== 'Z'; $col++) {
            $this->PHPExcel->getActiveSheet()
                ->getColumnDimension($col)
                ->setAutoSize(true);
        }

        //set the first sheet to open first
        $this->PHPExcel->setActiveSheetIndex(0);
    }

    private function DownloadXLS() {
        $this->SetProperties();
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="'.$this->FileName.'-'.date("y.m.d").'.xls"');
        header('Cache-Control: max-age=0');
        $objWriter = PHPExcel_IOFactory::createWriter($this->PHPExcel, 'Excel2007');
        $objWriter->save('php://output');

        exit;
    }

    private function DownloadCSV() {
        $this->SetProperties();
        header('Content-Type: text/csv');
        header('Content-Disposition: attachment;filename="'.$this->FileName.'-'.date("y.m.d").'.csv"');
        header('Cache-Control: max-age=0');
        $objWriter = new PHPExcel_Writer_CSV($this->PHPExcel);
        $objWriter->save("php://output");

        exit;
    }

    private function SetHeaderCells($Result) {
        $row = 1; // 1-based index
        $row_data = sqlsrv_fetch_array($Result, SQLSRV_FETCH_ASSOC);
        $col = 0;
        foreach(array_keys($row_data) as $key) {
            $this->PHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, $row, $key);
            $col++;
        }
    }

    private function SetBodyCells($Result) {
        $row2 = 4;
        while($row_data = sqlsrv_fetch_array($Result, SQLSRV_FETCH_ASSOC)) {
            $col2 = 0;

            foreach($row_data as $key=>$value) {
                $this->PHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col2, $row2, $value);
                $col2++;
            }
            $row2++;
        }
    }
}

A: You should first move the sheet generation code from the foreach($subarray loop to your foreach($this->AllSheetData (since you want to add new sheet for every.. well.. new sheet. Not for every new sheet property).
You should then use a very similar code to the one you had, and $counter will be used only within that part of the code. Note that to create a new sheet and place is as the last one, you should simply pass null to the createSheet() method.
So your code should look like this:
public function ExportMultiSheet() {

    ...
    $count = 0;
    foreach($this->AllSheetData as $subarray)
    {
      if ($count > 0)
      {
          $this->PHPExcel->createSheet(null);
          $this->PHPExcel->setActiveSheetIndex($count);
      }
      $count++

      foreach($subarray as $key => $value)
      ...
    }
    ...


text:
Q: Импорт *.csv файла в MySQL $import = "LOAD DATA INFILE '/sata2/home/users/xn80akhml/www/test.xn--80akhmlofgv.net/database_EDRSR/regions.csv' INTO TABLE edrsr FIELDS TERMINATED BY '\t' optionally ENCLOSED BY '\"' LINES TERMINATED BY '\n' IGNORE 1 LINES (region_code, name)";
$mysqli->query($import);
echo mysqli_error($mysqli);

Ошибка: "Access denied for user ....."
Пробую так
if (($handle = fopen("database_EDRSR/documents.csv", "r")) !== FALSE) {
        while (($dataFile = fgetcsv($handle, 0, "\t")) !== FALSE) {
            $value .= "('".$dataFile[0]."', '".$dataFile[1]."'),";
        }
        fclose($handle);
    }
$values = substr($values, 0, -1);
 $insert = "INSERT INTO edrsr_documents (doc_id, regions) VALUES $values";
    $mysqli->query($insert);

Вставляется только половина и ошибка
Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 14645586 bytes) in
или
504 Gateway Time-out
csv файл 500000 строк. Каждый день добавляются новые строки, изменяются имеющиеся. Нужно импортировать каждый день. К концу года будет около 5000000 строк. Подскажите как правильно импортировать?

A: *

*Может не быть привилегии доступа FILE (можно проверить, выполнив запрос SHOW GRANTS)

*Есть привилегия, но установлена переменная secure_file_priv и файл лежит не в указанной директории (или переменная установлена в NULL - тогда LOAD FILE будет отключен)

См. также

*

*Системные переменные сервера (secure_file_priv) (по-английски)

*Привилегии (FILE) (по-английски)

*Синтаксис GRANT (по-английски)


text:
Q: Unable to perform batch update from jdbc template in mariadb I have piece of code which is working fine with oracle db but giving exception SQL state [HY000]; error code [1205]; (conn=30) Lock wait timeout exceeded; try restarting transaction; nested exception is java.sql.BatchUpdateException: (conn=30) Lock wait timeout exceeded; try restarting transaction when trying to execute with mariadb . I have tried multiple solutions i.e. increased innodb_lock_wait_timeout , changed the @@GLOBAL.tx_isolation, @@tx_isolation but still getting the same error . Here is the code which is working fine with orcale but giving exception with mariadb:
    public void updateFailureData(final Long mId, final Set<String> errorVals)  {
        try {
            this.jdbcTemplate.batchUpdate("UPDATE MARKETS SET ERR_VALS = ? WHERE M_ID = ?", new BatchPreparedStatementSetter() {

                @Override
                public void setValues(final PreparedStatement preparedStatement, final int arg1) throws SQLException {
                    int index = 1;
                    preparedStatement.setString(index++, StringUtils.join(errorVals, ","));
                    preparedStatement.setLong(index, mId);
                }

                @Override
                public int getBatchSize() {
                    return 1;
                }
            });
        } catch (DataAccessException dataAccessException) {
            System.out.println("Updating errorVals.", dataAccessException);
        }
    }

Is there anything which can be done or I am missing ?


text:
Q: How to detect @ in keydown or keypress in jquery I was trying to use the keypress or keydown event on '@' to generate a dropdown on a contenteditale  div. But I didnot find the key code for '@' and i cannot use shift and 2 beacause it will be problem for many keyboard layout including mobile keyboard layout

A: You can look for the keycode for @ which is decimal 64 in jQuery's e.which:
$(document).on("keypress", function(e) {
    // look for @ key
    if (e.which === 64) {
        alert("@ key pressed");
    }
});

Working demo: http://jsfiddle.net/jfriend00/s7KGb/

You could also code it like this which might be a bit more readable:
$(document).on("keypress", function(e) {
    // look for @ key
    if (String.fromCharCode(e.which) === '@') {
        alert("@ key pressed");
    }
});


text:
Q: Hide html element when specific resolution I am using twitter bootstrap 3.0. When resolution of the screen gets changed to smaller the menu changed to mobile view. I have a div contained slider with images, so I want to hide that div when my menu changed to mobile view (when screen resolution small).
I tried to apply css classes on my div visible-desktop visible-tablet but it is not working.
Is there other way I can do?

A: Consider using media queries.  Something like
@media screen and (max-width:480px) {
    .mydiv {display:none}
}

A: You just have to apply the Bootstrap classes as seen here.   You can test them there also, if you resize your browser screen you can check wich ones are active.

This is the div that will hide on mobile

Should only be seen in any screen bellow 768px (mobiles)

A: 2021 update / Bootstrap 5.1
See Display property - Hiding elements
To hide an element on extra-small (portrait mobile) screen widths, use

That is hidden by default (.d-none) but visible on small or larger devices.

Original 2013 answer
If you're using Bootstrap v3, they changed the responsive utility class names. See http://getbootstrap.com/css/#responsive-utilities
You probably want .hidden-xs
This was also documented in Migrating from 2.x to 3.0

A: You can put in the class of that div .hidden-xs.. It's more simple. You are only telling that this div is visible on desktop and tablets, and not telling that it isn't visible in small devices.


text:
Q: python regex to remove and obtain required string Using regex i need to filter the following random input:
<_io.TextIOWrapper name='C:/Python34/abcd.txt' mode='w' encoding='cp1252'>

to
C:/Python34/abcd.txt

How can i do in regex to abtain the selected portion?

A: If you need to do this using regex, you can use the following:
>>> import re
>>> s = "<_io.TextIOWrapper name='C:/Python34/abcd.txt' mode='w' encoding='cp1252'>"
>>> re.search(r"<[^>]*\bname='([^']*)", s).group(1)
'C:/Python34/abcd.txt'

Explanation:
This matches a beginning bracket, everything up to name and captures whats inside single quotes. A word boundary \b does not consume any characters, it asserts that on one side there is a word character, and on the other side there is not.
<         # '<'
[^>]*     # any character except: '>' (0 or more times)
\b        # the boundary between a word character (\w) and not a word character
name='    # 'name=\''
(         # group and capture to \1:
  [^']*   #   any character except: ''' (0 or more times)
)         # end of \1

A: You could use lookbehind also. It matches the string which was just after to name=' upto the next ' symbol.
>>> import re
>>> s = "<_io.TextIOWrapper name='C:/Python34/abcd.txt' mode='w' encoding='cp1252'>"
>>> m = re.search(r"(?<=name=\')[^\']*", s)
>>> m
<_sre.SRE_Match object at 0x7fa131e6f370>
>>> m.group()
'C:/Python34/abcd.txt'

A: I feel like this isn't random, but here you go:
import re
string = "<_io.TextIOWrapper name='C:/Python34/abcd.txt' mode='w' encoding='cp1252'>"
regexString = r'<\S+ \s+ name=\'(?P<name>.*?)\'.*?>'
regex       = re.compile(regexString, re.X)
match       = regex.match(string)
if match != None:
    myName = match.group('name')


text:
Q: Generar PDF en base a codigo HTML me encuentro en un problema y recurro a ustedes para ver posibles soluciones.
Trabajo en una aplicación con Ionic (v1) y dentro de la app tengo un template HTML prototipo, de uno de los flujos sale la data que nosotros mostramos en el pdf. Obtengo el codigo html del template asi
$http.get('app/modules/Test/views/comprobante.html', {
    cache: $templateCache
})
.then(function(result) {
     console.log(result.data);

});

El valor de result.data es el codigo HTML puro y para reemplazar los valores utilizo palabras claves y las remplazo con el tipico replace
Esto funciona muy bien, ademas utilizamos un plugin pdf-generator para de todo ese texto HTML obtenemos un archivo pdf en base64 y eso lo subimos al servidor.
Ahora bien, se nos solicito ademas la versión web de la aplicación (browser) y como saben, los plugins cordova que no tienen soporte para esta platforma simplemente no funcionan, por lo que este proceso que explique no funciona. Intente implementar la libreria jsPDF pero no cumple con lo que necesito, de ese texto html que obtengo no genera un PDF correcto, más bien vacio y me imagino que es porque no interpreta el codigo html como tal.
Existirá alguna manera de hacer este proceso desde javascript? Obtener desde un archivo HTML un pdf en base64 y luego poder subirlo al servidor?
Quedo atento a cualquier duda.


text:
Q: Importing from a web page that seems to expect specific browsers I've successfully and fruitfully imported data from web sites before, but now seem to have a particularly troublesome site that I would like to access through Mathematica on my MacBook.
Import[site="https://auctionfiling.fcc.gov/form175/search175/index.htm"]

returns the error:
FetchURL::httperr: The request to URL
https://auctionfiling.fcc.gov/form175/search175/index.htm was not successful.
The server returned the HTTP status code 500 ("Internal Server Error").

Exploring further, the command URLExecute[site] returns an long exception report that includes the text:
<cflog text="#Variables.errorTemplate#: UnsupportedBrowser The
browser you are using is not supported. <br>The error occurred on
line 32." type="error">

Further text indicates that the site requires either: Microsoft Internet Explorer 5.5 (or higher), Netscape 6 (or higher), Opera 6 (or higher), or Mozilla. Though I've successfully used it with Safari, Chrome and Firefox.
Is there a way around this? I am wanting to pull down many thousands of FCC license records through this approach.
Alternatively, perhaps there is an approach of running an external browser linked with Mathematica?
Thank you for any suggestions.
Steve

A: Posting J.M.'s comment as an answer, you can specify the user agent string in HTTPRequest directly via "UserAgent" (here it is for Firefox 40.1 taken from this site):
URLRead[HTTPRequest[
  "https://auctionfiling.fcc.gov/form175/search175/index.htm", <|
   "UserAgent" ->
    "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.1"|>]]

(note that the code in the comments is broken due to hidden Unicode characters).
It is worth to know that

The default "UserAgent" is typically "Wolfram HTTP Client xxxx", where xxxx is a version number.

A:
Alternatively, perhaps there is an approach of running an external browser linked with Mathematica?

This seems to be possible since v12.0, using WebExecute. You can find it in the new-features page of v12, under "Controlling Web Browsers" and described shortly as "execute commands in a web browser".
I don't know whether this would have been sufficient for your purposes (and, I would suspect, it's too late for your original task). But it's an interesting option to consider for similar problems.


text:
Q: Isomorphism of structures I am working on this problem :
Let $N$ be the $L_{0}$-structure $(\mathbb{N} ,<)$, where $\mathbb{N}$ is the set of non-negative integers, and let $M$ be the $V_{0}$-structure $({\mathbb{N}} - 0, <)$ (where $<$ is the usual inequality relation on $\mathbb{N}$. Show the following :

*

*(1) $M \cong N$

*(2) $M \equiv N$

*(3) $M$ is a substructure of $N$

*(4) $M$ is not an elementary substructure of $N$.

I know that I need to find an isomorphism between the structures in order to show (1)(is that enough?) and then (1) and (2) are equivalent, however I am struggling to do the whole proof in detail. Also (3) and (4) confused me.
Any help?
Thank you in advance!


text:
Q: Python3: class member function call preceded by class member variable? I'm trying to program a Montecarlo Tree Search implementation for a TicTacToe.
I'm using the code from this page as an example to test initially.
So basically I'm getting an error when program tries to execute
self._untried_actions = self.state.get_legal_actions()
Error is AttributeError: 'list' object has no attribute 'get_legal_actions'.
State variable is supposed to by a 3x3 array, representing the board of TicTacToe.
Get_legal_actions() is another member function of the MonteCarloTreeSearchNode class that returns a list of all possible moves (all 0's in the array). It's only parameter is "self".
So basically for me it makes no sense to call the function like this, instead it should be something like self._untried_actions = self.get_legal_actions(self.state).
Code is suppose to work like this so what am I missing?
class MonteCarloTreeSearchNode():
    def __init__(self, state, parent=None, parent_action=None):
        self.state = state
        self.parent = parent
        self.parent_action = parent_action
        self.children = []
        self._number_of_visits = 0
        self._results = defaultdict(int)
        self._results[1] = 0
        self._results[-1] = 0
        self._untried_actions = None
        self._untried_actions = self.untried_actions()
        return

    def untried_actions(self):

        self._untried_actions = self.state.get_legal_actions()
        return self._untried_actions


text:
Q: Oracle 12c PLSQL MERGE error The below code snippet is from a larger procedure of mine. When I execute this procedure manually in TOAD it works without error as I would expect.
I am now trying to put it into a form for the user - however when I try to compile it I get the following error on the MERGE line:
"Encountered the symbol "INTO" when expecting one of the following:
:=.(@%;"
MERGE INTO count_balance cb
USING (select location_code, product_code, closing_stock
       from trd_stock_closing ts
      where period = gen.add_periods(p_period, -1)
        and exists (select null
                      from ag_product_view
                     where product_code = ts.product_code
                       and group_code = 'Q')) cs
ON (cb.location_code = cs.location_code AND cb.product_code = cs.product_code)
WHEN MATCHED THEN
UPDATE SET cb.opening_stock = cs.closing_stock
WHEN NOT MATCHED THEN
INSERT (location_code, product_code, opening_stock)
VALUES (cs.location_code, cs.product_code, cs.closing_stock);

Can someone advise?

A: It looks like you're trying to use good old Oracle*Forms, which have no support for MERGE statement at all. Try either use the newer version of Forms or wrap this code into stored procedure.


text:
Q: Wolfram Alpha result for infinite series summation . Consider the infinite sum $s=1+1/2^2-1/3^2-1/4^2+1/5^2+1/6^2-...$. We can see that the series is absolutely convergent and hence convergent. But WolframAlpha seems to give me a different answer. When I add two more terms it shows me that the series converges. Can anyone explain why this happens and also give an analytical expression for the sum ?

A: Wolfram alpha guessed your general term wrong. If you look at the cell titled "Result", you see the general term
$$\frac{-54-(-7+n)n(16+(-7+n)n)}{n^2}$$
instead of what you intended.
Try instead inputting the sum directly.
We can compute the sum explicitly by computing four related sums using Wolfram alpha:
$$
\begin{align*}
S_0 &= \sum_{n=1}^\infty \frac{1}{n^2} = \frac{\pi^2}{6}, \\
S_1 &= \sum_{n=1}^\infty \frac{i^n}{n^2} = -\frac{\pi^2}{48} + Ci, \\
S_2 &= \sum_{n=1}^\infty \frac{(-1)^n}{n^2} = -\frac{\pi^2}{12}, \\
S_3 &= \sum_{n=1}^\infty \frac{(-i)^n}{n^2} = -\frac{\pi^2}{48} - Ci,
\end{align*}
$$
where $C$ is Catalan's constant.
The sum we are after is
$$
\left(-\frac{1}{2}-\frac{1}{2}i\right)S_1 + \left(-\frac{1}{2}+\frac{1}{2}i\right)S_3 = \frac{\pi^2}{48} + C.
$$

A: $$\sum_{n\geq0}\left(-1\right)^{n}\left(\frac{1}{\left(2n+2\right)^{2}}+\frac{1}{\left(2n+1\right)^{2}}\right)=\sum_{n\geq0}\frac{\left(-1\right)^{n}}{\left(2n+2\right)^{2}}+\sum_{n\geq0}\frac{\left(-1\right)^{n}}{\left(2n+1\right)^{2}}=\frac{1}{4}\sum_{n\geq1}\frac{\left(-1\right)^{n+1}}{n^{2}}+C=\frac{1}{4}\eta\left(2\right)+C$$
 where $C$
  is the Catalan constant and $\eta$
  is the Dirichlet eta funcion. Using the identity$$\eta\left(s\right)=\left(1-2^{1-s}\right)\zeta\left(s\right)$$
  with $$\textrm{Re}\left(s\right)>1,$$
  and $\zeta$ is the Riemann zeta function we have$$\eta\left(2\right)=\frac{1}{2}\zeta\left(2\right)=\frac{\pi^{2}}{12}$$
 so$$\sum_{n\geq0}\left(-1\right)^{n}\left(\frac{1}{\left(2n+2\right)^{2}}+\frac{1}{\left(2n+1\right)^{2}}\right)=\frac{\pi^{2}}{48}+C.$$


text:
Q: Unable to locate the requested element: By.xpath: //*[@id="SF-Refresh"] I have been trying to get my Automation Tests up and Running but keep running into some Xpath Errors. I am having 5 errors all with missing/not being able to locate the Xpath that I have wrote. I need to have my test click on a "Refresh" Button located in a data table that is located on the Web page. Button instead of clicking on the button I get the error below. The ID of the button is "SF-Refresh" .
@When("I click refresh button")
@Given("I click refresh button")
@Then("I click refresh button")
public void clickRefreshButton() {
    By linkSelect = new By.ByXPath("//*[@id=\"SF-Refresh\"]");
    try {
        Thread.sleep(5000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    LightningButton.click(linkSelect);

}

Error:
Unable to locate the requested element: By.xpath: //*[@id="SF-Refresh"]

A: There is few possible error as below:
1) The Xpath is might wrong or same Xpath return multiple elements, the xpath must return one element only if you are using findElement
2) The element is might not load properly yet or not ready for action use below:
    WebDriverWait wait = new WebDriverWait(driver, 30);
    wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[@id="SF-Refresh"]")));
    wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//*[@id="SF-Refresh"]")));
    LightningButton.click(linkSelect);


text:
Q: Multiple Conditional mapping in Automapper I need a little help with some mappings I am doing.
I am mapping a Model which has two fields
public ProductCategory
public string FirstType
public string SecondType

to another Model which has only one field
public string ProductType

Now I have to map the First or Second Type to ProductType based on a the content of ProductCategory.And if the condition is not met the ProductType should be null
For example I need something like this:
.ForMember(dest => dest.ProductType, opt => opt.MapFrom(src =>
{
   if (src.ProductCategory.Equals("something")
     {
        src.FirstType
     }
   else if (src.ProductCategory.Equals("something")
     {
        src.SecondType
     }
   else
    {
       null
    }
}))

Of course the syntax is completely wrong and obviously won`t work , I just wanted to explain what I am trying to achieve.
I have a temporary solution
.ForMember(dest => dest.ProductType, opt => opt.MapFrom(src => src.ProductCategory.Contains("something") ? src.FirstType: src.SecondType))

but it is not completely what I need.
Any suggestions?
Thanks in advance

A: What you can do to avoid making the map code look very tangled is to actually separate it into methods that you actually know require some checking for the right value to be assigned.
Here's the code
.ForMember(dest => dest.ProductType, opt => opt.MapFrom(src => CalculateProductCategory(src.ProductCategory))) and then you write your own CalculateProductCategory

And your method would look something like this
    public ProductType CalculateProductCategory(ProductCategory category) {

    if (productCategory.Equals("something")
    {
        return FirstType
    }
    else if (productCategory.Equals("something")
    {
        return SecondType
    }
    else
    {
       return null
    }

}


text:
Q: Using Chef, limiting user access to certain servers/environments I've got a use case where I have a contractor who needs ssh and sudo access to one server, but not to our other servers. All of our servers are managed by Chef, and we use databags to configure each user. Any tips on the best way to approach this?

A: As always, there is a large variety of possibilities :-)
Here is, how we configure per-node user access based on a users data bag.

*

*All users with group: sysadmin are automatically assigned to all nodes with sudo privileges.

*All other users are added based on their assignment to particular hosts. The users data bag is
searched for items that contain an entry for node['fqdn'] in the "nodes" key of the data bag:

{
    "id": "a-srv123-admin",
    ...
    "nodes": {
            "srv123.typo3.org": {
                    "sudo": "true"
            }
    }
}

In order to remove a user from all nodes, action: remove can be set
on the highest level:
{
    "id": "a-user-to-remove",
    "action": "remove"
}

In order to remove a user from a certain node, action: remove can be set
on the node level:
{
    "id": "a-user-to-remove",
    ...
    "nodes": {
            "srv123.typo3.org": {
                    "action": "remove"
            }
    }
}

The implementation of this (not very clean in truth, unfortunately), just searches for all users associated with the node[fqdn]:
node_attribute = "fqdn"
log "Searching for users associated with node #{node[node_attribute]}"
begin
  users = search(users_databag_name, "nodes:#{node[node_attribute]}")
rescue Net::HTTPServerException
  Chef::Log.warn "Searching for users in the 'users' databag failed, search for users associated with node '#{node[node_attribute]}'"
  users = {}
end

users.each do |u|
  node_options = u['nodes'][node[node_attribute]]
  Chef::Log.info "Got node options: #{node_options}"
  if u['action'] == "remove" || node_options['action'] == "remove"
    user u['username'] ||= u['id'] do
      action :remove
    end
  else
    # snip...

    # Create user object.
    user u['username'] do
      uid u['uid'] if u['uid']
      gid u['gid'] if u['gid']
      shell u['shell']
      comment u['comment']
      password u['password'] if u['password']
      supports manage_home: true
      home home_dir
      action u['action'] if u['action']
    end

    # sudo management
    if node_options['sudo'] == "true"
      sudo u['username'] do
        nopasswd true
        user u['username']
      end
    else
      sudo u['username'] do
        action :remove
      end
    end
  end
end

EDIT: Be warned that any user with access to Chef's client certificate can query data based on what the client can read. This can include passwords that are stored in other node's attributes. RBAC or chef-vault can mitigate this.


text:
Q: How do I save structured data to file? My program contains a huge precomputation with constant output. I would like to avoid running this precomputation in the next times I run the program. Thus, I'd like to save its output to file in the first run of the program, and just load it the next time I run the program.
The output contains non-common data types, object and structs I defined myself.
How do I go about doing that?

A: A de-facto standard way for (de-)serializing rust objects is serde. Given a rust struct (or enum) it produces an intermediate representation, which then can be converted to a desired format (e.g. json). Given a struct:
use serde::{Serialize, Deserialize};

// here the "magic" conversion is generated
#[derive(Debug, Serialize, Deserialize)]
struct T {
    i: i32,
    f: f64,
}

you can get a json representation with simple as oneliner:
let t = T { i: 1, f: 321.456 };
println!("{}", serde_json::to_string(&t).unwrap());
// prints `{"i":1,"f":321.456}`

as well as converting back:
let t: T = serde_json::from_str(r#"{"i":1,"f":321.456}"#).unwrap();
println!("i: {}, f: {}", t.i, t.f);
// prints i: 1, f: 321.456

Here is a playground link. This is an example for serde_json usage, but you may find other more suitable libraries like serde_sbor, serde_yaml, bincode, serde_xml and many many others.

A: You would want to use something like serde to serialize the data, save it to disk, and then restore it from there on the next run. In particular, bincode, is useful to serialize the data in the binary format which saves much more space than JSON or other human readable format. But, you have to be careful not to use old serialized data if you have changed the layout of the structures in your program.
For more in depth, I would go to Serde's documentation, but the basic idea is to mark all your structures that need saving with #[derive(Serialize, Deserialize)], and use bincode to do the serialization/deserialization. Playground link for an example I wrote using serde_json (as bincode is not available in rust playground), but bincode is no different, other than using serialize and deserialize as opposed to to_vec and from_slice.


text:
Q: Digital time to readable duration using javascript I'm using clockpicker to collect user input that will give me a digital timestamp in a string.
For example:
02:15

I would like to keep that as is in the database but in my view print it as, using this example:
2h 15m

Unnecessary zero's removed, spaced and with added "h" for "hours" and "m" for "minutes". Also if no hours would be specified I'd prefer only getting the minutes, and vice versa if no minutes is specified.
All examples I seem to find is about converting a complete timestamp using "Date" function in JavaScript. I don't seem to be able to use that with just this value and I'm terrible with regex.
I would like to find an elegant way, perhaps a one line regex to replace it before rendering my view. I'd prefer not using any additional libraries.
Any help appreciated!

A: I seem to have managed anyway.
It's not as pretty as I would like it to be, but it works, and It's technically a one line regex.
  t = "00:05";
  t2 = "01:00";
  t3 = "12:10";
  t4 = "02:02";

  const replaceTime = (myString) => {
    myString = myString.replace(/0?([1-9]{0,}[0-9]):0?([1-9]{0,}[0-9])/g, '$1h $2m').replace(/\s0m/g, '').replace(/0h\s/g, '');
    return myString;
  }

  console.log(replaceTime(t));
  console.log(replaceTime(t2));
  console.log(replaceTime(t3));
  console.log(replaceTime(t4));

returns:
5m
1h
12h 10m
2h 2m


text:
Q: Change value of selectric drop down programmatically? What is a good way to change the value of a Selectric drop down programmatically based on name? I know the value of the option I want to set as selected. I don't know the name or the index.
Here is my best attempt:
$('.store-availability').prop('selectedIndex', 3).selectric('refresh').change();

Since I don't know the index I would have to jQuery.Index() on the options first to find it or something like that. Is there a cleaner approach?

A: If you know the value of the option you want to set you can use the setter of val(), then call refresh on the selectric instance, like this:
$('.store-availability').val(yourValueHere).change().selectric('refresh');


text:
Q: Prestashop 1.7.8.8 Service Not Found Exception - Admin page blank (Error 500) after update to 1.7.8.8 I have updated from Prestashop 1.7.8.6 to 1.7.8.8, admin worked, but after I updated a translation in the Backoffice, the Backoffice got a 500 error and I can't access it anymore. This is the Debug message:
ServiceNotFoundException
The service "prestashop.adapter.product.options.redirect_target_provider" has a dependency on a non-existent service "prestashop.adapter.product.repository.product_preview_repository".

in CheckExceptionOnInvalidReferenceBehaviorPass.php line 31
at CheckExceptionOnInvalidReferenceBehaviorPass->processValue(object(Reference), false)
in AbstractRecursivePass.php line 60
at AbstractRecursivePass->processValue(array(object(Reference), object(Reference), object(Reference)), false)
in CheckExceptionOnInvalidReferenceBehaviorPass.php line 28
at CheckExceptionOnInvalidReferenceBehaviorPass->processValue(array(object(Reference), object(Reference), object(Reference)))
in AbstractRecursivePass.php line 67
at AbstractRecursivePass->processValue(object(Definition), true)
in CheckExceptionOnInvalidReferenceBehaviorPass.php line 28
at CheckExceptionOnInvalidReferenceBehaviorPass->processValue(object(Definition), true)
in AbstractRecursivePass.php line 60

I don't know how to proceed :( - any tips?


text:
Q: How to find if a specific  has an  tag nested within it using Excel VBA? I'm extracting data from source using xmlHttp request and looking for a certain error where a specific
 tag contains no data between the opening & closing tag. If the class name was unique, I could use getElementsByClassName to search, but the page I'm trying to access is using multiple
 tags with the same class.
Example 1 (
 without data):

Example 2 (
 with data):

The 2nd example contains  within the div
.
Is there a way to find all
 with class="col-xs-12 col-sm-6 imageleftpadding centered" and check whether they contain any data or none?

A: You could gather all the divs with that class name and then loop testing if they have a child img tagged element. In my example, I print out the outerHTML of the elements which don't have the child img.
Sadly VBA implementation doesn't support the :not CSS pseudo-class selector or you could simply have done html.querySelectorAll(".col-xs-12.col-sm-6.imageleftpadding.centered:not(img)").
With XMLHTTP you would use the following:
Set html = New HTMLDocument
With CreateObject("MSXML2.XMLHTTP")
    .Open "GET", "URL", False
    .setRequestHeader "If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT"
    .send
    html.body.innerHTML = StrConv(.responseBody, vbUnicode)
End With
Dim nodeList As Object, i As Long, ele As Object
Set nodeList = html.querySelectorAll(".col-xs-12.col-sm-6.imageleftpadding.centered")

For i = 0 To nodeList.Length - 1
    On Error Resume Next
    Set ele = nodeList.item(i).getElementsByTagName("img")
    If ele.Length = 0 Then Debug.Print nodeList.item(i).outerHTML
    On Error GoTo 0
Next i


text:
Q: Contact form 7 (wordpress) I´m using contact form 7 on my website to get customers to order
products from my Wordpress site.
But I want to let the user (customers) to add their own form fields if they want to add other products then listed in the form.
Is that possible?

A: Fields in the CF7 creator are inserted as a kind of shortcode/internal format, and after that it passes a parser that changes them into valid HTML form elements. What you can do, is to use  DOM (Document Object Model) to create a new element - but then, you should definitely pay attention to your PHP code afterwards.


text:
Q: React State Updating after code requiring state change runs I'm trying to create a grid of Nodes, which update when clicking/dragging on them. I'm running into a weird React State where the state is updating after the code following it runs.
Expected behaviour:

*

*nodeTypePointer is set to 0 as default react state

*Click on Blank Node, nodeTypePointer is set to 0 (unchanged) + logic uses 0

*Click on Coloured Node, nodeTypePointer is set to 1 + logic uses 1

Actual behaviour

*

*nodeTypePointer is set to 0 as default react state

*Click on Blank Node, nodeTypePointer remains unchanged + logic uses 0

*Click on Coloured Node for the first time, nodeTypePointer is set to 0 (unchanged) + logic uses 0, then after code is finished nodeTypePointer is set to 1

*Click on Coloured Node for the second time, nodeTypePointer is now still set to 1, logic uses 1, then after code is finished nodeTypePointer is set to 0

I know that the state is async but unsure about the exact reason/problem/solution to go on. Unsure about how to pass parameters to the next functions if I were to use a UseEffect.
Here is the code:
import React, { useEffect, useState } from 'react';
import Node from './Node'

import './Grid.css';

const rectDiameter = 25
const gridHeightRatio = 0.9

const Grid: React.FC = () => {

    const gridHeight: number = Math.floor(window.innerHeight * gridHeightRatio)
    const gridWidth: number = window.innerWidth

    const numX: number = Math.floor(gridHeight / rectDiameter)
    const numY: number = Math.floor(gridWidth / rectDiameter)

    const tempGrid: number[][] = [...Array(numX)].map(() => Array(numY).fill(0));

    const [grid, setGrid] = useState(tempGrid)
    const [isMousePressed, setMousePressed] = useState(false)
    const [nodeTypePointer, setNodeTypePointer] = useState(0)

    useEffect(() => {
        console.log('Use Effect', nodeTypePointer)
    }, [nodeTypePointer])

    // Hacky el.ID to workaround React performance until I know how to do it better
    const paintNode = (x: number, y: number) => {
        const el = document.getElementById(`${x}-${y}`)
        if (!el) return
        if (nodeTypePointer === 0) {
            el.classList.add("node-wall")
        } else {
            el.classList.remove("node-wall")
        }
    }

    const updateGridPosition = (x: number, y: number) => {
        const newValue = nodeTypePointer === 0 ? 1 : 0
        let newGrid: number[][] = grid
        newGrid[x][y] = newValue
        setGrid(newGrid)
    }

    const handleMouseDown = (event: React.MouseEvent<HTMLDivElement>, x: number, y: number) => {
        console.log('Node pointer type Before', nodeTypePointer)
        setNodeTypePointer(grid[x][y])
        console.log('Node pointer type After', nodeTypePointer)
        setMousePressed(true)
        console.log('Before updated Grid', grid[x][y])
        updateGridPosition(x, y)
        console.log('After updated Grid', grid[x][y])
        paintNode(x, y)                             // <------------- Uses nodeTypePointer
    }

    const handleMouseUp = (event: React.MouseEvent<HTMLDivElement>, x: number, y: number) => {}

    const handleHover = (event: React.MouseEvent<HTMLDivElement>, x: number, y: number) => {
        if (!isMousePressed) return
        updateGridPosition(x, y)
        paintNode(x, y)
}

    return (
        <div className='gridContainer' >
            {
                grid.map((row: number[], i: number) =>
                    row.map((val: number, j: number) =>
                        <Node
                            x={i}
                            y={j}
                            d={rectDiameter}
                            key={`${i}-${j}`}
                            state={val}
                            onMouseDown={handleMouseDown}
                            onMouseUp={handleMouseUp}
                            onHover={handleHover} />
                    )
                )
            }
        </div>
    );
}

export default Grid

Any help on understanding the problem and suggested solutions would be greatly appreciated!

A: State changes are asynchronous (both component ones and hook ones). So your state hasn't update by the time you call paintNode. There's 2 ways I can think of around it. One is to put the call to paintNode in your nodeTypePointer's useEffect, like so:
 useEffect(() => {
     paintNode(x,y);
 }, [nodeTypePointer])

but this means you'll need to store the x and y of clicked one in some standard variables, since you won't be able to pass them directly to useEffect. Another way (and maybe a better one, since I'm not a huge fan of state changes having side effects) is to just pass the x/y directly into paintNode during the handleMouseDown function:
paintNode(x, y, grid[x][y])

however it looks like updateGridPosition also needs the x/y, so maybe you would be better off storing the raw clicked one in state, then having a useEffect for the clicked one that does everything needed once a node is clicked. All depends on how this function is gonna end up looking.
But yeah, the reason for your bug is cause state changes are async so it hasn't updated by the time you call paintNode


text:
Q: How do I get a gltfpack-processed model to appear in A-Frame? I compressed my models and textures with gltfpack and now they are invisible in A-Frame 1.1.0. In gltfpack, I used -tc to convert the texture files to BasisU and left everything else as is. When I loaded them in A-Frame, the models aren't there. Interestingly, the models work in Don McCurdy's viewer. Update: there is a relevant Javascript console message

THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2
textures.

So it appears I'm misusing Three.js.
Here is a bare Glitch showing the issue. There should be two models visible in the scene but only the unprocessed one is there. Anyone know I could fix it?

A: The models are working with Don's viewer because he isn't using the standard gltf-model component, but uses a raw threejs loader(with multiple extras):
const loader = new GLTFLoader().setCrossOrigin('anonymous');
loader.setDRACOLoader(new DRACOLoader().setDecoderPath('./wasm/'));
loader.setKTX2Loader(new KTX2Loader().detectSupport(renderer));

Afaik the KTX2Loader on the threejs repo is available only as a module (here), so I've managed to make it work by creating my own module which imports the KTX2Loader. In a nutshell:
// probably only need the KTX2Loader since aframe gives access to
// the GLTFLoader and DRACOLoader.
import { GLTFLoader } from './path_to_three/examples/jsm/loaders/GLTFLoader.js';
import { KTX2Loader } from './path_to_three/examples/jsm/loaders/KTX2Loader.js';
import { DRACOLoader } from './path_to_three/examples/jsm/loaders/DRACOLoader.js';

// this is a 'minimal' version of the gltf-component,
// a more faithful one is linked later on
module.exports.Component =
AFRAME.registerComponent("full-gltf-model",
   schema: { type: 'model' },
   init: function() {
      const loader = new GLTFLoader().setCrossOrigin('anonymous')
               .setDRACOLoader(new DRACOLoader().setDecoderPath('./wasm/'))
               .setKTX2Loader(new KTX2Loader().detectSupport(renderer));
      var src = this.data;
      // load the model:
      loader.load(src,
         function gltfLoaded(gltfModel) {
            let model = self.model = gltfModel.scene || gltfModel.scenes[0];
            // assuming el is an entity;
            el.setObject3D("mesh", model);
         }, undefined /* in progress */,
         function error(err) {
            console.log("error:", err);
      })
   }
})

I've bundled it with browserify (browserify index.js -p esmify > dist/full-gltf-model.js), and used like this:
<!-- Somewhere in the scripts -->
<script src="dist/full-gltf-model.js>
<!-- Somewhere in the scene -->
<a-entity full-gltf-model="#model"></a-entity>

You can check it out here. The models are straight from Your glitch (credited to you ofc).
Feel free to check out the directory with the component and package.json. I'm pretty sure the bundle contains already defined stuff (1Mb even with only the KTX2Loader imported o.O), so there definitely is room for improvement. Still this seems like a good start :)

A: Just want to provide an updated answer to this--this is now natively supported in A-Frame. Just do the following:
    <a-scene gltf-model="dracoDecoderPath: https://www.gstatic.com/draco/v1/decoders/;
                         basisTranscoderPath:https://cdn.jsdelivr.net/npm/super-three@0.141.0/examples/js/libs/basis/;;
                         meshoptDecoderPath: https://unpkg.com/meshoptimizer@~0.18.1/meshopt_decoder.js;">

Note: that basisTranscoderPath is only on master right now--so, not included yet in A-Frame 1.3.0, you'd have to pull master and run a build at the moment. Next release will have it, though. (see the PR)
See the docs on this: https://github.com/jameskane05/aframe/blob/9df1d2cb50ab12aa341cc250c703624510d25deb/docs/components/gltf-model.md
The official master build links are currently lagging behind, and using a github cdn won't work because dist files are not being committed in the last few months, but I made a build and put it on a glitch project of mine--you can use that file at this link if you need this if aframe 1.3.0 is still the most recent version out for you:
https://gltf-packed.glitch.me/aframe-diego.js
(this is a dev build of a particular branch of diego's fork as of oct 15 2022)


text:
Q: n+1 query in rails, need solution Below given are the model in my application. I am trying to find all the companies that matches the keyskills. For example. If I type java in my search-box it should get me all the companies that are matching and keyskills.
class User < ActiveRecord::Base
  has_one :company
end

class Company < ActiveRecord::Base
  has_many :jobs
  belongs_to :user
end

class Job < ActiveRecord::Base
  belongs_to :company
  has_many :key_skills, dependent: :destroy
  accepts_nested_attributes_for :key_skills, reject_if: :all_blank, allow_destroy: true
end

class KeySkill < ActiveRecord::Base
  belongs_to :job
end

The steps that I am following are,
step1: Find all the keyskills matching the entered word. (ex: java)
@matched_keyskills = KeySkill.where('name like ?','java')

Since I have association between jobs and keyskills, that is jobs has_many key_skills and key_skills belongs_to job. I can iterate over
@matched_keyskill.each do |k|
  k.job.company
end
and get the company records. But, when I tried this method it results in n+1 query also the company name is getting repeated.
Is there a way through which I can get only the company name shown on show page then by clicking on company it shows the jobs associate to it.
also kindly let me know is the db model and association are correct inorder to achieve it.

A: You can use "joins" and "inclue" to remove the n+1 query:
Try this, it will give you the list of all companies as You required.
Company.joins(key_skill: :job).where('key_skill.name like ?','java')

you can also use eager loading.
http://railscasts.com/episodes/22-eager-loading


text:
Q: Navigation between controllers without loading the whole page There is a way to load the contents of a page by navigating from one controller to another controller without loading the whole page and without changing the URL?
I need it for example to keep title, user information, etc, without having to load them each time.

A: youll need a single page application. you might want to use a framework for that.
Angular JS
or DurandalJS  and you have many more.
you can do it alone, but it can be complicated.