text:
Q: Unable to establish network connection between two servers I have 7 Ubuntu 14.04.4 servers running in EC2.  One server is hosting memcached (port 11211) and the other 6 are clients.  Of the 6 clients, 5 are able to connect and one is not (see note).
I've taken a TCP dump of both sides of the connection.  I saw that the client sent a SYN request, but no ACK was sent back.  The tcpdump looked like this for the failed connection (the SYNs repeat many times after this)
1   0.000000    172.16.1.58 172.16.1.94 TCP 76  43469 → 11211 [SYN] Seq=0 Win=29200 Len=0 MSS=1460 SACK_PERM=1 TSval=849737 TSecr=0 WS=128

And for a successful connection from a different server:
1   0.000000    172.16.1.64 172.16.1.94 TCP 76  44908 → 11211 [SYN] Seq=0 Win=29200 Len=0 MSS=1460 SACK_PERM=1 TSval=19201098 TSecr=0 WS=128
2   0.000298    172.16.1.64 172.16.1.94 TCP 68  44908 → 11211 [ACK] Seq=1 Ack=1 Win=29312 Len=0 TSval=19201098 TSecr=3160738522

Some more traces & commands:
working-client$ nc -vnz 172.16.1.94 11211
Connection to 172.16.1.94 11211 port [tcp/*] succeeded!

broken-client$ nc -vnz 172.16.1.94 11211
nc: connect to 172.16.1.94 port 11211 (tcp) failed: Connection timed out

broken-client$ nc -vnz -q 5 -u 172.16.1.94 11211
Connection to 172.16.1.94 11211 port [udp/*] succeeded!

Routing table (identical on all clients & server)
$ route
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
default         ip-172-16-1-1.e 0.0.0.0         UG    0      0        0 eth0
172.16.1.0      *               255.255.255.0   U     0      0        0 eth0

IP Tables on the broken client
broken-client$ sudo iptables -nvL -t nat
--------------------------------------

Chain PREROUTING (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination

Chain INPUT (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination

Chain OUTPUT (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination

Chain POSTROUTING (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination

broken-client$ sudo iptables -nvL
--------------------------------------

Chain INPUT (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination

Chain FORWARD (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination

Chain OUTPUT (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination

IP Tables on the server
server$ sudo iptables -nvL -t nat
--------------------------------------

Chain PREROUTING (policy ACCEPT 7332 packets, 531K bytes)
 pkts bytes target     prot opt in     out     source               destination

Chain INPUT (policy ACCEPT 7332 packets, 531K bytes)
 pkts bytes target     prot opt in     out     source               destination

Chain OUTPUT (policy ACCEPT 370 packets, 25781 bytes)
 pkts bytes target     prot opt in     out     source               destination

Chain POSTROUTING (policy ACCEPT 370 packets, 25781 bytes)
 pkts bytes target     prot opt in     out     source               destination

server$ sudo iptables -nvL
--------------------------------------
Chain INPUT (policy ACCEPT 1963K packets, 341M bytes)
 pkts bytes target     prot opt in     out     source               destination

Chain FORWARD (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination

Chain OUTPUT (policy ACCEPT 2670K packets, 5518M bytes)
 pkts bytes target     prot opt in     out     source               destination

All the clients were cloned from the same base image and should be identical.  We aren't using iptables, all the servers are on the same subnet and security group.
The problem isn't with memcached: I can reproduce the problem with telnet (port 22 or port 11211) or ssh, neither are allowed to connect, though they are allowed by the security group.
Ping is disabled, but I can traceroute between servers (cache <=> client, client <=> cache) as long as its not these two servers.
It appears (see traces above) that a UDP connection can be established, but not TCP.
The problem is persistent.
Note: the 6 client servers are part of an auto-scaling group (in a VPC).  There are between 1 and 6 servers, depending on load, and sometimes one server fails to connect.  IP addresses and server names do get reused.
What can I look at to find where the connection is failing?

A: This seems to be caused by ARP caching (MAC address caching) in new linux kernels.
https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1331150


text:
Q: Rating stars for the iphone I have been looking for a 5-Star rating control for a while now and have not found a solid solution.
This question:
Anyone know whether there is a 5-star rating component on iPhone?
Provided a couple of links to projects which are no longer available, and i have not been able to track them down.
Edit:  I am apparently bad at tracking down projects, but I think part of my question still stands.  Here is the updated link http://code.google.com/p/s7ratingview/downloads/detail?name=s7ratingview-basic-release.zip
So this questions is 2 part - Is there a solid premade solution out there, and could you direct me to it?
Is it better / fairly easy to (yes, i realize these two facets are in conflict) grow my own solution?  Could you give me some tips/resources to do so.  I understand the basic idea of subclassing UIView and tracking touch events to expand an image ontop of another image to look like stars, but a little more direction would be helpful.  I have been developing on the iphone for a little under a week and still need a bit of hand-holding.

A: You can give DYRateView a try.  I wanted to reuse the one in Ray's tutorial as much as possible, but there were several features missing from it, so I made one myself.
You can check out my blog for further details on how to use DYRateView in your project: http://iappexperience.com/post/23227218867/dyrateview-a-simple-yet-powerful-rating-control-for.

A: Try Ray Wenderlich's custom UIView with a 5-star rating.

[EDIT]
You can also try using UISlider and supplying a minimum/maximum track images.

A: Another way you may try DLStarRating lets you customize the area below the stars, detecting touches.

A: Just Easy to Give a Star Follow this Code and Copy and Paste into Your Project and Simply Run.
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.

    startview = [[UIView alloc] initWithFrame:CGRectMake(45, 70, 230, 50)];
    startview.backgroundColor = [UIColor redColor];
    NSInteger getrating = 0;
    int x = 5;
    for (int k = 1; k <= 5; k++)
    {
        UIImageView * mystarimage = [[UIImageView alloc] initWithFrame:CGRectMake(x, 5, 40, 40)];

        if (getrating >= k)
        {
            mystarimage.image = [UIImage imageNamed:@"star.png"];
        }
        else
        {
            mystarimage.image = [UIImage imageNamed:@"gray-star.png"];
        }

        mystarimage.tag = k;
        mystarimage.userInteractionEnabled = YES;
        [startview addSubview:mystarimage];
        UITapGestureRecognizer *letterTapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(updateStar:)];
        rateMember = mystarimage.tag;
        NSLog(@"rateing %ld",(long)rateMember);
        letterTapRecognizer.numberOfTapsRequired = 1;
        [mystarimage addGestureRecognizer:letterTapRecognizer];
        x = x + 45;
    }
    [self.view addSubview:startview];
}

-(void)updateStar :(UITapGestureRecognizer*)sender
{
    UIView *view = sender.view;
    NSLog(@"hello ji %ld", (long)view.tag);
    NSInteger getrating;

    switch (view.tag)
    {
        case 1:
            NSLog(@"press 1");
            rateMember = 1;
            break;
        case 2:
            NSLog(@"press 2");
            rateMember = 2;
            break;
        case 3:
            NSLog(@"press 3");
            rateMember = 3;
            break;
        case 4:
            NSLog(@"press 4");
            rateMember = 4;
            break;
        case 5:
            NSLog(@"press 4");
            rateMember = 5;
            break;
        default:
            NSLog(@"press 5");
            rateMember = 5;
            break;
    }

    getrating = rateMember;
    NSLog(@"Get rating -------> %ld",(long)getrating);
    int x = 5;
    for (int k = 1; k <= 5 ; k++)
    {
        UIImageView * mystarimage = [[UIImageView alloc] initWithFrame:CGRectMake(x, 5, 40, 40)];

        if (getrating >= k)
        {
            mystarimage.image = [UIImage imageNamed:@"star.png"];
        }
        else
        {
            mystarimage.image = [UIImage imageNamed:@"gray-star.png"];
        }
        mystarimage.tag = k;
        mystarimage.userInteractionEnabled = YES;
        [startview addSubview:mystarimage];
        UITapGestureRecognizer *letterTapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(updateStar:)];
        letterTapRecognizer.numberOfTapsRequired = 1;
        [mystarimage addGestureRecognizer:letterTapRecognizer];
        x = x + 45;
    }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why are packed structures not part of the C language? Every C compiler offers the option to "pack" C structures (e.g. __attribute__ ((__packed__)), or #pragma pack()). Now, we all know that packing is required, if we'd like to send or store data in a reliable way. This must also have been a requirement since the first days of the C language.
So I wonder why packed structures are not part of the C language specification? They're not even in C99 or C11 even though the necessity of having them is known for decades now? What I am missing? Why is it compiler specific?

A: I guess it's because it's depending on the combination of target CPU / compiler used. This means that it's better to be a compiler directive (as it's related to that) than a language aspect, because how to spec that? The only way they could do it is with union.
Raymond's article gives some insight in why this is: http://www.catb.org/esr/structure-packing/

A: There are three main factors.

*

*Some processors cannot access unaligned data (for example an integer or float starting on an odd address). Attempting to do triggers an exception.

*Some processors can access unaligned data, but at a performance cost.

*Most structures are accessed by a single set of C/C++ source code, and interoperability with other languages is the exception, not the rule.

With these factors in mind, both the standard and all C/C++ compilers routinely pad structures to ensure optimal alignment for the processor, but also provide mechanisms to override this if needed for the purposes of interop.
This is by no means something that has been overlooked. It is extremely well understood and the current situation is by design. The latest versions of the C++ standard have extensive support for handling alignment issues, which perhaps you are not familiar with.

A: It is compiler-specific because it is not in the standard. And it's not in the standard because it would be difficult to specify in a way that wouldn't require lots of implementation effort for compilers of obscure platforms with enforced alignment restrictions.
And none of that effort has much justification, because every compiler/platform that anyone using a C89 or later compiler cares about already has it implemented.


text:
Q: Setting Custom Adapter to a Layout I am new to creating custom listviews.  I've created a new adapter, but would like to set its adapter layout to one of my own.  How would I change this method to select my own layout file?  I would be grateful for an example.
public override View GetView(int position, View convertView, ViewGroup parent)
{
    View view = convertView;
    if (view == null)
        view = context.LayoutInflater.Inflate(Android.Resource.Layout.SimpleListItem1, null);
    view.FindViewById<TextView>(Android.Resource.Id.Text1).Text = items[position];
    return view;
}

A: view = context.LayoutInflater.Inflate(R.Layout.my_list_item, null);

A: if you want to develop a custom adapter for a listview,
1)your activity must extend ListActivity.
2)second,you must have a listview which has the id "list".
3)you should have a layout for your rows. it should be like
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" >

    <ImageView
        android:id="@+id/icon"
        android:layout_width="22px"
        android:layout_height="22px"
        android:layout_marginLeft="4px"
        android:layout_marginRight="10px"
        android:layout_marginTop="4px"
        android:src="@drawable/ic_launcher" >
    </ImageView>

    <TextView
        android:id="@+id/label"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@+id/label"
        android:textSize="20px" >
    </TextView>

</LinearLayout>

4) your main activity should be like
public class MyListActivity extends ListActivity {
  public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    String[] values = new String[] { "Android", "iPhone", "WindowsMobile",
        "Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X",
        "Linux", "OS/2" };
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
        android.R.layout.simple_list_item_1, values);
    setListAdapter(adapter);
  }

that should do the work.


text:
Q: DropDownListfor in EditorTemplates Am creating a EditorTemplate for Boolean fields to have Yes no DropDown and below is my code
@model Nullable<bool>

@{
    var listItems = new[]
    {
        new SelectListItem { Value = "true", Text = "Yes" },
        new SelectListItem { Value = "false", Text = "No" }
    };

}

    @Html.DropDownListFor( ????, listItems,"")

Where i want to load the Drop-down with previously selected item which is available in Model which can be true or false
From My view i will be getting true or false in Model Property to this template. How can i use DropDownfor as it accepts linq in 1st paramtere ?
Thanks

A: You can either use
@Html.DropDownListFor(m => m, listItems, "")

or
@Html.DropDownList("", listItems, "")


text:
Q: Stastics Probability Suppose we draw two cards from a deck of playing cards. What is the probability of drawing two spades P(two spades)?

*

*a. P(two spades) = $\frac{1}{26}$

*b. P(two spades) = $3\cdot\frac{1}{51}$

*c. P(two spades) = $\frac{2}{52}$

*d. P(two spades) = $\frac{1}{16}$

Is it A, please help thanks

A: The number of ways to pick two cards is $C(52, 2)$, and the number of ways to pick two spades is $C(13,2)$
Thus the probability is $\frac{C(13,2)}{C(52,2)}$, which is equal to 1/17


text:
Q: Date and username if clicked I have a tracker, the users add the lines to it on a daily basis.
I need a code that shows the current date and username, once a cell is double clicked. Co column A would be a date cell and column P would be username.
I had some code but it shows user and date once a tick is done. Now I need a click.
Sub CheckBox_Date_Stamp()

Dim cbx As CheckBox

'Application.Caller returns the name of the CheckBox that called this macro
Set cbx = ActiveSheet.CheckBoxes(Application.Caller)

'.TopLeftCell returns the cell address located at the top left corner of the cbx checkbox
With cbx.TopLeftCell
    'Check the checkbox status (checked or unchecked)
    If cbx.Value = xlOn Then
        ' Checkbox is Checked
        ' User Name and Date-Time
        .Offset(0, 1).Value = Environ("UserName")
        .Offset(0, 2).Value = Now
    Else
        ' Checkbox is unchecked; Clear cell contents?
        .Offset(0, 1).ClearContents
        .Offset(0, 2).ClearContents
    End If
End With

End Sub

Will you be able to help?
thank you

A: Quite tough to get what exactly do you mean, but in general, you need SelectionChange an event in worksheet. Add the following in the worksheet here:

Option Explicit

Private Sub Worksheet_SelectionChange(ByVal Target As Range)

    If Target.Cells.Count <> 1 Then Exit Sub

    If Target.Address = Cells(1, 2).Address Then
        Cells(1, 1) = Application.UserName
        Cells(1, 16) = Now
    Else
        Debug.Print "This was not B1"
    End If

End Sub

Once you click on B1 you will get UserName and time in columns A and P.

A: This will place the computer username and date/time in column A/B of whichever cell you double-click in.
Add the code to the worksheet rather than a separate module.
You may also want to add code to check that column A:B doesn't already contain data, or ask for confirmation.
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
    Cells(Target.Row, 1) = Environ("username")
    Cells(Target.Row, 2) = Now
End Sub


text:
Q: obtener la utilidad (ganancia) de una venta segun historial de lotes (PHP MYSQL) estoy en un tremendo dilema, espero puedan ayudarme se los agradeceria bastante.
Tengo estas tablas mysql:
productos:
-------------------------------
|id_producto|id_canal|unidades|
|123        |1       |15      |
-------------------------------

productos_lotes: guardo el registro de unidades ingresadas y varia el precio_costo
-------------------------------------------------------
|id_producto|id_canal|fecha     |unidades|precio_costo|
|123        |1       |2021-09-24|10      |20.00       |
|123        |1       |2021-09-23|5       |10.00       |
-------------------------------------------------------

productos_ventas: guardo la cantidad de unidades vendidas, si agrego una nueva venta le sumo las unidades actuales mas la cantidad a vender
-------------------------------
|id_producto|id_canal|n_ventas|
|123        |1       |10      |
|123        |2       |5       |
-------------------------------

ahora bien yo lo que quisiera es obtener la ganancia que e generado comparando el precio de costo - el precio de venta;
Lo que yo estoy haciendo:
guardar todas las cantidades de ventas en una tabla productos_ventas, cosa que yo ya se cuantas unidades estoy vendiendo del producto (update n_ventas+cantidad_a_vender)
y al momento de realizar una venta lo que hago es recorrer todos los lotes del producto e ir sumando primer lote + siguiente lote hasta que el resultado me de mayor o igual que n_ventas + cantidad_a_vender y me detengo allí, con esto logre encontrar en que lote me encuentro y despues de esto extraigo cuanto me costo ese lote y hago la siguiente resta (precio_venta_producto - precio_costo_lote) y el resultado es mi utilidad.
yo se que esto no es lo mas ortodoxo pero no se me ocurre una mejor idea, si alguien pudiera ayudarme con este problema estaria muy muy agradecido
notas:
esta es la estructura de la lista de productos al momento de realizar una venta: ($_POST['detalle_venta'])
2109241629406588|500.00|10;2109241713471373|100.00|1

id_producto | precio_venta (modificable) | unidades a vender ;


text:
Q: generate right click and select custom menu R shiny JS automatically I have created the following App using R Shiny
  library(shiny)
  library(rhandsontable)
  library(shinyjs)

ui <- fluidPage(
sidebarLayout(sidebarPanel = "Inputparameter",
            numericInput(inputId = "Noi", label = "Row Count", value = 7, 0, max = 1000)),mainPanel (useShinyjs(),rHandsontableOutput(outputId = 'Adjusttable', width ='100%', height
= '100%'),dataTableOutput(outputId = "Init_Tbl")))

server <- function(input, output, session) {
DF <-reactive({
DF_Out<-data.frame(ID = 1:5,'Column2' = 0, Start = "D",FM="",stringsAsFactors = FALSE)
return(DF_Out)})

output$Adjusttable<-renderRHandsontable({
input_Val<-input$Noi
js_func<-paste("function (key, options) {this.alter('insert_row',[0],",
input_Val,");this.render();}")
 ###
namestate<-paste("Add",input_Val, "rows at the bottom")
output_Adjusttable<- DF() %>% head(5) %>% rhandsontable(width = 280, height = 677,stretchH =
"all") %>%hot_context_menu(customOpts = list(insert_row = list(name = namestate,callback =
htmlwidgets::JS(js_func))))
return(output_Adjusttable)}, quoted = FALSE )}
shinyApp(ui, server)

the js_func line generates a right click option that adds extra rows. The number of extra rows is determined by the numericinput row count. Is it possible to automatically add the extra rows by the numericinput without the right click.

A: This example, will add as many empty rows to the output as given by input$Noi. The idea is that you create an empty data.frame which has input$Noi rows and rbind it to your original data.frame:
library(shiny)
library(rhandsontable)

ui <- fluidPage(
   sidebarLayout(sidebarPanel = "Inputparameter",
                 numericInput("Noi", "Row Count", 7, 0, 1000)),
   mainPanel(rHandsontableOutput("Adjusttable", "100%", "100%"),
             dataTableOutput("Init_Tbl"))
)
server <- function(input, output, session) {
   DF <- reactive({
      DF_Out <- data.frame(ID = 1:5,
                           Column2 = 0,
                           Start = "D",
                           FM = "")
      df_fill <- data.frame(ID = NA_integer_,
                            Column2 = NA_real_,
                            Start = NA_character_,
                            FM = NA_character_)[rep(1L, input$Noi), ]
      res <- rbind(DF_Out,
                   df_fill)
      rownames(res) <- NULL
      res
   })

   output$Adjusttable <- renderRHandsontable({
      DF() %>%
         rhandsontable(width = 280,
                       height = 677,
                       stretchH = "all")
   })
}
shinyApp(ui, server)


text:
Q: repeating prepositions in a sentence sounds more or less natural? Does repeating prepositions in a sentence sound more or sound less natural?
For example in the following example, What sounds more natural?

This dog likes to yawl and hiccup.

or

This dog likes to yawl and to hiccup.

A: Like so many situations in English, how natural it sounds will depend on both context and intent.
As a general rule, we like to take shortcuts in English, so if the meaning remains unaffected, dropping (or "eliding") the second preposition in sentences like this is both common and natural. By extension, if there's no apparent reason to repeat it, the repetition may sound a bit unusual. However, there are several reasons why you might choose to repeat it due to context and/or intent:

*

*emphasising that both words are important. A typical way to do this is in spoken English is to stress the word "and" (in written English, we would show this with bold or italic font: "This dog likes to yawl and to hiccup"), and in this situation it sounds natural to repeat the "to".

*giving the statement a sense of formality, for instance as part of a speech. As shortcuts tend to be associated with informal or conversational English, not taking the shortcut conveys a sense of properness and formality.

*wanting to sound very correct and exact, perhaps even pedantic, for example in a police report ("the accused began to swear and to spit"), in legislation ("to facilitate and to promote learning"), or in a grumpy old grammarian's classroom (well, that's the way a particular high-school English teacher of mine used to speak!).
The one other situation where it's natural to repeat the "to" is in a longer sentence where the bare infinitive (i.e. without "to") would be well separated from the to-infinitive, typically because of intervening objects, phrases or clauses. For example:

I've been authorised to provide information about the duties that you
  will carry out and to instruct you in the necessary procedures.

A: Chappo's answer is correct, but I have another piece of advice.
When you include the to before each verb, it is clear that you are talking about two different actions: The dog likes to yawn and the dog likes to hiccup.
Without the second to it's possible to analyse that statement as describing one action with two parts: The dog likes to yawn-and-hiccup.  It doesn't like a yawn or a hiccup on its own.  Whenever it yawns, it must also hiccup.  Whenever it hiccups it must also yawn.
That's a strange example, but consider these:
I like to walk along the beach and go fishing
I like to walk along the beach and to go fishing
In the first example, fishing is connected to walking along the beach.  There's one action (with two parts) that the speaker likes: walking along the beach and then while walking along the beach, fishing (from the beach).
In the second example, there is not necessarily any connection between walking and fishing.  The speaker likes walking and likes fishing but does not necessarily like walking and fishing at the same time.


text:
Q: Paypal Express Checkout with Intent Authorize not returning authorization id We are using Paypal express checkout which is integrated in our UI project with javascript.
Everything working as expected when we use intent: sale.
i.e. execute call with intent: sale returning { sale : {id: ...} } object for related_resources property.
But when I use intent: authorize no { authorization : {id: ...}} is returning for related_resources property. ( it's same behaviour for both paypal, credit_card payment method types).
Note: I am passing intent: sale/authorize for payment call

A: Its been fixed from paypal server api update from their side. Thanks team.


text:
Q: Find duplicate directory trees on a Mac Sounds dumb, but actually, I'm not looking for single duplicate files (which is easily achieved via either specific programs or via command line tools like diff), but for complete directory trees (including the files, of course) I expect to have on my computer. Taking a file search and checking the individual location of each file is not easy to be handled - think of the copy of a folder with music or images. Having an individual file with several copies is not a problem nowadays (I don't really care about 5MB), but a complete artist with several albums in several instances might still be annoying. And after nearly 20 years of copying files back and forth, I'm pretty sure I have forgotten some "backups" in obscure locations.
tl;dr:
I want to have a list of entire directories which appear repeatedly on my machine (different drives possibly) - this would mean that the directories have the same content (files or other directories).
Being identical, I would consider content (to start with: size) and name being identical, owner and date might differ.


text:
Q: custom view: horizontal stacked bar. Any libs? Trying to implement so-called stacked Bar chart.
Horizontal bar with different colors depends of input data.
I'm going to write this custom view from scratch.
Does anyone know any libs that can do this? Seems it is common chart, but can't find lib..


text:
Q: CoinFlipGame help.. Input True in a if statement This is a game i am trying to make. You start off the game with $1500, and every time you want to play the game you must pay $100.( select 1 to play) (press 2 to read rule) (press 3 to see high scores) The game is a flipping coin game. When the game start there is $4 in the pot. When it's head the money in the pot doubles and you flip again. When it's tail , you obtain all the money in the pot. When you have less then $100 you are broke (game over). You return to the starting menu... And i wish to make it so that this game record your highest money (high score)
So this is what i got so far...
public class COINFLIP
{
public static void main(String[] args)
{
int tail = 0;//tail
int head = 0;//head
int x = 0;//tries
while (x < 1)
{
    int coin;//coin
    coin = (int) (Math.random() * 2);
    x++;
    if (coin == 0) {
    headCount++; // int type
    wasHeads = true; // boolean type
    wasTails = false;
  } else {
    tailCount++;
    wasHeads = false; // boolean type
    wasTails = true;
 }
    int sm = 1500;//starting money
    int cm;//current money
    int pm = 4;//money in the pot
    cm = sm - 100 + pm;
}
if (wasHeads)
{
pm = pm * 2;
}
else if (wasTails)
{
System.out.println("Your money is: $" + cm);
}
if (cm < 100);
System.out.println("Sorry, but you are broke!!!");
}
}

errors:
C:\Users\Loyal Xie\Documents\COINFLIP.java:14: error: cannot find symbol
    headCount++; // int type
    ^
symbol:   variable headCount
location: class COINFLIP
C:\Users\Loyal Xie\Documents\COINFLIP.java:15: error: cannot find symbol
    wasHeads = true; // boolean type
    ^
symbol:   variable wasHeads
location: class COINFLIP
C:\Users\Loyal Xie\Documents\COINFLIP.java:16: error: cannot find symbol
    wasTails = false;
    ^
symbol:   variable wasTails
location: class COINFLIP
C:\Users\Loyal Xie\Documents\COINFLIP.java:18: error: cannot find symbol
   tailCount++;
   ^
symbol:   variable tailCount
location: class COINFLIP
C:\Users\Loyal Xie\Documents\COINFLIP.java:19: error: cannot find symbol
    wasHeads = false; // boolean type
    ^
symbol:   variable wasHeads
location: class COINFLIP
C:\Users\Loyal Xie\Documents\COINFLIP.java:20: error: cannot find symbol
    wasTails = true;
    ^
symbol:   variable wasTails
location: class COINFLIP
C:\Users\Loyal Xie\Documents\COINFLIP.java:27: error: cannot find symbol
if (wasHeads)
    ^
symbol:   variable wasHeads
location: class COINFLIP
C:\Users\Loyal Xie\Documents\COINFLIP.java:27: error: illegal start of type
if (wasHeads)
   ^
C:\Users\Loyal Xie\Documents\COINFLIP.java:29: error: cannot find symbol
pm = pm * 2;
^
symbol:   variable pm
location: class COINFLIP
C:\Users\Loyal Xie\Documents\COINFLIP.java:29: error: cannot find symbol
pm = pm * 2;
     ^
symbol:   variable pm
location: class COINFLIP
C:\Users\Loyal Xie\Documents\COINFLIP.java:31: error: cannot find symbol
else if (wasTails)
         ^
symbol:   variable wasTails
location: class COINFLIP
C:\Users\Loyal Xie\Documents\COINFLIP.java:31: error: illegal start of type
else if (wasTails)
        ^
C:\Users\Loyal Xie\Documents\COINFLIP.java:33: error: cannot find symbol
System.out.println("Your money is: $" + cm);

                                        ^
symbol:   variable cm
location: class COINFLIP
C:\Users\Loyal Xie\Documents\COINFLIP.java:35: error: cannot find symbol
if (cm < 100);
    ^
symbol:   variable cm
location: class COINFLIP
14 errors

But there is a lot of errors, and my statement is still errored... i think the problem is with in      the if statement and i think i am still having trouble setting head = true and then use it in if statement....  Any thoughts?

A: If you corrected your indentation you may notice that with
if (coin == 0)
{
    headCount++; // int type
}
    wasHeads = true; // boolean type

wasHeads is NOT in the if statement and will be executed 100% of the time.  The same is true for wasTails = true;
This means that later your testing for if (wasHeads) will always be executed.
Also, why have this in a while loop as it will only execute once.
Edit
Regarding your errors, you need to define variables before you can use them.
For example
headCount++;

Needs to be defined first as
int headCount = 0;

A: You assignments to your booleans aren't in their respective test cases (and you should really prefer the simple else). So something like,
if (coin == 0) {
  headCount++; // int type
  wasHeads = true; // boolean type
  wasTails = false;
} else {
  tailCount++;
  wasHeads = false; // boolean type
  wasTails = true;
}


text:
Q: parametric equation of level curve in three dimensional plane What is the parametric equation for the tangent plane to the level curve of the function $$w(x,y,z) = xy+yz+xz$$ at the point $(1,-1,2)$?
My answer was:
$$(x,y,z) = (1,-1,2)+r<1,0,δz/δx>+<0,1,δz/δy>$$
but since $δz/δx$ and $δz/δy$ are not defined at $(1,-1,2)$, is there another way to find the parametric equation to the tangent plane?

A: When $w(x,y,z)$ is constant (i.e. defining a level surface), then the normal vector $\vec N$ to the surface points in the direction of the gradient $\nabla w$.
Here, the gradient is given by
$$\begin{align}
\vec N&=\nabla w(x,y,z)\\\\
&=\nabla (xy+yz+xz)\\\\
&=\hat x \frac{\partial w}{\partial x}+\hat y \frac{\partial w}{\partial y}+\hat z \frac{\partial w}{\partial z}\\\\
&=\hat x (y+z)+\hat y (x+z)+\hat z (x+y)
\end{align}$$
which at $(1,-1,2)$ is $\vec N=\hat x+3\hat y$.
The equation of the plane that passes through $(1,-1,2)$ and has normal $\hat N=\hat x+3\hat y$ is
$$\hat N \cdot (\vec r - \vec r_0)=0$$
where $\vec r$ locates an arbitrary point of the surface and $\vec r_0$ is the given point $\vec r_0=\hat x -\hat y+2\hat z$.
Thus, the equation of the tangent plane to the level surface at $(1,-1,2)$ is given by
$$(x-1)+3(y+1)=0$$

Now, if we want a parametric description of the plane we need two vectors that span the plane.  Let's find two more point on the plane.  This is arbitrary, provided that the triad of points are not collinear.
For Point 1, we choose $\vec r_1=\hat x 4-\hat y 2+\hat z 2$, and for Point 2 we choose $\vec r_2=\hat x-\hat y$.
Then, two vectors that span the plane are given by the difference of pairs of the three points chosen.  We can therefore write these vectors as
$$\begin{align}
\vec T_1&=\hat x3-\hat y+\hat z 2\\
\vec T_1&=\hat x3-\hat y
\end{align}$$
Note that $T_1 \times T_2$ is parallel to $\vec N$ as required.
Finally, the parametric description of the plane can be expressed as
$$\begin{align}
\vec r&=\vec r_0+u\vec T_1 +v \vec T_2\\\\
&=(\hat x -\hat y+2\hat z)+u(\hat x3-\hat y+\hat z 2)+v(\hat x3-\hat y)
\end{align}$$
or in non-vector form
$$\begin{align}
x&=1+3u+3v\\
y&=-(1+u+v)\\
z&=2(1+u)
\end{align}$$
Note that this parametric description is not unique.

A: You find the tangent plane via the point-normal form of the equation of the plane. That is, you now the normal, which gives you the orientation of the plane, and a point on the plane, which gives you the exact positioning of the plane in space. Per Wolfram MathWorld (http://mathworld.wolfram.com/Plane.html), you have:
$$\vec n \cdot (\vec x - \vec x_0)=0$$
Where $\vec x_0$ is the point on the plane, and $\vec n$ is the normal vector. In your case, they would be as follows: $\vec x_0 = <1,-1,2>$
To find the normal of the plane, you have to find the slope of the surface at that point. To do this, use the gradient of the original function:
$$\vec \nabla w(x,y,z)=<\frac{\partial w}{\partial x},\frac{\partial w}{\partial y},\frac{\partial w}{\partial z}>=<y+z,x+z,y+x>$$
This function gives you the slope of the tangent plane, much like the derivative gives you the slope of the tangent line in 2D. Evaluated at the above point, you obtain: $\vec n = <-1+2,1+2,-1+1>=<1,3,0>$.
Going back to the original equation, you obtain:
$$<1,3,0>\cdot(<x,y,z>-<1,-1,2>)=0$$
$$(x-1)+3(y--1)+0(z-2)>=x-1+3y+3=0$$
I think this answers your question. If it doesn't, please help me too. Thanks!


text:
Q: How to enable all suggestions in intellisense all the time? I am quite new to Microsoft Visual Studio. I am using VS Community 2019. I want to enable all suggestions in intellisense all the time, how can I do that?
For example, I have a vector variable v2qPenLine which is a QVector<QVector<QPen>>. The vector variable is named in such a way so that I have easy access to it through intellisense. When I try to use it inside setPen() method (which is expecting a QPen but not a vector of QPen I guess) the intellisense does not suggest this vector:

To have it suggested, I need to click on the + button at the bottom and then it suggests the correct variable immediately:

This behaviour is not convenient at all. How can I change this behaviour of the intellisense so that it suggests only based on the name and do it all the time so that I don't have to click the + button at the bottom of the suggestion list? I think there should be a setting for this and so I tried to look up the settings of intellisense but I was unable to change this behaviour. I also couldn't find any reference to this on the internet.

A: I think it is a problem of your VS IDE Intellisense. And you can see that the Intellisense of your environment does have any info about variables, functions, classes ....on the first time. It should show all types on the first time. In your side, it only has the type of methods, quite strange.

Try the following suggestions:
1) disable any third party extensions under Extensions--> Manage Extensions-->Installed to check if there is an extension which caused that.
2) close VS, delete all files under C:\Users\xxx\AppData\Local\Microsoft\VisualStudio\16.0_xxx\ComponentModelCache
3) reset all vs settings under Tools-->Import and Export Settings-->Reset all settings
4) close Vs, delete .vs hidden folder under the solution folder and then restart your project to test again.
5) repair vs or update it if there is a new release version


text:
Q: Botframework-WebChat - Why doesn't it work with Internet Explorer? I've got the webchat working correctly in Chrome but not in IE.
My app is an Angular website using WebChat to connect to my bot.
Code looks like this (technically this is TypeScript, not JavaScript, the arrow functions are transpiled out):
directLine: DirectLine = new DirectLine({ secret: environment.botDirectLineSecretKey })

@ViewChild("botWindow") botWindowElement: ElementRef;

ngOnInit() {

    this.directLine.activity$
      .filter(activity => activity.type === "event" && activity.name === "init")
      .subscribe(activity => this.changeSize());

    BotChat.App({
      botConnection: this.directLine,
      user: { id: 'user' },
      bot: { id: 'bot' },
    }, this.botWindowElement.nativeElement);

}

changeSize(){
    console.log("here")
    var container = document.getElementById("bot-chat-container");
    container.classList.add("fullSize");
}

In Internet Explorer, I get this error in the console:

ERROR TypeError: You provided an invalid object where a stream was
  expected. You can provide an Observable, Promise, Array, or Iterable.

If I switch botConnection: this.directLine to directLine: this.directLine, the webchat works but then the changeSize() method never gets called.
Any help is appreciated. This bot is going on a public website and IE must be supported.

A: I found the answer. After reading answers and comments that were posted, I created a "vanilla" html/JavaScript version of this code and it, as stated by Eric Dahlvang above, worked perfectly. I then focused on the Angular side of things for a while.
Then I noticed one difference in my original Angular code vs my plain JavaScript version and the samples found here: https://github.com/Microsoft/BotFramework-WebChat. I made a simple change:
Changed this:
directLine: DirectLine = new DirectLine({ secret: environment.botDirectLineSecretKey })
to this:
directLine: DirectLine = new BotChat.DirectLine({ secret: environment.botDirectLineSecretKey }) (note that I am now using BotChat.DirectLine)
and everything works. Unfortunately, I don't know why.

A: Arrow functions are not supported in IE:
https://caniuse.com/#feat=arrow-functions
https://learn.microsoft.com/en-us/scripting/javascript/functions-javascript#arrow-functions
The code you've shared should work in IE if it is modified to uses actual functions:
    this.directLine.activity$
        .filter(isInitEvent)
        .subscribe(changeSize);

...

    function isInitEvent(activity) {
        return activity.type === "event" && activity.name === "init";
    }

    function changeSize(activity) {
        console.log("here")
        var container = document.getElementById("bot");
        container.classList.add("fullSize");
    }


text:
Q: How to prevent freezing PhoneGap app in Android when doing asynchronous AJAX call? I have PhoneGap-Android app and I am using Jquery. I am doing ASYNCHRONOUS AJAX call and during the call, app just freezes and waits after AJAX call finish ( it is mainly noticeable when on GSM connection ).
I would understand this, if I would be doing synchronous request, but I have:
$.ajax({type: 'POST',url: 'http://www.example.com', data: data,async:true,success:callback});

Anybody can help ?

A: Can you get your AJAX call off the main UI thread?  Example:
public class JsonParsingActivity extends Activity {

    private static final String url = "http://search.twitter.com/search.json?q=javacodegeeks";
    protected InitTask _initTask;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Button button = (Button)findViewById(R.id.button1);
        button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                _initTask = new InitTask();
                _initTask.execute( getApplicationContext() );
            }
        });
    }

    @Override
    public void onStop() {
        super.onStop();
        _initTask.cancel(true);
    }

    protected class InitTask extends AsyncTask<Context, String, SearchResponse>
    {
        @Override
        protected SearchResponse doInBackground( Context... params )
        {
            InputStream source = retrieveStream(url);
            SearchResponse response = null;
            if (source != null) {
                Gson gson = new Gson();
                Reader reader = new InputStreamReader(source);
                try {
                    response = gson.fromJson(reader, SearchResponse.class);
                    publishProgress( response.query );
                    reader.close();
                } catch (Exception e) {
                    Log.w(getClass().getSimpleName(), "Error: " + e.getMessage() + " for URL " + url);
                }
            }
            if (!this.isCancelled()) {
                return response;
            } else {
                return null;
            }
        }

        @Override
        protected void onProgressUpdate(String... s)
        {
            super.onProgressUpdate(s);
            Toast.makeText(getApplicationContext(), s[0], Toast.LENGTH_SHORT).show();
        }

        @Override
        protected void onPostExecute( SearchResponse response )
        {
            super.onPostExecute(response);
            StringBuilder builder = new StringBuilder();
            if (response != null) {
                String delim = "* ";
                List<Result> results = response.results;
                for (Result result : results) {
                    builder.append(delim).append(result.fromUser);
                    delim="\n* ";
                }
            }
            if (builder.length() > 0) {
                Toast.makeText(getApplicationContext(), builder.toString(), Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(getApplicationContext(), "The response was empty.", Toast.LENGTH_SHORT).show();
            }

        }

        @Override
        protected void onCancelled() {
            super.onCancelled();
            Toast.makeText(getApplicationContext(), "The operation was cancelled.", 1).show();
        }

        private InputStream retrieveStream(String url) {
            DefaultHttpClient client = new DefaultHttpClient();
            HttpGet getRequest;
            try {
                getRequest = new HttpGet(url);
                HttpResponse getResponse = client.execute(getRequest);
                HttpEntity getResponseEntity = getResponse.getEntity();
                return getResponseEntity.getContent();
            } catch (Exception e) {
                Log.w(getClass().getSimpleName(), "Error for URL " + url, e);
                return null;
            }
        }

    }

}

A: Ran into the same problem today. Solved it by using a setTimeout with a 10ms delay.
Not sure why it works, which is scary. But does work.

A: I had the same problem, and I solved this by calling the ajax request on "deviceready" event fired by phonegap.
I read an tutorial by accident here which says that the ajax request can be sent after the application is loaded properly. First bind to document deviceready event and send the ajax request inside the event handler. Doing in this way can solve the blocking UI problem.
function appReady(){
  // do the ajax here
}
document.addEventListener("deviceready", appReady, false);

I hope this can also solve your issue.

A: From the Jquery docs:
async
Boolean
Default: true
By default, all requests are sent asynchronously (i.e. this is set to true by default). If you need synchronous requests, set this option to false. Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active.
Since the phonegap code is running on localhost it will be cross-domain. If you can, do a request via GET instead of POST.

A: Try this code:
 $(document).ready(function () {
        $.ajax({
        type: "POST",
        url: "https://demo.yoursuppliernetwork.com/tnvrs/userservice/login/checkUser",
        data:{"username":login,"password":password},
        dataType:"json",
        contentType: "application/json; charset=utf-8",
        success: function(html)
        {
            ss=html;
            console.log(ss);
            document.write("success");
        },
       error:function(error)
       {
        console.log(error.status)
        document.write("error");
       },
       complete:function(html){
       console.log()
       document.write("complete");
       }
            });

     });


text:
Q: Method for Returning Top 'n' Values from 'x' Tables and Joining I'm trying to write a query that returns the top 3 values from each table, then joins the tables together on their shared year.
SELECT los_ty_year AS `year`, `los_ty_#_nights`, los_ty_nights_frequency, reg_ty_region, reg_ty_region_frequency

FROM  ( SELECT los_ty_year, `los_ty_#_nights`, los_ty_nights_frequency
        FROM ty_jp_kr_length_of_stay
        WHERE los_ty_year = 2017
        ORDER BY los_ty_nights_frequency desc
        LIMIT 3) T1

JOIN (
        SELECT reg_ty_year, reg_ty_region, reg_ty_region_frequency
        FROM ty_jp_kr_region_residence
        WHERE reg_ty_year = 2017
        ORDER BY reg_ty_region_frequency DESC
        LIMIT 3 ) T2

ON T1.los_ty_year = T2.reg_ty_year
LIMIT 3

Expected Output
year   los_ty_#_nights   los_ty_nights_freq   reg_ty_region   reg_ty_region_freq
2017   2_nights          .333                 south           .256
2017   3_nights          .244                 southwest       .195
2017   1_night           .215                 west            .137

My problem is that I always get duplicates for one of the columns, no matter how I seem to order.

A: The major problem with your current join logic is that all 3 top records from both subqueries share the same year 2017.  This means that your join is effectively a cross join, and should yield a result set with 9 records.  With MySQL 8+, we can handle this using ROW_NUMBER:
WITH cte1 AS (
    SELECT los_ty_year, `los_ty_#_nights`, los_ty_nights_frequency,
           ROW_NUMBER() OVER (ORDER BY los_ty_nights_frequency DESC) rn
    FROM ty_jp_kr_length_of_stay
    WHERE los_ty_year = 2017
),
cte2 AS (
    SELECT reg_ty_year, reg_ty_region, reg_ty_region_frequency,
           ROW_NUMBER() OVER (ORDER BY reg_ty_region_frequency DESC) rn
    FROM ty_jp_kr_region_residence
    WHERE reg_ty_year = 2017
)

SELECT
    t1.los_ty_year AS year,
    t1.`los_ty_#_nights`,
    t1.los_ty_nights_frequency,
    t2.reg_ty_region,
    t2.reg_ty_region_frequency
FROM cte1 t1
INNER JOIN cte2 t2
    ON t1.rn = t2.rn
ORDER BY
    t1.rn;

Note that here we join the "first" record from the first subquery (actually a CTE) to the "first" record from the second subquery, and so on.


text:
Q: Load view without rendering I have a Twig extension in my Symfony project which renders a twitter widget. Currently, in my extension, I have this:
public function twitter($handle, $number = 5)
{
    return "

";
}

However I really don't like this solution, I'd rather have the HTML saved under views and then load the file from within my extension.
I have access to the container from within the extension using:
private $container;

public function __construct(ContainerInterface $container){
    $this->container = $container;
}

So I need something like
$view_file = $this->container->get('...')->view('InternalSocialBundle:twitter_placeholder.html.twig')

A: Of course you have totally right. Name of the service you are looking for is templating.
So this will work for You:
$html = $this->container->get('templating')->render('InternalSocialBundle:twitter_placeholder.html.twig');

edit:
This is an working example:
class FooExtension extends \Twig_Extension
{
    private $container;

    public function setContainer(\Symfony\Component\DependencyInjection\Container $container)
    {
        $this->container = $container;
    }

    public function foo()
    {
        return $this->container->get('templating')->render('CogiPortfolioBundle:Portfolio:tmp.html.twig');
    }

    public function getFunctions()
    {
        return array(
            'foo' => new \Twig_Function_Method($this, 'foo', array('is_safe' => array('html')))
        );
    }

    /* (...) */
}

