text:
Q: Searching in sql, Transactions and DB File Locked I am using JavaFX with SQLite DB for making a general store management. Previously I was using SQL server as an assignment but to implement it I needed an embedded database. For that purpose I chose SQLite. Here I faced many problems as it didn't have stored procedures now I got the following 3 problems in my whole management System:

*

*Error in searching through query

*Error in executing a transaction

*Getting error message that database file is locked.
Now I am going to define each part separately.
1.Error in Searching through query
I was using stored procedure in SQL server for searching in a table using some text the inner query was:
Create PROC [dbo].[spGetProductListByQuery]
@query varchar(MAX)
AS
BEGIN
SELECT p.Product_id, p.Name, pt.Type, p.Pur_Price, p.Sale_Price,   p.Stock,s.Name, s.Contact_No, s.Email
FROM ((Product AS p
INNER JOIN ProductType AS pt ON p.Type_Id=pt.Type_Id)
INNER JOIN Supplier AS s ON p.Supplier_Id=s.Supplier_Id)
WHERE p.Name LIKE @query+'%'
And in java i executed this stored procedure using following code:
pst=con.prepareStatement("EXEC spGetProductListByQuery @query=?");
pst.setString(1,query)

and it worked at that time but now as i am using SQLite studio for that purpose i am using following code:
sql="SELECT p.Product_id, p.Name, pt.Type, p.Pur_Price, p.Sale_Price, p.Stock,s.Name, s.PhoneNumber, s.Email\r\n" +
                        "FROM ((Product AS p\r\n" +
                        "INNER JOIN ProductType AS pt ON p.Type_Id=pt.Type_Id)\r\n" +
                        "INNER JOIN Supplier AS s ON p.Supplier_Id=s.Supplier_Id)\r\n" +
                        "WHERE p.Name LIKE ?+'%'";
                System.out.println(searchText);
                pst=con.prepareStatement(sql);
                pst.setString(1, searchText);
                rs=pst.executeQuery();

