text:
Q: Why does my timer hook not update it's internal state? For some reason my timer is not updating it's internal Timer State after I modify the input field.  Here is the intial state of my page and State.

This is what my screen and state look like after I modify the input from 10 to 8 seconds. Notice that the Timer State does not update

Here is my code for the workout page:
function WorkoutPage(props: any) {

const DEFAULT_SECONDS_BETWEEN_REPS: number = 10
const [secondsBetweenRepsSetting, setSecondsBetweenRepsSetting] = useState(DEFAULT_SECONDS_BETWEEN_REPS)
const {secondsLeft, isRunning, start, stop} = useTimer({
        duration: secondsBetweenRepsSetting,
        onExpire: () => sayRandomExerciseName(),
        onTick: () => handleTick(),
    })
const onTimeBetweenRepsChange = (event: any) => {
        const secondsBetweenRepsSettingString = event.target.value;
        const secondsBetweenRepsSettingInt = parseInt(secondsBetweenRepsSettingString)
        setSecondsBetweenRepsSetting(secondsBetweenRepsSettingInt)
    }

return <React.Fragment>
<input type="number" name="secondsBetweenRepsSetting" value={secondsBetweenRepsSetting} onChange={onTimeBetweenRepsChange}/>
</React.Fragment>

}

Here is my useTimer Class:
import { useState } from 'react';
import Validate from "../utils/Validate";
import useInterval from "./useInterval";

export default function useTimer({ duration: timerDuration, onExpire, onTick}) {
  const [secondsLeft, setSecondsLeft] = useState(timerDuration)
  const [isRunning, setIsRunning] = useState(false)

  function start() {
    setIsRunning(true)
  }
  function stop() {
    setIsRunning(false)
  }

  function handleExpire() {
    Validate.onExpire(onExpire) && onExpire();
  }

  useInterval(() => {
    const secondsMinusOne = secondsLeft - 1;
    setSecondsLeft(secondsMinusOne)
    if(secondsMinusOne <= 0) {
      setSecondsLeft(timerDuration) // Reset timer automatically
      handleExpire()
    } else {
      Validate.onTick(onTick) && onTick();
    }
  }, isRunning ? 1000 : null)

  return {secondsLeft, isRunning, start, stop, }
}

My full codebase is here in case someone is interested: https://github.com/kamilski81/bdt-coach

A: Here's the sequence of events you expect:

*

*User changes the input

*The change handler fires and calls setSecondsBetweenRepsSetting with the new value

*The component re-renders with the new value for secondsBetweenRepsSetting

*useTimer is invoked with a duration property of the new value

*The secondsLeft state in the useTimer hook changes to the new duration value <-- oops! this does not happen
Why doesn't this last item happen? Because within the useTimer implementation, the only place you use the duration is as the initial value of secondsLeft. Calling the hook a second time with a new duration value will not change the secondsLeft state, and this is by design.
My recommendation would be to include setSecondsLeft in the return value of the useTimer hook to give you a way to override the time left in the timer. You could then use setSecondsLeft directly in the input change handler:
const { secondsLeft, setSecondsLeft, isRunning, start, stop } = useTimer({
  duration: secondsBetweenRepsSetting,
  onExpire: () => sayRandomExerciseName(),
  onTick: () => handleTick(),
});

const onTimeBetweenRepsChange = (event: any) => {
  const secondsBetweenRepsSettingString = event.target.value;
  const secondsBetweenRepsSettingInt = parseInt(
    secondsBetweenRepsSettingString
  );
  setSecondsBetweenRepsSetting(secondsBetweenRepsSettingInt);
  setSecondsLeft(secondsBetweenRepsSettingInt);
};


text:
Q: Sorting of Object inside Object On the basis of Order key Sorting & arrange list of object inside object on the basis of order key
const listing = {
   "football":{
      "name":"FOOTBALL",
      "slug":"football",
      "arr":[],
      "order": 4
   },
   "table-tennis":{
      "name":"TABLE TENNIS",
      "slug":"table-tennis",
      "arr":[],
      "order": 1
   },
   "cricket":{
      "name":"CRICKET",
      "slug":"cricket",
      "arr":[],
      "order": 5
   },
   "badminton":{
      "name":"BADMINTON",
      "slug":"badminton",
      "arr":[],
      "order": 2
   },
   "hockey":{
      "name":"HOCKEY",
      "slug":"hockey",
      "arr":[],
      "order": 3
   }
}

Object.keys(listing).sort().map((item) => {
  return (

 sportsKitFilter()}>{listing[item].name}

  )
})

Actual Result:-
BADMINTON
CRICKET
FOOTBALL
HOCKEY
TABLE TENNIS

Expected Result:-
TABLE TENNIS
BADMINTON
HOCKEY
FOOTBALL
CRICKET

So, In the expected result, Storing is on the basis of order key
Guide me, In this scenerio??

A: Currently i am sorting listing.order. try this code it's working !
 Object.keys(listing).sort((a, b) => listing[a].order - listing[b].order).map((item) => {
      return (

 sportsKitFilter()}>{listing[item].name}

      )
    })

A: How's this for you?
const listing = {
  football: {
    name: "FOOTBALL",
    slug: "football",
    arr: [],
    order: 4,
  },
  "table-tennis": {
    name: "TABLE TENNIS",
    slug: "table-tennis",
    arr: [],
    order: 1,
  },
  cricket: {
    name: "CRICKET",
    slug: "cricket",
    arr: [],
    order: 5,
  },
  badminton: {
    name: "BADMINTON",
    slug: "badminton",
    arr: [],
    order: 2,
  },
  hockey: {
    name: "HOCKEY",
    slug: "hockey",
    arr: [],
    order: 3,
  },
};

const ordered = Object.keys(listing).sort(
  (a, b) => listing[a].order - listing[b].order
).map(item => ["YOUR JSX HERE"]);

redpajama_set_name: RedPajamaStackExchange


text:
Q: SVG CSS3 Show and Hide element on hover from other element Given the SVG below, I am trying to use CSS to allow one to hover over tspan.hovertext classed elements within g#Main_Layer, to unhide unrelated g elements in #Hover_Panels. See below:
<?xml version="1.0" encoding="utf-8"?>
<!-- Generator: Adobe Illustrator 20.0.0, SVG Export Plug-In . SVG Version: 6.00 Build 0)  -->
<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="1280px"
     height="1569.2px" viewBox="0 0 1280 1569.2" style="enable-background:new 0 0 1280 1569.2;" xml:space="preserve">
