text:
Q: How to get a VBA Class code execute only on one single instance of an Object? Below is a simplified code for which I cannot explain the behavior. I am using 3 different classes. An object Dot, and object cls_Trace and an object cls_DataSet containing one array called AllTraces()
In cls_DataSet I call a sub of the object cls_Trace. That Corners Sub uses 1 Dot contained in an object of type tDot. The sub pertain to One(1) only instance of object Trace. Yet, after execution of One(1) only call from One(1) only object Trace all other objects Trace stored in the array AllTraces() will be affected the same.
That Sub Corners is supposed to edit values XY for the Dot object UpperLeft and LowRight contained its unique variable myTrace. Yet, after execution, All single Trace in the array AllTraces() have now inherited the values attributed to that one single Trace object.
Could that be a VBA subtle bug? Or a subtle bug in my code (most probably)? Yet, I've spent hours trying to find where could the problem be.

In class definition named cls_DataSet
Dim AllTraces() As cls_Trace

Public Sub CreateInterDot()
    Dim i As Long
    SpreadCount = 30
    CNT = UBound(AllTraces)
    For i = 3 To CNT - 1
       PointAddress = AllTraces(i).LPo
       BezelCount = SpreadCount - 1

       Call DebugAllDots
       Call AllTraces(PointAddress).Corners(AllTraces(PointAddress - 1).LXY, True)
       Call DebugAllDots
       Call AllTraces (PointAddress).Corners(AllTraces (PointAddress).LXY, False)
       Call DebugAllDots
    Next i
End Sub

In class definition named cls_Trace
Private Type tDot
    Po As Long
    Ra As Double
    CT As clsDot        ' Center XY value
    XY As clsDot        ' XY value for this point
    UperLeft As clsDot  ' One Dot define the Upper Left  corner
    LowRight As clsDot  ' One Dot define the Lower Right
End Type

Dim myTrace As tDot
Dim X As Double, Y As Double

Property Get LXY() As cls__Dot        ' Server for the Dot object
    Set LXY = myTrace.XY
End Property

Public Sub Corners(DotOne As cls__Dot, First As Boolean)
    With myTrace
        X = DotOne.XY(Y)
        If First Then
            Let .UperLeft.XY(Y) = X:     Let .LowRight.XY(Y) = X
            ULX = X: ULY = Y: LRX = X: LRY = Y
        Else
            ULX = IIf(X < ULX, X, ULX): ULY = IIf(Y > ULY, Y, ULY)  ' Upper
            LRX = IIf(X > LRX, X, LRX): LRY = IIf(Y < LRY, Y, LRY)  ' Lower
            Let .UperLeft.XY(ULY) = ULX:     Let .LowRight.XY(LRY) = LRX
        End If
    End With
End Sub

In class definition named cls__Dot
Private Type XY
    X As Double     ' X value for the point
    Y As Double     ' Y value for the point
End Type

Dim MyXY As XY

Property Let XY(Y As Double, X As Double)   ' Assigne les valeurs X Y au point
    MyXY.X = X: MyXY.Y = Y
End Property

Property Get XY(Y As Double) As Double     ' Serveur X Y de ce point
    XY = MyXY.X: Y = MyXY.Y
End Property

in cls_DataSet this Corners Sub is called with one variable of type cls__Dot
Call AllTraces(PointAddress).Corners(AllTraces(PointAddress - 1).LXY, True)

More simply it would look like this
call MyTrace.Corners(MyDot, True)

In the Debug code I list all 25 objects Traces XY values as well as XY values of UpperLeft and LowerRight. In all I can see all XY values of 3 Dots recorded in each instance of a Trace. In total that is 25 x 6 values in the VBA Debug window.
At each iteration of i I will read all those 150 values. XY will always remain the same since they are the original data. Each 25 lines will show the XY value for each Dot. But at each iteration of i, the Dot values of UpperLeft and LowerRight will change, but all 25 object will see its LowerRight and Upperleft values become the same, where the intended behavior would be that each LowerRight and UpperLeft Dot should take a different value for each instance of a single Trace in the array.
Where is my mistake in this code?
Debug MSExcel2007 file Link with all the VBA code and class definitions
Further investigation lead me to find that in the VBA module MainMod Sub FillClassDataSet the instance definition for variable object
Set currentPoint = New cls__Dot
Set currentTrace = New cls_Trace
,If I displaced, the currentTrace definition within the i loop, then I will create a new instance of that variable for each i iteration. This will correct the problem. The code then works fine. I am now at the level where I have to understand why this is. It should not work any better because embeded in the cls_Trace class definition there is already a .copy function which is suppose to take care of making sure a new instance of that trace is created.
Furthermore, within the cls_DataSet class Public Sub AppendTrace, there is here too a .copy call when that new trace instance is added to the Array.
So now the question is :  Why must a new instance be created when within my class definition I do create a new one systematically ?
Thanks for your help guys :)


text:
Q: why am I getting an empty test suite with parallel_tests ruby gem Any help getting the gem working would be appreciated.  I'm down to configuration issues (i think) and there isn't a lot of documentation to help me get running.
So I have the parallel_tests gem in my project.  I believe I have two problems, one that cannot be seen without the other.
The first problem is that I don't think I have my database.yml file setup correctly.  #1 we call it servers.yml (not sure if there is an importance with the name), and 2 we didn't have a "test" section setup.  The example shows
test:
  database: yourproject_test<%= ENV['TEST_ENV_NUMBER'] %>

our server.yml file contains the following:
db1:
  adapter: jdbc
  driver: oracle.jdbc.driver.OracleDriver
  url: url_to_db1
  username: uname
  password: pass

db2:
  adapter: jdbc
  driver: oracle.jdbc.driver.OracleDriver
  url: url_to_db2
  username: uname
  password: pass

db3:
  adapter: jdbc
  driver: oracle.jdbc.driver.OracleDriver
  url: url_to_db3
  username: uname
  password: pass

so I just added the test line above the rest of the databases at the top of the file
The problem is I cannot even check to see if that's working right because when I try to run the parallel_tests gems, it returns empty!!!!
This is the guide I've been following, with the exception of finding out I had to require parallel_tests/tasks into my rakefile: https://github.com/grosser/parallel_tests
I have require 'parallel_tests/tasks' in my rakefile
I run the 3 commands in the parallel_tests gem to get execution running (don't worry about the java options and java tool options)

As you can see, there are no error messages, nothing out of the ordenary other then my tests do not run with or without the parameters to the features task.  The following is a printout of the trace stack

A: Was running this on a windows machine... Windows doesn't support forking which is what this gem does.

A: Update, the newer versions of the gem allow you to run on any platform, with a new command.  parallel_cucumber is the new command.  Check https://github.com/grosser/parallel_tests for more details

redpajama_set_name: RedPajamaStackExchange


text:
Q: RSymPy - Handling multivariate equation When I try to solve an equation using RSymPy library, I get the NotImplementedError: multivariate equation error.
I am not sure where am I wrong or should I use some other library for multivariate equation or is there a workaround to make it work?
Also I am not able to pass the values in the form of variables to the equation parameters (ymax, ymin and ec50) without hard coding it.
library(rSymPy)
ymax <- Var("ymax")
ymin <- Var("ymin")
ec50 <- Var("ec50")
sympy("var('x y')")
sympy("expr = ((y-ymin)*(ec50+x))+abs(ymax)*x")
sympy("solve(expr.subs([(ymin, 1615.72687), (ec50, 2.19835099), (ymax, -1607.73011)]),x, y)")

A: 1) If you are trying to solve ((y-ymin)*(ec50+x))+abs(ymax)*x = 0 for x symbolically in terms of y where the other variables are known then try this:
library(Ryacas)

ymin <- -1607.73011
ymax <- 1615.72687
ec50 <- 2.19835099

x <- Sym("x")
y <- Sym("y")

e <- ((y-ymin)*(ec50+x))+abs(ymax)*x

Solve(e, x)

giving:
expression(list(x == -(2.19835099 * (y + 1607.73011)/(y + 3223.45698))))

2) or if you want x in terms of all other symbols then instead of substituting their values define the other variables as yacas symbols:
library(Ryacas)

ymax <- Sym("ymax")
ymin <- Sym("ymin")
ec50 <- Sym("ec50")
x <- Sym("x")
y <- Sym("y")

e <- ((y-ymin)*(ec50+x))+abs(ymax)*x

Solve(e, x)

giving:
expression(list(x == -((y - ymin) * ec50/(y - ymin + abs(ymax)))))

Read the vignette, the help files and run the demos that come with Ryacas if you need more info.
3) multiroot Rather than perform symbolic maninpulation an alternative approach is to find the root numerically using the rootSolve package:
library(rootSolve)

ymin <- -1607.73011
ymax <- 1615.72687
ec50 <- 2.19835099

f <- function(x, y) ((y-ymin)*(ec50+x))+abs(ymax)*x

# using x=1 as the starting value find the value of x for which y=10
y <- 10
multiroot(f, 1, y = y)

giving:
$root
[1] -1.099856

$f.root
[1] 0

$iter
[1] 3

$estim.precis
[1] 0

Double check using the equation we derived using Ryacas in (1):
-(2.19835099 * (y + 1607.73011)/(y + 3223.45698))
## [1] -1.099856

3a) nlm Actually we can do this numerically without any packages at all.  Using the same setup as in (3):
nlm(function(x, y) f(x, y)^2, 1, y = y)

3b) uniroot  If you are able to bracket the x value, between -10 and 10, say, then another way to do it without any packages using the same setup is as in (3) is:
uniroot(f, c(-10, 10), y = y)

Note:

*

*although the equation has two variables, x and y, this would normally be regarded as a univariate problem, not a multivariate problem, because we are solving for one variable, x, in terms of y

*in the question ymin exceeds ymax so we have exchanged them


text:
Q: Ambiguous use of 'subscript(_:)' after Pod Install After adding Firebase/Firestore to my pod file and running pod install my app reports 4 Ambiguous use of 'subscript(_:)' messages in my code below at: let monToFri, let sat, let latitude and let longitude. How can this be corrected?
 func displayAnnotations() {

        if Reachability.isConnectedToNetwork() {

            let ref = Database.database().reference()
            ref.child("Postbox").observe(.childAdded, with: { (snapshot) in

                let monToFri = (snapshot.value as AnyObject?)!["Monday to Friday Collection Time"] as! String?
                let sat = (snapshot.value as AnyObject?)!["Saturday Collection Time"] as! String?
                let latitude = (snapshot.value as AnyObject?)!["Latitude"] as! String?
                let longitude = (snapshot.value as AnyObject?)!["Longitude"] as! String?

                let lastCollection = "Mon - Fri: \(monToFri!)" + " Sat:  \(sat!)"

                let annotation = MKPointAnnotation()
                annotation.coordinate = CLLocationCoordinate2D(latitude: (Double(latitude!))!, longitude: (Double(longitude!))!)
                annotation.title = "Last Collection:"
                annotation.subtitle = lastCollection

                self.mapView.addAnnotation(annotation)

                self.allAnnotations.append(annotation)
                self.allIds.append(snapshot.key)
                self.postboxesLoggedLabel.text = String(self.mapView.annotations.count)

            })
        } else {

            print("Internet Connection not Available!")

            let alertController = UIAlertController(title: "No Internet Connection", message: "Make sure your device is connected to the internet.", preferredStyle: .alert)

            // Create the actions
            let okAction = UIAlertAction(title: "OK", style: UIAlertAction.Style.default) {
                UIAlertAction in
                NSLog("OK Pressed")
            }

            // Add the actions
            alertController.addAction(okAction)

            // Present the controller
            self.present(alertController, animated: true, completion: nil)
        }

    }