it works on SQLite studio but it returns nothing java, i can't understand where is the problem.
2.Error in executing a transaction
I have tried for so many time to execute even a single statement in transaction but it still returns error message as shown below:
BEGIN TRANSACTION;
INSERT INTO Staff (Name, Address, Contact_No,Salary,Accountant)
VALUES ('Danish', 'Gujrat','034803','22000,0)
END TRANSACTION

and i got following error message:

cannot start a transaction within a transaction Unable to fetch row.

3. Getting error message that database file is locked
As the 3rd problem is connected to 2nd problem if it resolves I can use multiple statements in one SQL Transaction and make it possible to work. But the strange thing is that when I tried to execute this function:
public static Boolean saleItem(int productId, double quantity) {
        con=Connectivity.getConnectivity();
        Connection con2 = null;
        try {
            if(productId!=0&&quantity!=0)
            pst=con.prepareStatement("INSERT INTO SALE (Product_Id, Date, Quantity)\r\n" +
                    "VALUES (?, CURRENT_TIMESTAMP, ?)");
            pst.setInt(1, productId);
            pst.setDouble(2, quantity);
            pst.executeUpdate();
            if(!con.isClosed()) {
                con.close();
            }
            pst=con.prepareStatement("UPDATE Product\r\n" +
                    "SET Stock=Stock-? WHERE Product_id=?");
            pst.setInt(2, productId);
            pst.setDouble(1, quantity);
            pst.executeUpdate();
            con.close();
        } catch (SQLException e) {
            //showErrorAlert(e.getMessage());
            e.printStackTrace();
            return false;
        }catch(NullPointerException e) {
            showErrorAlert(e.getMessage());
        }
        return true;
    }

here we can see that two connections are being established at one time and it shows the error message

org.sqlite.SQLiteException: [SQLITE_BUSY]  The database file is locked (database is locked)

But when I tried to execute the function having only one connection instances in which update query was executed:
public static void changeStock(double quantity, int id) {
        con=Connectivity.getConnectivity();
        if(quantity!=0) {
            try {
                pst=con.prepareStatement("UPDATE Product \r\n" +
                        "SET Stock=Stock+(?) \r\n" +
                        "WHERE Product_id=?");
                pst.setDouble(1, quantity);
                pst.setInt(2, id);
            } catch (SQLException e) {
                showErrorAlert(e.getMessage());
                e.printStackTrace();
            }
        }
    }

it still showed the error that is shown above.
My problems are a little long but hope so that you can help me.
Thanks


text:
Q: How to track the changes done in the CRM solution (i.e., like version control)? We are a distributed development team working on same solution while performing customization for our CRM instance.
At times, it becomes important to know who has done what changes, or which customization has been done by whom. For example, if I would want to know who has added/ modified/ deleted a few fields from a particular entity.
Is there any such provision in Dynamics CRM? And also, if there is approach can follow to track the changes in CRM solution.
Any help on this will be much appreciated.

A: One option would be the Solution Packager, which will allow you to pack / unpack a CRM solution into / from source control (like TFS)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Access button in ListBoxItem in Silverlight Hey everyone. I'm new to Silverlight and would like to access a button control that is part of a ListBoxItem. However, I'm not quite sure how to do this. My XAML is:
<DataTemplate x:Key="ItemTemplate2">
            <Grid Height="51">
                <TextBlock x:Name="tbName" Text="{Binding Property1}" Margin="0,0,98,0" d:LayoutOverrides="Height" Grid.ColumnSpan="2" HorizontalAlignment="Left" VerticalAlignment="Center"/>
                <Button x:Name="btnInfo"  HorizontalAlignment="Right" Margin="0,-11,0,0" Width="87" Height="54" VerticalAlignment="Top" Background="#FF8EC1D2" BorderBrush="#FF8EC1D2" BorderThickness="0">
                    <Image Source="../Images/btnNameImage.png" Stretch="None"/>
                </Button>
            </Grid>
        </DataTemplate>

How can I access the "btnInfo" from the code-behind?
Thanks for any help

A: you wont be able to access it directly from code behind, but you should be able to do what you want by registering an event with it.  Add a Loaded event to the button then in your codebehind define the corresponding method.
protected btninfo_Loaded(object sender, EventArgs e)
{
    Button btnInfo = (Button) sender;
    //do whatever you need to do
}

obviously you can do the same thing to handle click events or whatever you want.

A: This doesn't directly answer your question of programatically accessing a data template, but how about Binding?


text: Q: T-test with conditional data I have some data giving the vital signs of people before and after one experiment. Also for each single measurement I have some informations about the subject that could affect the results and need to be taken into account. How can I take more variables into account for the t-test? Is it possible?


text:
Q: Can I scan with a HP OfficeJet Pro 9018 without logging into an HP account? I bought an HP OfficeJet Pro 9018 for its duplex scanning capability.  The HP Smart scan application will not scan anything without logging into an HP account.  I absolutely do not want anything I scan to leave my LAN.  It can only go from my printer to my computer without leaving my LAN.
Is this possible with the HP 9018 (9010 series) without being logged into a HP account?
I've also tried the Windows 10 scan and fax utility.  It works, but duplex scans are done in two images, one for each side which is not what I want.
Is there any way to make a HP 9018 duplex scan without requiring internet access?  I'm open to buying a reasonably priced application if that is what it takes.


text:
Q: Canvas fill style is randomly changing i have a checkerboard. When the user hovers their mouse over a tile, it will highlight in yellow. When this happens, the game border will also turn yellow aswell as the last white checkers border.
I didnt even set the checkers to have a border so I have no idea why this is happening.
I draw the border like this:
context.fillStyle = '#000';
context.lineWidth = Math.min(canvas.width, canvas.height) / 170;

context.rect(board.gapW ,board.gapW, board.w - (board.gapW * 2), board.h - (board.gapH * 2));
context.stroke();

As you can see I set it to black everytime
I draw the checkers like this:
context.fillStyle = (board.info[i][j].c == 1) ? checkers.colours[checkers.colour].p1 : checkers.colours[checkers.colour].p2;
context.beginPath();
context.arc(x + (board.squareW / 2), y + (board.squareH / 2), r, 0, 2 * Math.PI, false);
context.fill();

The fill style is either black or white in this case and no border line is even used.
Here is a live version to see: http://jsfiddle.net/xupkmc60/2/
Border is line 78-82
Checker is line 111-114

A: There are two different types of context styles here: fillStyle and strokeStyle. You set the strokeStyle to yellow in highlightTile, but never unset it. I believe if you reset the strokeStyle as part of drawBoard you should be good.
That said, you may wish to use save and restore methods in functions that modify the canvas context to avoid this sort of inadvertent state leaking.

A:
When the user hovers their mouse over a tile

You set the strokeStyle to yellow in your event listener. This never gets reset to default value when you draw the board again.
To fix this you could either put context.strokeStyle = 'black' at the beginning of your drawBoard method, or use save and restore to preserve the state when drawing the board again.


text:
Q: Validating Google reCaptcha Just a simple challenge that I'm facing. I'm using Bootstrap Validator
 to validate my forms and I want to integrate it with Google reCaptcha.
My code

                  Please check that you are not a robot.

                Please enter a the security code.

How to I make it required so that a user cannot submit it without completing the captcha. I've found some javascript to do it but I want to integrate it with this library.
Update
I've used something like this and it works. You can provide feedback if you wish.

   Check "I am human" below
   <input type="text" name="recaptcha" required value="" id="recaptchaValidator" pattern="1" data-error="Check `I am human` !" style="display:none;">

Prove you are a human!

A: you can refer reCaptcha referance


text:
Q: Spark AR CAMERA zoom in and zoom out I am new to spark AR, I have seen the documentation but unable to find support where you can achieve below queries.

*

*Zoom in and zoom out camera towards a 3D object

*Rotate around a 3D object

It says camera coordinates are read only, you cannot change its position on an event.
Any pointers or insights on this guys?
Thanks

A: No, you cannot move the actual camera in Spark, because that is mapped to the device camera position (aka your phone).
However, if you wish to scale the video feed, you could get the camera extract texture, apply it as a material to a canvas or plane, and then scale the plane in order to create a "zoom" effect.
You can also rotate and move 3d objects by editing their transform properties, like so:
let myObj = Scene.root.find('my-object');
myObj.transform.x = value;
myObj.transform.y = value;
myObj.transform.z = value;
myObj.transform.rotationX = value;
myObj.transform.rotationY = value;
myObj.transform.rotationZ = value;
myObj.transform.scaleX = value;
myObj.transform.scaleY = value;
myObj.transform.scaleZ = value;

etc.


text:
Q: Integrate Mirth Connect with Splunk I want to push the logs that we generate in the Mirth to Splunk, I am not able to find if there is some direct way in which mirth logged errors can be pushed to Splunk dashboards. I am open to indirect but efficient ways of doing this if direct integration is not possible.

A: I'm not familiar with Mirth, but do a lot of onboarding of data into Splunk.  There are a few options:

*

*Install the Splunk Universal Forwarder to monitor Mirth logs and push them to Splunk.  The UF should be installed on the server running Mirth.

*Send Mirth logs as syslog to a syslog server and then on to Splunk.

*Send Mirth logs directly to Splunk using HTTP Event Collector.

There are other methods, but they probably don't apply.


text:
Q: Java:Android exclude packages with dependencies in final compiled file I have this problem in Android/Eclipse.
I´m working in Android Project , this one has to be configured in different ways for different customers,  this configurations are not similar(very different methods) between them.
The code is shared in 90%, but each customer has his own requirements.
Each customer has a package with diferent and multiple classes.
I would like only include package of choiced customer in the final compiled file.
But i have conditional object creation in my shared code, and i have to join all package for compiling.
More or less is this (Example)
//import every  customer packages
import com.project.customer_1
import com.project.customer_2
import com.project.customer_3
…..
import com.project.customer_98
import com.project.customer_99
……..
final static int customer=2; //Define the customer for this compilation
………

if (customer==1) { //unreachable code
customerClass1 customer1=new customerClass1();
customer1.method1_1;
customer1.method1_2;
customer1.method1_3;
}

else if (customer==2) {
customerClass2 customer2=new customerClass2();
customer2.method2_1;
customer2.method2_2;
customer2.method2_3;
}
…….//unreachable code
else if (customer==98) {//unreachable code
customerClass98 customer98=new customerClass98();
customer98.method98_1;
customer98.method98_2;
customer98.method98_3;
}
else if (customer==99{//unreachable code
customerClass99 customer99=new customerClass99();
customer99.method99_1;
customer99.method99_2;
customer99.method99_3;
}
............

Is clear when customer=X, the other choices  are unreachable code. I would like  exclude other customer packages/classes than customer is choiced in compiled file. But exist dependency in code
Note: For me is not valid comment code, neither reflection.

A: You shouldn't do it in way you've described.
You should create additional level of abstraction to access data/logic specific to customers. And move that customer specific logic/data to separate libraries/projects.
To work with separated customer projects, your abstraction level should use dynamic class loading.
Edit. If you can't refactor your project, you can create Proguard config files for each customer to remove unreachable code.


text:
Q: Get next Hannukah date in C# I am trying to find out from today's UTC date the date of the next Hannukah.
I already found that C# has HebrewCalendar class and I was able to get the current Jewish date with GetYear(), GetMonth()andGetDayOfMonth(). But don't really know how to work with this information to get the Jewish date that is gonna happen next for the current date.
Hannukah is dated on 25th of Kislev (3rd month in Jewish calendar).

A: @DmitryBychenko's answer is fine, although if you don't want to loop, you can also calculate it:
var calendar = new HebrewCalendar();
var result = DateTime.UtcNow;
if(
        calendar.GetMonth(result) < 3
    || (calendar.GetMonth(result)==3 && calendar.GetDayOfMonth(result)<25)
  )
   result = new DateTime(calendar.GetYear(result), 3, 25, calendar);
else
   result = new DateTime(calendar.GetYear(result)+1, 3, 25, calendar);

If you are under 25/3 on the HebrewCalendar, use this year, else use next
Result is also 7 Dec 2015 in the gregorian calendar
If (as per the comments) you don't want those pesky if statements for some reason, you could do something like:
var calendar = new HebrewCalendar();
var result = DateTime.UtcNow;
var addYear = (calendar.GetMonth(result) < 3 || (calendar.GetMonth(result)==3 && calendar.GetDayOfMonth(result)<25)) ? 0 : 1;
result = new DateTime(calendar.GetYear(result) + addYear, 3, 25, calendar);

I don't think this helps readability but there you go

A: As it was suggested on Twitter, here's a Noda Time solution:
// As of 2.0, it will be CalendarSystem.HebrewCivil
var calendar = CalendarSystem.GetHebrewCalendar(HebrewMonthNumbering.Civil);
var today = SystemClock.Instance.InZone(DateTimeZone.Utc, calendar).Date;

var thisHannukah = new LocalDate(today.Year, 3, 25, calendar);
return thisHannukah >= today ? thisHannukah : thisHannukah.PlusYears(1);

Alternative for the last two statements:
var year = today.Month < 3 || today.Month == 3 && today.Day <= 25
    ? today.Year : today.Year + 1;
return new LocalDate(year, 3, 25, calendar);

If we go ahead with feature request 317, this could be much simpler. For example:
// Putative API only! Doesn't work yet!
MonthDay hannukah = new MonthDay(3, 25, calendar);
var nextHannukah = hannukah.NextOrSame(today);

A: Eh, just looping? Testing date one by one starting from, say, DateTime.Now?
  HebrewCalendar calendar = new HebrewCalendar();
  DateTime result = DateTime.Now;

  for (DateTime date = DateTime.Now.Date; ; date = date.AddDays(1)) {
    if (calendar.GetDayOfMonth(date) == 25 && calendar.GetMonth(date) == 3) {
      result = date;

      break;
    }
  }

it returns result == 7 Dec 2015?


text:
Q: Java Queue Program Results to Empty When Dequeueing This is my code:
import java.util.LinkedList;
import java.util.Scanner;
import java.util.InputMismatchException;
import java.util.*;

class Customer {
       public String lastName;
       public String firstName;
       public Customer() {
       }
       public Customer(String last, String first) {
          this.lastName = last;
          this.firstName = first;
       }
       public String toString() {
          return firstName + " " + lastName;
       }
    }
    class HourlyCustomer extends Customer {
       public double hourlyRate;
       public HourlyCustomer(String last, String first) {
          super(last, first);
       }
    }

class GenQueue<E> {
   private LinkedList<E> list = new LinkedList<E>();
   public void enqueue(E item) {
      list.addLast(item);
   }
   public E dequeue() {
      return list.poll();
   }
   public boolean hasItems() {
      return !list.isEmpty();
   }
   public boolean isEmpty()
   {
       return list.isEmpty();
   }
   public E removeFirst(){
       return list.removeFirst();
   }
   public E getFirst(){
       return list.getFirst();
   }
   public int size() {
      return list.size();
   }

   public void addItems(GenQueue<? extends E> q) {
      while (q.hasItems()) list.addLast(q.dequeue());
   }
}

public class something {

    public static void main(String[] args){

        Scanner sc = new Scanner(System.in);
        String input1;
        String input2;
        int choice = 1000;

        GenQueue<Customer> empList;
        empList = new GenQueue<Customer>();
        GenQueue<HourlyCustomer> hList;
        hList = new GenQueue<HourlyCustomer>();

        while(true){

        do{

            System.out.println("================");
            System.out.println("Queue Operations Menu");
            System.out.println("================");
            System.out.println("1,Enquene");
            System.out.println("2,Dequeue");
            System.out.println("0, Quit\n");
            System.out.println("Enter Choice:");
            try{

                choice = sc.nextInt();

                switch(choice){
                case 1:

                    do{

                    System.out.println("\nPlease enter last name:  ");
                    input1 = sc.next();
                    System.out.println("\nPlease enter first name:  ");
                    input2 = sc.next();
                    hList.enqueue(new HourlyCustomer(input1, input2));
                    empList.addItems(hList);

                    System.out.println("\n"+(input2 + " " +  input1) + " is successful queued");

                    System.out.println("\nDo you still want to enqueue?<1> or do you want to view all in queue?<0> or \nBack to main menu for dequeueing?<menu>: ");
                    choice = sc.nextInt();

                    }while (choice != 0);

                     System.out.println("\nThe customers' names are: \n");

                     while (empList.hasItems()) {
                     Customer emp = empList.dequeue();
                     System.out.println(emp.firstName + " " + emp.lastName + "\n" );
                     }

                     break;

                case 2:

                    if (empList.isEmpty()) {
                        System.out.println("The queue is empty!");
                    }
                    else
                    {
                    System.out.println("\nDequeued customer: "  +empList.getFirst());
                    empList.removeFirst();
                    }

                    if (empList.isEmpty()) {
                        System.out.println("The queue is empty!");
                    }
                    else
                    {
                    System.out.println("\nNext customer in queue: "  +empList.getFirst()+"\n");
                }

                    break;

                case 0:

                    System.exit(0);

                default:
                        System.out.println("Invalid choice");
                }

            }

            catch(InputMismatchException e){
                System.out.println("Please enter 1-5, 0 to quit");
                sc.nextLine();
            }

        }while(choice != 0);
        }
    }
}

I want to make a program that accepts queue and then can also dequeue. in case 1 i made the queue successfully, but at case 2, i encountered a certain trouble that I cant figure out that I have to stack overflow it, Im stuck here and I might just be missing out the trivial things on this code. So I need your help. Why does in case 2 my dequeue gets passed an empty list? How do i fix this? Thank you very much!

A: when you populate your hlist you dequeue all elements from empList and hence your empList will be empty at last.
while (q.hasItems()) list.addLast(q.dequeue());
You can rewrite your addItems method, to just iterate over the elements in the given queue and add them to its own LinkedList.


text:
Q: Trying to setup a proxy via a c++ program. Doesn't work I am trying to set up a proxy via a c++ program but it doesn't work.
The program itself works fine but actually, it doesn't set anything.
This is the code:
#include <iostream>
#include <windows.h>
#include <string>
using namespace std;

void newproxy();

int main (){

    int ch = 0;

    cout << "Select the option:\n\n\t(1)Set a NEW proxy\n\t(2)View the current proxy settings\n\t(3)Clear ALL proxy settings\n\t(4)Exit\n\n\t";
    cin >> ch;
    cin.ignore();
    switch (ch){

        case 1 :
            system("cls");
            newproxy();
            break;

        case 2 :
            system("cls");
            system("netsh winhttp show proxy");
            system("pause");
            system("cls");
            main();
            break;

        case 3 :
            system("cls");
            system("netsh winhttp reset proxy");
            system("cls");
            cout << "ALL proxy settings cleared\n\n";
            main();
            break;

        case 4 :
            return 0;
            break;

    }
}

void newproxy(){

    string ip;
    string port;
    int ch = 0;

    cout << "Insert ip: ";
    getline (cin, ip);
    cout << "Inster port: ";
    getline(cin, port);
    cout << "\nAre those the correct ip and port? " << ip << ":" << port << "\n\n\t(1)Yes (2)No (3)Abort\n\n\t";
    cin >> ch;
    cin.ignore();
    switch (ch){

        case 1 :
            break;

        case 2 :
            system("cls");
            newproxy();
            break;

        case 3 :
            system("cls");
            main();
            break;

    }
    system(("netsh winhttp set proxy proxy-server="+ip+":"+port).c_str());
    system("cls");
    cout << "Proxy succesfully setted\n\n";
    main();
}

When I set a new proxy the program actually sees it and displays it even if I restart the program, but nothing is really done. If I open the browser and search "my IP" it displays the same public IP not like when I set it up in the Windows setting.
Can someone help me?
Is the problem in the code or is it something else?
Thanks.

A:  system((std::string("netsh winhttp set proxy ") + ip +":" + port).c_str());

You almost had it.
To use the Netsh.exe tool to configure a proxy server, follow these steps:
Click Start, click Run, type cmd, and then click OK.
At the command prompt, type netsh winhttp set proxy proxyservername:portnumber, and then press ENTER.
Good luck.


text:
Q: How can I query all entities that have an associated entity in Hibernate Query Language? I'm struggling to understand how can I query all products that have specified category association.

I might need something like this
select p.* from product p
inner join product_category pc on p.product_id = pc.product_id
inner join category c on pc.category_id = c.category_id
where c.name = :categoryName;

but in HQL.

A: Assuming that you use the following mapping:
@Entity
@Table(name = "product")
class Product
{
   @Id
   @Column(name = "product_id")
   private Long id;

   @ManyToMany
   @JoinTable(name = "product_category",
        joinColumns = @JoinColumn(name = "category_id"),
        inverseJoinColumns = @JoinColumn(name = "product_id")
    )
   private List<Category> categories;

   // getters/ setters
}

@Entity
@Table(name = "category")
class Category
{
   @Id
   @Column(name = "category_id")
   private Long id;

   @Column(name = "name")
   private String name;

   // getters/ setters
}

you can use the following HQL:
select p from Product
join fetch p.categories c
where c.name = :categoryName


text:
Q: Calculating Margin from Two Tables SQL So I am running into an issue that I have isolated to part of the WHERE statement and I can't figure it out.  I am calculating margin for an item based on the cost and price tables associated with it. It works fine if I want to limit it to items whose list price is below 17%, but if I want to check the other price tiers, e.g. pricing if a customer buys +100 units, I get an ODBC error. This is my code that doesn't work:
            strSQL = "SELECT IMFGR || ICOLOR || IPATT as Item, INAME as Description1, INAME2 as Description2,  IPRCCD as PClass, ICSTCD as CClass, " _
               & "c.TLASTC as Cost, p.$LIST as List, ((p.$LIST-c.TLASTC)/p.$LIST) as GPM, p.$P2 as Price2, ((p.$P2-c.TLASTC)/p.$P2) as GPM2, " _
               & "p.$P3 as Price3, ((p.$P3-c.TLASTC)/p.$P3) as GPM3, p.$P4 as Price4, ((p.$P4-c.TLASTC)/p.$P4) as GPM4, p.$P5 as Price5, ((p.$P5-c.TLASTC)/p.$P5) as GPM5, " _
               & "p.$P6 as Price6, ((p.$P6-c.TLASTC)/p.$P6) as GPM6, p.$P7 as Price7, ((p.$P7-c.TLASTC)/p.$P7) as GPM7, p.$P8 as Price8, ((p.$P8-c.TLASTC)/p.$P8) as GPM8, " _
               & "p.$P9 as Price9, ((p.$P9-c.TLASTC)/p.$P9) as GPM9, p.$P10 as Price10, ((p.$P10-c.TLASTC)/p.$P10) as GPM10, p.$P11 as Price11, ((p.$P11-c.TLASTC)/p.$P11) as GPM11, " _
               & "p.$P12 as Price12, ((p.$P12-c.TLASTC)/p.$P12) as GPM12 " _
               & "FROM ITEM i " _
               & "LEFT JOIN COST c " _
                    & "ON i.ICSTCD = c.TCSTCD " _
               & "LEFT JOIN PRICE p " _
                    & "ON i.IPRCCD = p.$PRCCD " _
               & "WHERE (IPRCCD != '') AND (p.$LIST# = 'LP') AND (IPOL1 != 'DI' AND IPOL2 != 'DI' AND IPOL3 != 'DI') AND (IPOL1 != 'BR' AND IPOL2 != 'BR' AND IPOL3 != 'BR') AND (IMFGR = '" & man & "') AND " _
               & "((ICCTR != 'ZDS') AND (IPRODL != 'XXX')) AND " _
               & "((p.$LIST-c.TLASTC)/p.$LIST) <= '" & margin & "' OR ((p.$P2-c.TLASTC)/p.$P2) <= '" & margin & "' " _
               & "ORDER BY IMFGR"

The OR in the second to last line generates the error. If I change it to AND, it runs but then it looks for both statements to be true. I want to return a result if any of the margins are below a certain %. What am I doing wrong?
It isn't the p.$LIST# = 'LP' because the p.$p2, p.$p3, etc. are still in there with 'LP'

A: AND has precedence over OR.  You need to wrap the OR clause in parens:
  & "(((p.$LIST-c.TLASTC)/p.$LIST) <= '" & margin & "' OR ((p.$P2-c.TLASTC)/p.$P2) <= '" & margin & "') " _


text:
Q: Would cartesian product be the best approach for this Related Questions:

*

*Matrix Combination Logic

*Efficient way to determine the outcome of test matrix
I have 25 individual validations that I need to test all possible combinations, I have seen a couple of questions related to what I'm looking for. The answers suggested something along the lines of using the cartesian product. Would that be the best method for finding the results I'm looking for or is there a better way?
Example:
Think about a 9 by 9 number grid starting from 0 - 9 on the X and Y axis:
|0|1|2|3|4|5|6|7|8|9|
|1|
|2|
|3|
|4|
|5|
|6|
|7|
|8|
|9|

All the individual validations are boolean ( true = passed, false = failed ).
The X Axis represents all the test results, Example:
|0|1|2|3|4|5|6|7|8|9|
|1|T|T|T|T|T|T|T|T|T|
|2|
|3|
|4|
|5|
|6|
|7|
|8|
|9|

And the Y Axis represents all the possible combinations, Example:
|0|1|2|3|4|5|6|7|8|9|
|1|T|T|T|T|T|T|T|T|T|
|2|F|T|T|T|T|T|T|T|T|
|3|F|F|T|T|T|T|T|T|T|
|4|F|F|F|T|T|T|T|T|T|
|5|F|F|F|F|T|T|T|T|T|
|6|F|F|F|F|F|T|T|T|T|
|7|F|F|F|F|F|F|T|T|T|
|8|F|F|F|F|F|F|F|T|T|
|9|F|F|F|F|F|F|F|F|T|

There will be more Y Axis combinations but I hope you get the point.
My question is how would I go about solving all the possible combinations?


text:
Q: Where do I fix the asm error: 'asm' undeclared (first use in this function) in compiling gcc-7.2.0 I have been trying to install gcc-7.2.0. I am getting the same error on both ubuntu and on centos 6.7.The posts I have seen suggest changing the CFLAGS from -std=c99 to -std=gnu99. But I cannot figure out in which file I have to change this. The same error occurs on several lines, starting at line 55 of the file gcc_7_2_0_release/libgcc/config/i386/sfp-exceptions.c.
The error is
gcc_7_2_0_release/libgcc/config/i386/sfp-exceptions.c: In function '__sfp_handle_exceptions':
gcc_7_2_0_release/libgcc/config/i386/sfp-exceptions.c:55:7: error: 'asm' undeclared (first use in this function)
asm volatile ("fdiv\t{%y0, %0|%0, %y0}" : "+t" (f));

Help will be appreciated please
gcc- v gives the following long extract:
 "Using built-in specs.
Target: i686-redhat-linux
Configured with: ../configure --prefix=/usr --mandir=/usr/share/man
--infodir=/usr/share/info --with-bugurl=http://bugzilla.redhat.com/bugzilla
--enable-bootstrap --enable-shared --enable-threads=posix --enable-checking=release --with-system-zlib --enable-__cxa_atexit --disable-libunwind-exceptions --enable-gnu-unique-object --enable-languages=c,c++,objc,obj-c++,java,fortran,ada --enable-java-awt=gtk --disable-dssi --with-java-home=/usr/lib/jvm/java-1.5.0-gcj-1.5.0.0/jre --enable-libgcj-multifile --enable-java-maintainer-mode --with-ecj-jar=/usr/share/java/eclipse-ecj.jar --disable-libjava-multilib --with-ppl --with-cloog --with-tune=generic --with-arch=i686 --build=i686-redhat-linux
Thread model: posix
gcc version 4.4.7 20120313 (Red Hat 4.4.7-18) (GCC)

I had to put this as an edit because it is too long for a comment


text:
Q: Variable importance in party vs randomForest I am getting completely different results from cforest and randomForest with regards to variable importance (mean decrease in accuracy):
require(randomForest)
require(party)
require(RCurl)

x <- getURL("https://raw.githubusercontent.com/mguzmann/r-funcs/master/data/tempData.csv")

tempData <- read.csv(text = x, quote="\"", row.names=1)

tempData$resp = as.factor(as.numeric(tempData$resp))
tempData$a = as.factor(as.numeric(tempData$a))
tempData$b = as.factor(as.numeric(tempData$b))
tempData$c = as.factor(as.numeric(tempData$c))
tempData$d = as.factor(as.numeric(tempData$d))

tempData.rf = randomForest(resp ~., tempData, importance=T)
importance(tempData.rf)

(simplified output)
MeanDecreaseAccuracy
a 10.18511
b 15.88859
c 27.13357
d 15.36184
tempData.cf = cforest(resp ~., tempData,
        controls=cforest_unbiased(ntree=500, mtry=4))
varimp(tempData.cf)

MeanDecreaseAccuracy
a 0.02219259
b 0.02903704
c 0.06500741
d 0.03765926
How should I compare these numbers and interpret their discrepancies? Why does this happen?

A: The two importances agree for a and c actually. There is a good tutorial about variable importance here. These are some of the guys who worked in cforest.
Also, I think the values are different in absolute value because if you check the documentation of the randomForest package it says:
importance(x, type=NULL, class=NULL, scale=TRUE, ...)
Which means that by default the importance of feature $\mathbf{x}_j$ is standardized: $\frac{\mbox{VI}(\mathbf{x}_j)}{\hat{\sigma}/\sqrt{\mbox{ntree}}}$
Where
$$\mbox{VI}(\mathbf{x}_j) = \frac{\sum_{t}^{\mbox{ntree}}\mbox{VI}^{(t)}(\mathbf{x}_j)}{\mbox{ntree}}$$

A: Traditional Random Forest uses "Gini Gain" splitting criterion in assessing Variable Importance, which is biased towards factor variables with many levels/categories. In contract, cforest function creates random forests not from CART trees, but from unbiased classification trees based on conditional inference, which gives much more robust results when multifactorial variables are involved, particularly when the function is used with subsampling without replacement. Here's a good paper that explains the differences more in depth:
Bias in random forest variable importance measures: Illustrations, sources and a solution. Strobl et al. (2007)


text:
Q: Cron job issue at centos server There are many processess executed via cron job at our production server. Time decided to run process is after every 50 minutes.
Crontab file entry-:
*/50 * * * * /usr/bin/php  /webuser/production/class/abc.php
*/50 * * * * /usr/bin/php  /webuser/production/class/abc_1.php
*/50 * * * * /usr/bin/php  /webuser/production/class/abc_2.php

But when we check cron logs there is error as shown below:
Oct 22 12:56:01 prodserver CROND[40603]: (root) CMD (/usr/bin/php  /webuser/production/class/abc.php )
Oct 22 12:56:01 prodserver CROND[40604]: (CRON) EXEC FAILED (/usr/sbin/sendmail): No such file or directory

Oct 22 12:56:14 prodserver CROND[40602]: (root) MAIL (mailed 1911 bytes of output but got status 0x0001#012)

When we run same process as stand alone on command line /usr/bin/php  /webuser/production/class/abc.php it runs successfully.
We browsed over internet and found an answer on stackoverflow by one user saying just make the process which tend to get executed by cron job to write its output in some random file, so we did as shown below:
/usr/bin/php  /webuser/production/class/abc.php >> /somerandomfolder/log_cron_check

By doing this the process get executed without an error via cron job. Though cron job executed by placing >> this but the time of execution is random its not what is mentioned in crontab. Cron was mentioned to run after 50 minutes but our database and cron log showing it runs unexpectedly after 10 minutes.
queue_start_time
2022-10-22 12:20:01
2022-10-22 12:30:01

Please suggest where we are doing wrong.

A: You get an error in the crontab logs because you don't have sendmail installed.
How is that related even if you don't use sendmail in your PHP code?
crontab has an implementation to send alert notifications when finishes a job.
from crontab man page

If standard output and standard error are not redirected by commands executed from the crontab entry, any generated output or errors shall be mailed, via an implementation-defined method, to the user.

As mentioned you need to redirect both stdout and stderr, you have only tried to redirect the stdout.
Something like this should solve it.
*/50 * * * * /usr/bin/php /webuser/production/class/abc.php &>/tmp/log


text:
Q: Disable html validation and cleanup in CKEditor We have additional placeholders, which are embeded in conent edited by CKEditor and we need to be possible to place such placeholders before and after TR-tag, so we could organize repeating of data in the table. But CKEditor probably find that is not valid HTML and take out repeater placeholders before the table.
For example I write next html in source mode:

{start}
...
{end}

I switch to html mode and back to source, now my html is treated to the next view:

{start}{end}

...

Possibly there is a CKEditor switch to turn off all syntax cleanup or specially for tables?

A: Try Adding this line to Config.js file:
config.allowedContent = true;

A: CKEditor is not a source code editor, but a WYSIWYG editor which uses browsers' contenteditable implementations for its editing feature. Therefore, it needs to work on valid and real HTML.
Although, check the config.protectedSource setting. You'll be able to hide those {start|end} tags from parser.


text:
Q: Implementing a stack to use backtracking for struct This is a program that enables a Robot to follow black lines through a "maze". The maze is made of 7x7 black lines with a entry line leading through it. There can be empty squares and lines leading nowhere. where the black lines meet there is a white square.
The idea is to save these squares in a struct and make the robot run through the maze and save the individual structs in a stack.
I want to do this so that the robot can find the way back through backtracking.
void push(int value ){
if(top ==49){ //uncertain what to write here
} else{
    top = top+1;
    a[top] = value;
}

int pop(){

if(top ==-1){
    return -234;
}else{

    int r = a[top];
    top = top-1;
    return r;
   }
 }

I'm uncertain how make this work together with this
typedef struct proxy {
int edges[4];
int visited;
int exists;
int token;
} proxy;

int main() {

   /* This part is to make simulation work, idea is to start in the middle
      an 14x14, because that allows us to go in any direction.
      the arrays are the values that the simulation gives back.
      This seems to work even though it's not pretty. */

   static int x = 7;
   static int y = 7;
   static int zaehler = 0;  //Zähler für Rundenbegrenzung
   int Ary[14][14];
   int hilfN, hilfO, hilfS, hilfW;
   int i,j;
   int N[8] = {16, 48, 80, 112, 144, 176, 208, 240};
   int O[8] = {128, 144, 160, 176, 192, 208, 224, 240};
   int S[8] = {32, 48, 96, 112, 160, 176, 224, 240};
   int W[8] = {64, 80, 96, 112, 192, 208, 224, 240};
   int Intersec = Robot_GetIntersections();
   int myRobot_Move(x,y){
   return Robot_Move(x-7,y-7);
}
for(i= 0; i < 14; i++){

    for(j= 0; j < 14; j++){
        Ary[i][j] = 0;
        }
}

myRobot_Move(x,y);

while (x < 14 && y < 14) {
Intersec = Robot_GetIntersections();
Ary[x][y] = Intersec;

for (hilfN=0; hilfN<8; hilfN++){
    if(N[hilfN] == Intersec){
        if(Ary[x][y+1] == 0){
            y++;
            myRobot_Move(x,y);
        }
    }
}
//Osten
for (hilfO=0; hilfO<8; hilfO++){
        if(O[hilfO] == Intersec){
            if(Ary[x+1][y] == 0){
                x++;
                myRobot_Move(x,y);
            }
        }
    }
//Süden
for (i=0; i<8; i++){
        if(S[i] == Intersec){
            if(Ary[x][y-1] == 0){
                y--;
                myRobot_Move(x,y);
            }
        }
    }
//Westen
for (i=0; i<8; i++){
            if(W[i] == Intersec){
                if(Ary[x-1][y] == 0){
                x--;
                myRobot_Move(x,y);
            }
        }
    }

if (Ary[x][y+1] && Ary[x+1][y] && Ary[x][y-1] && Ary[x-1][y] > 0){
    break;
    printf("End");
   }
 }

return EXIT_SUCCESS;
}

A: If you want your stack a to save struct proxys instead of ints, change the presumed int a[50]; to proxy a[50]; and the functions push() and pop() as follows:
void push(proxy value)
{
    if (top == 49) puts("'a' stack overflow"), exit(1);
    else a[++top] = value;
}

proxy pop()
{
    if (top == -1) return (proxy){-234};
    else return a[top--];
}


text:
Q: Stop code from copying header I have been tweaking the following vba code that copies data from a sheet into new sheets bases on a code in the column. My hang up is that I do not have headers so the code copies the first line to all the new sheets. How do I change the code so it does not look for a header?
Sub parse_data()
Dim lr As Long
Dim ws As Worksheet
Dim vcol, i As Integer
Dim icol As Long
Dim myarr As Variant
Dim title As String
Dim titlerow As Integer

    vcol = 5
    Set ws = ActiveSheet
    lr = ws.Cells(ws.Rows.Count, vcol).End(xlUp).Row
    title = "A1:AA1"
    titlerow = ws.Range(title).Cells(1).Row
    icol = ws.Columns.Count
    ws.Cells(1, icol) = "Unique"
    For i = 2 To lr
        On Error Resume Next
        If ws.Cells(i, vcol) <> "" And Application.WorksheetFunction.Match(ws.Cells(i, vcol), ws.Columns(icol), 0) = 0 Then
            ws.Cells(ws.Rows.Count, icol).End(xlUp).Offset(1) = ws.Cells(i, vcol)
        End If
    Next
    myarr = Application.WorksheetFunction.Transpose(ws.Columns(icol).SpecialCells(xlCellTypeConstants))
    ws.Columns(icol).Clear
    For i = 2 To UBound(myarr)
        ws.Range(title).AutoFilter field:=vcol, Criteria1:=myarr(i) & ""
        If Not Evaluate("=ISREF('" & myarr(i) & "'!A1)") Then
            Sheets.Add(after:=Worksheets(Worksheets.Count)).Name = myarr(i) & ""
        Else
            Sheets(myarr(i) & "").Move after:=Worksheets(Worksheets.Count)
        End If
        ws.Range("A" & titlerow & ":A" & lr).EntireRow.Copy Sheets(myarr(i) & "").Cells(Rows.Count, 1).End(xlUp)(2)
        Sheets(myarr(i) & "").Columns.AutoFit
    Next
    ws.AutoFilterMode = False
    ws.Activate
End Sub

A: I think you can try:
 ws.Range("A" & titlerow + 1 & ":A" & ...

This would skips the titlerow in the copy. (These things are hard to be sure of not having the sheet.)


text:
Q: How to pagination TWILIO Conversations and its messages in PHP? I am having issues in paginating the TWILIO Conversations and Its messages. I have tried to paginate but all the pages are giving same results. Can someone please help ?
$conversations = $twilio
    ->conversations
    ->v1
    ->services(TWILIO_CHAT_SERVICE_SID)
    ->conversations
    ->read($page_size, $page);


text:
Q: QDataWidgetMapper Как в диалоговом окне сделать кнопку которая будет добавлять данные из диалогового окна neworder.cpp в базу из этих трех полей(lineedit)?
Листинг mainwindow.cpp:
model =  new QSqlTableModel(this,baze);
model->setTable("orders");
model->setEditStrategy(QSqlTableModel::OnManualSubmit);
model->select();
ui->tableView->setModel(model);
new_o = new newOrder();
new_o->setParent(this,Qt::Window);
new_o->setModel(model);

редактирование при дабл клике
void MainWindow::on_tableView_doubleClicked(const QModelIndex &index)
{

    new_o->mapper->setCurrentModelIndex(index);
    new_o->show();
}

Вызываю окно добавление данных
void MainWindow::on_addOrderButton_clicked()
{
    new_o->show();
}

файл окна neworder.cpp
    mapper = new QDataWidgetMapper(this);
    mapper->setSubmitPolicy(QDataWidgetMapper::ManualSubmit);

}

void newOrder::setModel(QAbstractItemModel *model)
{

    mapper->setModel(model);
    mapper->addMapping(ui->adressLineEdit,1);
    mapper->addMapping(ui->orderTextEdit,2,"plainText");
    mapper->addMapping(ui->phoneLineEdit,3);

}

void newOrder::on_applyButton_clicked()
{
    mapper->submit();

}

A: Как-то так:
void newOrder::on_insertButton_clicked() {
    const int row = model->rowCount();
    model->insertRow(row);
    mapper->setCurrentModelIndex(model->index(row,0));
}

Дополнение
Чтобы указатель на модель не хранить отдельно, лучше так:
void newOrder::on_insertButton_clicked() {
    if(mapper->model() == Q_NULLPTR) return;

    const int row = mapper->model()->rowCount();
    mapper->model()->insertRow(row);
    mapper->setCurrentModelIndex(mapper->model()->index(row,0));
}


text:
Q: Can one calculate the distance from Earth to the camera, given a single picture? Given an image of (part of) a sphere of known size, can one calculate the distance to the camera based on the relative size of the sphere in the image?  My instinct is "no" unless you have some fixed parameters either for the camera, the resulting image, or at least an object in the foreground for reference.
Then you would attempt to calculate the size of the 2D sphere based on the visible segment and use some ratio to determine the distance as compared to the actual known thing.
Am I on the right track or how would you do this?  In the example below, we could attempt to fix variable related to the camera or by using the humanoids in the bottom left corner.

A: You are right - if you know nothing at all about the camera, you can't figure this out.
Here is one way to approach the solution:
If you assume that the lens of the camera acts like a pinhole, then the outline of the sphere on the focal plane of the camera (film, sensor) would be a circle - and the center of the circle would correspond to the center of the sphere.
Therefore, if you can see enough of the edge of the sphere you can figure out how large the image of the sphere would have been on the focal plane. If you then know the focal length of the lens, and with what magnification you are looking at the image on the focal plane, you can figure out how big the angle is that the sphere subtends. Then you also need to know the distance to the sphere in order to compute its actual distance.


text:
Q: Vagrant vs VBox folder share I have been using Vagrant for few months. Also I have started using Virtual box without Vagrant with sharing folders from host OS and it works well so far.
My question is why is Vagrant needed if Virtual Box can share folders without Vagrant?
Maybe I don't use Vagrant's other features so I don't need them so far.

A: Just a few things, but will probably not be exhaustive:

*

*Vagrant operates multiple provider, not only Virtualbox, you can run vagrant with Virtualbox, VMWare, HyperV ... (docker as well even if there are different pros and cons) so vagrant abstracts this for you

*vagrant can setup shared folders as you experienced, but can easily set different shared folder types (nfs, rsync ..) depending your setup

*vagrant will manage all the networking of the VM, if you need a static IP, it will associate hostname and static IP and setup all the routes for you.

*vagrant works well with many provisioning tools (puppet, chef, ansible ...) so you can easily create and re-created multiple times the same environment
On top of all this, why is vagrant good to use ? In team. If you work in team, you share a vagrant file (just a ruby script file) and "magically" all your team members share the same environment to work.


text:
Q: Problem with URLs for thumbnails created using Shrine plugin on Rails 6 I have been struggling with this for a couple of days and hoping someone can help.  There may be something obvious that I am missing!
I am using Shrine plugin for Rails to upload PDF files and generate a thumbnail for the first page.  The PDF is loading in the designated storage space and the thumbnail is also getting created and getting sorted in the same location.  However I am not able to display the thumbnail in the view.
Initializer:
require "shrine"
require "shrine/storage/file_system"
#require "shrine/storage/memory"

Shrine.storages = {
    cache: Shrine::Storage::FileSystem.new("public", prefix: "uploads/cache"),
    store: Shrine::Storage::FileSystem.new("public", prefix: "uploads/store")
}

Shrine.plugin :activerecord    # loads Active Record integration
Shrine.plugin :cached_attachment_data # enables retaining cached file across form redisplays
Shrine.plugin :restore_cached_data  # extracts metadata for assigned cached files
Shrine.plugin :determine_mime_type
Shrine.plugin :validation_helpers
Shrine.plugin :validation
Shrine.plugin :derivatives
#Shrine.plugin :model, cache: false

Uploader:
require "image_processing/mini_magick"

class FileUploader < Shrine
 include ImageProcessing::MiniMagick

 plugin :processing # allows hooking into promoting
 plugin :versions   # enable Shrine to handle a hash of files
 plugin :derivatives
 plugin :default_url
# plugin :delete_raw # delete processed files after uploading

 Attacher.validate do
  validate_max_size 5*1024*1024, message: "is too large (max is 5 MB)"
  validate_mime_type %w[application/pdf]
 end

 Attacher.derivatives do |original|
  magick = ImageProcessing::MiniMagick.source(original).loader(page:0).convert("jpeg")
  {
   thumb: magick.resize_to_limit!(200, 200)
  }

 end

end

Testing View:

<%= notice %>

  Number:
  <%= @issue.number %>

  Title:
  <%= @issue.title %>

  Data:
  <%= @issue.file_data %>

  Issue Preview
  <embed src="<%= @issue.file_url %>" width="80" height="160" />

  Issue Thumbnail:
  <%= image_tag @issue.file_url(:thumb) if @issue.file %>

  Issue:
  <%= image_tag @issue.file_url if @issue.file %>

<%= link_to 'Edit', edit_issue_path(@issue) %> |
<%= link_to 'Back', issues_path %>

Also, when I look at data stored in the file_data field I see no information added for the thumbnail.
File Data: {"id":"fccd20a9323aa5b63fd912f4ca833ebb.pdf","storage":"store","metadata":{"filename":"pdf_sample.pdf","size":351987,"mime_type":"application/pdf"}}

A: You need to either enable automatic creation on attachment promotion to permanent storage:
Shrine.plugin :derivatives, create_on_promote: true

Or process the derivatives manually on attachment:
record.file_derivatives!

A: Finally figured it out.  I solved the issue by adding the following to the _form.html.erb:
<%= form.hidden_field :image, value: @photo.cached_image_data %>


text:
Q: Performance issues : Kafka + Storm + Trident + OpaqueTridentKafkaSpout We are seeing some performance issues with Kafka + Storm + Trident + OpaqueTridentKafkaSpout
Mentioned below are our setup details :
Storm Topology :
Broker broker = Broker.fromString("localhost:9092")
    GlobalPartitionInformation info = new GlobalPartitionInformation()
    if(args[4]){
        int partitionCount = args[4].toInteger()
        for(int i =0;i<partitionCount;i++){
            info.addPartition(i, broker)
        }
    }
    StaticHosts hosts = new StaticHosts(info)
    TridentKafkaConfig tridentKafkaConfig = new TridentKafkaConfig(hosts,"test")
    tridentKafkaConfig.scheme = new SchemeAsMultiScheme(new StringScheme())

    OpaqueTridentKafkaSpout kafkaSpout = new OpaqueTridentKafkaSpout(tridentKafkaConfig)
    TridentTopology topology = new TridentTopology()
    Stream st  = topology.newStream("spout1", kafkaSpout).parallelismHint(args[2].toInteger())
            .each(kafkaSpout.getOutputFields(), new NEO4JTridentFunction(), new Fields("status"))
            .parallelismHint(args[1].toInteger())
    Map conf = new HashMap()
    conf.put(Config.TOPOLOGY_WORKERS, args[3].toInteger())
    conf.put(Config.TOPOLOGY_DEBUG, false)

    if (args[0] == "local") {
        LocalCluster cluster = new LocalCluster()
        cluster.submitTopology("mytopology", conf, topology.build())
    } else {
        StormSubmitter.submitTopology("mytopology", conf, topology.build())
        NEO4JTridentFunction.getGraphDatabaseService().shutdown()
    }

Storm.yaml we are using for Storm is as below :
########### These MUST be filled in for a storm configuration
storm.zookeeper.servers:
     - "localhost"
#     - "server2"
#
storm.zookeeper.port : 2999

storm.local.dir: "/opt/mphrx/neo4j/stormdatadir"

nimbus.childopts: "-Xms2048m"
ui.childopts: "-Xms1024m"
logviewer.childopts: "-Xmx512m"
supervisor.childopts: "-Xms1024m"
worker.childopts: "-Xms2600m -Xss256k -XX:MaxPermSize=128m -XX:PermSize=96m
    -XX:NewSize=1000m -XX:MaxNewSize=1000m -XX:MaxTenuringThreshold=1 -XX:SurvivorRatio=6
    -XX:+UseParNewGC -XX:+UseConcMarkSweepGC -XX:+CMSParallelRemarkEnabled
    -XX:CMSInitiatingOccupancyFraction=75 -XX:+UseCMSInitiatingOccupancyOnly
    -server -XX:+AggressiveOpts -XX:+UseCompressedOops -Djava.awt.headless=true -Djava.net.preferIPv4Stack=true
    -Xloggc:logs/gc-worker-%ID%.log -verbose:gc
    -XX:+UseGCLogFileRotation -XX:NumberOfGCLogFiles=10 -XX:GCLogFileSize=1m
    -XX:+PrintGCDetails -XX:+PrintHeapAtGC -XX:+PrintGCTimeStamps -XX:+PrintClassHistogram
    -XX:+PrintTenuringDistribution -XX:-PrintGCApplicationStoppedTime -XX:-PrintGCApplicationConcurrentTime
    -XX:+PrintCommandLineFlags -XX:+PrintFlagsFinal"

java.library.path: "/usr/lib/jvm/jdk1.7.0_25"

supervisor.slots.ports:
    - 6700
    - 6701
    - 6702
    - 6703

topology.trident.batch.emit.interval.millis: 100
topology.message.timeout.secs: 300
#topology.max.spout.pending: 10000

*

*Size of each message produced in Kafka : 11 KB

*Execution time of each bolt(NEO4JTridentFunction) to process the data : 500ms

*No. of Storm Workers : 1

*Parallelism hint for Spout(OpaqueTridentKafkaSpout): 1

*Parallelism hint for Bolt/Function(NEO4JTridentFunction) : 50

*We are seeing throughput of around 12msgs/sec from Spout.

*Rate of messages produced in Kafka : 150msgs/sec

Both Storm and Kafka are a single node deployment.
We have read about much higher throughput from Storm but are unable to produce the same. Please suggest how to tune the Storm+ Kafka + OpaqueTridentKafkaSpout configuration to achieve higher throughput. Any help in this regard would help us immensely.
Thanks,

A: You should set spout parallelism same as partition count for mentioned topics.
By default, trident accept one batch for each execution, you should increase this count by changing topology.max.spout.pending property. Since Trident forces ordered transaction management, your execution method (NEO4JTridentFunction)must be fast to reach desired solution.
In addition,you can play with "tridentConfig.fetchSizeBytes", by changing it, you can ingest more data for each new emit call in your spout.
Also you must check your garbage collection log, it will give you clue about real point.
You can enable garbage collection log by adding "-XX:+PrintGCDetails -XX:+PrintGCTimeStamps -verbose:gc -Xloggc:{path}/gc-storm-worker-%ID%.log", in worker.childopts settings in your worker config.
Last but not least, you can use G1GC, if your young generation ratio is higher than normal case.

A: Please set your worker.childopts based on your system configuration. Use SpoutConfig.fetchSizeBytes to increase the number of bytes being pulled into the topology. Increase your Parallelism hint.

A: my calculations: if 8 Cores and 500MS per bolt -> ~16 Messages/sec.
if you optimize the bolt, then you will see improvements.
also, for CPU bound bolts, try Parallelism hint = 'amount of total cores'
and increase topology.trident.batch.emit.interval.millis to the amount of time it takes to process entire batch divided by 2.
set topology.max.spout.pending to 1.


text:
Q: How to check validation of IP Address in jquery I need to add  IP Validation in my project .Is there any function in jquery or in jquery mobile.So that it will validate the in put field?
Thanks

A: The short version:
^(?!0)(?!.*\.$)((1?\d?\d|25[0-5]|2[0-4]\d)(\.|$)){4}$

Explained here
https://stackoverflow.com/a/26445549/3356679

A: You can use regular expressions to test if an IP is valid:
"127.0.0.1".match(/^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$/);

A: This should work for IP address
$.validator.addMethod('IP4Checker', function(value) {

    var ip="^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
    "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
    "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
    "([01]?\\d\\d?|2[0-4]\\d|25[0-5])$";
        return value.match(ip);
    }, 'Invalid IP address');

    $('#remoteForm').validate({
        rules: {
            ipAddr: {
                required: true,
                IP4Checker: true
            }
        }
    });

A: refer this document
IP validation
here he has used jqueryvalidator.js and explained with an example.
            $.validator.addMethod('IP4Checker', function(value) {
                return value.match(/^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$/);
            }, 'Invalid IP address');

            $('#form1').validate({
                rules: {
                    ip: {
                        required: true,
                        IP4Checker: true
                    }
                }
            });

A: Hi this is the best Solution and Mask for IP Adress
$.validator.addMethod('IP4Checker', function(value) {
        var ip = /^(\d|[1-9]\d|1\d\d|2([0-4]\d|5[0-5]))\.(\d|[1-9]\d|1\d\d|2([0-4]\d|5[0-5]))\.(\d|[1-9]\d|1\d\d|2([0-4]\d|5[0-5]))\.(\d|[1-9]\d|1\d\d|2([0-4]\d|5[0-5]))$/;
        return value.match(ip);
        }, 'Invalid IP address');

    var $validator = $("#addCardForm").validate({
          rules: {
              txtIP: {
              required: true,
              IP4Checker: true
              }

          }
        });

A: I use jQuery Validation Plugin by:
$.validator.addMethod('IP4Checker', function(value) {
        var ip = "^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$";
            return value.match(ip);
}, 'Invalid IP address');

$('#form').validate({
    rules:{
        ip:{
            required: true,
            IP4Checker: true
        }
    }
});

Hope helpful.
Refer to: Regular expression to match DNS hostname or IP Address?

A: /*
    validIpAddressRegex = "^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$";
    validHostnameRegex = "^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$";
*/
$.validator.addMethod('ipChecking', function(value) {
    //var ip = "^(?:(?:25[0-5]2[0-4][0-9][01]?[0-9][0-9]?)\.){3}" +"(?:25[0-5]2[0-4][0-9][01]?[0-9][0-9]?)$";
    validIpAddressRegex = "^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$";
    ipCheckFlag = true;
    ipLists = value.split(',');
    for(ip=0; ip<ipLists.length; ip++){
        if(!ipLists[ip].trim().match(validIpAddressRegex)){
            ipCheckFlag = false;
        }
    }
    return ipCheckFlag;
});

link

A: Addition to answer by @RAVI MONE for IP address with subnet mask:
$.validator.addMethod('IP4Checker', function(value) {
    var ip="^$|([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
      "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
      "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
      "([01]?\\d\\d?|2[0-4]\\d|25[0-5])((/([01]?\\d\\d?|2[0-4]\\d|25[0-5]))?)$";
    return value.match(ip);
}, 'Invalid IP address.');

A: This function returns true if IP address is in correct format otherwise it returns false:
function isIpAddressValid(ipAddress) {
    if (ipAddress == null || ipAddress == "")
        return false;
    var ip = '^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}' +
        '(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$';
    if (ipAddress.match(ip) != null)
        return true;
}


text:
Q: Linux shell use disown on serial calculations I have two scripts: script1.sh and script2.sh and I want to disown each of them (for external reasons I cannot use nohup here). How can I run one after the other?
I tried:
script1.sh & disown ; script2.sh & disown

but then both scripts are executed when I press Enter... Adding brackets does not solve the problem.
Thank you for your help.

A: You can just do a "shell escape":
( { script1.sh; script2.sh; } </dev/null &>/dev/null &)

Now your scripts are disconnected from the controlling terminal and owned by init.
In plain sh you may need to replace &>/dev/null with >/dev/null 2>&1.


text: Q: Is there a CLI command to show if packages need to be updated When you login, you are shown "X packages can be updated, Y are security updates," Is there a terminal command that will give this message on demand?


text:
Q: How to rip dvd and arrange files I'm ripping a dvd with dvd shrink. There are lots of anime episodes on it. And when I open those .vob files it seems that the episodes are not arranged in one .vob file. Because 1 .vob file has multiple episodes but they are not arranged as ep 1, ep 2, ep 3, etc. Is it possible to edit those files so that the episodes would be arranged

A: There are different alternatives to achieve what you want to do. This guide explains how to convert DVD episodes to AVI XviD or MP4 H264 with subtitles. It includes required tools (you have freeware option), preparation and explanation with screenies of the process.
As an alternative, this guide also tells about how to easily convert a DVD with episodes to multiple DivX/XviD files.
I hope this helps.


text:
Q: How can I pass a a modified Command value to the Help() function of Cobra? I'd like to be able to take the Long value of a Command from Cobra and modify it before it's returned to the user when [program] [command] --help is called.
While there's ample documentation, Cobra lacks examples to illustrate ways of modifying what's returned from the Help() function. As an exmaple, I'd like to include markdown within the Long value:
// other values
Long:    `This [feature](https://www.google.com) blah, blah blah.`

And then use a custom parser - which I've already written - that removes the markdown before returning the string to the user:
// other help information

This feature blah, blah blah.

Essentially: can someone provide an example of a function I can pass to SetHelpFunc() that will permit me to change this value?


text:
Q: Is "wherever", or even "where", OK in this sentence to take place of "anywhere" as a clause introducer?
In this case, the bus was crowded and some white people needed a seat. So the driver asked Rosa Parks to give up her seat. But she refused. She was tired after a long day working as a seamstress (sewer) in a department store and she felt she should have the right to sit anywhere she wanted. So she told the drive "no."

Is "wherever", or even "where", OK in this sentence to take place of "anywhere"?
I think it's a quite subtle language question, and it might take a lot of complicated effort to clarify, but I do need help on using "wherever","anywhere" and "where",especially when they are used to introduce clauses.

A: All are ok (anywhere, wherever, where). They all have essentially the same meaning in this sentence.

A:
She was tired after a long day working as a seamstress (sewer) in a department store and she felt she should have the right to sit anywhere she wanted.

Anywhere is a locative preposition. It has the meaning in any location. It is not a relative word like that, which or where or wherever. The original sentence could just finish with anywhere:

*

*She was tired after a long day working as a seamstress (sewer) in a department store and she felt she should have the right to sit anywhere.

The writer in the original example decided to use a relative clause to change the meaning of anywhere in the sentence. The original example doesn't use the relative word that:

*

*she should have the right to sit anywhere (that) she wanted.

Here we don't need to use the word that because there is a subject, she, in the relative clause. In this relative clause the word wanted is 'standing in' for missing words. We understand that wanted means "wanted to sit" in this sentence. If wanted wasn't standing in here, the sentence would read like this:

*

*she should have the right to sit anywhere (that) she wanted to sit.

There is a gap at the end of this sentence where the preposition is missing. We understand that it means:

*

*she should have the right to sit anywhere that she wanted to sit  there .

The word anywhere is the antecedent for this relative clause. We understand that the clause is giving us more information about the word anywhere. Notice that the word anywhere is not part of the relative clause. It comes before the clause:

*

*she should have the right to sit anywhere [that she wanted to sit ___ ]

The locative prepositions where and wherever are different. They function as relative words. In the Original Poster's alternative sentence they take part in a fused relative construction:

*

*she should have the right to sit [where she wanted].

The verb SIT usually takes a locative complement. Locative complements usually begin with a preposition, or preposition phrase: sit up, sit down, sit here, sit on the sofa. In the fused relative example, there is no antecedent for the relative clause. The whole clause is a locative complement for the verb SIT. There is no other word that the fused relative clause describes.
This relative clause would have a gap in it, if wanted didn't 'stand in' for missing words. This gap represents the preposition where. We understand the sentence like this:

*

*she should have the right to sit [where she wanted to sit  there].

The preposition wherever works in exactly the same way. Wherever emphasises that there is no limit to where Rosa Parks should be able to sit, if she wants to. But the meaning of the sentence is the same.
The fused relative clause version of the sentence has very different grammar from the anywhere version. In the fused relative, the word where is the antecedent for the gap but it is part of the relative clause. There is no other word which is the antecedent for where. This means that the clause with where is not changing the meaning of another word. The word anywhere is very different. It cannot function as the relative word in a relative clause. It can only be an antecedent for a relative word or relative clause.
Hope this is helpful!


text:
Q: Detecting outliers using correlogram If there is an outlier in a time series, how does its correlogram behave? Is it possible to find outliers using a correlogram?
EDIT
I have such a Time series:
ts <- c(1,2,3,1,2,2,30,40,3,2,4,1,3,2,3,1,1,2)

its correlogram looks like this:

I have an outlier in my time series, Is it possible to detect these outlier from correlogram?

A: Depends on the details, but in general think of each autocorrelation as close to the correlation of a series and itself lagged. An outlier adds two points to the corresponding scatter plot, as the outlier appears first as itself and second as a previous value. The net result will often be difficult to detect. I wouldn't expect a correlogram to be a useful way to detect outliers, certainly not compared with the usual plot of a series versus time.
EDIT It's difficult to know how seriously to take your example, but it does underline the point that outliers are more obvious on a time plot than in a correlogram.

A: Outliers affect the covariance and the variance. The acf is the ratio between the covariance and the variance. Since the variance is inflated, the acf is dampened by the outliers. Effectively, the true acf is masked by the outliers. This is why simple model identification schemes are just too simple.


text:
Q: infinity sending requst in POSTMAN Node.js So i would like to register user at the server and to add info to db, but postman return infinity request. And i don't know how to fix it. When running at browser localhost:5000 it shows me message "Cannot GET /" so i don't know what is it related to
here is my server
const mongoose = require("mongoose");
const authRouter = require("./routes/auth.routes");
const config = require("config");

const app = express();
const PORT = config.get("serverPort");

app.use(express.json());
app.use("/api/auth", authRouter);

const start = async () => {
  try {
    await mongoose.connect(config.get("dbUrl"), {
      useNewUrlParser: true,
      useUnifiedTopology: true,
      useCreateIndex: true,
    });
    app.listen(PORT, () => {
      console.log(`Server run on ${PORT}`);
    });
  } catch (e) {}
};

start();

///here is my route
const { Router } = require("express");
const User = require("../models/User");
const bcrypt = require("bcryptjs");
const { check, validationResult } = require("express-validator");
const router = new Router();

router.post(
  "/reg",
  [
    check("email", "Uncorrect email").isEmail,
    check("password", "Try one more time").isLength({ min: 3, max: 12 }),
  ],
  async (req, res) => {
    // console.log(req.body);
    try {
      const errors = validationResult(req);
      if (!errors.isEmpty()) {
        return res.status(400).json({ message: "Uncorrect request", errors });
      }

      const { email, password } = req.body;

      const candidate = await User.findOne({ email });
      if (candidate) {
        return res
          .status(400)
          .json({ message: `User with ${email} already exist` });
      }

      const hashPassword = await bcrypt.hash(password, 15);
      const user = new User({ email, password: hashPassword });
      await user.save();
      return res.json({ message: "user was created" });
    } catch (e) {
      console.log(e);
      res.send({ message: "Warning" });
    }
  }
);

module.exports = router;

port = 5000
here photo how i send request


text:
Q: AWS custom TCP port access for ejabberd in ubuntu Linux? I want to access the custom TCP port on aws ubuntu ejabberd. Eajjb erd installation is perfectly working when accessed via wget on the terminal of the system. But not able to access via the browser. All the access rule for inbound traffic have been set in the aws security group. I'm not able to figure out the problem that why the interface is not avalilable on browser.
--2015-10-03 07:02:00--  http://iglimped.com:5280/admin/

Resolving iglimped.com (iglimped.com)... 52.74.228.147
Connecting to iglimped.com (iglimped.com)|52.74.228.147|:5280... connected.
HTTP request sent, awaiting response... 401 Unauthorized

A: It seems you are actually putting incorrect login and password credentials on the admin interface.


text:
Q: Why `return()` & `onsubmit()` do not work while creating a login form to welcome page in html While creating login form to welcome page in HTML, CSS, js the problem faced is the return statement is not working.
create code for HTML inbuilt javascript.

<!DOCTYPE html>

<title>LOGIN FORM</title>
 <link rel="stylesheet" type="text/css" href="style.css">

Login Here

  <form action="loginbox.html" method="post" onsubmit="return validate()">

user name

   <input type="text" name="" placeholder="Enter User name" id="user name">

password

   <input type="password" name="" placeholder="Enter password" id="password">

            <input type="submit" name="" value="login">

   Lost your pasword??

   don't have an account??
  </form>

Using return false statement it should stop entering into welcome page, but in this code it's not working, it goes to next page.
Tried that onsubmit="return false; validate();" while using this code entire block gets stop & won't enter to welcome page.

A: You are using spaces in your id attribute which is incorrect, the id attribute must not have anykind of spaces. Plus, you are missing id="submit" on the submit button. In your code the JS is unable to execute this line
            document.getElementById("submit").disabled = true;

Because the submit button doesn't have any ID.
 Below has the errors fixed. This should work
<!DOCTYPE html>

<title>LOGIN FORM</title>
    <link rel="stylesheet" type="text/css" href="style.css">

Login Here

        <form action="loginbox.html" method="post" onsubmit="return validate()">

user name

            <input type="text" name="" placeholder="Enter User name" id="username">

password

            <input type="password" name="" placeholder="Enter password" id="password">

            <input type="submit" name="" value="login" id="submit">

            Lost your pasword??

            don't have an account??
        </form>

A: The problem was that id was missing in submit, you have to declare id in the input that has type submit. Secondly, the logic was incorrect when you validate the form, return statement was missing in the else part when the attempt was not equal to zero.

<!DOCTYPE html>

  <title>LOGIN FORM</title>
  <link rel="stylesheet" type="text/css" href="style.css">

Login Here

    <form action="/loginbox.html" name="myForm"  onsubmit="return validateForm()">

user name

        <input type="text" name="userName" placeholder="Enter User name" id="username">

password

        <input type="password" name="password" placeholder="Enter password" id="password">

      <input type="submit" id="submit" value="login">

      Lost your pasword??

      don't have an account??
    </form>


text:
Q: XCode Project: should we put source code in separate folders for meaningful purpose I'm a Java developer, and a new comer to ios development. In learning phrase, I try to download some sample projects (include from small one to medium one) for reading how often they do work in an ios project. As I see, often, they put all source file into one folder (include header file, source file, .storyboard file, xib file ...) and I see this will make your project become messy.
So, I come here to ask a question that. Should we put source code in separate folders base on their usage, to make project less messy, right ? For example, all custom core data model class files should put into Model folder. All View file (such as .storyboard, .xib file ...) should put into View folder. All Controller file should put into Controller folder ...
If you often do this, please tell me your experience, how you folder your code ? And does XCode support virtual folders (that in XCode IDE you see source code in folders, but in hard drive, they're just same).
Thanks :)

A: Xcode differs from Eclipse and Android Studio in maintaining a separate project-level division of resources into folders that need have no correlation whatsoever to the file system. Given that the lack of namespaces usually leads people to be very relaxed about what formally is and is not a 'package', it's a real wild west out there.
I tend to keep things organised by mental package — model, view, controller at the top level, e.g. maybe web services, persistent store under model, etc. But even then command+shift+O and type a symbol or class name is by far the easiest way to navigate a project.
Others might argue that keeping things flat is better because then you don't have to keep the file system layout in sync manually and open-by-symbol plus the class browser obviate the need for stringent organisation, presenting a hierarchical relationship without the need to get either the disk or the workspace into agreement.

A: You first have to make the difference between folders and groups. Folders are used to organize contents on your filesystem whereas groups are used to organize contents within your Xcode project. You can think of groups as virtual folders. I personally prefer to keep a flat structure on the filesystem and organize everything using groups. This way is slightly more straight forward to include header files and it doesn't force you to maintain both the filesystem structure and the xcode structure.

A: Folders makes your code and its management easily, like we have packages in Java that we use to accumulate some common classes and its supporting class files.
In the same way we can use folders to manage our classes in XCode.
However its not necessary, varies from developer to developer as well as the complexity of code.
Happy Coding. :)

A: In you Project you ca do any GROUPS you want to make simple and clean your project, like my screen:

Is easy and simple and you have two ways:
1) in your project right click in to right column then select  NewGroup

2) drag and drop your folder in to a column to create a folder reference:

this only if you want integrate in your project a root with inside files PHP, HTML, ASP and more, but attention because after you distribute your app, if a people open .app file they found inside your REFERENCE FOLDER with all your clear code.
I think this is it ;)

