text:
Q: Ajax encoding parameters before send? I have this ajax call
$.cordys.ajax({
        url   : "xxx"
        method: "xxx",
        namespace: "xxx",
        parameters: {
            Lines : {
                "@xmlns" : "http://www.exemple.com",
                Line : TFLines
            }
        },
        success: function(data) {
            console.log(data);
        }

    }).fail(function(error) {
        alert(error);
    });

I would like to send an object Lines which is a collection of Line, the object TFLine is an array and looks like this:
[{
  @xmlns: "http://exemple.com",
  Code: "DENOLEGAL",
  Comments: "",
  Content: "<![CDATA[test]]>",
  DisplayedLanguageId: "1",
  DisplayedLanguageName: "FR",
  IsMandatory: "1",
  Label: "Dénomination légale de vente"
}, {...}
]

My problem is with the field Content where I have special characteres.
This data have to be sent in Json Format but in the target application it will be convert into XML (this is why i need to enclose my data with CDATA tag)
Juste before the ajax call my dataset looks exactly like this but when I look into the console the request payload, the field Content has been encoded like that:
<![CDATA[<strong>test</strong>]]>

I thought the ajax library did that, actually not, i put breakpoint everywhere the library use encodeURIComponent(), anyone stopped
Do you have an idea why this happen ??

A: The payload was HTML encoded (not URL encoded). So, you could find out if some part of the code is Html-encoding the payload data
The payload should be encoded as
%3C!%5BCDATA%5B%3Cstrong%5Btest%3C%2Fstrong%5B%5D%5D%5B


text:
Q: How to do Creation Updation and Deletion of Data from IList for Kendo Grid? this is my kendogrid code :

KendoDemosFactory.controller("MyCtrl", function ($scope, $sessionStorage) {
        $scope.mainGridOptions = {
            dataSource: {
                transport: {
                    read: {url:"/User/GetUserDetail",datatype:"json"},
                    update: { url: "/User/UpdateUser", type: "POST" },
                    destroy:{ url:"/User/DeleteUser",type:"POST"},
                    Create:{url:"/User/CreateUser",type:"POST"}
                },
                parameterMap: function(options, operation) {
                    if (operation !== "read" && options.models) {
                        return {models: kendo.stringify(options.models)};
                    }
                },

                batch: true,
                pageSize: 5,
                serverPaging: false,
                serverSorting: false
            },
            sortable: true,
            pageable: true,
            navigatable: true,
            toolbar: ["create", "save", "cancel"],
            dataBound: function () {
                this.expandRow(this.tbody.find("tr.k-master-row").first());
            },
            columns: [{
                field: "FirstName",
                title: "First Name",
                width: "80px"
            }, {
                field: "LastName",
                title: "Last Name",
                width: "80px"
            }, {
                field: "Address",
                width: "80px"
            }, {
                field: "Email",
                width: "100px"
            }, {
                field: "Gender",
                width: "80px"
            },
            {
                field: "Salary",
                width:"100px"
            },
            { command: "destroy", title: " ", width: 100 }
            ],
            editable:true
        };
    })

and here is my controller with my userlist and all the methods :

  public ActionResult GetUserDetail()
        {
            IList<UserModel> userList = new List<UserModel>()
            {
            new UserModel{
                id=1,
                FirstName = "Pawan",
                LastName = "Kapoor",
                Address = "Mohali",
                Email = "test@test.com",
                Gender = "Male",
                Salary = 25000
            },

          new UserModel
            {
                id=2,
                FirstName = "Ayan",
                LastName = "Banerjee",
                Address = "Bangalore",
                Email = "test1@test.com",
                Gender = "Male",
                Salary = 30000
            },
}
}

[HttpPost]
        public ActionResult CreateUser()
        {
            IList<UserModel> userList = new List<UserModel>();
            return Json(userList, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public ActionResult UpdateUser()
        {
            IList<UserModel> userList = new List<UserModel>();
            return Json(userList, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public ActionResult DeleteUser()
        {
            IList<UserModel> userList = new List<UserModel>();
            return Json(userList, JsonRequestBehavior.AllowGet);
        }

My kendo Grid is populating fine with editable functionality and all the CRUD controls but i am not able to bind data with the controller using CRUD Methods(they are not getting hit and any crud functionality is not getting persisted). Please help

A: Let me give you a few notes to correct your your code.

*

*If you do not want to make batch update, send to controller only the current row.
parameterMap: function (options, operation) {
    if (operation !== "read" && options.models) {
         return { models: options.models[0] };
    }
}

*Correct your update action method as follows: MVC will bind the data send from grid into UserModel.
[HttpPost]
public ActionResult UpdateUser(UserModel model)
{
    // do something with model
    return Json(model, JsonRequestBehavior.AllowGet);
}

This link will lead you to solve your problem

redpajama_set_name: RedPajamaStackExchange


text:
Q: drop down with onfocus needs double click to show menu On my page using Internet explorer I have a drop down but on the first load of the page because it has a onFocus on it, it needs a double click to show menu. How do I avoid the double click.
The onFocus must still fire but the menu must show at the same time?
how do I do this because the double click is irritating?
Here is a simple example
http://jsfiddle.net/tgH7b/3/
here is the code
    <select name="cars" >
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="fiat" selected="selected">Fiat</option>
<option value="audi">Audi</option>
</select>

<select name="cars" onFocus="this.style.background = '#999';$(this).click();">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="fiat" selected="selected">Fiat</option>
<option value="audi">Audi</option>
</select>

A: The only solution i can think of is to use focusin() callback function instead:
NOTE: focusin() supports event bubbling
http://jsfiddle.net/2AUs6/
<select name="cars" >
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="fiat" selected="selected">Fiat</option>
<option value="audi">Audi</option>
</select>

<!-- this one -->
<select name="cars">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="fiat" selected="selected">Fiat</option>
<option value="audi">Audi</option>
</select>

$('select[name=cars]:eq(1)').focusin(function(){
    $(this).css('background','#999')
})

A: Here is a possible solution from code project
http://www.codeproject.com/Questions/89610/ASP-NET-how-to-create-a-dropdownlist-that-onfocus


text:
Q: IIS ASP.Net windows authentication doesn't work I have an intranet web application.
Even though I've set "Windows Authentication = Enabled" (and all other Authentications are disabled), when the application tries to access resources, it is treated as though it is run by the same user that runs the Application Pool's process.
Is there a problem here, or do I not understand correctly how Windows Authentication works?
If I did get it wrong, is there another way to make the application run as the client user?

A: Remote resources?  If using Kerberos, there are a few caveats to get that working correctly.  For an IIS computer to impersonate a user when accessing remote resources, it needs to generate a delegation-level token for the user.
If the application pool is running under a custom identity (it usually is in these scenarios), the account needs to have the ability perform unconstrained delegation.  On the account Delegation tab in Active Directory Users and Computers, select "Trust this user for delegation to any service (Kerberos only)".
If you don't see the Delegation tab, it means an SPN has not been assigned to the account.  That needs to be corrected first using the setspn.exe command.
The IIS identity account needs to have the "Act as part of the operating system" privilege (SetTCB privilege) on the IIS server(s).
Download the Delegation Configuration tool and add that as an application on the web site.  It lets you browse to the application url and generate a report that determines if delegation is configured correctly.
It's also very easy for the code to check the token type to determine if it is a delegation token or not, and log that information to a file.
Summary (Kerberos Protocol Transition and Constrained Delegation)
http://technet.microsoft.com/en-us/library/cc772683%28v=ws.10%29.aspx
How To: Use Impersonation and Delegation in ASP.NET 2.0
http://msdn.microsoft.com/en-us/library/ff647404.aspx
DelegConfig download
https://www.iis.net/community/default.aspx?tabid=34&g=6&i=1887
http://channel9.msdn.com/posts/Troubleshooting-Kerberos-Delegation-Using-DelegConfig

A: You have to add impersonation to your web.config:

<identity impersonate="true" />

http://support.microsoft.com/kb/306158


text:
Q: Xamarin forms content view does not showing when I click once but need to click twice I trying to display a content page in content view.
My problem is :
when I tap on the StackLayout "Ontest" the content view is  blank.
If I want to see it I need to tap a second time
My question :
Is there a way to refresh a content view ?
using "Device.BeginInvokeOnMainThread Does not work   :
  Device.BeginInvokeOnMainThread(async () => {
            });

Here is the code :
public void OnTest(object sender, EventArgs e)
        {

             LoadtestPage();
        }

        public   void  LoadtestPage()
        {

            Device.BeginInvokeOnMainThread(async () =>
            {

                HomeView.IsVisible = false;
                TestView.IsVisible = true;
                TestView.Content = new TestWordsPage().Content;
            });

        }

            public void OnMyWords(object sender, EventArgs e)
        {

            Device.BeginInvokeOnMainThread(async () => {

           TestView.IsVisible = false;
           HomeView.IsVisible = true;

            });
        }


text:
Q: SqlAlchemy delete() function doesn't work I have a code :
engine = create_engine('mysql+pymysql://root:password@localhost/DBName')
Session = sessionmaker(bind=engine)
session = Session()
session.query(Theatre).filter(Theatre.id == 1).delete(synchronize_session = False)
session.expire_All()

After execution of the code, it returns 0 and there is no effect on the database. The row doesn't get deleted. Tried testing through command prompt.
Meanwhile a simple select query run fines
session.query(Theatre).all()

A: The function is
session.expire_all()

all() with lower case a. See the docs

A: Maybe you're missing a commit?
session.commit()


text:
Q: How dataproc works with google cloud storage? I am searching for working of google dataproc with GCS. I am using pyspark of dataproc. Data is read from and written to GCS.But unable to figure out best machine types for my use case. Questions
1) Does spark on dataproc copies data to local disk? e.g. If I am processing 2 TB of data, is it ok If I use 4 machine node with 200GB hdd? OR I should at least provide disk that can hold input data?
2) If the local disk is not at all used then is it ok to use high memory low disk instances?
3) If local disk is used then which instance type is good for processing 2 TB of data with minimum possible number of nodes? I mean is good to use SSD ?
Thanks
Manish

A: Spark will read data directly into memory and/or disk depending on if you use RDD or DataFrame. You should have at least enough disk to hold all data. If you are performing joins, then amount of disk necessary grows to handle shuffle spill.
This equation changes if you discard significant amount of data through filtering.
Whether you use pd-standard, pd-ssd, or local-ssd comes down to cost and if your application is CPU or IO bound.
Disk IOPS is proportional to disk size, so very small disks are inadvisable. Keep in mind that disk (relative to CPU) is cheap.
Same advice goes for network IO: more CPUs = more bandwidth.
Finally, default Dataproc settings are a reasonable place to start experimenting and tweaking your settings.
Source: https://cloud.google.com/compute/docs/disks/performance


text:
Q: Laravel 5 localization based on sub domain How can I have localization based on the subdomain?
www.example.com ==> locale = default local  = en
ar.example.com ==> local  = ar
After researching online, I am not sure if it should be a middleware or in the routes file.

A: I think you can do something like:
Route::group(['domain' => '{lang}.myapp.com'], function()
{

    Route::get('/', function($lang)
    {
        App::setLocale($lang);
    });

});

Or use the App::setLocale in your controller.
The group allows you to use a wildcard, ar.example.com en.example.com or it.example.com all will be catch by the group. Inside de group you can define all the routes you need and pass the $lang
Maybe you can add a middleware to limit the language, maybe a middleware that check if the language exists.


text:
Q: Cron job in my ubuntu server does not start In my project i have to schedule a job on my subuntu server;
i try using Cron like this:
$ sudo nano /etc/crontab

and then , at the end of the file, append my command:
00 5    * * *   ubuntu  /usr/bin/python /var/www/web/core/frontend/allschemas.py

for start my python file call every day at 5 pm.
If i try to manual launche from server command, al was done, but my cron job never start, and never log error or warning.
Someone has idea about this issue?
So many thanks in advance

A: Cron will run after re-editing your commands.
00 5    * * *   ubuntu cd /var/www/web/core/frontend && /usr/bin/python allschemas.py

You can also use per user cront:located in
/var/spool/cron/crontabs/<username>

Example:
echo "00 5 * * * cd /var/www/web/core/frontend && /usr/bin/python allschemas.py" >> /var/spool/cron/crontabs/root #or /var/spool/cron/crontabs/<username>

A: Your record in cron should look like:
0 5 * * *  /usr/bin/python /var/www/web/core/frontend/allschemas.py

If you want to start the job at 5 a clock in the morning, if its 5 a clock after noon record become
0 17 * * *  /usr/bin/python /var/www/web/core/frontend/allschemas.py

Also be aware that if python depend of some environment variables the job will fail. Better create shell script which will execute the job and add before execution line like this:
. /home/username/.bash_profile


text:
Q: Event Log Security Exception After Installing Visual Studio 2015 Community So I just installed VS 2015 Community SxS with an existing VS 2013 Professional. Everything appeared to install correctly, however after the installation, when attempting to navigate to a locally hosted ASP.NET application on IIS, I get some sort of security exception related to the event logs:

I've found that if I manually remove the .NET Framework 4.6, the issue goes away (although then I can't use VS 2015.)
I guess I'm just looking for tips on how exactly to troubleshoot this further. I've scanned through the Event Log browser (ironically enough) looking for anything that might help pin the problem down, but can't find anything. I'm at a loss as to what else I can try.

