text:
Q: General error: 1364 Field 'el' doesn't have a default value How to solve this,
My table structure was look like below

CREATE TABLE leave_histroy (   his_id int(11) NOT NULL COMMENT
  'histroy id auto increment',   user_id int(50) NOT NULL COMMENT 'get
  from users table id',   cl double(4,2) NOT NULL COMMENT 'casual
  leave',   sl double(4,2) NOT NULL COMMENT 'seak leave',   el
  double(4,2) NOT NULL COMMENT 'earned leave',   mt double(4,2) NOT
  NULL COMMENT 'maternity leave',   pt double(4,2) NOT NULL COMMENT
  'paternity leave',   lop double(4,2) NOT NULL COMMENT 'loss of pay',
  compoff double(4,2) NOT NULL COMMENT 'compensatory off leave',
year year(4) DEFAULT NULL COMMENT 'store leave year',   created_on
  date DEFAULT NULL COMMENT 'created time',   created_by varchar(100)
  NOT NULL COMMENT 'created by whome?',   updated_on date DEFAULT NULL
  COMMENT 'updated time',   updated_by varchar(100) NOT NULL COMMENT
  'updated by whom?' ) ENGINE=InnoDB DEFAULT CHARSET=latin1;

-insert function -
$query = "INSERT
    INTO
        `leave_histroy`(
            `user_id`,
            `cl`,
            `sl`,
            `year`,
            `created_by`
        )
    VALUES(
        :create_by,
        :casual_leave,
        :sick_leave,
        :year,
        :create_by
    )";
try {
    $result = $this->dbh->prepare($query);
    $result->bindParam(":create_by", $leave_param['create_by']);
    $result->bindParam(":casual_leave", $leave_param['casual_leave']);
    $result->bindParam(":sick_leave", $leave_param['sick_leave']);
    $result->bindParam(":year", $leave_param['year']);
    $result->bindParam(":create_by", $leave_param['create_by']);
    $result->execute();
    return $result;
} catch (\PDOException $e) {
    echo $e->getMessage();
    die();
    return false;
}

A: Change your Prepared Statement to this
$query = "INSERT INTO `leave_histroy`( `user_id`, `cl`, `sl`, `year`, `created_by`) VALUES(?,?,?,?)";
$query->bind_param("iiiis", $create_by, $casual_leave, $sick_leave, $year, $create_by);
    try {
        // set parameters and execute
        $create_by =  $leave_param['create_by']
        $casual_leave = $leave_param['casual_leave']
        $sick_leave = $leave_param['sick_leave']
        $year = $leave_param['year']
        $create_by = $leave_param['create_by']
        //Execute Statement
        $stmt->execute();
        //return $result;
    } catch (\PDOException $e) {
       echo $e->getMessage();
       die();
       return false;
    }