A: The approach you are discussing about is correct.

As far as folder in code is considered. If you create folder within Xcode and dividing the codes based on folders. Than all the classes will exist together on hard disk. But if you create folders within the project using finder and than adding the folder than codes will be saved to their respective folders.
Hope it will help you. Happy coding :)


text:
Q: How to retrieve Firebase pushed key? I have an event I'm storing in my database. It is stored as
events
   my_party123
     info
       -KZbdiR_PBrAwxYvUR4U
         name: 'John'
         city: 'Los Angeles'
   my_party124
      ...

However, I'm trying to retrieve this info and I can't quite get it.
I tried
ref
  .child('events')
  .child('my_party123') // I also tried .push('my_party123')
  .once('value')
  .then(snapshot => {
    console.log(snapshot.key) // my_party123
    console.log(snapshot.val().info)
    // this shows object with
    // "-KZbdiR_PBrAwxYvUR4U" property, this is the pushed key property
    im trying to access
   })

.pushed is creating new keys when i called it - how do i just access the value stored in my database?

A: If you're looking to have unique event URLs that point at events, I'd recommend a change to your data structure to be something more like:
events
  -KZ123PUSHID
    name: 'John'
    location: 'Los Angeles'
  -KZ124PUSHID
    name: 'Morgan'
    location: 'New York City'