A: You can check if your application pool identity used by your application has read/write permission to the following registry Keys,
HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\EventLog
HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\EventLog\Security
You can see what's the difference (different identity or different permissions required by the keys) after you got 4.6 installed.
Besides, the first answer in this link might be helpful https://social.msdn.microsoft.com/Forums/windowsdesktop/en-US/00a043ae-9ea1-4a55-8b7c-d088a4b08f09/how-do-i-create-an-event-log-source-under-vista?forum=windowsgeneraldevelopmentissues.

A: So it turns out that a particular HTTP module is somehow the culprit. It directly relates to another question I had posted (at the time I thought they were separate things):
There is no EventLog source named 'ASP.NET 4.6.81.0'. This module requires .NET Framework 2.0
By commenting out the UnhandledExceptionModule through the web.config:
<httpModules>
<add type="WebMonitor.UnhandledExceptionModule" name="UnhandledExceptionModule"/>

</httpModules>
I've got things working. I'm still not satisfied however and will need to spend more time digging in and determining where the incompatibility lies.


text:
Q: Como ordenar um ArrayList em ordem crescente pela data Eu preciso ordenar um ArrayList em ordem crescente pela data. Pois eu vou adicionando valores fora de ordem nele. No meu ArrayList tem apenas dois campos em cada elemento: data e valor. Alguém sabe de algum método que eu posso usar?

A: Pode usar o método sort da classe Collections. O exemplo abaixo foi adaptado desta resposta do SOEn:
Collections.sort(suaLista, new Comparator<SeuObjeto>() {
  public int compare(SeuObjeto o1, SeuObjeto o2) {
      if (o1.getDate() == null || o2.getDate() == null)
        return 0;
      return o1.getDate().compareTo(o2.getDate());
  }
});


text:
Q: Unable to block port 25 on server When I scan my server using nmap $ sudo nmap -sS IP.ADDR.OF.SRVR, I see a line with 25/tcp    open  smtp. This is despite the fact that I'm not running postfix, exim or any other kind of mail server on the machine.
I have also tried to block port 25, using IP table rules.
$ sudo iptables -A INPUT -p tcp --destination-port 25 -j DROP
But despite running this and verifying that the iptable rule exists with $ sudo iptables -L -n -v running nmap still shows the port as being open.
I have also run $ netstat -tulnp on the server to see what ports are open, and port 25 does not show up in the list there.
Very confused on how to proceed, any help or pointers would be much appreciated.
Output of sudo iptables -nvL - https://pastebin.com/5W9V2rrz
Output of sudo iptables -t nat -nvL - https://pastebin.com/v9ST06uz

A: It may be the the ordering of your rule is incorrect. Try and move the rule further up, also what version of Linux are you running? If in Ubuntu try #> lsof -i -n -P | grep :25 and see what program is being used to listen on that port and then change/stop that process


text:
Q: how to plot learning rate vs accuracy sklearn? I am using the sklearn.neural_network MLPClassifier, want to plot the learning rate(0.0001:10) with accuracy. I have getten the data code as follows.
from sklearn.neural_network import MLPClassifier
import numpy as np

X_train = Input_Data['Train_Input']
X_test = Input_Data['Test_Input']
Y_train = Input_Data['Train_Target']
Y_test = Input_Data['Test_Target']
Y_train = Y_train.astype('int')
Y_test = Y_test.astype('int')

classifier = svm.SVC(kernel='linear', C=0.01)
Y_pred = classifier.fit(X_train, Y_train).predict(X_test)

for lr in np.r_[0.001:10:0.002]:
    mlp = MLPClassifier(hidden_layer_sizes=(8, 8), max_iter=10, alpha=1e-4,
            solver='sgd', verbose=10, tol=1e-4, random_state=1,
            learning_rate=lr)

    print(mlp.fit(X_train, Y_train))
    Acc = accuracy_score(Y_test, Y_pred)
    plt(learning_rate, Acc)

with error as follows:
ValueError: learning rate 0.001 is not supported.

A: Do you need to run the MLPClassifier with every learning rate from 0.0001 to 10? If so, then you'd have to run the classifier in a loop, changing the learning rate each time. You'd also have to define the step size between 0.001 to 10 if you need the learning rate at certain intervals - say 0.0001, 0.0005, 0.0010, ....10.
Say you have a list of learning rates at these intervals,
learning_rates = [0.001, 0.005, ..., 10]

for lr in learning_rates:
    mlp = MLPClassifier(hidden_layer_sizes=(8, 8), max_iter=10, alpha=1e-4,
                solver='sgd', verbose=10, tol=1e-4, random_state=1,
                learning_rate=lr)

    print(mlp.fit(X_train, Y_train))
    print("Training set score: %f" % mlp.score(X_train, Y_train))
    print("Test set score: %f" % mlp.score(X_test, Y_test))

You can now collect mlp.score for train and test sets into separate lists and plot them against the learning rate in matplotlib.
Hope this helps!
I think your confusion is about the max_iter parameter which relates to the algorithm and not the upper bound for the learning rate.


text:
Q: ngx-datatable - Any way to preserve column order after a user repositions them? Users like the out of the box ability to drag columns around to reorder them in the ngx-datatable. However, they want me to preserve the order after they get them exactly like they like them. I understand how to define the columns in the TS file. But I'm not sure how to capture the changes to the columns when the user drags them around in the UI. Is this possible?
To be clear, if my original column structure is [A, B, C] and the user manually drags column B to the left and now the order is [B, A, C], how to I get notified in code that the reorder happened so I can save the new order of [B, A, C] somewhere?

A: They have an event emitter notifying when a column has been reordered https://github.com/swimlane/ngx-datatable/blob/master/projects/swimlane/ngx-datatable/src/lib/components/datatable.component.ts
@Output() reorder: EventEmitter<any> = new EventEmitter();

Docs: https://swimlane.gitbook.io/ngx-datatable/api/table/outputs#reorder


text:
Q: Getting a window's PID by clicking on it Is there any package which shows PID of a window by clicking on it?

A: Yes. Try xprop and you are looking for the value of _NET_WM_PID:
xprop _NET_WM_PID | cut -d' ' -f3
{click on window}

A: xprop will return a window's PID.
You can filter the verbose output using awk:
xprop | awk '/PID/ {print $3}'

A: To complete those excellent answers, here is a little bash command to get the command (that I actually needed):
id=`xprop _NET_WM_PID | awk '/PID/ {print $3}'`; cat /proc/$id/comm

Example:
Lila ~ # id=`xprop _NET_WM_PID | awk '/PID/ {print $3}'`; cat /proc/$id/comm

gnome-terminal-


text:
Q: Why my double is shown as scientific? How can I add a scientific and a float number  ? I have something like
 var1 0.99999899 var2  3.5008552e-05 sum  3.5008552e-05

but what I dont understand is why in the first place var2 is shown as scientific while in the first place I declared
double var1, var2;

so, actually their sum is just var2...
thanks
a

A: The way a floating-point value is displayed is down to the mechanism by which you display it. It is not a property of the value itself, nor is it in any way stored within the variable:

A number is a number is a number. What you call "scientific" is not a class of numbers. It's a class of representations of numbers. The same way that "twelve" and "12" and "XII" and "a dozen" and "IIIIIIIIIIII" all represent the same number. This "scientific" thing only exists when you decide to represent the number in some specific way (i.e. when you output it). Calculations don't "turn numbers into scientific" the same way that saying that "2 * 6 is twelve" doesn't turn numbers into English words. The variables always store the numbers not the representations. — R. Martinho Fernandes

Your display mechanism — std::cout? — is choosing the best way to output the value. You can override this with IO manipulators such as std::fixed, though it's pretty fiddly sometimes to get it just how you want it, due to library limitations.

A: If you have <stdio.h> available then you may use int printf ( const char * format, ... ); the format specifier would look something like this: printf("%.5f", your_double) where 5 is the number of digits you want after the decimal point, the default is 6.
(printf docs)


