text:
Q: Multiple adsense publisher id's mixing and matching etc Does anyone know the adsense TOS regarding using more than one publisher ID
on a site.
can a page have 1 ad using publisher ID#1 and another ad using publisher ID#2
    i.e the top banner ad is using one pubid and the bottom banner ad is using another
    pubid
This is important as I have been noticing some very strange results lately, but
I want to make certain what I am doing is 'legal' before saying more..

A: You are allowed to have multiple Adsence id's on the same site, even the same page as long as the total number of adds per page is not exceeded (I don't think extra adds will show up if you have more than 3 anyway.)
There are a number of sites around that allow you to include your Adsence ads with your content. Take a look at these:

*

*www.weebly.com

*www.hubpages.com

*www.triond.com

*More...

Its 100% allowed to use more than one publisher ID on a single page or across a website provided the total number of ad units per page is not exceeded (that per page not per account.)

http://productforums.google.com/forum/#!topic/adsense/eBwPjDixtUY

The answer is that yes, we do allow this. But before you place your ad code on the same page or site as another publisher, here are a few important points to keep in mind:

*

*The maximum number of products per page will remain the same.

*If you don't own the site, you'll need to receive permission from the site owner to display your ads on their pages.

*We're unable to divide earnings between accounts, so any revenue generated will be credited to the account associated with the ad unit that was clicked or viewed.
  Any shared site that displays Google ads must also comply with our program policies.

*You're responsible for the content of any page where your ad code appears. Before placing your ad code on another publisher's site, we recommend reviewing the site for any policy violations.
And one final tip before giving your code to another publisher -- try using our Allowed Sites feature to monitor where your ads are appearing and keep your account in good standing.

http://adsense.blogspot.com/2008/07/sharing-your-ad-space.html


text:
Q: How can I add a google play badge to my header and footer? How I can add images or edit html for the header and footers within wordpress.
I am looking in the header and footer sections under both "Theme Panel" and "Appearance" but can't figure out how to add html anywhere for adding the Google Play badge.