eventNames
  my_party_123: '-KZ123PUSHID'
  sweet_nyc_part: '-KZ124PUSHID'

Then, in your code, you could do something like:
var eventNamesRef = firebase.database().ref('eventNames');
var eventsRef = firebase.database().ref('events');

var event;
eventNamesRef.child(nameFromUrl).once('value').then(nameSnap => {
  eventsRef.child(nameSnap.val()).on('value', eventSnap => {
    event = eventSnap.val();
  });
});


text:
Q: Using Camel Bindy in Has-A relationship Hi I have a problem with exporting java Object to CSV file in Camel. Suppose if i have a java object namely Student,
@CsvRecord(separator=",")
public class Student {
    @DataField(pos=1)
    private String name;
    @DataField(pos=2)
    private String college;

    // getters and setters
}

I will export this object into a csv file using below code in camel route,
.marshal(new BindyCsvDataFormat(camel.demo.Book.class))
.to("file:data/destination?fileName=book.csv")

But what if i have a one more entity Object named Address in Student object. And i want to print particular values of Address along with remaing student details in my csv.
@CsvRecord(separator=",")
public class Student {
    @DataField(pos=1)
    private String name;
    @DataField(pos=2)
    private String college;

    private Address address;

    // getters and setters
}

public class Address {
    private int houseNo;
    private String street;
    private String city;