text:
Q: Atmel processor is reset, but there is no reset source indicated in MCUSR The short story:
What are those reset conditions, which will not set a bit in MCUSR of an ATmega processor, but still cause a reset?
The long story:
I use brown-out detection in an ATmega168 and have a place in my code to handle it. If my system loses power, a capacitor keeps it above brown-out level for around a half second, and when I restore power, the brown-out handling routine successfully runs. (I check the brown-out bit in the MCUSR.)
However, when I slowly decrease voltage on the system, and slowly give it back, the processor restarts, and the brown-out handling routine does not run: the MCUSR is zero!!! (I use an external debugger through DebugWire to check it.)
What can cause this? If it were something else, like the watchdog being accidentally enabled (I don't use it, and disable it at startup), there would be at least something in the MCUSR.
But no, it was neither a Watchdog reset (bit 3), a brown-out reset (bit 2), external reset (bit 1), or power-on reset (bit 0), so what did cause the reset if neither of the above??
Another strange thing: after such a condition, a reset will, in some cases, periodically occur, always with a value of zero in MCUSR.
Otherwise, when this does not happen, the system runs always perfectly.
Edit:
I couldn't find a conclusive answer elsewhere, what kind of reset does a stack overflow, or similar software-related error lead to? Maybe those are the conditions which might reset the processor, and leave the MCUSR alone? I thought such conditions just corrupt the RAM or maybe even the Program Counter, but don't cause a reset.

A: A stack overflow does not cause a reset. A stack overflow is purely a software condition, which will likely lead to undefined behavior. There are many, many symptoms that could result from a stack overflow. For example:

*

*No apparent change in behavior

*Corruption of adjacent memory leads to unexpected or undefined behavior such as deferencing a null pointer or executing invalid instructions

A stack overflow might appear to cause a reset if the processor executes an invalid instruction and the exception is unhandled. This again is software-defined behavior depending on the software exception handler. The same thing can happen with dereferencing a NULL pointer, or pointer to invalid memory space.
You may want to double check that there aren't additional registers that may specify reason for the reset as well.
You mentioned that you lower the voltage and then raise it. Does it go into reset if you simply lower the voltage? Do you have code that is monitoring the voltage? I wonder why you suspect a software condition bug as the cause when you are changing the hardware conditions.

A: Have you tried playing with BODLEVEL fuse if it makes any difference?
However, this could be easily caused by stack overflow or some other software issue. Especially if you are working with function pointers - it can be just a jump to 0. I had such problems in the past.
Never really did that, but I believe you could easily distinguish between reset and 'jump' if you check the value of some other register that you changed in your software. If it really was a reset registers should be reinitialized too.
E.g. set PORTB to 0x55 somewhere in your code. Then on boot check its value. If it was a reset it should be 0x00, if not it should remain 0x55.

A: If you use avrgcc try this:
volatile char mcusr __attribute__ ((section (".noinit")));
void main(void){
  mcusr=MCUSR;
  ...
  if(mcusr&0x01)printf("WD");
  if(mcusr&0x02)printf("EX");
  if(mcusr&0x04)printf("BO");
  if(mcusr&0x08)printf("PO");
  ...
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: VBox Guest not filling entire screen on start-up I'm running Linux Mint 18.1 as a guest using VirtualBox.
I've done this about 5 times now trying to see what's causing the issue, but because I'm not that well endorsed in these kind of things, I just couldn't possibly figure out where to look.
The issue I'm having is that whenever I boot up the VM, the machine arrives to the logon screen in a chopped up scale ratio (i.e. borders). Only once I logon OR reboot will the issue fix itself.
The issue I have with this is that it's inconsistent. It can obviously load at full-screen at all times as it does when I reboot, but it doesn't do so when initially booting up. Even if the issue is only present at the start/logon screen, this is annoying.
I don't understand what's throwing off the machine, but I've had it.
Call me OCD, but this is driving me nuts. I didn't have this issue with my 17.3 VM, but VBox has gone through some updates since then.
I installed the G.A. using VB, and I have enough video memory allocated to the machine. I also have 3D acceleration enabled. If I didn't, I'd be getting a warning for software rendering mode.
I've gone through the process of posting on both related forums, but I have not received sufficient feedback.
All I need is a point in the right direction. Where I can look to find out what's going on?

A: This is completely normal for most hypervisors softwares (  used Oracle virtual box some time ago and now currently with Hyper V)
What happens is that initially during startup the hypervisor uses its graphics default  drivers which usually do not amount to full resolution, but after loading BIOS it then detects those drivers you added for the particular virtual machine and adjusts the resolution according to the settings you have saved in Display properties, so I doubt if there is really a workaround for that (my hypervisor acts just like that)
Maybe configuring the Hypervisor to prevent them initially load their default drivers?? But I'm you might need to approach the software developers for that.


text:
Q: How to pass date from controller to modal in ionic 1 i want to pass data from controller to ionic modal , but i didn't find any method to do that. so please suggest something
what i have tried:-

var modalInstance = $modal.open({
  templateUrl: 'confirm_booking.html',
  controller: 'confirm_bookCtl',
  resolve: {
    items: function () {
      return $scope.items;
    }
  }
});

but $modal is undefined in controller

A: //First you don't need to declare a controller because you call your modal from your controller
.controller('MyController', function($scope, $ionicModal) {
   $ionicModal.fromTemplateUrl('templates/modal-template.html', {
      scope: $scope,
      animation: 'slide-in-up',
   }).then(function(modal) {
      $scope.modal = modal;
   });

   $scope.openModal = function() {
      $scope.modal.show();
   };

   $scope.closeModal = function() {
      $scope.modal.hide();
   };

   //Cleanup the modal when we're done with it!
   $scope.$on('$destroy', function() {
      $scope.modal.remove();
   });

   // Execute action on hide modal
   $scope.$on('modal.hidden', function() {
      // Execute action
   });

   // Execute action on remove modal
   $scope.$on('modal.removed', function() {
      // Execute action
   });
});

Maybe better you visit this page
https://www.tutorialspoint.com/ionic/ionic_js_modal.htm


text:
Q: Strange Function with duplicate name "DoBenchmark" cannot be defined as the function is defined only at one place (With Matlab 2018b under latest windows10.) I have a folder Folder containing DoStuff.m whose code is :
%addpath('./SubFolder/SubSubFolder'); // SubSubFolder contains mex file defining myFunction used below
%close all;

function [res] = DoStuff(param) % Function has same name as the script defining it

    res = myFunction(param)

end

where myFunction is defined in a mexw64 file contained in './SubFolder/SubSubFolder'.
Naturally, as it is, executing the function DoStuff(param) inside Matlab's GUI (in the folder Folder) throws the following error :
'myFunction' is not found in the current folder or on the MATLAB path, but exists in ...

... in './SubFolder/SubSubFolder'. Superb. I therefore remove the % in the first line of DoStuff.m and re-execute the function DoStuff(param) inside Matlab's GUI (in the folder Folder) and get the following error :
Function with duplicate name "DoStuff" cannot be defined.

Strange, as DoStuff is defined at only one place : insided the DoStuff.m script. (Confirmed by a which -all DoStuff in Matlab in Folder.)
Remark. In Matlab2018b one can defined a function named toto inside a script named toto.m, Matlab won't have any problem with it. So that my problem has nothing to do with the same naming. It has to do with adding the addpath line, but I don't know how. Confirmation of this feeling : replacing line res = myFunction(param) with res = 1 and uncommenting the addpath leads to the naming error as well.

A: The name of the m-file must be different that that of the function if the function is inside a script file. i.e your m-filename cannot be DoStuff.m if DoStuff is not a function file. Either DoStuff.m should be a function file like this:
function [res] = DoStuff(param) % Note that there is no executable line before this
res = myFunction(param)
end

or you should rename either your function or your m-file.
Assuming you rename your m-file, you may use it like this:
addpath('./SubFolder/SubSubFolder'); %SubSubFolder contains mex file defining myFunction
close all;

res = DoStuff(param); %Calling the function

function [res] = DoStuff(param)
res = myFunction(param)
end


text:
Q: How to prevent ReadOnly computed column in vb.net dataset to raise RowChanged event How to prevent or detect in the code if a Read Only computed column was the cause of the RowChanged event.
Dim dsCambios As DataSet = DS.GetChanges()
If dsCambios.CxP_OCE_Detalle.Count > 0 Then
     ' I need this code to be executed only and always only if a non computed column was changed.
End If

Thanks

A: Yes the rowChanged event is raised when a computed column is changed for example a total column when I change the detail table. I made this work around:
    Dim dsCambios As DataSet = DS.GetChanges()
    If dsCambios.CxP_OCE_Detalle.Count > 0 Then
         Dim Modificada As Boolean = False
         Dim row As DataSet.CxP_OCE_DetalleRow
         Dim col As System.Data.DataColumn
         For Each row In dsCambios.CxP_OCE_Detalle
             For Each col In DS.CxP_OCE_Detalle.Columns
                 If Not col.ReadOnly AndAlso Not row(col.ColumnName, DataRowVersion.Original).Equals(row(col.ColumnName, DataRowVersion.Current)) Then Modificada = True
             Next
         Next
         If Modificada Then
              ' I need this code to be executed only and always only if a non computed column was changed.
         End If
    End If


text:
Q: How do I install the 'no-ip' package on 12.04?
Possible Duplicate:
The noip2 (no-ip.com) package was deleted from the repository, now what?

I just Installed Ubuntu server 12.04 and I want to install no-ip.
I ran as root: sudo apt-get install noip2
And I got this:
root@topcat:/var# sudo apt-get install noip2
Reading package lists... Done
Building dependency tree
Reading state information... Done
E: Unable to locate package noip2

I also tried with this command:
wget http://www.no-ip.com/client/linux/noip-duc-linux.tar.gz

But I got this error:
wget: unable to resolve host address 'www.no-ip.com'`

Can someone help me? I am new to Ubuntu.


text:
Q: How do I print all but the Nth to last line in sed?
*

*I'd like to do the complement / "opposite" of
sed 13q;d <file.txt

More generally, is it possible to do this sort of
complement/inverse/opposite in sed? Or only for regexes?

*How do I print all but the third-to-last line?. Does this
require two tac's and counting forward in sed? Or is there a way
to get sed itself to count from the back?

A: Part 1
Simply delete the 13th line:
sed '13d' <file.txt

And a general way to do the complement of the above is:
sed '13!d' <file.txt

Part 2
Because it can be done:
sed -n ':a;${P;q};N;4,$D;ba' <file.txt

Note the 4 is one more than the number you require.  So if you wanted the last-10th line, this would be 11.
Testing with seq:
$ seq 100 | sed -n ':a;${P;q};N;4,$D;ba'
98
$

Attempted explanation
:a        # define label a
${        # match the last line
    P     # print the first line of the pattern space
    q     # quit
}
N         # match all lines: append the next line to the pattern
4,${      # match the range of lines 4 to the end of the file
    D     # delete the first line of the pattern space
}
ba        # match all lines: jump back to label a

Glenn Jackman's valuable addition:
That was "only the Nth line". Here is "all BUT the Nth line":
sed -n ':a;${s/^[^\n]*\n//;p;q};N;4,${P;D};ba'

works with GNU sed, the \n sequence may not work with other seds.

I tried this with BSD sed (OSX) and found it didn't quite work in the form above.  The issues appear to be:

*

*; used to separate lines seems to generally work, but doesn't work after a label

*BSD sed appears to require ; after the last command in a one-line {} command group, whereas GNU sed does not

*\n can generally be used within the regular expression, but apparently not within a [] bracket expression.  So to exclude newlines, we can use something like [[:alnum:][:punct:][:graph:][:blank:]] instead, though this may exclude other characters (specifically other control characters).

So this is an attempt at a more platform independent version:
sed -n ':a
${s/^[[:alnum:][:punct:][:graph:][:blank:]]*\n//p;q;};N;4,${P;D;};ba'

This appears to work under OSX and Ubuntu.


text:
Q: Flutter error : RangeError (index): Invalid value: Only valid value is 0: 1 i have a checkbox list of services.  when i open this page, it returns error.

 List<bool> listBool = [];

 Padding(
                padding: const EdgeInsets.fromLTRB(30, 0, 30, 5),
                child: FutureBuilder<Booking>(
                  future: getBookingById(),
                  builder: (context, snapshot) {
                    if (snapshot.hasData) {
                      return Container(
                        height: MediaQuery.of(context).size.height *0.25,
                        child: ListView.builder(
                           itemCount: snapshot.data!.addons.length,
                            itemBuilder: (context,index){
                             return ListTile(
                               leading: Checkbox(
                                 activeColor: const Color(0xFF4B0082),
                                 onChanged: (value) {
                                   setState(() {
                                       listBool[index] = value!;

                                   });
                                 },
                                 value: listBool[index],
                               ),
                               title: Text(
                                 '${snapshot.data?.addons[index].name}',
                                 style: const TextStyle(
                                   color: Color(0xFF0A2544),
                                   fontSize: 18.0,
                                   fontWeight: FontWeight.bold,
                                 ),
                               ),
                               subtitle: Text(
                                 "${snapshot.data?.addons[index].description} ",
                               ),
                             );
                      })
                      );

                    } else if (snapshot.hasError) {
                      return Text("${snapshot.error}");
                    }
                    return CircularProgressIndicator();
                  },
                ),
              ),

the error:
======== Exception caught by widgets library =======================================================
The following RangeError was thrown building:
RangeError (index): Invalid value: Only valid value is 0: 1

When the exception was thrown, this was the stack:
#0      List.[] (dart:core-patch/growable_array.dart:254:60)
#1      _ServiceListPageState.serviceView.<anonymous closure>.<anonymous closure> (package:apex/screens/service_list_page.dart:193:45)

I got that error and that is because of the index for value.
the error's line: value: listBool[index],


text:
Q: Why did my DDR3 memory VSS pin burn? I have an ASUS P9X79 motherboard. It had one 8GB DDR3 1600MHz memory module installed. I wanted to use some slower 1333MHz Muskin memory I had with it (https://www.newegg.ca/Product/Product.aspx?Item=N82E16820226095). This machine was quite dusty inside and I gave it a blast of compressed air, though that made a decent cloud.
At first the machine booted and reported 12GB of memory. I shutdown and moved the new memory around and ultimately ended with both memory modules' VSS pins visibly damaged - the smell caught my attention first:

Since the memory worked at all, I'm wagering the issue was actually dust. Is there some DDR3 pitfall I've stumbled in to here? I wonder if it was just dust, I might actually be able to repair these modules as the burn might have been too must resistance that only burned the PCB itself.


text:
Q: Почему не работает overflow-y auto Ipad? Привет!
Почему-то не работает скролл  в safari на ipad?

html,
body {
  position: relative;
  height: 100%;
}

.goals-select-items {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  z-index: 5;
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-orient: vertical;
  -webkit-box-direction: normal;
  -ms-flex-direction: column;
  flex-direction: column;
  justify-content: space-between;
}

.goals-select-items {
  width: 100%;
  height: 100%;
  left: auto;
  z-index: 100;
  background-color: red;
}

.goals-list-wrapper {
  position: relative;
  border: 1px solid red;
  -webkit-box-flex: 1;
  -ms-flex: 1 1 auto;
  flex: 1 1 auto;
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-orient: vertical;
  -webkit-box-direction: normal;
  -ms-flex-direction: column;
  flex-direction: column;
  -webkit-box-pack: justify;
  -ms-flex-pack: justify;
  justify-content: space-between;
  overflow: hidden;
}

.goals-select-items>.goals-list-wrapper>ul {
  margin-top: 60px;
  border-top: 1px solid rgba(40, 43, 62, 0.05);
  font-size: 26px;
  border: 1px solid green;
  overflow-x: hidden;
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;
  background-color: black;
  flex: 1 1 auto;
}

.goals-select-items>.goals-list-wrapper>ul li {
  position: relative;
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  min-height: 105px;
  background-color: #fafafa;
  border-bottom: 1px solid rgba(40, 43, 62, 0.05);
  overflow: hidden;
}

plan for my retirement

save for my children's education

get coverage for medical expenses

grow my wealth

learn about insurance

learn about investing


text:
Q: Hover pseudoclass is not working on FontAwesome icon in React I'm quite baffled. Yesterday I did the same thing in the other component and it worked perfectly fine. Let me show you the code...
<FontAwesomeIcon onClick={this.displayVerticalNavbar} className="faColorOverwriter" id="toggleInContNavBar" icon={faBars} pull="right"/>

    #toggleInContNavBar:hover{
    height:84%;
    opacity:0.8;
    cursor:pointer;
}

Today, I've been trying to do a similar thing in the other component, and :hover just won't work no matter what. Why do you think it is?
My Present code:
<FontAwesomeIcon id="menuSearchElementEdit" icon={faEdit}/>

    #menuSearchElementEdit:hover{
    opacity:0.8;
    cursor:pointer;
}

A: This code is work for me. you can add cursor style as below rather than adding different css.
<FontAwesomeIcon id="menuSearchElementEdit" icon={faEdit} style={{ cursor: "pointer" }}/>


text:
Q: Check a users comment for multiple extra letters added on to a banned word I want to filter some bad words like 'asshole' but you can bypass the word by just saying 'asssssshole' or 'asshoooole'
Here is my code currently.
string Word = "asshole";

if (Comment.Contains(Word)
    //block the comment from being posted

How would I check the message for multiple extra letters added on to a banned word, without creating hundreds of different rules for each way you can spell 'asshole'.

A: You might have some partial success using a soundex.  Try putting your variations into https://www.functions-online.com/soundex.html and they all return the same value A240, even a*s*h*o*l*e.  Unfortunately it won't work with a$$hole, but you might be able to come up with some simple substitutions to run before testing.
It should be pretty easy to find a c# implementation online.

A: Make a regex out of it and check for a match:
//using System.Text.RegularExpressions;
string word = "asshole";
//add a '+' after each letter to make it find any number of it
string pattern = string.Join("+", word.ToCharArray());
//pattern is "a+s+s+h+o+l+e"
if(Regex.IsMatch(comment, pattern))
{
    //do something
}


text:
Q: Consulta en Access con un ciclo While Buenas.
Tengo un problema, quisiera seleccionar datos de mi base de datos en Access con un rango de fechas y un nombre en especifico. ¿Cómo puedo hacerlo? Mi pensamiento es con un While pero no me funciona.
select * from Registro
While Fecha_uso between #12/19/2016# and #12/23/2016#
where name = 'Juan'

A: While no es un comando SQL.
Tu pensamiento esta perfecto, pero lo que escribiste en el while debe ir en el where.
select * from Registro
Where Fecha_uso between #12/19/2016# and #12/23/2016#
and name = 'Juan'

A: comandos basicos de mysql son:

select: selecciona los valores de los campos que quieres obtener
from:
  mencionar las tablas de los atributos
where: detalla las condiciones
  para que tu consulta sea efectiva

en tu caso esta mal el while, si embargo es where, tu codigo quedaria asi:
Where Fecha_uso between #12/19/2016# and #12/23/2016#


text:
Q: Is there a way to call function without passing its parameters? Iam new in information security and iam trying to teach my self how to build a simple keylogger with python, i found this code in a site :
import pythoncom, pyHook

def OnKeyboardEvent(event):
    print 'MessageName:',event.MessageName
    print 'Message:',event.Message
    print 'Time:',event.Time
    print 'Window:',event.Window
    print 'WindowName:',event.WindowName
    print 'Ascii:', event.Ascii, chr(event.Ascii)
    print 'Key:', event.Key
    print 'KeyID:', event.KeyID
    print 'ScanCode:', event.ScanCode
    print 'Extended:', event.Extended
    print 'Injected:', event.Injected
    print 'Alt', event.Alt
    print 'Transition', event.Transition
    print '---'

    # return True to pass the event to other handlers
    return True

# create a hook manager
hm = pyHook.HookManager()
# watch for all mouse events
hm.KeyDown = OnKeyboardEvent
# set the hook
hm.HookKeyboard()
# wait forever
pythoncom.PumpMessages()

and while i was trying to understand this code, i found the call of the function 'OnKeyboardEvent' without giving it's parameter
hm.KeyDown = OnKeyboardEvent

So my question is :
is there a way in python to call a function without giving it the parameter ?

A: in python a function name is equivalent to a variable in which a function is stored. in other words: you can define a function called foo and store / reference it in a second variable bar:
def foo():
    print("foo!")

bar = foo

bar() # prints: foo!

in your case, you are only defining the function OnKeyboardEvent(event) and you save a reference of it in hm.KeyDown
the call of the function happens only if you press a keyboard key and is called internally in hm from an event handler. and there the event handler passes down an event object to the function.
to answer your question concerning calling functions without their parameters.
it's possible for functions where default values for all parameters are set
e.g.:
def foo(bar = "default string"):
    print(bar)

print(foo()) # prints: default string
print(foo("hello world!")) # prints: hello world!

A: Calling a function:
OnKeyboardEvent()

Assigning a function to let's say a variable (this doesn't call the function immediately):
var = OnKeyboardEvent

and your is just assigning the function OnKeyboardEvent to pyHook.HookManager('s) KeyDown property
hm = pyHook.HookManager()
hm.KeyDown = OnKeyboardEvent

A: when you do hm.KeyDown = OnKeyboardEvent you are not calling the function OnKeyboardEvent, you are just assign that function to hm.KeyDown. Later pyHook.HookManager will invoke that method for you when any KeyboardEvent happens.


text:
Q: Are robes considered light armor? Will my light armor skills go up wearing robes? I don't see the "light armor" tag on them. I have been wearing robes my whole game and have very low armor skills in every tree.

A: Robes and other apparel which do not have the armor tags - are not armor.  As a consequence, these items:

*

*do not grant armor skill experience

*do not benefit from armor perks or skill

*do not grant hidden armor rating
You can still get some of these benefits while wearing robes if you wear some armor in other slots (head, feet, hands, shield)

A: No; robes are clothing and are not considered to be armor, light or heavy. As such, robes will not increase your light armor skill.

A: No you don't level up light armor, the only the perk it helps (destruction, conjuration) and if that's not enough when you equip robes and hoods you still have room for gauntlets and boots. So no.


text:
Q: Putting the label of an angle at a specific polar coordinate By default, the position of label of an angle is at the ray passing through the middle of an arc.
Is there a way to put the label at a point with a specific polar coordinate?
The motivation is that when there are too many rays, changing pos does not necessarily fit the label at the right place. One has to change the arc position of the label.
I tried pos={(20:1.1)} but it didn't work (i.e., I tried to put the label at the polar coordinate with the angle 20 degree and the length 1.1).
\documentclass{article}

\usepackage{tikz}
\usepackage{tkz-euclide}
\usetkzobj{all}%IMPORTANT--recognizes points, lines, circles, etc
\usetikzlibrary{angles,quotes,bending}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\begin{document}

\begin{center}
\begin{tikzpicture}[scale=1]
\tkzDefPoint(1, 2){A}
\tkzDefPoint(3, 1){B}
\tkzDefPoint(0,0){O}
\tkzDrawSegment(O,A)
\tkzDrawSegment(O,B)
\tkzMarkAngle[arc=ll,size=.85 cm](B,O,A)
\tkzLabelAngle[pos=1.1](A,O,B){$\beta$}
\end{tikzpicture}
\end{center}
\end{document}

A: Coordinate transformations in tikz are additive (within reason). That is, you can provide coordinates absolutely (the \tkzDefPoint above), draw a line relative to the coordinates (tkzMarkAngle) based unrelated requirements (the [size]), add position a label along this path. The position here is given by [pos=], resulting in a relative position along the path. This position can then be further refined using [shift={(coordinate)}] (which can take radial coordinates) and xshift=/yshift=. Note that the order here can be important. Additionally you can use the above, left, right, below keywords that give you pre-defined shifts (on a cartesian grid; has to be given before any numerical shifts). The position words such as at end, very near end and so on clash with pos= and cannot be used at the same time, tikz will take the last argument given.
So if you give [pos=1.1, shift={(20:0.2)}, xshift=0.1], tikz will dutifully go to position 1.1 along your path, shift the position by 0.2 in a 20° direction and then shift it by 0.1 on the x axis.
Aside: Usually the pos argument goes from 0 to 1, with a logical extension in both directions if possible. I think the reason why pos=1.1 works here has to do with the way that tkzMarkAngle is defined.


text:
Q: issue with view in memory warning
Possible Duplicate:
Simulated low memory warning not working

So I have a UIViewController with a webview in it. I tried pushing another viewcontroller into the nav controller and then simulate a memory warning and then go back. Now the view with the webview is purely blank. I tried adding a view and changing the background color to this code and it didn't add it after the memory warning. I tried calling setNeedsLayout and setNeedsDisplay and it didn't help either. It's as if the view is not there. So I double checked the view frame and it is:
<UIView: 0x8aebd70; frame = (0 0; 768 960); clipsToBounds = YES; autoresize = W+H; layer = <CALayer: 0x8ae2830>>

any idea why?

A: You need to download the complete HTML page then store it in local cache and then tell the webview load it. So whenever the webview receive mem warning it will unload the content it memory and when you go back it will load HTML in cache

A: It's normal. Before iOS6 memory warning remove the root view from not visible view controllers, from iOS6 it removes just the backing store of non visible views owned by view controllers. So everything depends on where you tell the webview to load the html page. I will suggest you to use -viewWillAppear.


text:
Q: Getting a 'Field' object has no attribute 'vocab' error when trying to predict on a test set Ive been successfully able to train models with my train data, but am having some trouble now predicting on my test data. So I am loading in by test data with
id1 = ttd.LabelField(use_vocab =False)
test_dataset= ttd.TabularDataset(
    path= 'test_1.csv',
    format='csv',
    skip_header=True,
    fields=[('id', id1),('text', TEXT)]
)
test_iter= ttd.BucketIterator(
    test_dataset_kaggle,
    batch_size=64,
    sort_key=lambda x: len(x.text),
    device=device)

and use the following function for prediction
def get_predictions_test(test_iter, model):
  model.eval()
  with torch.no_grad():
    predictions= np.array([])
    id2= np.array([])

    for batch in test_iter:
      output=model(batch.data)
      ##print(np.shape(output))
      ##print(output)
      y_pred_tag = np.squeeze(torch.round((output)))
      #_,indices = torch.max(output,dim=1)
      ##print(np.shape(predictions))
      ##print(np.shape(y_pred_tag))
      predictions=np.concatenate((predictions,y_pred_tag.cpu().numpy()))
      ##print(predictions)
      ##y_test = np.concatenate((y_test,batch.label.cpu().numpy()))
      id2 = np.concatenate((id2,batch.id.cpu().numpy()))

  return id2, predictions

However, when I try to run
id4, predictions = get_predictions_test(test_iter,rnn_model)

I get the error 'Field' object has no attribute 'vocab'. I already built a vocab for TEXT so that shouldn't be the problem. Am I supposed to build a vocab for ID? Or is there something else I am doing wrong


text:
Q: Como sobrecargar operator int de forma global en C++ estoy practicando la sobrecarga de operadores en C++, hasta el momento puedo sobrecargar un operador adentro de la clase pero he visto códigos donde puede declarar la sobrecarga de forma global, he probado con el operador + y me funciona de maravilla pero con el operador int solo funciona al definirlo de forma interna en la clase:
#include <iostream>

class objeto{
public:
    int valor;
    objeto(int entrada){
        this->valor=entrada;
    }
    //operador resta interno
    objeto operator - (objeto otro){
        return objeto(this->valor-otro.valor);
    }
    //operador int interno
    operator int(){
        return this->valor;
    }
};

//operador suma global
objeto operator+ (objeto primero, objeto segundo){
    return objeto(primero.valor+segundo.valor);
}

int main(int argc, char *argv[]) {

    objeto objeto_1 = objeto(6);
    objeto objeto_2 = objeto(4);

    //usando el operador de resta que esta definido de forma interna en la clase
    objeto objeto_3 = objeto_1-objeto_2;

    //usando el operador de suma que esta definido de forma global
    objeto objeto_4 = objeto_1+objeto_2;

    std::cout << "objeto restados resultado: " << objeto_3.valor << std::endl;
    std::cout << "objeto sumados resultado: " << objeto_4.valor << std::endl;

    //usando operador int interno
    std::cout << "operador int resultado: " << static_cast<int>(objeto_1) << std::endl;

    return 0;
}

Alguien conoce alguna forma de sobrecargar el operador int de forma global porque el siguiente código no funciona como yo esperaría:
operator int (objeto entrada){
    return entrada.valor;
}

A: Lo que tú llamas operador int es conocido en c++ como operador de conversión y como su (verdadero) nombre indica sirve para decirle al compilador cómo convertir un tipo de dato en otro; en tu caso le dices al compilador cómo un objeto de tipo objeto puede ser convertido en un objeto de tipo int, por ejemplo:
struct S { operator int() { return {}; } };

void f(int) {}

int main()
{
    S s;

    /* Se llama al operador 'int' para convertir la instancia de 'S' en un entero
       para poder guardarlo en 'i1'. La conversión es implícita. */
    int i1 = s;

    /* Se llama al operador 'int' explícitamente para convertir la instancia de 'S'
       en un entero para poder guardarlo en 'i1'. */
    int i2 = static_cast<int>(s);

    /* Se llama al operador 'int' para convertir la instancia de 'S' en un entero
       para poder pasarlo como argumento a la función 'f'. La conversión es implícita. */
    f(s);

    return 0;
}

Los operadores sirven para decirle al compilador cómo tratar un operador cuando un tipo de dato aparece a la izquierda o a la derecha de dicho operador, por ejemplo:
struct S
{
    S operator+(float) { return {}; };
    S operator+(float) const { return {}; };
};

S operator+(const S &, const std::string &) { return {}; };
S operator+(const std::string &, const S &) { return {}; };

int main()
{
    S s1;
    const S s2;

    s1 + .0f; // Llama a S::operator+(float)
    s2 + .0f; // Llama a S::operator+(float) const porque 's2' es const.
    0.f + s1; // Error, no existe operador + con 'S' a la derecha de un float.
    0.f + s2; // Error, no existe operador + con 'S' a la derecha de un float.

    /* Llama a operator+(const S &, const std::string &) porque 's1' esta a la
       izquierda del operador. */
    s1 + "Hola";

    /* Llama a operator+(const std::string &, const S &) porque 's2' esta a la
       derecha del operador. */
    " mundo!" + s2;

    return 0;
}

Los dos tipos de operador (función miembro y función libre, que tú llamas global) se usan en contextos diferentes: en el operador miembro el objeto siempre estará a la izquierda del operador y el operador libre permite que el objeto esté a la izquierda o a la derecha del operador.
En resumen, el uso de estos operadores se deduce por contexto:

*

*Cuando el objeto de un tipo toma el lugar de otro tipo, si existe una conversión se usará esa conversión.

*Cuando el objeto forma parte de una expresión con un operador, si existe el operador se usará el operador.

Y es por eso que no existe un operador de conversión libre (que tú llamas global), mientras que en un operador binario (+, -, *, ...) el objeto puede aparecer a la izquierda o a la derecha del operador, en una conversión de datos sólo puede formar parte de una expresión del lado derecho (RValue).


text:
Q: ST_Intersection not returning all intersecting geometries I have a query that will calculate the proportions of given columns based on the area of intersection. The  returns mostly the polygons entirely inside the other polygon, and in some cases returns the ones that intersect. Why is it not returning polygons entirely inside AND those bisected by the boundaries of another?
SELECT
    ROW_NUMBER() OVER () AS my_new_id,
    st_intersection(a.geom, b.geom)
into newlayer
from mass_pop_censustract as a, mass_regions as b

EDITED: The query should return the bright green plus the areas in the blue hatch (right picture). Essentially, I want to calculate the proportion of the population that lives in the portion of the census tracts (yellow) that falls in my area of interest (light green, left picture.)

A: Following my comment above, here's a suggestion to get the areal proportion of those intersections directly, to then be used in further steps, instead of your initial workflow. Might help, if that is actually what you want.
Since you didn't mention the data's CRS I'll assume WGS84 (EPSG:4326) and use a cast to geography type to derive measurements based on spheroidal algebra and in metric units.
I'll also assume the census tract data has an id, and a pop column with each tracts population.
Running
WITH
  its AS (
    SELECT ct.id,
           ct.pop,
           ST_Area(ct.geom::geography) AS area,
           ST_Area(ST_Intersection(ct.geom, rg.geom)::geography) AS prop_area
    FROM <census> AS ct
    JOIN <region> AS rg
      ON ST_Intersects(ct.geom, rg.geom)
  )

SELECT id,
       prop_area / 1000 AS prop_area_sqkm,
       prop_area / area AS prop_area_pct,
       pop * (prop_area / area) AS prop_pop
FROM its;

will calculate prop_pop as population proportion for each census tract id based on percentage of the area intersecting the ROI.If you need to join this with other data holding population numbers, the query returns the respective intersection area prop_area_sqkm (if you are working with e.g. population density), and that area's proportion prop_area_pct in percentage (for e.g. external total population data).
Does that help?

A: the two queries below should get you what you need. you need to use the st_intersects to spatially filter the records that overlap. (I believe st_intersects first checks for bounding box intersections)
drop table if exists new_layer;
create table new_layer as
SELECT
    ROW_NUMBER() OVER () AS my_new_id,
    st_intersection(a.geom, b.geom)
from mass_pop_censustract as a join mass_regions as b
on st_intersects(a.geom, b.geom)

or this variation is sometimes useful
drop table if exists new_layer;
create table new_layer as
SELECT
    ROW_NUMBER() OVER () AS my_new_id,
    st_intersection(a.geom, b.geom)
from mass_pop_censustract as a join mass_regions as b
on st_dwithin(a.geom, b.geom,0.001)


text:
Q: AngularJs 2 with ASP .NET 4.5.1 I would like to use Angular 2 for the front end of an existing ASP.NET 4 app, i.e. not MVC 6/ASP.NET CORE, and I'd rather not use node as we are already using nuget as our package manager. Does anyone know of any resources that will guide me through this?

A: They've updated the Angular site with a non-Core scenario:
https://angular.io/docs/ts/latest/cookbook/visual-studio-2015.html

A: I have created a startup project for Angular 2.0 which just went live at https://github.com/chanoto89/angular2-startup with ASP.NET 4.5.2.
I used the http://blogs.msmvps.com/deborahk/angular-2-getting-started-with-a-visual-studio-2015-asp-net-4-x-project/ outline, but took advantage of using MVC as well as gulp to move the needed dependencies inside the project rather than using the entire node_modules installed by npm.

A: To answer my original question, this is how we have managed to get Angular 2 up and running with .net 4.5.1 (we did end up having to use npm).
In the header of _Layout.cshtml, imported the Angular 2 files from the cdn and configured SystemJs.
<!-- 1. Load libraries -->
<!-- IE required polyfills, in this exact order -->
<script src="../../node_modules/es6-shim/es6-shim.min.js"></script>
<script src="../../node_modules/systemjs/dist/system-polyfills.js"></script>
<script src="../../node_modules/angular2/es6/dev/src/testing/shims_for_IE.js"></script>

<script src="../../node_modules/angular2/bundles/angular2-polyfills.js"></script>
<script src="../../node_modules/systemjs/dist/system.src.js"></script>
<script src="../../node_modules/rxjs/bundles/Rx.js"></script>
<script src="../../node_modules/angular2/bundles/angular2.dev.js"></script>

<!-- 2. Configure SystemJS -->
<script>
  System.config({
    packages: {
        'my-app': {
        format: 'register',
        defaultExtension: 'js'
      }
    }
  });
    System.import('my-app/main')
        .then(null, console.error.bind(console));
</script>

Added package.json and tsconfig.json to the route of the project
packages.json:
{
 "name": "angular2-quickstart",
 "version": "1.0.0",
 "scripts": {
  "tsc": "tsc",
  "tsc:w": "tsc -w",
  "typings": "typings",
  "postinstall": "typings install"
  },
 "license": "ISC",
 "dependencies": {
  "angular2": "2.0.0-beta.9",
  "systemjs": "0.19.24",
  "es6-promise": "^3.0.2",
  "es6-shim": "^0.35.0",
  "reflect-metadata": "0.1.2",
  "rxjs": "5.0.0-beta.2",
  "zone.js": "0.5.15"
 },
 "devDependencies": {
  "typescript": "^1.8.7",
  "typings": "^0.7.5"
  }
}

tsconfig.json:
{
 "compileOnSave": true,
 "compilerOptions": {
 "target": "es5",
 "module": "system",
 "moduleResolution": "node",
 "sourceMap": true,
 "emitDecoratorMetadata": true,
 "experimentalDecorators": true,
 "removeComments": false,
 "noImplicitAny": false
},
"exclude": [
 "node_modules",
 "typings/main",
 "typings/main.d.ts"
 ]
}

If you have node and npm installed on your machine, it should automatically download the npm modules you need, and save them in the node_modules folder. You should now be ready to set up an Angular 2 application, we used the this to get started.

A: I followed https://angular.io/docs/ts/latest/cookbook/visual-studio-2015.html and ran into an issue, this is just to help if someone runs into same.
For some reason I wasn't getting restore packages option on package.json on a new project, restarting the visual studio 2015 profession brought the option again.
And I had to copy systemjs.config.js in projects folder else it was stuck on Loading ... , developer bar showed 404 for systemjs.config.js and copying it brought 'My First Angular Help'.


text:
Q: Field not rendering properly on VF page I have developed page to display..object,itsfields,childobjects,relationships and childobjfields
right now i have a problem with to render the child object fields..when we do change in parent objects...
it should render by according to respective child object fields.
Class:
public with sharing class ConfigurationController {

    public Map <String, Schema.SObjectType> schemaMap = Schema.getGlobalDescribe();
    public String selectedObject {get; set;}
    public String selectedField {get; set;}
    public String selectedChildobject {get; set;}
    public String selectedchildField {get; set;}
    public String Relationship {get; set;}

    Public ConfigurationController() {
        selectedObject = 'Account';
        selectedChildobject = 'Account';
    }

    public List<SelectOption> getObjectNames() {
        List<SelectOption> objNames = new List<SelectOption>();
        List<String> entities = new List<String>(schemaMap.keySet());
        entities.sort();
        for (String name : entities) {
            objNames.add(new SelectOption(schemaMap.get(name).getDescribe().getName() , schemaMap.get(name).getDescribe().getLabel() ));
        }
        return objNames;
    }

    public List<SelectOption> getObjectFields() {
        Map<String, Schema.SObjectType> schemaMap = Schema.getGlobalDescribe();
        Schema.SObjectType ObjectSchema = schemaMap.get(selectedObject);
        Map<String, Schema.SObjectField> fieldMap = ObjectSchema.getDescribe().fields.getMap();
        List<SelectOption> fieldNames = new List<SelectOption>();
        for (String fieldName : fieldMap.keySet()) {
            fieldNames.add(new SelectOption(fieldMap.get(fieldName).getDescribe().getLabel(), fieldMap.get(fieldName).getDescribe().getLabel()));
        }
        return fieldNames;
    }

    public List<SelectOption> getRelatedObjects() {
        map<string, string> relatedObjectsMap = new map<string, string>();
        system.debug('selectedObject :' + selectedObject);
        list<Schema.Childrelationship> relatedObjectsList = Schema.getGlobalDescribe().get(selectedObject).getdescribe().getChildRelationships();
        system.debug('relatedObjectsList :' + relatedObjectsList);
        List<SelectOption> ChildobjNames = new List<SelectOption>();
        for (Schema.Childrelationship  relatedObject : relatedObjectsList) {
            if (relatedObject.getChildSObject().getDescribe().isUpdateable()
                    &&
                    relatedObject.getChildSObject().getDescribe().getKeyPrefix() != null
                    &&
                    !relatedObject.getChildSObject().getDescribe().isCustomSetting()
                    &&
                    relatedObject.getChildSObject().getDescribe().isCreateable()
               )
                ChildobjNames.add(new SelectOption(relatedObject.getChildSObject().getDescribe().getName(), relatedObject.getChildSObject().getDescribe().getLabel()));
            system.debug('ChildobjNames :' + ChildobjNames);
        }
        return ChildobjNames;
    }

    public List<SelectOption> getRelationships() {
        map<string, string> relatedObjectsMap = new map<string, string>();
        system.debug('selectedObject :' + selectedObject );
        list<Schema.Childrelationship> relatedObjectsList = Schema.getGlobalDescribe().get(selectedObject).getdescribe().getChildRelationships();
        system.debug('relatedObjectsList :' + relatedObjectsList);
        List<SelectOption> Relationships = new List<SelectOption>();
        for (Schema.Childrelationship  relatedObject : relatedObjectsList) {
            if (relatedObject.getChildSObject().getDescribe().isUpdateable()
                    &&
                    relatedObject.getChildSObject().getDescribe().getKeyPrefix() != null
                    &&
                    !relatedObject.getChildSObject().getDescribe().isCustomSetting()
                    &&
                    relatedObject.getChildSObject().getDescribe().isCreateable()
               )
                if (relatedObject.getRelationshipName() != null) {
                    Relationships.add(new SelectOption(relatedObject.getRelationshipName(), relatedObject.getRelationshipName()));
                }
            system.debug('Relationships :' + Relationships);
        }
        return Relationships;
    }

    public List<SelectOption> getChildObjectFields() {
        Map<String, Schema.SObjectType> schemaMap = Schema.getGlobalDescribe();
        system.debug('selectedChildobject :' + selectedChildobject);
        Schema.SObjectType ObjectSchema = schemaMap.get(selectedChildobject);
        Map<String, Schema.SObjectField> ChildfieldMap = ObjectSchema.getDescribe().fields.getMap();
        List<SelectOption> ChildfieldNames = new List<SelectOption>();
        for (String ChildfieldName : ChildfieldMap.keySet()) {
            ChildfieldNames.add(new SelectOption(ChildfieldMap.get(ChildfieldName).getDescribe().getLabel(), ChildfieldMap.get(ChildfieldName).getDescribe().getLabel()));
        }
        return ChildfieldNames;
    }
}

Vf page:
<apex:page controller="ConfigurationController" sidebar="false">
<apex:form >
  <apex:pageBlock >
      <apex:pageBlockSection columns="2" title="ParentSection">

          <apex:pageBlockSectionItem >
              <apex:outputlabel value="Object:"/>
                  <apex:actionRegion >
                       <apex:selectList value="{!selectedObject}" size="1">
                                <apex:selectOptions value="{!ObjectNames}"/>
                                <apex:actionSupport event="onchange" rerender="myFields,childobj,relationship,childfields1"/>
                       </apex:selectList>
                 </apex:actionRegion>
          </apex:pageBlockSectionItem>

          <apex:pageBlockSectionItem >
                  <apex:outputlabel value="Fields:"/>
                  <apex:outputPanel id="myFields">
                    <apex:actionRegion >
                       <apex:selectList value="{!selectedField}" size="1">
                            <apex:selectOptions value="{!ObjectFields}"/>
                        </apex:selectList>
                    </apex:actionRegion>
                 </apex:outputPanel>
          </apex:pageBlockSectionItem>

      </apex:pageBlockSection>

       <apex:pageBlockSection columns="3" title="ChildSection">

          <apex:pageBlockSectionItem >
              <apex:outputlabel value="ChildObjects:"/>
                  <apex:outputPanel id="childobj">
                  <apex:actionRegion >
                       <apex:selectList value="{!selectedChildobject}" size="1">
                                <apex:selectOptions value="{!RelatedObjects}"/>
                                <apex:actionSupport event="onchange" rerender="childfields"/>
                        </apex:selectList>
                 </apex:actionRegion>
                 </apex:outputPanel>
          </apex:pageBlockSectionItem>

          <apex:pageBlockSectionItem >
              <apex:outputlabel value="Relationships:"/>
                 <apex:outputPanel id="relationship">
                 <apex:actionRegion >
                       <apex:selectList value="{!Relationship}" size="1">
                                <apex:selectOptions value="{!Relationships}"/>
                        </apex:selectList>
                 </apex:actionRegion>
                 </apex:outputPanel>
          </apex:pageBlockSectionItem>

          <apex:pageBlockSectionItem >
                  <apex:outputlabel value="Fields:"/>
                  <apex:outputPanel id="childfields">
                    <apex:actionRegion >
                       <apex:selectList value="{!selectedchildField}" size="1">
                            <apex:selectOptions value="{!ChildObjectFields}"/>
                        </apex:selectList>
                    </apex:actionRegion>
                  </apex:outputPanel>
          </apex:pageBlockSectionItem>

      </apex:pageBlockSection>
  </apex:pageBlock>
 </apex:form>

A: The issue is not that it is not re-rendering but actually the way you have written your code, it means it is dependent on the value of

selectedObject

However you are not explicitly updating this when you select a new value in the dropdown for selected object. This happens because you are using the standard setter / getter and have not provided your own implementation. What you need to do is update the setter of

selectedObject

so that it looks something like this

public String selectedObject {
        get;
        set {
            selectedObject = value;
            selectedChildobject = value;
        }
      }

Hope this helps.


text:
Q: Uderstanding netstat output When I run netstat -b on Windows 10
I get lots of results of similar nature
TCP    127.0.0.1:64248        LocalHostName:64249   ESTABLISHED
 [w3wp.exe]
 TCP    127.0.0.1:64249        LocalHostName:64248   ESTABLISHED
 [w3wp.exe]
I would like to know what causes connections on ports 64248 and 64249. They both seem to be open and connected on w3wp.exe process. This doesn't seem right and I must be missing something.

A: They are app pool connections, you can run "appcmd list wp" to see the PID and app pools running.


text:
Q: Textarea de tinymce no funciona tengo un textarea en un form que lo manejo con un control tinymce... Simplemente apliqué lo que ya hice en otro formulario y que quedó funcionando perfectamente.

DEFINO el tinymce (me lo muestra perfecto en el formulario) el formulario lo tengo definido de esta forma, es mucho mas extenso con muchos controles, pero pase a ir paso a paso, funciona todo lo anterior al textarea... es decir puedo grabar los datos, pero por alguna cuestión cuando coloco el textarea apreto el boton submit y no pasa nada... ni un solo mensaje de error... es decir NO PASA... el form es asi:
<form action="guardar.php" method="POST">
    Título del Curso de Formación:
    <input id="nombre_curso" type="text" name="nombre_curso" required>

    Nombre/Empresa que lo realiza:
    <input id="dicta" type="text" name="dicta" required>

    Lugar donde se cursa:
    <input id="lugar" type="text" name="lugar" required>

    Objetivos Generales:
    <textarea id="objetivo" name="objetivo" required ></textarea>

    <input type="submit" name="save" value="Submit" />
    Cursos y Capacitaciones
</form>

despues en el guardar.php tengo nada extraño... el problema es que no llega al guardar.php... y no se como salir de esta encrucijada. Probé sacarle el id al textarea para que no tome el tinymce y resulta que ahi funciona perfecto... es como que indentifique que el problema esta evidentemente en el textarea cuando le pongo el tinymce...
 //Si supera el captcha es porque es un humano
    $nombre = $mysqli->real_escape_string($_POST['nombre_curso']);
    $dicta = $mysqli->real_escape_string($_POST['dicta']);
    $lugar = $mysqli->real_escape_string($_POST['lugar']);

    $allowedTags='

';
    if($_POST['objetivo']!='') {
        $sObjetivo = strip_tags(stripslashes($mysqli->real_escape_string($_POST['objetivo'])),$allowedTags);
        echo $sObjetivo;
    } else {
        $sObjetivo = "";
    }

    $sql = "INSERT INTO cursos (nom_cur, dictanc, dom_cur, objetiv) VALUES('$nombre', '$dicta', '$lugar', '$sObjetivo')";
    $resultado = $mysqli->query($sql);

    if($resultado) {
        echo "todo perfecto";
    } else{
        echo "error al guardar";
    }

cómo me enoja que no exista una forma de detectar el error rápidamente !!!

A: Le saqué el REQUIRED al textarea que tiene el tinymce y funcionó.
<textarea id="objetivo" name="objetivo"></textarea>


text:
Q: DisclosureGroup Expandable List in SwiftUI I'm trying to close my expandable list when I click one of the item in my list. But somehow it is not triggering. I don't know where I'm making mistake. For that I'm using isExpanded Bool and when I click other items in my list im making isExpanded = false but its not working. Any idea?

struct SingleSelectionRow: View {

    @Binding var selectSingle: Int
    @Binding var selectedFilter: String?
    var title: String
    var isSelected: Bool
    var childrenList: [FilterChildren]
    @State var filterDetail: SortAndFilterData
    @State var singleSelectedFilters: [String]
    @State  var isExpanded : Bool = false
    var action: () -> Void
    @State var onClick: Bool = false

    var body: some View {

        if selectSingle == 1  {

            if childrenList.isEmpty == true {
                Button(action: {
                    self.action()
                    isExpanded = false
                    print("İS EXPANDED İS \(isExpanded)")
                }) {

                    Text(self.title.uppercased())
                        .font(.custom("DM Sans",size:15))
                        .foregroundColor(isSelected ? Color(red: 10 / 255, green: 207 / 255, blue: 131 / 255) : Color.black)
                }
            }

            if childrenList.isEmpty == false {
                DisclosureGroup(
                    isExpanded: $isExpanded,
                    content: {
                        ForEach(childrenList, id: \.id) { item in
                            Button(action: self.action) {
                                Text(item.name ?? "")
                                    .font(.custom("DM Sans",size:15))
                                    .frame(maxWidth: .infinity, alignment: .leading)

                            }
                        }
                    },
                    label: {
                        Text(self.title.uppercased())
                            .foregroundColor(isSelected ? Color(red: 10 / 255, green: 207 / 255, blue: 131 / 255) : Color.black)
                    }
                )
                .contentShape(Rectangle())
                .onTapGesture {
                    withAnimation(.easeOut) {
                        isExpanded.toggle()
                        print("İS EXPANDED İS \(isExpanded)")
                        self.action()
                    }
                }
            }
        }
    }
}


text:
Q: Smooth discrete 2D array I need to smooth a 2D numpy array containing elevations at discrete steps. Here I have the z-value = 1 (elevation) in position (0, 0) however, it can be any value between 0 and 1. My array looks like this:
['1.00', '0.00', '0.00', '0.00', '0.00', '0.00', '0.00', '0.00', '0.00', '0.00']
['0.00', '0.00', '0.00', '0.00', '0.00', '0.00', '0.00', '0.00', '0.00', '0.00']
['0.00', '0.00', '0.00', '0.00', '0.00', '0.00', '0.00', '0.00', '0.00', '0.00']
['0.00', '0.00', '0.00', '0.00', '0.00', '0.00', '0.00', '0.00', '0.00', '0.00']
['0.00', '0.00', '0.00', '0.00', '0.00', '0.00', '0.00', '0.00', '0.00', '0.00']
['0.00', '0.00', '0.00', '0.00', '0.00', '0.00', '0.00', '0.00', '0.00', '0.00']
['0.00', '0.00', '0.00', '0.00', '0.00', '0.00', '0.00', '0.00', '0.00', '0.00']
['0.00', '0.00', '0.00', '0.00', '0.00', '0.00', '0.00', '0.00', '0.00', '0.00']
['0.00', '0.00', '0.00', '0.00', '0.00', '0.00', '0.00', '0.00', '0.00', '0.00']
['0.00', '0.00', '0.00', '0.00', '0.00', '0.00', '0.00', '0.00', '0.00', '0.00']

I tried applying a cosine kernel with scipy, and then using convolve2d. Like this:
import numpy as np
from scipy import signal

peak_array = np.array([
   [ 1.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
   [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
   [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
   [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
   [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
   [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
   [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
   [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
   [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
   [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.]])

def elevation_grid():
    """Creates a smooth elevation-grid, from an array of peaks."""
    def gkern():
        """Returns a 2D Triangle kernel array."""
        # Decay is a cosine.
        # It is centered, so multiply by two, and add one
        # This way, we cover the entire grid, and assert
        # equal smoothing (due to an odd width)
        gkern1d_c = signal.cosine(peak_array.shape[0]*2 + 1)
        gkern1d_r = signal.cosine(peak_array.shape[1]*2 + 1)

        gkern2d = np.outer(gkern1d_c, gkern1d_r)
        return gkern2d

    kernel = gkern()
    grad = signal.convolve2d(peak_array, kernel, mode='same')

    # Normalize the grid
    grad -= np.amin(grad)
    grad /= np.amax(grad)

    return grad

def print_readable(array):
    """Prints the map to a human-readable format."""
    for row in range(0, array.shape[0]):
        # Round to two decimals
        r = ["%.2f" % array[col][row] for col in range(0, array.shape[1])]
        print(r)

smooth_array = elevation_grid()

print_readable(smooth_array)

Which results in an array looking like this:
['1.00', '0.99', '0.95', '0.90', '0.82', '0.72', '0.60', '0.47', '0.33', '0.18']
['0.99', '0.98', '0.94', '0.89', '0.81', '0.71', '0.60', '0.47', '0.33', '0.18']
['0.95', '0.94', '0.91', '0.85', '0.78', '0.68', '0.57', '0.45', '0.32', '0.17']
['0.90', '0.89', '0.85', '0.80', '0.73', '0.64', '0.54', '0.42', '0.29', '0.16']
['0.82', '0.81', '0.78', '0.73', '0.67', '0.59', '0.49', '0.38', '0.27', '0.14']
['0.72', '0.71', '0.68', '0.64', '0.59', '0.51', '0.43', '0.33', '0.23', '0.12']
['0.60', '0.60', '0.57', '0.54', '0.49', '0.43', '0.36', '0.28', '0.19', '0.09']
['0.47', '0.47', '0.45', '0.42', '0.38', '0.33', '0.28', '0.21', '0.14', '0.06']
['0.33', '0.33', '0.32', '0.29', '0.27', '0.23', '0.19', '0.14', '0.09', '0.03']
['0.18', '0.18', '0.17', '0.16', '0.14', '0.12', '0.09', '0.06', '0.03', '0.00']

Which is the expected result. However if i place peaks at each corner:
['1.00', '0.00', '0.00', '0.00', '0.00', '0.00', '0.00', '0.00', '0.00', '1.00']
['0.00', '0.00', '0.00', '0.00', '0.00', '0.00', '0.00', '0.00', '0.00', '0.00']
['0.00', '0.00', '0.00', '0.00', '0.00', '0.00', '0.00', '0.00', '0.00', '0.00']
['0.00', '0.00', '0.00', '0.00', '0.00', '0.00', '0.00', '0.00', '0.00', '0.00']
['0.00', '0.00', '0.00', '0.00', '0.00', '0.00', '0.00', '0.00', '0.00', '0.00']
['0.00', '0.00', '0.00', '0.00', '0.00', '0.00', '0.00', '0.00', '0.00', '0.00']
['0.00', '0.00', '0.00', '0.00', '0.00', '0.00', '0.00', '0.00', '0.00', '0.00']
['0.00', '0.00', '0.00', '0.00', '0.00', '0.00', '0.00', '0.00', '0.00', '0.00']
['0.00', '0.00', '0.00', '0.00', '0.00', '0.00', '0.00', '0.00', '0.00', '0.00']
['1.00', '0.00', '0.00', '0.00', '0.00', '0.00', '0.00', '0.00', '0.00', '1.00']

They add up in the middle resulting in a larger peak in the center, and i would expect the lowest value in the middle...
['0.00', '0.17', '0.30', '0.39', '0.44', '0.44', '0.39', '0.30', '0.17', '0.00']
['0.17', '0.36', '0.51', '0.61', '0.66', '0.66', '0.61', '0.51', '0.36', '0.17']
['0.30', '0.51', '0.67', '0.77', '0.83', '0.83', '0.77', '0.67', '0.51', '0.30']
['0.39', '0.61', '0.77', '0.89', '0.94', '0.94', '0.89', '0.77', '0.61', '0.39']
['0.44', '0.66', '0.83', '0.94', '1.00', '1.00', '0.94', '0.83', '0.66', '0.44']
['0.44', '0.66', '0.83', '0.94', '1.00', '1.00', '0.94', '0.83', '0.66', '0.44']
['0.39', '0.61', '0.77', '0.89', '0.94', '0.94', '0.89', '0.77', '0.61', '0.39']
['0.30', '0.51', '0.67', '0.77', '0.83', '0.83', '0.77', '0.67', '0.51', '0.30']
['0.17', '0.36', '0.51', '0.61', '0.66', '0.66', '0.61', '0.51', '0.36', '0.17']
['0.00', '0.17', '0.30', '0.39', '0.44', '0.44', '0.39', '0.30', '0.17', '0.00']

How can I smooth out my peaks?
It needs to be efficient, since I have large arrays (up to 1000x1000).

A: Therefore, if k is your kernel, and * is convolution, and v1,..v4 input matrices like the first one you posted, you can sum them and obtain another matrix as w

w=v1+v2+v3+v4

You are applying convolution, which is a linear operation.

output=k * w = k * (v1+v2+v3+v4)= k * v1 + k2 * v2 ...

If you notice, you input with four 1s at the corner (Inp2) is basically the same as the sum of four of the initial matrix with only one 1 (Inp1).
You could build Inp2 by simply rotating by 90 degrees Inp1 and summing ( in numpy, transposes and fliprl).
Therefore, you could just rotate the results of the first computation and add them up to find the correct final results.
It is very unlikely that the sum of the four rotated version of Inp1 is going to be different from the convolution apply to the Inp2.
If that is the case, it could be a numerical problem (if you are using those numbers it should not happen). Check well how you rescale the data with max and min. You are dividing by max, so make sure that is nonnegative, by more than an eps


text:
Q: Jquery change/set link params on click I need to click a link by jquery dynamically.
And before click, I set some extra or new params to that link.
      $('#add-new-event a:first').attr('href', `/admin/content/events/add/lesson?popup=/day-view&start=2019-10-15T08:00:00&end=2019-10-15T08:15:00&instructor=673`);
      $('#add-new-event a:first').click();
      console.log($('#add-new-event a:first').attr('href'));

It set params correctly, but the params that sent are not updated and it gets the old params. How it is possible to add new or extra params to a link when it is clicked by jquery?

A: jQuery click event does not work on anchor tags. You will have to updated your code as below
      $('#add-new-event a:first').attr('href', `/admin/content/events/add/lesson?popup=/day-view&start=2019-10-15T08:00:00&end=2019-10-15T08:15:00&instructor=673`);
      $('#add-new-event a:first').get(0).click();
      console.log($('#add-new-event a:first').attr('href'));

I am assuming that your HTML is something like below:

        Google

This will change the href value of your anchor tag and call the click event. Don't forget the target="_blank" property if you want to check the console.
Here is the Demo at JSFiddle

A: Here is one way to do it.

$(document).ready(function(){
  $('.link').click(function(e){
    this.href='/admin/content/events/add/lesson?popup=/day-view&start=2019-10-15T08:00:00&end=2019-10-15T08:15:00&instructor=673';
    console.log(this.href);
    //use e.preventDefault() to prevent redirect to check updation
  });
  $('.link')[0].click();    // call click()
});

click me!


text:
Q: Why does a trailing forward-slash in linkpath make a difference in symlink() call? I'm trying to figure out a bug in some Linux application code creating symlinks. One issue I've isolated is the use of a trailing forward slash in the linkpath argument.
I have an existing directory structure /A/B/C. I want to create links to the relative directory B/C in the /A directory with the following:
const char * target = "B/C";
const char * linkpath = "/A/D";
int error = 0;

int rc = symlink(target, linkpath);
if (rc < 0)
{
    error = errno;
    printf("Error creating symlink %s : %s, errno = %d\n", linkpath, strerror(error), error);
}

linkpath = "/A/E/";
rc = symlink(target, linkpath);
if (rc < 0)
{
    error = errno;
    printf("Error creating symlink %s : %s, errno = %d\n", linkpath, strerror(error), error);
}

The output of this is:
Error creating symlink /A/E/ : No such file or directory, errno = 2

*

*Why does the trailing slash cause the call to fail?

*Where is the source that implements this error checking?


text:
Q: How to call django class based view get function from normal function? I want to get a response of get function present inside class-based view. So I have written a small function outside the scope of a class. How to pass a URL to this get function or how to call this function directly in order to get its response?
The function will fetch the value from a template and need to pass the fetched paramter value to get function inside Get_data.
The Get_data class currently serves purpose of to directly get values from URL called and give json response and I want to extend its functionality where by I want I get value from template and pass it to this Get_data function and get its response.
Sample code:
class Get_data(APIView):

   def get(self, request):
       username = request.GET.get('username')
       # Processing Code #

       response_data = {'status': 'SUCCESS',
                     'data': XYZ}
       return Response(response_data, status=status.HTTP_200_OK)

def fetch_value():
    # Code to get response data from GET function of class Get_data by passing GET parameter value

#
So what should be the code inside the function fetch_value to pass the value fetched from a template and get response data from GET function of class Get_data?

A: You can use the .as_view() and then "dispatch" the request:
def fetch_value(request):
    response = Get_data.as_view()(request)
    # …
This will return a HttpResponse object [Django-doc] that you can then inspect, for example its .content attribute [Django-doc].
That being said, why don't you just add the Get_data.as_view() result in the urls.py? Processing a response is often not a good idea, since then a lot of "context" is already lost.

A: You can use the below code:
from rest_framework.request import HttpRequest, Request

def fetch_value():
    obj = Get_data()
    # make http request object
    http_request_obj = HttpRequest()
    # make http request object
    request = Request(http_request_obj)
    query_output_data = obj.get(request)


text:
Q: Knapsack Problem in F# with recursive function We have to program the knapsack problem in for a school project in different programming types. One is functional programming and I am trying it in F#.
I am using a recursive function to always get the items with the highest value to put into my knapsack. At the end I want to have the highest total value of all elements combined. Here is the solution in Python and I just hoped I could transfer it to F#.
    let names = ["Zahnbürste","Zahnpasta", "Teller", "Duschgel", "Shampoo", "Handtuch", "Besteck", "Trinkflasche", "Becher", "Taschenlampe", "Sonnenschutz", "Medikamente"]
let volumes = [2,4,5,2,2.5,10,5,3,3,9,2,1]
let values = [3,19,17,15,13,3,2,8,5,6,17,15]
    maxVol = 20;

def rucksackProblem(restVol, i) :
if (i < (len(volumes))) :
    dontPack = rucksackProblem(restVol, i + 1)

    pack = 0
    if (restVol - volumes[i] >= 0) :
        pack = values[i] + rucksackProblem(restVol - volumes[i], i + 1)
    if (dontPack > pack) :
        return dontPack
    else :
        return pack
else :
    return 0

result = rucksackProblem(maxVol, 0)
print(result)

This is what I tried in F#. Please help me figuring out my problems. I am new to F# and functional programming and other solutions to the knapsack problem with hundreds of code lines seem overcomplicated. This doesn´t really print the end result I want to get from this function. It just returns 0:

   open System

let names_list = ["Zahnbürste";"Zahnpasta"; "Teller"; "Duschgel";"Shampoo"; "Handtuch"; "Besteck"; "Trinkflasche"; "Becher";"Taschenlampe";"Sonnenschutz";"Medikamente"]
let volumes_list = [2;4;5;2;3;10;5;3;3;9;2;1]
let values_list = [3;19;17;15;13;3;2;8;5;6;17;15]
let maxVolume = 20
let rec rucksackProblem (restVol : int, i : int) =
    if i < volumes_list.Length then
       let dontPack = rucksackProblem(restVol, i + 1)
       let pack = 0
       let currentVolumeItem = volumes_list.Item(i)
       if restVol - volumes_list.Item(i) >= 0 then
        let mutable pack = values_list.Item(i) + rucksackProblem(restVol - volumes_list.Item(i), i + 1)
        printf "%i" (volumes_list.Item(i))
        else()
       if dontPack > pack then
        dontPack
        else
            pack

    else
        0

let result = rucksackProblem(maxVolume, 0)
printfn "%i" result

Console.ReadKey() |> ignore

A: I can't vouch for the correctness or efficiency of the algorithm but this should do what you're looking for:
 open System

let names_list = ["Zahnbürste";"Zahnpasta"; "Teller"; "Duschgel";"Shampoo"; "Handtuch"; "Besteck"; "Trinkflasche"; "Becher";"Taschenlampe";"Sonnenschutz";"Medikamente"]
let volumes_list = [2;4;5;2;3;10;5;3;3;9;2;1]
let values_list = [3;19;17;15;13;3;2;8;5;6;17;15]
let maxVolume = 20

let rec rucksackProblem (restVol : int)  (i : int) =
    if i < volumes_list.Length then
       let dontPack = rucksackProblem restVol (i + 1)

       let currentVolumeItem = volumes_list.[i]

       let pack =
            if restVol - volumes_list.[i] >= 0 then
              values_list.[i] + rucksackProblem (restVol - volumes_list.[i])  (i + 1)
            else 0

       if dontPack > pack then
            dontPack
       else
            pack

    else
        0

let result = rucksackProblem maxVolume 0
printfn "%i" result

Note that because your mutable pack was defined inside of the scope of an if it was inaccessible outside that branch of the if.  I moved that definition above so it could be accessed outside.
I also did a few other changes.  In F# items in a list can be accessed as list.[index].   Parameters are passed separated by spaces not commas as this is a more flexible approach, for example allows currying.

A: I took the liberty to rewrite your code and I ended up with this.

    let names = ["Zahnbürste"; "Zahnpasta"; "Teller"; "Duschgel"; "Shampoo"; "Handtuch"; "Besteck"; "Trinkflasche"; "Becher"; "Taschenlampe"; "Sonnenschutz"; "Medikamente"]
    let weights = [2; 4; 5; 2; 3; 10; 5; 3; 3; 9; 2; 1]
    let profits = [3; 19; 17; 15; 13; 3; 2; 8; 5; 6; 17; 15]
    let cap = 20

    type Product = { Name: string; Profit: int; Weight: int }

    let knappsack names profits weights cap =
        let sortItemsInDecreasingOrder =
            List.zip3 names profits weights
            |> List.map (fun x -> { Name=x.Item1; Profit=x.Item2; Weight=x.Item3 })
            |> List.sortBy (fun p -> p.Profit / p.Weight)
            |> List.rev
        let products = sortItemsInDecreasingOrder
        let rec pack bag totalWeight idx =
            if idx > List.length names - 1 then bag
            else
                let p = products.[idx]
                if (totalWeight + p.Weight) > cap then bag
                else
                    pack (bag @ [p]) (totalWeight + p.Weight) (idx + 1)
        pack List.empty 0 1

    knappsack names profits weights cap
    |> Dump
    |> ignore

The result I get is

    Name            Profit  Weight
    Sonnenschutz    17      2
    Duschgel        15      2
    Shampoo         13      3
    Zahnpasta       19      4
    Teller          17      5
    Trinkflasche    8       3
                    89      19

Btw. if you are interested in learning functional programming using f# I can highly recommend https://fsharpforfunandprofit.com/.


text:
Q: How to Add users to Azure Active Directory with Graph API I am trying to understand how Azure Active Directory Graph API works for adding users to the directory. According to this:
http://msdn.microsoft.com/en-us/library/azure/dn130117.aspx
I need to acces the graph API URL and pass in something called a "bearer token" in the "Authorization" header so that it will allow me to add the user specified in the request's body.  However, I have no idea where I can get one of these tokens. All my research points to the user having to be already authenticated to get a token, which kind of beats the point, since I want to add the user so he can authenticate.
I have configured my app in the Azure Management Portal, and thought the bearer token was the "Client ID" that I get when I go to my added applications in the Directory. But when I pass this number to the Graph API, I get "Access Token Missing or malformed".  I am testing this using the Fiddler Web Debugger app.

A: These 2 posts describe very thoroughly the steps to get the required token in 2 different scenarios:
Authorization Code Grant flow: http://msdn.microsoft.com/en-us/library/azure/dn645542.aspx
Client Credentials Grant flow: http://msdn.microsoft.com/en-us/library/azure/dn645543.aspx
If you want to use the Client Id and Client Key to authenticate your client to Azure Active Directory, then you should read the 2nd article. The first one is to authenticate an already existing user.
If you want to programmatically get the OAuth2 token, then you could use the AAD authentication libraries: http://msdn.microsoft.com/en-us/library/azure/dn151135.aspx


text:
Q: Create a symbol-like shape in tikz and reuse it easily? I wanted to create something like a circle and place arrows around it facing towards the circle (or maybe rectangle):

I did it in this way, if someone has improvements since my approach is very manually, you are welcome:
\documentclass[tikz]{standalone}
\usetikzlibrary{positioning}
\begin{document}
\def\size{2}
\begin{tikzpicture}
\node[circle, draw, text width=\size cm, text height=\size cm](down){};
\foreach \x/\y in {
north/90,
north east/45,
east/0,
south east/315,
south/270,
south west/225,
west/180,
 north west/135}
{\draw[latex-] (down.\x) to ++ (\y:1cm);
}
\end{tikzpicture}
\end{document}

I now want to use this picture inside a bigger tikz_diagramm like a easy, maybe scalable, symbol. Is there a more efficient way than create a new tikz-environment inside node (where the symbol is needed) and copy&paste the code above?
Do you maybe know good repsoitories for already predefines symbols in tikz (something like tikssymbols)?

A: You can use pics for such things. They can have parameters, here it is the size. Notice also that north and 90 are equivalent, so you only need one variable in the loop.
\documentclass[tikz,border=3.14mm]{standalone}
\tikzset{pics/.cd,
            funky circle/.style={
            code={
            \node[circle, draw,minimum size=#1](down){};
            \foreach \X in {90,45,...,-225}
            {\draw[latex-] (down.\X) to ++ (\X:1cm);}
            }}}
\begin{document}
\begin{tikzpicture}
\path (0,0) pic{funky circle=2cm};
\path (4,2) pic{funky circle=1cm};
\path (pi,-1) pic[blue]{funky circle=1cm};
\end{tikzpicture}
\end{document}

Just for fun: you can use these things for funky tasks.
\documentclass[tikz,border=3.14mm]{standalone}
\tikzset{pics/.cd,
            funky circle/.style={
            code={
            \node[circle, draw,minimum size=#1](-down){};
            \foreach \X in {0,45,...,315}
            {\draw[latex-] (-down.\X) to ++ (\X:1cm) coordinate(-\X);}
            }}}
\begin{document}
\begin{tikzpicture}
\pic (Emma) at (0,0) {funky circle=2cm};
\pic (Elisa) at (4,2) {funky circle=1cm};
\path (pi,-1) pic[blue,rotate=30,transform shape]{funky circle=1cm};
\draw[red,latex-latex] (Elisa-135) to[out=135,in=90] (Emma-90);
\end{tikzpicture}
\end{document}

As you see, some care has to be taken when rotating these pics: since you have a node inside, you have to add transform shape. This is particularly subtle here because a rotated circle does have the same shape as the unrotated one. Transform shape does, however, transform the anchors 90 and so on that are used in the construction of the pic.


text:
Q: OptionMenu command argument changing when function called I'm new to tkinter and I'm trying to create an OptionMenu that updates a frame when an option is chosen from the menu. The issue I'm running into is that the frame I'm passing as an argument to the select function is changing to the menu selection. Can someone help me understand why this is happening?
Here is an example code. When I print self.display I get the expected value of .!frame, but after I pass it as an argument to select and print I get the value of the option chosen from the drop down menu.
import tkinter as tk

class menu(tk.Frame):
    def __init__(self, parent, display, *args, **kwargs):
        tk.Frame.__init__(self, parent, *args, **kwargs)
        self.parent = parent
        self.display = display

        menu_frame = tk.Frame(self.parent)

        self.default_val = tk.StringVar()
        self.default_val.set("Default")

        print(self.display)
        menu = tk.OptionMenu(menu_frame, self.default_val, "A", "B", "C", command=lambda arg=self.display: self.select(arg))
        menu.pack()

        menu_frame.pack()

    def select(self, frame):
        print(frame)
        selection = self.default_val.get()
        self.default_val.set("Default")

app = tk.Tk()
app.geometry("400x200")
display_frame = tk.Frame(app)
display_frame.pack()

menu(app, display_frame)

app.mainloop()


text:
Q: Convert any currency to USD using Python I have a dataframe
rates=
  from_currency  to_currency     exc_rate   date
  CAD               USD           13    1/1/2020
  AED               USD           50    2/1/2020
  GBP               USD           36    2/1/2020
  INR               USD           72    1/1/2020

and another dataframe
company=
  currency         value            company    date
  CAD               10              A       1/1/2020
  AED               10              B       2/1/2020
  GBP               10              C       2/1/2020
  INR               10              A       1/1/2020

Now I want to convert currency of each company to USD on a specific date based on the exc_rate column in the rates dataframe.
So the output dataframe would look like
company=
  currency         value            company    date         converted
  CAD               10              A       1/1/2020          130
  AED               10              B       2/1/2020          500
  GBP               10              C       2/1/2020          360
  INR               10              A       1/1/2020          720

A: First convert rates to a lookup table:
exc_rate = rates.set_index(['from_currency', 'to_currency', 'date'])['exc_rate']

from_currency  to_currency  date
CAD            USD          1/1/2020    13
AED            USD          2/1/2020    50
GBP            USD          2/1/2020    36
INR            USD          1/1/2020    72
Name: exc_rate, dtype: int64

Then for each row in company, get the corresponding rate, multiply by the 'value', and assign the result to 'converted':
def convert_to_usd(row):
    return row['value'] * exc_rate[row['currency'], 'USD', row['date']]
company['converted'] = company.apply(convert_to_usd, axis=1)

  currency  value company      date  converted
0      CAD     10       A  1/1/2020        130
1      AED     10       B  2/1/2020        500
2      GBP     10       C  2/1/2020        360
3      INR     10       A  1/1/2020        720


text:
Q: Newest entry first in while loop I'm building a PM system in PHP, and I have a problem.
Every mail, is stored in a database.
This query gets all the mails, that were written to the user your logged in as
$getmails = "SELECT * FROM mail WHERE reciever='$drow[ID]'";

Then I have this code, to show every mail, written to the user in a list.
if ($getter->num_rows > 0) {
    while($mrow = $getter->fetch_assoc()) {
        // do something
    }
}

This code works and shows the mails. The problem is, that his code shows the newest mail, at them bottom of the list. And the oldest mail at the top.
Every mail has a ID, and i'm thinking that a way to sort these mails to the newest first, would be to sort after the lowest ID at the top.
Can anyone here help me achieving this?
Thanks in advance
Full code:

<?php
    if ($getter->num_rows > 0) {
        while($mrow = $getter->fetch_assoc()) {
            if($mrow['seen'] == 0) {
                echo "
$mrow[titel]
";
            } else {
                echo "
$mrow[titel]
";
            }
        }
    } else {
        echo "You have no mails";
    }
?>

A: Sort e-mails by date, I expect column create_date in your table.
$getmails = "SELECT * FROM mail WHERE reciever='$drow[ID]' ORDER BY create_date DESC";

Or using ID, the newest should be the highest:
$getmails = "SELECT * FROM mail WHERE reciever='$drow[ID]' ORDER BY id DESC";

A: Using the ORDER BY command and picking a column name to sort by would be the easiest.
"SELECT * FROM mail WHERE receiver='$drow[ID]' ORDER BY date DESC"

I'd also recommend including the 'seen' value in your selection to increase efficiency
"SELECT * FROM mail WHERE receiver='$drow[ID]' and seen=0 ORDER BY date DESC"

A: You should add 'ORDER BY column_name DESC' at the end of your query.
This results in retrieving database information in a specific order.
DESC stands for 'DESCENDING'.
Your query should look as follows:
$getmails = "SELECT * FROM mail WHERE reciever='$drow[ID]' ORDER BY ID DESC";


text:
Q: Jquery .height() is giving rounded value instead of exact value http://jsfiddle.net/XRXNv/
Exact height is 18.4 px when watching by browser, jquery is giving 18
How to fix this
http://jsfiddle.net/XRXNv/1/
In this second jsfiddle I want to set the viewport height to the sum of first 8 li-s, and there is a little problem...
IE is giving 144, mozilla 172, chrome 160 :)

A: The reason that you receive different heights in different browsers is not pixel rounding issues, it is because the default rendering styles are different between different browsers.
If you want the exact same height across all browsers, style the list to set a height manually. And while you're at it, set it to an integer.

A: You can't set decimal values in pixels:

can an element have a a decimal height in html/css?

If you take a look at the computed style in the javascript console, you'll see that the height is 18px

A: I don't think you are suposed to use decimal numbers. The jQuery transforms the number into and int. And not a double or float. I recommend sticking to whole numbers :)


text:
Q: Proof of "$G$ is locally finite and connected" $\iff||G||$ is homeomorphic to $|G|$ I have trouble understanding the proof of "$G$ is locally finite and connected" $\iff||G||$ is homeomorphic to $|G|.$
The proof is at Theorem 8.8.2 at Diestel.
At third paragraph of the proof, he consider the case when $x_p$ is a dummy vertex for every $p$.
Would this happen even if $p$ is a partition which send every vertex to singleton which means no dummy vertex?
Update: I'm sorry. I misunderstood the definition of $p$. He only consider the partition which have "finitely" many cross edges. So, partition which send every vertex to singleton is impossible if there is infinite edges.


text:
Q: How can I access Swagger UI on my AWS EC2 instance? I am very new to the AWS world and have recently been tasked with transferring a Web API from a traditional server set up to AWS. This has involved the following steps:

*

*Creating a new EKS cluster using eksctl

*Creating an ECR repository

*Publishing the Docker image of the ASP.NET Web API to the repo

*Configure service and deployment YAML

*Deploy application using kubectl

*Access Web API application using Load Balancer URL

The above steps have been successful. However I am having trouble accessing Swagger UI from the Load Balancer URL. Swagger UI was running successfully locally from the Docker image in VS2022. But I get a 404 when trying to resolve the same URL appended to the Load Balancer URL (see the image).
What additional steps are required for Swagger UI to execute from the aforementioned application setup?
Here are the YAML files:
apiVersion: apps/v1
kind: Deployment
metadata:
  name: ekstest2
  labels:
    app: ekstest2
spec:
  replicas: 3
  selector:
    matchLabels:
      app: ekstest2
  template:
    metadata:
      labels:
        app: ekstest2
    spec:
      containers:
      - name: ekstest2
        image: xxxxx.dkr.ecr.us-east-2.amazonaws.com/ekstest2:ekstest2
        ports:
        - containerPort: 80
---
apiVersion: v1
kind: Service
metadata:
  name: ekstest2
  labels :
    app  : ekstest2
spec:
  ports:
    - port: 80
      targetPort: 80
  selector:
    app: ekstest2
  type : LoadBalancer


text:
Q: Removing consecutive repeated characters in a string in C++ Its a string problem.First remove all repeated consecutive substring with length 1,then delete substring of length 2 and so on...
for eg if we have a string like this -> abcababceccced
After removing substring of length 1 we will get abcababceced
After removing substring of length 2 we will get abcabced
After removing substring of length 3 we will get abced
This will be the final output
I have devised an algorithm but it has has a complexity of O(n3) and this is not desirable at all.My algorithm is as follows
char str[20]="abcababceccced";
int len=strlen(a);
 for(i=1;i<=len/2;i++){
     for(j=0;j<len;){
      bool flag=chk(a,j,i);//this function will check whether the substring starting at a[j] and a[j+i] of length i are same or not.
       if(flag){
        //remove the second same substring.
       }
       else
         j=j+i;
      }
  }

I will be very grateful if someone comes up with a less complex algo in C++ for this certain problem.

A: You might be able to build something by "sliding" the string relative to itself, comparing character-to-character, then looking for where you have matches.  Eg:
abcababceccced
-abcababceccced
-0000000001100-

abcababceced
--abcababceced
--0001100110--

Not clear that it would be any faster, "order-wise", though -- just a different way to look at the problem.

A: You can do it with a single pass:
#include <stdio.h>
#include <string.h>

int main()
{
  char str[] = "abbbbcaaaababbbbcecccedeeed";
  int len = strlen(str);
  int read_pos, write_pos, prev_char;

  prev_char = str[0] + 1;
  for (read_pos = 0, write_pos = 0; read_pos < len; read_pos++)
  {
    if (str[read_pos] != prev_char)
    {
      str[write_pos] = str[read_pos];
      write_pos++;
    }
    prev_char = str[read_pos];
  }
  str[write_pos] = '\0';

  printf("str = %s\n", str);
  return 0;
}

Since you always write into a position that is less than or equal to the read position, you never destroy the string before you use it.
I've initialised prev_char to something that is definitely different to the first character, but it would make sense to check that the length of the string is not zero.

A: Indeed, linear time is possible for each substring length, since you only want consecutive identical substrings. Just keep a counter a identical characters, and update the string when you've found a substring. Since you want to remove substrings of all possible lengths, the overall complexity is quadratic.
The following C code should be working:
char str[20]="abcababceccced";
int len = strlen(str);
int i, j, counter;
for(i = 1; i <= len / 2; ++i)
{
   for(j = i, counter = 0; j < len; ++j)
   {
      if (str[j] == str[j - i])
         counter++;
      else
         counter = 0;
      if (counter == i)
      {
         counter = 0;
         memmove(str + j - i, str + j, (len - j) * sizeof(char));
         j -= i;
         len -= i;
      }
   }
   str[j] = 0;
   printf("%s\n", str);
}

This should print successively:
abcababceced
abcabced
abced


text:
Q: Syntax and semantic in classical logic I have some questions about classical logic (I am not a logician, so please be indulgent).
First, for propositional logic:
$(I)$ Can you explain to me the difference between the symbols "$\vdash$" and "$\models$" ?
$(II)$ I would like to understand how syntax and semantic are linked and more precisely, how rules of inference (for example: https://en.wikipedia.org/wiki/List_of_rules_of_inference) and truth tables (of logical operators $\vee$, $\wedge$, etc.) are linked.
I'm wondering "what comes first" and I will continue with an example (modus ponens) to keep it simple for me:
$(1)$ If we consider "first" truth tables, we have that $[p \ \wedge \ (p \rightarrow q)] \rightarrow q$ is a tautology. Can we conclude that $p, (p \rightarrow q) \vdash q$ (or that $p, (p \rightarrow q) \models q$) ?
If we consider "first" rules of inference, we have that $p, (p \rightarrow q) \vdash q$ (or $p, (p \rightarrow q) \models q$ ?). Can we conclude that $[p \ \wedge \ (p \rightarrow q)] \rightarrow q$ is a tautology ?
Basicaly, if we imagine how should we beggin to create propositional logic, what would come first in mind ? Also, let's say for example that rules of inference are the most natural thing to beggin with, are the truth tables built in order to respect these rules (i.e. to obtain a tautology as for my previous example) ?
Now, consider predicate logic:
$(I)$ For example, where does the universal generalization rule (again: https://en.wikipedia.org/wiki/List_of_rules_of_inference) comes from ? Is it assumed to be "true" as modus ponens could be assumed to be "true" in the case of propositional logic ?
Because we don't have truth tables in the case of predicate logic, I have the feeling that it is less "balanced" as propositional logic (like if from now, we need to have rules of inference such as universal generalization (so, a more syntactic approach in a sense) in order to perform proofs, not as before).
$(II$) Do we have $\neg \ (\forall x, P(x)) \vdash \exists x, \neg \ P(x)$ or $\neg \ (\forall x, P(x)) \models \exists x, \neg \ P(x)$ ?
Finally, for both propositional logic and predicate logic:
$(I)$ Are there simple examples of proof using only a syntactic approach ?
I am sorry if some if certain passages are not very clear and I will try to be more explicit if needed.
Thank you for your help.

A: See : " logical consequence" in Internet Encyclopedia of Philosophy ( 3 excellent articles) / also, for a basic approach ( on syntax, semantics and metalogical notions such as soundness and completeness)  Papineau, Philosophical Devices.

1) The two symbols mean " [ set Gamma of premisses] has, as logical consequence [ proposition P]". The first one means " ... has, as logical consequence from a syntactical point of view ... " . The second " .... from a semantic point of view...".
Note : these symbols denote a relation ( the logical consequence relation); this relation is not a function since a given set of premises can have more than one logical consequence.
2) Semantics deals with questions such as : " what formulas are true in all possible interpretations? what in no interpretation? what only in some? " or " is there a possible interpretation in which all the given premisses are true and the alledged consequence false?". Syntax deals with questions such as : " is this string of symbols / formulas conformable to the syntactic rules?", " is there a way that leads from this set of formulas to this other one by using a rule and only one  at each step of the process?"
Note : In the same way, english syntax tells you that out of  " I wonder whether I will take the money. Will I run? " one cannot construct " I wonder whether I will take the money & will I run?". Not because of the meaning / interpretation/semantics  of the sentences, but because the form is not grammatically corrrect.
For example, having written "(A-->(BvC)),  ~ (BvC)", can I write after that the symbol " ~A ". Syntax  answers that the string of formulas
                     " (A--> (BvC)), ~(BvC), ~ A "

is correct ( "grammatically"), being allowed by the modus tollens rule of inference  : " from (X--> Y) and (~Y), infer ~X".
Semantics is often considered as more basic than syntax: syntax is supposed to reflect semantics and the semantic notion of logical consequence is considered standardly as the ground of syntactic logical consequence.
Analogously, ( almost) every rule of inference has a corresponding tautology ( having the form of a conditional) which has value " true" in all the rows of its truth table. One will say that the rule of inference " from (X--> Y) and ~Y , infer ~X" is a good rule because the formula " {[ (X--> Y) & ~Y) --> ~X } is logically true ( true in all possible interpretations).
Although the rule by itself totally abstracts from interpretations ( truth values) the tautology guarantees, so to say, that the rule never leads from true premises to a false consequence.
A caveat : it is not absolutely true that " logical consequence" can be reduced to logical implication via tautological conditionals , see the answer I got to the question here How to show precisely that the conditional definition of validity is equivalent to the standard semantic definition.


text:
Q: Jest - Unit Testing a Namespaced File Is it possible to write a unit test with Jest for a JavaScript file that is namespaced using the below format?
// utilities.js

var MyApp = MyApp || {};
MyApp.Common = MyApp.Common || {};
MyApp.Common.Utilities = new function(){
    this.getSomething = function(){  // Need to unit test this function
        return 'Something';
    }
}

If not, is there a better way to structure the namespaces to allow for unit testing?

A: If you export MyApp like following example then in utilities.test.js you can
const {MyApp} = require('./utilities');

it('should work', ()=>{
  expect(MyApp.Common.Utilities.getSomething()).toEqual('something');
});


text:
Q: I'm getting this unusual error in my code, Invalid argument supplied for foreach() I'm checking if the $errors variable is empty, but foreach() still complains about an invalid argument:
<?php
    if (empty($errors) === false) {
?>

            <?php
                foreach ($errors as $error) {
                    echo "
{$error}
";
                }
            ?>

<?php
    }
?>

A: Try using is_array along with count instead of empty like as
if (is_array($errors) && count($errors) > 0) {

is_array — Finds whether a variable is an array

A: http://php.net/manual/en/function.empty.php
So, if $errors is, say, set to an integer value of 2, empty($errors) is going to return true.  However, it isn't an array, hence will be invalid for your foreach loop.
Instead, use is_array().
Also consider, for debugging, using var_dump($errors) and find out exactly what it is at that point.

A: The $errors may not be an array, so you must check its type or convert it to array. A simple example:
<?php
    if (empty($errors) === false) {
?>

        <?php
        foreach((array) $errors as $error){
            echo "
{$error}
";
        }
        ?>

<?php
    }

?>