The service definition:
<service id="cogi.foo.ext" class="Cogi\PortfolioBundle\TwigExtension\FooExtension">
    <call method="setContainer">
        <argument type="service" id="service_container" />
    </call>
    <tag name="twig.extension" />
</service>

And know if I call in any template {{ foo() }} it renders html from tmp.twig.html. And on the other side - if in my extension I put "path" to non existing template in render method then an exception is thrown.
I hope this helps.

A: Ok, so I resolved the issue that I had but it was sort of my fault for not testing this fully. @Cyprian's solution does indeed work absolutely fine when you're not doing anything complicated and just using the extension as intended.
My problem was that I was using this evaluate extension which was loading a template from the database, therefore it was twig that was doing all of the loading (and therefore was only interpreting the first param of $this->render() as a string - it made no attempt to load it using the symfony naming pattern).
This means my extension would work fine when using the above method in an actual twig file, but not when I used the {{body|evaluate}} extension.
The solution to this problem was as follows:
In my services.yml file, not only did I need service_container, but also twig.loader so it looked something liked:
class: Test\SocialBundle\Twig\SocialExtension
arguments: [@service_container,@twig.loader]
tags:
    -  { name: 'twig.extension' }

I then have this as the twig extensions constructor:
public function __construct(ContainerInterface $container, \Symfony\Bundle\TwigBundle\Loader\FilesystemLoader $loader)
{
    $this->container = $container;
    $this->loader = $loader;
}