    //getters and setters
}

NOw i want to save Student details (name,college) and only (city) from Address in csv. Can someone please help me to achieve this. Thank you for your help.

A: Use the @Link annotation as described here:
@CsvRecord(separator=",")
public class Student {
    @DataField(pos=1)
    private String name;

    @DataField(pos=2)
    private String college;

    @Link
    private Address address;
...
}

And for the class Address:
@Link
public class Address {
...
}


text:
Q: Python search through a text file using a Dataframe column I have a very large text file (11 million+ records), ";" delimited, three columns.  I have a Pandas dataframe (single column) with the values that I need to search through the text file.
The problem is that I am not able to load the large text file into memory.
I have nested for loops and that is taking a very long time.  Searching for each column value within each line of the text file.  This is what I have:
import os
import pandas as pd

os.chdir('D:\\AllFiles\\Projects')
mainPath = os.getcwd()

inputFile = 'A.txt'
inputPath = os.path.join(mainPath, inputFile)
input_data = open(inputPath, 'r')

outputFile = 'A_A.csv'
outputPath = os.path.join(mainPath, outputFile)
output_data = open(outputPath,'w')

#  input file name and location
actFile = 'SingleColList.txt'
actPath = os.path.join(mainPath, actFile)

#   Read the cleaned data in a dataframe
act_df = pd.read_csv(actPath,header=0)