A: Why subscript snapshot.value every time it's used?
let ref = Database.database().reference()
ref.child("Postbox").observe(.childAdded, with: { (snapshot) in
       let data = snapshot.value as? NSDictionary
       let monToFri = data!["Monday to Friday Collection Time"] as? String ?? "Empty String"

      // Other code....
}


text:
Q: azuresearch search.ismatch is ignoring "1" at the end I have following records -
{
"RoleDetails": "0AC05D80-B1E2-4E13-B1E7-602F6C272117  pqr  1",

 "GroupDetails": "0AC05D80-B1E2-4E13-B1E7-602F6C272117  Abc Xyz  1",

},
{
 "RoleDetails": "0AC05D80-B1E2-4E13-B1E7-602F6C272117  pqr  1",

 "GroupDetails": "0AC05D80-B1E2-4E13-B1E7-602F6C272117 Â Abc Xyz 1 Â 1",

},
{
"RoleDetails": "0AC05D80-B1E2-4E13-B1E7-602F6C272117  pqr  1",

"GroupDetails": "0AC05D80-B1E2-4E13-B1E7-602F6C272117 Â Abc Xyz 2 Â 1",

},
{
"RoleDetails": "0AC05D80-B1E2-4E13-B1E7-602F6C272117  pqr  1",

"GroupDetails": "0AC05D80-B1E2-4E13-B1E7-602F6C272117  Abc Xyz 1 New  1",

}
1)
When I am using following filter -

&$filter=search.ismatch('Abc Xyz 1','GroupDetails','simple', 'all')

Returned = all records
Expecting = just two rows ("Abc Xyz 1" and "Abc Xyz 1 new")
2)
When I am using following filter -

&$filter=search.ismatch('Abc Xyz 2','GroupDetails','simple', 'all')

Returned = returning matched record i.e. one row ("Abc Xyz 2") which is expected
3)
But when using this filter -

&$filter=search.ismatch('Abc Xyz 1 new','GroupDetails','simple',
  'all')

Returned = returning matched record i.e. one row ("Abc Xyz 1 new")  which is expected
So why it is returning all records when searched "Abc Xyz 1" ?
Also note: I tried "simple" and "full" querytype
SOLUTION
As per answer provided by Matthew Gotteiner, I modified the query like this -

&$filter=search.ismatch('"Abc Xyz 1"','GroupDetails','simple',
  'all')

and it worked!

A: Since you are looking for exact phrases you should use the phrase search operator by surrounding your query in double quotes. For example, instead of searching for Abc Xyz 1, you can search for  "Abc Xyz 1".
Also, you only need to use the search.ismatch function if you are planning to combine the search with a filter using and. Otherwise, you can use the search parameter in the REST API or the searchText parameter in the .NET SDK


text:
Q: How to initate full uncompression of ZFS filesystem I have created a large filesystem with compression on. Now I have disabled compression, but I don't get full performance. The reason is that uncompression is lazy and will only apply to new files.
Is there a way to initiate uncompression on background?
I know about copying files to a new partition and back, but is there a smarter way?

A: That's odd as usually, a better performance is observed with compression enabled.
Anyway, should you really want to decompress your files, there is no need to use a new "partition" (not sure if you mean a new file-system or pool here). Assuming there is enough space to hold a copy of the biggest file in your file system, and that the files are not being concurrently use/updated by applications, you can just copy the files in the same directory then move them to their original name, overwriting the compressed original, eg:
find . -type f -exec ksh -c 'for i do echo cp -p "$i" "$i.u$$" && echo mv "$i.u$$" "$i"; done' ksh {} +

Remove both "echo" instructions to actually do the change.


text:
Q: Magento 1.9 string replace in grid I have made a custom grid where i have an overview in columns of prices, discounts and amounts. The decimals are separated by a dot (32.400).
What is the best way to change the dot to a comma (32,400).
I have tried the properties (price, number, currency) but these doesn't change de dot.
SAMPLE:
$this->addColumn('price_total', array(
        'header' => $helper->__('Total'),
        'type'   => 'price',
        'index'  => 'Total'
    ));