A: You can edit your header and footer file or you can insert these codes in the functions.php file
function add_google_code($url="",$utm_code="",$utm_campaign=""){ ?>
<a href='<?php echo $url ?>?utm_source=<?php echo $utm_code ?>&utm_campaign=<?php echo $utm_campaign ?>&pcampaignid=MKT-Other-global-all-co-prtnr-py-PartBadge-Mar2515-1'>

add_action('wp_head','add_google_code','#url','#utm_code','#utm_campaign');
add_action('wp_footer','add_google_code','#url','#utm_code','#utm_campaign');

Now save it and refresh the main site you can see your badge.
You need to replace the
#url with your app url
#utm_code utm code with the utm code ...

A: First of all, you can modify your header and footer from either using FTP client else from WP admin dashboard. if you are not familiar with FTP the please follow following steps.
1.Go to WP admin dashboard.
2.Under the Appearance menu, there is an option for edit theme. name it Edit.
3.In right side section list of files under the theme, ll be list.
4.Click on header.php and footer.php for edit header and footer accordingly.
please refer this for Google badge and paste the code in header or footer as per your needs.
I hope its useful and solve your issue.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Как запустить фрагмент при нажатии на уведомление ЗДравствуйте, мне необходимо реализовать открытие активности с определенным фрагментом.
Как это реализовать?
Само собой в сервисе это не работает:
    Intent intent = new Intent(this,ExamFragment.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(this,0,intent,0);

Но зато работает этот код, он запускает активность и старый фрагмент(который был последний открыт):`
    Intent intent = new Intent(this,Activity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(this,0,intent,0);

Как при нажатии на уведомление открывать активность с нужным фрагментом?

A: Невозможно отобразить фрагмент без активити.
Вам надо запустить активити так, чтобы она знала что ей нужно отобразить строго определённый фрагмент.
Для этого поместите что-нибудь в интенет запуска активити, в активити вытащите это и в зависимости от него отображайте требуемый фрагмент


text:
Q: R: Lattice How to remove white space between bars and x axis? I am new to R and am using lattice to create a clustered bar graph. I wrote the following code.
nature <- read.table(text = "Nature_of_recreation, Familiarity_with_the_partner, Count
Danced, Not familiar at all, 21
Danced, Not very familiar, 22
Danced, Very familiar, 22
Sketched, Not familiar at all, 6
Sketched, Not very familiar, 17
Sketched, Very familiar, 16
Dined, Not familiar at all, 16
Dined, Not very familiar, 14
Dined, Very familiar, 10
Swimmed, Not familiar at all, 6
Swimmed, Not very familiar, 15
Swimmed, Very familiar, 11
Played, Not familiar at all, 1
Played, Not very familiar, 6
Played, Very familiar, 7
Dreamed, Not familiar at all, 5
Dreamed, Not very familiar, 17
Dreamed, Very familiar, 10",
                     header = TRUE, sep = ",")
colors = c("lightsalmon3", "lightgoldenrod2", "cadetblue4")
lattice::barchart(data = nature, origin = 0, Count ~ Nature_of_recreation,
                  groups = Familiarity_with_the_partner,
                  xlab = list(label = "Nature of recreation", font = 2, cex = 1),
                  ylab= list (label = "Number of students", font = 2, cex = 1),
                  labels = TRUE, auto.key = list(space="top", columns= 3),
                  par.settings = list(superpose.polygon = list(col = colors)))

The output looks all good, except:

*

*It has a white space in between bars and the X-axis.

*It does not have values displayed on top of each bar.

Can anyone please help me fix these issues?


text:
Q: WLAN Networkmanager Xubuntu 18 As I was asking about WIFI that was possible to enable in the earlier question, I now see the connection enabled, a pop-up tells to "view the network menu..." but that network menu is nowhere to find.
And I can not view available WIFI connections meaning I have no way to select and click any from the display, however, I can as always, see the wired connection for the Ethernet in "Network Connections" though.
WIFI and Bluetooth were both possible with Ethernet to enable and disable in another view from the display.
In my Ubuntu 16 on a Hp Mini anno 2010 I have the sound, battery, contrast seen in the display's right corner but they are like the connections view not missing (even only WIFI is critical here)  What can I do?
Many thanks indeed.
9th Generation Intel® Core™ i7-9750H Processor (2.60GHz, up to 4.50GHz with Turbo Boost, 6 Cores, 12MB Cache)
Wireless
802.11 AC (2 x 2) & Bluetooth® 4.1
https://www.lenovo.com/us/en/laptops/legion-laptops/legion-y-series/Lenovo-Legion-Y540-15/p/88GMY501214


text:
Q: How to exclude a currently selected item from an exception handling I'm relatively new to C# working on a project currently where I want to exclude an item that is edited from an exception. In this scenario a user can edit an appointment including the appointment, however; there can not be overlapping appointments. When I run my program and edit the appointment, the exception is checking against the appointment being edited which it shouldn't. Can someone advise me on how to do this?
foreach (var appt in AppointmentScreen.ListOfAppts)
{
    if (selectedStart <= appt.Start && selectedEnd > appt.Start && (!(SelectApptID >= 0)) || SelectApptID >= 0)
    {
        overlaping = true;
    }

    if (appt.Start <= selectedStart && appt.End > selectedStart && (!(SelectApptID >= 0)) || SelectApptID >= 0)
    {
        overlaping = true;
    }
}

if more information is needed please let me know. I will be checking periodically throughout the day.
thanks for all the help in advance

A: Does the appointment being edited have an unique id you can check against with?
If not what about add a Guid property to the appointment object and with a simple condition skip if it's current? Something like:
foreach (var appt in AppointmentScreen.ListOfAppts)
{
    if (appt.Id == CurrentAppt.Id) continue;  //this condition skips the appointment being edited
    if (selectedStart <= appt.Start && selectedEnd > appt.Start && (!(SelectApptID >= 0)) || SelectApptID >= 0)
    {
        overlaping = true;
    }

    if (appt.Start <= selectedStart && appt.End > selectedStart && ((SelectApptID >= 0)) || SelectApptID >= 0)
    {
        overlaping = true;
    }
}

In your Appointment class:
public class Appointment
{
    public Guid Id { get; set; }
    .
    .
    .
}

A: I'm not sure what SelectedApptId>=0 means but in order to verify if the current interval overlaps with any other interval you could do it like this:
var overlapping = AppointmentScreen.ListOfAppts.Any(appt=> appt.Start <= selectedEnd && appt.End >= selectedStart);


text:
Q: Why is Jackson messing with the parsing of application/javascript? so I have this RESTful Spring Boot API that reads a JS file from the file system and exposes the contents of this file. Currently, this is how I return the contents of that JS file to the API consumer:
return ResponseEntity.ok().header("Content-Type", "application/javascript").body(jsText) // jsText is a String variable

This is (partially) what API consumer sees:
(function (w, d, s, l, i) {
    w[l] = w[l] || [];
    w[l].push({});
 ....)

Now I'm working on a totally unrelated feature that required me to introduce a config class to configure Jackson serialization of java.time classes:
@Configuration
class WebConfig extends WebMvcConfigurerAdapter {

    private final static String DATE_TIME_PATTERN = "yyyy-MM-dd'T'HH:mm:ss'Z'"

    @Autowired
    private ObjectMapper objectMapper

    @Override
    void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        MappingJackson2HttpMessageConverter jacksonConverter = new MappingJackson2HttpMessageConverter()
        DateFormat dateFormat = new SimpleDateFormat(DATE_TIME_PATTERN, Locale.default)

        objectMapper.setDateFormat(dateFormat)
        objectMapper.registerModule(new JavaTimeModule())

        jacksonConverter.setObjectMapper(objectMapper)
        converters.add(jacksonConverter)

        super.configureMessageConverters(converters)
    }
}

And this is where my problems start. As soon as I added the converters.add(jacksonConverter) line, the response from that same endpoint changed to this:
"(function (w, d, s, l, i) {\n  w[l] = w[l] || [];\n  w[l].push({});\n..."

(notice the " and \n characters in there)
Now, what am I doing wrong here? If I look at the response headers, it still says application/javascript after the change, but why have the contents changed?
Can I avoid / work around this somehow? I mean, I still need the part about JavaTimeModule, but would like to avoid breaking the API consumers (they can't parse the version with " and \n...)
Thanks!

A:
is is how I return the contents of that JS file to the API consumer

since you have your javascript in file and not dynamic Why dont you go to the standard for spring to expose the resources?
In your WebConfiguration (the class that extends WebMvcConfigurerAdapter) override addResourceHandlers method
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry)   {
    registry.addResourceHandler("/javascript/**").addResourceLocations("classpath:/static/");
}

All you need then is to put your file under src/main/resources/static and request your file, lets say your file name is script.js and you are running your server on localhsot:8080, the request will be
http://localhost:8080/javascript/script.js

A: I managed to fix it via configuration items on application.yml:
spring:
  jackson:
    date-format: "yyyy-MM-dd'T'HH:mm:ss'Z'"
    serialization:
      write_dates_as_timestamps: false

With these configs in place, I removed the WebConfig class and everything works fine: I have both the JS rendering and the java.time formatting working as expected.


text:
Q: accept() return value when there is no pending connection I make simple server.c that doing this :

*

*listening to port 7705.

*accept the incoming connection from "Client-x".

*while there is no pending connection, then receive data from "Client-1".

*if there is pending connection from another client then goto step second.

and this is the code
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>

int main(int argc, char *argv[])
{
     int sockfd, newsockfd, portno;
     socklen_t clilen;
     char buffer[256];
     struct sockaddr_in serv_addr, cli_addr;
     int n;
     if (argc < 2) {
         fprintf(stderr,"ERROR, no port ..\n");
         exit(1);
     }
     sockfd = socket(AF_INET, SOCK_STREAM, 0);
     if (sockfd < 0)
        perror("ERROR opening socket");
     bzero((char *) &serv_addr, sizeof(serv_addr));
     portno = atoi(argv[1]);
     serv_addr.sin_family = AF_INET;
     serv_addr.sin_addr.s_addr = INADDR_ANY;
     serv_addr.sin_port = htons(portno);
     if (bind(sockfd, (struct sockaddr *) &serv_addr,sizeof(serv_addr)) < 0)
         p error("ERROR on binding");
     listen(sockfd,5);
     clilen = sizeof(cli_addr);
    accpt:
     while (newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen) < 0)
    {
    /* i don't know return value for "there is no pending connection" in accept() function, so i use -1 value" */
     bzero(buffer,256);
     n = read(newsockfd,buffer,255);
    ....... // Process data, and etc //
    }
    goto accept
     }

A: Blame it on precedence.
Original:
while (newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen) < 0) { ...}

Fixed version:
while ((newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen)) < 0) { ...}
   // ^           ?                                                       ^ ?

Without the extra parentheses, the < takes precedence ( binds tighter than ) over the =, and the statement would be evaluated as while (newsockfd = (accept(sockfd, (struct sockaddr *) &cli_addr, &clilen) < 0) ) { ...} , which assigns the result of the < comparison to newsockfd, which is clearly not the intention.
The above is a good reason to avoid compound assignments, and instead use an idiom like this:
while (1) {
  newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen);
  if (newsockfd >=  0) break;
  ...}

BTW: in the OQ, the direction of the < is also completely wrong; the stuff inside the while {...} seems to handle an incoming connection, and that would need a filedescriptor >= 0 .

A: If there are no pending connections, accept won't return; it will block until there is a connection, and then it will return. You can make it return immediately by making the socket non-blocking, but by default, they are blocking, and the aforementioned behavior holds.

A:
i don't know return value for "there is no pending connection" in accept() function

There isn't one. It doesn't return until there is a connection to accept. It blocks.


text:
Q: How to use this row in Xslt and how to sort the list to get the information come under right channel when transformin to xhtm with xlst I wonder if somebody could help me!
I have 4 files of these http://xmltv.xmltv.se/1.bluemovie.de_2019-10-27.xml
I have merged them from 4 to 1
While creating xslt file I now need to make 4 channels in xslt file
The problem I am having now is to sort these 4 lists so they come under right channel.
I don´t know if I have to split the lists again or can I just sort them.
Now when I read the values it comes like a huge list.
The problem is how to read this line to extract values for each channel under a row.
<programme channel="1.bluemovie.de" start="20191027060000 +0000" stop="20191027080000 +0000">
<title lang="de">Der Voyeur 2</title>

I guess if I wont to have the programs under header of the right channel I have write right values from the row I posted.
With other words is there any way to sort the channels using the inforamtion in the code above?
I would really appreciate a littel help


text:
Q: Code Profiling in Visual Studio 2005 I have a Visual Studio 2005 Solution workspace which in turn has 8 projects included in it. I want to profile the complete code(all the projects) and get some measure about the absolute cycles taken by each function to execute, or at least percentage cycle consumptions.
I checked out help for VS 2005, and also the project setiings options but could not find any pointers on hwo to get the profile info.
Any help regarding this would be beneficial.
-AD.

A: If your application is not particularly processor intensive, redgate ANTS Profiler is a good choice - the line-by-line stats can come in quite handy, and the whole product is clean and well-designed.
If your app needs a lot of CPU to operate normally, however, most of the .NET profilers on the market won't be able to handle it. The only two that I have ever found that will work for a really heavy-weight application are JetBrains dotTrace and YourKit. The two are very similar, which is not surprising, given that YourKit seems to have been started by a former JetBrains employee. I personally prefer dotTrace, but that may just be because that is what I used first, and there has never been any good reason to switch.
I have tested ANTS, AQTime, DevPartner, GlowCode, Borland OptimizeIt and Intel VTune, and all of them have too much overhead to handle a demanding application. (VTune is a possible exception, but it is so horribly complex to configure and use that I was never able to figure out exactly what it could handle. It is also very expensive.)

A: I guess the inbuilt profiler of Visual Studio 2005 comes onyl with the Developer Edition and Team Edition. I have a Professional edition which, it seems doesnot have the inbuilt profiler tool.
-AD

A: I've used both the profiler in Compuware's DevPartner (I like to still call it "TrueTime") and Rational's Quantify. I always liked Quantify better, but as I've moved between companies DevPartner is usually already the "standard".
Both are expensive, but they (seem to) add so much value that any commercial shop should have no problem investing in some seats.
Quantify didn't require special rebuilds of the project – which was GREAT. It also crashed less (that's not saying much, it had its own issues). DevPartner also tends to break as each new version of Visual Stuido was release (maybe this is better now?).  Buy the yearly maintenance agreement if you go this way.
That said, I've often just write a class remembers the time at construction and spits out (log file) the elapsed time in its destructor. I used QueryPerformanceCounter.  I'd stick this class at the top of the function I'd want to time. You could get fancy with making it a macro, use the preprocessor to include this class only under a special build…

A: I recommend you EQATEC profiler which also includes in its site a tracer.
Also it's free and easy to use.
alt text http://www.eqatec.com/tools/profiler/profiler-logo.gif

A: We use DevPartner with Visual Studio 2005. It gives you performance analysis of the specific projects in your solution you want to look at. We also use it for memory management analysis, and error analysis. Is commercial tool, so it's not free.

A: Red-gate's Profiler is great for this.

A: I use Jebrains profiler is very easy to use and performs very well too.

A: If your app needs a lot of CPU to operate normally, however, most of the .NET profilers on the market won't be able to handle it.
I have used a trial version of RedGate Ant's profiler on an optimizing algorithm that normally uses up to 100% CPU on a single core machines and though slow it managed to get through and report all I needed to know. Extremely helpfull tool. I wonder what kind of algorithms have you run on the Ant's profiler.
Has anyone used the VS profiler ?


text:
Q: Контроллер asp net core не может распарсить post запрос Привет, у меня есть контроллер с методом:
    [HttpPost]
    [Route(FirstStepFilledRoute)]
    public IActionResult OnFirstStepFilled(
        PdoResultViewModel pdoResultViewModel,
        int id)
    {}

И форма, которая этот контроллер дергает:
@model WebApp.Models.PdoResultViewModel
<form asp-route="@Model.Route" method="post">
@for(int i = 0; i < Model.PdoQuestionSetViewModels.Length; i++){

            @Model.PdoQuestionSetViewModels[i].Value

            @for(int j = 0; j < Model.PdoQuestionSetViewModels[i].PdoQuestionAnswerViewModels.Length; j++){

                        @Html.HiddenFor(m => m.PdoQuestionSetViewModels[i].PdoQuestionAnswerViewModels[j].Id)
                        @Html.CheckBoxFor(m => m.PdoQuestionSetViewModels[i].PdoQuestionAnswerViewModels[j].IsChecked)

                        @(j+1).
                        @Model.PdoQuestionSetViewModels[i].PdoQuestionAnswerViewModels[j].Value

            }

}
    <input type="submit" class="btn btn-primary" value="Далее" />
</form>

Модель:
public sealed class PdoResultViewModel
{
    public int Id { get; set; }
    public PdoQuestionSetViewModel[] PdoQuestionSetViewModels { get; set; }
    public string Message { get; set; }
    public string Route { get; set; }
}

public sealed class PdoQuestionSetViewModel
{
    public string Value { get; set; }
    public PdoQuestionAnswerViewModel[] PdoQuestionAnswerViewModels { get; set; }
}

public sealed class PdoQuestionAnswerViewModel
{
    public int Id { get; set; }
    public string Value { get; set; }
    public bool IsChecked { get; set; }
}

При сабмите формы, я удачно попадаю в свой метод контроллера. Но часть данных не не приходит: pdoResultViewModel.PdoQuestionSetViewModels всегда null.
Я точно знаю, что данные пересылаются
Request.Form. содержит в себе необходимое количество заполненных  KeyValuePair.
Примерно следующее показывает консоль firefox'a:
...
PdoQuestionSetViewModels[0].PdoQuestionAnswerViewModels[0].Id:"15728"
PdoQuestionSetViewModels[0].PdoQuestionAnswerViewModels[0].IsChecked:"false"
...

Что я мог сделать неправильно? Почему контроллер не может распарсить сложную модель?

A: Не дождавшись ответа переписал на более легкую вью-модель: теперь с формы в контроллер отправляю список {id: number, isChecked: bool}, а всё остальное во view-bag.
А вообще такое ощущение, что либо форма строит json в неправильном формате, либо нужна была какая-то магия с аттрибутами, либо наличие в модели конструктора или какого-то метода сбивает рефлексию с толку.


text:
Q: How to call an API dynamically in functional programming paradigm My application receives http requests from humain clients.
My application needs to call only one API, among 12 other APIs, depending on one specific data in the input it receives.
My first thought was of course
// requestPrice.js

const service = req.body.service

const APIs = {
    ser1: callAPI1,
    ser2: callAPI2,
    ser3: callAPI3,
    // ...
    ser12: callAPI12,
}

return APIs[service](req.body)

This works fine but I guess needs some refactoring to make it SOLID compliant.
Normally in OOP I would go with one of the design patterns such as strategy or chain of responsibility maybe.
However I'm using the functional programming so a bit different.
I thought of doing the following:
// ser1.js
export default callAPI(data) {
    // code 1
}

// ser2.js
export default callAPI(data) {
    // code 2
}

// ser3.js
export default callAPI(data) {
    // code 3
}

//...

// ser12.js
export default callAPI(data) {
    // code 12
}

// requestPrice.js
const service = req.body.service
const api = require(`./${service}`)

return api(req.body)

This looks much better than the first version as it follows much better the Single responsibility principle. Plus it follows Open/Closed principle as well, I guess, as the requestPrice.js won't change if a 13th api is to be added.
In the other hand, I should be able to easily unit test even the file requestPrice.js as the req can be injected.
Is it SOLID principles compliant to do so or is there a better and cleaner way?

A: I would suggest a factory method (implemented as a curried function in FP) so that decision of which service to call and what to do in each service becomes separated. request.body should be passed to the returned impl function.
function createService(body) {
  if(checkInput(body) == [something]) return service1;
  else if(checkInput(body) == [something2]) return service2;
  ..
}

function service1(body) {..}
function service2(body) {..}
..

let service = createService(req.body);
service(request.body);

I haven't put it in different files but you may do so. Now createService can be in a different module. And each impl (service1, service2, etc) can be in their own separate files, and the caller of service doesn't need to know which impl to call, hence maintaining Dependency inversion. Higher level module doesn't know about the lower level module. :)


text:
Q: "new System.Timers.ElapsedEventHandler(DoStuff)" call did not work I'am trying to create watch folder aplicaction in C# that will do an action when new file will arrive. Since the watched folder is on GPFS share I'am unable to use FileSystemWatcher (which works fine for me in NTFS). So I've based the app on other collegue solution.
The app shows nicely "Timer starts" message but when it comes to
timer.Elapsed += new System.Timers.ElapsedEventHandler(DoStuff);

it did not calls the DoStuff method - "Starting new files proc" message never show up. What I've done wrong? Here is complete code:
namespace MonitorFolderActivity
{
    public partial class frmMain : Form
    {
        List<string> fileList = new List<string>();
        System.Timers.Timer timer;
        DateTime LastChecked;

        public frmMain()
        {
            InitializeComponent();
        }
        private void abortAcitivityMonitoring()
        {
            btnStart_Stop.Text = "Start";
            txtActivity.Focus();
        }

        private void startActivityMonitoring(string sPath)
        {
            if (sPath.Length < 3)
            {
                MessageBox.Show("You have to enter a folder to monitor.",
                    "Hey..!", MessageBoxButtons.OK, MessageBoxIcon.Stop);

                abortAcitivityMonitoring();
            }
            else
            {
                TS_AddLogText(string.Format("Timer starts\r\n"));
                timer = new System.Timers.Timer();
                timer.AutoReset = false;

                timer.Elapsed += new System.Timers.ElapsedEventHandler(DoStuff);
            }
        }

        private void stopActivityMonitoring()
        {
            TS_AddLogText(string.Format("Timer stops\r\n"));
            this.timer.Stop();
        }

        private void DoStuff(object sender, System.Timers.ElapsedEventArgs e)
        {
            TS_AddLogText(string.Format("Starting new files proc\r\n"));
            LastChecked = DateTime.Now;

            string[] files = System.IO.Directory.GetFiles("D:\\MEDIAIN\\", "*", System.IO.SearchOption.AllDirectories);

            foreach (string file in files)
            {
                if (!fileList.Contains(file))
                {
                    fileList.Add(file);
                    TS_AddLogText(string.Format(file));
                }
            }

            TimeSpan ts = DateTime.Now.Subtract(LastChecked);
            TimeSpan MaxWaitTime = TimeSpan.FromMinutes(1);

            if (MaxWaitTime.Subtract(ts).CompareTo(TimeSpan.Zero) > -1)
                timer.Interval = MaxWaitTime.Subtract(ts).TotalMilliseconds;
            else
                timer.Interval = 1;

            timer.Start();
        }

        private delegate void AddLogText(string text);
        private void TS_AddLogText(string text)
        {
            if (this.InvokeRequired)
            {
                AddLogText del = new AddLogText(TS_AddLogText);
                Invoke(del, text);
            }
            else
            {
                txtActivity.Text += text;
            }
        }

        private void btnStart_Stop_Click(object sender, EventArgs e)
        {
            if (btnStart_Stop.Text.Equals("Start"))
            {
                btnStart_Stop.Text = "Stop";
                startActivityMonitoring(txtFolderPath.Text);
            }
            else
            {
                btnStart_Stop.Text = "Start";
                stopActivityMonitoring();
            }
        }

        private void lblActivity_Click(object sender, EventArgs e)
        {

        }

        private void lblToMonitor_Click(object sender, EventArgs e)
        {

        }
    }
}

A: There are few issues in your code.
First of all you are not setting the time at which timer should elapse, which means it will read the default value which is

100 ms

Secondly you are not starting your timer. You need to add this line to your code in this method startActivityMonitoring else statement.

timer.Interval = yourdesiredinterval;
timer.Start();

Thirdly, as you are doing stop and start (by looks of your code) you should not create a new timer on each call of your startActivityMonitoring method. Rather you should do this
If(timer == null)
{
    timer = new System.Timers.Timer();
    timer.AutoReset = false;
    timer.Interval = yourinterval;
    timer.Elapsed += new System.Timers.ElapsedEventHandler(DoStuff);
}
timer.Start();

A: In your else clause, you never start the timer. Here's a fix:
else
{
    TS_AddLogText(string.Format("Timer starts\r\n"));
    timer = new System.Timers.Timer();
    timer.AutoReset = false;
    timer.Elapsed += new System.Timers.ElapsedEventHandler(DoStuff);
    timer.Start();
}


text:
Q: If-else JavaScript not working Whats wrong with this script? It resets itself and the second div never changes. I'm missing something? I'm thinking I probably need a better way to handle the variable so if someone knows of one that would be awesome. This is my jsfiddle testing script:
var lang="de";

$('#en').click(function () {
    lang="en";
});
$('#de').click(function () {
    lang="de";
});
$('#es').click(function () {
    lang="es";
});

function showtext() {
    $('#text').text(lang);
    if (lang="en") {
        $('#cur').text(lang);
    }
    else if (lang="de") {
        $('#cur').text(lang);
    }
    else if (lang="es") {
        $('#cur').text(lang);
    }
}

showtext();

setInterval(function () {
    showtext();
}, 2000);

Demo on jsfiddle

A: Your function is doing assignment through =, for comparison you must use ==.
function showtext() {
    $('#text').text(lang);
    if (lang == "en") {
        $('#cur').text(lang);
    }
    else if (lang == "de") {
        $('#cur').text(lang);
    }
    else if (lang == "es") {
        $('#cur').text(lang);
    }
}

jsFiddle Working demo

A: Your comparisons are actually assignments try below:
$('#text').text(lang);
    if (lang=="en"){
        $('#cur').text(lang);
    }
    else if (lang=="de"){
        $('#cur').text(lang);
    }
    else if (lang=="es"){
        $('#cur').text(lang);
    }

A: You have an if loop that does exactly nothing (and it uses the wrong comparison operator). Try this instead:
http://jsfiddle.net/Su3RC/158/
function showtext() {
    $('#text').text(lang);
    $('#cur').text(lang);
}


text:
Q: git branches are very confusing for me (creating new branches, features) I've tried to create feature branch in GIT.
What I trying to create
A -- B -- C ------ D
      \
       E --

Where first line is development, second line is feature branch.
How I need to create feature branch? Like this?
git checkout -d myFeature

After changing files:
git add .
git commit -m "My awesome commit"

And then push
git push origin myFeature

Merge in dev branch
git merge myFeature

And then commit and push again. Is this a right way?
Can a branch created from commit?
What means --track flag in GIT and when i need to use it?
What is the difference between branch and origin/branch?
Can somebody explain me about branches?

A:
How I need to create feature branch?

If you're trying to create myFeature branch from commit hash B
git checkout -b myFeature B

Note the syntax error in your posted question error: unknown switch 'd'

Merge in dev branch

Don't forget to checkout your dev branch first, and then merge myFeature
git checkout dev
git merge myFeature

And then commit and push again. Is this a right way?

No need to commit again, the successful merge will create the commit.

Can a branch created from commit?

Yes, as demonstrated in step 1

What means --track flag in GIT and when i need to use it?

I will refer you to the git branch documentation
-t, --track
    When creating a new branch, set up branch.<name>.remote and branch.<name>.merge configuration
    entries to mark the start-point branch as "upstream" from the new branch. This configuration will
    tell git to show the relationship between the two branches in git status and git branch -v.
    Furthermore, it directs git pull without arguments to pull from the upstream when the new branch
    is checked out.

    This behavior is the default when the start point is a remote-tracking branch. Set the
    branch.autoSetupMerge configuration variable to false if you want git checkout and git branch to
    always behave as if --no-track were given. Set it to always if you want this behavior when the
    start-point is either a local or remote-tracking branch.

What is the difference between branch and origin/branch?

branch should refer to your local copy, and origin/branch refers to the copy on the remote server.

Can somebody explain me about branches?

This is verging on off-topic for SO as too-broad, but here's a wonderful free interactive tutorial that should answer this for you in addition to the git book and the aforementioned git branch documentation.


text:
Q: what is the linux-kernel-devel equivalent in 12.04.2 LTS 3.5.0? apologies for the noob question, but when I try to
sudo apt-get install Linux-kernel-devel

I get the following:
sudo apt-get install linux-kernel-devel
Reading package lists... Done
Building dependency tree
Reading state information... Done
E: Unable to locate package linux-kernel-devel

I have tried the following:
sudo apt-get install linux-headers-$(uname -r)
sudo apt-get install build-essentials
sudo apt-get install Linux-headers-generic

with no joy... any suggestions?

A: Executive Summary
You probably want to install the package called linux-headers-generic.
If running uname -r gives you something other than generic after the version number, substitute that for generic in linux-headers-generic. (This might be server or generic-pae on some installations of some Ubuntu releases, and there are a few other occasional kernel "flavors.")
Since you most likely needs this so that you can build a driver (which might be automated, you might not be "building it yourself"), it's a good idea to install build-essential too to make it so you'll probably have all the necessary tools.
Full Explanation
To the best of my knowledge, no operating system has a package called Linux-kernel-devel. This is for two reasons:

*

*Package names starting with capital letters are extremely rare, for any Unix-like OS.

*GNU/Linux operating systems typically name their kernel-related packages so that the names contain the word kernel or the word linux, but not both. (On Ubuntu, it's the word linux.)

It's common for kernel-related packages on systems that use the Red Hat Package Manager (rpm) and related utilities to have kernel in the name of their packages. For example, Mageia has a number of packages whose names start with kernel and end in devel. These packages almost always (on Mageia and any OS that has them) provide the header files needed to build drivers from source for use with the kernel. They may also provide related utilities to facilitate. These packages:

*

*do not provide the full source code of the kernel. That's provided by other packages.

*do not provide a pre-compiled, usable kernel. That's provided by other packages.

*do not provide a compiler or most other purpose build tools. Those, too, are provided by other packages.

In Ubuntu, as can be seen in the list here, the packages that provide kernel headers have names that start with linux-headers. Usually the correct package to install is linux-headers-generic. However, to be sure of what package to install to get headers that correspond to your currently running kernel, run:
uname -r

You'll get output that looks something like:
3.5.0-36-generic

That is, you'll have a version number (which will include . characters and usually at least one -), followed by a -, followed by one or more words indicating which kind of kernel you are running.
If you just want the headers for the specific version you happen to be running now, you could install the package whose name is linux-headers-* where * is replaced by the full output of uname -r. For example, on my system, I could run:
sudo apt-get update && sudo apt-get install linux-headers-3.5.0-36-generic

I could even automate it:
sudo apt-get update && sudo apt-get install linux-headers-`uname -r`

These approaches are equivalent, but they are not usually the best way to go.
Instead, you usually will want to install the metapackage that always provides the newest kernel headers as an update (by perpetually depending on whatever header package is newest). This parallels the way your compiled, running kernel is installed and gets updated. To do that, look just at the part of uname -r's output after the version number. That is, if uname -r gives you 3.5.0-36-generic, take just the generic part.
Then install the package called linux-headers-* where * is replaced by that part. So, on my system, it would be linux-headers-generic and one way I could install it would be to run:
sudo apt-get update && sudo apt-get install linux-headers-generic

For most people it is linux-headers-generic, but depending on what Ubuntu release you're running, what architecture and type of device you're running it on, and how it is installed and configured, other possibilities include generic-pae, highbank, omap, server, and virtual.
Related Packages
Header files facilitate developing and compiling/building software that uses facilities provided by the software whose header files are being used. The most common reason you might need kernel headers is if you are going to build a driver (a kernel module) from source code. Some applications, like VMware and VirtualBox, will sometimes require this, and will automate the build themselves.
In addition to header files, to build software a compiler and other tools are needed. To maximize the likelihood that you have the necessary tools, it's a good idea to install the build-essential package also.
It's uncommon for anyone to need the actual full kernel source code (unless, of course, you're planning on building your kernel from source). But if you do need that, you'll have to install another package too. In Ubuntu the package for full kernel source code is called linux-source. (This is in keeping with the Debian/Ubuntu convention of naming packages that provide substantive parts of the Linux kernel linux rather than kernel.)
If You Still Have Trouble
If you try to install any of these packages but experience problems, and you want help, then you will have to include the complete and exact text from the Terminal, including the lines where you typed commands. The best way to provide this is by editing your question, but if it is too long, you can paste it somewhere like http://paste.ubuntu.com and provide us with the URL where we can access it.
If you comment on this question, I'll be notified. You can edit your question and also comment here to call attention to the information you've provided in your question. (Important information is best kept in questions and answers.) Good luck!

A: As the report said (E: Unable to locate package linux-kernel-devel)
There are no packages like that.
You can install every kernel version you want by downloading the debian kernel packages from here
For example; we want to install kernel 3.9.8 (i386 architecture);
Download all **i386.deb packages And also ***all.deb package to a folder.
Get in to the folder with cd command in terminal;
sudo dpkg -i *.deb
sudo update-grub2
sudo reboot

This will install the kernel version you want. You can analyse the versions of the kernel mainline and longterm versions in this site

A: You'll have to map out yourself which specific deb's you need, but there is the debs you will need in Ubunut's kernel builds.
Honestly I'd first check with sudo apt-get update and then sudo apt-get dist-upgrade to make sure your running the latest kernel and won't need to do this again shortly.
Next look through the kernel build listing for your version that matches your uname -r. You need to look in each builds build.log to find out what head version they are mapping that build to. I have 3.5.0-34#55 listed as my kernel but this really maps out to build 3.5.7.14-quantal. Install all the debs that correspond with that version to get your headers and such, and make sure you've got your build tools with sudo apt-get install build-essential
Your mileage may very though depending on what you plan to do with the devel files.

A: linux-kernel-devel is the name of a SUSE/Redhat package providing things like genksyms.
A very quick Google suggests that linux-headers-generic provides genksyms on Debian/Ubuntu.


text:
Q: Approve a pull request I need to programmatically approve a pull request, but I keep getting exceptions.
If I do this, then I catch - "System.AggregateException: 'One or more errors occurred. (Method Not Allowed)'
Inner Exception: VssServiceResponseException: Method Not Allowed".
"System.AggregateException: 'One or more errors occurred. (Method Not Allowed)'
Inner Exception: VssServiceResponseException: Method Not Allowed"
var pr = new GitPullRequest
        {
            MergeStatus = PullRequestAsyncStatus.Succeeded,
            Title = $"PR AUTO from {SrcBranch} into {TrgtBranch}",
            Description = $"PR AUTO from {SrcBranch} into {TrgtBranch}",
            SourceRefName = SrcBranch.Name,
            TargetRefName = TrgtBranch.Name,
            Repository = rep,
            AutoCompleteSetBy = new IdentityRef(),
            Reviewers = new IdentityRefWithVote[]
                {
                    new IdentityRefWithVote
                    {
                        DisplayName = nameReviewer,
                        Id = idReviewer,
                        ImageUrl = imageUrl,
                        ReviewerUrl = reviewerUrl,
                        UniqueName = uniqueName,
                        Url = url
                    }
                };

            var createPr = gitClient.CreatePullRequestAsync(pr, Project, RepositoryId).Result;

            var getPr = gitClient.GetPullRequestByIdAsync(createPr.PullRequestId).Result;

            var reviewer = new IdentityRefWithVote
            {
                Vote = 10
            };

            var updateReviewer = gitClient.UpdatePullRequestReviewerAsync(reviewer, repository.Id, pullRequestId, reviewerId);


text:
Q: Triggered Send Delivery Profile Error I have an issue with Triggered Sends.
In order to get rid of the standard header and footer I override the Delivery Profile with a custom one. To this profile I have attached my own header and footer, created with the content editor. However, when I want to save these profile changes to the Triggered Send I see this:

This seems to be related to removing the header and footer. As soon as I use the default Delivery Profile (with the default header and footer), there is no problem. What am I doing wrong?

A: You need to add personalized strings, minimum required:
%%Member_Busname%% %%Member_Addr%% %%Member_City%%, %%Member_State%%,
%%Member_PostalCode%%, %%Member_Country%%

Update Your Profile:
%%profile_center_url%%

A: You can bypass the error checking by embedded the codes above by using something like: . for each. However, there's a reason those error checks are in place - they're to keep people from running afoul of CAN-SPAM and spam filters from the ESP's, so do so after careful consideration.


text:
Q: Unable to Intentionally Trigger Async Deadlock I'm trying to confirm that a library I wrote will not cause an asychronous deadlock. To do that, I'm first trying to intentionally cause one (so that I can replace the innermost call with a call to my library), but no matter what I do, no deadlock occurs... what am I misunderstanding?
I've setup the relevant code in a new api (because I thought that apis were non-reentrant/single-threaded) and just in case it matters, I've moved each function to its own class and added Thread.Sleep commands to ensure that there is activity in each method both before and after the await.

    public class TestingController : ApiController
    {
        [HttpPost]
        [Route("api/Testing/TriggerAsyncDeadlock")]
        [ResponseType(typeof(string))]
        public HttpResponseMessage TriggerAsyncDeadlock()
        {
            return Request.CreateResponse(HttpStatusCode.OK, new AsyncCaller().CallerAsync().Result);
        }
    }

    public class AsyncBase
    {
        public async Task<string> BaseAsync()
        {
            Thread.Sleep(500);
            var ret = await Task.FromResult("Result");
            Thread.Sleep(500);
            return ret;
        }
    }
    public class AsyncCaller
    {
        public async Task<string> CallerAsync()
        {
            Thread.Sleep(500);
            var ret = "These are the results: ";
            var asyncBase = new AsyncBase();
            for (var i = 1; i < 5; i++)
            {
                ret += $"'{await asyncBase.BaseAsync()}',";
                Thread.Sleep(500);
            }
            return ret.Substring(0, ret.Length - 1);
        }
    }

Edit: I'm running .net framework 4.7.1

A: If you mean this kind of deadlock, then it requires these things to be present:

*

*A context that only allows one thread at a time. If your code is ASP.NET, then it has a context like this. ASP.NET Core doesn't, and thus isn't subject to this kind of deadlock.

*Code that blocks in this context waiting for an an asynchronous continuation to complete.

*An asynchronous continuations that needs to enter the context in order to complete.

In this case, you don't have any asynchronous continuations. await Task.FromResult("Result") is literally just a less-efficient form of "Result" - i.e., no asynchronous work is being done. The code is always fully synchronous.
In order to cause this kind of deadlock (assuming you're running on ASP.NET pre-Core where this kind of deadlock is possible), you need to replace Thread.Sleep with await Task.Delay. That way the code will actually run asynchronously.


text:
Q: How to manage Two WindowedApplication in Flex? Case:
1) There are two .mxml files (Windowed Application): one is Log-in(Active Window/ Start up Window) and other is Main Window.
2) Main Window has viewstack
3) On log-in successful, log-inHandler called from Main Window.
4) log-inHandler access viewstack id of Main Window.
5) But viewstack id shows null.
Question:
1) How to solve this case?

A: *

*You should not use 2 Windowed Applications

*Make your Login page as a MXMLComponent

*Add the Login page as a new NativeWindow from your main App, so you can communicate with it.


text:
Q: How to select multiple rectangles in a word search game? First of all, here is a picture.

How can I do to select multiple rectangles, while the left mouse button is pushed ?
For example, I want to write in the "man" word, so I click on the m rectangle, move it through the a, release it at the n, and get back a string with the "man" word.
I've made a Cube class, which stores a Rectangle, and a string, and has a Drawing method, which needs some parameters: a Graphic object, a Pen, and a Rectangle. I draw them to a panel, in the following way:
Cube[,] kockak = new Cube[3,3];
//fill cubes with data...

private void panel1_Paint(object sender, PaintEventArgs e)
        {
            Graphics g = e.Graphics;

            for (int i = 0; i < 3; i++)
            {
                for (int j = 0; j < 3; j++)
                {
                    kockak[j,i].Draw(g, new Pen(Brushes.Black), new Rectangle(i * 100, j * 100, 100, 100));
                }
            }
            Invalidate();
        }

A: Just add some method to select the cube in Cube class like this:
public class Cube : Panel {
   public Cube(){
      Selected = false;
   }
   protected override void OnPaint(PaintEventArgs e){
      //Draw your background to make it look like selected first before drawing string on top.
      if(Selected) e.Graphics.FillRectangle(Brushes.Green, ClientRectangle);
      //Draw your string normally as you did here
      //.......
   }
   public bool Selected { get; set;}
   public void Select(){
      Selected = true;
      Invalidate();
   }
   public void Deselect(){
      Selected = false;
      Invalidate();
   }
}
//use the code
yourCube.Select();//select a cube
yourCube.Deselect();//deselect a cube

A: Some additional idea on King King answer:
I would add the MouseMove event in the form and check the MouseButton state.
If it is Left, set the Cude.selceted to true.
private void TreeViewTeschd_MouseMove(object sender, MouseEventArgs e) {
    if (e.Button == MouseButtons.Left) {
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                if (kockak[j,i].rect.Contains(e.Location)) kockak[j,i].selected = true;
            }
        }
    }
}


text:
Q: Integral involving matrix exponential Is there any way to simplify the integral
$$
I = \int_{t_1}^{t_2}e^{\Lambda t} A e^{\Lambda t}\,dt
$$
knowing that A is symmetric and Λ is a diagonal matrix?

A: Let $\Lambda\equiv\operatorname{diag}(\lambda_{1},\ldots,\lambda_{n})$ and $A\equiv(a_{ij})$.
Then,
$$
[e^{\Lambda t}Ae^{\Lambda t}]_{ij}=e^{(\lambda_{i}+\lambda_{j})t}a_{ij}
$$
and hence
$$
[I]_{ij}=a_{ij}\int_{t_{1}}^{t_{2}}e^{(\lambda_{i}+\lambda_{j})t}dt=a_{ij}\frac{e^{(\lambda_{i}+\lambda_{j})t_{2}}-e^{(\lambda_{i}+\lambda_{j})t_{1}}}{\lambda_{i}+\lambda_{j}}.
$$
BTW, it seems like a dangerous idea to use the symbol $I$ to mean anything other than identity if there are matrices involved.

A: Let $\lambda_1,\dots, \lambda_n$ denote the diagonal entries of $\Lambda$, and let $a_{ij}$ denote the entries of $A$. Note that we have
$$
[e^{\Lambda t}A e^{\Lambda t}](i,j) = e^{(\lambda_i + \lambda_j)t} a_{ij}
$$
Thus, integrating entrywise yields
$$
I(i,j) = \frac{e^{(\lambda_i + \lambda_j)t_2} - e^{(\lambda_i + \lambda_j)t_1}}{\lambda_i + \lambda_j}
$$
in the case that $\lambda_i \neq -\lambda_j$.  If $\lambda_i = -\lambda_j$, then we end up with $I(i,j) = a_{ij}(t_2 - t_1)$.


text:
Q: How to fix computation errors? I'm trying to write a program that reads 2 numbers from the user and divides them. Here is the code I have so far:
import java.util.Scanner;

public class divideByZero {

public static int quotient(int numerator, int denominator)
{
   return numerator / denominator;
}

public static void main(String args[])
{
   Scanner scanner = new Scanner(System.in);

    System.out.print("Please enter the first number: ");

    int numerator = scanner.nextInt();

    System.out.print("Please enter the second number: ");

    int denominator = scanner.nextInt();

    int result = quotient( numerator, denominator );

    float result2 = (float)result;

    System.out.printf("\n The first number %d divided by the second number "
            + "%d = %f\n", numerator, denominator, result2 );

}

I'm having problems with the computations. For example, when I enter 3 divided by 4, I get the result 0.000000. How do I get the correct result to 2 decimal places?

A: Cast the numerator and denominator as floats before you divide them.
import java.util.Scanner;

public class divideByZero {

public static float quotient(float numerator, float denominator)
{
   return numerator / denominator;
}

public static void main(String args[])
{
   Scanner scanner = new Scanner(System.in);

    System.out.print("Please enter the first number: ");

    int numerator = scanner.nextInt();

    System.out.print("Please enter the second number: ");

    int denominator = scanner.nextInt();

    float result = quotient( (float) numerator, (float) denominator );

    System.out.printf("\n The first number %d divided by the second number "
            + "%d = %f\n", numerator, denominator, result );

}

A: Why don't you use the datatype double instead of float?
Here is some code to format into two decimal points:
import java.text.*;

public class DecimalPlaces {

   public static void main(String[] args) {

       double d = 1.234567;
       DecimalFormat df = new DecimalFormat("#.##");
       System.out.print(df.format(d));
   }

}

A: The following changes will do what you need.
public static float quotient(int numerator, int denominator)
{
    return (float)numerator / (float)denominator;
}

float result = quotient( numerator, denominator );

System.out.printf("\n The first number %d divided by the second number "
        + "%d = %.2f\n", numerator, denominator, result2 );

You cannot do division on an int and get a fractional int (there is no such thing), so the division must be done with floats and stored into a float.  The %.2f limits it to 2 decimal places.

A: You are getting 0.0000 because you are dividing integer numbers and storing that result back into an integer.  To see the fractional part, you can declare result to be a float variable.
When that's working, to print 2 decimals you can use printf formatting.
In C it'd be something like %.2f.
Based on the errors, I think you'd benefit from reading about data types, especially floating point numbers.

A: If you change the return type of the quotient method from an int to a float, it will no longer round the answer to the nearest integer.
public static float quotient(int numerator, int denominator)
{
   return (float) numerator / (float) denominator;
}


text:
Q: ScrollPane containing JTable takes up height of COntainer I have a ScrollPane and JTable that should only have one row of data.
String[] daysOfWeek = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
        String[][] data = {{"None","None","None","None","None","None","None"}};

        JTable mTable = new JTable(data, daysOfWeek);

        JScrollPane scrollPane = new JScrollPane(mTable);
        mTable.setFillsViewportHeight(false);

I want the ScrollPane to fit around the borders of the table but at the moment the height of the Scrollpane takes up the entirety of the container, making it look really ugly. I don't understand why, since I set mTable.setFillsViewportHeight(false).
Any help how to achieve a ScrollPane that doesn't stretch beyond the size of the table would be welcome.

A: you can use table.setPreferredScrollableViewportSize(table.getPreferredSize());
edit

import java.awt.*;
import java.awt.event.ActionEvent;
import java.util.Random;
import java.util.concurrent.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.DefaultTableModel;

public class ChangeNotifiersOnEvent extends JFrame implements Runnable {

    private static final long serialVersionUID = 1L;
    private boolean runProcess = true;
    private Random random = new Random();
    private javax.swing.Timer timerRun;
    private Executor executor = Executors.newCachedThreadPool();
    private String[] columnNames = {"Source", "Hit", "Last", "Ur_Diff"};
    private JTable table;
    private Object[][] data = {{"Swing Timer", 2.99, 5, 1.01},
        {"Swing Worker", 7.10, 5, 1.010}, {"TableModelListener", 25.05, 5, 1.01}};
    private DefaultTableModel model = new DefaultTableModel(data, columnNames);

    public ChangeNotifiersOnEvent() {
        table = new JTable(model) {

            private static final long serialVersionUID = 1L;

            @Override
            public Class getColumnClass(int column) {
                return getValueAt(0, column).getClass();
            }
        };
        model.addTableModelListener(new TableModelListener() {

            @Override
            public void tableChanged(TableModelEvent tme) {
                if (tme.getType() == TableModelEvent.UPDATE) {
                    if (tme.getColumn() == 1 && tme.getLastRow() == 2) {
                        double dbl = ((Double) table.getModel().getValueAt(2, 1))
                                - ((Integer) table.getModel().getValueAt(2, 2));
                        table.getModel().setValueAt(dbl, 2, 3);
                    } else if (tme.getColumn() == 1 && tme.getLastRow() == 0) {
                        prepareUpdateTableCell();
                    } else if (tme.getColumn() == 1 && tme.getLastRow() == 1) {
                        executor.execute(new MyTask(MyTask.UPDATE_TABLE_COLUMN));
                    }
                }
            }
        });
        table.setRowHeight(30);
        table.setFont(new Font("Serif", Font.BOLD, 20));
        table.getColumnModel().getColumn(0).setPreferredWidth(180);
        table.setPreferredScrollableViewportSize(table.getPreferredSize());
        JScrollPane scrollPane = new JScrollPane(table);
        add(scrollPane, BorderLayout.CENTER);
        new Thread(this).start();
    }

    private void prepareUpdateTableCell() {
        timerRun = new javax.swing.Timer(10, UpdateTableCell());
        timerRun.setRepeats(false);
        timerRun.start();
    }

    private Action UpdateTableCell() {
        return new AbstractAction("Update Table Cell") {

            private static final long serialVersionUID = 1L;

            @Override
            public void actionPerformed(ActionEvent e) {
                double dbl = ((Double) table.getModel().getValueAt(0, 1))
                        - ((Integer) table.getModel().getValueAt(0, 2));
                table.getModel().setValueAt(dbl, 0, 3);
            }
        };
    }

    @Override
    public void run() {
        while (runProcess) {
            try {
                Thread.sleep(330);
            } catch (Exception e) {
                e.printStackTrace();
            }
            changeTableValues();
        }
    }

    private void changeTableValues() {
        Runnable doRun = new Runnable() {

            @Override
            public void run() {
                table.getModel().setValueAt(random.nextInt(128) + random.nextDouble(), 0, 1);
                table.getModel().setValueAt(random.nextInt(256) + random.nextDouble(), 1, 1);
                table.getModel().setValueAt(random.nextInt(512) + random.nextDouble(), 2, 1);

                table.getModel().setValueAt(random.nextInt(128), 0, 2);
                table.getModel().setValueAt(random.nextInt(128), 1, 2);
                table.getModel().setValueAt(random.nextInt(128), 2, 2);
            }
        };
        SwingUtilities.invokeLater(doRun);
    }

    private class MyTask extends SwingWorker<Void, Integer> {

        private static final String UPDATE_TABLE_COLUMN = "update";
        private String namePr;
        private double dbl;

        MyTask(String str) {
            this.namePr = str;
        }

        @Override
        protected Void doInBackground() throws Exception {
            dbl = ((Double) table.getModel().getValueAt(1, 1))
                    - ((Integer) table.getModel().getValueAt(1, 2));
            return null;
        }

        @Override
        protected void done() {
            SwingUtilities.invokeLater(new Runnable() {

                @Override
                public void run() {
                    table.getModel().setValueAt(dbl, 1, 3);
                }
            });
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                ChangeNotifiersOnEvent frame = new ChangeNotifiersOnEvent();
                frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
                frame.setLocation(150, 150);
                frame.pack();
                frame.setVisible(true);
            }
        });
    }
}

A: Unless you explicitly set a scroll pane's preferred size using setPreferredSize(Dimension size), the scroll pane computes it based on the preferred size of its nine components (the viewport, and, if present, the two scroll bars, the row and column headers, and the four corners). The largest factor, and the one most programmers care about, is the size of the viewport used to display the client. see here for more: http://docs.oracle.com/javase/tutorial/uiswing/components/scrollpane.html


text:
Q: Anyone have an idea how to dismiss this DatePicker/Subview This is the method I use to display a UIPickerView when a button is pressed, what method would I used to dismiss it?
if (buttonIndex == 4) {
    int height = 255;

//create new view
UIView * newView = [[UIView alloc] initWithFrame:CGRectMake(0, 200, 320, height)];
    newView.backgroundColor = [UIColor colorWithWhite:1 alpha:1];

//add toolbar
UIToolbar * toolbar = [[UIToolbar alloc] initWithFrame: CGRectMake(0, 0, 320, 40)];
    toolbar.barStyle = UIBarStyleBlack;

//add button
UIBarButtonItem *infoButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Done" style:UIBarButtonItemStyleDone target:nil action:@selector(dismissCustom:)];
    toolbar.items = [NSArray arrayWithObjects:infoButtonItem, nil];

//add date picker
UIDatePicker *datePicker = [[UIDatePicker alloc] init];
    datePicker.datePickerMode = UIDatePickerModeDateAndTime ;
    datePicker.hidden = NO;
    datePicker.date = [NSDate date];
    datePicker.frame = CGRectMake(0, 40, 320, 250);
    [datePicker addTarget:self action:nil/*@selector(changeDateInLabel:)*/ forControlEvents:UIControlEventValueChanged];
    [newView addSubview:datePicker];

//add popup view
[newView addSubview:toolbar];
[self.view addSubview:newView];

//animate it onto the screen
CGRect temp = newView.frame;
    temp.origin.y = CGRectGetMaxY(self.view.bounds);
    newView.frame = temp;
    [UIView beginAnimations:nil context:nil];
    temp.origin.y -= height;
    newView.frame = temp;
    [UIView commitAnimations];

}

A: To remove the view, do another animation. Just reverse the frame setting so it moves off of the screen. When the animation completes, remove the 'newView' by calling [newView removeFromSuperview].
You should consider using the newer block form of UIView animations. It will make it much easier.
One other thing. If you have a custom view class, why doesn't that custom class do all the work to set itself up?
Also, it is standard convention for class names to begin with an upper case letter. This makes it easy to tell a classname from a variable name when looking at the code.


text:
Q: mongoDB Collection LRU Policy +java I am new to mongoDB. I am working on building an application which requires implementing LRU policy on the collection. In the mongoDB site i see capped collections support FIFO. Is there any other collection which support LRU. Throught the documentation i see only capped collections in the site. Are there any other collections in mongoDb.
Are collections by default capped in mongodb?

A: MongoDB capped collections are the only kilobyte size-limited collections supported by the database. There is no built-in support for LRU or FIFO based on limiting to a particular number of documents.
Collections are not capped by default in MongoDB - a capped collection is a special case.


text:
Q: 'identity.api.rackspacecloud.com' randomly throws 'The remote name could not be resolved' exception I am accessing Rackspace Cloud APIs.
I have one api call which authenticates me on the rackspace cloud.
The method works perfectly, however, from time to time, i get this exception, randomly :
The remote name could not be resolved: 'identity.api.rackspacecloud.com'
When i am not getting this exception, the method returns the expected result, as it should be.
Is there any specific reason why it does this?
Here is my .net code:
private async Task<XDocument> AuthenticateAsync()
{
    XNamespace ns = "http://docs.rackspace.com/identity/api/ext/RAX-KSKEY/v1.0";

    XDocument doc =
        new XDocument(
            new XDeclaration("1.0", "UTF-8", "Yes"),
            new XElement("auth",
                new XElement(ns + "apiKeyCredentials",
                    new XAttribute("username", "the userName"),
                    new XAttribute("apiKey", "the apiKey")
                )
            )
        );

    using (HttpClient client = new HttpClient())
    {
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));

        StringContent content = new StringContent(doc.ToString(), Encoding.UTF8, "application/xml");

        // i randomly get "The remote name could not be resolved" exception
        HttpResponseMessage response = await client.PostAsync("https://identity.api.rackspacecloud.com/v2.0/tokens", content);
        response.EnsureSuccessStatusCode();

        string stringResponse = await response.Content.ReadAsStringAsync();
        return XDocument.Parse(stringResponse);
    }
}

A: This certainly sounds like a DNS failure. Can you configure your machine to use the Google DNS servers and try again?


text:
Q: Google Apps Script - Changing values in a range of google sheets cells In the following example I use Apps Script to schedule Google calendar events based on spreadsheet input. This code works just fine however I need to tweak it to do a small manipulation on the source sheet as well.
You can see here that I filter the range to only include rows that have "Pending" value in column D (r[3]). However I need to include a line of code in the loop so that after the filtered rows are synced to my Google Calendar the same cell value in column D changes to "Scheduled" for the respective cell. I have tried following this solution but could not implement it since I am new to JS.
Google Apps Script - .setValue in cell based on for loop matching

function calendarSync() {
var ss = SpreadsheetApp.getActiveSheet();
var calendarId = "My Calendar ID";
var eventCal = CalendarApp.getCalendarById(calendarId);
var eventArray = ss.getRange('A2:I500').getValues().filter(r => r[3] == "Pending Schedule");

for (x=0; x<eventArray.length; x++) {
  var event = eventArray[x];
  var eventName = event[0];
  var startTime = event[1];
  var endTime = event[2];

  var exisEvents = eventCal.getEvents(startTime, endTime, {search: eventName}) //prevents creating duplicate events;
  if (exisEvents.length == 0) {
  eventCal.createEvent(eventName, startTime, endTime);
  }
}
}

A: One simple solution is to change a bit logic of your script. Instead of using filter use an if statement then overwrite the whole range.
function calendarSync() {
  var ss = SpreadsheetApp.getActiveSheet();
  var calendarId = "My Calendar ID";
  var eventCal = CalendarApp.getCalendarById(calendarId);
  var eventArray = ss.getRange('A2:I500').getValues();

  for (x = 0; x < eventArray.length; x++) {

    var event = eventArray[x];
    var eventName = event[0];
    var startTime = event[1];
    var endTime = event[2];
    var status = event[3]; // Used to in the following comparison expression instead of filter
    if (status === "Pending Schedule") {
      var exisEvents = eventCal.getEvents(startTime, endTime, {
        search: eventName
      }) //prevents creating duplicate events;
      if (exisEvents.length == 0) {
        eventCal.createEvent(eventName, startTime, endTime);
        eventArray[x][3] = "Scheduled"; // Update the status
      }
    }

  }
  ss.getRange('A2:I500').setValues(eventArray); // Overwrite the source data with the modified array
}

P.S. If you are using the default runtime instead of var it's better to use const and let, specially when writing complex scripts.


text:
Q: Tracing Apache Camel route with Jaeger I have developed a Camel route with Spring Boot. Now I want to trace the route using Jaeger. I tried this example to trace the route using camel-opentracing component, but I am unable to get the traces to Jaeger.
I can only see it in the console. One thing I am not clear is where to add the Jaeger URL?
Any working example will be helpful.

A: What I eventually did is create a JaegerTraces and annotated with Bean

A: Apache Camel doesn't provide an implementation of OpenTracing, so you have to add also an implementation to your dependencies. For example Jaeger.
Maven POM:
    <dependency>
        <groupId>org.apache.camel.springboot</groupId>
        <artifactId>camel-opentracing-starter</artifactId>
        <version>${camel.version}</version>
    </dependency>
    <dependency>
        <groupId>io.opentracing.contrib</groupId>
        <artifactId>opentracing-spring-jaeger-starter</artifactId>
        <version>3.2.2</version>
    </dependency>

Also you have to enable OpenTracing for Apache Camel on your Spring Boot application class, see Spring Boot:

If you are using Spring Boot then you can add the camel-opentracing-starter dependency, and turn on OpenTracing by annotating the main class with @CamelOpenTracing.
The Tracer will be implicitly obtained from the camel context's Registry, or the ServiceLoader, unless a Tracer bean has been defined by the application.

Spring Boot application class:
@SpringBootApplication
@CamelOpenTracing
public class CamelApplication {

    public static void main(String[] args) {
        SpringApplication.run(CamelApplication.class, args);
    }
}


text:
Q: Core Data Query Multiple Columns with Single Search String I have a simple Core Data model with two string attributes (size and category). Given a search string like 'small widget' is it possible to return records that match all the query words to at least one attribute (i.e. all records with 'small' size and 'widget' category)? I currently have:
NSString *search = @"small widget"
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"size contains[cd] %@ OR category contains[cd] %@", search, search];
...

This won't return any results (as no category or size equals "small widget"). Any suggestions? Note that the search strings will be user entered from a text field and may come in any order so I can't split up manually.

A: I haven't tested it but it looks like your want this:
NSString *search = @"small widget";
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"%@ contains[cd] size AND %@ contains[cd] category", search, search];

The search string would contain (or not) the size and the category, you should ask if the current size or category is contained on the search string.
You could also split the search string and modify your predicate. You should them to identify the one that performs better
NSString *search = @"small widget";
    NSArray *array = [search componentsSeparatedByString:@" "];
    NSMutableArray *subPredicates = [NSMutableArray array];
    for (NSString *q in array) {
        [subPredicates addObject:
         [NSPredicate predicateWithFormat:@"size contains[cd] %@ OR category contains[cd] %@", q, q]];
    }
    NSCompoundPredicate *predicate = [[[NSCompoundPredicate alloc] initWithType:NSAndPredicateType
                                                                 subpredicates:subPredicates] autorelease];

A: For Swift you can fetch multiple columns by using propertiesToFetch
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "<YOUR ENTITY NAME>")
let predicate = NSPredicate(format: "<YOUR PREDICATE>")
fetchRequest.predicate = predicate
fetchRequest.resultType = .dictionaryResultType

// Here is where you can query multiple columns, you can add as much columns as you want and fetch them as an array of dictionaries
fetchRequest.propertiesToFetch = ["column1", "column2", "column3, "column4"]

let sort = NSSortDescriptor(key: "column1", ascending: false)
fetchRequest.sortDescriptors = [sort]


text:
Q: Why am I not getting any events for my anchor element? For a quite simple element
public static class ToolHtml extends Anchor {

    private Long toolId;

    public ToolHtml(ToolDetails toolDetails) {

        this.toolId = toolDetails.getToolId();
        this.setText(toolDetails.getName());

        Style style = this.getElement().getStyle();
        style.setColor("orange");

        this.getElement().setId(DOM.createUniqueId());
    }

    public Long getToolId() {
        return this.toolId;
    }

}

I am trying to add some event handlers. I am interested in the DragStartEvent but not even the ClickEvent seems to work and I simply can't figure out why:
public void addOfferItem(ToolHtml toolHtml) {

    Set<ToolHtml> toolHtmlSet = this.toolIdToToolHtml.get(toolHtml.getToolId());

    if (toolHtmlSet == null) {
        toolHtmlSet = new HashSet<>();
        this.toolIdToToolHtml.put(toolHtml.getToolId(), toolHtmlSet);
    }

    toolHtml.getElement().setAttribute("contenteditable", "false");
    toolHtml.getElement().setAttribute("draggable", "true");

    toolHtml.addBitlessDomHandler(new ClickHandler() {

        @Override
        public void onClick(ClickEvent event) {
            LOGGER.fine("Click");
            LOGGER.fine("Click");
            LOGGER.fine("Click");

        }
    }, ClickEvent.getType());

    toolHtml.addDomHandler((DragStartEvent event) -> {
                LOGGER.fine("HANDLER DRAG START");
            },
            DragStartEvent.getType());

    toolHtml.addDomHandler((DragStartEvent event) -> {
                LOGGER.fine("DOM DRAG START");
            },
            DragStartEvent.getType());

    toolHtml.addBitlessDomHandler((DragStartEvent event) -> {
                LOGGER.fine("DRAG START");
            },
            DragStartEvent.getType());

    toolHtmlSet.add(toolHtml);

    // Attach/append to DOM
    this.getElement().appendChild(toolHtml.getElement());
}

Does anybody know what the issue is here?

A: You append an element, not a Widget to which your handlers have been attached. You need to add a widget to a widget for all the functionality to work.
NB: Instead of toolHtml.addBitlessDomHandler you need to use
toolHtml.addClickHandler


text:
Q: How to test an Heroku Buildpack without committing and pushing to heroku server each time I am working on a heroku buildpack that will allow the deployment of symfony2 PHP applications to Heroku.
Each time I do a modification in the buildpack I follow the folowing procedure to test it:
echo 1 >> dummy
git add .
git commit -m "heroku"
git push heroku master

The first line (echo 1 >> dummy) is just to guarantee that is there something to commit. Otherwise when pushing to heroku the deployment with my buildpack would not be triggered.
I suspect there exists an easier and may be more elegant way of testing an heroku buildpack.
I would like to know if heroku exposes a way to test buildpacks or is there a way to test it without committing and pushing each time.

A: You can use heroku push, with that, you can specify a local buildpack:
$ heroku push -b ~/mybuildpack

There's also Mason, but I don't know much about that.


text:
Q: descriptor concept in NIC I am trying to understand the concept of Rx and Tx descriptors used in Network driver code.

*

*Are Descriptors in software(RAM) or hardware (NIC card).

*How do they get filled.

EDIT: So in a Realtek card driver code. I have a following struct defined.
struct Desc
{
        uint32_t opts1;
        uint32_t opts2;
        uint64_t addr;
};

txd->addr = cpu_to_le64(mapping);
txd->opts2 = cpu_to_le32(opts2);
txd->opts1 = cpu_to_le32(opts1 & ~DescOwn);

So are the opts1 and opts2 and there bits like DescOwn card specific? Will they be defined by the manufacturer in the datasheet?

A: Quick Answer:

*

*They are software constructs that follows the definition by NIC hardware so both understands and could talk to each other.

*They could get filled either way, depending on the contract defined by the vendor. Possible scenarios could include but are not limited to:

*

*By driver (e.g. For empty buffer prepared by driver to be received by hardware Rx; For packet buffer prepared by driver to be transmitted by hardware Tx)

*By NIC (e.g. For packet buffer written back by hardware for completed Rx packet; For finished Tx packet buffer indicated by hardware that it's transmitted)

More Architectural Details:
Note: I assume you have knowledge of ring data structure, concept of DMA.
https://en.wikipedia.org/wiki/Circular_buffer
https://en.wikipedia.org/wiki/Direct_memory_access
Descriptor, as its name implies, describes a packet. It doesn't directly contain packet data (for NICs as far as I know), but rather describes the packet, i.e. where is packet bytes stored, length of the packet, etc.
I will use RX path as an example to illustrate why it's useful. Upon receiving a packet, the NIC translates the electronic/optical/radio signal on the wire to binary data bytes. Then NIC need to inform the OS that it has received something. In the old days, this is done by interrupts and OS would read bytes from a pre-defined location on the NIC to RAM. However this is slow since 1) CPU are required to participate in data transfer from NIC to RAM 2) there could be lots of packets, thus lots of interrupts which could be too many to handle for CPU. Then DMA came along and solves the first problem. Also, folks designed poll mode driver (or hybrid mode, as in Linux NAPI) so CPU could be freed from interruption handling and poll many packets at once thus solving the 2nd problem.
The NIC finishes signal translation to bytes and would like to do a DMA to RAM. But before that, NIC needs to know where to DMA to, as it can't randomly put data in RAM which CPU won't know where and isn't secure.
So during initialization of RX queue, NIC driver pre-allocates some packet buffer, as well as an array of packet descriptors. It initializes each packet descriptor according to the NIC definition.
Below is the convention used by Intel XL710 NIC (names have been simplified for better understanding):

/*
   Rx descriptor used by XL710 is filled by both driver and NIC,
 * but at different stage of operations. Thus to save space, it's
 * defined as a union of read (by NIC) and writeback (by NIC).
 *
 * It must follow the description from the data sheet table above.
 *
 * __leXX below means little endian XX bit field.
 * The endianness and length has to be explicit, the NIC can be used by different CPU with different word size and endianness.
 */

union rx_desc {
    struct {
        __le64 pkt_addr; /* Packet buffer address, points to a free packet buffer in packet_buffer_pool */
        __le64 hdr_addr; /* Header buffer address, normally isn't used */
    } read; /* initialized by driver */

    struct {
        struct {
            struct {
                union {
                    __le16 mirroring_status;
                    __le16 fcoe_ctx_id;
                } mirr_fcoe;
                __le16 l2tag1;
            } lo_dword;
            union {
                __le32 rss; /* RSS Hash */
                __le32 fd_id; /* Flow director filter id */
                __le32 fcoe_param; /* FCoE DDP Context id */
            } hi_dword;
        } qword0;
        struct {
            /* ext status/error/pktype/length */
            __le64 status_error_len;
        } qword1;
    } wb;  /* writeback by NIC */
};

/*
 * Rx Queue defines a circular ring of Rx descriptors
 */
struct rx_queue {
    volatile rx_desc rx_ring[RING_SIZE]; /* RX ring of descriptors */
    struct packet_buffer_pool *pool;     /* packet pool */
    struct packet_buffer *pkt_addr_backup; /* save a copy of packet buffer address for writeback descriptor reuse */
....
}

*

*Driver allocates some number of packet buffer in RAM (stored in packet_buffer_pool data structure).
pool = alloc_packet_buffer_pool(buffer_size=2048, num_buffer=512);

*Driver put each packet buffer's address in the descriptor field, like
rx_ring[i]->read.pkt_addr = pool.get_free_buffer();

*Driver tells NIC the starting location of rx_ring, its length and head/tail. So NIC would know which descriptors are free (thus packet buffer pointed by those descriptors are free). This process is done by driver writing those info into NIC registers (fixed, could be found in NIC datasheet).
rx_ring_addr_reg = &rx_ring;
rx_ring_len_reg = sizeof(rx_ring);
rx_ring_head = 0; /* meaning all free at start */
/* rx_ring_tail is a register in NIC as NIC updates it */

*Now NIC knows that descriptor rx_ring[{x,y,z}] are free and {x,y,z}.pkt_addr could be put new packet data. It go ahead and DMA new packets into {x,y,z}.pkt_addr. In the meantime, NIC could pre-process (offload) the packet processing (like check sum validation, extract VLAN tag) so it would also need some place to leave those info for software. Here, descriptors are reused for this purpose on writeback (see the second struct in descriptor union). Then NIC advances rx_ring tail pointer offset, indicating a new descriptor has been written back by NIC.[A gotcha here is that, since descriptors are re-used for pre-process results, driver has to save {x,y,z}.pkt_addr in a backup data structure].
/* below is done in hardware, shown just for illustration purpose */
if (rx_ring_head != rx_ring_tail) { /* ring not full */
    copy(rx_ring[rx_ring_tail].read.pkt_addr, raw_packet_data);
    result = do_offload_procesing();

    if (pre_processing(raw_packet_data) & BAD_CHECKSUM))
        rx_ring[rx_ring_tail].writeback.qword1.stats_error_len |= RX_BAD_CHECKSUM_ERROR;
    rx_ring_tail++; /* actually driver sets a Descriptor done indication flag */
                    /* along in writeback descriptor so driver can figure out */
                    /* current HEAD, thus saving a PCIe write message */
}

*Driver reads the new tail pointer offset and found {x,y,z} are with new packets. It would read off the packet from pkt_addr_backup[{x,y,z}] and related pre-precessing result.

*When upper layer software is done with packets, {x,y,z} would be put back to rx_ring and ring head pointer would be updated to indicate free descriptors.
This concludes the RX path. TX path is pretty much the reverse: upper layer produces packet, driver copy packet data into packet_buffer_pool and let tx_ring[x].buffer_addr points to it. Driver also prepares some TX offload flags (such as hardware checksumming, TSO) in the TX descriptor. NIC reads TX descriptor and DMA tx_ring[x].buffer_addr from RAM to NIC.
This information normally appears in NIC datasheet, such as Intel XL710 xl710-10-40-controller-datasheet, Chapter 8.3 & 8.4 LAN RX/TX Data Path.
http://www.intel.com/content/www/us/en/embedded/products/networking/xl710-10-40-controller-datasheet.html
Also you can check the open source driver code (either Linux kernel or some user space library like DPDK PMD), which would contain descriptor struct definition.
-- Edit 1 --
For your additional question regarding Realtek driver:
Yes, those bits are NIC specific. A hint is lines like
    desc->opts1 = cpu_to_le32(DescOwn | RingEnd | cp->rx_buf_sz);

DescOwn is a bit flag which by setting it tells NIC that it now owns this descriptor and associated buffer. Also it need to convert from CPU endianness(might be power CPU, which is BE) to Little Endian that NIC agrees to understand.
You can find relevant info in http://realtek.info/pdf/rtl8139cp.pdf (e.g. Page 70 for DescOwn), though it's not as through as XL710 but at least contains all register/descriptor info.
-- Edit 2 --
The NIC descriptor is a very vendor dependent definition. As shown above, Intel's NIC descriptor use the same RX descriptor ring to provide NIC buffers to write to, and for the NIC to write back RX info. There are other implementations like split RX submission/completion queue (more prevalent in NVMe technology). For instance, some of Broadcom's NICs have a single submission ring (to give buffer to NIC) and multiple completion ring. It's designed for NIC decide and put packets in different ring for e.g. different traffic class priority, so that driver can get most important packets first.
 (From BCM5756M NIC Programmer's Guide)
--Edit 3--
Intel usually make NIC datasheet open to public download, while other vendors might disclose to ODMs only. A very brief summary of Tx/Rx flow is described in their Intel 82599 family datasheet, section 1.8 Architecture and Basic Operations.


text:
Q: How to create an embossed button in objective c I think it's called embossed button..
Is it possible to make one from code?
I mean like the "Sign Up for Facebook" button in the Facebook iPhone app logging screen.
I know three20 have something like that but i want to create one my self

A: you can create it easily i think because what you will need is only the embossed image.
drag a UIButton to your view and the go to attribute Inspector in you IB then under button section change the type to custom.
Now when you have the custom type then assige your embossed image as the background image.
if you are looking for custom code then refer This link


text:
Q: How to get position of file in objective-c? FILE *fileStream;
fileStream = fopen(filePath,"r");

How to get current file position in Objective-C for Mac os x?

A: In this way?
  NSString* filename = [NSString stringWithCString:@"your-file" encoding:NSASCIIStringEncoding];
  NSString* content = [NSString stringWithContentsOfFile:filename encoding:NSASCIIStringEncoding error:nil];

A: Use ftell to get the current file position.


text:
Q: ChartJS Line chart causes browser crash I am updating a Line chart using HTTP get through ngResource and a rest API.
My technique is to get the JSON dataset and create a new chart every time a user is clicking on a button.
It works great, but at one time, it causes the browser crash. I have tested on Chrome, Firefox on both Windows and Linux.
In my controller :
$scope.labels = $scope.dataFromREST;
$scope.series = ['Series A'];
$scope.data = [$scope.dataFromREST2];
$scope.onClick = function (points, evt) {
    console.log(points, evt);
};
$scope.datasetOverride = [{ yAxisID: 'y-axis-1' }];
$scope.options = {
    scales: {
        yAxes: [
            {
                id: 'y-axis-1',
                type: 'linear',
                display: true,
                position: 'left'

            }
        ],
        xAxes: [{
            responsive: true,
            ticks: {
                autoSkip: true,
                maxTicksLimit: 20
            }
        }]

    }

};

In my index.html :
<canvas id="line" class="chart chart-line" chart-data="data"
                    chart-labels="labels" chart-series="series" chart-options="options"
                    chart-dataset-override="datasetOverride" chart-click="onClick">
            </canvas>

Is there a way to just update or refresh the Line Chart with the $scope.dataFromREST data received and not create a new Chart object every time? (Because I think, the crash come from creating a new chart every time) I see the ".update()" function, but I can't seem to get it to work.
I have also tried the ".destroy()" and I am still getting the browser wind up to crash.
How can I get rid of that crash? Please help!

A: Yes, there is a way to simply update the underlying chart.js chart data without having to re-instantiate the chart each and every time.  You just need to use the update(duration, lazy) function from the API.
Here is an example that I use in one of my apps (modified for your specific case).  Note, chart is my chart.js object (what was returned from new Chart()...:
assembledData = {};
assembledData.data = // data from api call in an acceptable data format that chart.js understands
assembledData.colors = // new color definition for your data so it will update correctly
assembledData.labels = // new label definition for your data so it will update correctly

chart.data.datasets[0].data = assembledData.data;
chart.data.datasets[0].backgroundColor = assembledData.colors;
chart.data.labels = assembledData.labels;
chart.update();

Depending on how your chart behaves you may not have to re-define colors and labels on each update.


text:
Q: Best practice: how to interpret/process QDataStream? I need to process streamed binary data (QDataStream) of defined structure created by another non-Qt program. I wonder what is the best practice to interpret that data. Let's say the data is structured (struct definition provided) in telegrams as follows and cannot be changed by myself:
4 bytes header | 2 bytes sequence number | 1 byte checksum | 10 bytes data
I see the following possibilities to handle the data in a "Telegram" class:

*

*The Telegram class has a private QByteArray member variable. All data (17 bytes) is read at once from the stream with the readRawData method and stored in there. The variables are accessed and interpreted with public methods like return (array.at(4)<<8) + array.at(5) for the sequence number, with is not very elegant.

*The Telegram class has a public char[17] member variable in union with a struct. All data is read from the stream with readRawData and stored in there. When accessing the variables after, this is done only over the struct, like telegramstruct.squenceNumber I see potential problems with this method like endianness and padding.

*The Telegram class has private member variables for each of the telegram fields like QString strHeader. When reading the telegrams from the stream, data is stored directly in these variables. Reading is done with readRawData or with the operator>> for basic types.

The code should be as fast as possible since there is a lot of data to process. I am using Qt 5.0.1 on Windows with MinGW.
My questions:

*

*Which one of the above solutions is best practice and fast, or is there a better way?

*Is reading all at once like in 1 faster than reading 4 bytes, 2 bytes, 1 byte, ... like in 3?

*With 1 and 3, I cannot use a provided header file with a defined struct, would that be bad practice?

*Is it somehow possible to have kind of a "union" with QByteArray and a structure?

*How would I easily calculate the checksum with solution 3?

Thanks a lot for your opinions and hints.
Chris

A: Well, sorry dont have that much time to write code examples, but will try to give a brief hints.
1) Performance issue. As soon as you have performance constrains first thing to optimise is an  amounts of actual reads from the stream from where data are coming. Whatever it's File/Socket/etc it's anyway QIODevice. So first thing to do is to maintain some kind of QByteArray where you adding all data available on a QIODevice on every ready attempt/handling data received notification. So below I assume there is certain QByteArray m_rawData which holds currently unprocessed bytes, which can be some amount of Telegrams + last telegram which can be received partially.
2) I would make a class like Telegram which holds telegram data, roughly saying
class Telegram {
       QString       header;
       int           sequenceNumber;
       unsigned char checkSum;
       QByteArray    data;

       ...

       bool          checkSumOK();  // check is checksum is OK for provided data

}

with constructors and operators on your taste (you can implement copy constructor/etc)..
Then I would extend this class with ( <<, >>) operators to support QDataStream which operates on temporary buffer mentioned in part 1).
So general concept is that you read data from the stream to temporary buffer as soon as possible and after read is done you fetch from resulted buffer as many Telegram's instances as possible. Then you work with QDataSteam applied on a QByteArray you can safely use read 4 bytes, read 1 byte etc calls without having that much performance impact because in general it's mostly about shifting pointers.
3) Of course if you talking about extreme condition.. you can think of unions (as being mentioned in previous answer) to make direct copy of raw data on top of a aligned structure but that way requires much more careful programming (especially taking in consideration x32/x64 archs as well as big/little endians platforms)


text:
Q: domain, subdomain and file Now i have domain and subdomain. I want what subdomain show file from domain file.
Ex.
dom.example.com -> must show file from example.com/subdomain.php
How make that with htaccsess
thanks

A: You have to put something like this in httpd.conf. You can't do it in .htaccess.
<VirtualHost *:80>
    ServerAdmin webmaster@dummy-host.example.com
    DocumentRoot "/Applications/XAMPP/xamppfiles/docs/dummy-host.example.com"
    ServerName dummy-host.example.com
    ServerAlias www.dummy-host.example.com
    ErrorLog "logs/dummy-host.example.com-error_log"
    CustomLog "logs/dummy-host.example.com-access_log" common
</VirtualHost>


text:
Q: YouTube showinfo parameter not working According to the YouTube docs for the showinfo parameter:

Setting the parameter's value to 0 causes the player to not display information like the video title and uploader before the video starts playing.

So why does the title still show in the code below? Note that I'm not using any other parameters that could cause a conflict (e.g. modestbranding).

<iframe src="https://www.youtube.com/embed/fVH2lJeZVGU?showinfo=0">

A: Showinfo doesnot work like that.
Refer to the defined method help:

Setting the parameter's value to 0 causes the player to not display
  information like the video title and uploader before the video starts
  playing. If the player is loading a playlist, and you explicitly set
  the parameter value to 1, then, upon loading, the player will also
  display thumbnail images for the videos in the playlist. Note that
  this functionality is only supported for the AS3 player.


text:
Q: Firebase .keepSynced best practices
*

*Where is the best place to put a .keepSynced(true) on a Firebase ref? This particular ref points to data that won't change much but that I need for almost all of my app's view controllers.

*Do I need an event listener for this ref if I set .keepSynced to true?


text:
Q: Print largest, second largest, smallest, and second smallest values in a list in O(n) (linear time) l = [5, 4, 3, 2, 1, 100, 69]
largest = l[0]
smallest = l[0]
seclargest = 0
secsmallest = 0
a = len(l)
b = a - 1
for i in range(a):
    if l[i] > largest:
        seclargest=largest
        if b == i:
            print(seclargest)
        largest = l[i]
    if l[i] < smallest:
        if b>i:
            secsmallest = smallest
        smallest = l[i]

print(largest)
print(seclargest)
print(smallest)
print(secsmallest)

Help, please. This code only prints the smallest and second smallest correctly but not the largest and second largest values.

A: If you want to do it in linear time (one for loop), you can modify your code as follows:
l = [5, 4, 3, 2, 1, 100, 69]
largest = -1e10  # initialize to large negative number
smallest = 1e10  # initialize to large positive number
seclargest = -1e9
secsmallest = 1e9
for x in l:
    if x > largest:
        seclargest=largest
        largest = x
    elif x > seclargest:
        seclargest = x
    elif x < smallest:
        secsmallest = smallest
        smallest = x
    elif x < secsmallest:
        secsmallest = x

print(largest)
print(seclargest)
print(smallest)
print(secsmallest)

Which outputs:
100
69
1
2

You were pretty close. You just needed to add one condition for the case where the number was smaller than the largest, but larger than the second largest and one similar condition for the second smallest.
Also, you can iterate through the list simply using for x in l, there's no need to iterate over the indices.


text:
Q: When i press buttons in my calculator , they work inconsistently Here is my logic to handle button presses.
hbp(e) {

let iVal = e.target.value;
switch(iVal) {
  case "=" :
        this.setState({calculate : true});
    break;
  case "AC" :
    this.setState({opList : [],calculate : false});
    console.log(this.state.opList)
    break;
  default:
    let list = this.state.opList.concat(iVal);
            this.setState({opList : list,calculate : false});

}

Sometimes it appends the value that i want and sometimes it appends undefined.
My pen for this issue :
https://codepen.io/furkanozdemir2003/pen/QWKYMBP?editors=1111

A: I was able to replicate this by clicking on the decimal point button. The issue is occurring because e.target is set to the <i> within the button if the pointer is over the element. For example, here's a console.log:

Since the <i> element does not have a value attribute, e.target.value will always be undefined The same is also true for the operator buttons, such as divide, multiply, add, subtract, etc.)
You can either remove the use of FontAwesome and thus the sub-elements, or update your getter to reference currentTarget instead:
let iVal = e.currentTarget.value;


text:
Q: Angular - Variable is not updating on view inside two nested loops I am trying to update the progress value in a 'round-robin' operation, but the % value is not updating in the view, but yes in the console.log().
I tried ngZone and the DetectorChanges method, but none worked.
I let you here the code. Thanks in advise.
   this.pageInfo.listPdfs.forEach((item,x) =>{
    this.pageInfo.listPdfs.forEach((item2,y) =>{
      if(x != y){
        let diff = jsdiff.diffWords(this.pageInfo.listPdfs[x].merged, this.pageInfo.listPdfs[y].merged)
        let removeds = diff.filter(el => el.removed == true).map(item => item.value).join(' ');
        let shared = diff.filter(el => el.removed === undefined && el.added === undefined).map(item => item.value).join(' ');
        let percent = (shared.trim().split(' ').filter(el => el != '').length / (removeds.trim().split(' ').filter(el => el != '').length + shared.trim().split(' ').filter(el => el != '').length)) * 100;
        this.pageInfo.resultsPdf.push({
          origin      : this.pageInfo.listPdfs[x],
          destination : this.pageInfo.listPdfs[y],
          diff        : diff,
          percent     : percent
        })
        count++;
        this.ngZone.run(()=>{

        this.pageInfo.progressAnalyzer = (count / totalRevitions)*100; // <-- THIS NOT UPDATING ON TEMPLATE
        console.log(this.pageInfo.progressAnalyzer); // <-- THIS WORKS
        this.changeDetectorRef.detectChanges();

      });
        console.log(this.pageInfo.progressAnalyzer + '%');
      }
    })
  })

And in my view, it just a simply {{pageInfo.progressAnalyzer}} but never gets updated.


text:
Q: PyPy + Cpython extension written with Rust (rust-cpython) I was going to try using PyPy. But an extension (.so file) I wrote with rust-cpython can't be loaded when executed with pypy3:
ImportError: No module named 'pkg.lib'

where lib is my lib.so file.
CPython(3.5) loads it fine. I thought PyPy had support for loading CPython extensions.
If not - what do I need to do to load .so file compiled with Rust (rust-cpython)?

A: PyPy has source compatibility only with CPython's C extension modules.  You need to recompile the .c sources.  Normally this is done by running setup.py with PyPy instead of CPython.