with input_data as f:
    for num, line in enumerate(f, 1):
        for index, row in act_df.iterrows():
            if row['col1'] in line:
                output_data.write( line )

input_data.close()
output_data.close()

print('Done!')

Is there something faster that I can use?

A: Here are some examples that might help
Set up a simple file called 'A.txt' as
a;b;c
cat;dog;mouse
mouse;moose;mice
apple;pie;good
no;its;not
what;is;this
three;word;sentences
great;good;best
stop;doing;this
or;doing;that

Create a search word list
mylist = ['ca', 'why', 'help', 'cat', 'is', 'three', 'best']

Option 1: read file and parse; then search by column. Don't think this is a good option, but shown for comparison purposes.
In [33]: df = pd.read_csv('A.txt', sep=';')
    ...: df[df['a'].str.contains('|'.join(mylist), regex=True)]
Out[33]:
       a     b          c
0    cat   dog      mouse
5  three  word  sentences

Option 2: read file, don't parse so it searches entire row
In [34]: df = pd.read_csv('A.txt', header=0)
    ...: df[df['a;b;c'].str.contains('|'.join(mylist), regex=True)]
Out[34]:
                  a;b;c
0         cat;dog;mouse
4          what;is;this
5  three;word;sentences
6       great;good;best
7       stop;doing;this