EDIT:
Thank you Sunil, with your help i figured it out!
Here is how i did it, if someone might be interested.
My class in (app/code/local/SML/Exportorders/Block/Adminhtml/Sales/Order/Grid.php) Grid.php
class SML_Exportorders_Block_Adminhtml_Sales_Order_Grid extends Mage_Adminhtml_Block_Widget_Grid
{
public function __construct()
{
    parent::__construct();
    $this->setId('sml_order_grid');
    $this->setDefaultSort('increment_id');
    $this->setDefaultDir('DESC');
    $this->setSaveParametersInSession(true);
    $this->setUseAjax(true);
}

protected function _prepareCollection()
{...

Defining column:
$this->addColumn('sub_total', array(
        'header' => $helper->__('Sub Total'),
        'type'   => 'text',
        'index'  => 'SubTotal',
        'renderer' => 'sml_exportorders/adminhtml_sales_order_renderer_replace'
    ));

Then i created a renderer file as suggested by Sunil.
app/code/local/SML/Exportorders/Block/Adminhtml/Sales/Order/Renderer/Replace.php
class SML_Exportorders_Block_Adminhtml_Sales_Order_Renderer_Replace extends Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Abstract {
public function render(Varien_Object $row) {
$value =  $row->getData($this->getColumn()->getIndex());

return str_replace('.', ',', $value);

}}

A: Radia, please check following link of mine for options
Magento: Decimal Price in spanish language display Dot instead comma
this will change the . to , everywhere on the website, if needed only for this particular column you can use
str_replace(',', '.', $form);

in the renderer of the output


text:
Q: How to open file using anchor tag What im doing is I have a dynamic table and creating rows which all works fine. In one of the cells im trying to create a link which when clicked will open a file. But when I clicked the link it give me an error saying cannot find server at file. Then what I do to check the file is I type the location into the address bar and it finds it but changes the address to (file:///c:/inetpub/wwwroot/test1.txt). So what I did was put that address into the anchor tag but then its still doesnt work. Here is what I have so far. Any help would be very appreciated.
tblrow = New TableHeaderRow
tblcell = New TableHeaderCell
tblcell.Text = "" & Test &   ""
 tblrow.Cells.Add(tblcell)
 tableName.Rows.Add(tblrow)

A: Use a url and not a physical path.
Change

by an absolute url location

or a relative url location if the file is located on your site

A: *

*Most of the OS don't support with direct file call because of security reasons. Either you have to use temp location or load the file from server.

*Your file should be in virtual directory and with complete URL as other post mentions.

A: You should consider using an Async Handler (ASP.NET) to download the file. Ultimately, the anchor with launch another request in the browser and that request will download the file to the user.
Here is an article with some info from MSDN.
Here is a code sample of what you would write in the handler:
public void ProcessRequest(HttpContext context) {
    // read input etx
    context.Response.Buffer = false;
    context.Response.ContentType = "text/plain";
    string path = @"c:\somefile.txt";
    FileInfo file = new FileInfo(path);
    int len = (int)file.Length, bytes;
    context.Response.AppendHeader("content-length", len.ToString());
    byte[] buffer = new byte[1024];
    Stream outStream = context.Response.OutputStream;
    using(Stream stream = File.OpenRead(path)) {
        while (len > 0 && (bytes =
            stream.Read(buffer, 0, buffer.Length)) > 0)
            {
                outStream.Write(buffer, 0, bytes);
                len -= bytes;
            }
    }
}

Hope this helps


text:
Q: Найти карусель для angularJs Есть отличный плагин slick, даже есть дериктива для angular, но он не работает с моделями. Кто что использовал, поделитесь. Нужна карусель чтоб несколько слайдов было на активной странице, и чтоб была возможность вставить не только картинку но и любые html элементы.

A: Мы используем OwlCarousel2 с небольшой директивой-обёрткой.
Вызов получается такой
<ul owl-carousel owl-options="owlOptions">
  <li class="item owl-item" ng-repeat="item in items">
     <!-- content -->
  </li>
</ul>

UPD:
В директиве по таймауту вызываем, примерно так
app.directive('owlCarousel', ['$timeout', function ($timeout) {
        return {
            restrict: 'A',
            scope: {
                owlOptions: '='
            },
            link: function (scope, element, attrs) {
                $timeout(function () {
                     // ...
                     var owl = $(element).owlCarousel(scope.owlOptions);
                     // ...
                });
         };
}]);

A: Я использую slick. Ничего лучше сам не находил. В крайнем случае юзай Jquery.


text:
Q: How do I get the last element of a list? How do I get the last element of a list?
Which way is preferred?
alist[-1]
alist[len(alist) - 1]

A: The simplest way to display last element in python is
>>> list[-1:] # returns indexed value
    [3]
>>> list[-1]  # returns value
    3

there are many other method to achieve such a goal but these are short and sweet to use.

A: list[-1] will retrieve the last element of the list without changing the list.
list.pop() will retrieve the last element of the list, but it will mutate/change the original list. Usually, mutating the original list is not recommended.
Alternatively, if, for some reason, you're looking for something less pythonic, you could use list[len(list)-1], assuming the list is not empty.

A:
In Python, how do you get the last element of a list?

To just get the last element,

*

*without modifying the list, and

*assuming you know the list has a last element (i.e. it is nonempty)

pass -1 to the subscript notation:
>>> a_list = ['zero', 'one', 'two', 'three']
>>> a_list[-1]
'three'

Explanation
Indexes and slices can take negative integers as arguments.
I have modified an example from the documentation to indicate which item in a sequence each index references, in this case, in the string "Python", -1 references the last element, the character, 'n':
 +---+---+---+---+---+---+
 | P | y | t | h | o | n |
 +---+---+---+---+---+---+
   0   1   2   3   4   5
  -6  -5  -4  -3  -2  -1

>>> p = 'Python'
>>> p[-1]
'n'

Assignment via iterable unpacking
This method may unnecessarily materialize a second list for the purposes of just getting the last element, but for the sake of completeness (and since it supports any iterable - not just lists):
>>> *head, last = a_list
>>> last
'three'

The variable name, head is bound to the unnecessary newly created list:
>>> head
['zero', 'one', 'two']

If you intend to do nothing with that list, this would be more apropos:
*_, last = a_list

Or, really, if you know it's a list (or at least accepts subscript notation):
last = a_list[-1]

In a function
A commenter said:

I wish Python had a function for first() and last() like Lisp does... it would get rid of a lot of unnecessary lambda functions.

These would be quite simple to define:
def last(a_list):
    return a_list[-1]

def first(a_list):
    return a_list[0]

Or use operator.itemgetter:
>>> import operator
>>> last = operator.itemgetter(-1)
>>> first = operator.itemgetter(0)

In either case:
>>> last(a_list)
'three'
>>> first(a_list)
'zero'

Special cases
If you're doing something more complicated, you may find it more performant to get the last element in slightly different ways.
If you're new to programming, you should avoid this section, because it couples otherwise semantically different parts of algorithms together. If you change your algorithm in one place, it may have an unintended impact on another line of code.
I try to provide caveats and conditions as completely as I can, but I may have missed something. Please comment if you think I'm leaving a caveat out.
Slicing
A slice of a list returns a new list - so we can slice from -1 to the end if we are going to want the element in a new list:
>>> a_slice = a_list[-1:]
>>> a_slice
['three']

This has the upside of not failing if the list is empty:
>>> empty_list = []
>>> tail = empty_list[-1:]
>>> if tail:
...     do_something(tail)

Whereas attempting to access by index raises an IndexError which would need to be handled:
>>> empty_list[-1]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range

But again, slicing for this purpose should only be done if you need:

*

*a new list created

*and the new list to be empty if the prior list was empty.

for loops
As a feature of Python, there is no inner scoping in a for loop.
If you're performing a complete iteration over the list already, the last element will still be referenced by the variable name assigned in the loop:
>>> def do_something(arg): pass
>>> for item in a_list:
...     do_something(item)
...
>>> item
'three'

This is not semantically the last thing in the list. This is semantically the last thing that the name, item, was bound to.
>>> def do_something(arg): raise Exception
>>> for item in a_list:
...     do_something(item)
...
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
  File "<stdin>", line 1, in do_something
Exception
>>> item
'zero'

Thus this should only be used to get the last element if you

*

*are already looping, and

*you know the loop will finish (not break or exit due to errors), otherwise it will point to the last element referenced by the loop.

Getting and removing it
We can also mutate our original list by removing and returning the last element:
>>> a_list.pop(-1)
'three'
>>> a_list
['zero', 'one', 'two']

But now the original list is modified.
(-1 is actually the default argument, so list.pop can be used without an index argument):
>>> a_list.pop()
'two'

Only do this if

*

*you know the list has elements in it, or are prepared to handle the exception if it is empty, and

*you do intend to remove the last element from the list, treating it like a stack.

These are valid use-cases, but not very common.
Saving the rest of the reverse for later:
I don't know why you'd do it, but for completeness, since reversed returns an iterator (which supports the iterator protocol) you can pass its result to next:
>>> next(reversed([1,2,3]))
3

So it's like doing the reverse of this:
>>> next(iter([1,2,3]))
1

But I can't think of a good reason to do this, unless you'll need the rest of the reverse iterator later, which would probably look more like this:
reverse_iterator = reversed([1,2,3])
last_element = next(reverse_iterator)

use_later = list(reverse_iterator)

and now:
>>> use_later
[2, 1]
>>> last_element
3

A: You can also use the code below, if you do not want to get IndexError when the list is empty.
next(reversed(some_list), None)

A: Ok, but what about common in almost every language way items[len(items) - 1]? This is IMO the easiest way to get last element, because it does not require anything pythonic knowledge.

A: Strange that nobody posted this yet:
>>> l = [1, 2, 3]
>>> *x, last_elem = l
>>> last_elem
3
>>>

Just unpack.

A: You can use ~ operator to get the ith element from end (indexed from 0).
lst=[1,3,5,7,9]
print(lst[~0])

A: some_list[-1] is the shortest and most Pythonic.
In fact, you can do much more with this syntax. The some_list[-n] syntax gets the nth-to-last element. So some_list[-1] gets the last element, some_list[-2] gets the second to last, etc, all the way down to some_list[-len(some_list)], which gives you the first element.
You can also set list elements in this way. For instance:
>>> some_list = [1, 2, 3]
>>> some_list[-1] = 5 # Set the last element
>>> some_list[-2] = 3 # Set the second to last element
>>> some_list
[1, 3, 5]

Note that getting a list item by index will raise an IndexError if the expected item doesn't exist. This means that some_list[-1] will raise an exception if some_list is empty, because an empty list can't have a last element.

A: If your str() or list() objects might end up being empty as so: astr = '' or alist = [], then you might want to use alist[-1:] instead of alist[-1] for object "sameness".
The significance of this is:
alist = []
alist[-1]   # will generate an IndexError exception whereas
alist[-1:]  # will return an empty list
astr = ''
astr[-1]    # will generate an IndexError exception whereas
astr[-1:]   # will return an empty str

Where the distinction being made is that returning an empty list object or empty str object is more "last element"-like then an exception object.

A: Accessing the last element from the list in Python:
1: Access the last element with negative indexing -1
>> data = ['s','t','a','c','k','o','v','e','r','f','l','o','w']
>> data[-1]
'w'

2. Access the last element with pop() method
>> data = ['s','t','a','c','k','o','v','e','r','f','l','o','w']
>> data.pop()
'w'

However, pop method will remove the last element from the list.

A:
METHOD 1:
L = [8, 23, 45, 12, 78]
print(L[len(L)-1])

METHOD 2:
L = [8, 23, 45, 12, 78]
print(L[-1])

METHOD 3:
L = [8, 23, 45, 12, 78]
L.reverse()
print(L[0])

METHOD 4:
L = [8, 23, 45, 12, 78]
print(L[~0])

METHOD 5:
L = [8, 23, 45, 12, 78]
print(L.pop())

All are outputting 78

A: To prevent IndexError: list index out of range, use this syntax:
mylist = [1, 2, 3, 4]

# With None as default value:
value = mylist and mylist[-1]

# With specified default value (option 1):
value = mylist and mylist[-1] or 'default'

# With specified default value (option 2):
value = mylist[-1] if mylist else 'default'

A: To avoid "IndexError: list index out of range", you can use this piece of code.
list_values = [12, 112, 443]

def getLastElement(lst):
    if len(lst) == 0:
        return 0
    else:
        return lst[-1]

print(getLastElement(list_values))

A: Pythonic Way
So lets consider that we have a list a = [1,2,3,4], in Python List can be manipulated to give us part of it or a element of it, using the following command one can easily get the last element.
print(a[-1])

A: You can also use the length to get the last element:
last_elem = arr[len(arr) - 1]

If the list is empty, you'll get an IndexError exception, but you also get that with arr[-1].

A: If you use negative numbers, it will start giving you elements from last of the list
Example
lst=[1,3,5,7,9]
print(lst[-1])

Result
9

A: You can also do:
last_elem = alist.pop()

It depends on what you want to do with your list because the pop() method will delete the last element.

A: lst[-1] is the best approach, but with general iterables, consider more_itertools.last:
Code
import more_itertools as mit

mit.last([0, 1, 2, 3])
# 3

mit.last(iter([1, 2, 3]))
# 3

mit.last([], "some default")
# 'some default'

A: Another method:
some_list.reverse()
some_list[0]

A: Here is the solution for your query.
a=["first","second","second from last","last"] # A sample list
print(a[0]) #prints the first item in the list because the index of the list always starts from 0.
print(a[1]) #prints second item in list
print(a[-1]) #prints the last item in the list.
print(a[-2]) #prints the second last item in the list.

Output:
>>> first
>>> second
>>> last
>>> second from last

A: If you do my_list[-1] this returns the last element of the list. Negative sequence indexes represent positions from the end of the array. Negative indexing means beginning from the end, -1 refers to the last item, -2 refers to the second-last item, etc.

A: You will just need to take the and put [-1] index. For example:
list=[0,1,2]
last_index=list[-1]
print(last_index)

You will get 2 as the output.

A: You could use it with next and iter with [::-1]:
>>> a = [1, 2, 3]
>>> next(iter(a[::-1]))
3
>>>

A: array=[1,2,3,4,5,6,7]
last_element= array[len(array)-1]
last_element

Another simple solution

A: Couldn't find any answer mentioning this. So adding.
You could try some_list[~0] also.
That's the tilde symbol


text:
Q: Regular Expression for date in python? How to check date value in pandas dataframe through regex and pick wrong date type values?
date: df
Date_col
22-01-2016
2016-01-22
2016/01/22
2018-12-25 09:27:53
22-Jan-2016
abcd
1203
2072006
20030201

output:
Bad_Date
22-Jan-2016
abcd
1203
2072006
20030201

may be regular expression which allows only numbers,'-'
,'/', ':' would work out this problem.

A: One idea could be to see which values pandas.to_datetime rejects:
import pandas as pd

bad_times = []
for i in df.Date_col.values:
    try:
        pd.to_datetime(i)
    except ValueError:
        bad_times.append(i)

A: Use str.contains with regular expressions:
wrong_dates1 = ~df['Date_col'].str.contains('[-/:]')   # rows without the characters -, /, :
wrong_dates2 = df['Date_col'].str.contains('[A-Za-z]') # rows with letters

df[wrong_dates1 | wrong_dates2]

      Date_col
4  22-Jan-2016
5         abcd
6         1203
7      2072006
8     20030201

side note
If you would consider 22-Jan-2016 and 20030201 as valid dates (which they are), you can simply use pd.to_datetime with errors='coerce' which casts invalid dates tot NaT:
bad_dates = pd.to_datetime(df['Date_col'], errors='coerce').isna()
df[bad_dates]

  Date_col
5     abcd
6     1203
7  2072006


text:
Q: Failing to set a variable in bash I use WSL2, and need an environment variable called DISPLAY to communicate with XServer which is running on my host (windows) IP.
I am trying to set this environment each time my shell starts using my .bashrc. It has to update each time because my IP is dynamically assigned.
Here is the section of the code in the .bashrc responsible for setting the DISPLAY environment variable.
alias windowsip="ipconfig.exe | grep IPv4 | cut -d: -f2 | head -1 | sed 's/^[ \t]*//;s/[ \t]*$//'"
WINDOWSIP="$(windowsip)"
ENDING=":0.0"

export DISPLAY="$WINDOWSIP$ENDING"

Although the .bashrc runs quietly, there are a number of things that indicate that the environment variable was not set as desired.
Firstly,
bensmus@BENSMUSPC:~$ $DISPLAY
:0.0: command not found
bensmus@BENSMUSPC:~$

This is strange because my windowsip command works fine, and gives output without any leading spaces.
bensmus@BENSMUSPC:~$ windowsip
123.123.1.23
bensmus@BENSMUSPC:~$

(Note: My ip is not 123.123.1.23, I just feel weird about sharing my IP)
Even more strangely, when I do
bensmus@BENSMUSPC:~$ echo $DISPLAY
:0.0123.1.23

What the heck is going on?
I really want it to just be
bensmus@BENSMUSPC:~$ echo $DISPLAY
123.123.1.23:0.0

A: It looks like there is a char 0d character at the end of the data returned by the windowsip alias (probably because of the output encoding of ipconfig.exe):
myprompt~$ echo $DISPLAY
:0.0168.1.7

myprompt~$ echo $DISPLAY | xxd
00000000: 3139 322e 3136 382e 312e 370d 3a30 2e30  192.168.1.7.:0.0
00000010: 0a

Since 0d is the carriage return, I guess the weird result of printing $DISPLAY is caused by the print logic returning to the beginning of the line when it encounters 0d. But maybe that was obvious to everyone besides me...
Better Answer:
Since this is just a windows/unix newline issue, running ipconfig.exe through dos2unix seems to fix the problem:
alias windowsip="ipconfig.exe | dos2unix | grep IPv4 | cut -d: -f2 | head -1 | sed 's/^[ \t]*//;s/[ \t]*$//'"

Leading to:
myprompt:~$ echo $DISPLAY
192.168.1.7:0.0
myprompt~$ echo $DISPLAY | xxd
00000000: 3139 322e 3136 382e 312e 373a 302e 300a  192.168.1.7:0.0.

Previous Answer:
I'm not sure why there is an 0d in the middle and then a 0d at the end, but if you remove both with sed, it seems to work for me:
alias windowsip="ipconfig.exe | grep IPv4 | cut -d: -f2 | head -1 | sed 's/^[ \t]*//;s/[ \t]*$//;s/[\n\r]//g;'"

This leads to:
myprompt~$ echo $DISPLAY
192.168.1.7:0.0
myprompt~$ echo $DISPLAY | xxd
00000000: 3139 322e 3136 382e 312e 373a 302e 300a  192.168.1.7:0.0.

I'm not sure why it has a 0a at the end, but that seems to be the case if you just set it to a string:
myprompt~$ DISPLAY="192.168.1.7:0.0"
myprompt~$ echo $DISPLAY | xxd
00000000: 3139 322e 3136 382e 312e 373a 302e 300a  192.168.1.7:0.0.


text:
Q: How to make two instance of selenium safaridriver? How can i make two instance of selenium driver ?? i used these codes and i am having a problem.
        SafariDriver sf = new SafariDriver();

        sf.Navigate().GoToUrl("http://marathonbet.com/");

        SafariDriver sf2 = new SafariDriver();

        sf2.Navigate().GoToUrl("http://bet365.com/");

here is the screenshot: http://sdrv.ms/1fDzQYT

A: you can instantiate 2 instance of selenium webdriver, use the code below.

    WebDriver sf1 = new SafariDriver();
    sf1.Navigate().GoToUrl("http://marathonbet.com/");
    WebDriver sf2 = new SafariDriver();
    sf2.Navigate().GoToUrl("http://bet365.com/");

You need to instantiate WebDriver object with SafariDriver, that you were not doing correctly.


text:
Q: Configuring Apache content negotiation for languages using MultiViews I'm attempting to get the MultiViews option working in Apache to vary the content returned to the browser based on the Accept-Language provided in requests.
I've got the following configuration:
Alias /multiviewstest "C:/MultiViews Test"

<Directory "C:/MultiViews Test">
    Options MultiViews
    AllowOverride None
    Order allow,deny
    Allow from all
</Directory>

In my C:\MultiViews Test directory I have the following files:

*

*spam.html

*foo.html.en
When I request http://localhost/multiviewstest/spam the contents of spam.html is returned. Here are the request and response headers:
Host: localhost
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.0.10) Gecko/2009042316 Firefox/3.0.10 (.NET CLR 3.5.30729)
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache

Date: Fri, 08 May 2009 11:07:54 GMT
Server: Apache/2.2.10 (Win32)
Content-Location: spam.html
Vary: negotiate
TCN: choice
Last-Modified: Fri, 08 May 2009 10:48:34 GMT
Etag: "0-4-469645ec81e70;469645ff5a5d8"
Accept-Ranges: bytes
Content-Length: 4
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Content-Type: text/html

The Content-Location, Vary, and TCN response headers indicates MultiViews have correctly kicked in.
I've configured English as the only preferred language for displaying languages in my browser; an Accept-Language en header is set on requests. When I request http://localhost/multiviewstest/foo.html a 404 response is returned. Based on my understanding of Apache's file naming conventions for language negotiation I'd expect the contents of the foo.html.en file to be returned.
Here are the request and response headers:
Host: localhost
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.0.10) Gecko/2009042316 Firefox/3.0.10 (.NET CLR 3.5.30729)
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache

Date: Fri, 08 May 2009 11:08:39 GMT
Server: Apache/2.2.10 (Win32)
Content-Length: 221
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Content-Type: text/html; charset=iso-8859-1

Here's what appears in the access log for the request:
127.0.0.1 - - [04/May/2009:10:28:24 +1200] "GET /multiviewstest/foo.html HTTP/1.1" 404 221

And from the error log:
[Mon May 04 10:28:24 2009] [error] [client 127.0.0.1] Negotiation: discovered file(s) matching request: C:/MultiViews Test/foo.html (None could be negotiated).

Why isn't the content negotiation for the language correctly kicking in? Is there some configuration I have overlooked?

A: Do the proper language/extension relationships exist in your configuration?
AddLanguage en .en
LanguagePriority en fr de
ForceLanguagePriority Fallback

A: FWIW, I ran into a similar issue, with the proper AddLanguage etc directives in place.  Eventually I realized that the problem was PHP-specific.
For some reason I was using SetHandler within a FilesMatch directive:
<FilesMatch \.php$>
    SetHandler application/x-httpd-php
</FilesMatch>

Switching to a simple AddType solved the problem:
AddType application/x-httpd-php .php

A: The answer given by metkat hinted at the source of my trouble as well. However, I decided for a different approach. This is what my config had:
<FilesMatch ".+\.ph(p[345]?|t|tml)$">
    SetHandler application/x-httpd-php
</FilesMatch>

And this is what I changed it into:
<FilesMatch ".+\.ph(p[345]?|t|tml)(\.[a-z]{2}|)$">
    SetHandler application/x-httpd-php
</FilesMatch>

I basically added to the end of the file name: (\.[a-z]{2}|), which means "...followed by a dot and two characters of the range a-z OR (|) nothing". Seems to work smoothly so far :)


text:
Q: Creating a data-frame with Sequences of Dates When creating a data-frame with Sequences of Dates (months from Jan. to Oct. 2018), with a list of values, I have following lines:
sales <- c(429, 400, 986, 618, 754, 424, 289, 401, 916, 852)
periods <- seq(as.Date("2018/1/1"), as.Date("2018/10/1"), "months")

Passengers <- data.frame(sales, periods)
pax <- ts(Passengers)

ggplot(pax, aes(x = months, y = sales)) + geom_line(colour = "grey75")

The output doesn't show a column of periods:
Time Series:
Start = 1
End = 10
Frequency = 1
   sales periods
 1   429   17532
 2   400   17563
 3   986   17591
 4   618   17622
 5   754   17652
 6   424   17683
 7   289   17713
 8   401   17744
 9   916   17775
10   852   17805

The x axis of month doesn't show like a month, how can I have it displayed in yyyy-mm format? Thank you.

A: I'm also confused as to what you expected as output. In ts you need to specify the time of the first observation and the number of observations per unit of time (see ?ts for details and examples).
Perhaps you're after the functionality that zoo provides?
library(zoo)
z <- zoo(Passengers$sales, Passengers$periods)
plot(z)

time(z)
#[1] "2018-01-01" "2018-02-01" "2018-03-01" "2018-04-01" "2018-05-01"
#[6] "2018-06-01" "2018-07-01" "2018-08-01" "2018-09-01" "2018-10-01"


text:
Q: MySQL: 'group by' without losing marks I have a table like this:
name
Smith
Smith
Perez
Pérez

I would like to eliminate duplicates like Smith but preserve both Perez and Pérez (e and é).
If I use 'group by' I get two rows (Smith and one of the two Perez/Pérez), but I would like to get three rows (Smith, Perez, Pérez).
It happens the same with Sjögren and Sjogren, etc.
Thanks

A: 1)First check your table if it has utf8 charset encoding with
select table_name,engine
from information_schema.tables
where table_schema = 'your_database'