text:
Q: How can I access my desktop from root shell prompt in recovery menu? I updated graphics drivers today, which unfortunately causes a black screen at login. I want to access my desktop so I can copy certain files off the laptop while I figure out a fix, but I'm unable to open a terminal at login using Ctrl+Alt+F1.
Booting in recovery mode, I can select the "root"  option to drop to a root shell prompt. From here, I can login to my user account through:
su --login myuser
...where I get a message that says "No directory,  logging in with HOME=/". However, I cannot change directories to my Desktop, which should be located at /home/myuser/Desktop/. I can cd into the home directory, but it appears like there's nothing in it. Any thoughts on how to access my Desktop through the root shell?

A: As I know, when you boot into recovery mode, the home partition will not mount automatically.
First locate your home partition using commands like: lsblk or fdisk -l or even by having a look at /etc/fstab:
# grep '/home' /etc/fstab | grep ext

Then mount that partition at /home (in my case sda2 is my home partition).
# mount /dev/sda2 /home

And copy your file to your desired path, device.
Remember that you may need to remount or mount your partitions with rw option.


text:
Q: 4 NSarray's in to pickerview how can i get 4 nsarrays into  1 pickerviewer
each array has 4 names in them.
so let say i have this:
Array1: Alex

*

*Tel nr:xxxxxxxxxx

*Tel nr:xxxxxxxxxx

*Tel nr:xxxxxxxxxx

*Tel nr:xxxxxxxxxx

Array2: Andrew

*

*Tel nr:xxxxxxxxxx

*Tel nr:xxxxxxxxxx

*Tel nr:xxxxxxxxxx

*Tel nr:xxxxxxxxxx

Array3: Sam

*

*Tel nr:xxxxxxxxxx

*Tel nr:xxxxxxxxxx

*Tel nr:xxxxxxxxxx

*Tel nr:xxxxxxxxxx

Array4: Rick

*

*Tel nr:xxxxxxxxxx

*Tel nr:xxxxxxxxxx

*Tel nr:xxxxxxxxxx

*Tel nr:xxxxxxxxxx

and now when i pull down the pickerviewer i want to see only the names alex, andrew, sam and rick in that pickerviewer.
and when i select a name (alex) i want to have 4 buttons that are changed in to the value of the numbers so when you tap the button you can call them.
can someone help me with this issue.
i am a bit brain frozen at this moment:S

A: Add them to a dictionary :
self.dict = [[NSMutableDictionary alloc] init]; //Obviously create a property first:

[dict setObject:array1 forKey:@"Alex"];
//etc .....

Then your picker delegates would look like:
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    return [self.dict allKeys] count];
}

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    return 1;
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
    return [self.dict allKeys][row];
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {

    NSString *person = [dict allKeys][row];
    NSArray *personDetails = [dict objectForKey:person];
}

A: are you sure you want to use UIPickerView ? If you aren't using more then 1 component then you can use UITableView. Each cell will contain only the name as you want (with method cellForRow:), and when you'll select it (didSelectRow:) it will show the former 4 buttons of that cell, which were hidden by now. when you type on another cell, the former one come back to its default state (the buttons are hidden), and of course if you tap one of the unhidden buttons you dial to the wanted number.
Making sense ?

A: Form what I can understand is you need to have an array with dictionaries
NSMutableArray *superArray = [NSMutableArray array]; //superArray should be declared in the interface

NSArray *setNames = [NSArray arrayWithObjects:@"Alex",@"Andrew",@"Sam",Rick,nil];

NSArray *alexArray = [NSArray arrayWithObjects:@"Tel nr:xxxxxxxxxx",@"Tel nr:xxxxxxxxxx",nil];
NSArray *andrewArray = [NSArray arrayWithObjects:@"Tel nr:xxxxxxxxxx",@"Tel nr:xxxxxxxxxx",nil];
NSArray *samArray = [NSArray arrayWithObjects:@"Tel nr:xxxxxxxxxx",@"Tel nr:xxxxxxxxxx",nil];
NSArray *rickArray = [NSArray arrayWithObjects:@"Tel nr:xxxxxxxxxx",@"Tel nr:xxxxxxxxxx",nil];

NSArray *totalArray = [NSArray arrayWithObjects:alexArray,andrewArray,samArray,rickArray,nil];

for (int i=0 ; i < [setNames count] ; i++){
NSDictionary *dictionary = [NSDictionary dictionaryWithObjectAndKeys:[setNames objectAtIndex:i],@"setName",[totalArray objectAtIndex:i],@"telephoneArray" ,nil];

[superArray addObject:dictionary];

}

Now you have all data stored in the way you would need it
for pickerView delegates
set numberOfRowsInCOmponent to be [superArray count];
titleForRowInComponent to be [superArray objectAtIndex:row]valueForKey:@"setName"];
Further on selecting any particular name from pickerView
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
// get the array of the selected setName
//Eg: After selecting Sam in pickerView

NSArray *selectedNamesTelephoneArray = [superArray objectAtIndex:row]valueForKey:@"telephoneArray"];

NSLog(@"the selected ones telephone numbers are %@",selectedNamesTelephoneArray);
}


text:
Q: zlib compiling on windows 7 (x64) I had compiled zlib on my comp to compile libxml (for collada dom).
But I don't know which directories are supposed to be /lib and /include at compiling libxml.
Sorry for my English and my noobinity :) Thx for the answers and the worthy time You have spent on answering me.

A: Whichever folder the zlib header files are in is the folder to add into the list of include paths when compiling libxml. Similarly the folder that holds your compiled zlib library should go into the linker's list of search directories. Is that what you mean?


text:
Q: How Can I Compare and Hold Some Value : SQL SERVER 2008 R2 I have a table looks like this:
ITEM    |   DATE    |  PRICE | NEW_PRICE | REDUCTION |
Pencil  | 01/10/14  |    25  |    21     |     4     |
Pencil  | 01/12/14  |    21  |    21     |     0     |
Pencil  | 01/30/14  |    21  |    21     |     0     |
Pencil  | 02/05/14  |    21  |    18     |     3     |
Pencil  | 02/17/14  |    18  |    18     |     0     |
Pencil  | 03/20/14  |    18  |    18     |     0     |
Pencil  | 06/08/14  |    18  |    16     |     2     |
Pencil  | 07/14/14  |    16  |    16     |     0     |
Pencil  | 07/28/14  |    16  |    16     |     0     |

How can I select so I can get the result like this:
ITEM    |   DATE    |  PRICE | NEW_PRICE | REDUCTION | REDUCTION_HOLD |
Pencil  | 01/10/14  |    25  |    21     |     4     |       4        |
Pencil  | 01/12/14  |    21  |    21     |     0     |       4        |
Pencil  | 01/30/14  |    21  |    21     |     0     |       4        |
Pencil  | 02/05/14  |    21  |    18     |     3     |       3        |
Pencil  | 02/17/14  |    18  |    18     |     0     |       3        |
Pencil  | 03/20/14  |    18  |    18     |     0     |       3        |
Pencil  | 06/08/14  |    18  |    16     |     2     |       2        |
Pencil  | 07/14/14  |    16  |    16     |     0     |       2        |
Pencil  | 07/28/14  |    16  |    16     |     0     |       2        |

Thanks in advance.

A: Try a sub query:
SELECT ITEM = 'Pencil', DATE = '01/10/14', PRICE  = 25, NEW_PRICE = 21 , REDUCTION = 4 INTO #Table
UNION ALL SELECT 'Pencil'   ,'01/12/14'      ,21      ,21         ,0
UNION ALL SELECT 'Pencil'   ,'01/30/14'      ,21      ,21         ,0
UNION ALL SELECT 'Pencil'   ,'02/05/14'      ,21      ,18         ,3
UNION ALL SELECT 'Pencil'   ,'02/17/14'      ,18      ,18         ,0
UNION ALL SELECT 'Pencil'   ,'03/20/14'      ,18      ,18         ,0
UNION ALL SELECT 'Pencil'   ,'06/08/14'      ,18      ,16         ,2
UNION ALL SELECT 'Pencil'   ,'07/14/14'      ,16      ,16         ,0
UNION ALL SELECT 'Pencil'   ,'07/28/14'      ,16      ,16         ,0

GO