In my getFilters() definition:
public function getFilters()
{
  return array(
    'twitter' => new \Twig_Filter_Method($this, 'twitter',array(
        'is_safe' => array(
            'evaluate' => true
            ),
        'needs_environment' => true,
        )
    )
  )
}

and finally, before I returned the rendered output:
public function twitter(\Twig_Environment $environment, $id)
{
    $social_item = array(); // get my data here from my service;
    $environment->setLoader($this->loader);
    return $environment->render("TestSocialBundle:Front:twitter_placeholder.html.twig",array());
}

This ensured that I was always using the \Symfony\Bundle\TwigBundle\Loader\FilesystemLoader loader, and not \Twig_Loader_String which was being used in my case.


text:
Q: Online cycle detecting in a directed graph I'm thinking about this problem for a couple of days and still don't know how to deal with it:

We are given integers $n\le 1000,m\le 300000$ - number of vertices and edges respectively. Then we are given edges one by one. Edges are directed and are given by pair of two integers: $(a,b)$ (both from interval $[1..n]$) which means edge from vertex $a$ to vertex $b$. For each edge instantly we have to decide if adding it will create a cycle in constructed graph. If it will - we print this edge and we don't add it to our graph, else we add this edge and print nothing.

So this graph can be quite dense, but it always has very small number of vertices and we should probably use it. Moreover, I guess time complexity will be amortized in a standard solution. Can anybody help?
For example: $n=4, m=5$ and edges in order of appearance:
$2\rightarrow 4, \ 4\rightarrow 3, \ 3\rightarrow 2, \ 1\rightarrow 2, \ 3 \rightarrow 1$, then the answer is: $3\rightarrow 2, \ 3\rightarrow 1$ because adding those edges will create a cycle.