2)Secondly , if it is not than (else skip to 3rd step),  ALTER your table (utf8 character set encoding, so it will support special character)
ALTER TABLE `name` CHARACTER SET utf8;

3) SELECT from your db with utf8 charset
select * from your_table group by name collate utf8_general_ci

A: Try using utf8_unicode_ci rather than utf8_general_ci - it uses a more accurate comparison algorithm.


text:
Q: PHPExcel downloaded file giving error as file extension not correct in live server I am using PHPExcel library for downloading excel sheet in CodeIgniter framework. Its working fine in local server, its downloading excel sheet file, opening and showing correct data, now when I run that same code in live server it is downloading, when I open that file, it is giving this error, The file you are trying to open 'filename.xsl' is in a different format than specified by the file extension. verify that the file is not corrupted and is from a trusted source before opening the file.
Here is the code.
$this->excel->createSheet();
$this->excel->setActiveSheetIndex(2);
$filename='Monthly Report'.date("m-d-Y, h:i:s").'.xls';
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment; filename="'.$filename.'"');
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($this->excel, 'Excel5');
$objWriter->save('php://output');

I also used the method ob_end_clean(); before $objWriter, still got the same error. Any help will be appreciated.[it's in a live server on the local server it's working fine]

A: ob_end_clean();
ob_start();
Used the above lines of code before $objWriter->save('php://output');
and it worked.


text:
Q: value from span to input I have value that is displayed in span tag. If i want to post the value i have to assign that value to an input. So this is the code i have written to assign value to input and trying to post that value. But when i alert the assigned value its
showing as
[object Object]

Pls check the code and correct me.
var value = $("#spanElement").text();
var lower=$("#inputElement").val(value);
alert(lower);

and i tried this also
var value = $("#spanElement").text();
var lower=$("#inputElement").val(value);
alert(lower);

Both the above code shows
[object Object]

Because of this i am not able to post values.

A: That is because the value setter function on an input return the jQuery object of that input element only, it allows you to chain the event.
Try this
var value = $("#spanElement").text();
var lower=$("#inputElement").val(value);
alert(lower.val());

Read more about it here http://api.jquery.com/val/#val-value

A: "lower" is an object. if you want to see the text inside, you need to call lower.val().
e.g.
var value = $("#spanElement").text();
var lower=$("#inputElement").val(value);
alert(lower.val());