SELECT *
, REDUCTION_HOLD = (SELECT TOP 1 REDUCTION FROM #Table b WHERE a.DATE >= b.DATE AND b.REDUCTION > 0 ORDER BY b.DATE DESC)
FROM #Table a ORDER BY DATE

Result:


text:
Q: Is it possible to forward X11 windows in a Capistrano 3? I'm trying to forward an X11 window from a remote server. Usually I can do something like
ssh -X some@address
and then for example run
feh image.jpg
to see the image.jpg picture on my local machine. Is it possible to get that behaviour in Capistrano 3? I'm installing a software and it requires me to do the usual "nextnextnextfinish". I want to do something similar to (inside the config/deploy.rb)
set ssh_option, {:forward_x11 => true} #doesn't work
but it seems that sshkit doesn't have that option. Is there a list of the ssh_option for sshkit somewhere or is there another solution to this?

A: Capistrano is to automate deployment using some sort of *sh script on the remote computer. Forwarding X11 Windows would make the user having to interact with the window. Therefore I ended up using a Bash script, Sikuli and Xvfb to automate the solution.


text:
Q: How can I put dropdowns in cells of jQuery's Flexigrid? I need to put dropdowns in a cell of my jQuery Flexigrid for the user to change the data in Flexigrid own. How do I do this?
I need only knowing how to put the dropdowns in cells.

A: You can put any HTML object in a Flexigrid.
function Retornaddl()
{
    string linha = "<select class='inputlogininterno' id='resultadolista' name='resultadolista' style='width:150px;'><option value=''>Escolha...</option></select>";
    return linha;
}

var jsonData = new
{
    page = pageIndex,
    total = count,
    rows = (
        from item in pagedItems
        select new
        {
            id = item.ID,
            cell = new string[] {
                item.ID.ToString(),
                Retornaddl()
            }
        }).ToArray()
};
return Json(jsonData, JsonRequestBehavior.AllowGet);

A: You can't. But you can make an edit button in the grid and display your edit stuff in a floting div.


text:
Q: Security between rails and nodejs I have an app that is mostly in rails but also uses nodejs for some realtime features, for example, chat. Users log in via Rails and get assigned a session, etc as usual. However, what's the best way to authenticate with nodejs as that same user? For example I would like to prevent users from impersonating one another but login is done on rails right now and messaging is done on nodejs. Rails and nodejs both have access to the same database.
I am using devise and socketio if that matters.

A: There's a number of ways implementation wise that you could tackle this. The one that jumps to mind is to share the session cookie that devise uses with nodejs via the database.
IIRC devise creates an encrypted session cookie during authentication; save this value temporarily to your database, and let nodejs pop it off the database for its authentication. There's likely some difficulty in accomplishing this (porting some of the devise encryption to nodejs, and the like) but if you're doing a rails/nodejs app, I'm pretty sure you're capable of handling it. :D
The benefit here is that a user can't get between the hand-off to accomplish impersonation.

A: You could always generate a one-time token for any user passed between rails and node. Much, much easier than re-implementing (and maintaining) the crypto strategy used by devise and rails.
That said, sharing sessions between servers creates a lot of extra work for you and effectively doubles your bug surface area (schema, validations, etc.)
Faye is an awesome project which handles this exact use case, so it's probably worth a look :) http://faye.jcoglan.com/


text:
Q: How to convert this d3 v3 graph to a v4? I have been trying to convert this example in d3 v3 to a v4 version but still having trouble.
http://bl.ocks.org/eesur/be2abfb3155a38be4de4
Here is a JSFiddle of what I have so far: https://jsfiddle.net/echilee/sfbcntph/135/
I am able to console.log the LINKS and the NODES.  I made some progress and am able to see the nodes and click to open and close those that are connected. But cannot see links and how they should connect the nodes.
I replaced the nodes and links declaration and force function with this code:
// create a hierarchy from the root
const treeRoot = hierarchy(root)
tree(treeRoot)
const nodes = flatten(treeRoot.descendants())
const links = treeRoot.links()
var simulation = d3.forceSimulation()

I am not able to see the links.


text:
Q: Keep tabindex order if element is hidden This is a demo fiddle : http://jsfiddle.net/gLq2b/
<input value="0" />
<input id="test" value="1" />
<input value="2" />

If you press TAB repeatedly, it should focus on the 1st, 2nd, then 3rd input by order. So if for some reason, the 2nd input is hidden when it is focused, if you press TAB again, the tabindex order is resetted and you got to start from the beginning.
How to make it focus on the 3rd input instead when I press TAB again after the 2nd input is hidden?
Note that the input is just a test case, it could be a radio, a select, or any tabbable element with "tabindex" attribute, etc..

A: Just don't hide it but animate to an opacity of 0 and make the input field as small as possible at the end of the animation
$(this).animate({opacity:0}, function(){
    $(this).css({width:0,margin:0,padding:0});
});

Fiddle: http://jsfiddle.net/gLq2b/5/

A: you could change this line $(this).fadeOut(); to
$(this).next().focus().end().fadeOut();
example
EDIT:
Is this what you're looking for?
$(function(){
   $('#test').focus(function(){
       $(this).fadeOut(function() {
           $(this).next().focus();
       });
   });
});

new example


text:
Q: Why these instructions which should operate on unsigned integers still affect flags used when signed numbers are dealt with? It's documented that "INC", "DEC" and "MUL" instructions should be used on unsigned integers but still two first instructions affect overflow and sign flags and "MUL" affects overflow flag which are flags used when dealing with signed numbers and it doesn't make sense with that documentation, So why ?

A: I'm not sure where you get the idea that inc and dec should be restricted to unsigned integers. Please point me at the pertinent documentation.
In general, the 8086 processor didn't have different instructions for signed/unsigned operations.  The processor had built-in knowledge of how the result of an operation would be viewed in a "signed" world, but that's pretty much as far as it went.  And that has been carried through to the latest iterations of the x86 processor design.
It would make little sense to have an inc instruction that worked only with unsigned values, as then it would be either very expensive to increment a signed value (you would have to use the add or adc instruction to add 1), or it would be very expensive to check for overflow after doing the inc (or dec).

A: Assuming we are talking x86 here, the Wikipedia page on the overflow flag says it's set by all arithmetic operations.  Which documentation are you referring to that suggests otherwise?

A: This is how it works:
Consider two byte values 0x65 and 0x31. They are both unsigned values regardless of whether you look at them from a signed or unsigned point of view.
Then you add them:
0x65 + 0x31 becomes 0x96 which is fine from the unsigned point of view (the sum fits in a byte so no carry flag was set). However from the signed view the addition of two positive numbers resulted in a negative number, hence the overflow and sign flags were set. In fact, for all signed numbers the overflow flag is set if the most significant bit changes as a result of the operation, otherwise it is cleared.
You can see it as if the cpu performs two operations for every instruction by setting the applicable flags for both the unsigned and the signed add. After that it is up to the compiler (or assembly programmer) to decide if an unsigned conditional branch (using flags zero and carry) or a signed conditional branch (using flags zero, sign and overflow).
So what's the point?
The point is that if it were not done in this way the processor would need one set of instructions for signed operations (that would only affect the zero, sign and overflow flags) and another for unsigned operations (affecting zero and carry).


text:
Q: How to write in ruby test that at least one of three variables is blank? I have this validation:
if self.var_a.blank? || self.var_b.blank? || self.var_c.blank?
  self.errors[:base] << "Error."
end

If are all three variables set up or all three are not set up, everything's ok.
But if there is set up one of those 3 or 2 of 3, I need to display the error.
I am fighting with this issue some time, but cannot effectively write it.

A: if [var_a,var_b,var_c].any?{|m| m.blank?}
  self.errors[:base] << "Error."
end

or
self.errors[:base] << "Error." if [var_a,var_b,var_c].any?(&:blank?)

A: Im guessing syntax here (dont know ruby).. but logic should be something like this:
if [var_a,var_b,var_c].any?{|m| m.blank?} && ![var_a,var_b,var_c].all?{|m| m.blank?}
  self.errors[:base] << "Error."
end


text:
Q: RecyclerView error: cannot find symbol variable ao Executar o Projeto Android Studio Meu projeto ao axecutar aparece esse erro:
Error:(417, 63) error: cannot find symbol variable testando

Local do erro:

O gradle do app está com todos os imports para o uso do RecyclerView correto:
apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.3"

    defaultConfig {
        applicationId "com.t2ti.cardapiobalcao"
        minSdkVersion 14
        targetSdkVersion 22
        versionCode 1
        versionName "1.0"
        ndk {
            abiFilters "armeabi", "armeabi-v7a", "x86", "mips"
        }

    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

repositories {
    maven {
        url 'https://oss.sonatype.org/content/repositories/ksoap2-android-releases/'
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    //v7:22.2.1
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support:recyclerview-v7:25.3.1'
    compile 'com.github.bumptech.glide:glide:3.5.2'
    compile 'com.google.code.ksoap2-android:ksoap2-android:3.4.0'
    compile 'com.google.code.gson:gson:2.3.1'
    compile 'commons-io:commons-io:2.4'
    compile 'com.squareup.picasso:picasso:2.5.2'
    compile 'pl.droidsonroids.gif:android-gif-drawable:1.1.17'
    compile('org.simpleframework:simple-xml:2.7.1') {
        exclude module: 'stax'
        exclude module: 'stax-api'
        exclude module: 'xpp3'
    }

    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile "com.google.firebase:firebase-messaging:9.0.2"
    //compile 'com.google.firebase:firebase-core:9.0.2'
}
apply plugin: 'com.google.gms.google-services'

Mesmo assim continua o erro e não consigo solucionar.
Abaixo o xml da main activity
<ScrollView  xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"

    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"
    android:orientation="vertical"
    android:elevation="1dp"
    android:weightSum="1"
    >

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="63dp"
        android:src="@drawable/logo"
        android:id="@+id/imageView" />

    <TextView
        android:text="@string/txt_info1"
        android:layout_width="match_parent"
        android:id="@+id/txt_info1"
        android:textAppearance="@style/TextAppearance.AppCompat.Body2"
        android:layout_weight="0.91"
        android:layout_height="match_parent" />

    <Space
        android:layout_width="match_parent"
        android:layout_height="10dp" />

    <TextView
        android:text="@string/txt_info2"
        android:layout_width="match_parent"
        android:id="@+id/txt_info2"
        android:textAppearance="@style/TextAppearance.AppCompat"
        android:layout_weight="1.28"
        android:layout_height="match_parent" />

    <Space
        android:layout_width="match_parent"
        android:layout_height="10dp" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="35dp"
        android:text="@string/bt_incluir_item"
        android:id="@+id/button"
        android:layout_gravity="center_horizontal"
        android:onClick="cadastraItem"
        android:elevation="0dp"
        android:elegantTextHeight="false"
        android:background="@drawable/botao_customizado"
        android:textAppearance="@android:style/TextAppearance.StatusBar.EventContent.Title" />

    <Space
        android:layout_width="match_parent"
        android:layout_height="10dp" />

    <TextView
        android:text="@string/txt_info3"
        android:layout_width="match_parent"
        android:id="@+id/textView7"
        android:textAppearance="@style/TextAppearance.AppCompat.Body2"
        android:layout_weight="0.14"
        android:layout_height="24dp" />

    <Space
        android:layout_width="match_parent"
        android:layout_height="10dp" />

    <android.support.v4.widget.NestedScrollView
        android:layout_width="match_parent"
        android:layout_height="348dp">

        <android.support.v7.widget.RecyclerView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/testando" />
    </android.support.v4.widget.NestedScrollView>

    <Space
        android:layout_width="match_parent"
        android:layout_height="10dp" />

    <TextView
        android:text="@string/txt_info4"
        android:layout_width="match_parent"
        android:id="@+id/textView8"
        android:layout_height="24dp"
        android:layout_weight="0.19"
        android:gravity="center"
        android:textAppearance="@style/TextAppearance.AppCompat.Body2" />

</LinearLayout>
</ScrollView>

MainActivity abaixo modifiquei o nome da variável testando por recyclerViewTest
package com.t2ti.cardapiobalcao;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.squareup.picasso.Picasso;
import com.t2ti.cardapio.Constantes;
import com.t2ti.cardapio.RequisicaoWebService;
import com.t2ti.cardapio.helper.CardapioContract;
import com.t2ti.cardapio.helper.DatabaseOpenHelper;
import com.t2ti.cardapio.model.DataFish;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    ImageView imageView2;
    String url = "http://media.prefeituradeimperatriz.com.br/pVCzLbf4KZ-ADFsQ9QPGLTWRw0c=/750x0/https://d2uzqu0gkpnx87.cloudfront.net/site/content/article/recicla_catatreco.jpeg";
    private static final int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
    private BroadcastReceiver mRegistrationBroadcastReceiver;
    private static final String TAG = "MainActivity";
    private String currentUrl;
    // CONNECTION_TIMEOUT and READ_TIMEOUT are in milliseconds
    public static final int CONNECTION_TIMEOUT = 10000;
    public static final int READ_TIMEOUT = 15000;
    private RecyclerView mRVFishPrice;
    private AdapterFish mAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //Make call to AsyncTask

        mRegistrationBroadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                SharedPreferences sharedPreferences =
                        PreferenceManager.getDefaultSharedPreferences(context);
                boolean sentToken = sharedPreferences
                        .getBoolean(Constantes.SENT_TOKEN_TO_SERVER, false);
                if (!sentToken) {
                    Toast.makeText(MainActivity.this, R.string.msg_erro_token, Toast.LENGTH_LONG).show();
                }
            }
        };

        if (checkPlayServices()) {
            // Start IntentService to register this application with GCM.
            Intent intent = new Intent(this, RegistrationIntentService.class);
            startService(intent);
        }
        new AsyncLogin().execute();

        //imageView2 = (ImageView)findViewById(R.id.imageView2);
        //loadImagefromUrl(url);

    }

    /**
     * Check the device to make sure it has the Google Play Services APK. If
     * it doesn't, display a dialog that allows users to download the APK from
     * the Google Play Store or enable it in the device's system settings.
     */
    private boolean checkPlayServices() {
        int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
        if (resultCode != ConnectionResult.SUCCESS) {
            if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
                GooglePlayServicesUtil.getErrorDialog(resultCode, this,
                        PLAY_SERVICES_RESOLUTION_REQUEST).show();
            } else {
                Log.i(TAG, "This device is not supported.");
                finish();
            }
            return false;
        }
        return true;
    }