A: My first thought would be simply to maintain the transitive closure of the edges seen so far as an $n\times n$ array of bits.
On the other hand, updating this array when a new edge is added could be expensive. Without some clever way to reduce this work (better than looking through the Cartesien product of "predecessors of $a$" with "successors of $b$" when we add an edge $a\to b$), the total work done here can end up being $\Theta(mn^2)$, compared to $O(m^2)$ for simply searching for a path from scratch for each edge added.

A: *

*A connected graph on $n$ vertices has no cycles if and only if it has exactly $n-1$ edges. Adding any edge over $n-1$ creates new cycle.

*If a graph on $n$ vertices has strictly less than $n-1$ edges, it is necessarily disconnected.

*If you have graph with two disjoint components, then connecting them with an edge does not create a new cycle.

This means basically that adding an edge to the graph adds in a new cycle if and only if both edges lie in the same connected component.


text:
Q: Why is it not possible to inherit tests methods from other assemblies WHy is it not possible to inheritance tests from other assemblies to run:
namespace TestProject.Base
{
    [TestClass]
    public abstract class TestBaseClass
    {
        [TestMethod]
        public void BaseTest()
        {
            Assert.IsTrue(false);
        }
    }
}

Test Runner
namespace TestProject.UnitTest
{
    [TestClass]
    public class UnitTest : TestBaseClass
    {
    }
}