A: jQuery supports chaining objects return.
So, whenever you do an operation on an object (except some like .val() getter, it returns object of that selector element.
So, you can do much more operations in a single statement.
In your statement,
var lower=$("#inputElement").val(value);
alert(lower);,

It is returning the object of element #lower.
You can add more operations to it.
For example:
var lower=$("#inputElement").val(value).css('color', 'red');

You want only plain value.
So, rather you should do this:
var value = $("#spanElement").text();
$("#inputElement").val(value);
var lower=$("#inputElement").val();
alert(lower);

A: Just do in this way..
var span_text = $("#spanElement").text(); //get span text
$("#inputElement").val(span_text); //set span text to input value
var input_value = $("#inputElement").val(); //get input value
alert(input_value); //alert input value

Hope this will help

A: This is because it will return a jQuery object . If you want to see the same text which is in the input you can either use .val() like answered previously or use like this
var value = $("#spanElement").text();
var lower=$("#inputElement").val(value);
alert($("#spanElement").prop('innerHTML'));

WORKING DEMO

A: You are getting 'Object Object' because lower is an object if you want to get the text you need to perform below actions.
var value = $("#spanElement").text();
var lower=$("#inputElement").val(value);
alert(lower.val());

Or
var value = $("#spanElement").text();
var lower=$("#inputElement").val(value);
alert(lower.val());

Hope it helps !


text:
Q: rails - render form fields dynamically I Have a Simple Form field with year and month field in the form.
<%= form_for :calender, remote: true do |f| %>
  <%= f.select :year, @year_array %>

  <% if :year == DateTime.now.strftime("%Y").to_i %>
    <%= f.select :month, @month_array[0..Date::MONTHNAMES.index(DateTime.now.strftime("%B"))-1] %>
  <% else %>
    <%= f.select :month, @month_array %>
  <% end %>

  <%= f.submit "Submit" %>
<% end %>

@year_array data contains in format [[2020, 2020], [2021, 2021], [2022, 2022]]

@month_array data contains in format
[["January", "Jan"], ["February", "Feb"], ["March", "Mar"], ["April", "Apr"], ["May", "May"],
 ["June", "Jun"], ["July", "Jul"], ["August", "Aug"], ["September", "Sep"], ["October", "Oct"],
 ["November", "Nov"], ["December", "Dec"]]

How can I render this form dynamically. what I mean is when the user select the current year then month only render up to current month from January rather than whole array.


text:
Q: How to generate this list from user entered number using python? I want to generate a list from user entered number using Python
I had tried it but I was unable to find out the proper solution for it.

For example:
If user enters 2, then list should be [1,1]
If user enters 11, then list should be [1,2,3,4,1]
If user enters 12, then list should be [1,2,3,4,2]
If user enters 16, then list should be [1,2,3,4,5,1]
If user enters 24 then list should be [1,2,3,4,5,6,3]

Rules:

*

*Total of all the numbers in the list should equal the input number.

*The first number in the list be 1

*Except the last number, difference between any two elements should be 1

*Last number should be equal to input number - sum of all the numbers in the list.

A: maxNum, current, result = 12, 1, []

while maxNum > current:
    result.append(current)
    maxNum -= current
    current += 1
result.append(maxNum)
print result

Output
[1, 2, 3, 4, 2]

Edit:
Mathematical solution:
inputNumber = int(raw_input("Please enter the input number: "))
a, b, c = 1, 1, -2 * inputNumber
innerPart = ((b**2) - 4 * a * c)**0.5
N = int(max((-b + innerPart) / (2 * a), (-b - innerPart) / (2 * a)))
result, sumTillN = [i for i in range(1, N + 1)], (N * (N + 1)) // 2
if inputNumber - sumTillN: result.append(inputNumber - sumTillN)
print result

First N - 1 elemets can be calculated using N(N+1)/2 formula. We can find positive N for N^2+N-2*inputNumber and fill the first N - 1 elements. The last element will be just the remainder.


text:
Q: Laravel - retrieve data inside controller – POST x PATCH First important information: I'm new to laravel, so your patience is appreciated.
I'm currently migrating a framework of mine to laravel, so I'm in the early stages.
Currently, I'm trying to set up an API endpoint to make small changes on some records. I've already managed to set up a API for inserting records and works perfectly. However, for setting up an API for small changes (patch), I'm having difficulties, probably because I'm not fully familiar with laravel's Request class.
My successful insert set up looks like this:
\routes\api.php
Route::post('/categories/',[ApiCategoriesInsertController::class, 'insertCategories'], function($insertCategoriesResults) {
    return response()->json($insertCategoriesResults);
})->name('api.categories.insert');

\app\Http\Controllers\ApiCategoriesInsertController.php
// some code
public function insertCategories(Request $req): array
{
    $this->arrCategoriesInsertParameters['_tblCategoriesIdParent'] = $req->post('id_parent');

    // some code
}

With this set up, I'm able to retrieve "id_parent" data set through POST.
So, I tried to do exactly the same architecture for patch, but doesn't seem to work:
\routes\api.php
Route::patch('/records/',[ApiRecordsPatchController::class, 'patchRecords'], function($patchRecordsResults) {
    return response()->json($patchRecordsResults);
})->name('api.records.patch');

\app\Http\Controllers\ApiRecordsPatchController.php
// some code
public function patchRecords(Request $req): array
{
    $this->arrRecordsPatchParameters['_strTable'] = $req->post('strTable');

    // some code
}

In this case, I´m using postman (PATCH request), testing the data in the "Body tab" with key "strTable" and value "123xxx" and I´m receiving "strTable" as null.
Any idea of why this is happening or if I should use another method in the Request class?
Thanks!

A: You can access parameters on the Request object using one of the following methods:
$req->strTable;

// or

$req->input('strTable');

The input method also accepts a second parameter which will be used as the default return value if the key is not present in the Request.
If you want to check whether or not the Request contains a value before you attempt to access it, you can use filled:
if ($req->filled('strTable')) {
  // The request contains a value
}

A: Turns out that the way I had set up was in fact working and retrieving data:
$req->post('strTable');

The problem was in how I was testing it. In postman, there are several options to configure:

*

*form-data

*x-www-form-urlencoded

*raw

*binary

I had already switched to x-www-form-urlencoded to test it, but I forgot to fill the "key" and "value" information again. I didn't realize that the fields blank as we switch between them.

Summing it up: It works when x-www-form-urlencoded selected but doesn't work with form-data selected. Don't know what the difference between them yet, but I'll research it further.
By the way, it worked also with the suggestion from Rube Hart:


text:
Q: Not able to upload 2gb size file with struts 2.0 frmework Now days all latest browser, support 2 gb size limit for file upload process,
Right now we are using following in our application
Java, JSP, Struts 2.0 framework , we did not able to upload 2gb size file, so i have search in net, i am able to find  struts.multipart.maxSize property configuration in struts.xml, i have set this value up to 2gb size, i have also set maxPostSize size property in tomcat server.xml file for increase postdata size with request.
Still we did not able to upload  2gb size file from browser.
Please some one advice us, is there any setting available in Apache server, tomcat, struts or browser, then let us know about those.
We are not using fileUpload interceptor in our file upload action
<action name="fileUpload" method="fileUpload" class="fileUploadAction">
<interceptor-ref name="check">
</interceptor-ref>
<result name="Errorjsp">tFrame.jsp</result>
<result name="insert">FileFrame.jsp</result>
</action>

and our java side action have flat logic of upload , there is no filesize limit validation  at server side code.
i want to know the reasons why large file did not upload?
for more update , we found that issue creating in our environment is CDN network. Client request through browser to send file to cdn network , and then cdn network send those file to actual server.
Issue only happen due to cdn network when we request of more than 2 gb size file,so it is not related to browser issue.
Issue not happen with cdn network , when we send out file byte to chunk to cdn network,means when we send chunk request of file byte using one java demo program. so from this analysis, we can say that cdn network work properly when we send data in chunk-ed.
and in our case we sending file upload request throgh browser, so we can't send chunk-ed request, So now my question is that is any technique or mechanism available to resolve our issue Is there any js or request mechanism available , which send chunk byte request through browser? Is there any other technique available to resolve our issue?
Thanks and regards Yatin Baraiya

A: Struts2 lets you upload file UP TO 2GB, that is the maximum allowed size for a Request:

This setting defaults to approximately 2 megabytes and should be adjusted to the maximum size file (2 gigs max) that your will need the framework to receive.

To do that, you need to set both:

*

*set the common <constant name="struts.multipart.maxSize" value="2147483648" />, for the overall request size;

*set the FileUpload Interceptor parameter, both locally to an Action, or common to a package, for the single file maximum size:
<interceptor-ref name="fileUpload">
    <param name="maximumSize">2147483648</param>
</interceptor-ref>

The .2 is the missing piece in your configuration: currently, you are allowed to send 2 GigaBytes of stuff, but with a maximum filesize of 2 MegaBytes, eg. 1000 files of 2mb max each one.
Apply the above setting to your configuration to make it work, eg:
<action name="doUpload" class="com.example.UploadAction">
    <interceptor-ref name="defaultStack">
        <param name="fileUpload.maximumSize">2147483648</param>
    </interceptor>
    <result name="success">good_result.jsp</result>
</action>


text:
Q: Click module ignoring subgroup commands Trying to implement the example from the palletsprojects website:
https://click.palletsprojects.com/en/7.x/commands/
imoport click

@click.group()
@click.option('--debug/--no-debug', default=False)
def cli(debug):
    click.echo('Debug mode is %s' % ('on' if debug else 'off'))

@cli.command()  # @cli, not @click!
def sync():
    click.echo('Syncing')

The following lines produce no output in my terminal:
python cli_test.py cli
python cli_test.py sync
python cli_test.py

When I'd expect 'Syncing' to be printed for the second line.

A: You're (presumably from how I understand the library) supposed to invoke a master command after setting up the commands and groups. Append this to your code:
if __name__ == '__main__':
    cli()

And python cli_test.py sync should in turn call the sync command.


text:
Q: AngularJs: Error: [ng:areq] Argument 'fn' is not a function, got undefined guys!
I am working on some Angular code from another person, and I am trying to figure stuff out. I updated libraries, using bower (because I needed some newer version to finish off the work) and I've got an error from Angular, on my homepage. The error is as follows: "Error: [ng:areq] Argument 'fn' is not a function, got undefined". I tried to debug it but no success. I also read a lot about it in here but nothing helped me. From what I've read the problem could be in the app .config() or in a wrongly declared controller, or ... who knows :D
If you'd like to try and help me, I will provide important (in my opinion) bits of code:
1) App configuretion:

'use strict';
var agencySeekApp = angular.module('agencySeekApp', ['ngResource', 'ngRoute', 'flang', 'ngCookies', 'agencySeekFilters'])
      .value('toastr', toastr)
      .config(function($routeProvider, $locationProvider) {
        $locationProvider.html5Mode({
          enabled: true,
          requireBase: false
        });

        var routeUserChecks = {
          adminRole: {
            authenticate: function(auth) {
              return auth.isAuthorizedForRole('admin');
            }
          },
          authenticated: {
            authenticate: function(auth) {
              return auth.isAuthenticated();
            }
          }
        };

        $routeProvider
          .when('/', {
            templateUrl: '/app/views/home.html',
            controller: 'HomePageCtrl'
          })
          .when('/category/:categoryId/choose-network/', {
            templateUrl: '/app/views/network_pick.html',
            controller: 'ChooseNetworkCtrl'
          })
          .when('/category/:categoryId/network/:networkId', {
            templateUrl: '/app/views/schools_pick.html',
            controller: 'SchoolPageCtrl'
          })
          .when('/agencies/:categoryId/:schoolId', {
            templateUrl: '/app/views/agency.html',
            controller: 'AgencyPageCtrl'
          })
          .when('/show/agency/:agencyId', {
            templateUrl: '/app/views/agency_show.html',
            controller: 'ShowAgencyCtrl'
          })
          .when('/show/school/:schoolId', {
            templateUrl: '/app/views/school_show.html',
            controller: 'ShowSchoolCtrl'
          })
          .when('/case/open', {
            templateUrl: '/app/views/open_case.html',
            controller: 'OpenCaseCtrl'
          })
          .when('/case/show/:case_id', {
            templateUrl: '/app/views/show_case.html',
            controller: 'ShowCaseCtrl'
          })
          .when('/account/retrivePassword', {
            templateUrl: '/app/views/account.html',
            controller: 'AccountPageCtrl'
          })
          .when('/search/:search_params',{
            templateUrl: '/app/views/search_page.html',
            controller: 'SearchPageCtrl'
          }).when('/postcode-agencies/category/:categoryId/postcode-id/:postCodeId',{
            templateUrl: '/app/views/post_code_agencies.html',
            controller: 'PostCodeAgenciesCtrl'
          })
        /*for delete*/
          .when('/sysadmin/network',{
            templateUrl: '/app/views/sys_admin_network.html',
            controller: 'SysAdminNetworkCtrl'
          })
          .when('/sysadmin/categories',{
            templateUrl: '/app/views/sys_admin_categories.html',
            controller: 'SysAdminCategoriesCtrl'
          })
          .when('/sysadmin/list',{
            templateUrl: '/app/views/sys_admin_list.html',
            controller: 'SysAdminListCtrl'
          })
          .when('/sysadmin/users',{
            templateUrl: '/app/views/sys_admin_users.html',
            controller: 'SysAdminUsersCtrl'
          })
        /*end*/
        /*account*/
          .when('/account/cases',{
            templateUrl: '/app/views/account_cases.html',
            controller: 'AccountCasesCtrl'
          })
          .when('/account/teachers',{
            templateUrl: '/app/views/account_teachers.html',
            controller: 'AccountTeachersCtrl'
          })
          .when('/account/schools',{
            templateUrl: '/app/views/account_schools.html',
            controller: 'AccountSchoolsCtrl'
          })
          .when('/account/agencies',{
            templateUrl: '/app/views/account_agencies.html',
            controller: 'AccountAgenciesCtrl'
          })
          .when('/account/case_workers',{
            templateUrl: '/app/views/account_councilors.html',
            controller: 'AccountCouncilorsCtrl'
          })
          .when('/account/linking',{
            templateUrl: '/app/views/account_linking.html',
            controller: 'AccountLinkingCtrl'
          })
          .when('/account/handshaking',{
            templateUrl: '/app/views/account_handshaking.html',
            controller: 'AccountHandshakingCtrl'
          })
          .when('/account/myprofile',{
            templateUrl: '/app/views/my_profile.html',
            controller: 'AccountProfileCtrl'
          })
          .when('/account/report',{
            templateUrl: '/app/views/account_report.html',
            controller: 'AccountReportCtrl'
          })
          .when('/account/admin-settings', {
            templateUrl: '/app/views/account_admin_settings.html',
            controller: 'AccountAdminSettingsCtrl'
          })

        /*end*/
          .otherwise({
            templateUrl: '/app/views/home.html',
            controller: 'in_Otherwise'
          });
      });

2) Homepage controller:

angular.module('agencySeekApp')
  .controller('HomePageCtrl',['$scope','identity','$http','selectedSchoolCookieService',function($scope,identity,$http,selectedSchoolCookieService){
    //$scope.test = 'some test';
    $scope.identity = identity;
    $http.get('/api/v1/agency/categories')
      .success(function(res){
        console.log("res : ",res);
        $scope.arr = res.data;
      })
      .error();

    var url = '';
    var schoolIdCookie = selectedSchoolCookieService.getCookie('schoolId');
    $scope.urlForTheUser = function (someId) {
      if(identity.currentUser && identity.currentUser.isFromSchool() ){
        url = '/agencies/'+someId+'/'+identity.currentUser.school_id+'/';
      }else {
        if(schoolIdCookie) {
          url = '/agencies/' + someId + '/' + schoolIdCookie;
        }else {
          url = '/category/'+someId+'/choose-network/';
        }
      }
      return url;
    };

3) The scripts section from my index.html, including all the scripts (for inclusion order reference):

<script type="text/javascript" src="/lib/jquery/dist/jquery.min.js"></script>
<script type="text/javascript" src="/lib/charts/jquery.flot.js"></script>
<script type="text/javascript" src="/lib/charts/jquery.flot.pie.js"></script>
<script type="text/javascript" src="/lib/charts/jquery.flot.spline.js"></script>
<script type="text/javascript" src="/lib/jRate-master/dist/jRate.min.js"></script>

<script type="text/javascript" src="/lib/angular/angular.js"></script>
<script type="text/javascript" src="/lib/bootstrap/dist/js/bootstrap.min.js"></script>
<script type="text/javascript" src="/lib/toastr/toastr.js"></script>
<script type="text/javascript" src="/lib/angular-resource/angular-resource.min.js"></script>
<script type="text/javascript" src="/lib/angular-route/angular-route.js"></script>
<script type="text/javascript" src="/lib/angular-cookies/angular-cookies.js"></script>
<script type="text/javascript" src="/lib/angular-sanitize/angular-sanitize.min.js"></script>
<script type="text/javascript" src="/app/flangCharts.js"></script>
<script type="text/javascript" src="/app/app.js"></script>
<script type="text/javascript" src="/app/custom.js"></script>

<script type="text/javascript" src="/app/account/auth.js"></script>
<script type="text/javascript" src="/app/account/identity.js"></script>
<script type="text/javascript" src="/app/account/LoginController.js"></script>
<script type="text/javascript" src="/app/account/usersResource.js"></script>
<script type="text/javascript" src="/app/services/selectedAgencies.js"></script>
<script type="text/javascript" src="/app/services/pageService.js"></script>
<script type="text/javascript" src="/app/services/selectedSchoolCookieService.js"></script>
<script type="text/javascript" src="/app/services/lastPageCategorySelected.js"></script>
<script type="text/javascript" src="/app/directives/fileUploadDirective.js"></script>
<script type="text/javascript" src="/app/directives/popUpAgencyDirective.js"></script>
<script type="text/javascript" src="/app/directives/popUpLinkingDirective.js"></script>
<script type="text/javascript" src="/app/directives/reportDirectives.js"></script>
<script type="text/javascript" src="/app/filters.js"></script>

<script type="text/javascript" src="/app/controllers/HomePageCtrl.js"></script>
<script type="text/javascript" src="/app/controllers/ChooseNetworkCtrl.js"></script>
<script type="text/javascript" src="/app/controllers/ShowAgencyCtrl.js"></script>
<script type="text/javascript" src="/app/controllers/SchoolPageCtrl.js"></script>
<script type="text/javascript" src="/app/controllers/AgencyPageCtrl.js"></script>
<script type="text/javascript" src="/app/controllers/ShowAgencyCtrl.js"></script>
<script type="text/javascript" src="/app/controllers/OpenCaseCtrl.js"></script>
<script type="text/javascript" src="/app/controllers/SearchPageCtrl.js"></script>
<script type="text/javascript" src="/app/controllers/ShowCaseCtrl.js"></script>
<script type="text/javascript" src="/app/controllers/ShowSchoolCtrl.js"></script>
<script type="text/javascript" src="/app/controllers/LeftSideBarCtrl.js"></script>
<script type="text/javascript" src="/app/controllers/PostCodeAgenciesCtrl.js"></script>
<script type="text/javascript" src="/app/controllers/AccountAdminSettingsCtrl.js"></script>
<script type="text/javascript" src="/app/account/user_page_ctrl/SysAdminNetworkCtrl.js"></script>
<script type="text/javascript" src="/app/account/user_page_ctrl/SysAdminListCtrl.js"></script>
<script type="text/javascript" src="/app/account/user_page_ctrl/SysAdminUsersCtrl.js"></script>
<script type="text/javascript" src="/app/account/user_page_ctrl/SysAdminCategoriesCtrl.js"></script>
<script type="text/javascript" src="/app/account/user_page_ctrl/AccountCasesCtrl.js"></script>
<script type="text/javascript" src="/app/account/user_page_ctrl/AccountTeachersCtrl.js"></script>
<script type="text/javascript" src="/app/account/user_page_ctrl/AccountSchoolsCtrl.js"></script>
<script type="text/javascript" src="/app/account/user_page_ctrl/AccountAgenciesCtrl.js"></script>
<script type="text/javascript" src="/app/account/user_page_ctrl/AccountCouncilorsCtrl.js"></script>
<script type="text/javascript" src="/app/account/user_page_ctrl/AccountLinkingCtrl.js"></script>
<script type="text/javascript" src="/app/account/user_page_ctrl/AccountMenuCtrl.js"></script>
<script type="text/javascript" src="/app/account/user_page_ctrl/AccountHandshakingCtrl.js"></script>
<script type="text/javascript" src="/app/account/user_page_ctrl/AccountProfileCtrl.js"></script>
<script type="text/javascript" src="/app/account/user_page_ctrl/AccountReportCtrl.js"></script>

Hope that is enough!
Best regards,
H.

A: I found the problem. When calling the $http, I should chain a .success() callback and a .error(). The problem is that the .error() expects an function argument, and I am supplying nothing. What fixed is was:
 .error(function(data, status, headers, config){
    console.log(data, status, headers, config);
  });

That was it :)
Thanks for the tip on breakpoints. I can't believe I didn't do that and just ran to StackOverflow crying :D
Anyway, It's done. Thanks to @bilpor for helping me!

A: It's hard to tell from this. Have you tried stepping the code to try and narrow the line that it doesn't like. You should be able to use the Chrome browser tools and set breakpoints etc. I'm assuming from your first piece of code that

'ngResource', 'ngRoute', 'flang', 'ngCookies', 'agencySeekFilters'

are present


text:
Q: Sidebar menu implementation on iOS like Facebook? I want to create side-bar menu like in Facebook iPhone app in iOS 6.
How can I create it?
I'm new to this iPhone development.
Please give me some pointers or tell me some basic tutorial that I can follow step by step to achieve it.

A: There are lots of implementations but I will suggest you JTRevealSidebarDemo its simple and easy to customize, you can also use ViewDeck or JASidePanels.
JASidePanels is well documented and has basic examples for new developers like you!

A: We can easily do it by ourselves. It's so easy.
The approach I explain here is being used in my app.
objective:

When a button is pressed in title bar a side bar has to slide in and
  out from left side.

Steps:

1) Create a view controller(home) and two nsObject
  classes(sidebar,main)
2) add a tool bar on view controller
3) In sidebar (Left side view):
i) Build a uiview(to be added on vc) with desired sidebar width within that add views as needed for your project
ii) then create button and make it as property because it's target
  events will have to occur in view controller
iii) you have to have two CGRects for both button and the resultant
  view one CGrect is for expanded state another CGrect is for collapsed
iv) as far as button is cocerned it's x is sidebarwidth-buttonwidth
  for expanded state and it's x is 0+buttonwidth for collapsed state and
  as far as view is concerned it's x is 0 for expanded state and it's x
  is -sidebarwidth for collapsed state
4) In main(right side view):
i) Build a UIView and add it to UiscollView(to be added on vc)
ii) UIView will have two CGREcts for UIscrollView one for expanded and
  one for collapsed
iii) UIview's x is 0 y is 0 width is 1024 and height is 726(landscape
  view height-toolbar width on vc)
iv) On Collapsed time uIscrollview's x is sidebarwidth y is 42(vc'tool
  bar height) and width is 1024-sidebarwidth and height is same as
  uiview's
v) on expanded time Uiscrollview's x is 0 and width becomes 1024
vi) Uiscrollview content size always should be 1024,726 as we need
  scrolling if the size is shrunk than this
5) In view controller (home page):
i) add both the side bar and main in home
ii) then add and event for the button in sidebar and then add it on
  the tool bar usign addsubview method
iii) In the button touch event call toggle events inside
 -(void)OnCollapsibleExtenderTouchUpInside
{
   [UIView animateWithDuration:1.0 animations:^{

    [sideBarObj ToggleVuPosition];

    [mainVuObj ToggleVuSize];

 }];

}

The below code works for me..(I just renamed some field for my own
  sake)

To understand the below code better:

1) The View controller name is Home and side bar name is side bar and
  right side area name is Main
2) I have wrote the coding for landscape alone...you can customize it
  for portrait also one use it.

Side bar:
#import <Foundation/Foundation.h>

@interface SideBar : NSObject
{
UIView *vuSideBar;

UIScrollView *scrollVuSideBar;

UIImageView *imgProfilePicture;

CGRect rectVuSideBar,rectExpandedScrollVuSideBar,rectCollapsedScrollVuSideBar,rectImgProfilePicture,rectExpandedBtnCollapsibleExtender,rectCollapsedBtnCollapsibleExtender;

 int sideBarWidth,sideBarHeight;
}

@property(strong,nonatomic)UIButton *btnCollapsibleExtender;

-(id)initWithParent:(UIView *)vuParent andToolBar:(UIToolbar *)toolBarParent;

-(void)ToggleVuPosition;

@end

Side bar implementation:
 #import "SideBar.h"

@interface  SideBar()

-(void)initRects;

-(void)initVus;

-(void)initOtherIvars;

-(void)AddViewsOnHierarchy;

-(void)AddToParentVu:(UIView *)ParentVu;

-(void)OnCollapsibleExtenderTouchUpInside;

@end

@implementation SideBar

@synthesize btnCollapsibleExtender;

-(id)initWithParent:(UIView *)vuParent andToolBar:(UIToolbar  *)toolBarParent
{
 self = [super init]; //calls init because UIResponder has no custom init methods
 if (self)
 {
    [self initOtherIvars];

    [self initRects];

    [self initVus];

    [self AddViewsOnHierarchy];

    [self AddToParentVu:vuParent];

    [self AddToParentToolbar:toolBarParent];

   }
   return self;
 }

 -(void)initOtherIvars
 {
   NSLog(@"initOtherIvars");

   sideBarWidth=300;

   sideBarHeight=768;
 }

 -(void)initRects
 {
  NSLog(@"initRects");

  rectExpandedScrollVuSideBar=CGRectMake(0,42,sideBarWidth,sideBarHeight);

 rectCollapsedScrollVuSideBar=CGRectMake(-sideBarWidth,42,sideBarWidth,sideBarHeight);

rectExpandedBtnCollapsibleExtender=CGRectMake(sideBarWidth-30,6,30,30);

rectCollapsedBtnCollapsibleExtender=CGRectMake(6,6,30,30);

rectVuSideBar=CGRectMake(0,0,sideBarWidth,sideBarHeight);

rectImgProfilePicture=CGRectMake(5,5,sideBarWidth-10,200);
 }

 -(void)initVus
 {
  NSLog(@"initVus");

   scrollVuSideBar=[[UIScrollView  alloc]initWithFrame:rectExpandedScrollVuSideBar];

   [scrollVuSideBar setContentSize:CGSizeMake(sideBarWidth,sideBarHeight)];

   btnCollapsibleExtender=[[UIButton alloc]initWithFrame:rectExpandedBtnCollapsibleExtender];

   UIImage *imgCollapsibleExtender=[UIImage imageNamed:@"SideBarExpandCollapse.png"];

   [btnCollapsibleExtender setImage:imgCollapsibleExtender forState:UIControlStateNormal];

   vuSideBar=[[UIView alloc]initWithFrame:rectVuSideBar];

   [vuSideBar setBackgroundColor:[UIColor darkGrayColor]];

   imgProfilePicture=[[UIImageView alloc]initWithFrame:rectImgProfilePicture];

   UIImage *imgDefaultProfile=[UIImage imageNamed:@"defaultProfileImage.png"];

   [imgProfilePicture setImage:imgDefaultProfile];

  }

 -(void)AddViewsOnHierarchy
{
   NSLog(@"AddViewsOnHierarchy");

   [vuSideBar addSubview:imgProfilePicture];

   [scrollVuSideBar addSubview:vuSideBar];
 }

 -(void)AddToParentVu:(UIView *)ParentVu
 {
   NSLog(@"AddToParent vu");

  [ParentVu addSubview:scrollVuSideBar];
 }

 -(void)AddToParentToolbar:(UIToolbar *)ParentToolBar
 {
  NSLog(@"AddToParent toolbar");

 [ParentToolBar addSubview:btnCollapsibleExtender];
 }

 -(void)ToggleVuPosition
 {
 switch ((int)scrollVuSideBar.frame.origin.x)
 {
     case 0:

        scrollVuSideBar.frame=rectCollapsedScrollVuSideBar;

             btnCollapsibleExtender.frame=rectCollapsedBtnCollapsibleExtender;

        break;

      default:

        scrollVuSideBar.frame=rectExpandedScrollVuSideBar;

          btnCollapsibleExtender.frame=rectExpandedBtnCollapsibleExtender;

        break;
   }
 }