/*
    public void listaItens(View view) {
        int categoria;
        switch (view.getId()) {
            case (R.id.buttonEntrada): {
                categoria = Constantes.CATEGORIA_ENTRADA;
                break;
            }
            case (R.id.buttonPratoPrincipal): {
                categoria = Constantes.CATEGORIA_PRATO_PRINCIPAL;
                break;
            }
            case (R.id.buttonBebida): {
                categoria = Constantes.CATEGORIA_BEBIDA;
                break;
            }
            case (R.id.buttonSobremesa): {
                categoria = Constantes.CATEGORIA_SOBREMESA;
                break;
            }
            default: {
                categoria = Constantes.CATEGORIA_NAO_DEFINIDA;
            }
        }
        Intent intent = new Intent(this, ListaItemActivity.class);
        intent.putExtra("categoria", categoria);
        startActivity(intent);
    }*/

    public void cadastraItem(View view) {
        Intent intent = new Intent(this, CadastraItemActivity.class);
        startActivity(intent);
    }
/*
    public void pedidosPendentes(View view) {
        Intent intent = new Intent(this, PedidoPendenteActivity.class);
        startActivity(intent);
    }
*/

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle(getResources().getString(R.string.txt_alert_atualizacao));
            builder.setMessage(getResources().getString(R.string.txt_alert_confirma_atualizacao));
            builder.setPositiveButton(R.string.txt_sim, new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    new AtualizaDados().execute();
                }
            });

            builder.setNegativeButton(R.string.txt_nao, new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {

                }
            });
            AlertDialog dialog = builder.create();
            dialog.show();

            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    private class AtualizaDados extends AsyncTask<Void, Void, Boolean> {

        private ProgressDialog dialog = new ProgressDialog(MainActivity.this);

        @Override
        protected void onPreExecute() {
            dialog.setMessage(getResources().getString(R.string.msg_processando));
            dialog.show();
        }

        @Override
        protected Boolean doInBackground(Void... params) {
            try {
                RequisicaoWebService requisicaoWebService = new RequisicaoWebService();
                List<com.t2ti.cardapio.model.DetalheDenuncia> detalhes = requisicaoWebService.getItensCardapio();

                DatabaseOpenHelper databaseOpenHelper = new DatabaseOpenHelper(MainActivity.this);
                SQLiteDatabase db = databaseOpenHelper.getWritableDatabase();

                databaseOpenHelper.onUpgrade(db, 0, 0);

                for (com.t2ti.cardapio.model.DetalheDenuncia detalhe : detalhes) {
                    ContentValues contentValues = new ContentValues();
                    contentValues.put(CardapioContract.DetalheDenuncia._ID, detalhe.getId());
                    contentValues.put(CardapioContract.DetalheDenuncia.COLUMN_NAME_TIPO_DENUNCIA, detalhe.getTipoDenuncia());
                    contentValues.put(CardapioContract.DetalheDenuncia.COLUMN_NAME_DENUNCIADO, detalhe.getDenunciado());
                    contentValues.put(CardapioContract.DetalheDenuncia.COLUMN_NAME_LOCAL_DENUNCIA, detalhe.getDescricao());
                    contentValues.put(CardapioContract.DetalheDenuncia.COLUMN_NAME_PONTO_REFERENCIA, detalhe.getpReferencia());
                    contentValues.put(CardapioContract.DetalheDenuncia.COLUMN_NAME_DESCRICAO_DENUNCIA, detalhe.getDescricao());
                    contentValues.put(CardapioContract.DetalheDenuncia.COLUMN_NAME_URL_IMAGEM, detalhe.getUrlImagem());

                    db.insert(CardapioContract.DetalheDenuncia.TABLE_NAME, null, contentValues);
                }
                db.close();
                return true;
            } catch(Exception e) {
                Log.e("MainActivity", e.getMessage());
                return false;
            }
        }

        @Override
        protected void onPostExecute(Boolean b) {
            if(b) {
                Toast.makeText(MainActivity.this, getResources().getString(R.string.msg_atualizado), Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(MainActivity.this, getResources().getString(R.string.msg_erro_atualizar), Toast.LENGTH_SHORT).show();
            }
            if (dialog.isShowing()) {
                dialog.dismiss();
            }
        }
    }

    private class AsyncLogin extends AsyncTask<String, String, String> {
        ProgressDialog pdLoading = new ProgressDialog(MainActivity.this);
        HttpURLConnection conn;
        URL url = null;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            //this method will be running on UI thread
            pdLoading.setMessage("\tLoading...");
            pdLoading.setCancelable(false);
            pdLoading.show();

        }

        @Override
        protected String doInBackground(String... params) {
            try {

                // Enter URL address where your json file resides
                // Even you can make call to php file which returns json data
                //url = new URL("http://192.168.1.7/test/example.json");
                url = new URL("https://cardapiobalcao-91464.firebaseapp.com/jsonData/prefeitura.json");

            } catch (MalformedURLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                return e.toString();
            }
            try {

                // Setup HttpURLConnection class to send and receive data from php and mysql
                conn = (HttpURLConnection) url.openConnection();
                conn.setReadTimeout(READ_TIMEOUT);
                conn.setConnectTimeout(CONNECTION_TIMEOUT);
                conn.setRequestMethod("GET");

                // setDoOutput to true as we recieve data from json file
                conn.setDoOutput(true);

            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
                return e1.toString();
            }

            try {

                int response_code = conn.getResponseCode();

                // Check if successful connection made
                if (response_code == HttpURLConnection.HTTP_OK) {

                    // Read data sent from server
                    InputStream input = conn.getInputStream();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(input));
                    StringBuilder result = new StringBuilder();
                    String line;

                    while ((line = reader.readLine()) != null) {
                        result.append(line);
                    }

                    // Pass data to onPostExecute method
                    return (result.toString());

                } else {

                    return ("unsuccessful");
                }

            } catch (IOException e) {
                e.printStackTrace();
                return e.toString();
            } finally {
                conn.disconnect();
            }
        }

        @Override
        protected void onPostExecute(String result) {

            //this method will be running on UI thread

            pdLoading.dismiss();
            List<DataFish> data=new ArrayList<>();

            pdLoading.dismiss();
            try {

                JSONArray jArray = new JSONArray(result);

                // Extract data from json and store into ArrayList as class objects
                for(int i=0;i<jArray.length();i++){
                    JSONObject json_data = jArray.getJSONObject(i);
                    DataFish fishData = new DataFish();
                    fishData.fishImage= json_data.getString("image");
                    fishData.fishName= json_data.getString("channel");
                    fishData.catName= json_data.getString("title");
                    //fishData.sizeName= json_data.getString("size_name");
                    //fishData.price= json_data.getInt("price");
                    data.add(fishData);
                }

                // Setup and Handover data to recyclerview
                mRVFishPrice = (RecyclerView)findViewById(R.id.recyclerViewTest);
                mAdapter = new AdapterFish(MainActivity.this, data);
                mRVFishPrice.setAdapter(mAdapter);
                mRVFishPrice.setLayoutManager(new LinearLayoutManager(MainActivity.this));

            } catch (JSONException e) {
                Toast.makeText(MainActivity.this, e.toString(), Toast.LENGTH_LONG).show();
            }
        }

    }
}

A: Foi resolvido, o erro ocorria por existir três Activity_main.xml coisa que eu não tinha percebido, uma estava sem o RecyclerView, e outra o Visual Studio bem que podia ter informado no erro qual Activity tava o problema, demorei quase duas semanas para resolver isso.


text:
Q: Capture node.js crash reason I have a script written in node.js, it uses 'net' library and communicates with distant service over tcp. This script is started using 'node script.js >> log.txt' command and everything in that script that is logged using console.log() function gets written to log.txt but sometimes script dies and I cannot find a reason and nothing gets logged in log.txt around the time script crashed.
How can I capture crash reason?

A: Couldn't you listen to uncaughtException event. Something along the lines of =>
process.on('uncaughtException', function (err) {
  console.log('Caught exception: ' + err);
});

P.S: after that you are adviced to restart process according to this article from Felix Geisendörfer

A: It's much easier to capture exceptions by splitting stdout and stderr. Like so:
node script.js 1> log.out 2> err.out

By default, node logs normal output to stdout, which I believe you are capturing with >>.
As noted in the comments, a segmentation fault is a signal put to stderr by the shell, not necessarily your program. See this unix.stackexchange answer for other options.


text:
Q: flutterfire configure not working even after installing via npm, and relogging I keep getting this error no matter what I attempt to do,
I've already tried using "npm install -g firebase-tools",
and "firebase projects:list" displays a correct list of my current projects.
Looking for help as I have sunk countless hours into this problem without being able to move a step forward.
   FirebaseCommandException: An error occured on the
   Firebase CLI when attempting to run a command.
   COMMAND: firebase --version
   ERROR: The FlutterFire CLI currently requires the official Firebase CLI to also be installed, see https://firebase.google.com/docs/cli#install_the_firebase_cli for how to install it. ```

A: In case you have installed (and renamed) firebase.exe from the windows installer, remove that first.
The installation of npm install -g firebase-tools and the windows installer are conflicting with each other.
Then go through firebase logout and firebase login again before running flutterfire configure.

A: I added the firebase-tools file downloaded from  https://firebase.tools/bin/win/instant/latest in the root of the directory of my project and it works for me. I changed the name to firebase only.

A: This solved it for me
curl -sL firebase.tools | upgrade=true bash