It is ONLY possible to do run the test when the classes are in the SAME assembly WTF!
Is it possible to have test inheritance like above with NUnit and be runnable?

A: Unfortunately it seems this is a limitation of the MSUnit framework. In the MSDN documentation it states clearly that tests can inherit methods from another test class in the same assembly (see http://msdn.microsoft.com/en-us/library/ms182517.aspx).
Probably the cause for this is the way MSUnit discovers tests and so far it seems there is no workaround (other than having a copy of the test files in the project).


text:
Q: calling apply async inside apply async python function i am trying to call a pool with inside apply_async function , i get error of serialize object when i tried to pass one function the pool of another function so i moved the second pool to be global but still it not worked for me, what am i missing ?
my code :
from multiprocessing import Pool
b_pool = Pool(1)

def func_a(i):
    global b_pool
    print "a : {}".format(i)
    try:
        res = b_pool.apply_async(func_b, args=(i,))
    except Exception as e:
        print e

def func_b(i):
    print "b : {}".format(i)
    file = "/home/ubuntu/b_apply.txt"
    f = open(file, "a")
    f.write("b : {}".format(i))
    f.close()

if __name__ == '__main__':
    a_pool = Pool(1)
    for i in range(10):
       res =  a_pool.apply_async(func_a,args=(i,) )

    a_pool.close()
    a_pool.join()

    b_pool.close()
    b_pool.join()

in this code only a is printing 0 -9 and b not printing not even to file.
i am using python 2.7

A: the queue was good direction , just that that multiprocessing.Queue can't be passed like this but Manager.Queue  is the correct way of doing this , my code that worked :
from multiprocessing import Pool,Manager
def func_a(i,q):
    print "a : {}".format(i)
    try:
        q.put(i)
    except Exception as e:
        print e

def func_b(i,q):
    i = q.get()
    print "b : {}".format(i)

if __name__ == '__main__':
    m = Manager()
    q = m.Queue()
    a_pool = Pool(1)
    b_pool = Pool(1)

    for i in range(10):
        res = a_pool.apply_async(func_a,args=(i,q,) )
        res_2 = b_pool.apply_async(func_b, args=(i,q,))

    a_pool.close()
    a_pool.join()

    b_pool.close()
    b_pool.join()

this answer Sharing a result queue among several processes was very helpful


text:
Q: Trim end of string by pattern (regex?) I'm not so good at regex..
Looking for a way to trim the end of a string, if the end is:
A space followed by ONE character (can be any character)
Is preg_replace() the thing for that, or is there an easier and faster way?
The trimming will only happen once in the page

A: For just a space do this. And yes preg_replace is the way to go.
$string = preg_replace('/ .$/', '', $string);

A: For example:
$foo = 'hello w';
$bar = preg_replace('/\s\S\z/', '', $foo);

(assuming "any character" means "any non-space character"). More on "\" stuff.


text:
Q: Vaadin Visual Designer not working I created a Vaadin 7 project in Eclipse Kepler for Java EE. I am having difficulty in opening the Vaadin Visual Designer.  I am using Win 7 64 bit, Java JDK 7, Vaadin plugin for eclipse, IveDE, Apache Tomcat 7.
The source tab for the visual designer is accessible but the Design tab is not available at the bottom left corner.  Anyone faced this issue before?  I might be missing some files, but I tried updating eclipse and resolved Ive without any change.
Please advice.  Thanks in advance for the help.
It is the same issue as described in this post,
https://vaadin.com/forum#!/thread/3655464
Found the workaround, at http://dev.vaadin.com/ticket/12141
add this to the ecilpse.ini file
-Dorg.eclipse.swt.browser.XULRunnerPath=C:\

However I still get a pop up message in eclipse saying that is cannot detect XULRunner 1.9
Any suggesstions?
Thanks in advance.

A: Did you update the path to your actual xul runner location? For example, if you extracted the archive directly to C:, your path will look like this:
-Dorg.eclipse.swt.browser.XULRunnerPath=C:\xulrunner

You probably don't have all the xul runner files directly on C:.

A: I am not sure the Vaadin Plugin for Eclipse installs the xulrunner by default. I say this because on this blog Using Vaadin Eclipse Plugin under Win7 x64 I found xulrunner installment listed as a required step.

A: Just add to the eclipse.ini this:
-Dorg.eclipse.swt.browser.XULRunnerPath=C:\xulrunner\xulrunner.exe

Eclipse will show an error, just ignore that as designer will be working then.


text:
Q: How to get chi-square p-value from gofstat in R I'm trying to compare sample data with lists of distributions (thanks to help on StackOverflow), but have hit a bit of a roadblock. gofstat seems to be working splendidly, and the graphical output is exactly what is desired. However, the final point of this piece of code is to find the most fitting distribution to the sample data (which will eventually be read from a text file, and will not be ideal at all), and the parameters of said distribution.
The first step for me is to find the appropriate p-value for the chi-square test statistic for each distribution and the data, and then find the largest of these p-values, which should indicate the most fitting distribution. However, I can't seem to get proper output from the code. Whenever I run the code below, I receive a NULL output (twice, because of the loop in the code). According to documentation, this is the output when the test statistic is not calculated. How do I get gofstat to calculate it, and display the p-value? (and the distribution parameters, if possible)
library(fitdistrplus)
set.seed(1)
testData <- lnorm(1000)
distlist <- c("norm","unif")

# Loop through list of distributions
for(i in 1:length(distlist)){
  x <- fitdist(testData, distlist[i])
  gofstat(x)
  print(x$chisqpvalue)
  plot(x)
}


text:
Q: ios - sqlite database not opening I'm trying to create a database using the sqlite framework - i've set up a couple of methods to get the file path and to then open the database but I'm getting an "unable to open database" error (as you can see i've logged out the result of sqlite3_open)
this is my header file:
#import "sqlite3.h"

@interface ProgListViewController : UITableViewController <UITableViewDataSource, UITableViewDelegate, UIAlertViewDelegate>
{
    sqlite3 *db;
}

-(NSString *) filePath;
-(void)openDB;

this is my implementation file:
//file path to db
-(NSString *) filePath {
    NSLog(@"pathtest");
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES);
    return [[paths objectAtIndex:0] stringByAppendingPathComponent:@"bp.sql"];
}

//open the db
-(void)openDB {
    NSLog(@"opentest");
    if (sqlite3_open([[self filePath] UTF8String], &db) !=SQLITE_OK) {
        NSLog(@"%d", sqlite3_open([[self filePath] UTF8String], &db));
        sqlite3_close(db);
        NSLog(@"Database failed to open");
    } else {
       NSLog(@"database opened");
    }
}

any ideas?

A: I believe you meant to use NSDocumentDirectory rather than NSDocumentationDirectory.


text:
Q: How to optimize switch case in swiftui I have a view to show different styles according to parameters passed in.
There are more than 50 different styles, each style have a conflict layout. I want to show different styles according to the style passed in.
I have to write 50+ cases as below:
struct StyleDefaultView: View {
    let style: Int
    var body: some View {
        VStack() {
            Text("111")
        }

    }
}

struct Style1View: View {
    let style: Int
    var body: some View {
        HStack() {
            VStack() {
                Text("111")
            }
            Text("222")
        }
    }
}

struct Style2View: View {
    let style: Int
    var body: some View {
        VStack() {
            Text("111")
            HStack() {
                Text("111")
                Text("111")
            }
        }
        Text("222")
    }
}

struct Style3View: View {
    let style: Int
    var body: some View {
        HStack() {
            Text("111")
            VStack() {
                Text("111")
                Text("111")
            }
        }
        Text("222")
    }
}

struct Style4View: View {
    let style: Int
    var body: some View {
        HStack() {
            Text("222")
            VStack() {
                Text("111")
                Text("111")
            }
            Text("111")
        }
    }
}

// ... other 50+ style

struct ContentView: View {
    let style: Int
    var body: some View {
        VStack() {
            switch style {
            case 1:
                Style1View(style: style)
            case 2:
                Style2View(style: style)
            case 3:
                Style3View(style: style)
            case 4:
                Style4View(style: style)
            // case .. other 50+ style
            default:
                StyleDefaultView(style: style)
            }
        }
    }
}