<style type="text/css">
    text{font-family:'Lato';font-weight:300;}

    #Hover_Text {
        text-transform: uppercase;
    }

    .st0{fill:#404041;}
    .st1{font-family:'Lato';font-weight:300;}
    .st5{font-family:'Lato';font-weight:400;}
    .st6{font-size:20px;}
    .st7{fill:none;stroke:#5880AC;stroke-width:1.073;}
    .st22{display:none;}
    .st23{display:inline;fill:#016699;}
    .st24{font-size:26.44px;}

    .hovertext {
        cursor: pointer;
    }

    .hovertext:hover {
        font-weight: bold;
    }

    .hovertext:hover + #Hidden_Text {
        display: block;
    }

</style>
<g id="Main_Layer">
    <text id="Hover_Text" transform="matrix(1 0 0 1 1044.0001 878.011)">
        <tspan x="0" y="0" class="st4 st5 st6">hover </tspan>
        <tspan x="0" y="180" class="hovertext st4 st1 st6">HOVER TEXT</tspan>
    </text>
</g>
<g id="Hover_panels">
    <g id="Default_Text" >
        <text transform="matrix(1 0 0 1 459.2306 1051.639)">
            <tspan x="0" y="0" class="st16 st1 st19">Default Text </tspan>
        </text>
    </g>
    <g id="Hidden_Text" class="st22">
        <text transform="matrix(1 0 0 1 566.0988 1163.5396)" class="st23 st1 st24">Hidden Text</text>
    </g>
</g>
</svg>

The problem is I am not exactly in much control of the XML layout (thats generated by Illustrator provided by our designer), and for reasons I wish I could discuss here, we can't use Javascript to accomplish this effect.
How do I get, when using just CSS, when hovering over an .hovertext element, to add display: block to the #Hidden_Text element, and hide the #Default_Text element?
Thank you!

A: It's not possible with CSS alone to specify an element not directly behind ("+" Operator) or below (some children).
But you could instead use visibility: collapse instead of display: none for #Hidden_Text (which looks just the same) and define a <set> animation in #Hidden_Text which sets this property to visible if the text is hovered. You need to wrap the hidden text in a <tspan> and apply an id to the hovertext to make that possible:
<?xml version="1.0" encoding="utf-8"?>
<!-- Generator: Adobe Illustrator 20.0.0, SVG Export Plug-In . SVG Version: 6.00 Build 0)  -->
<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="1280px"
     height="1569.2px" viewBox="0 0 1280 1569.2" style="enable-background:new 0 0 1280 1569.2;" xml:space="preserve">
<style type="text/css">
    text{font-family:'Lato';font-weight:300;}

    #Hover_Text {
        text-transform: uppercase;
    }

    .st0{fill:#404041;}
    .st1{font-family:'Lato';font-weight:300;}
    .st5{font-family:'Lato';font-weight:400;}
    .st6{font-size:20px;}
    .st7{fill:none;stroke:#5880AC;stroke-width:1.073;}
    .st22{visibility: collapse;}
    .st23{display:inline;fill:#016699;}
    .st24{font-size:26.44px;}

    .hovertext {
        cursor: pointer;
    }

    .hovertext:hover {
        font-weight: bold;
    }

    .hovertext:hover + #Hidden_Text {
        display: block;
    }

</style>
<g id="Main_Layer">
    <text id="Hover_Text" transform="matrix(1 0 0 1 1044.0001 878.011)">
        <tspan x="0" y="0" class="st4 st5 st6">hover </tspan>
        <tspan x="0" y="180" id="hovertext" class="hovertext st4 st1 st6">HOVER TEXT</tspan>
   </text>
</g>
<g id="Hover_panels">
    <g id="Default_Text" >
        <text transform="matrix(1 0 0 1 459.2306 1051.639)">
            <tspan x="0" y="0" class="st16 st1 st19">Default Text </tspan>
        </text>
        <g id="Hidden_Text" class="st22">
            <text transform="matrix(1 0 0 1 566.0988 1163.5396)" class="st23 st1 st24">
                <tspan>Hidden Text</tspan>
                <set attributeName="visibility" to="visible" begin="hovertext.mouseover" end="hovertext.mouseout"/>
            </text>
        </g>
    </g>
</g>
</svg>

I don't know much about what Illustrator allows you to do, but at least it works without JavaScript.


text:
Q: Download file from ftp with javascript in webpage I want to get list of files from ftp server and show to user to select some file and then download it.
I don't want to use server side code because the ftp server is not access with server.(it is in local of client side)
I search about it and I found window.open or iframe that only show ftp files in another window. but i want to manage the selection files with JavaScript.
also I find this but it work only in IE and i want to work with Firefox and chrome.
so how can i access ftp with JavaScript code?
Edit:
Firefox says XMLHttpRequest  work with ftp in this link. but this don't work and get error access to restricted URI denied.
i search about this and find to add netscape.security.Privilege.enablePrivilege( "UniversalXPConnect" ) but netscape.security.Privilege removed from Firefox after version 15.
so how can i send XMLHttpRequest  to ftp server from webpage with javaScript?


text:
Q: Что сделать чтобы в конструкторе не было много параметров Всем привет! Есть такой конструктор который считывает информацию о квартире:
public Flat(Address flatAddress, double flatArea, boolean furnishing, int bedroomsNum, double flatPrice, List<InfrastructureObject> infrustructure)

Также есть конструкторы Адреса:
public Address(String country,String town,String street,int houseNumber)

И конструктор инфраструктуры:
 public InfrastructureObject(InfrastructuresType infrastructuresType,String infrastructureObjectName,double distance)

в итоге , когда я создаю квартиру(объект) получается огромный конструктор вроде этого:
Flat flat1 = new Flat(new Address("Great Britain", "London", "Linkoln St.", 25), 290,
                true, 4, 750, new LinkedList<>(Arrays.asList(
                new InfrastructureObject(InfrastructuresType.SCHOOL, "School №19", 900),
                new InfrastructureObject(InfrastructuresType.HYPERMARKET, "Victoria Gardens hypermarket", 800))));

Как можно сократить такой конструктор, дабы он занимал меньше места по скольку в будущем мне надо будет создавать список квартир? Спасибо за предложения!!!

A: В зависимости от того объект у вас должен ли быть неизменяемый и все ли параметры должны быть проиницилизированны.

*

*Можно сделать конструктор без параметров и использовать set-ры

*

*ваш объект будет изменяемы - что не всегда хорошо

*Можно применить билдер паттерн

*Для списков можно использовать add методы

*

*например для Flat можно добавить метод что-то типа
addInfrastructureObject(InfrastructureObject infrustructure)

A: Во-первых, хардкодить конкретные названия прямо в Java - это значит самому себе проблемы в будущем создать. Надо объекты создавать из БД - ну на крайний случай с текстового файла. Тогда и код будет выглядеть более компактным автоматически.
Во-вторых, InfrastructuresType.SCHOOL - не очень хорошее решение с позиции ООП - потому что в методах Вам тогда придется писать "если тип такой-то то делай это, иначе если тип такой-то ..." - во что потом превращаются такие методы видел неоднократно. Намного лучше и короче просто new School(), причем в нем не надо будет тип проверять - у каждого объекта свой переопределенный метод.
В-третьих, new LinkedList<> - это тоже не очень хорошо. Например, есть документ, а есть журнал документов - это разные сущности со своим поведением и свойствами. Думаю то же самое есть и в Вашем случае.
Если хотя бы эти три рекомендации используете - код значительно сократится и будет намного более читаемым.

A: Могу предложить использовать паттерн Fluent Interface. Он похож на Builder. Суть такова - в классе, для которого у вас пишется такой большой конструктор, вы должны объявить пустой публичный конструктор по умолчанию + set методы для каждой переменной, которые возвращают this. Пример:
class ClassA {
  ...
  public ClassA setVar1(... var1) {
    this.var1 = var1;
    return this;
  }
  ...
}

В итоге, при создании объекта вам нужно будет сделать так:
ClassA a = new ClassA()
             .setVar1(...)
             .setVar2(...)
             .setVar3(...);


text:
Q: Why is [^@] regular expression acting the way it does? I was looking for a regular expression to validate e-mails when I found this:
[^@]+@[^@]+\.[^@]+

The [^@] expression seems not to work like the documention says it should.
s = 'test'

match = re.match("[^@]", s)

print(match.group())

This for example prints the first character of the string that is t.
If i use regular expression [^] I get an error: unexpected end of regular expression. The documentation says that:

Special characters lose their special meaning inside sets.

[] is a set and ^ is a special character.

A: The statement "special characters lose their special meaning inside sets" is true because the caret character has two special meanings; at the logical start of a regular expression (where it is an anchor), and at the start of a character class (or 'character set' where it forms a 'complementing set of characters').
The reported error comes from the [^] construct which is invalid since the character class is not closed: the ^ affects the next character(s).
In this case the effect is the ] does not close the character class and the entire regular expression is "not ended", resulting in the regular expression syntax error.

Anyway, the error reported about [^] has nothing to do with [^@] which is a character class that will match any character except @. This, coupled with the incorrectly focused title, probably explains some of the downvotes..
re.match("[^]",  "anything")  # => regex error, as explained above
re.match("[^]]", "z")         # => match; z is not ]
re.match("[^@]", "z")         # => match; z is not @
re.match("[^@]", "@")         # => no match

A: The character ^ is a special character.
^Test ... matches a string that starts with Test
   \^ ... matches the character ^
 [\^] ... matches the character ^
 [^^] ... matches a character that is not a ^
 [-^] ... matches a - or a ^
 [^-] ... matches a character that is not a -
[\^-] ... matches a - or a ^

A: [^] is a special case. It means "match a single character that is not in the brackets." Have a look at the wiki page for more detail.


text:
Q: How to fill a car with tennis balls if i want to fill interior of a car with tennis balls how many will be required.
How to calculate this?
if we are provided with length,breadth,height  of car(height varies at each part)  and radius of tennis ball.
Some one please explain it in detail.

A: Alright, first of all you should try to work the volume of the car and the volume of the balls and figure it out by there. In trying to figure the volume of the car, you can seperate the car into pieces and work your way through there. However, this will not give you a correct answer in the real life.
While trying to figure out the volume of the balls, you should consider the best possible combination in which you can put them. Because in whatever way you combine them, there will be some spaces between them, and this will cause the mistake in the previous calculation. For this combination thing, I suggest you looking at packaging ratio. http://mathworld.wolfram.com/SpherePacking.html I hope this would help you.


text:
Q: Oracle Database Job run issue-ora01031, insufficient privileges ora06512 I am very new to oracle and dont have much of an idea of how to resolve this problem.
I have two schema ERM22_TEST and ERM22_TEST_CUSTOM
One package exists in RM22_TEST.ASYNC_JOB_QUEUE_COMMAND_BAS
and another package in ERM22_TEST_CUSTOM.C_PSP_INTERFACE
I have a job scheduler in ERM22_TEST_CUSTOM schema, which exports the data from a view in to CSV file, but when I click on run job it gives me the error:
ORA-01031: insufficient privileges
ORA-06512: at "ERM22_TEST.ASYNC_JOB_QUEUE_COMMAND_BAS", line 101
ORA-06512: at "ERM22_TEST.ASYNC_JOB_QUEUE_COMMAND_BAS", line 106
ORA-06512: at "ERM22_TEST_CUSTOM.C_PSP_INTERFACE", line 39
ORA-06512: at "ERM22_TEST_CUSTOM.C_PSP_INTERFACE", line 95

But it same export I do form my application than it export the data in csv file. Both user name are not same which run the database job and run the job from application client.
I just know it has some issue of granting the access but I have no idea how to grant access to ERM22_TEST_CUSTOM schema which run a package in another schema ERM22_TEST.
ORA-01031: insufficient privileges
ORA-06512: at "ERM22_TEST.ASYNC_JOB_QUEUE_COMMAND_BAS", line 101
ORA-06512: at "ERM22_TEST.ASYNC_JOB_QUEUE_COMMAND_BAS", line 106
ORA-06512: at "ERM22_TEST_CUSTOM.C_PSP_INTERFACE", line 39
ORA-06512: at "ERM22_TEST_CUSTOM.C_PSP_INTERFACE", line 95


text:
Q: ASP.NET & C# - Two values in a listbox? I'm adding ListItems to a ListBox from two controls, both are DropDownLists.
The ListItem has the properties ListItem.SelectedItem and ListItem.SelectedValue, but I also want the ListBox to keep track of which DropDownList the ListItem came from.
What would be the best way to do this?

A: You could set the ID of the dropdown programatically as a attribute of the listitem.
ListItem i = new ListItem();
i.Attributes["IDofDropDown"] = "SomeID";

A: Encode the .Value section so that its something like DropDownList1:SomeValue and then you can use String.Split to extract the info back out of .SelectedValue?

A: ListItem item contains Text and Value properties that mapped from option element in HTML. So you can not add any other value to this structure. But maybe you can save the source dropdown's id to the Value of the ListItem.

A: You could create an in memory dataset to store all the data needed and then bind the dataset to your ListBox. When ever a value is selected you will have access to more fields in code behind.

A: The way I went about solving this, was creating an ArrayList, with another array inside for each item.


text:
Q: Ada: Declaration & assignment overhead I'm curious about the initialization within Ada procedures:
Suppose I have the following procedure:
procedure Foo (Bar : Integer) is
    Another_Bar : Integer := Bar;
begin
    ...
end Foo;

Should the assignment to Another_Bar have the same overhead as
procedure Foo2 (Bar : Integer) is
    Another_Bar : Integer;
begin
    Another_Bar := Bar;
    ...
end Foo;

My question is essentially if both assignments generate the same assembly instructions and thus are equal in speed? (without detailing the target machine)

A: Based on the Ada language standard, there is no general reason why those two forms of code should have different performance. It would all depend on the target machine and the compiler being used. Depending on the rest of the code in the procedure, some compilers could even completely optimize away the Another_Bar variable.
However, there is a semantic difference, which could be important if the subtypes of Bar and Another_Bar were different -- for example, if Another_Bar were declared as Positive instead of Integer. Namely, in the first form any exception raised by the initialization of Another_Bar (say, because Bar has a negative value) is not handled by the possible exception handlers in the procedure itself, but is propagated to the caller. In the second form, where Another_Bar is assigned after the begin, exceptions from that assignment can be handled by the procedure's own exception handlers.


text:
Q: PHP проверка столбцов на значения больше нуля Есть функция которая проверяет строки выбранных столбов на значения больше нуля, сделано это для того, чтобы пользователю было понятно в каком столбце проблема(в каком столбце у строк нули).
Вот сама функция, ну это не совсем то, что надо. Сейчас объясню.
function check_zeros($p_csv)
{
    $check = '';
    foreach ($p_csv as $row) {
        if ($row[3] != 0 && $row[5] != 0) {
            $check = '1';
            break;
        }
        if ($row[3] == 0 && $row[5] == 0) {
            $check = '2';
            break;
        }
        if ($row[3] == 0) {
            $check = '3';
            break;
        }
        if ($row[5] == 0) {
            $check = '4';
            break;
        }
    }
    return $check;
}

Т.е. первый If проверяет если есть значение больше нуля для всех строк столбцов, тогда прерываем перебор массива, возвращаем '1'.
Если он не находит у всех строк в обоих столбцах значения больше нуля, делаем второй if который проверит строку обоих столбцов, на значения равным 0, если в обоих столбцах 0, тогда возвращаем 2, прерываем перебор массива.
Третий if проверяет строку столбца на значение равным нулю, возвращает 3 если значение строки для выбранного столбца равно 0. Точно так же и для 4го if.
Проблема в том, что с 2го по 4ый if он проверяет только первую строку выбранных столбцов, а надо чтобы он проверял все строки на значения больше нуля.
Т.Е. могут приходить данные 0, 0, 1 для первого столбца(через запятую, это значит новая строка) и 0, 0, 1 для второго.
У меня лишь проверит что в первом столбце первая строка 0, и выведет ошибку, что в первом столбце все нули, так и не дойдя до 3 строки где указано 1.
И далее у меня есть другая функция, в которой я вызываю функцию check_zeros таким образом
if(check_zeros($csv) == '2')
{
    $error_string = "Все значения для обоих столбцов равны 0";
    $error = true;
    return;
}
if(check_zeros($csv) == '3')
{
    $error_string = "Все значения для 3го столбца равны 0";
    $error = true;
    return;
}
if(check_zeros($csv) == '4')
{
    $error_string = "все значения для 5го столбца равны 0";
    $error = true;
    return;
}

Подскажите пожалуйста, как я могу реализовать, чтобы он все строки проверял и четко выводил ошибку, указывая пользователю в каком столбце у него проблема.
Надеюсь я смог правильно донести мысль, и вы меня поймете, так же прошу прощения за орфографию. Чукча не писатель.
Заранее огромное спасибо.

A: function check_zeros($p_csv)
{
    /**
    * Правила проверки столбцов в формате 'ошибка(код ошибки) => номера столбцов'
    */
    $rules = [
        'Все значения для обоих столбцов равны 0' => [3,5],
        'Все значения для 3го столбца равны 0' => [3],
        'Все значения для 5го столбца равны 0' => [5]
    ];

    foreach($rules as $error => $rule) { // для каждого правила
        $zero = []; // создаем пустой массив
        foreach ($rule as $col) { // для каждого столбца
            foreach ($p_csv as $row) // перебираем строки
            if ($row[$col] === 0) {
                $zero[] = true; // записываем в массив при нахождении нулевого элемента в столбце
            }
        }

        if (count($zero) === count($p_csv) * count($rule)) {
            return $error; // в случае, когда количество нулей для текущего правила равно количеству строк умноженному на количество проверяемых столбцов возвращаем ошибку;
        }
    }

    return false;
}

$arr = [

    [1,0,0,1,0,0],
    [0,1,0,0,0,0],
    [0,0,1,0,0,0],

];
echo '<pre>';
var_dump(check_zeros($arr));
echo '<pre>';

С точки зрения производительности, это неоптимальный вариант решения задачи, если количество строк будет очень большим и количество проверяемых столбцов будет расти, то следует оптимизировать код.
UPD
Оптимизированый вариант алгоритма:
function check_zeros($p_csv)
{
    $rules = [
        'Все значения для обоих столбцов равны 0' => [3,5],
        'Все значения для 3го столбца равны 0' => [3],
        'Все значения для 5го столбца равны 0' => [5]
    ];

    foreach($rules as $error => $rule) {
        foreach ($rule as $col) {
            foreach ($p_csv as $row)
            if ($row[$col] !== 0) {
                continue 3; // переходим к следующему правилу, если элемент в столбце не равен нулю
            }
        }

        return $error;

    }

    return false;
}

$arr = [

    [1,0,0,0,0,0],
    [0,1,0,0,0,0],
    [0,0,1,0,0,1],

];
echo '<pre>';
var_dump(check_zeros($arr));
echo '<pre>';

UPD2
Пример использования в контексте вопроса:
if ( $error = boolval($error_string = check_zeros($p_csv)) ) {
   return;
}


text:
Q: Coordinating Conjunctions + Conjunctive Adverbs
1- Alexander II was an obscure commander but nevertheless interesting
  Scottish king.
(Full version: Alexander II was an obscure commander but nevertheless
  Alexander II was an interesting Scottish king
2- The defendant was depressed and therefore not fully
  responsible for her own actions.
(Full version: The defendant was depressed and therefore the
  defendant was not fully responsible for her own actions.)

In the examples above, we use reduction in conjuction clause by omitting "subject and the auxillary verb (be) . Can I do the same reduction if I use just a conjunctive adverb in the sentence? As:

1a- Alexander II was an obscure commander, nevertheless interesting
  Scottish king.
2a- The defendant was depressed, therefore not fully responsible
  for her own actions.

A: In answer to the question as you originally wrote it: yes, you can omit the coordinating conjunction, "and" and still have an idiomatic, grammatical sentence.
Sentence 2 can be correctly rewritten as sentence 2a.
Sentence 1, as you originally had it should have had a pair of commas to set off the parenthetical remark, "but nevertheless interesting". In other words:

1- Alexander II was an obscure, but nevertheless interesting, Scottish
  king.
(Then the full version would be: Alexander II was an obscure Scottish
  king, but nevertheless Alexander II was an interesting Scottish king.)

That can be condensed down, as you originally proposed, to:

1a- Alexander II was an obscure, nevertheless interesting, [but note that
  second comma] Scottish king.

I think an extra complication was introduced along with adding the noun, "commander" in your correction to sentence 1, when all that was needed was a couple of commas, and that has led to some new grammatical problems with the edited versions of sentence 1.

A:
Can I do the same reduction if I use just a conjunctive adverb in the
  sentence?

Coordinating conjunctions differ from conjunctive adverbs. When you omit the subject and the auxiliary verb (be) you are using the parallelism; while the conjunctive adverbs should only exist in a complete sentence.

1a- Alexander II was an obscure commander, nevertheless interesting
  Scottish king.
2a- The defendant was depressed, therefore not fully responsible for
  her own actions.

Here are the correct and compact corrections:

1a- Alexander II was an obscure commander; nevertheless, he is an interesting
  Scottish king.
2a- The defendant was depressed; therefore she is not fully responsible for
  her own actions.


text:
Q: Using Flask-Security as part of a REST API The Flask-Security docs mention JSON/Ajax support for all of the important view endpoints. So it's possible to get all of the buit-in Flask-Security awesomeness by hitting the views with JSON objects.
But, now I'm trying to use it as part of a RESTful API, and it's not working, because it needs a CSRF token, which is necessary for webpages, but not for APIs:
{
    "meta": {
        "code": 400
    },
    "response": {
        "errors": {
            "csrf_token": [
                "CSRF token missing"
            ]
        }
    }
}

What is the best way to get around this?

A: When using a REST API, the prefered method is token based authentication with something like JSON Web Token (JWT). This scheme has a different security landscape because you are not generating HTML on the server side or using cookies. I'm not a security expert, but from what I've read, this means you are not susceptible to Cross Site Request Forgery (CSRF). This is why turning off CSRF tokens in Flask-Security is ok.
Try using PyJWT token based authentication scheme. To get the token, you post credentials to the 'login' endpoint and receive a token in response. You will then have to send the token with each request through HTTP headers. You can often set this globally on the JS side.
Here are a few references:

*

*http://jwt.io/

*https://pythonhosted.org/Flask-JWT/  (see note below)

*Combining Flask-restless, Flask-security and regular Python requests

*https://github.com/jpadilla/pyjwt/

*https://github.com/mpdavis/python-jose/

*https://auth0.com/docs/server-apis/python

*https://auth0.com/blog/2014/01/07/angularjs-authentication-with-cookies-vs-token/

*https://auth0.com/blog/2014/01/27/ten-things-you-should-know-about-tokens-and-cookies/
note: It seems that Flask-JWT uses the python itsdangerous library which hasn't been updated in awhile. There is a discussion here: https://github.com/mattupstate/flask-jwt/issues/10  Again, I'm not a security expert and both libraries seem to be handle the encoding/decoding by default with the same algorithm. PyJWT and Python-Jose are both listed on jwt.io and have extended functionality.

A: Okay, figured it out. All it needs is a Flask config variable to be set for the app:
WTF_CSRF_ENABLED = False


text:
Q: Applying DataTrigger To GridViewColumn How can I apply a datatrigger to the following in a VS 2012 WPF app?
I have tried this:  Error: Foreground is not accessible or recognized
                <ListView.View>
                    <GridView AllowsColumnReorder="true"
                              ColumnHeaderToolTip="Information">
                        <GridViewColumn DisplayMemberBinding= "{Binding Path=Title , TargetNullValue='No Title Found'}"
                                        Header="Title" Width="100">
                             <GridViewColumn.CellTemplate>
                                <DataTemplate>
                                    <DataTemplate.Triggers>
                                        <DataTrigger Binding="{Binding Title}" Value="{x:Null}">
                                            <Setter Property="Foreground" Value="Salmon"/>
                                        </DataTrigger>
                                    </DataTemplate.Triggers>
                                </DataTemplate>
                            </GridViewColumn.CellTemplate>
                         </GridViewColumn>
                    </GridView>
                </ListView.View>

I want it to Display No Title Found in a different color
                <DataTrigger Binding="{Binding Title}" Value="{x:Null}">
                    <Setter Property="Foreground" Value="Salmon"/>
                </DataTrigger>

A: You have to specify the class of Foreground, you have to omit DisplayMemberBinding and use e.g. a TextBlock in DataTemplate instead:
<DataTemplate>
    <TextBlock Text="{Binding Path=Title , TargetNullValue='No Title Found'}"/>
    <DataTemplate.Triggers>
        <DataTrigger Binding="{Binding Title}" Value="{x:Null}">
            <Setter Property="TextBlock.Foreground" Value="Salmon"/>
        </DataTrigger>
    </DataTemplate.Triggers>
</DataTemplate>


text:
Q: Testing props that are being passed down to child component so i need help with writing a test for proper prop passing to a child component.
beforeEach(() => {
wrapped = shallow(
    <CommentDetail
        author="Sam"
        timeAgo="Today at 4:45 pm"
        content="nice blog post"

    avatar="https://s3.amazonaws.com/uifaces/faces/twitter/m_kalibry/128.jpg"
    />
);
});

it("renders author's name", () => {
expect(wrapped.find(".author").prop("author")).toEqual("Sam");
});

// snippet from the react file
<a href="/" className="author">
    {author}
</a>

It seems pretty similar to what I found in the docs but I'm getting undefined value in the received value in test output.
There's another test that can be written but I'm not really sure if it's properly testing the props:
it("renders author's name", () => {
    expect(wrapped.render().find(".author").text()).toContain("Sam");
});

A: Not 100%, but try removing your find method. The prop should show up on the component itself, rather than whatever element possesses the .author class, unless Author is itself a React component, in which case you'd want to find('Author'):
expect(wrapped.prop("author")).toEqual("Sam");


text:
Q: Run MiKTeX 2.9 on Windows 8 I have tried to install MiKTeX 2.9 on my Windows 8 laptop and the installation wizard was running fine and i had no problems. when I was compiling TeX the first time the following occurred:
Sorry, but "MiKTeX Configuration Utility" did not succeed.

The log file hopefully contains the information to get MiKTeX going again:

  C:/Users/Julian/AppData/Local/MiKTeX/2.9/miktex/log/initexmf.log

You may want to visit the MiKTeX project page (http://miktex.org), if you
need help.

Sorry, but C:\Program Files\MiKTeX 2.9\miktex\bin\x64\texify.exe did not succeed.

The log file hopefully contains the information to get MiKTeX going again:

  C:/Users/Julian/AppData/Local/MiKTeX/2.9/miktex/log/texify.log

You may want to visit the MiKTeX project page (http://miktex.org), if you
need help.

Could somebody help me?


text:
Q: how to print dictionary as defined I have the following code:
from functions import *

powers = AutoVivification()
powers[1] = {'c1': 0.5, 'gamma': 1, 'lambda': 1, 'A': 1}

print powers[1]

my autovivification is the following (taken from: What is the best way to implement nested dictionaries?):
class AutoVivification(dict):
    """Implementation of perl's autovivification feature."""
    def __getitem__(self, item):
        try:
            return dict.__getitem__(self, item)
        except KeyError:
            value = self[item] = type(self)()
            return value

it prints the following:
{'A': 1, 'c1': 0.5, 'gamma': 1, 'lambda': 1}

notice the order has been changed.  it's now alphabetical.  is there any way to prevent this from happening?   sory, wasn't clear enough: (without changing the keys, and using the property of autovivificaion of "making arbitrarilly expanding the dictionary super easy")

A: As the documentation says:

Keys and values are iterated over in an arbitrary order which is non-random, varies across Python implementations, and depends on the dictionary's history of insertions and deletions.

In other words, dictionaries have no inherent order. And you can see that without all your complicated extras:
>>> print {'c1': 0.5, 'gamma': 1, 'lambda': 1, 'A': 1}
{'A': 1, 'c1': 0.5, 'gamma': 1, 'lambda': 1}

If you want a dict that maintains its keys in the order of insertion, you can do that with OrderedDict.

However, that's not enough to help you in this case. If you construct a dict (which has arbitrary order), then pass that to an OrderedDict, all you're doing is freezing that initial arbitrary order:
>>> from collections import OrderedDict
>>> print OrderedDict({'c1': 0.5, 'gamma': 1, 'lambda': 1, 'A': 1})
OrderedDict([('A', 1), ('c1', 0.5), ('gamma', 1), ('lambda', 1)])

The repr of that OrderedDict should give you a clue to how you can create an OrderedDict with an order for its initial values: create it from a sequence, where each element is a key-value pairs:
>>> print OrderedDict([('c1', 0.5), ('gamma', 1), ('lambda', 1), ('A', 1)])
OrderedDict([('c1', 0.5), ('gamma', 1), ('lambda', 1), ('A', 1)])

If you want to auto-vivify the OrderedDict, you can do that by using OrderedDict instead of dict in your existing class. However, there are a few problems with the class you're using that you might want to consider. In particular, you really want to use super rather than classic-style calls on parent-class methods; if you'd done that, you could just define class AutoVivifiedOrderedDict(OrderedDict, AutoVivification): pass and be done with it! Also, I don't think your class will pickle properly as-is.

If you use a defaultdict for autovivification, it's already taken care of all the tricky bits:
def AutoVivification():
    return defaultdict(AutoVivification)

If you then want to add ordering to that, you will need an OrderedDefaultDict, so you can do this:
def OrderedAutoVivification():
    return OrderedDefaultDict(AutoVivification)

If you don't know how to create OrderedDefaultDict yourself, search for recipes. (You can almost just inherit from both classes… except for the fact that they have different signatures, so you need to think through what your __init__ should look like and explicitly call the right base initializers with the right arguments. See this question for some discussion.)

A: You could add another key to specify the order...
import operator

powers = {0: ['c1', 0.5], 1: ['gamma', 1], 2: ['lambda', 1], 3: ['A', 1]}
print sorted(powers.items(), key=operator.itemgetter(0))

Hope this helps!

A: Dictionaries are not ordered in Python. It won't retain its order once sorted. Instead, use
from collections import OrderedDict

powers = OrderedDict()
powers[1] = {'c1': 0.5, 'gamma': 1, 'lambda': 1, 'A': 1}

print powers[1]


text:
Q: Call to a member function fetch_assoc() on array   $author_content = $db->query( "SELECT * FROM post WHERE author = '$id'" );

  while ( $author_content = $author_content->fetch_assoc() )
  {
    $content = ''.$author_content['name'].'';
  }

Пишет:

[Sun Jun 02 10:18:09.317923 2019] [lsapi:error] [pid 1946075] [client
  62.148.226.69:37464] [host history.kiselyov.ml] Backend fatal error: PHP Fatal error:  Uncaught Error: Call to a member function
  fetch_assoc() on array in
  /var/www/user63337/data/www/history.kiselyov.ml/author.php:22\nStack
  trace:\n#0 {main}\n  thrown in
  /var/www/user63337/data/www/history.kiselyov.ml/author.php on line
  22\n


text:
Q: Demoiselle no OpenJDK Ouvi dizer que o Demoiselle não funciona com OpenJDK.
É verdade? Mesmo para o OpenJDK 7?
Há planos ou trabalho em andamento para que o Demoiselle possa ser usado com o OpenJDK, pelo menos da versão 7 em diante?
Obs: a partir do Java 7, o OpenJDK é a implementação de referência e não há "pedaços não implementados" no OpenJDK ou classes com.sun nas classes padrão. Portanto, utilizar o OpenJDK 7 não deveria ter problemas.

A: Isso não é verdade, pois o Demoiselle funciona com o OpenJDK, inclusive na comunidade recomendamos desenvolver a partir do OpenJDK e depois testar com o JDK da Oracle.
Para verificar isso, você pode baixar o Live DVD que disponibilizamos para os usuários. É uma distribuição do LUbuntu e vem somente com o OpenJDK instalado.
O que ocorre é que o Demoiselle ainda está na especificação 6 do JEE, assim algumas funcionalidades previstas no JEE7 que já é contemplado pelo OpenJDK 7 não são compatíveis.
Há um componente de certificado digital ICP Brasil que foi feito com base no JDK da Oracle porque foi desenvolvido internamente pelo SERPRO e não através do processo da Comunidade, mas já foi corrigido para não ter essa dependência e em breve será lançada a nova versão deste componente.
Já estamos trabalhando numa nova versão do Demoiselle compatível com o JEE7.


text:
Q: jQuery prop('disabled') not working on radio button I am trying to mark a radio button as disabled, which i have had success with before. But i have met a problem i don't understand, where the radio button won't set the disabled attribute, but will without problem set the checked attribute.
I am creating timeslots in a for-loop (based on data collected async) where i create the new timeslot doms through jQuery like so:
for(var key in aTimeslots){
    $timeslot = $('<div/>', {
        "class": "timeslot"
    });

    $timeslotLabel = $('<label/>');

    $timeslotRadio = $('<input />', {
        "type": "radio",
        "class": "timeslots",
        "name": "timeslotRadios"
    });

    // LOGIC TO CHECK IF THE TIMESLOT HAS BEEN RESERVED IS HERE

    // Glue shit together
    $timeslotLabel.append($timeslotRadio);
    $timeslot.append($timeslotLabel);

    // Add the timeslot to the DOM containing all the timeslots
    $availableTimeslots.append($timeslot);

    // Check if the timeslots is reserved
    if(bIsReservedDate){
        $timeslotRadio.prop('checked', true);
        $timeslotRadio.prop('disabled', true);
    }
}

As written above, i set the checked attribute to true, at this works without problem. But the disabled attribute will not be set. Do anyone have an idea why this is? I even moved the logic to after the DOMS have been added to the $availableTimeslots, which so i am sure the doms has been rendered.. but it still doesn't work :(


text:
Q: TypeError: unsupported operand type(s) for +: 'HttpResponse' and 'str' как исправить class Product:
    __MAX_ID = 0
    def __init__(self, name: str, category: str, manufacturer: str, cost: str, hello: str):
        self.id = Product.__MAX_ID
        self.name = name
        self.category = category
        self.manufacturer = manufacturer
        self.cost = cost
        self.hello = hello
        Product.__MAX_ID += 1

    def __str__(self):
        return (
            f'{self.hello}\n'
           + f'name: {self.name}'
           + f'category: {self.category}\n'
           + f'manufacturer: {self.manufacturer}\n'
           + f'cost: {self.cost}\n'
        )

    def home(request):
        product = Product('Привет! Я ',"RX580", 'GPU', 'AMD', '1000$')
        return HttpResponse(f'number: {random.randint(1, 100)}
') + (f"{product}".replace('\n', '
'))


text:
Q: IIS / Proxy Issue: Error 12166 (local webpage) Iam trying to set up a local web site (with IIS in local Intranet).
Therefore i copied the content of the site to:

C:\inetpub\wwwroot\Test

and i converted the folder Test into an application under Default Web Site in IIS. (port 80.)
If i now try to open the site in Browser via
http://localhost/Test/Text.html
i got some errors in my logfile:
gs.client: get: http://localhost/Test/version.txt
System.Net Information: 0 : [8304] Der aktuelle Betriebssysteminstallationstyp ist "Client".
System.Net Information: 0 : [8304] RAS unterstützt: True
System.Net Error: 0 : [8304] Die Proxyeinstellungen für URI "http://localhost/Test/version.txt" können nicht abgerufen werden. Fehlercode: 12166
System.Net Information: 0 : [8304] Associating HttpWebRequest#6614365 with ServicePoint#42849418
System.Net Information: 0 : [8304] Associating Connection#63677697 with HttpWebRequest#6614365
System.Net Information: 0 : [8304] Connection#63677697 - Die Verbindung von 10.10.10.10:52350 mit 10.10.10.10:80 wurde hergestellt.
System.Net Information: 0 : [8304] Associating HttpWebRequest#6614365 with ConnectStream#59134297
System.Net Information: 0 : [8304] HttpWebRequest#6614365 - Request: GET /Test/version.txt HTTP/1.1
System.Net Information: 0 : [4820] ConnectStream#9144789::ConnectStream(Es wurden 5213 Bytes gepuffert.)
System.Net Information: 0 : [4820] Associating HttpWebRequest#34696492 with ConnectStream#9144789
System.Net Information: 0 : [4820] Associating HttpWebRequest#34696492 with HttpWebResponse#27293151
System.Net Error: 0 : [4820] Ausnahme in HttpWebRequest#34696492::GetResponse - Der Remoteserver hat einen Fehler zurückgegeben: (404) Nicht gefunden.
System.Net Error: 0 : [4820] Ausnahme in HttpWebRequest#34696492:: - Die Anfrage wurde abgebrochen: Die Anfrage wurde abgebrochen...
gs.client: get.error: Der Remoteserver hat einen Fehler zurückgegeben: (404) Nicht gefunden.
how can this be solved
Thank you.
PS: This is the Logfile of IIS:
2014-03-31 08:56:29 127.0.0.1 GET /outageMap/ - 80 - 127.0.0.1 Mozilla/5.0+(Windows+NT+6.1;+WOW64;+Trident/7.0;+rv:11.0)+like+Gecko 200 0 0 3
2014-03-31 08:56:31 127.0.0.1 GET /outageMap/OutageMap.html - 80 - 127.0.0.1 Mozilla/5.0+(Windows+NT+6.1;+WOW64;+Trident/7.0;+rv:11.0)+like+Gecko 200 0 0 1
2014-03-31 08:56:31 127.0.0.1 GET /outageMap/geoserver-api/content/user.css - 80 - 127.0.0.1 Mozilla/5.0+(Windows+NT+6.1;+WOW64;+Trident/7.0;+rv:11.0)+like+Gecko 404 0 2 2
2014-03-31 08:56:31 127.0.0.1 GET /outageMap/geoserver-api/content/OutageTable.css - 80 - 127.0.0.1 Mozilla/5.0+(Windows+NT+6.1;+WOW64;+Trident/7.0;+rv:11.0)+like+Gecko 404 0 2 2
2014-03-31 08:56:31 127.0.0.1 GET /outageMap/img/menu_white_28x28.png - 80 - 127.0.0.1 Mozilla/5.0+(Windows+NT+6.1;+WOW64;+Trident/7.0;+rv:11.0)+like+Gecko 200 0 0 3
2014-03-31 08:56:31 127.0.0.1 GET /outageMap/Content/themes/base/jquery-ui.css - 80 - 127.0.0.1 Mozilla/5.0+(Windows+NT+6.1;+WOW64;+Trident/7.0;+rv:11.0)+like+Gecko 200 0 0 3
2014-03-31 08:56:31 127.0.0.1 GET /outageMap/img/arrow_gray_28x28.png - 80 - 127.0.0.1 Mozilla/5.0+(Windows+NT+6.1;+WOW64;+Trident/7.0;+rv:11.0)+like+Gecko 200 0 0 2
2014-03-31 08:56:31 127.0.0.1 GET /outageMap/img/close_12x12.png - 80 - 127.0.0.1 Mozilla/5.0+(Windows+NT+6.1;+WOW64;+Trident/7.0;+rv:11.0)+like+Gecko 200 0 0 1
2014-03-31 08:56:31 127.0.0.1 GET /outageMap/main.css - 80 - 127.0.0.1 Mozilla/5.0+(Windows+NT+6.1;+WOW64;+Trident/7.0;+rv:11.0)+like+Gecko 200 0 0 5
2014-03-31 08:56:31 127.0.0.1 GET /outageMap/img/arrow_white_28x28.png - 80 - 127.0.0.1 Mozilla/5.0+(Windows+NT+6.1;+WOW64;+Trident/7.0;+rv:11.0)+like+Gecko 200 0 0 2
2014-03-31 08:56:31 127.0.0.1 GET /outageMap/img/search.png - 80 - 127.0.0.1 Mozilla/5.0+(Windows+NT+6.1;+WOW64;+Trident/7.0;+rv:11.0)+like+Gecko 200 0 0 1
2014-03-31 08:56:31 127.0.0.1 GET /outageMap/img/search_30x50.png - 80 - 127.0.0.1 Mozilla/5.0+(Windows+NT+6.1;+WOW64;+Trident/7.0;+rv:11.0)+like+Gecko 200 0 0 3
2014-03-31 08:56:31 127.0.0.1 GET /outageMap/img/oms-minimize.png - 80 - 127.0.0.1 Mozilla/5.0+(Windows+NT+6.1;+WOW64;+Trident/7.0;+rv:11.0)+like+Gecko 200 0 0 2
2014-03-31 08:56:31 127.0.0.1 GET /outageMap/img/ajax_loader.gif - 80 - 127.0.0.1 Mozilla/5.0+(Windows+NT+6.1;+WOW64;+Trident/7.0;+rv:11.0)+like+Gecko 200 0 0 7
2014-03-31 08:56:31 127.0.0.1 GET /outageMap/scripts/require.js - 80 - 127.0.0.1 Mozilla/5.0+(Windows+NT+6.1;+WOW64;+Trident/7.0;+rv:11.0)+like+Gecko 200 0 0 22
2014-03-31 08:56:31 127.0.0.1 GET /outageMap/scripts/main.js - 80 - 127.0.0.1 Mozilla/5.0+(Windows+NT+6.1;+WOW64;+Trident/7.0;+rv:11.0)+like+Gecko 200 0 0 130
2014-03-31 08:56:31 127.0.0.1 GET /outageMap/geoserver-api/content/htmlTemplates.html - 80 - 127.0.0.1 Mozilla/5.0+(Windows+NT+6.1;+WOW64;+Trident/7.0;+rv:11.0)+like+Gecko 404 0 2 1
2014-03-31 08:56:31 127.0.0.1 GET /outageMap/geoserver-api/content/configuration.js _=1396256191237 80 - 127.0.0.1 Mozilla/5.0+(Windows+NT+6.1;+WOW64;+Trident/7.0;+rv:11.0)+like+Gecko 404 0 2 1
2014-03-31 08:56:31 127.0.0.1 GET /outageMap/geoserver-api/content/strings.js - 80 - 127.0.0.1 Mozilla/5.0+(Windows+NT+6.1;+WOW64;+Trident/7.0;+rv:11.0)+like+Gecko 404 0 2 1
2014-03-31 08:57:19 127.0.0.1 GET /OutageMap/version.txt - 80 - 127.0.0.1 - 200 0 0 0
2014-03-31 08:57:19 127.0.0.1 GET /OutageMap/geoserver-api/set/Reset - 80 - 127.0.0.1 - 404 0 2 1
2014-03-31 08:58:20 127.0.0.1 GET /OutageMap/version.txt - 80 - 127.0.0.1 - 200 0 0 1
2014-03-31 08:58:20 127.0.0.1 GET /OutageMap/geoserver-api/set/Reset - 80 - 127.0.0.1 - 404 0 2 0
2014-03-31 08:59:20 127.0.0.1 GET /OutageMap/version.txt - 80 - 127.0.0.1 - 200 0 0 1
2014-03-31 08:59:20 127.0.0.1 GET /OutageMap/geoserver-api/set/Reset - 80 - 127.0.0.1 - 404 0 2 0
2014-03-31 08:59:46 127.0.0.1 GET /outageMap/geoserver-api/content/OutageTable.css - 80 - 127.0.0.1 Mozilla/5.0+(Windows+NT+6.1;+WOW64;+Trident/7.0;+rv:11.0)+like+Gecko 404 0 64 1
2014-03-31 08:59:46 127.0.0.1 GET /outageMap/geoserver-api/content/user.css - 80 - 127.0.0.1 Mozilla/5.0+(Windows+NT+6.1;+WOW64;+Trident/7.0;+rv:11.0)+like+Gecko 404 0 2 1
2014-03-31 08:59:46 127.0.0.1 GET /outageMap/geoserver-api/content/htmlTemplates.html - 80 - 127.0.0.1 Mozilla/5.0+(Windows+NT+6.1;+WOW64;+Trident/7.0;+rv:11.0)+like+Gecko 404 0 2 1
2014-03-31 08:59:46 127.0.0.1 GET /outageMap/geoserver-api/content/configuration.js _=1396256386608 80 - 127.0.0.1 Mozilla/5.0+(Windows+NT+6.1;+WOW64;+Trident/7.0;+rv:11.0)+like+Gecko 404 0 2 1
2014-03-31 08:59:46 127.0.0.1 GET /outageMap/geoserver-api/content/strings.js - 80 - 127.0.0.1 Mozilla/5.0+(Windows+NT+6.1;+WOW64;+Trident/7.0;+rv:11.0)+like+Gecko 404 0 2 0
2014-03-31 09:00:21 127.0.0.1 GET /OutageMap/version.txt - 80 - 127.0.0.1 - 200 0 0 1
2014-03-31 09:00:21 127.0.0.1 GET /OutageMap/geoserver-api/set/Reset - 80 - 127.0.0.1 - 404 0 2 0


text:
Q: R ddply dcast alternative? I want to cast my data (data.frame) from long to wide format with the values of "ITEM" as columns and values ("ITEM2") (see below):
Long format:

Wide format:

Therefore I use the dcast-function from the package reshape2:
df <= dcast(df,SEQUENCEID + EVENTID ~ ITEM, value.var="ITEM2")

Doing this everything works fine. But with 7m data records in my data frame I was struggling with memory limits. Thus I decided to use ddply from the package plyr.
To make sure that every split has the same columns in the same order I extract the values from "ITEM" in advance, append the column with N/A if does not exist and order all columns alphabetically.
Below the whole code:
#Example data
lo_raw <- data.frame(SEQUENCEID=rep(1546842, 10),
               EVENTID=c(5468503146,5468503146,5468503146,5468503147,5468503147,5468503148,5468503148,5468503148,5468503148,5468503148),
               ITEM =c("cakes","limonade","coffee","coffee","juice","limonade","cakes","water","fruits","vegetable"),
               ITEM2=c("cakes","limonade","coffee","coffee","juice","limonade","cakes","water","fruits","vegetable"),
               SPLIT=rep(1547000, 10))

#Extract items
item <- as.character(unique(lo_raw$ITEM))

#Function dcast
castff <- function(df,item){

  df = dcast(df, SEQUENCEID + EVENTID ~ ITEM, value.var="ITEM2")

  for(i in item){
    if (!(i %in% colnames(df))){
      df[,i] <- NA
    }
  }

  df <- df[,c(1,2,(order(colnames(df[,3:dim(df)[2]])))+2)]
  df
}

#Apply dcast
df_pivot <- ddply(lo_raw, .(SPLIT), .fun=function(lo_raw,item) castff(lo_raw,item), item=item, .progress="text", .inform=TRUE)

When executing ddply, used RAM is increasing at runtim until it reached its max (12 GB). Thus performance is very slow and I terminated R after a couple of hours.
Is there an alternative way to cast the whole dataset?
Thanks in advance.


text:
Q: Es posible cambiarle el nombre a la base de datatos que se usa desde el controlador con laravel? Tengo actualmente un controlador en donde quiero pasarle el nombre de la base de datos que necesitare hay manera de hacerlo directamente desde un controlador? editar el .env o el config database desde la carpeta config?

A: Primero deberías configurar tus diferentes conexiones en tu archivo database.php, dentro del array "connections":
'connections' => [

    'conexion1' => [
        'driver' => 'sqlsrv',
        'host' => env('DB_HOST', 'SERVER'),
        'port' => env('DB_PORT', '49447'),
        'database' => env('DB_DATABASE', 'NOMBRE_BD_1'),
        'username' => env('DB_USERNAME', 'user'),
        'password' => env('DB_PASSWORD', 'pass'),
        'charset' => 'utf8',
        'prefix' => '',
        'prefix_indexes' => true,
    ],

    'conexion2' => [
        'driver' => 'sqlsrv',
        'host' => env('DB_HOST', 'SERVER'),
        'port' => env('DB_PORT', '49447'),
        'database' => env('DB_DATABASE', 'NOMBRE_BD_2'),
        'username' => env('DB_USERNAME', 'user'),
        'password' => env('DB_PASSWORD', 'pass'),
        'charset' => 'utf8',
        'prefix' => '',
        'prefix_indexes' => true,
    ],

Luego, digamos que la función dentro de tu controlador recibe un parámetro con el nombre de la conexión, simplemente la referencias al hacer tu query:
public function getUsuarios(Request $req){
$nombreconexion = $req->nombreconexion;
$data=DB::connection($nombreconexion)->table('usuarios')->where('categoria', 'empleado')->get();
}


text:
Q: attention calculation at matrix level I am confused with the calculation in self attention or attention only.
Lets talk about self-attention first and I have:
x -> [batch_size, query_len, embedding_size]

now query's shape = key's shape = value's shape in self-attention, so
query = key = value = [batch_size, query_len, embedding_size]

self-attention -> softmax((query x key)/ square_root(key_len)) x value

In coding, I am confused in which dimension to apply softmax and how to take care of multiplication of score with value ? I mean which dimension is multiplied with each other ?
def attention(self, query, key, value):
    N = query.shape[0] # batch size
    # context's shape -> [batch_size, 10, 768]
    query_len, key_len, value_len = query.shape[1], key.shape[1], value.shape[1]

    energy = torch.einsum("nqd,nkd->nqk", [query, key])
    # [b, 10, 768]* [b, 10, 768] -> [b, 10, 10]
    attention = torch.softmax(energy / (self.embed_dim ** (1/2)), dim= 2)

    out = torch.einsum("nql, nld-> nqd", [attention, value])

    return out, attention


text:
Q: Swift: Check if data response is an array or a dictonary I'm calling an API and storing the data in an array.
But if there is no data the debugger says:
Expected to decode Array but found a dictionary instead.
The fail JSON response is:
    '{"status":"Failed","msg":"Sorry It\'s Not Working"}'

The success JSON response is:
'[{"id":"509","name":"TEC TEST !"#!12","sortingId":"1"},
{"id":"510","name":"TEC TEST !"#!12","sortingId":"2"},
{"id":"511","name":"TEC TEST !"#!12","sortingId":"3"},
{"id":"512","name":"TEC TEST !"#!12","sortingId":"4"},
{"id":"513","name":"TEC TEST !"#!12","sortingId":"5"},
{"id":"514","name":"TEC TEST !"#!12","sortingId":"6"},
{"id":"519","name":"TEC TEST !"#!12","sortingId":"7"}]'

So I want to switch between fetching my response as
var result:[Items]?

and
var result:Items?

if the Failed JSON gets send
I've been google´ing and searching Stackoverflow without luck
Is there an solution to say if JSON is an array or dictionary?
My Struct:
struct Items: Codable {
    let id: String?
    let sortingId: String?
    let name: String?
    let response: String?
    let status: String?
    let msg: String?
}

My processing of the response:
var result:[Items]?
result = try JSONDecoder().decode([Items].self, from: data!)
DispatchQueue.main.async {
for item in result! {
  self.itemArray.append((name: item.name!, id: Int(item.id!)!, sortingId: Int(item.sortingId!)!))
  }
}

A: One solution is to write a custom initializer which conditionally decodes the array or the dictionary.
Please ask the owner of the service to send more consistent JSON. It's very bad. At least the object should be always a dictionary with key status and either the array for key items or the key msg.
This code first tries to decode the array with unkeyedContainer. If it fails it decodes the dictionary.
struct Item: Decodable {
    let id: String
    let sortingId: String
    let name: String
}

struct ItemData : Decodable {

    private enum CodingKeys: String, CodingKey { case status, msg }

    let status : String?
    let msg: String?
    var items = [Item]()

    init(from decoder: Decoder) throws {
        do {
            var unkeyedContainer = try decoder.unkeyedContainer()
            while !unkeyedContainer.isAtEnd {
                items.append(try unkeyedContainer.decode(Item.self))
            }
            status = nil; msg = nil
        } catch DecodingError.typeMismatch {
            let container = try decoder.container(keyedBy: CodingKeys.self)
            status = try container.decodeIfPresent(String.self, forKey: .status)
            msg = try container.decodeIfPresent(String.self, forKey: .msg)
        }
    }
}

And call it
result = try JSONDecoder().decode(ItemData.self, from: data!)

A – probably more suitable – alternative is to catch the error in the  JSONDecoder().decode line and use two simple structs
struct Item: Decodable {
    let id: String
    let sortingId: String
    let name: String
}

struct ErrorData : Decodable {
    let status : String
    let msg: String
}

and call it
do {

    let decoder = JSONDecoder()
    do {
       let result = try decoder.decode([Item].self, from: data!)
       print(result)
    } catch DecodingError.typeMismatch {
       let result = try decoder.decode(ErrorData.self, from: data!)
       print(result)
    }
} catch { print(error) }

A big benefit is that all properties can be non-optional.

A: First of all the JSON does not contain any array. It's very very easy to read JSON. There are only 2 (two!) collection types, array [] and dictionary {}. As you can see there are no square brackets at all in the JSON string.
   it will helpful


text:
Q: Clojure or Scala for bioinformatics/biostatistics/medical research I am not a professional programmer (my area is medical research), but I am quite capable in C/C++, and various scripting languages. A while back I got intrigued by Lisp, but I never got the time to seriously learn it. After a brief exposure to R I decided to invest more time in a functional programming language.
I would like the practicality of a JVM language and thus narrowed to Clojure and Scala. From what I understand, both can use already existing Java libraries and given at performance-critical code can be delegated to Java, have the potential to perform relatively equally well.
How do these languages compare in the application space I need them for?
Are There any real-life projects in bioinformatics using either?
Already existing code would be a serious plus, as would be good documentation and a fairly gentle learning curve. Also, how does the concurrency model of the two compare with each other?
Any significant advantages/disadvantages any one has?

A: I am only passingly familiar with Scala, so the best I can do is evangelize a bit for Clojure. It's a great language, but take all this advice with a grain of salt as it's coming from an enthusiast.
If you are looking for concurrency, Clojure is fantastic both for ease of programming and for performance. The immutable data structures mean that it's trivial to work with a coherent snapshot of the world without any manual and error-prone locking; the STM makes it fairly simple to change data in a thread-sensitive way without breaking anyone else's snapshots.
My understanding is that Scala has a lot of the nice functional tools that Clojure does, but Clojure will always win syntactically by virtue of being a Lisp. If you're looking to do some specialized bioinformatics stuff, Clojure is able to hide the bits of Lisp that you don't want, and raise your own constructs to the same level as the built-in language constructs. I can't find the reference right now, but there's some well-known quote about Lisp that goes like:

Lisp is not the perfect language for any program. But it is the perfect language for building the perfect language for every program.

That's horribly paraphrased, but in my experience it has been true. It looks like you'll want a fairly specialized set of tools, and no language will make those feel as natural as a Lisp.

A: You have to ask yourself how important functional programming is for you. You know C++ so you probably know OO. I would say it's easier to do FP in Clojure (because you can't really drop back to OO-style) in Scala you will probebly end up dropping FP and do more OO style.
I can't really say anything about your application space.
Since you mentioned R, there is an R-like Clojure library for statistics called Incanter. I don't know about other existing projects in your application space.
There is a lot of information about both languages, so that should not be a problem. The learning curve is kind of steep with both languages. Clojure is a much smaller language and since you already know some lisp it should not be to hard to learn the important stuff. Scala has a type system that will be hard to pick up especially since your main experience is with C/C++.
Both languages have great concurrency models and you will probably be happy with both.

A: I can personally vouch for Clojure as a great tool for this kind of work. (I believe Scala would be great too, I just have less experience with it).
My personal research is in the field of predictive modelling / machine learning and is very computationally intensive - so I think it has many parallels with bioinformatics or biostatistics.
My personal approach / setup includes:

*

*Incanter used primarily as a data visualisation tool. Great for producing quick visualisations which are usually just 1-liners at the REPL. There are also lots of statistical and numerical processing tools which I believe use the Colt library under the hood. I'm not an expert in R but I understand that Incanter is roughly "R translated to Clojure/Lisp".

*Exploiting quite a few Java libraries as needed. Some of these are my own, for example algorithms that I have written in Java in order to get the best possible fine-tuned performance out of the JVM. But you could equally easily use any of the other great Java libraries available, as calling Java from Clojure is very simple (.methodName object param1 param2)

*Quite a lot of higher order functions to automate my workflow. For example I have a higher order function that will run an optimisation algorithm of any kind in a loop for a specified amount of time and then produce an Incanter graph of the improvement on each iteration. Not rocket science, but really easy to code up in a few lines of Clojure.

*Never really having to worry about performance. You can make Clojure go pretty fast if you want to (e.g. with type hints, primitive arithmetic support etc.) but normally it's irrelevant as you're going to spend 99%+ of your cycles in well-optimised library code anyway. Hence a bit of overhead in the "glue" code is negligible - I feel I gain much more in terms of personal productivity by having a dynamic, high-level, functional language to work in.

*Major use of Clojure's concurrency features - this has to be one of Clojure's strongest features. I tend to use the STM to code concurrent processes with transactions that can't interfere with each other, then kick off long-running calculations in a future so that I can get on with other tasks and wait for notification of the result.

*A slowly growing collection of macros to "extend the language" when needed. I actually use macros less than I thought I would (higher order functions are often a better choice). But when you need them they are invaluable - this is where you really appreciate the value of a homoiconic language. Since they effectively allow you to add new syntax to the language itself, they are very powerful when used correctly to build the DSL that you need.
In short - I don't think you can go wrong with Clojure as a researcher.
The one thing I probably wouldn't use it for (yet) is actually writing a new numerical library - this would probably be better done in Scala or pure Java as you would probably want to adopt a more imperative / OOP style.

A: I am not sure about bioinformatics and biostatistics per se, but I do scientific data analysis frequently and I appreciate that Scala allows me to write as-fast-as-Java code with relative ease.  I believe that it is often possible in Clojure now, but I haven't seen the benchmarks to back that up.  For the time being, I think the prudent thing to assume is that they do not perform equally well.  See, for example, the Computer Languages Benchmark Game, where Scala is faster than Clojure in every single test.  (Ignore the horrible "pidigits" result for Clojure--Scala (and Java) are calling the GMP library written in C, which Clojure could do but because of a technical detail requiring a different wrapping for the library, isn't presently allowed in the game).  Looking at multicore comparisons doesn't improve Clojure's showing, and note that the Clojure code is no shorter for these sorts of lowish-level algorithmic tasks.
Clojure is ahead for the time being with parallel collections, though the upcoming 2.9 release of Scala should make up much of the difference.  Neither has a gentle learning curve when coming from C++; Scala is maybe a little easier given that the syntax outwardly looks a little more familiar.  I believe there are good materials for learning each of them.

Edit: P.S. You can call R from Java (and therefore from either Clojure or Scala) using rJava (specifically the JRI interface).  Edit to edit: and, these days, rScala.
Edit #2: Scala was faster than Clojure in everything at the time of writing; as of this edit, Clojure's a little ahead in one (at the cost of a huge amount of code)--but anyway, the overall point stands.  (And the Scala implementation on that one test could be sped up.)

A: I have some experience in Scala and only little knowledge in Clojure, but I programmed Lisp many years ago.
Lisp is a beautiful language, but it never made it to the world, because it was too limited. I believe you need a statically-typed language to develop robust systems. The type system in Scala is not difficult to master to benefit from it. If you want to do very advanced things with it to make your libraries idiot-proof, you can, but then you will need to study the type system a little more.
Scala favours immutable types, but you can use mutables without any problem, which you sometimes do need. Concurrency in Scala is very well implemented and frameworks like akka extend and enhance these possibilities.
Scala stands a better chance to become a mainstream language since it's a fuller language. I'm afraid that Clojure is too much like Lisp (but reimplemented on the JVM). I liked Lisp a lot, but it had too many disadvantages for real-life programs. With Scala I think we have the best of both worlds (OO and functional) in a clean marriage. On top of that, Scala seems to really catch on in the market.

A: If you like R, give Incanter a try! It's R for Clojure.
Scala's is geared toward being syntactically easy for people coming from Java, which was intended to be syntactically easy for people coming from C though with two levels of indirection like this the advantage may be lost.
Clojure is getting a lot of traction in the Big Data space and maps very well onto Hadoop jobs for Huge Data. I think this would be a big advantage in the bioinformatics world.
Really, these things are largely personal taste so try both and see that makes you happy :)
If you are looking to get a feel for Clojure without a lot of "intellectual overhead" may I suggest using leiningen to get a test project started quickly?

A: To build on Rex's answer I would like to add some Scala libraries/products that may be of interest to you:

*

*ADAM

*Spark (sparkseq, 2)

*Scala Map Reduce (SMR): http://scala-blogs.org/2008/09/scalable-language-and-scalable.html

*SHadoop: http://jonhnny-weslley.blogspot.com/2008/05/shadoop.html

*ScalaLab: MATLAB-like scientific computing in Scala

*ScalaNLP: Collection of libraries for natural language processing (NLP), machine learning, and statistics.

*Factorie: Toolkit for deployable probabilistic modeling

*Gridgain: Compute cluster for Scala and Java

*BioScala: Bioinformatics for the Scala programming language

A: I don't know Scala, so I can't offer a comparison, but I am actively using Clojure in bioinformatics projects.
The Java integration is excellent, and I have had no problem making use of the BioJava libraries.
Where Clojure's concurrency model shines is in the immutable default data types and functional programming with the seq abstraction.
In my bioinformatic work I very often find myself with a lot input data (say gene sequences) which need to be subjected to the same analysis. Once I have my analysis function I can map it over a sequence of inputs (with the results lazily generated). I have gotten full utilization of a large 48-core server simply by changing that map to a pmap.
Large scale parallelization with a single character change is hard to beat!
Of course pmap isn't a magic bullet and only helps when the analysis function computationally dominates, but the fact that map and pmap can just be plugged in and out shows the elegance and simplicity enabled by Clojure's design.

A: We have been working on some experimental code in the Rudolf/BioClojure project on GitHub. Also, look at Jan Aert's BioClojure project which is more structured.
Additionally, there is a BioCaml project in the works...


text:
Q: Adding custom schema to openldap I want to setup my postfix with ldap authentication. I follow this tutorial https://blog.tnyc.me/postfix-with-ldap
I need to setup a PostfixBookMailAccount but therefore i need to load that schema. I tried this one schema and adjusted the attributetype to attributetype:, same for objectclass (syntax change in newer ldap version)
Loading this schema looks good without an error.
root@openldap:~/postfix# ldapadd -Y EXTERNAL -H ldapi:/// -f /etc/ldap/schema/postfix-book.ldif
SASL/EXTERNAL authentication started
SASL username: gidNumber=0+uidNumber=0,cn=peercred,cn=external,cn=auth
SASL SSF: 0

But i can not choose a schema called PostfixBookMailAccount!
Any ideas?

Edit
Ok I found out that i have to convert the schema to a ldif first ... but doing this results in an error
root@openldap:/etc/ldap/schema# cat schema_conv.conf
include /etc/ldap/schema/postfix-book.schema

root@openldap:/etc/ldap/schema# slaptest -f ./schema_conv.conf -F /tmp/ldif/
5d3d5e5c /etc/ldap/schema/postfix-book.schema: line 72 objectclass: AttributeType not found: "mail"

A: Ok I had to add some core schemas to be able to convert the postfix schema
include /etc/ldap/schema/core.schema
include /etc/ldap/schema/cosine.schema
include /etc/ldap/schema/inetorgperson.schema
include /etc/ldap/schema/nis.schema
include /tmp/ldif/ldap-mail-schema-master/postfix-book.schema

then slaptest did the job


text:
Q: Discord.js Send a message every X seconds with Client.on('ready', () => { }); I would like to send a message every X seconds and that the user who reacts first gives him 10 coins.
The problem does not come from the system of coins, it is correctly executed.
This code does not work and tells me
Cannot read properties of undefined (reading 'send')
I know this is because I'm not using Client.on('message', message => {  }) but I really wish it would go through ready is there any way to do it differently? Can you help me to correct this code?
Client.on('ready', () => {
    const fs = require('fs');

    const userCoin = JSON.parse(fs.readFileSync('Storage/userCoin.json', 'utf-8'));

    const channel2up22 = Client.channels.cache.get('935549530210983976');

                    //Random Drop
    const doSomething = () => {
        let Embed = new Discord.MessageEmbed()
                    .setTitle("Wild Gift  ! | GuinGame - v2.0 ")
                    .setColor('#caabd0')
                    .setDescription("Be the **first** to react ``''`` to this message to win **10 !**")
                    .setThumbnail("https://media.giphy.com/media/Jv1Xu8EBCOynpoGBwd/giphy.gif")
                    .setFooter(text=" GuinbearBot  |   Guinbeargang.io")
                    .setTimestamp()
                    channel2up22.send(Embed)
                    .then(message => {
                        message.react('');
                    Client.on('messageReactionAdd', (reaction, user) => {
                        if (reaction.emoji.name === '' && user.id == "338621907161317387") {
                            message.delete();
                            var Magic09 = 1;
                            while (Magic09 <= 10)
                                {
                                userCoin[user.id].CoinsAmount++;
                                Magic09++;
                                }
                        fs.writeFile('Storage/userCoin.json', JSON.stringify(userCoin), (err) => {if (err) console.error(err);})
                            let Embed = new Discord.MessageEmbed()
                            .setTitle("Wild Gift  ! | GuinGame - v2.0 ")
                            .setColor('#caabd0')
                            .setDescription("<@"+ user.id + "> has won the **Wild Gift  !**")
                            .setThumbnail("https://media.giphy.com/media/Jv1Xu8EBCOynpoGBwd/giphy.gif")
                            .setFooter(text=" GuinbearBot  |   Guinbeargang.io")
                            .setTimestamp()
                            channel2up22.send(Embed)
                        }
                    })
                    }).catch(console.error);
      }
    setInterval(doSomething(), 5000)
  })

                    //Random Drop
        });

A: Not able to fully test this code but this should work assuming all this code goes into a single file, if you get errors or anything comment below and I'll see what I can do to help out.
// Near top of file but after you have defined your client with const Client = new Discord.Client()
const fs = require('fs')
const Discord = require('discord.js')
const Client = new Discord.Client ({
    intents: /*your intents here*/,
})
const guild = Client.guilds.cache.get('935549530210983976')
const channel2up22 = guild.channels.cache.get('935549530210983976');
// channels are an element of the guild not the client
const userCoin = JSON.parse(fs.readFileSync('Storage/userCoin.json', 'utf-8'));

// placing the function outside of a listener and can be called at anytime
function doSomething() {
    const Embed = new Discord.MessageEmbed()
        .setTitle("Wild Gift  ! | GuinGame - v2.0 ")
        .setColor('#caabd0')
        .setDescription("Be the **first** to react ``''`` to this message to win **10 !**")
        .setThumbnail("https://media.giphy.com/media/Jv1Xu8EBCOynpoGBwd/giphy.gif")
        .setFooter({
            text: " GuinbearBot  |   Guinbeargang.io"
        })
        .setTimestamp()
    channel2up22.send({
        embeds: [Embed]
    }).then(message => {
        message.react('');
    }).catch(console.error);
}

Client.on('ready', () => {
    setInterval(doSomething(), 5000)
    // every 5 seconds
})

// you want to avoid nesting listeners if at all possible
Client.on('messageReactionAdd', async (reaction, user) => {
    if (reaction.message.channel.id === channel2up22) {
        if (reaction.emoji.name === '' && user.id === "338621907161317387") {
            // only lets one user react
            reaction.message.delete();
            var Magic09 = 1;
            while (Magic09 <= 10) {
                userCoin[user.id].CoinsAmount;
                Magic09++;
            }
            fs.writeFile('Storage/userCoin.json', JSON.stringify(userCoin), (err) => {
                if (err) console.error(err);
            })
            const Embed = new Discord.MessageEmbed()
                .setTitle("Wild Gift  ! | GuinGame - v2.0 ")
                .setColor('#caabd0')
                .setDescription(`${user} has won the **Wild Gift  !**`)
                .setThumbnail("https://media.giphy.com/media/Jv1Xu8EBCOynpoGBwd/giphy.gif")
                .setFooter({
                    text: " GuinbearBot  |   Guinbeargang.io"
                })
                .setTimestamp()
            channel2up22.send({
                embeds: [Embed]
            })
        }
    }
})

A: Here is my code after your first modifications,
I got now an error back : Uncaught TypeError TypeError: Cannot read properties of undefined (reading 'channels') on the line : const channel2up22 = guild.channels.cache.get('935549530210983976');

const Discord = require("discord.js");
const Client = new Discord.Client;
const fs = require('fs')
const guild = Client.guilds.cache.get('925830522138148976');

const channel2up22 =
 guild.channels.cache.get('935549530210983976');

const userCoin = JSON.parse(fs.readFileSync('Storage/userCoin.json', 'utf-8'));

function doSomething() {
    const Embed = new Discord.MessageEmbed()
        .setTitle("Wild Gift  ! | GuinGame - v2.0 ")
        .setColor('#caabd0')
        .setDescription("Be the **first** to react ``''`` to this message to win **10 !**")
        .setThumbnail("https://media.giphy.com/media/Jv1Xu8EBCOynpoGBwd/giphy.gif")
        .setFooter({
            text: " GuinbearBot  |   Guinbeargang.io"
        })
        .setTimestamp()
    channel2up22.send({
        embeds: [Embed]
    }).then(message => {
        message.react('');
    }).catch(console.error);
}

Client.on('ready', () => {
    setInterval(doSomething(), 5000)
});

Client.on('messageReactionAdd', async (reaction, user) => {
    if (reaction.message.channel.id === channel2up22) {
        if (reaction.emoji.name === '' && user.id === "338621907161317387") {
            reaction.message.delete();
            var Magic09 = 1;
            while (Magic09 <= 10) {
                userCoin[user.id].CoinsAmount;
                Magic09++;
            }
            fs.writeFile('Storage/userCoin.json', JSON.stringify(userCoin), (err) => {
                if (err) console.error(err);
            })
            const Embed = new Discord.MessageEmbed()
                .setTitle("Wild Gift  ! | GuinGame - v2.0 ")
                .setColor('#caabd0')
                .setDescription(`${user} has won the **Wild Gift  !**`)
                .setThumbnail("https://media.giphy.com/media/Jv1Xu8EBCOynpoGBwd/giphy.gif")
                .setFooter({
                    text: " GuinbearBot  |   Guinbeargang.io"
                })
                .setTimestamp()
            channel2up22.send({
                embeds: [Embed]
            })
        }
    }
});


text:
Q: dynamically create an image with image URL's I have a single decorated "picture frame" image with 5 blank boxes.
The user will provide 5 facebook picture URL's which will populate the 5 blank boxes.
I want to take the resulting "picture frame" populated with these 5 uploaded photos and generate a SINGLE image... with PHP/html/css/javascript... is this possible??
I already know that I can take the 5 URL's, upload them to a database and spit out the "template" image with the placeholder background-image source to be pulled from the picture URL's.  The problem is generating this SINGLE image... how can I do this?  please help!
thanks

A: You can use PHP GD to generate an image from the 5 uploaded photos.
See PHP GD Documentation


text:
Q: How do I plot several graphs from one DF without manually retyping the graph function each time I have a DF with prices (Open) and volume for lots of different stocks on each day. I'm trying to plot the same chart for each ticker (shown below example for EZJ). However, i'd like to be able to do this for all the different tickers without having to manually isolate each ticker in a separate df and then retype the plot function. And if the Ticker's in the df change, there is no requirement to update the code.
Ticker  Date    Open    volume_m
EZJ 2016-01-04  17.3    1.311801
EZJ 2016-01-05  17.45   0.808658
EZJ 2016-01-06  17.64   1.027079
EZJ 2016-01-07  17.21   2.484108
EZJ 2016-01-08  16.78   1.733707
... ... ... ...
KO  2021-02-11  0.4981  21.928581
KO  2021-02-12  0.5057  13.137059
KO  2021-02-16  0.5062  15.093406
KO  2021-02-17  0.5 12.775807
KO  2021-02-18  0.5016  12.749841

ezj_stock=stock_returns.loc['EZJ'].set_index('Date')
ezj_stock['14d_mean_price']=ezj_stock['Open'].rolling(window=14).mean()

plt.figure(figsize=(10,5))
top = plt.subplot2grid((4,4), (0, 0), rowspan=3, colspan=4)
bottom = plt.subplot2grid((4,4), (3,0), rowspan=1, colspan=4)
top.plot(ezj_stock.index, ezj_stock['Open'])
bottom.bar(ezj_stock.index, ezj_stock['volume_m'])
top.plot(ezj_stock.index, ezj_stock['14d_mean_price'])

# set the labels
top.axes.get_xaxis().set_visible(False)
top.set_title('EZJ')
top.set_ylabel('Open_Price £', fontsize=12)
bottom.set_ylabel('Volume (mn)', fontsize=10) ```

A: This can be done by running the plotting functions in a for loop that goes through the list of tickers and makes it possible to select the data corresponding to each ticker in an automated way. In the following example, the data for each ticker is selected by using boolean indexing with stocks[stocks['ticker'] == ticker]:
import numpy as np               # v 1.19.2
import pandas as pd              # v 1.1.3
import matplotlib.pyplot as plt  # v 3.3.2

# Create sample of random data for daily stock opening price and volume traded
rng = np.random.default_rng(seed=1234)  # random number generator
dti = pd.bdate_range(start='2016-01-01', end='2021-02-22')
ABC = pd.DataFrame(data=dict(ticker='ABC',
                             Open = 100 + rng.normal(size=dti.size).cumsum(),
                             volume_m = rng.uniform(0.5, 3, size=dti.size)),
                   index=dti)
XYZ = pd.DataFrame(data=dict(ticker='XYZ',
                             Open = 50 + rng.normal(size=dti.size).cumsum(),
                             volume_m = rng.uniform(0.5, 3, size=dti.size)),
                   index=dti)
stocks = pd.concat([ABC, XYZ])
stocks

for ticker in stocks['ticker'].unique():
    stock = stocks[stocks['ticker'] == ticker].copy()
    stock.loc[:, '14d_mean_price'] = stock['Open'].rolling(window=14).mean()

    plt.figure(figsize=(10,5))
    top = plt.subplot2grid((4,4), (0, 0), rowspan=3, colspan=4)
    bottom = plt.subplot2grid((4,4), (3,0), rowspan=1, colspan=4)
    top.plot(stock.index, stock['Open'])
    bottom.bar(stock.index, stock['volume_m'])
    top.plot(stock.index, stock['14d_mean_price'])

    # set the labels
    top.axes.get_xaxis().set_visible(False)
    top.set_title(ticker)
    top.set_ylabel('Open_Price £', fontsize=12)
    bottom.set_ylabel('Volume (mn)', fontsize=10)


text:
Q: game displayed in the bottom-left quarter of my screen in SDL2 I recently updated my mac and the code that was normally running stopped functioning.
When I now run my program (a game) the window still has the right dimensions but the elements are displayed in the bottom-left quarter of my screen.

I don't understand where it comes from.
here is the .cpp that I used in the exemple:
#include "../../include/game.h"

int     main(int argc, char **argv)
{
    SDL_Window      *window;
    SDL_Renderer    *render;
    int             w;
    int             h;

    (void)argc;
    (void)argv;

    SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER);
    window = SDL_CreateWindow("lul", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, WINDOW_W, WINDOW_H, 0);
    render = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
    SDL_GetWindowSize(window, &w, &h);

    SDL_Surface     *surface;
    SDL_Texture     *texture;

    surface = IMG_Load("FondHome2.jpg");
    texture = SDL_CreateTextureFromSurface(render, surface);

    SDL_Event   event;
    bool        close_requested = false;

    while (!close_requested)
    {
        while (SDL_PollEvent(&event))
        {
            if (event.type == SDL_QUIT)
            {
                close_requested = true;
            }
        }
        SDL_RenderCopy(render, texture, NULL, NULL);
        SDL_RenderPresent(render);
    }

    return(0);
}

and here is the .h used:
#ifndef GAME_H
# define GAME_H

# include <SDL2/SDL.h>
# include <SDL2/SDL_timer.h>
# include <SDL2/SDL_image.h>
# include <SDL2/SDL_ttf.h>

# include <fstream>
# include <iostream>
# include <string>
# include <vector>
# include <stdarg.h>
# include <math.h>

# define WINDOW_W 400
# define WINDOW_H 300

#endif

A: See content related to High-DPI differences when working with Retina displays on Mac: SDL_GL_GetDrawableSize. Pass the SDL_WINDOW_ALLOW_HIGHDPI flag to SDL_CreateWindow, and the SDL_Render API should do the right thing.
The problem is that without high DPI enabled, the actual width and height of your SDL_Window correspond to more pixels than you passed to SDL_CreateWindow (2X width and height, in this case). It seems like SDL_RenderCopy still thinks the target framebuffer is 400x300, which is correct when the DPI scaling factor is 1. When the image is drawn, only 1/4 of the physical space is covered.
I can't tell you exactly where the scaling issue happens without reading the SDL2 source, since it could be happening with an internal framebuffer or during the final blit, but the issue is the assumption of a DPI scaling factor of 1. Passing the SDL_WINDOW_ALLOW_HIGHDPI flag during window creation tells SDL to query the actual monitor DPI to be used.
Related issue: SDL 2.0 retina mac


text:
Q: Trouble Installing spaCy english model in python 2.7? And upgrading python to 3.5? I am trying to install the spaCy english model on my mac after installing the program. Right now my machine has python 2.7. I have installed spaCy in the venv then followed that with "python -m spacy.en.download" to install the model as instructed on the website. When I try to do that I get the following in response:

$ python -m spacy.en.download

Traceback (most recent call last):

  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/runpy.py", line 162, in _run_module_as_main
    "__main__", fname, loader, pkg_name)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/runpy.py", line 72, in _run_code
    exec code in run_globals
  File "/Users/katietemrowsky/Documents/Desktop/machine/.env/lib/python2.7/site-packages/spacy/en/download.py", line 1, in
    import plac
  File "/Users/katietemrowsky/Documents/Desktop/machine/.env/lib/python2.7/site-packages/plac.py", line 38, in
    from plac_tk import TkMonitor
  File "/Users/katietemrowsky/Documents/Desktop/machine/.env/lib/python2.7/site-packages/plac_tk.py", line 46
    print('Process %d killed by CTRL-C' % os.getpid(), file=sys.stderr)
                                                           ^
SyntaxError: invalid syntax

I then tried to install spaCy and the model on my computer outside of the venv which I would rather not do, but wanted to see if it would work. Again I got the same error.
Additionally I am wondering if the issue has something to do with running python 2.7? I upgraded my python on my computer to 3.5 but am not sure how to replace 2.7 with 3.5? Right now I can run both on the interpreter using $ python or $ python3. How can I upgrade everything to 3.5?
Thank you in advance!

A: In short:
The latest version of spacy and plac doesn't have this issue anymore.
Upgrade your spacy version, it should automatically upgrade plac too:
pip install -U spacy

In long:
In the latest version of spacy, the import plac line is no longer in the spacy.en.download.py but the plac library is used in other places
plac is an argument parser like the native argparse or the popular docopt.
  File "/Users/katietemrowsky/Documents/Desktop/machine/.env/lib/python2.7/site-packages/plac_tk.py", line 46
    print('Process %d killed by CTRL-C' % os.getpid(), file=sys.stderr)
                                                           ^
SyntaxError: invalid syntax

The error you've occurred above is caused by the difference between the print_function syntax of Python2 and Python3, i.e.:
alvas@ubi:~$ python
Python 2.7.12 (default, Nov 19 2016, 06:48:10)
[GCC 5.4.0 20160609] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> print('foo bar', file=sys.stderr)
  File "<stdin>", line 1
    print('foo bar', file=sys.stderr)
                         ^
SyntaxError: invalid syntax
>>> exit()
alvas@ubi:~$ python3
Python 3.5.2 (default, Nov 17 2016, 17:05:23)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> print('foo bar', file=sys.stderr)
foo bar

And this was introduced by this commit.
Since there is the from __future__ import print_function at https://github.com/micheles/plac/blob/46d8d393fbca8820e5cba5d1da808b65a1c879a3/plac_tk.py#L1
The print_function should have kicked in and allow the file= parameters in the print for Python2, e.g.
alvas@ubi:~$ python2
Python 2.7.12 (default, Nov 19 2016, 06:48:10)
[GCC 5.4.0 20160609] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from __future__ import print_function
>>> import sys
>>> print('foo bar', file=sys.stderr)
foo bar

But the __future__ import from plac didn't kick in and that remains a mystery to me =( But that's another answer for another question at another time...


text:
Q: MySQL - Persistent connection vs connection pooling In order to avoid the overhead of establishing a new connection each time a query needs fired against MySQL, there are two options available:

*

*Persistent connections, whereby a new connection is requested a check is made to see if an 'identical' connection is already open and if so use it.

*Connection pooling, whereby the client maintains a pool of connections, so that each thread that needs to use a connection will check out one from the pool and return it back to the pool when done.

So, if I have a multi-threaded server application expected to handle thousands of requests per second, and each thread needs to fire a query against the database, then what is a better option?
From my understanding, With persistent connections, all the threads in my application will try and use the same persistent connection to the database because they all are using identical connections. So it is one connection shared across multiple application threads - as a result the requests will block on the database side soon.
If I use a connection pooling mechanism, I will have all application threads share a pool of connections. So there is less possibility of a blocking request. However, with connection pooling, should an application thread wait to acquire a connection from the pool or should it send a request on the connections in the pool anyway in a round-robin manner, and let the queuing if any, happen on the database?

A: Having persistent connections does not imply that all threads use the same connection. It just "says" that you keep the connection open (in contradiction to open a connection each time you need one). Opening a connection is an expensive operation, so - in general - you try to avoid opening connections more often than necessary.
This is the reason why multithreaded applications often use connection pools. The pool takes care of opening and closing connections and every thread that needs a connection requests one from the pool. It is important to take care that the thread returns the connection as soon as possible to the pool, so that another thread can use it.
If your application has only a few long running threads that need connections you can also open a connection for each thread and keep this open.
Using just one connection (as you described it) is equal to a connection pool with the maximum size one. This will be sooner or later your bottleneck as all threads will have to wait for the connection. This could be an option to serialize the database operations (perform them in a certain order), although there are better options to ensure serialisation.

A: Update: The newer X Protocol supports asynchronous connections, and newer drivers like Node's can utilize this.
Regarding your question about should the application server wait for a connection, the answer is yes.
MySQL connections are blocking. When you issue a request from MySQL server over a connection, the connection will wait, idle, until a response is received from the server.
There is no way to send two requests on the same connection and see which returns first. You can only send one request at a time.
So, generally, a single thread in a connection pool consists of one client side connection (in your case, the application server is the client) and one server side connection (database).
Your application should wait for an available connection thread from the pool, allowing the pool to grow when it's needed, and to shrink back to your default number of threads, when it's less busy.


text:
Q: Need detailed working or explanation of SCAN register in DSPIC I am not able to figure out the working of SCAN register in DSPIC30F2010.I need to read 4 analog inputs in ADC and for that need to set the sampling and conversion

A: From dsPIC30F2010 datasheet,

The inputs are selected by the ADCSSL register. If a particular bit in
  the  ADCSSL register is '1', the corresponding input is selected. The
  inputs are always scanned from lower to higher numbered inputs,
  starting after each interrupt. If the number of inputs selected is
  greater than the number of samples taken per interrupt, the higher
  numbered inputs are unused.

Code example is here (for 4013, but the idea is the same)


text:
Q: Clock Pulse is shifting in Tikz-timing? MWE
\documentclass[border=2mm]{standalone}
\usepackage{tikz}
\usepackage{tikz-timing}
\usetikztiminglibrary[dual arrows]{clockarrows}
\begin{document}
\begin{tikztimingtable}[
scale=2.5,
timing/slope=0.1,
timing/rowdist=3ex,
]
\textnormal{Clock} &  [black] {h} 47{c} \\
\extracode
\begin{pgfonlayer}{background}
\node[anchor=east] at (row1.north west){\tiny +5V};
\node[anchor=east] at (row1.south west){\tiny 0};
\vertlines[help lines,red]{0,1,3,5,7,9,11,13,15,17,19,21,23}
\end{pgfonlayer}
\tablegrid
\end{tikztimingtable}
\end{document}

And output

The clock pulses are shifting. How can we do?

A: Some thing like this:

TikZ-timing diagrams scale relative to the font size as stated in the package documentation. Options for scaling, then, can be using a \scalebox{<factor >}{<content>} or putting things inside a node as mentioned in the documentation and also noted by @percusse in a comment. A more natural way, though, could be scaling like a normal text, that is, using standard sizes (\small, \large, \Large, ...etc) or issuing \fontsize{<size>}{<baselineskip>} command. Here, I used \Huge for example:
\documentclass[border=2pt]{standalone}
\usepackage{tikz}
\usepackage{tikz-timing}
\usetikztiminglibrary[dual arrows]{clockarrows}
\begin{document}

{%
\Huge %\fontsize{40}{40}\selectfont
\begin{tikztimingtable}[line width=.5pt,
timing/slope=0.1,
timing/rowdist=3ex,%
]
\textnormal{\small Clock} &  [black] {h} 47{c} \\
\extracode
\begin{pgfonlayer}{background}
\node[anchor=east] at (row1.north west){\tiny +5V};
\node[anchor=east] at (row1.south west){\tiny 0};
\vertlines[help lines,red]{0,1,3,5,7,9,11,13,15,17,19,21,23}
\end{pgfonlayer}
\tablegrid
\end{tikztimingtable}
}
\end{document}


text:
Q: Mongoose error: Cannot update __v and __v at the same time I need help with this.
I have this node project that's been working from the beginning.
Recently I began getting an error about mongoose not being able to update __v an __v at the same time (details below)
My first thought was that a new update of mongoose brought about this, but I'm not sure.
Any help will be appreciated.
Thanks
/.../node_modules/mongoose/lib/utils.js:413
        throw err;
              ^
MongoError: exception: Cannot update '__v' and '__v' at the same time
    at Object.toError (/.../node_modules/mongoose/node_modules/mongodb/lib/mongodb/utils.js:114:11)
    at /.../node_modules/mongoose/node_modules/mongodb/lib/mongodb/db.js:1131:31
    at /.../node_modules/mongoose/node_modules/mongodb/lib/mongodb/db.js:1846:9
    at Server.Base._callHandler (/.../node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/base.js:445:41)
    at /.../node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/server.js:478:18
    at MongoReply.parseBody (/.../node_modules/mongoose/node_modules/mongodb/lib/mongodb/responses/mongo_reply.js:68:5)
    at null.<anonymous> (/.../node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/server.js:436:20)
    at EventEmitter.emit (events.js:95:17)
    at null.<anonymous> (/.../node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/connection_pool.js:201:13)
    at EventEmitter.emit (events.js:98:17)

EDIT
Looks like the error is thrown when I attempt to save. Here's the save method I call;
save: function (callback) {
  // A Helper function
  function setID(instance, id) {
    instance._id = id;
  };

  var self = this; // Preserve reference to the instance
  var update = Utils.clone(this);
  delete update._id; // Delete the _id property, otherwise Mongo will return a "Mod on _id not allowed" error

  // Prepare updates for saving
  for (var key in update) {
    if (update[key] == undefined)
      delete update[key];
    if (key == 'company' || key == 'local_currency')
      update[key] = update[key].getID();
  }

  PreferenceModel.save(this._id, update, function (err, savedDoc) {
    if (err) callback(err);
    else {
      if (!self.getID()) // If the object didn't previously have an _id property
        setID(self, savedDoc._id);
      callback(null, self);
    }
  });
}

and here's where i call it;
preference.save(function (err, savedPreference) {
  if (err) callback(err);
  else callback(null);
});

also, here's PreferenceModel.save method;
function save(id, update, callback) {
  Preference.findByIdAndUpdate(id, update, {upsert: true}, function (err, savedDoc) {
    if (err) callback(err);
    else callback(null, savedDoc);
  });
}

A: I suggest you put _id related delete logic into your mongoose model Schema definition file :
var UserSchema = new mongoose.Schema(fieldDefinitions);

// Ensure virtual fields are serialised.
UserSchema.set('toJSON', {
    virtuals: true
});

// Ensure able to see virtual fields output when using console.log(obj)
UserSchema.set('toObject', {
    virtuals: true
});

UserSchema.options.toJSON = {

    transform : function(doc, ret, options) {

        console.log('--> ' + require('util').inspect( ret._id.id ));

        ret.id = ret._id.id;
        delete ret._id;
        delete ret.__v;

        return ret;
    },
    virtuals: true
};

Then in your callback execute toJSON :
var processedJson = resultDoc.toJSON();

to retrieve the processed version which nicely hides reusable logic.
NOTE :  toJSON() is also magically executed by JSON.stringify()