@end

Main(Right side view):
 #import <Foundation/Foundation.h>

 @interface MainView : NSObject
 {
  UIView *vuMain;

  UIScrollView *scrollVuMain;

  CGRect  rectVuMain,rectScrollVuMainExpanded,rectScrollVuMainCollpased;

  int mainWidth,mainHeight,sideBarWidth,HeaderBarHeight;
 }

 -(id)initWithParent:(UIView *)vuParent;

 -(void)ToggleVuSize;
 @end

Main(Right side view) implementation:
#import "MainView.h"

@interface MainView ()

-(void)initRects;

-(void)initVus;

-(void)initOtherIvars;

-(void)AddViewsOnHierarchy;

-(void)AddToParentVu:(UIView *)ParentVu;

@end

@implementation SGGI_MainView

-(id)initWithParent:(UIView *)vuParent
{
  self = [super init]; //calls init because UIResponder has no custom init methods
  if (self)
  {
    [self initOtherIvars];

    [self initRects];

    [self initVus];

    [self AddViewsOnHierarchy];

    [self AddToParentVu:vuParent];
   }
   return self;
 }

-(void)initRects
{
rectVuMain=CGRectMake(0,0,1024,726);

       rectScrollVuMainExpanded=CGRectMake(0,HeaderBarHeight,mainWidth,mainHeight-HeaderBarHeight);

  rectScrollVuMainCollpased=CGRectMake(sideBarWidth,HeaderBarHeight,mainWidth-sideBarWidth,mainHeight-HeaderBarHeight);
}

-(void)initVus
{
 scrollVuMain=[[UIScrollView alloc]initWithFrame:rectScrollVuMainCollpased];

 [scrollVuMain setContentSize:CGSizeMake(mainWidth,mainHeight-HeaderBarHeight)];

 vuMain=[[UIView alloc]initWithFrame:rectVuMain];

 UILabel *lbl=[[UILabel alloc]initWithFrame:CGRectMake(0,0,1024,30)];

 [lbl setText:@"Details123456789abcdefghijklmnopqrstuvwxyz987654321abcdefghijklmnopqrstuvwxyz123456789abcdefghijklmnopqrstuvwxyz9876"];

 [vuMain addSubview:lbl];

}

-(void)initOtherIvars
{
 NSLog(@"initOtherIvars");

 mainWidth=1024;

 mainHeight=768;

 sideBarWidth=300;

 HeaderBarHeight=42;

}

-(void)AddViewsOnHierarchy
{
 [scrollVuMain addSubview:vuMain];
}

  -(void)AddToParentVu:(UIView *)ParentVu
 {
   [ParentVu addSubview:scrollVuMain];
 }

  -(void)ToggleVuSize
 {

 switch ((int)scrollVuMain.frame.size.width)
 {
    case 1024:

        scrollVuMain.frame=rectScrollVuMainCollpased;

        break;

    default:

        scrollVuMain.frame=rectScrollVuMainExpanded;

        break;
  }
}

@end

Home(Embedding the above two one a VC):
#import <UIKit/UIKit.h>

@interface Home : UIViewController

@end

Home implementation:
#import "Home.h"

#import "sideBar.h"

#import "Main.h"

@interface Home ()
{
 sideBar *sideBarObj;

 Main *mainVuObj;

 UIToolbar *HeaderBarObj;
 }

 -(void)AddSideBar;

 -(void)AddMainView;

 -(void)AddHeaderBar;

 -(void)AddCollapsibleExtenderEvent;

 -(void)OnCollapsibleExtenderTouchUpInside;

@end

@implementation Home

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
 self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
 if (self) {
    // Custom initialization
 }
  return self;
}

- (void)viewDidLoad
{
 [super viewDidLoad];

 [self.view setBackgroundColor:[UIColor grayColor]];

 [self AddHeaderBar];

 [self AddSideBar];

  [self AddMainView];

 [self AddCollapsibleExtenderEvent];
}

  - (void)didReceiveMemoryWarning
 {
  [super didReceiveMemoryWarning];
  // Dispose of any resources that can be recreated.
 }

-(void)AddHeaderBar
 {
  HeaderBarObj=[[UIToolbar  alloc]initWithFrame:CGRectMake(0,0,1024,42)];

  [self.view addSubview:HeaderBarObj];
 }

-(void)AddSideBar
{
 sideBarObj=[[SideBar alloc]initWithParent:self.view andToolBar:HeaderBarObj];
}

-(void)AddMainView
{
 mainVuObj=[[MainView alloc]initWithParent:self.view];
}

-(void)AddCollapsibleExtenderEvent
{
SEL   selCollapsibleTouch=@selector(OnCollapsibleExtenderTouchUpInside);

 [sideBarObj.btnCollapsibleExtender addTarget:self action:selCollapsibleTouch forControlEvents:UIControlEventTouchUpInside];
}

-(void)OnCollapsibleExtenderTouchUpInside
{
     [UIView animateWithDuration:1.0 animations:^{

    [sideBarObj ToggleVuPosition];

    [mainVuObj ToggleVuSize];

 }];

}

@end

The above code can be customized further by without using main and adding the code for that in Home view controller likewise one can avoid a separate class for sidebar and include that in home viewcontroller itself.
As far as when user presses button in sidebar, for changes in main view you can use protocol delegates or we can have the buttons in sidebar as property and add events in view controller.
I hope this helps.

A: You can use InteractiveSideMenu library written in Swift. It's quite good documented and has a lot of customizations.


text:
Q: Index of checked/unchecked checkbox in listview I am trying to modify XML file based on a value (true/false) of checked checkbox in listview, so I need index of a used checkbox. Problem is whenever I check or uncheck a checkbox I get the same result when using ListView.FocusedItem.Index because when clicking on a checkbox item is not selected.
Is it possible to get index of a currently used checkbox in a listview?

A: In the ListView ItemCheck event check the e.Index. Here is an example of how I have used this.
Private Sub lvCoffee_ItemCheck(ByVal sender As Object, ByVal e As ItemCheckEventArgs) Handles lvCoffee.ItemCheck
        ' e.Current state - the state before the click
        ' e.New State - after the click
        'While the ListView loads the check boxes, keep the update code from running
        If LoadingChecks Then
            Exit Sub
        End If
        'This code runs BEFORE the check mark changes
        'Hence the use of e.NewValue
        Dim bolFav As Boolean
        If e.NewValue = CheckState.Checked Then
            bolFav = True
        Else
            bolFav = False
        End If
        Cursor.Current = Cursors.WaitCursor
        Try
            'I store the primary key value in the Tag property of the ListViewItem
            DataAccess.UpdateFavorites(CInt(lvCoffee.Items(e.Index).Tag), bolFav)
        Catch ex As Exception
            MessageBox.Show($"The change to {lvCoffee.Items(e.Index).SubItems(1).Text} failed.{vbCrLf}{ex.Message}", "Favorites change Failed", MessageBoxButtons.OK, MessageBoxIcon.Error)
        Finally
            Cursor.Current = Cursors.Default
        End Try
    End Sub


text:
Q: Display first comment of post outside the comments template (using SQL maybe) in Wordpress, how can I find and display the first comment or the comment of an administrator outside of the comments table?
I imagine like an sql query that displays the first comment of the post...
Any clues?
Thank you!
This is a function that gets 5 recent comments of all posts. I would like to edit this and show the latest of the post I am reading
function showLatestComments() {
  global $wpdb;
  $sql = "
   SELECT DISTINCT comment_post_ID, comment_author, comment_date_gmt, comment_approved, SUBSTRING(comment_content,1,100) AS com_excerpt
   FROM $wpdb->comments
   WHERE comment_approved = '1'
   ORDER BY comment_date_gmt DESC
   LIMIT 5";
 $comments = $wpdb->get_results($sql);
 $output .= '
latest comments

';
 foreach ($comments as $comment) {
   $output .= '
'. $comment->comment_author . ' said : "' . strip_tags($comment->com_excerpt). '..."
';
   }
 $output .= '
';
 echo $output;
}//end function

A: I take it that "first post" means the earliest comment.  One simple way is to change the order (so earlier comments come first), then take the first row.
$sql = "
 SELECT DISTINCT comment_post_ID, comment_author, comment_date_gmt,
     comment_approved, SUBSTRING(comment_content,1,100) AS com_excerpt
 FROM $wpdb->comments
 WHERE comment_approved = '1'
 ORDER BY comment_date_gmt ASC
 LIMIT 1";

Only these two lines need to be changed if you do it this way.
 ORDER BY comment_date_gmt ASC
 LIMIT 1";

A: I'm not familiar with the database structure of WordPress, but basicly you would have to get the ID of the current post and pass that along as a WHERE parameter.
I assume comment_post_ID keeps track of the ID of the post the comment was added to? Ifso:
$id = mysql_escape_string($_GET["id"]); // get id of post somewhere
  $sql = "
   SELECT DISTINCT comment_post_ID, comment_author, comment_date_gmt, comment_approved, SUBSTRING(comment_content,1,100) AS com_excerpt
   FROM $wpdb->comments
   WHERE comment_approved = '1' AND comment_post_ID = {$id}
   ORDER BY comment_date_gmt DESC
   LIMIT 5";

That would show the 5 most recent comments to the post of which you pass along the id


text:
Q: Creating a TreeGraph? I am in the process of trying to design a graph.  I am not sure the correct term for this type of graph.  It is similar to a tree view but instead is nested within the graph.
It looks something like this.

Where each color is a different hierarchy  and the next level breaks down from that.
The information will be dynamically loaded from the server which runs a stored procedure that is used for a tree view currently.
Does anyone know a good way to create this or maybe a open graph plugin for this?  jQuery, asp.net, c# all work for me.


text: Q: Counting Process Conditioned on Random Rate Having some trouble figuring out this problem. Say you have a counting process $N_t$ where the rate is a random variable $\Lambda$ which is exponentially distributed with rate $\alpha$. I'm trying to find the unconditional PMF of $N_t$, as well as the conditional expectation of $\Lambda$ given $N_t$ and the first $n$ arrival times (i.e. $E(\Lambda | N_t = n, S_1 = s_1, ... , S_n = s_n)$). I'm hoping this would maybe be easier to figure out once I'm able to figure out the unconditional PMF of $N_t$. Any help is appreciated!


text:
Q: selecting one specific children i'm hovering i'm trying to select the  element i'm hovering inside a table, in order to change its properties. I was trying with the children method, like this:

and the script is:
function() {
$('.tablemain').children(this).hover(function(){
$(this).addClass('selected');
});
};

A: A few issues.

*

*hover takes two functions to be of any practical use. One to call when entering, one when leaving the element. A single function only gets called on entry.

*The children of a table are thead and tbody, even if not in the original HTML. There are added by the browser when it completes the DOM. I assumed you wanted to target the TDs? The new selector chooses any TDs under the class="tablemain" element.

*I have it removing the selected class when you exit the item (delete the second function if you did not want that)

*You had your code wrapped in an anonymous function that was never called. I replaced that with a shortcut DOM ready handler ($(function(){YOUR CODE}); is short for $(document).ready(function(){YOUR CODE});)

JSFiddle: http://jsfiddle.net/TrueBlueAussie/ynhujf6v/1/
$(function () {
    $('.tablemain td').hover(function () {
        $(this).addClass('selected');
    }, function () {
        $(this).removeClass('selected');
    });
});


text:
Q: Adding additional time to main timer from movieclip? Hi so yeah in the main timeline I have the timer
 var count:Number = 300;//Count down from 300
 var myTimer:Timer = new Timer(1000,count);
myTimer.addEventListener(TimerEvent.TIMER, sayHello);
function sayHello(e:TimerEvent):void
{
trace("Current Count: " + myTimer.currentCount);
}

And when you go into the movieclip reimoi_mcand click the useplush button I want to be able to add additional seconds onto the timer. The following is the code in the reimoi_mc clip but yeah I really have no idea how to make this work, please help ;0; (I have to use MovieClip(root) to access the running timer from the main timeline within the movieclip)
import flash.events.MouseEvent;
import flash.utils.Timer;
import flash.utils.getTimer;

stop();
useplush.addEventListener(MouseEvent.CLICK, addtime);
function addtime(e:MouseEvent):void
{
            MovieClip(root).count += 2;
            MovieClip(root).myTimer.repeatCount += MovieClip(root).count; //add time to the timer

            trace("new time " + myTimer.currentCount);
}

A: You'd better use an external counter to count the time, instead of stuffing it into a Timer object. You would then need timers to measure delays, and listeners to count them.
var myTimer:Timer=new Timer(1000); // no second parameter
public var secondsLeft:int=300; // former "count"
myTimer.addEventListener(TimerEvent.TIMER, sayHello);
function sayHello(e:TimerEvent):void {
    secondsLeft--;
    trace("Seconds left:", secondsLeft);
    if (secondsLeft<=0) {
        myTimer.stop();
        myTimer.reset();
        // whatever else to trigger when time runs out
    }
}

And then you just add to secondsLeft and update the scoreboard.

A: I think what you are trying to do is add 2 seconds to the timer in the click handler, and then show how much time is left?    If so, just a couple tweaks will do:
function sayHello(e:TimerEvent):void {
    trace("Time Left: " + myTimer.repeatCount - myTimer.currentCount);  //time left is the repeat count - the current count
}

function addtime(e:MouseEvent):void {
    MovieClip(root).myTimer.repeatCount += 2 //add 2 more ticks to the timer (currentCount will always remain the same unless the timer is reset)
    trace("new time remaining: " + MovieClip(root).myTimer.repeatCount - MovieClip(root).myTimer.currentCount);
}

BONUS CODE!
If you wanted to make it agnostic of the timer delay (let's say you want it to update quicker than 1 second for instance), you could do this:
var startingTime:Number = 20; //the initial time in seconds
var myTimer:Timer = new Timer(200); //your timer and how often to have it tick (let's say 5 times a second)

myTimer.repeatCount = startingTime * Math.ceil(1000 / myTimer.delay); //set the initial repeat count
myTimer.addEventListener(TimerEvent.TIMER, sayHello);
myTimer.start();

function sayHello(e:Event):void {
     trace("Time Left: " + ((((myTimer.repeatCount - myTimer.currentCount) * myTimer.delay) / 1000)) + "seconds");
}

And in your other object:
stage.addEventListener(MouseEvent.CLICK, function(e:Event){
    myTimer.repeatCount += Math.ceil(2000 / myTimer.delay); //add 2000 milliseconds to the timer
});


text:
Q: Will large inserts crash a 3-node MySQL database cluster? We have a 3 node MySQL database cluster than runs on Percona. I have a stored procedure that inserts a lot of rows in one hit, potentially over a million rows.
I've been warned (by our DBA) this might cause the cluster to crash, but I can't find anything online regarding this or that would suggest this might happen.
Can anyone provide some insight?

A: Some general considerations, first:

*

*MySQL, and I am talking about InnoDB specifically, is optimized for OLTP loads, specially for good performance for point SELECTS and writes. That doesn't mean that you cannot do bulk inserts (I get 600 000 row insertions/second on my desktop-grade SSD), but that has an impact on the performance of other operations, mainly by taking extra locks and extra resources on transaction procesing/index merging/etc.

*Large transaction processing overhead exacerbates when distributing those over the network on a tight clustering solution (for a MySQL model). The fact that you have to load synchronously a large number of rows over several nodes usually requires a large amount of memory and makes them a problem for tightly-attached-node solutions such as NDB and Galera.
Now into Galera specifics:

*

*The first limitation that you will face is that by default, ws_max_size_rows is 128K (128 000 rows) and wsrep_max_ws_size is 1GB. Although those values are configurable, the load process will directly fail if the transactions are larger than the values configured.

*I wouldn't be surprised that the cluster could crash - You can see an example here that happened during an import- ending up with 2 nodes getting an OOM even if that specific problem was later fixed. Extra memory is needed in order to certify every transaction among all nodes before actually executing it.

*If you want the cluster to work adequately, I would recommend loading the files in chunks, using several transactions. There are event tools like [pt-fifo-split][1] that will help you do that. As an alternative, you could load those files individually on each node one at a time while they are temporally desynced.

This is one question that should not be argued about- If you have a production cluster, you should have a test cluster in which you can try your thesis first. Best case scenario, you will get a horrible performance/a deadlock. Normally, you will run out of memory and 1+ nodes will crash, leading to a full cluster crash.
To know more about the reasons behind galera behavior, and how to avoid downtime at the cost of sacrificing performance, you should read:

*

*Galera flow control in Percona XtraDB Cluster for MySQL

*Galera: Excessive memory use on sizable transactions

*http://www.percona.com/forums/questions-discussions/percona-xtradb-cluster/10106-xtradb-limitations-wsrep-max-ws-size-and-wsrep-max-ws-rows


text:
Q: Serious, intermittent errors with CF Web Service We've got an incredibly frustrating situation with a CF Web Services-based API that we wrote and maintain. We had an API in place for years that was stable and working happily with Ruby, PHP, and ColdFusion clients. Then this year a .NET client came along, and we found that our web service was not interoperable with statically-typed languages due to our extensive use of structs.
We eventually realized we had to re-write the API without structs, and we've done so. It now uses scaler values, arrays, and CFCs (which get translated to SOAP complexTypes). The .NET client is happy, and we wrote proof-of-concept clients in about 6 different languages to ensure that we'd be interoperable this time around.
To our great dismay, it appears that our ColdFusion 7 servers can't serve the new API reliably. It works for about a day or so after restarting, then the clients start getting errors like:
Error: coldfusion.xml.rpc.CFCInvocationException
[java.lang.ClassNotFoundException : tafkan.remote_api.pfapi.v.trunk.rsp_pf_survey_status_array]
and
java.lang.NoClassDefFoundError: tafkan/remote_api/pfapi/v/trunk/pf_unit
Restarting the CF instances is the only way to make the problem go away. A lot of time and money was put into rebuilding the API, so everyone is really at wit's end about this.
We've noticed that the WEB-INF/cfc-skeletons directories of our CF instances eventually seem to have two copies of the classes for each of the CFCs used by the API. For example:
-rw-r--r--  Feb 17 09:15 remote_api.pfapi.v.trunk.pf_datum.class
-rw-r--r--  Feb  3 12:20 tafkan.remote_api.pfapi.v.trunk.pf_datum.class

It seems like the errors are coming from a namespace or class search path problem, so we tried switching all CFC references to be fully-qualified (dot notation starting with a mapping) instead of just simple references to CFCs in the current directory. This seemed promising, but the problem came back within 24 hours.
Environment:

*

*ColdFusion 7,0,2,142559 with hf702-70523, 2-instance cluster

*Sun Java 1.4.2_13

*Apache 2.0.52

*Centos 4.5 32-bit

Maybe upgrading one of these venerable pieces of software would help? Maybe upgrading just AXIS?
Adobe support doesn't seem to be an option, as CF7 is EOL'ed and in extended-extended support (and that just for a few more days).
Update:
Thanks to all who've joined this discussion! Here's an update on where things stand at the moment.
The service just crapped out for the first time today. One of the cluster instances was still able to generate the WSDL, while the other instance said:
AXIS error
Sorry, something seems to have gone wrong... here are the details:
Exception - java.lang.NoClassDefFoundError: tafkan/remote_api/pfapi/v/trunk/rsp_pf_numeric_array

Both cfc-skeletons directories contain a file called tafkan.remote_api.pfapi.v.trunk.rsp_pf_numeric_array.class, and did not appear to contain the otherly-named files we've sometimes seen (remote_api.pfapi.v.trunk.rsp_pf_numeric_array.class). The files in cfc-skeletons do not appear to have been modified since the servers were started yesterday.
The uptime on both instances was about 21.5 hours. I was running without JIT (-Xint).
I've now restarted both instances. They're now running on Sun Java 1.4.2_19 (instead of _13), and JIT has been re-enabled as it clearly wasn't causing this error and was things were dramatically slower without it. I've also cleared the "save class files" check boxes.
And now, we wait again...
Update 2
The problem persists. I'm not sure what else to try at this point. Arg!
FYI, this is cross-posted at http://www.houseoffusion.com/groups/cf-talk/thread.cfm/threadid:60922

A: I've read this thread, and the CFTalk thread.  My initial thoughts about workarounds appear to have been already suggested by Mark Kruger and Dave Watts.  The only other workaround idea I had was to catch the error and refresh the webservice stub using the Service Factory methods.  (In CF8-9 there is a Admin API method to do this, not sure about CF7).
Researching the error I narrowed down possible matches to these:
http://www.houseoffusion.com/groups/cf-talk/message.cfm/messageid:144821
This was a match but unresolved
http://blog.coldfusionpowered.com/?p=28
This was a very similar error, resolved by "fixing case issues" on all CFCs & invocations.
ColdFusion Google Adwords Business Component Error
Resolved by rewriting code and removing cfcomments (I suspect that other factors were actually responsible for solving it here)
http://forums.crystaltech.com/index.php?topic=22364.0
We're getting closer now.  Resolution involved mistakenly having two document roots
http://qaix.com/coldfusion/313-410-web-service-on-cfmx-6-1-jrun-suddenly-not-working-read.shtml
Exact match for error message.  Exact match for having CFC mapping to doc root.  Resolution was to have only 1 mapping pointing to docroot, just "/".  This could be the solution.  In MX 6/6.1 and maybe 7, there was a default mapping for "/" pointing to docroot.  If you have another mapping pointing to docroot, then I can see how this problem might arise.  Check the physical paths for mappings and try the solution here, to use only the "/" mapping.

A: How are the external clients interacting with your webservice? Just via the WSDL I presume?
Is it possible that some client app, a unit test... something, anything ... has a wrong URL... has a URL to your WSDL file with the "tafkan" in it?
If I were working on it, probably the first avenue I'd look down would be figuring out what could possibly result in that problem. Is "tafkan" a valid directory in your system? Where do the .cfc files actually live on the file system, what if any mappings are there to these paths in CF Admin, and what are the URLs that people are using to access your webservice?
The key here, I believe, is getting inside CF's head and asking it "why would you generate, and be looking for, a class with "tafkan" as a package?