Is there a way to simplify these swift case codes? Similar to the reflection in Java as code bellow
struct ContentView: View {
    let style: Int
    let viewMap = [
        0 : "StyleDefaultView",
        1 : "Style1View",
        2 : "Style2View",
        3 : "Style3View",
        // ... other 50 views
    ]
    var body: some View {
        let viewName: String = viewMap[style] ?? "StyleDefaultView"
        //  initialization a view by a string
        viewName(style : style)
    }
}

A: EDIT:
this is just an example to get you thinking about looping over your different style views:
struct StyleDefaultView: View {
    var body: some View {
        VStack() {
            Text("111")
        }
    }
}

struct Style1View: View {
    var body: some View {
        HStack() {
            VStack() {
                Text("111")
            }
            Text("222")
        }
    }
}

struct Style2View: View {
    var body: some View {
        VStack() {
            Text("111")
            HStack() {
                Text("111")
                Text("111")
            }
        }
        Text("222")
    }
}
struct Style3View: View {
    var body: some View {
        Text("1112")
        Text("1112")
        Text("1112")
    }
}

struct Style4View: View {
    var body: some View {
        Text("1112")
        Text("1")
    }
}

class StyleViewModel {
    let styles: [AnyView] = [
        AnyView(Style1View()),
        AnyView(Style2View()),
        AnyView(Style3View()),
        AnyView(Style4View())]

    func selectedStyleView(_ ndx: Int) -> AnyView {
        if ndx < styles.count {
            return styles[ndx]
        } else {
            return AnyView(StyleDefaultView())
        }
    }
}

struct ContentView: View {
    let styles = StyleViewModel()
    let style: Int = 2

    var body: some View {
        styles.selectedStyleView(style)
    }
}

A: I think a much better way is to use a protocol which each of these conform to. You then only need to store the types, meaning it's really light-weight since you aren't instantiating a bunch of views that you may not need to use.
Example
Firstly, the ContentView so you can see mainly what's happening. It's an interactive example with a Slider so you can change the style to test it out.
struct ContentView: View {
    private static let styleTypes: [StyledView.Type] = [
        StyleDefaultView.self,
        Style1View.self,
        Style2View.self,
        Style3View.self,
        Style4View.self
    ]

    @State private var currentStyle = 0

    var body: some View {
        VStack {
            Text("Style: \(currentStyle)")

            Slider(
                value: Binding<Double>(
                    get: { Double(currentStyle) },
                    set: { currentStyle = Int($0) }
                ),
                in: 0 ... 4,
                step: 1
            )

            Spacer()

            Self.styleTypes[currentStyle].init().buildView()
        }
    }
}

Result (with rest of code too):

Protocol:
protocol StyledView {
    init()
    func buildView() -> AnyView
}

extension StyledView where Self: View {
    func buildView() -> AnyView {
        AnyView(self)
    }
}

Now all you need to do is conform each view to StyledView, no need for extra code in each of those views. Example for first view (but do this for all of them):
struct StyleDefaultView: View, StyledView {
    var body: some View {
        VStack() {
            Text("111")
        }
    }
}

Side note: the VStack doesn't need those () after since you have a trailing closure.


text:
Q: php pdo: it it possbile to have a DBMS agnostic 'describe table'? I have a script that parse the database and create php classes to work with that db. (zend-db-model-generator). is there a way to in php to have a DBMS agonstic commands so on each type of db it will return the table structure ?
so it doesn't matter if i use the pdo driver once for mysql and once for postgresql, it will still return the table structure.
the only solution that i see for now is to get the db type and to switch on each db type and execute the appropriate command.

A: Using the same SQL query, unfortunatly, doesn't seem quite possible, as far as I can tell...

About your idea of going through the database to extract informations about each table to generate some PHP classes, that's one of the things that Doctrine (the most famous PHP ORM) does.
If you download it, and take a look at the classes in Doctrine/Import/[DatabaseType].php, you'll see this is done differently for each kind of database.
For instance, for MySQL, the following piece of code is used in Doctrine_Import_Mysql :
'listTableFields' => 'DESCRIBE %s',

On the other hand, for PostgreSQL, you've got the following, in Doctrine_Import_Pgsql :
'listTableColumns'     => "SELECT
                            a.attnum,
                            a.attname AS field,
                            t.typname AS type,
                            format_type(a.atttypid, a.atttypmod) AS complete_type,
                            a.attnotnull AS isnotnull,
                            (SELECT 't'
                              FROM pg_index
                              WHERE c.oid = pg_index.indrelid
                              AND a.attnum = ANY (pg_index.indkey)
                              AND pg_index.indisprimary = 't'
                            ) AS pri,
                            (SELECT pg_attrdef.adsrc
                              FROM pg_attrdef
                              WHERE c.oid = pg_attrdef.adrelid
                              AND pg_attrdef.adnum=a.attnum
                            ) AS default
                      FROM pg_attribute a, pg_class c, pg_type t
                      WHERE c.relname = %s
                            AND a.attnum > 0
                            AND a.attrelid = c.oid
                            AND a.atttypid = t.oid
                      ORDER BY a.attnum",

Not that easy, it seems ^^

And, farther down each class, there is a method called listTableColumns -- which is not the same for each database type...
So I'm guessing things will, unfortunatly, not be as simple as you hoped...
But, as a sidenote : maybe you could use Doctrine for that part of your project -- might be faster than re-inventing the wheel ;-)


text:
Q: Consumir API en Solidity Blockchain Estoy intentando traer unos datos de un API montada con NODE.JS y Mysql a Solidity para ingresarlos en un mensaje de transacción en un contrato inteligente, pero no encuentro la documentación para hacer el llamado a la API, alguien sabe como puedo hacerlo? Agradezco sus comentarios

A: Resumen: usa un oraculo.
Primero: el blockchain no permite el acceso a datos externo desde un smartcontract, me refiero a que un contrato no puede llamar a una api.
Razon: Todas las operaciones en una blockchain deben ser inmutables en el tiempo, si llamas a una api hoy y te responde 1 y la llamas mañana y te responde 2, eso romperia la inmutabilidad.
Segundo: Si es posible guardar datos en un smartcontract desde una api, puedes usar un webhook para que cuando llames a tu api, esta se conecte al smartcontract y guarde datos en el, pero si tu api es vulnerada probablemente el smartcontrar sea vulnerado tambien.
Solucion: Usar un oraculo, puedes crear el tuyo propio o usar el proveedor mas popular es chainlink, cada llamada a chain link tiene un costo pero ofrecen una infraestructura relativamente robusta y soporte en muchas redes.


text:
Q: How to auto increment for a coulmn in sql server limited to partition For auto increment for a column, we use IDENTITY in SQL Server.
Syntax
CREATE TABLE Employee
(
EmployeeID INT IDENTITY,
Name VARCHAR(100) NOT NULL,
.
.
)

The default starting value of IDENTITY is 1 and will increment by 1 for each record.
The problem that I see with this logic is that it will generate across the table but I am interested in auto-increment per partition.
I can use counter in order to auto-increment per partition but the issue I see with counter is that suppose as part of single query I have to insert multiple rows into a table. Then I have to execute the same query two times.
1.  Calculate the no. of rows to insert for the counter.
2.  Insert the data.
So, what is the right way for auto-increment within the partition?


text:
Q: How does the heat equation model concrete problems accurately Let's just say that I am a beginning practitioner of mathematics who never gave physics a serious shot and looking to get an intuition of how partial differential equation works in relation to the physical words.
In particular, I am considering the classical heat equation
$$  \partial_{t} u - \mathit{\Delta}u = 0 \ \ \text{in $\mathit{\Omega}$}, \ \ u = f \ \ \text{on $ \mathit{\partial \Omega}$} $$
with initial condition $u_0$ for functions $ u = u(t,x)$ and $f=f(x,t)$, where $t > 0 $ is the time variable and $ x \in \mathit{\Omega} \subseteq \mathbb{R^{d}} $ is a bounded domain.
I want to understand this equation in relation to how it works physically.
In relation to the distribution of heat, my intuition for such a model is that, given an object with constant conductivity, if we can somehow control the temperature of the object on the boundary for all time (boundary condition), then based on the information at present (initial profile), we should be able to deduce the temperature inside the object for all time as well.
But how does such set up come in handy in real life? Intuitively, even if I take just a metal ball $B \subseteq \mathbb{R}^{3}$, and then heat up a small area on the surface of my metal ball. Intuitively I should be able to just sit there and wait it out in order to get a unique solution. However, the theory of heat equation says that if I do not already know how the flow will behave on the boundary, then I cannot expect to get a unique solution. But surly, all I had to do was just wait for the flow to go over the metal...
Some of my thoughts about this are the folloings:

*

*The environment will change and the heat could escape the boundary in certain way. Thus I need to know how the heat will behave when in contact with its surroundings in order to know how the interior behaves. However, this kind of thinking has a flaw, because if I take $\mathit{\Omega}$ to be say a closed loop $S^1$, then it will have no boundary and the theory says that I wouldn't have to take account of the boundary value.

*The heat flow is stochastic, meaning that if I fix everything else the same, every time I flow my heat, the distribution of heat through out the object as time increases will be different according to some probability density. This would make sense, because if the equation admits a solution in the probabilistic sense, then I need a priori a sample point, i.e. a solution to the heat equation. Restrict that sample point to the boundary, and then use the resulting function defined on the boundary to solve for the heat equation will then get me a unique solution.
But again I don't even know very well the first thing about physics. So I would appreciate if anyone could give a some clarification.
Many thanks in advance!

A: As a fan of heat equation ,some times called heat transfer by conduction ,I know with some kind of certitude a few axioms that may help:
i-The heat equation is some sort of the diffusion equation where the nature of the problem, medium properties such as diffusion combined with the boundary conditions often allow the simple solution by separation of variables x,t.
ii-The solution to the physically defined heat partial differential equation with Dirichlet boundary conditions and zero source term (as the question asks) exists uniquely .Of course this spatio-temporal evolution is deterministic not probabilistic.
iii- Recently,there are many analytic and numeric trials (some of them use stochastic methods ) to solve the heat equation in the general case (i.e. with heat source term distribution inside the heated object,such as microwave oven,).