text:
Q: how to set up SSL for Apache for a Mac so I can test Cross Domain iFrame on IE8 I set up Apache on with the standard self-signed ssl mods to my http.conf, and this is working locally on my mac, but when I try to access it from my windows machine with IE8 it doesn't seem to like the certificate.
I've tried to import the certificate into the Windows -> Internet Options modal, but that just doesn't seem to work for accessing the iFrame cross domain.  IE shows that yellow alert at the bottom of the page warning about an iFrame, but doesn't load the other files from that domain.  After I accept the alert, the page reloads and the same thing occurs.
In production this works with the real certs.
Any ideas on what might be wrong with my development environment and my certs?
UPDATE
I opened the command-line in admin mode and flushed the cache.  No help.
I am able to ping the domain name and get the correct IP back.
IE Reports: The security certificate presented by this website was issued for a different website's address.
UPDATE 2
http://wiki.apache.org/httpd/NameBasedSSLVHostsWithSNI
The above article touches on some of the key problems with running two SSL servers off of one machine (Mac OSX).  However learning something about NameBased SSLVirtualHosts and SNI, I don't think it's the problem I am having, but it might be related.  IE is reporting that the server domain and the cert don't match.  So I wonder if this is related to me using a global cert for both SSL domains.
UPDATE 3  ( solution )
https://serverfault.com/questions/393363/mismatched-address-error-on-self-signed-ssl-certtificate
It turns out that the common name for the certificate was wrong, which allowed the certificate to work in FF, and Chrome, but not in IE8, IE9, IE10.  After generating a new certificate as a wild card, I was able access all of the NameBased SSL Virtual Hosts via SNI. so set your common name to *.YourDomain.tld and you will be fine.

A: The problem I was having is that the Common Name specified in the certificate was not a proper domain name for the domains I was hosting.  Instead I was using a 'common name' for our company name, which was not a domain name at all.
If you are going to generate a self signed certificate you might want to use a Common Name like *.domain.tld to generate your star.domian.tld.key and star.domain.tld.crt


text:
Q: Сохранение данных на стороне клиента Попытаюсь подробно описать проблему. Разрабатываю сайт образовательного характера. Необходимо сделать так, чтобы та информация, которую обучающийся напишет в поля для ввода ответа, сохранялась где-либо (вопрос в том, где???) до того момента, пока он не отправит ответы в БД. Чтобы если он случайно закрыл страницу и захотел вернуться на неё, в полях для ввода ответов по умолчанию уже находилась введённая им до этого информация.
Примерный объём информации - 100кб.
Как это можно сделать (желательно, не используя БД)?

A: Как вариант, можно использовать localStorage. Пример использования:
<script>
     let data = [];

     # вы можете описать тут addEventListener, который получит информацию с полей input/textarea или других.
     $("input").each(function (i, input) {
         data.push(input.value);
     });

     localStorage.setItem('saved_data', data);
</script>

После этого вы сможете получить данные даже после обновления страницы:
<script>
    let data = localStorage.getItem('saved_data');
</script>


text:
Q: Making series of jpegs into videos on a PC I have sets of timelapse photos (jpegs), that I want to turn into a video.
I prefer freeware as this is just some fun-projects.
I need to do this on a windows-pc, so no Mac-soft please.

A: Windows Live Movie Maker.

A: I've used VirtualDub for this. As long as your images are numbered sequentially you can open them like a video and export them as avi.

To reading a series of numbered images as a video stream, use File > Open video file... and select the first image. VirtualDub will automatically step the filename and find any sequentially numbered frames after the starting file. - Working with image sequences

A: Take a look at JPGVideo, free and it looks like it does what you need.

A: MonkeyJam is what you're looking for.  This software was originally designed for pencil tests, but you can use it for stop motion animation/time lapse videos too.

A: *

*download and run Portable Movie Maker

*import images

*drag and drop images into the story board

*save movie ... done and dusted.
p.s.: the most recent versions of (Windows Live) Movie Maker for Vista and 7 don't have all the features and transitions you can find on earlier builds. this portable variant, based on Movie Maker 2.1, does have all the "bells 'n' whistles", it works with with Windows XP, Vista, and Windows 7 (without installation).


text:
Q: Group by with in Group by using dataframe python panda For the give piece of data from .csv file i want to get groupby and get sum of the amount by using following rule.
Note that some categories, such as "Cloud Security" needed to be composed / summed from categories such as: Cloud Security, Cloud Computing, and Cloud Data Services to come up with "Cloud Security Overall." Similarly, "Blockchain and Cryptocurrencies" is a sum of Blockchain, Virtual Currency, Bitcoin, and Etherium.

My Code:
tmp = pd.DataFrame({'Categories' : ['Blockchain,Cloud Computing,InformationTechnology,Software', 'Cyber Security,Fraud Detection,Information Technology,Network Security', 'Information Technology,Medical,Security,Virtual Currency,Telecommunications', 'Mobile,Mobile Devices, Security,Bitcoin',
                      'Computer,Cyber Security,Network Security', 'Accounting,Hardware,Security,Software,Cloud data Service', 'Content,Security,Software,Etherium', 'Cyber Security,Enterprise Software,Security'],
               'Amount' : [500, 400, 700, 900, 100, 800, 1000,600]})
print(tmp)

dfc = tmp.groupby(tmp['Categories'])['Amount'].sum().reset_index()
dfc.columns =['Categories', 'Amount']

this code just give over all group by and sum

A: Try this:
import pandas as pd
import numpy as np

df = pd.DataFrame({'Categories':['Blockchain, Cloud Computing, Information Technology, Software',
                                'Cyber Security, Fraud Detection, Information Tehnology, Network Security',
                                'Information Technology, Medical, Security, Virtual Currency, Telecommunications',
                                'Mobile, Mobile Devices, Security, Bitcoin',
                                'Computer, Cyber Security, Network Security',
                                'Accounting, Hardware, Security, Software, Cloud data Service',
                                'Content, Security, Software, Etherium',
                                'Cyber Security, Enterprise Software, Security'],
                  'Amount':[500,400,700,900,100,800,1000,600]})

dfe = df.assign(Cats=df['Categories'].str.split(',\s+?')).explode('Cats')

dd = {'Cyber Security': 'Cloud Security Overall',
      'Cloud Computing' : 'Cloud Security Overall',
      'Cloud data Service' : 'Cloud Security Overall',
      'Blockchain' : 'Blockchain and Cyptocurrencies',
      'Virtual Currency' : 'Blockchain and Cyptocurrencies',
      'Bitcoin' : 'Blockchain and Cyptocurrencies',
      'Etherium' : 'Blockchain and Cyptocurrencies'}

print(dfe.groupby(dfe['Cats'].map(dd))['Amount'].sum())

Output:
Cats
Blockchain and Cyptocurrencies    3100
Cloud Security Overall            2400
Name: Amount, dtype: int64

Update per comments, did you want?
dfe.groupby(dfe['Cats'].replace(dd))['Amount'].sum()

Output:
Cats
Accounting                         800
Blockchain and Cyptocurrencies    3100
Cloud Security Overall            2400
Computer                           100
Content                           1000
Enterprise Software                600
Fraud Detection                    400
Hardware                           800
Information Technology            1200
Information Tehnology              400
Medical                            700
Mobile                             900
Mobile Devices                     900
Network Security                   500
Security                          4000
Software                          2300
Telecommunications                 700
Name: Amount, dtype: int64

Or
dfe.groupby(dfe['Cats'].map(dd).fillna('Rest'))['Amount'].sum()

Output:
Cats
Blockchain and Cyptocurrencies     3100
Cloud Security Overall             2400
Rest                              15300
Name: Amount, dtype: int64


text:
Q: Adding months to a pandas object in Python I have this dataframe object:
    Date
2018-12-14
2019-01-11
2019-01-25
2019-02-08
2019-02-22
2019-07-26

What I want, if it's possible, is to add for example: 3 months to the dates, and then 3 months to the new date (original date + 3 months) and repeat this x times. I am using pd.offsets.MonthOffset but this just adds the months one time and I need to do it more times.
I don't know if it is possible but any help would be perfect.
Thank you so much for taking your time.
The expected output is (for 1 month adding 2 times):
[[2019-01-14, 2019-02-11, 2019-02-25, 2019-03-08, 2019-03-22,  2019-08-26],[2019-02-14, 2019-03-11, 2019-03-25, 2019-04-08, 2019-04-22,  2019-09-26]]

A: I believe you need loop with f-strings for new columns names:
for i in range(1,4):
    df[f'Date_added_{i}_months'] = df['Date'] + pd.offsets.MonthBegin(i)
print (df)
        Date Date_added_1_months Date_added_2_months Date_added_3_months
0 2018-12-14          2019-01-01          2019-02-01          2019-03-01
1 2019-01-11          2019-02-01          2019-03-01          2019-04-01
2 2019-01-25          2019-02-01          2019-03-01          2019-04-01
3 2019-02-08          2019-03-01          2019-04-01          2019-05-01
4 2019-02-22          2019-03-01          2019-04-01          2019-05-01
5 2019-07-26          2019-08-01          2019-09-01          2019-10-01

Or:
for i in range(1,4):
    df[f'Date_added_{i}_months'] = df['Date'] + pd.offsets.MonthOffset(i)
print (df)
        Date Date_added_1_months Date_added_2_months Date_added_3_months
0 2018-12-14          2019-01-14          2019-02-14          2019-03-14
1 2019-01-11          2019-02-11          2019-03-11          2019-04-11
2 2019-01-25          2019-02-25          2019-03-25          2019-04-25
3 2019-02-08          2019-03-08          2019-04-08          2019-05-08
4 2019-02-22          2019-03-22          2019-04-22          2019-05-22
5 2019-07-26          2019-08-26          2019-09-26          2019-10-26

A: I hope this helps
from dateutil.relativedelta import relativedelta
month_offset = [3,6,9]
for i in month_offset:
    df['Date_plus_'+i+'_months'] = df['Date'].map(lambda x: x+relativedelta(months=i))

A: If your dates are date objects, it should be pretty easy. You can just create a timedelta of 3 months and add it to each date.
Alternatively, you can convert them to date objects with .strptime() and then do what you are suggesting. You can convert them back to a string with .strftime().


text:
Q: Developing a custom SPA for browsing and uploading to S3 Is it possible to deploy an SPA on AWS that calls Amazon S3 APIs?
The SPA will act as a custom S3 browser app, where I want to be able to deploy, delete, etc documents that are stored in a S3 instance.
Thanks

A: You can certainly deploy a Single Page app written in the language of your choice and then use the corresponding AWS SDK to invoke S3 operations. For example, you can write a SPA in JS that uses the Amazon S3 JavaScript API to perform S3 CRUD operations on Amazon S3 content. Likewise, you can develop a SPA in Java and then use the Java S3 API.
Once you develop your app, you can deploy it to the cloud by deploying it to an EC2 instance. Using Elastic Beanstalk makes it easy to deploy an App to the cloud.