Option 3: use chunksize and use option 1 or 2 or whatever you need during each iteration
In [35]: iterator = pd.read_csv('A.txt', header=0, chunksize=2)
    ...: for i in iterator:
    ...:     print(i)
    ...:
              a;b;c
0     cat;dog;mouse
1  mouse;moose;mice
            a;b;c
2  apple;pie;good
3      no;its;not
                  a;b;c
4          what;is;this
5  three;word;sentences
             a;b;c
6  great;good;best
7  stop;doing;this
           a;b;c
8  or;doing;that


text:
Q: DataGridViewCheckBoxColumn Checked Tengo un check en el DataGridView, queria saber si es posible que cada vez que se agregue un valor automáticamente aparezca como checked

A: Puede hacerse, claro. Primero, podrías controlar cada vez que se añade un nuevo row al DataGridView manejando el evento RowsAdded y ahí establecer el valor de la celda del tipo DataGridViewCheckBoxColumn de esta forma:
private void dataGridView1_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
{
    // e.RowIndex proporciona el índice de la fila que se acaba de añadir
    dataGridView1.Rows[e.RowIndex].Cells["NombreDeTuCeldaCheckBox"].Value = true;
}

Pero ojo, si tu DataGridView tuviera datos previos, antes guardaría la cantidad de registros existentes en una variable y comprobaría que el nuevo índice fuera superior a esa cantidad, o de otra forma marcarías todos los CheckBox.


text:
Q: Using Javascript, how can I show a  on top of another  on hover, hiding the second ? JSFiddle: http://jsfiddle.net/9u8tnh97/
I'm using jQuery and Bootstrap. I have a table with 4
 elements like this:

      First Name
      Last Name

      Mark
      Otto

          Some link1

      Larry
      the Bird

          Some link2

And this is my Javascript:
$('table tbody tr').hover(function() {
    if($(this).hasClass('hover-data')){
        $(this).next().show();
        $(this).hide();
    } else {
        $(this).prev().show();
        $(this).hide();
    }
});

At first, I'm hiding the two rows with class table-hover by giving them a hide class and I'm only showing the ones with class table-data.
What I want to achieve: When I hover a tr with class table-data, I want the next and immediate tr with class table-hover to show and the "hovered tr" to hide.
When I move the mouse outside again I want everything to be restored and only see the tr with class hover-data
Not sure why my code won't work. Any ideas?

A: This one uses mouseenter on the original rows and mouseleave on the new rows.
$('table tbody').on('mouseenter', 'tr.hover-data', function () {
    $(this).next().show();
    $(this).hide();
}).on('mouseleave', 'tr.hover-link', function () {
    $(this).prev().show();).hide();
});

JSFiddle: http://jsfiddle.net/TrueBlueAussie/9u8tnh97/15/
I noticed that the bootstrap hide class is a little too "strong" and overrides show() so I also changed those to style="display: none" for now. Instead use your own class e.g. hideme in the following example: http://jsfiddle.net/TrueBlueAussie/9u8tnh97/17/
I am using delegated events (out of habit, and so they can share a common selector), but two separate "normal" (static) selectors will likely work just fine too. e.g. http://jsfiddle.net/TrueBlueAussie/9u8tnh97/16/

A: Like this:
$('table tbody tr').hover(function() {
    if($(this).hasClass('hover-data')){
        $(this).next().toggleClass('hidden');
    }
});

https://jsfiddle.net/gqyrpnes/


text:
Q: Close two form by one click? I'm working on project with sign in feature
When I run the project there is a form (form1) run the sign in .
after i click on login button build another form (form2) - It's the form of my program .
and made the first form (form1) hide .
The problem is when I press at the X button in form2 it's close but the form1 it's still running .
I tried to close the form1 instead of hide ... but this will close form2 before launching
In form1:
this.Hide();
Form2 x = new Form2();
x.Show();