text:
Q: Given $f : \mathbb{R} \to \mathbb{R}$ differentiable, $f(x + y) = f(x)f(y)$ and $f(0) = 1$, prove $f(x) = e^{cx}$, $c$ constant. Given $f : \mathbb{R} \to \mathbb{R}$ differentiable, $f(x + y) = f(x)f(y)$ and $f(0) = 1$, prove $f(x) = e^{cx}$, $c$ constant.
Attempt:
Differentiate $f(x + y) = f(x)f(y)$ with respect to $y$ using the chain rule:
$f'(x + y) = f(x)f'(y)$.
Let $y = 0$ to get $f'(x) = f(x)f'(0)$.
Rearrange to get $\frac{f'(x)}{f(x)} = f'(0)$.
Integrate both sides with respect to $x$ to get $\ln f(x) = f'(0)x + c$ where $c$ is the constant of integration.
Take exponentials of both sides to get $f(x) = e^{f'(0)x + c} = e^{f'(0)x}e^{c}$.
Since $f(0) = 1$, we get $f(0) = e^{f'(0) \times 0}e^{c} = e^0e^c = e^c = 1$.
Plugging this back in we get $f(x) = e^{f'(0)x}$ and setting $f'(0) = c$ we get $f(x) = e^{cx}$.
Question
Is this correct? One concern I have is at the integration step where the logarithm of $f(x)$ is taken. Is that legal given that we do not know whether $f(x)$ is strictly positive?

A: In fact, we can easily show $f(x) > 0$ for all $x$.
$f(x) = f(x/2)^2 \ge 0$
$f(x)f(-x) = f(0) \ne 0$
So $\ln f(x)$ is perfectly well-defined. Everything else looks fine.
(For an extra challenge, show that this is also true if we only assume $f$ is continuous. For a real extra challenge, show that it's not true in general.)


text:
Q: Barra de progresso em aplicação console em Delphi? Gostaria de exibir algum tipo de animacao em minha aplicacao console durante um processo longo.
Poderia ser uma barra de progresso ou uma outra animação.

A: Tente Assim: eu Guardei isso em uma arquivo pois estava tentando fazer o mesmo e deu certo... Achei isso em um Fórum na Época.
Var
cont, Linhas : integer;
Lista: TStringList;
begin
  try
    Lista.LoadFromFile('C:\Cadastro.txt');
    Linhas:= Lista.Count;
  finally
    Lista.Free;
  end;
  ProgressBar1.Max := Linhas; //Envia p/ Progressbar o Tamanho Total do Arquivo de acordo com o numero de linhas pego com a Try acima...

Esse acima é para Windows
esse aqui é para Console... Veja aqui


text:
Q: Array based Linked List in C, issues reading in all data I am trying to use an array-based linked list to read in values from data.txt and then display those items. The list does not need to be ordered. Currently, it is only printing the last item on the list. I am not positive if I am reading the entire list currently or just the last word. I would appreciate any advice. I have made some changes since earlier. It compiles but I get a segfault which valgrind states "Invalid write or size 1".
main.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define WORD_SIZE 25
#define MAX_NODES 100
#define FILENAME "data.txt"

char buffer[WORD_SIZE];
int count = 0, i = 0;

typedef struct WORDNODE {
    char word[WORD_SIZE];
    struct WORDNODE *next;
} t_word_node;

t_word_node node_array[MAX_NODES];
t_word_node *free_list = NULL;
t_word_node *tail = NULL;

t_word_node *create_node(void);
void add_word(char *buffer, t_word_node **);

void node_init() {
    for(int count = 0; count < MAX_NODES-2; count++) {
        node_array[count].next = &node_array[count+1];
    }
    node_array[MAX_NODES - 1].next = NULL;
    free_list = &node_array[0];
}

void add_word(char *buffer, t_word_node **list) {
    t_word_node *temp = NULL;
        t_word_node *last = NULL;
        t_word_node *this = *list;

    temp = create_node();
    strcpy(temp->word, buffer);
    while(this && strcmp(buffer, this->word) > 0) {
        last = this;
        this = this->next;
    }
    if(last == NULL) {
            temp->next = this;
                *list = temp;
        } else {
            last->next = temp;
        temp->next = this;
    }
}

t_word_node *create_node() {
    t_word_node *new = NULL;

    if(free_list != NULL)
    {
        new = free_list;
        free_list = free_list->next;
    }
    return new;
}

void print_nodes(t_word_node *this) {
        if(this == NULL) {
                return;
        }
        while(this != NULL) {
                printf("%s\n", this->word);
                this = this->next;
                }
}

int main() {
    count = 0;
    FILE *infile;
    t_word_node *new_list = NULL;
    node_init();
    if((infile = fopen(FILENAME, "r")) != NULL) {
        while (fscanf(infile, "%s", buffer) != EOF) {
                    add_word(buffer, &new_list);
                }
            fclose(infile);
        }
    print_nodes(new_list);
        return 0;
}

data.txt
Kaleidoscope
Rainbow
Navy
Highway
Printer
Junk
Milk
Spectrum
Grapes
Earth
Horse
Sunglasses
Coffee-shop
Ice
Spice
Tennis racquet
Drill
Electricity
Fan
Meat
Clown
Weapon
Drink
Record
Spiral
Air
Data Base
Cycle
Snail
Child
Eraser
Meteor
Woman
Necklace
Festival
Eyes
Foot
Diamond
Chocolates
Explosive
Web
Rifle
Leather jacket
Aeroplane
Chisel
Hose
Flower
Space Shuttle
Radar
Hieroglyph
Ice-cream
Insect
Feather
Ears
Square
Software
Cup
Comet
Church
PaintBrush
Slave
Elephant
Sphere
Aircraft Carrier
Fork
Needle
Prison
Solid
Window
Dress
Knife
Spot Light
Onion
Horoscope
Chief
Crystal
Coffee
Microscope
Freeway
Fruit
Kitchen
Desk
Spoon
Pyramid
Restaurant
Adult
Potato
Egg
Telescope
Family
Sports-car
Television
Jet fighter
Thermometer
Wheelchair
X-ray
Sun
Worm
Church

A: The problem is you are misusing your tail pointer as a temp pointer. Use temp for a temporary pointer. Next validate that every word read will fit in an array of WORD_SIZE and validate EVERY allocation.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define WORD_SIZE 25
#define FILENAME "data.txt"

typedef struct WORDNODE {
    char word[WORD_SIZE];
    struct WORDNODE *next;
} t_word_node;

t_word_node *head, *tail, *temp;

t_word_node *create_node()
{
    return(t_word_node *)malloc(sizeof(t_word_node));
}

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

    char buffer[WORD_SIZE];
    FILE *infile;

    infile = fopen(argc > 1 ? argv[1] : FILENAME, "r");

    while (fgets (buffer, sizeof(buffer), infile) != NULL) {
        size_t len;
        buffer[(len = strcspn (buffer, "\n"))] = 0;
        if (len >= WORD_SIZE) {
            fputs ("error: word exceeds WORD_SIZE\n", stderr);
            continue;
        }
        if (!(temp = create_node())) {
            perror ("malloc-create_node()");
            return 1;
        }
        strcpy(temp->word, buffer);
        temp->next = NULL;
        if (head == NULL)
            head = tail = temp;
        else {
            tail->next = temp;
            tail = temp;
        }
    }
    temp = head;
    while (temp != NULL) {
        puts (temp->word);
        temp = temp->next;
    }
    return 0;
}

You have a tail pointer -- there is never a need to iterate over the list to insert-at-end (that's what the tail pointer is for). Note above how tail is initialized when the first node is added to the list.
Example Use/Output
Do not hardcode filenames. That's what argc and argv are for in int main (int argc, char **argv), pass the filename to read as the first argument to your program or read from FILENAME by default if no argument is provided:
$ ./bin/llarraywords dat/datallwords.txt
Kaleidoscope
Rainbow
Navy
Highway
Printer
Junk
Milk
Spectrum
Grapes
Earth
Horse
Sunglasses
...
<snip>
...
Egg
Telescope
Family
Sports-car
Television
Jet fighter
Thermometer
Wheelchair
X-ray
Sun
Worm
Church

Look things over and let me know if you have further questions.


text:
Q: npm Error: Cannot find module 'core-util-is' When I run
npm -v, npm install and npm install --save react-native-voice

this error appears:
module.js:549
    throw err;
    ^

Error: Cannot find module 'core-util-is'

    at Function.Module._resolveFilename (module.js:547:15)
    at Function.Module._load (module.js:474:25)
    at Module.require (module.js:596:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> (/usr/local/lib/node_modules/npm/node_modules/readable-stream/lib/_stream_readable.js:67:12)
    at Module._compile (module.js:652:30)
    at Object.Module._extensions..js (module.js:663:10)
    at Module.load (module.js:565:32)
    at tryModuleLoad (module.js:505:12)
    at Function.Module._load (module.js:497:3)

A: Try running npm update and then npm install again. That worked for me.

A: this solution solve my problem
1- i run this command
rm -rf /usr/local/{lib/node{,/.npm,_modules},bin,share/man}/npm*

2- i install node.js again
3- i run
npm install

and now every thing is ok.

A: I had a same issue, but finally figured it why this is happening...
Solution
  Remove npm and npm-cache folder from users/yourName/Appdata/Roaming.
then remove node completely from your computer.
restart
Now, reinstall node.js using msi installer .
done.

A: Delete the npm-cache folder from local
Uninstall node
Restart
Re-install node


text:
Q: How to remove empty string data from an NSMutableArray I am getting an array from php server like:
<__NSArrayM 0x7fe6326f2340>(
 01460367533.jpg,
 01460353708.jpg,
 01460354725.jpg,
 01460363165.jpg,
 01460364760.jpg,
 01460367938.jpg,
 ,
 11460353708.jpg,
 ,
 ,
 ,
 11460363173.jpg,
 11460364762.jpg,
 ,
 ,
 21460353708.jpg,
,
)

How can I remove empty string data (,) in NSMutableArray.

A: You can create a non-empty array from mutable array.
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"length > 0"];
NSArray *anotherArray = [yourMutableArray filteredArrayUsingPredicate:predicate];

Agree with the first comment, though. You should take care of it while adding data to array.

A: You can remove multiple occurrence of multiple strings/objects.
NSMutableArray *arr = [NSMutableArray arrayWithObjects:@"hello", @"", @"HI", @" ", nil];

[arr removeObjectsInArray:@[@"", @" "]];

NSLog(@"%@", arr);

A: I would suggest just use this simple one line of code
[mutableArrayOfStrings removeObject:@""];

to remove empty string items from your mutable string array.


text:
Q: How to call a class:method determined at runtime in perl? I am trying to make a crm application with a lot of crud actions. So I have controller classes like
CRM::Cities
CRM::Countries

No I use ORLite as a lite weight ORM. It creates -on the fly- classes like so
Model::Cities
Model::Countries

Now say I want to load a city. In the CRM::Cities class I have to do something like
(ORLite uses class methods for access)
$obj1 = Model::Cities->load($id);

To load the current country in CRM::Countries:
$obj1 = Model::Countries->load($id);

So I end up in each controller class to enclose similar lines.
What I would want to be able todo is to do something generic like this in the CRM package (the base controller class):
$obj1 = Model::$package->load($id);
# package contains Cities or Countries, determined at runtime

I tried with various variations , with eval and so on but this is higher order perl. I think b/c the ORLite methods are class methods, inheritance is less obvious. Can someone give advice?  tia !

A: Just put the whole package name, e.g. Model::Cities, into the variable. For example:
package Stuff::Yeah;

sub whatever {
  print "yes\n";
}

package main;

my $package = "Stuff::Yeah";
$package->whatever;

A: die unless $package =~ /\A\w+\Z/;
eval "require Model::$package" or die $@;
$obj1 = "Model::$package"->load($id);

A: Perl lets you use strings as class names, so you can say
$obj1 = "Model::Cities"->load($id);

or indeed
$obj1 = "Model::$package"->load($id);

and in fact
my ($package) = $class =~ /([^:]+)$/;
$obj1 = "Model::$package"->load($id);

.
That's a nice generic way to load things, but I recommend one more layer of abstraction, to avoid getting too married to the one-Model-per-CRM-package idea:
sub _model_class {
    my ($class) = @_;

    my ($package) = $class =~ /([^:]+)$/;
    return "Model::$package";
}

And then
$obj1 = $class->_model_class->load($id);

.  This way, if one of the inheriting classes develops its own idea about what its model class ought to be (and this happens), you don't need to change any code.


text:
Q: Time complexity of recursive function with a loop What would be the time complexity of the below function?
int f = (int n) => {
  if (n === 1) {
    return 1;
  }

  for (let i = 0; i < n; i++) {
    console.log(i);
  }

  return f(n-1) + f(n-1)
}

This is what the recursion tree looks like where i denotes the depth:
                   f(4)                         // i = 0
                  /    \
                /        \
              /            \
            /                \
          /                    \
        f(3)                  f(3)              // i = 1
       /   \                  /   \
     /       \              /       \
   f(2)      f(2)         f(2)      f(2)        // i = 2
  /   \     /   \        /   \     /   \
f(1) f(1) f(1) f(1)    f(1) f(1) f(1) f(1)      // i = 3

Had there been no loop inside the function, the time complexity would have been O(2^n). But now there's a loop so:
At each depth, the number of function calls made is 2 ^ i and in each function call n - i iterations are done in the loop, hence at each level (2 ^ i) * (n - i) operations are being done. So, time complexity could be calculated as:
T(n) = [(2 ^ 0) * (n - 0)] + [(2 ^ 1) * (n - 1)] + [(2 ^ 2) * (n - 2)] + ... + [(2 ^ (n - 1)) * (n - (n - 1))]

So am I right on this and what could possibly be the final time complexity?

A: You are right, the number of log calls is driven by the recurrence
T(n) = C1 n + C2 + 2 T(n-1)

with T(1)=C3.
We can guess that the solution has the form
T(n) = A 2^n + B.n + C

and by identification,
T(n) = A 2^n - C1 n - C2 + C1.

Finally,
T(1) = 2 A - C2 = C3

gives A.


text:
Q: Syntax error with mutual recursion on a list in OCaml I am using OCaml v 4.00.1.  I am trying to write a function using mutual recursion to take a list and return an int.  The int is the results of taking alternating elements of the list and adding and subtracting them from each other.  For example, the list [1;2;3;4] would results in 1 + 2 - 3 + 4 = 4.
My code is as follows:
let alt list =
  let rec add xs = match xs with
    [] -> 0
    | x::xs -> x + (sub xs)
  and sub xs = match xs with
    [] -> 0
    | x::xs -> x - (add xs);;

OCaml throws a syntax error on the ;; at the very end of the code.  I am unsure where to start to figure out what this error actually is.

A: I suspect you forgot to add in ... portion of the let binding – changes in bold
let alt list =
  let rec add xs =
    match xs with
      | [] -> 0
      | x::xs -> x + (sub xs)
  and sub xs =
    match xs with
      | [] -> 0
      | x::xs -> x - (add xs)
  in
  add list
This will start the sequence with +, ie 1 + 2 - 3 ...
If you want it to start with - ...
...
in
sub list
We can swap match syntax for function and readability is improved here
let alt list =
  let rec add = function
    | [] -> 0
    | x::xs -> x + (sub xs)
  and sub = function
    | [] -> 0
    | x::xs -> x - (add xs)
  in
  add list


text:
Q: Safari crashes when using Rails inline_svg gem Certain pages in my Rails app seem to crash Safari complete when there are svgs on the page using the inline_svg gem.
Navigating to the page results in the error message 'Safari Web Content quit unexpectedly.'
Here is the part of the stack trace that leads me to believe it is an issue with SVG rendering:
Thread 0 Crashed:: Dispatch queue: com.apple.main-thread
0   libsystem_kernel.dylib          0x00007fff8e2c1286 __pthread_kill + 10
1   libsystem_c.dylib               0x00007fff9a58db53 abort + 129
2   libsystem_c.dylib               0x00007fff9a555c39 __assert_rtn + 321
3   com.apple.CoreGraphics          0x00007fff90ff9d0e CGPathCreateMutableCopyByTransformingPath + 242
4   com.apple.CoreGraphics          0x00007fff9101de10 CGContextAddPath + 93
5   com.apple.WebCore               0x00007fff920d70c0 WebCore::GraphicsContext::strokePath(WebCore::Path const&) + 80
6   com.apple.WebCore               0x00007fff929c4140 WebCore::RenderSVGShape::strokeShape(WebCore::GraphicsContext*) const + 160
7   com.apple.WebCore               0x00007fff929c8673 WebCore::RenderSVGPath::strokeShape(WebCore::GraphicsContext*) const + 99
8   com.apple.WebCore               0x00007fff929d0fce WebCore::RenderSVGShape::strokeShape(WebCore::RenderStyle const&, WebCore::GraphicsContext*) + 126
9   com.apple.WebCore               0x00007fff929d116f WebCore::RenderSVGShape::strokeShape(WebCore::GraphicsContext*) + 191
10  com.apple.WebCore               0x00007fff929d11ce WebCore::RenderSVGShape::fillStrokeMarkers(WebCore::PaintInfo&) + 78
11  com.apple.WebCore               0x00007fff91ff927b WebCore::RenderSVGShape::paint(WebCore::PaintInfo&, WebCore::LayoutPoint const&) + 379
12  com.apple.WebCore               0x00007fff92052b03 WebCore::RenderSVGContainer::paint(WebCore::PaintInfo&, WebCore::LayoutPoint const&) + 531
13  com.apple.WebCore               0x00007fff92052b03 WebCore::RenderSVGContainer::paint(WebCore::PaintInfo&, WebCore::LayoutPoint const&) + 531
14  com.apple.WebCore               0x00007fff92052b03 WebCore::RenderSVGContainer::paint(WebCore::PaintInfo&, WebCore::LayoutPoint const&) + 531
15  com.apple.WebCore               0x00007fff91ff8f12 WebCore::RenderSVGRoot::paintReplaced(WebCore::PaintInfo&, WebCore::LayoutPoint const&) + 1330
16  com.apple.WebCore               0x00007fff91f70d32 WebCore::RenderReplaced::paint(WebCore::PaintInfo&, WebCore::LayoutPoint const&) + 722

Here is what the svg itself looks like:
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:sketch="http://www.bohemiancoding.com/sketch/ns" width="91px" height="25px" viewBox="0 0 91 25" version="1.1" class="priority-urgent">
    <title>Urgent</title>
    <desc>Created with sketchtool.</desc>
    <defs></defs>
    <g id="1/18" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd" sketch:type="MSPage">
        <g id="Detail" sketch:type="MSArtboardGroup" transform="translate(-459.000000, -264.000000)">
            <g id="Group" sketch:type="MSLayerGroup" transform="translate(429.000000, 103.000000)">
                <g id="Urgent_flag" transform="translate(30.000000, 161.000000)">
                    <rect id="Rectangle-28" fill="#E74C3C" sketch:type="MSShapeGroup" x="0" y="0" width="91" height="25" rx="2">    </rect>
                    <text id="URGENT" sketch:type="MSTextLayer" font-family="Gotham Book" font-size="16" font-weight="313" sketch:alignment="middle" line-spacing="19" fill="#FFFFFF">
                        <tspan x="10.508" y="18">URGENT</tspan>
                    </text>
                </g>
            </g>
        </g>
    </g>
</svg>

A: Turns out that it was an issue with the padding I had applied to the css class I had on the <svg>. Something maybe with Safari taking padding into account for how large or small the image should be scaled possibly? Anyway, after removing the padding, Safari stopped crashing.


text:
Q: Upgrading to Flex 4.6 from Flex 4.5 The Background
I'm in the process of updating an AIR app that was built with Flex 4.5 and AIR 2.6 to Flex 4.6 and AIR 3.3. I'm doing this to take advantage of the native JSON class and to get ready for AIR 3.4 and Actionscript Workers, both things I plan to make use of. I'm also using PureMVC 2.0.4.
The actual updating process went fine. I downloaded the Flex 4.6 SDK and overlaid the AIR 3.3 SDK on top of it. So far so good. I was using the JSON class in as3corelib so I had to make some changes, removing references to that from my app. Aside from that smooth sailing. With the code compiling nicely I proceeded to launch the app.
The Problem
This is where things fall apart.
When the app launches the "welcome" view (this is essentially a landing that has buttons for things like "open file", "new file" and so on along with a news feed that is pulled from a web service) is just missing. The background image shows up but the UI is just not there. Here are some sample screen caps:
Before (The working 4.5 version of the Welcome View)

After (The broken 4.6 version of the Welcome View. This is the background image of the view.)

Stepping through the start up process with tons of breakpoints in the Flash Builder debugger isn't revealing anything obviously wrong. Other UI elements are also missing. For example: this tab bar is just missing buttons
Before (The working 4.5 version)

After (The broken 4.6 version)

In trying to establish what's going on here I've been playing around with the app as best I can (with the welcome UI gone this is rather hard) and I've found that minimizing the application then restoring it will cause the app to hang to the point where Windows adds the "(Not Responding)" bit to the app title bar then resume normally with the UI kinda-sorta-mostly working. Some sample images:
Welcome View after restore (Note the horizontal rule that is going far off to the right)

TabBar after restore (This content is completely disregarding layout rules. Further it's actually scrolling to the left -- that's right, it somehow grew legs and is just moving off the screen all on it's own. There was never any tweening/animation code attached to this view)

All of this is happening on Windows 7 x64 with Flash Builder 4.6.
The Question
What the heck is going on here? Why would my UI just disappear like this?
I feel like I'm missing something fundamental like "oh, just add this compiler option" and BAM! things will be fixed. I certainly don't feel that my app should be so completely broken with this upgrade.
Has anyone experienced a similar issue in upgrading to Flex 4.6/AIR 3.x from previous versions of Flex/AIR? How did you solve your problem?
Could it be my custom skins causing this problem? Why would that happen? On the topic of skins this seems like a similar question.
Update
I was hoping to avoid this but I wasn't really getting anywhere with this so I decided to start pulling out the theme and external SWCs until I could get the app to some sane level of functionality and work back from there. I started with the theme and, while the problem wasn't with the theme is pointed me in the correct direction.
In my app there is a class called HRule. It's the horizontal rule between the "Open from Dealers" and "Logout" buttons in some of the above screen shots. This class is simply a Spark Group with two Lines inside that draw the rule.
Here is the complete class:
<?xml version="1.0" encoding="utf-8"?>
<s:Group
    xmlns:fx="http://ns.adobe.com/mxml/2009"
    xmlns:s="library://ns.adobe.com/flex/spark"
    xmlns:mx="library://ns.adobe.com/flex/mx">
    <fx:Declarations>
        <!-- Place non-visual elements (e.g., services, value objects) here -->

    </fx:Declarations>

    <s:layout>
        <s:VerticalLayout
            gap="0">
        </s:VerticalLayout>
    </s:layout>

    <s:Line
        xTo="{width}">
        <s:stroke>
            <s:SolidColorStroke
                color="#000000"
                alpha="0.4" />
        </s:stroke>
    </s:Line>

    <s:Line
        xTo="{width}">
        <s:stroke>
            <s:SolidColorStroke
                color="#ffffff"
                alpha="0.15" />
        </s:stroke>
    </s:Line>

</s:Group>

I then use this class like this:
<s:VGroup
    width="300">

    <s:Button
        label="Button 1"
        percenthWidth="100"/>

    <mycomps:HRule
        percenthWidth="100"/>

    <s:Button
        label="Button 2"
        percenthWidth="100"/>

</s:VGroup>

I can fix all my problems simply by changing the base class from Group to SkinnableContainer. I downloaded WinMerge to do a diff on the 4.5 version of Spark Group and the 4.6 version and the files are identical.
So this brings up a new question: why would the behavior of Group change between 4.5 and 4.6?