A: Yes it's possible to deploy a SPA on AWS S3. Adding medium article for reference https://medium.com/@joecrobak/production-deploy-of-a-single-page-app-using-s3-and-cloudfront-d4aa2d170aa3.
Though you need to other AWS services as well like route 53 and cloudfront


text:
Q: How to fix strange dart error on http call I am getting the following error at run time I am doing an http call and getting json back.
"_TypeError (type 'List' is not a subtype of type '() => void')"
Here is my code
   class _ForumPostsState extends State<ForumPosts> {
List data;
String categoryID = 'D64D0737-746D-4562-8C10-6445F4069A92';
Future<String> getPostsByCategory() async {
    var response = await http.post(
 Uri.encodeFull("http://api/ForumPostsByCategory"),
      headers: {"Content-Type": "application/json",
             'Accept': 'application/json',},
      body: json.encode({'categoryID' : categoryID }));
     this.setState(
         data = json.decode(response.body)

     );
    print(data[1]["title"]);

return "Success!";
}

The error is thrown on this line
data = json.decode(response.body)

While debugging I noticed that the JSON was there it just errors on the data = json.decode call.

A: Change this:
this.setState(
     data = json.decode(response.body)

  );

To this:
 this.setState(() {
     data = json.decode(response.body)
    }
 );

More info here: https://docs.flutter.io/flutter/widgets/State/setState.html


text:
Q: PHP Package Dompdf renders empty pdf files I'm using the package dompdf/dompdf v2.0.1 (link here). I've followed the basic example given on their page, creating the following Php file:
<?php

declare(strict_types=1);

use Dompdf\Dompdf;

require __DIR__ . '/../vendor/autoload.php';

$dompdf = new Dompdf();
$dompdf->loadHtml('
Hello World!
');
$dompdf->setPape('A4');
$dompdf->stream();

As expected, the library creates a PDF file and sends a response to the browser to download it. The problem is, the PDF I get in return is completely empty. I've even looked at the raw code for the file and there's no mention of the text I've added.
I'm running php-fpm v8.1.13 on Alpine inside a Docker container. I've installed the necessary Php extensions (ext-dom, ext-mbstring) as well as GD. The official page says that the library works under PHP 8.1, and there's even a debug page that shows it's working under php 8.1.
Is this a bug, or am I doing something wrong?

A: I just got an answer from someone on the GitHub page for the library. You have to call $domPdf->render() to actually build the file. I mistakenly thought that was for a different purpose and you had to call $domPdf->stream() only.


text:
Q: Add dynamic variables to login_path and check_path In my case, when a user login our system, we have to figure out what source he/she is from. We have to add a dynamic variable to login_path, failure_path.
I searched a lot but did't find a useful answer, thanks.

A: The easiest way to achieve this is to create two classes and then reference them as the handler services in your security.yml.
First off, take a look at Symfony\Component\Security\Http\Authentication\DefaultAuthenticationSuccessHandler and Symfony\Component\Security\Http\Authentication\DefaultAuthenticationFailureHandler. These are the classes that are called when authentication succeeds or fails and are passed the relevant options from your security.yml configuration.
Create your own classes and extend from these defaults, overriding the onAuthenticationSuccess and onAuthenticationFailure methods with your own business logic (i.e. your dynamic variables). Then set them up as services:
my.authentication.success_handler:
    class: My\Authentication\SuccessHandler
    arguments: [ "1", "2", "3" ]

my.authentication.failure_handler:
    class: My\Authentication\FailureHandler
    arguments: [ "4", "5", "6" ]

Then in security.yml:
security:
    firewalls:
        my_firewall:
            form_login:
                success_handler: my.authentication.success_handler
                failure_handler: my.authentication.failure_handler

Then when you log, the relevant onAuthenticationX method will be called. You probably want to return a redirect response like in the defaults but with your dynamic variables added on.
If you want an easy way of maintaining / retrieving the options from the default handlers, I'd suggest looking into Service Decoration from the Symfony Cookbook.

A: In order to help others, I list what I found for my question.

*

*no need to add variables to path of firewall, it supports route name
with variables, symfony will get all veriables from url path ,and fill them into all routes of firewall.

*add global variables to all routes .
There is a example in symfony that demostrates how to add extra global variables to all routes. checkout this class Symfony\Component\HttpKernel\EventListener\LocaleListener


text: Q: encode url in laravel and decode in react I am working on project where backend is in laravel and frontend in react. I want to send some url with some parameters i.e http:://localhost:3000/reset?email=abc@email.com to user email and then open that url in frontend and then get email in frontend form url. I am using reach/router. But I don't want this parameter to be visible in browser url bar. Is there any way so I can send encoded url from laravel and then decode and get parameters in react.


text:
Q: Double Loops in R: Use .name_repair to specify repair? I have this dataset in R:
set.seed(123)

myFun <- function(n = 5000) {
  a <- do.call(paste0, replicate(5, sample(LETTERS, n, TRUE), FALSE))
  paste0(a, sprintf("%04d", sample(9999, n, TRUE)), sample(LETTERS, n, TRUE))
}

col1 = myFun(100)
col2 = myFun(100)
col3 = myFun(100)
col4 = myFun(100)
group <- c("A","B","C","D")
group = sample(group, 100, replace=TRUE)

example = data.frame(col1, col2, col3, col4, group)

       col1       col2       col3       col4 group
1 SKZDZ9876D BTAMF8110T LIBFV6882H ZFIPL4295E     A
2 NXJRX7189Y AIZGY5809C HSMIH4556D YJGJP8022H     C
3 XPTZB2035P EEKXK0873A PCPNW1021S NMROS4134O     A
4 LJMCM3436S KGADK2847O SRMUI5723N RDIXI7301N     B
5 ADITC6567L HUOCT5660P AQCNE3753K FUMGY1428B     D
6 BAEDP8491P IAGQG4816B TXXQH6337M SDACH5752D     C

I wrote this loop that compares different string distance metrics between all combinations of (col1,col2) and (col3,col4):
method = c("osa", "lv", "dl", "hamming", "lcs", "qgram", "cosine", "jaccard", "jw","soundex")

library(stringdist)

results = list()

for (i in 1:length(method))

{

method_i = method[i]
name_1_i = paste0("col1_col_2", method_i)
 name_2_i = paste0("col3_col_4", method_i)

p1_i = stringdistmatrix(col1, col2, method =  method_i, useNames = "string") %>%
            as_tibble(rownames = "a") %>%
            pivot_longer(-1, names_to = "b", values_to = name_1_i)

p2_i = stringdistmatrix(col3, col4, method =  method_i, useNames = "string") %>%
            as_tibble(rownames = "a") %>%
            pivot_longer(-1, names_to = "b", values_to = name_2_i)

p1_i = p1_i[,3]
p2_i = p2_i[,3]

final_i = cbind(p1_i, p2_i)

results[[i]] = final_i
}

final = do.call(cbind.data.frame, results)
final = cbind(col1,col2, col3,col4, final)

average_col1_col2_dist = (final$col1_col_2osa  + final$col1_col_2lv + final$col1_col_2dl      + final$col1_col_2hamming + final$col1_col_2lcs +     final$col1_col_2qgram  + final$col1_col_2cosine    + final$col1_col_2jaccard + final$col1_col_2jw   + final$col1_col_2soundex)/10

 average_col3_col4_dist =  ( final$col3_col_4osa     +    final$col3_col_4lv       +     final$col3_col_4dl  +     final$col3_col_4hamming +  final$col3_col_4lcs +  final$col3_col_4qgram  +   final$col3_col_4cosine +    final$col3_col_4jaccard  +    final$col3_col_4jw     +   final$col3_col_4soundex)/10

final = data.frame( col1, col2, col3, col4, average_col1_col2_dist,  average_col3_col4_dist)
final = scale(final)

Now, I would like to make this a "double loop" and have the same comparisons being done, but the comparisons should be made only within each "group" :
results = list()

for (i in 1:length(method))
for (j in 1:length(unique(example$group))

{

{

groups_j = unique(example$group[j])
my_data_i = file[which(file$fsa == groups_j  ), ]

method_i = method[i]
name_1_i = paste0("col1_col_2", method_i)
 name_2_i = paste0("col3_col_4", method_i)

p1_i = stringdistmatrix(my_data_i$col1, my_data_i$col2, method =  method_i, useNames = "string") %>%
            as_tibble(rownames = "a") %>%
            pivot_longer(-1, names_to = "b", values_to = name_1_i)

p2_i = stringdistmatrix(my_data_i$col3, my_data_i$col4, method =  method_i, useNames = "string") %>%
            as_tibble(rownames = "a") %>%
            pivot_longer(-1, names_to = "b", values_to = name_2_i)

p1_i = p1_i[,3]
p2_i = p2_i[,3]

final_i = cbind(p1_i, p2_i)
 results[[i]] = final_i

}

}

final = do.call(cbind.data.frame, results)
final = cbind(col1,col2, col3,col4, final)

average_col1_col2_dist = (final$col1_col_2osa  + final$col1_col_2lv + final$col1_col_2dl      + final$col1_col_2hamming + final$col1_col_2lcs +     final$col1_col_2qgram  + final$col1_col_2cosine    + final$col1_col_2jaccard + final$col1_col_2jw   + final$col1_col_2soundex)/10

 average_col3_col4_dist =  ( final$col3_col_4osa     +    final$col3_col_4lv       +     final$col3_col_4dl  +     final$col3_col_4hamming +  final$col3_col_4lcs +  final$col3_col_4qgram  +   final$col3_col_4cosine +    final$col3_col_4jaccard  +    final$col3_col_4jw     +   final$col3_col_4soundex)/10

final = data.frame( col1, col2, col3, col4, average_col1_col2_dist,  average_col3_col4_dist)
final = scale(final)

But I keep getting this error:
Error:
! Column 1 must be named.
Use .name_repair to specify repair.
Caused by error in `repaired_names()`:
! Names can't be empty.
x Empty name found at location 1.

Does anyone know how I can fix this?
Thank you!

A: In the process of trying to understand what you're doing, I drifted pretty far from your original code. There isn't anything necessarily wrong with the majority of it!
Your code
As far as your grouping code...
You started with
for(this in that)
   for(this in that)
   {
       {

The brackets nest what's inside the for statement. You need to
for(this in that) {
   for(this in that) {

# or this works
for(this in that)
   {
   for(this in that)
      {

When you specified your for criteria, you went with integers. However, you could just go with the string, as in
for(i in method) { # i is a string

# versus

for(i in 1:length(method)) { # i is an integer

When you wrote the nested for statement you missed a closing parenthesis.
for(j in 1:length(unique(example$group)) # end parentheses missing!

# should have been

for(j in 1:length(unique(example$group)))

# easier to see like this:

for(j in 1:length(
                  unique(
                         example$group
                        )
                  )
    )

Did you know? You can set RStudio to use 'Rainbow parentheses' which is great for ensuring you don't miss closing parentheses or brackets. Go to Tools -> Global Options -> Code (left menu in popup) -> Display (top menu in menu popup) & 'Rainbow parentheses' is the last item in the list. This is what it looks like with my current appearance settings:

When extracting the group, you selected a dataset row, not a unique value.
# this selects jth row, then looks for unique values
groups_j = unique(example$group[j])

# you need to get the unique values, then iterate
group_j = unique(example$group)[j]

# the j goes outside the call for unique()

In this code, you wrote file and file$fsa. I'm assuming this is equivalent to example and example$group, because I don't have whatever is in file.
All of these lines of code do the same thing. Keep in mind that group is in the data frame, but it's an object in the environment on its own, as well.
my_data_i = example[which(example$group == group_j), ] # this would work
my_data_i <- filter(example, groups == group_j)        # this would work
my_data_i <- example[group == group_j, ]               # this would work
my_data_i <- example[example$group == group_j, ]       # this would work

If you iterated over groups instead of indices, you can skip the creation of group_j which is the only time you used j.
for(j in unique(example$group)) {
    my_data_i <- example[example$group == j, ]
}

When you sent the results using i and i alone, you would overwrite the data with each iteration over j.
The first group iteration can go in results[[i]], but the next group, can either be bound to that data or placed in a list within a list.
For example:
results[[1]] <- group 1, method 1
results[[1]] <- rbind(results[[1]], [group 2, method 1])

# or

results[[1]][[1]] <- group 1, method 1
results[[1]][[2]] <- group 2, method 1

Considering those two options for the lists (above), the first will allow your remaining code (creation of final, averages, etc.) to work without any changes. However, if you use the second option (above), that code will require modification.
If you leave for(j with 1:length this will work:
if(j < 2) {
  results[[i]] <- final_i
} else {
  results[[i]] <- rbind(results[[i]], final_i)
}

If you use for(j in unique(example$group)), you could use this:
if(isTRUE(j == unique(example$group)[1])) { # isTRUE() to avoid null errors
  results[[i]] <- final_i
} else {
  results[[i]] <- rbind(results[[i]], final_i)
}

Your nested for statements all in one chunk.
results = list()
for (i in 1:length(method)) {  # bracket missing here; it was in the wrong place
  for (j in 1:length(unique(example$group))) { # missing a parentheses here
    # { # this needs to be after each for statement

    # groups_j = unique(example$group[j]) # you have selected the jth row, not the jth unique

    group_j = unique(example$group)[j] # the selection goes outside the call for unique()
    # use things like print or message to check what your function does
    # print(group_j)
    # message('this is a message ', group_j) # notice the different color in the console?

    my_data_i <- example[group == group_j, ] # this would work

    method_i = method[i]
    name_1_i = paste0("col1_col_2", method_i)
    name_2_i = paste0("col3_col_4", method_i)

    p1_i = stringdistmatrix(my_data_i$col1, my_data_i$col2, method =  method_i, useNames = "string") %>%
      as_tibble(rownames = "a") %>%
      pivot_longer(-1, names_to = "b", values_to = name_1_i)

    p2_i = stringdistmatrix(my_data_i$col3, my_data_i$col4, method =  method_i, useNames = "string") %>%
      as_tibble(rownames = "a") %>%
      pivot_longer(-1, names_to = "b", values_to = name_2_i)

    p1_i = p1_i[,3]
    p2_i = p2_i[,3]

    final_i = cbind(p1_i, p2_i)

    # results[[i]] = final_i # you replace this content everytime you change groups
    # you need to append the values between groups (assuming you want one column per test type)
    # first append, then combine
    if(j < 2) { # use < instead of == to avoid null error
      results[[i]] <- final_i
    } else {
      results[[i]] <- rbind(results[[i]], final_i)
    }
  }
}

My code to accomplish the same task
I've added a few checks and balances to make it more dynamic. You can send any number of columns, methods, or groups to grpComp.
This uses tidyverse, glue, and stringdist.
This first function is called by the other function.
library(tidyverse)
library(stringdist)
library(glue)

strD <- function(c1, c2, mm) { # input column 1; column 2; measurement method
  res <- stringdistmatrix(c1, c2, method = mm, useNames = 'string')
  f_res <- matrix(res) # extract values and flatten
}

This is the distances by group function.
grpComp <- function(fr, methods, grp) { # data frame of columns to compare,
  # methods to use, groups (vector same length as df rows)
  cnames <- names(fr)
  if(length(cnames) %% 2 != 0) {
    message('there are an uneven number of columns to compare')
    break # something's wrong
  }
  if(length(grp) != nrow(fr)) {
    message('there groups vector length must match number of rows in the data')
    break # something's wrong
  }
  # extract distances
  dists <- map(
    method,
    function(j) {
      str_ds <- map_dfc(    # by column sets
        seq(from = 1, to = length(cnames), by = 2),
        function(i) {
          str_gr <- map_dfr( # by group
            unique(grp),
            function(k) {
              as.data.frame(list(  # has to be list for `col.names` to work
                strD(fr[grp == k, cnames[i]],
                     fr[grp == k, cnames[i + 1]], j)),
                optional = F, row.names = NULL,
                col.names = paste0("c", i, i+1, '_', j))
            })        # combine groups by rows
          str_gr
        })            # combine methods by columns
      str_ds
    }) %>% do.call(cbind, .)
  ncnames <- names(dists) %>% substr(1, 3) %>% unique() # determine unique col groups
  for(m in ncnames) { # get averages for each comparison set
    dists <- mutate(dists,
                    "ave_{m}" := rowMeans(across(contains(m))) %>% scale())
  }
  dists <- select(dists, contains('ave'))
}

This is how you would use this code.
test5 <- grpComp(example[, 1:4], methods, example$group)

Even though your function for non-grouped data is working, I thought I would include that code as well.
strComp <- function(fr, methods) { # data frame of columns to compare, methods to use
  cnames <- names(fr)
  if(length(cnames) %% 2 != 0) {
    message('there are an uneven number of columns to compare')
    break # something's wrong
  }
  # extract distances
  dists <- map(
    method,
    function(j) {
      str_ds <- map_dfc(
        seq(from = 1, to = length(cnames), by = 2),
        function(i) {
          as.data.frame(list(  # has to be list for `col.names` to work
            strD(fr[, cnames[i]], fr[, cnames[i + 1]], j)), optional = F,
            col.names = paste0("c", i, i+1, '_', j))
        })
      str_ds
    }) %>% do.call(cbind, .)
  ncnames <- names(dists) %>% substr(1, 3) %>% unique() # determine unique col groups
  for(k in ncnames) { # get averages for each comparison set
    dists <- mutate(dists,
                    "ave_{k}" := rowMeans(across(contains(k))) %>% scale())
  }
  dists <- select(dists, contains('ave'))
}

To use this function:
test4 <- strComp(example[, 1:4], methods)


text:
Q: How to change Processor properties during runtime using Camel? I have a Camel Route Definition written in Java DSL like this:
from(myEndpoint)
.throttle(200)
.to(myOtherEndpoint);

This connects my two endpoints using a Throttler which limits the message flow to 200 messages per second.
I'm looking for a way to change the maximumRequestCount / second during runtime.
So I need to somehow get to the Throttler instance which is called and change the property.
How can I access the Throttler?

A: Ok, I figured it out by myself ...
You need to define your Throttler instance yourself.
Throttler throttler = new Throttler(null, 200);

Then you can use it in your routes like this, because Throttler implements the Processor interface:
from(myEndpoint)
.process(throttler)
.to(myOtherEndpoint);

Any time you like you can change the properties of the throttler.

A: Yeah that is a neat solution.
In Camel 2.0 you can now navigate the runtime processors in the route and thus find any Throttlers and then be able to change it dynamically.
But we are also working on improving the JMX in Camel 2.1 so you can change throttler/delayer and the likes from JMX.
And maybe also improve the Navigate API so you can find in a one liner, eg maybe lookup by id if you provide an id in the route. Or by types so you can filter and only get the Throttlers etc.

A: I am having a Apache camel spring boot application which has 5 instances reading from a kafka topic with a group ID and posting to a REST API. We would like to implement a throttling mechanism across these 5 Apache camel spring boot instances . For example 20K requests per minute to be routed to the  REST API. I read about the correlationExpression feature for Throttling . https://camel.apache.org/components/3.15.x/eips/throttle-eip.html
Let's name camel spring boot applications as A, B, C, D and E Then correlationExpression will only work 20K request per minute for individual instance basis - 20K request per minute for A, 20K request per minute for B, 20K request per minute for C, 20K request per minute for D and 20K request per minute for E Then it will be over loaded for the REST API endpoint.
I need to implement throttling feature across the 5 camel spring boot instances - total request per minute  should be 20K by adding all the instances request rate - i.e, Request per minute in A + Request per minute in B+Request per minute in C+Request per minute in D+Request per minute in E = 20K per minute
But I am not sure how we can configure this correlationExpression connecting the 5 camel spring boot instances so that total request per minute should be 20K requests per minute by considering all requests from these 5 camel spring boot instances.
I would appreciate all the help and guidance.
Throttling multi instance Apache camel spring boot


text:
Q: UITableViewCells not appearing initially I have three UITableViews that should look identical.  Each is placed inside a different subview of a UIScrollView.  As I scroll, I can see each table.  The first table appears perfectly.  However, only the background color shows for the second and third tables.
tableView:cellForRowAtIndexPath: is being called for every row for each table, where I insert a subview into the cell's contentView.  The subview has already been created before this method is called and is reused across the three tables for a given row (in an attempt to make tables look identical).
I made two interesting discoveries:

*

*Although the cell doesn't show initially, it will appear after scrolling to hide the row and then show it again.

*When the cell appears after scrolling, it has been moved from another table.  It no longer appears in the table where it had been showing.

Here's my code:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"PlotCellID";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"PlotCell" owner:self options:nil];

        if ([nib count] > 0)
            cell = self.plotCell;
        else
            NSLog(@"Failed to load AlertCell nib!");
    }

    // Set up the cell...
    NSUInteger row = [indexPath row];
    AppDelegate *del = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    ResultSet *rs = del.resultPlots;

    CPTGraphHostingView *cellPlotView = [rs.hostingViews objectAtIndex:row];
    cellPlotView.frame = cell.contentView.bounds;

    cellPlotView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    [cell.contentView insertSubview:cellPlotView atIndex:0];

    return cell;
}

cellPlotView refers to the subview already created.
Any idea how to fix this so I can see all my tables correctly showing as I scroll? It's as if the cells can't reuse content. Thanks.

A: View can have only one superview. So create 3 identical CPTGraphHostingView views.