A: I think you have your forms around the wrong way.
Form1 sould be your app and shold show Form2 as a dialog when it first loads, then when it closes you can process the result and decide wether to continue or close the application.
Something like:
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        Load += new EventHandler(Form1_Load);
    }

    void Form1_Load(object sender, EventArgs e)
    {
        Form2 myDialog = new Form2();
        if (myDialog.ShowDialog() == System.Windows.Forms.DialogResult.Cancel)
        {
            // failed login
            // exit application
        }
        // all good, continue
    }
}

A: You could subscribe to the child forms FormClosed event and use that to call Close on the parent form.
x.FormClosed += new FormClosedEventHandler(x_FormClosed);

void x_FormClosed(object sender, FormClosedEventArgs e)
{
    this.Close();
}

A: try this, in the log in button if access is granted
private void logInBtn_Click(object sender, EventArgs e)
        {
            Form2 frm = new Form2();
            frm.ShowDialog();
            this.Hide();
        }

then in form2 if you want to exit
private void exitBtn_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

hope this helps.

A: You go to your form2 then in the event of the form look for FormClosed.
Put this code in your eventhandler:
private void Form2_FormClosed(object sender, FormClosedEventArgs e)
    {
        Application.Exit();
    }

FormClosed is the event whenever the user closes the form. So when you close the form put a code that will exit your application that is -applicationn.exit();-
Hope this will work.


text:
Q: Understanding proof of continuity of partial derivative I have trouble understanding the general concept of how to prove the continuity of the partial derivative (I will here use the continuity definition via limits of sequences). May be someone can give me a quick feedback on my thoughts:
If I take the partial derivative of a function $f$ two things might happen:
1.) The function is simply a compostion of differentiable functions and not piece-wise defined, say $f:\mathbb{R}^2 \to \mathbb{R}$, $f{x \choose y}=x^2+xy^2$. So applying the rules of differentiation yields the partial derivative w.r.t $x$: $D_xf=2x+y^2$. If I check for continuity I plug in an arbitrary point ${x \choose y}$ into $D_xf{x \choose y}$ and afterwards I check if for any convergent sequence $lim_{n \to \infty}{x_n \choose y_n}= {x \choose y}$ it holds $D_xf{x \choose y}=lim_{n \to \infty}D_xf{x_n \choose y_n}$. Or I simply argue that $2x+y^2$ is a composition of continuous functions which also is continuous. This, I would regard as the "standard" case.
2.) However, I get confused when the function $f$ is piece-wise defined, as this almost always means that there are boundary points, say ${1 \choose 1}$, were you cannot simply apply the rules of differentiation but must check the limit. Let's assume a continuous function $g:\mathbb{R}^2 \to \mathbb{R}$,
$$g{x \choose y}=\left\{\begin{array}{ll} x^2+xy^2, & {x \choose y} \neq {1 \choose 1} \\
         2, & {x \choose y} = {1 \choose 1}\end{array},\right.  $$
Let the partial w.r.t. $x$ at ${1 \choose 1}$ be: $D_xg{1 \choose 1}= lim_{x\to 1} \frac{x^2+x1^2-2}{x-1}= 3$. Applying the rules of differentiation yields the partial for all other points except ${1 \choose 1}$ is: $D_xg{x \choose y}=2x+y^2$.
If I now want to check for continuity of the partial at point ${1 \choose 1}$ then for any convergent sequence $lim_{n \to \infty}{x_n \choose y_n}= {1 \choose 1}$ which I plug in into $D_xg{x \choose y}=2x+y^2$ it must hold $D_xg{1 \choose 1}=3=lim_{n \to \infty}D_xg{x_n \choose y_n}= lim_{n \to \infty} (2x_n+y_n^2)$.
I hope this is not too wordy but I would appreciate if someone could tell me if my thoughts on that topic are correct.


text:
Q: Powershell: Configure a static IP on an unplugged NIC I'm trying to find a way to configure a permanent static IP on Windows 10 IOT devices with their Nic unplugged. I have a script that needs to be run on the devices before they're in place and part of it is configuring the NICs. When I use the following:
New-NetIpAddress -InterfaceIndex 10 -IpAddress 192.168.9.10 -PrefixLength 24 -DefaultGateway 192.168.9.1 -AddressFamily IPv4
I get an error
New-NetIpAddress : Inconsistent parameters PolicyStore PersistentStore and Dhcp Enabled
I attempted to explictly turn off DHCP with Set-NetIPInterface  -InterfaceIndex 10 -Dhcp Disabled before ussing the New-NetIpAddress command but I get the same error.
Any suggestions?

A: You need to remove the existing DHCP IP address already assigned to the adapter.  You should also set the DNS server for the interface.  I provided an example below, but replace the xxx.xxx.xxx.xxx with your DNS Server IP Address.
You'll need to disable DHCP in the registry for this interface in the PersistentStore before you can set the IP address.
Set-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\services\Tcpip\Parameters\Interfaces\$((Get-NetAdapter -InterfaceIndex 10).InterfaceGuid)" -Name EnableDHCP -Value 0
Remove-NetIpAddress -InterfaceIndex 10 -AddressFamily IPv4
Remove-NetRoute -InterfaceIndex 10 -AddressFamily IPv4 -Confirm:$false
New-NetIpAddress -InterfaceIndex 10 -IpAddress 192.168.9.10 -PrefixLength 24 -DefaultGateway 192.168.9.1 -AddressFamily IPv4
Set-DnsClientServerAddress -InterfaceIndex 10 -ServerAddresses "xxx.xxx.xxx.xxx"

This website has a good example and explanation of the process: https://www.pdq.com/blog/using-powershell-to-set-static-and-dhcp-ip-addresses-part-1/
This website talks about the same problem you're having and their solution: http://www.darrylvanderpeijl.com/inconsistent-parameters-policystore-persistentstore-and-dhcp-enabled/

A: I had issues on windows 10 1909 with all code I found, it seemed inconsistent. The below code works for me, choose netsh or powershell exclusive code:
$IP = $builddata.templateIP
$SubnetMaskBits = $builddata.Subnetmaskbits
$SubnetMask = $builddata.Subnetmask
$Gateway = $builddata.gateway
$Dns = $builddata.DNS1,$builddata.DNS2

$IPType = "IPv4"
$adapter = Get-NetAdapter | Where-Object {$_.InterfaceDescription -like "vmx*"} #looking for vmxnet3

# you can use either at this point
# via netsh

netsh interface ipv4 set interface $adapter.InterfaceIndex dadtransmits=0 store=persistent
netsh interface ip set address name="$($adapter.name)" static $IP $SubnetMask $Gateway 1

# via PowerShell

$adapter | Get-NetIPInterface | ? {$_.addressfamily -eq  $IPType} | % {Get-NetIPAddress | Remove-NetIPAddress -Confirm:$false}
$adapter | Get-NetIPInterface | New-NetIPAddress `
     -AddressFamily $IPType `
     -IPAddress $IP `
     -PrefixLength $SubnetMaskBits `
     -DefaultGateway $Gateway -Confirm:$false


text:
Q: R Shiny "ERROR: Text to be written must be a length-one character vector" I'm trying to help a friend debug their first attempt at a basic shiny app.  There are some things I know are not ideal about this code (spelling at a minimum) but I don't see why it should throw the subject error...
ui.R is
library(magrittr)
library(dplyr)
library(tidyr)

olympic <- read.csv("olympic_games.csv", header = TRUE)

shinyServer(fluidPage(
  titlePanel("Olympic games medals from 2002 - 2012"),

  country <- levels(olympic$Country),

  total_medal <- unique(olympic$Total.Medal),

  sidebarLayout(
    sidebarPanel(
      helpText("Choose the contry to know how many medals they have"),

      selectInput("Country",
                  label = "chose country",
                  choices = country,
                  selected = country[1]),

      selectInput("country1",
                  label = "chose country",
                  choices = country,
                  selected=country[2]),
      br(),
      radioButtons("color", "Select the colour of histogram if you like?",
                   choices=c("green","red","yellow"), selected= "green")
    ),
    mainPanel(
      plotOutput("Olympic_games")
    )
  ))
)

and server.r
library(magrittr)
library(dplyr)
library(tidyr)
library(ggplot2)

shinyServer(
  function(input,output,session){
    olympic <- read.csv("olympic_games.csv", header = TRUE)
    output$Olympic_games <- renderPlot({

      olympic1 <- subset(olympic,Country==input$Country)
      olympic2 <- subset(olympic,Country==input$country1)
      col <- input$color
      frames <- rbind(olympic1,olympic2)
      ggplot(frames, aes(Total.Medals))+
        geom_histogram(aes(Total.Medals,fill=Country),color=col) + facet_grid(Country~Total.Medals)
    }
    )
  }
)

When the olympic_games.csv file is read the data look like
head(olympic)
           Athlete Age       Country Year Closing.Ceremony.Date      Sport Gold.Medals Silver.Medals
1   Michael Phelps  23 United States 2008             8/24/2008   Swimming           8             0
2   Michael Phelps  19 United States 2004             8/29/2004   Swimming           6             0
3   Michael Phelps  27 United States 2012             8/12/2012   Swimming           4             2
4 Natalie Coughlin  25 United States 2008             8/24/2008   Swimming           1             2
5    Aleksey Nemov  24        Russia 2000             10/1/2000 Gymnastics           2             1
6    Alicia Coutts  24     Australia 2012             8/12/2012   Swimming           1             3
  Bronze.Medals Total.Medals
1             0            8
2             2            8
3             0            6
4             3            6
5             3            6
6             1            5

I've found reference to this error occuring when you try to pass two character strings to a shiny UI function that only expects one, but I don't see anywhere here where that could be happening.


text:
Q: Second order ODE with initial condition How can I solve the following second order differential equation
$$ \frac{d^2\theta \:}{dt^2\:}\:=-\frac{g\theta \:\:}{L} $$ with initial conditions $$θ(0) = θ_0 , v(0) = v_0  $$
I know that I can rewrite the equation as
$$ \frac{d^2\theta \:}{dt^2\:}\:+\frac{g\theta \:\:}{L} = 0 $$
, find characteristic polynomial and solve the equation. I am just confused on how to solve this problem because of all the constants.
Thanks for help in advance

A: $$\frac{d^2\theta \:}{dt^2\:}\:+\frac{g\theta \:\:}{L} = 0$$
Characteristic polynomial is
$$r^2+\frac g L=0 \implies r=\pm i \sqrt {\frac gl}$$
Then the solution is
$$\theta(t)=c_1\cos(\sqrt {\frac gl}t)+c_2\sin(\sqrt{\frac gl}t)$$
Apply initial conditions now
$$θ(0) = θ_0 ,\implies \theta(0)=c_1   \implies c_1=\theta_0$$
$$\theta(t)=\theta_0\cos(\sqrt{\frac gl}t)+c_2\sin(\sqrt{\frac gl}t)$$
Differentiate
$$\theta(t)'=\sqrt{\frac gl} \left(-\theta_0\sin(\sqrt{\frac gl}t)+c_2\cos(\sqrt{\frac gl}t) \right )$$
Apply the second inditial condition to find $c_2$
$$\theta(0)'=\sqrt{\frac gl} c_2 \implies c_2=v_0\sqrt{\frac lg}$$
Finally
$$\theta(t)=\theta_0\cos \left(\sqrt{\frac gl}t \right)+v_0\sqrt{\frac lg}\sin \left (\sqrt{\frac gl}t \right)$$