text:
Q: How to programmatically change delivery date on Bigcommerce Order I'm using ajax to add a Saturday delivery surcharge on my bigcommerce site. Basically, I'm adding the surcharge as another product when a Sat delivery date is clicked:
$.ajax({type:"GET", url:"http://www.url.com/cart.php?action=add&product_id=138", success: function(text)

The problem we noticed is that this method changed the delivery date of the entire order to the current date. The product itself doesn't have its own delivery date.
I tried to rectify this by adding "delivery_date" and "deliveryDate" (from the xml product export) to the ajax call, but it resulted in nothing.
Here's an example order export:
<orders>
    <order>
        <Order_ID><![CDATA[358]]></Order_ID>
        <Customer_ID><![CDATA[0]]></Customer_ID>
        <Customer_Name><![CDATA[]]></Customer_Name>
        <Customer_Email><![CDATA[]]></Customer_Email>
        <Customer_Phone><![CDATA[]]></Customer_Phone>
        <Order_Date><![CDATA[11/05/2016]]></Order_Date>
        <Order_Status><![CDATA[Awaiting Payment]]></Order_Status>
        <Subtotal_inc_tax><![CDATA[140.00]]></Subtotal_inc_tax>
        <Subtotal_ex_tax><![CDATA[140.00]]></Subtotal_ex_tax>
        <Tax_Total><![CDATA[0.00]]></Tax_Total>
        <Shipping_Cost_inc_tax><![CDATA[0.00]]></Shipping_Cost_inc_tax>
        <Shipping_Cost_ex_tax><![CDATA[0.00]]></Shipping_Cost_ex_tax>
        <Ship_Method><![CDATA[Free Shipping]]></Ship_Method>
        <Handling_Cost_inc_tax><![CDATA[0.0000]]></Handling_Cost_inc_tax>
        <Handling_Cost_ex_tax><![CDATA[0.0000]]></Handling_Cost_ex_tax>
        <Order_Total_inc_tax><![CDATA[140.00]]></Order_Total_inc_tax>
        <Order_Total_ex_tax><![CDATA[140.00]]></Order_Total_ex_tax>
        <Payment_Method><![CDATA[Pay in Store]]></Payment_Method>
        <Total_Quantity><![CDATA[2]]></Total_Quantity>
        <Total_Shipped><![CDATA[0]]></Total_Shipped>
        <Date_Shipped><![CDATA[]]></Date_Shipped>
        <Order_Currency_Code><![CDATA[USD]]></Order_Currency_Code>
        <Exchange_Rate><![CDATA[1.0000000000]]></Exchange_Rate>
        <Order_Notes><![CDATA[]]></Order_Notes>
        <Customer_Message><![CDATA[]]></Customer_Message>
        <Billing_First_Name><![CDATA[f]]></Billing_First_Name>
        <Billing_Last_Name><![CDATA[f]]></Billing_Last_Name>
        <Billing_Company><![CDATA[ Traveler]]></Billing_Company>
        <Billing_Street_1><![CDATA[That Road]]></Billing_Street_1>
        <Billing_Street_2><![CDATA[That Road]]></Billing_Street_2>
        <Billing_Suburb><![CDATA[San Fran]]></Billing_Suburb>
        <Billing_State><![CDATA[CA]]></Billing_State>
        <Billing_Zip><![CDATA[1234567]]></Billing_Zip>
        <Billing_Country><![CDATA[United States]]></Billing_Country>
        <Billing_Phone><![CDATA[thah]]></Billing_Phone>
        <Billing_Email><![CDATA[test@gmail.com]]></Billing_Email>
        <Shipping_First_Name><![CDATA[d]]></Shipping_First_Name>
        <Shipping_Last_Name><![CDATA[d]]></Shipping_Last_Name>
        <Shipping_Company><![CDATA[Company]]></Shipping_Company>
        <Shipping_Street_1><![CDATA[That Road]]></Shipping_Street_1>
        <Shipping_Street_2><![CDATA[That Road]]></Shipping_Street_2>
        <Shipping_Suburb><![CDATA[San Frab]]></Shipping_Suburb>
        <Shipping_State><![CDATA[CA]]></Shipping_State>
        <Shipping_Zip><![CDATA[1234567]]></Shipping_Zip>
        <Shipping_Country><![CDATA[United States]]></Shipping_Country>
        <Shipping_Phone><![CDATA[]]></Shipping_Phone>
        <Shipping_Email><![CDATA[]]></Shipping_Email>
        <Product_Details>
            <item>
                <Product_ID><![CDATA[86]]></Product_ID>
                <Product_Qty><![CDATA[1]]></Product_Qty>
                <Product_SKU><![CDATA[]]></Product_SKU>
                <Product_Name><![CDATA[Lobster, Whole - Select]]></Product_Name>
                <Product_Weight><![CDATA[1.0000]]></Product_Weight>
                <Product_Variation_Details><![CDATA[Lobster, Whole - Select: 1 select lobster ($110), How do you want them prepared? Live (uncooked), Delivery Date: May 28th 2016]]></Product_Variation_Details>
                <Product_Unit_Price><![CDATA[120.00]]></Product_Unit_Price>
                <Product_Total_Price><![CDATA[120.00]]></Product_Total_Price>
            </item>
            <item>
                <Product_ID><![CDATA[138]]></Product_ID>
                <Product_Qty><![CDATA[1]]></Product_Qty>
                <Product_SKU><![CDATA[]]></Product_SKU>
                <Product_Name><![CDATA[Saturday Shipping Surcharge]]></Product_Name>
                <Product_Weight><![CDATA[0.0000]]></Product_Weight>
                <Product_Variation_Details><![CDATA[]]></Product_Variation_Details>
                <Product_Unit_Price><![CDATA[20.00]]></Product_Unit_Price>
                <Product_Total_Price><![CDATA[20.00]]></Product_Total_Price>
            </item>
        </Product_Details>
        <Store_Credit_Redeemed><![CDATA[0.00]]></Store_Credit_Redeemed>
        <Gift_Certificate_Amount_Redeemed><![CDATA[0.00]]></Gift_Certificate_Amount_Redeemed>
        <Gift_Certificate_Code><![CDATA[]]></Gift_Certificate_Code>
        <Gift_Certificate_Expiration_Date><![CDATA[]]></Gift_Certificate_Expiration_Date>
        <Coupon_Details>
        </Coupon_Details>
    </order>
</orders>

So, the question is: is there any way to programmatically add a delivery date to a product or order? Or perhaps another way to keep it from changing the delivery date from the product the person is actually ordering?


text:
Q: Non null Turing antichain This interesting question resulted from a query of Mushfeq: In ZFC, can we find a non null set of pairwise Turing incomparable reals?

A: This is a great question.
Let me get things started by showing that the answer is yes under
the continuum hypothesis. Assume CH. Let $\langle
U_\alpha\mid\alpha<\omega_1\rangle$ enumerate all the open sets
with less than full measure. I shall build an antichain $\langle
a_\alpha\mid\alpha<\omega_1\rangle$ of Turing incomparable reals,
which are not contained entirely in any $U_\alpha$. Thus, the set
$\{a_\alpha\mid\alpha<\omega_1\}$ will have full outer measure. At
any stage of the construction, we will have already specified $a_\beta$
for $\beta<\alpha$, which is countably many reals. Since
$U_\alpha$ is an open set with less than full measure, I claim
that we may find a real $a_\alpha$ that is not in $U_\alpha$ and
which is Turing incomparable with all $a_\beta$ for
$\beta<\alpha$. To see this, observe first that if we force to add
a random real $r$ not in $U_\alpha$, then $r$ will fit the bill in
the forcing extension $V[r]$, since clearly $r$ is not computable from any ground model real, and conversely I believe that no non-computable ground model real is computable from a random real. But next, observe that the existence
of such a real is a $\Sigma^1_1$ assertion, and hence it was
already true in $V$ by Shoenfield absoluteness. So we may find $a_\alpha\notin U_\alpha$ that
is incomparable with all earlier $a_\beta$. Thus, we have built
the antichain of Turing incomparable reals, which is not contained
in any open set of less than full measure. And so it is not
measure zero. QED

A: This is a $ZFC$-theorem. Actually for any $\Sigma^1_1$-locally countable partial ordering, there is a non-null antichain.
The proof is not quite simple. See my paper
http://ims.nju.edu.cn/~yuliang/lcpfinal
I feel that it might be helpful to give more details.
The idea is as following:
By Harrison's theorem, the question concerning  $\Sigma^1_1$-locally countable partial ordering can be reduced to the question about the measure of antichains of hyperarithmetic degrees. So it is sufficient to construct a non-null antichain of hyperarithmetic degree. By an application of some algorithmic randomness results due to Kucera, Miller and me, any such antichain must be nonmeasurable.
So we just need to construct a nonmeasureable antichain of hyperdegrees. By a generlaization of the results due to Miller and me, it can be proved that sufficient randomness (in the paper "sufficient randomness" means $\Delta^1_2$-randomness. Now we know that $\Pi^1_1$-randomness is sufficient after the development of higher randomness theory) is $\leq_h$-downward closed.
Now take a maximal set $X$ of reals so that any two different reals in $X$ bounds disjoint "sufficiently random" reals. If $X$ is not null, then we are done. Otherwise, by the randomness result above, the $\leq_h$-upward closure of $X$ must be null.  For each $e$, let $X_e$ be the collection of the $e$-th "sufficiently random" real hyperarithmetically below some $x\in X$ (such an $\omega$-type well ordering is "natural" for each $x$, i.e. the $e$-th hyperarithmetic reduction.) It cannot be true that for every $e$, $X_e$ is  null (Otherwise, by the randomness result and maximality of $X$, the set of "sufficiently random" reals would be null). By the property of $X$, $X_e$ is an antichain for every $e$. So there must be some $e_0$ so that $X_{e_0}$ is an antichain and non-null.
Note that even the hyperarithmetic closure of $X_{e_0}$ does not have a positive measure.
Under  $MA+\neg CH$, any locally countable partial ordering has a non-null antichain. However, under $V=L$, it fails for the $\Delta^1_2$ well-ordering $\leq_L$. I am not sure about $\Pi^1_1$-locally countable partial orderings.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Как убрать не нужную часть полученных данных из формы При отправке формы при нажатии на Enter - Добавляется новая строка которая фиксируется как
___

Форма приходит с данными:
раз два три __

Как с помощью php - удалить этот __ и записать в бд только "раз два три"?

A: $str = 'раз два три __';
$trimedStr = trim($str, "_");
echo $trimedStr;  // раз два три

trim - для удаления разных символов с начала и конца строки


text:
Q: How to use "CookieManager::removeAllCookies(ValueCallback callback)" I am a newbie to java and trying to remove the WebView cookies using the method CookieManager::removeAllCookies(ValueCallback callback). Not able to figure out what values has to be passed to the removeAllCookie method.
The docs https://developer.android.com/reference/android/webkit/ValueCallback.html and https://developer.android.com/reference/android/webkit/CookieManager.html#getInstance%28%29 does not say anything on how to use it.
My understanding is ValueCallback is similar to c++ templates. But not able to get why does an object is required to be passed to remove the cookies.

A: From the documentation:

If a ValueCallback is provided, onReceiveValue() will be called on the current thread's Looper once the operation is complete. The value provided to the callback indicates whether any cookies were removed. You can pass null as the callback if you don't need to know when the operation completes or whether any cookies were removed

So you can do this
CookieManager.getInstance().removeAllCookies(new ValueCallback<Boolean>() {
           @Override
           public void onReceiveValue(Boolean value) {
               Log.d(TAG, "onReceiveValue " + value);
           }
       });

or
CookieManager.getInstance().removeAllCookies(null);

This method is introduced in API level 21. You may have to give something like this if you are supporting older versions.
if(API Level >= 21){
     CookieManager.getInstance().removeAllCookies(null);
}else{
  CookieManager.getInstance().removeAllCookie();
}

A: You need to call it in a thread.
private class RemoveCookiesThread extends Thread {
    private final ValueCallback<Boolean> mCallback;

    public RemoveCookiesThread(ValueCallback<Boolean> callback) {
        mCallback = callback;
    }

    public void run() {
        Looper.prepare();

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            CookieManager.getInstance().removeAllCookies(mCallback);
        } else {
            CookieSyncManager cookieSyncManager = CookieSyncManager.createInstance(mApplication);
            cookieSyncManager.startSync();
            CookieManager.getInstance().removeAllCookie();
            cookieSyncManager.stopSync();
            mCallback.onReceiveValue(true);
        }

        Looper.loop();
    }
}

And then start the thread:
RemoveCookiesThread thread = new RemoveCookiesThread(callback);
thread.start();


text:
Q: Error while drawing a graph in networkx .module 'matplotlib.pyplot' has no attribute 'ishold' I want to plot a graph using networkx. But module 'matplotlib.pyplot' has no attribute 'ishold' error is coming. I have tried using the earlier versions of matplotlib but it didn't work. Yesterday, the same code was running but now it is showing this error. Please help. Im stuck.
I have tried using the earlier versions of matplotlib but it didn't work. Yesterday, the same code was running but now it is showing this error. Please help. Im stuck.
import networkx as nx
import numpy as np
import matplotlib.pyplot as plt

G = nx.Graph()
G.add_edges_from(
    [('A', 'B'), ('A', 'C'), ('D', 'B'), ('E', 'C'), ('E', 'F'),
     ('B', 'H'), ('B', 'G'), ('B', 'F'), ('C', 'G')])

val_map = {'A': 1.0,
           'D': 0.5714285714285714,
           'H': 0.0}

values = [val_map.get(node, 0.25) for node in G.nodes()]
%matplotlib inline
nx.draw_networkx(G, cmap = plt.get_cmap('jet'), node_color = values)

nx.draw(G)
plt.show()

AttributeError                            Traceback (most recent call last)
<ipython-input-13-127734f4f34b> in <module>()
     14 values = [val_map.get(node, 0.25) for node in G.nodes()]
     15 get_ipython().magic('matplotlib inline')
---> 16 nx.draw_networkx(G, cmap = plt.get_cmap('jet'), node_color = values)
     17
     18 nx.draw(G)

1 frames
/usr/local/lib/python3.6/dist-packages/networkx/drawing/nx_pylab.py in draw_networkx_edges(G, pos, edgelist, width, edge_color, style, alpha, edge_cmap, edge_vmin, edge_vmax, ax, arrows, label, **kwds)
    520         lw = width
    521
--> 522     if not cb.is_string_like(edge_color) \
    523            and cb.iterable(edge_color) \
    524            and len(edge_color) == len(edge_pos):

AttributeError: module 'matplotlib.cbook' has no attribute 'is_string_like'

A: I had the same issue, it's due to a mismatch in the versions of networkx and matplotlib. I tried uninstalling and reinstalling the packages - it worked!
sudo pip3 uninstall networkx

sudo pip3 uninstall matplotlib

python3 -mpip uninstall matplotlib

sudo conda uninstall matplotlib

If you've installed networkx via other sources like mpip or conda, uninstall via those too.
Then install both of them:
sudo pip3 install networkx

sudo pip3 install matplotlib

A: I downgraded matplotlib version to 2.2.3 and it works.
just input
pip install matplotlib==2.2.3.
hope it helps~


text:
Q: Least privileges required to put public-read objects on AWS S3? I created a new AWS IAM role, and gave it the following policy (trying to follow the principle of least privilege):
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "Stmt1493050925000",
            "Effect": "Allow",
            "Action": [
                "s3:PutObject"
            ],
            "Resource": [
                "arn:aws:s3:::avatars-bus-com-development/avatar/*"
            ]
        }
    ]
}

Using s3cmd, I attempt to upload a publicly readable file using the following command line:
s3cmd put --public-acl --access_key AKIA... --secret_key "..." \
  spec/fixtures/avatars/large-avatar.jpg \
  s3://avatars-bus-com-development/avatar/00-55/inbb7ljt-2017-02-17-09-00-55/original.jpg

When I do that, I receive an Access Denied error from S3.
Using the AWS CLI tools, I also get an AccessDenied error:
$ AWS_ACCESS_KEY_ID="AKIA..." AWS_SECRET_ACCESS_KEY="..." aws s3 cp \
    --acl public-read \
    --content-type image/png \
    spec/fixtures/image.png \
    s3://bus-com-avatars-development/avatar/francois.png
upload failed: spec/fixtures/image.png to s3://bus-com-avatars-development/avatar/francois.png An error occurred (AccessDenied) when calling the PutObject operation: Access Denied

What other actions must be provided in order to put publicly readable objects on S3?

A: The problem is being caused by --acl public-read, which requires PutObjectAcl permissions. (If you take that out, it works fine.)
Therefore, update your policy to this:
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "Statement1",
            "Effect": "Allow",
            "Action": [
                "s3:PutObject",
                "s3:PutObjectAcl"
            ],
            "Resource": [
                "arn:aws:s3:::avatars-bus-com-development/avatar/*"
            ]
        }
    ]
}


text:
Q: Join Query on Datetime field I need to write the query  based on the below condition.
I have two tables , in that i need to fetch the all the columns from table1 and one more column from another field based on the date field.
Date 1 field in Table 1 is in Datetime format,
Date2 field in table 2 id in date Format.
I am assuming the below query , please update me is there any changes
Select Table1.*, c3
From Table1
Full Outer join
Table2
On Date(Date1) = Date2

*

*here I'm using the Date function to convert the datetime field to date format.

*C3 is column in Table 2.

Please confirm me which join i should use?

A: Your ON clause looks correct. Your specification seems to call for a JOIN (inner join) or a LEFT JOIN.  MySQL doesn't have FULL OUTER JOIN. In any rate it probably doesn't make sense for your application. (But that's a guess on my part.)
Try this.
       SELECT t1.*, t2.c3
         FROM Table1 t1
    LEFT JOIN Table2 t2 ON Date(t1.Date1) = t.Date2

That will give you every row in Table1, and the associated c3 values from Table2.  If any given row in Table1 lacks a corresponding row in Table2, you'll get a NULL for the c3 value (that's what LEFT JOIN does).


text:
Q: Extend an ActiveAdmin page from gem I've installed a gem which relies on ActiveAdmin. Now I'd like to extend one particular ActiveAdmin Page of that gem. E.g. simply adding one new column or field
So if that ActiveAdmin Page is registered like
module GemModule
  ActiveAdmin.register Post do
    index do
      column :title
    end
  end
end

Is there any way to add another column to index?
Same question for form.inputs


text:
Q: All ways to split a string in k parts in ruby What is the best way to get an array that contains an array for every way to split a string in k factors, where the factors might also be empty?
As an example, if k is 3 and the string is
Hello

then I would like a return value as follows:
[ ["", "", "Hello"], ["","H","ello"], ["", "He", "llo"], ..., ["H", "e", "llo"], ["H", "el", "lo"], ..., ["Hello","",""] ]

And I would like to have this in a function, so that k is parameter (for a fixed k I would just write k-1 loops). Is there a nice way to do that in ruby?
Thanks for your help!

A: s = "Hello"
k = 3
(0..s.length).to_a.repeated_combination(k - 1)
.map{|a| [0, *a, -1].each_cons(2).map{|i, j| "#{s} "[i...j]}}

result:
[
  ["", "", "Hello"],
  ["", "H", "ello"],
  ["", "He", "llo"],
  ["", "Hel", "lo"],
  ["", "Hell", "o"],
  ["", "Hello", ""],
  ["H", "", "ello"],
  ["H", "e", "llo"],
  ["H", "el", "lo"],
  ["H", "ell", "o"],
  ["H", "ello", ""],
  ["He", "", "llo"],
  ["He", "l", "lo"],
  ["He", "ll", "o"],
  ["He", "llo", ""],
  ["Hel", "", "lo"],
  ["Hel", "l", "o"],
  ["Hel", "lo", ""],
  ["Hell", "", "o"],
  ["Hell", "o", ""],
  ["Hello", "", ""]
]

A: Using recursion:
def doit(s, k, b = [], r = [])
  case k
  when 0
    r << b
  when 1
    doit( [], 0, b + [s], r )
  else
    (0..s.size).each { |i| doit( s[i..-1], k-1, b + [s[0,i]], r ) }
  end
  r
end

v = doit('Hello', 3)
 #=> [["", "", "Hello"],["", "H", "ello"],["", "He", "llo"],["", "Hel", "lo"],
 #    ["", "Hell", "o"],["", "Hello", ""],["H", "", "ello"],["H", "e", "llo"],
 #    ["H", "el", "lo"],["H", "ell", "o"],["H", "ello", ""],["He", "", "llo"],
 #    ["He", "l", "lo"],["He", "ll", "o"],["He", "llo", ""],["Hel", "", "lo"],
 #    ["Hel", "l", "o"],["Hel", "lo", ""],["Hell", "", "o"],["Hell", "o", ""],
 #    ["Hello", "", ""]]


text:
Q: Count Connected Strings in Matrix Java using recursion I am supposed to count how many @ signs are connected to the original predetermined spot in a 2D array matrix. I am getting a stack overflow error and do not know why. Any suggestions are appreciated (Take a provided row and col location and count how many @ signs connect to the original location. @ signs are connected if they are connected up, down, left, and right of one another.)
Current Code:
   import static java.lang.System.*;

public class AtCounter
{
   private String[][] atMat;
   private int totalCount = 0;
   private boolean[][] visited; //used to see if location has been visited before.
   public AtCounter(int rows, int cols)
   {
       //size the matrix
       atMat = new String[rows][cols];
       //use nested loops to randomly load the matrix
       for(int r = 0; r < atMat.length; r++)
       {
           for(int c = 0; c < atMat[r].length; c++)
           {
               int num = (int) (Math.random() * 2);
               if(num == 0)
                   atMat[r][c] = "@";
               else
                   atMat[r][c] = "-";
           }
       }
       //you will need to use Math.random()

        visited = new boolean[atMat.length][atMat.length];
   }
   /**
    * Used to find out if location is in the 2D Matrix.
    */
   public boolean inBounds(int r, int c)
   {
        return ((r > -1 && r < atMat.length) && (c > -1 && c < atMat.length));
   }
   public int countAts(int r, int c)
   {
        //add in recursive code to count up the # of @s connected
        //start checking at spot [r,c]

        if(atMat[r][c].equals("-") || !inBounds(r,c))
            return 0;
        if(!visited[r][c])
        {
            if(atMat[r][c].equals("@"))
            {
                totalCount+=1;

                if(inBounds(r - 1, c))//up
                    countAts(r - 1, c);

                if(inBounds(r + 1, c))//down
                    countAts(r + 1, c);

                if(inBounds(r, c + 1))//right
                    countAts(r , c + 1);

                if(inBounds(r, c  - 1))//left
                    countAts(r, c - 1);
            }
        }
        return totalCount;
     }

    /*
     *this method will return all values in the matrix
     *this method should return a view of the matrix
     *that looks like a matrix
     */
    public String toString()
    {
        String grid = "";
        for(String[] row : atMat)
        {
            for(String val : row)
            {
                grid += val + " ";
            }
            grid += "\n";
        }
        return grid;
    }
}

A: You have several errors in your code:

*

*You are created the visited arrays using atMat.length which will create an square array even if your original dimensions (rows and cols) aren't equal.

*In the inBounds method you the column argument c against the length of the rows, not the length of the columns

*In the countAts method:

*

*The checking order of the invalid conditions needs to be reversed, you need to check first if it is valid position and later if the value in that cell is an @.

*If the current cell hasn't been visited then the first thing is to marked as visited within the if block, to avoid falling in an endless recursion.

With all that said, a possible solution could be as follows:
import static java.lang.System.*;

public class AtCounter
{
    private String[][] atMat;
    private int totalCount = 0;
    private boolean[][] visited; //used to see if location has been visited before.

    private int rows; // To store rows length
    private int cols; // To store cols length

    public AtCounter(int rows, int cols)
    {
        //size of the matrix
        this.rows = rows;
        this.cols = cols;
        atMat = new String[rows][cols];

        //use nested loops to randomly load the matrix
        for(int r = 0; r < rows; r++)
            for(int c = 0; c < cols; c++) {
                int num = (int) (Math.random() * 2);
                if(num == 0)
                    atMat[r][c] = "@";
                else
                    atMat[r][c] = "-";
            }

        visited = new boolean[rows][cols];
    }

    /**
    * Used to find out if location is in the 2D Matrix.
    */
    public boolean inBounds(int r, int c)
    {
        return r > -1 && r < rows && c > -1 && c < cols;
    }

    public int countAts(int r, int c)
    {
        //add in recursive code to count up the # of @s connected
        //start checking at spot [r,c]

        if(!inBounds(r,c) || atMat[r][c].equals("-")) // The order here matters
            return 0;

        if(!visited[r][c])
        {
            visited[r][c] = true; // Marks the current cell as visited
            if(atMat[r][c].equals("@"))
            {
                totalCount+=1;

                if(inBounds(r - 1, c))//up
                    countAts(r - 1, c);

                if(inBounds(r + 1, c))//down
                    countAts(r + 1, c);

                if(inBounds(r, c + 1))//right
                    countAts(r , c + 1);

                if(inBounds(r, c  - 1))//left
                    countAts(r, c - 1);
            }
        }
        return totalCount;
    }

}


text:
Q: Self host url. What is the difference between * and +? I have been looking at examples of self hosted web api and wcf services.
I have been noticing the url that these endpoints bind to use two distinct url's and I did not know what the difference between the two url formations.
The two types of endpoint url's are
http://*:8080
http://+:8080

Can someone explain to me what the difference is between these two url's in a self hosted environment?


text:
Q: How can I make webpack include unused functions with typescript? How can I make webpack keep unused functions in the final file, I have functions in a typescript file that are not used in the typescript file, but I need them in the final file since they are used in events like onclick which need a function to execute, this is my webpack.config.js file:
var webpack = require('webpack');
const path = require('path');
const TerserPlugin = require('terser-webpack-plugin');

module.exports = {
    entry: {
        home: "./resources/js/home.ts",
        contact: "./resources/js/contact.ts",
    },
    output: {
        path: path.resolve(__dirname, 'public/js'),
        filename: '[name].js',
    },
    resolve: {
        extensions: ['.js', '.ts'],
    },
    optimization: {
        minimizer: [new TerserPlugin({
            extractComments: false,
        })],
    },
    watch: true,
    module: {
        rules: [
            {
                test: /\.ts?$/,
                use: 'ts-loader',
            },
        ],
    },
    plugins: [
        new webpack.ProvidePlugin({
            $: 'jquery',
            jQuery: 'jquery',
        })
    ]
};

And this is my tsconfig.js file:
{
    "compilerOptions": {
        "module": "es6",
        "target": "es5",
        "moduleResolution": "node",
        "outDir": "./public/js",
        "rootDir": "./resources/js",
        "removeComments": true,
        "allowJs": true,
        "allowSyntheticDefaultImports":  true,
        "allowUnusedLabels": true,
    },
    "files": [
        "./resources/js/contact.ts",
    ],
}

I know the problem is webpack since when compiling using only typescript, I get the unused function in the final file. So how can I make webpack keep unused functions and leave them in the final javascript file?


text:
Q: Why I can not start harmony mode by "node --harmony test.js" from command line? The problem is:
longhao33@hePC:~$ node --harmony test.js
/home/longhao33/test.js:1
(function (exports, require, module, __filename, __dirname) { let str = 'es666666666666';
                                                              ^^^

SyntaxError: Block-scoped declarations (let, const, function, class) not yet supported outside strict mode
    at exports.runInThisContext (vm.js:53:16)
    at Module._compile (module.js:413:25)
    at Object.Module._extensions..js (module.js:452:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Function.Module.runMain (module.js:475:10)
    at startup (node.js:117:18)
    at node.js:951:3

But "let" is supported when:(So strange!)
longhao33@hePC:~$ node --harmony
> let str = 'es66666666666'
undefined
> str
'es66666666666'

*

*system:ubuntu 14.04LTS 64bit

*node:V4.1.1 (Installed by nvm,which is installed at $HOME)

*content of test.js:
let str = 'es666666666666';
console.log(str);
Thanks ahead of time.

A: You're missing 'use strict'; at the top of your test.js (as indicated by the error message).
It works in the REPL because 'use strict'; is automatically included during code evaluation.


text:
Q: ng-src changing with some delay on photo.src change I've an img tag with ng-src attribute applied for a master detail page.
Detail page has the image, once I switch to master and return, the previous image stays for a while until the new one takes it place.

my angular code, note the image property is changed outside the $scope.
this.$scope.detail.photo = details[0].photo;
this.$scope.$apply();

though on the way back switching to master, I'm nulling everything.
this.$scope.detail.photo = null;
this.$scope.$apply()

but it's not working, when I come back again, i see the previous image until the next one takes effect.

A: Changing ng-src to null(or any falsy value) will not change the value of the underlying src attribute(reference).
It doesn't make sense to do so, anyway. If you want to hide the picture, just use an ng-show.

A: http://makandracards.com/makandra/29415-resolving-angular-not-updating-an-image-src-when-ng-src-is-empty


text:
Q: activate timer on first click of button I am creating a web page where the user clicks a button as many times as they can in 5 seconds. Currently the timer starts when the page is initially loaded. However, I would like the timer to start when the user first clicks the 'Click' button and is not reset every time the user clicks the button after the first click.
Any ideas on how to do this? Thanks in advance.
HTML button:
<div class='buttonDiv'>
        <button onclick='countClicks()' id='click' type="button">Click Me!</button>
    </div>

Javascript functions:
/*record clicks*/
var clicks = 0;

function countClicks(){
document.getElementById('click').value = ++clicks;
document.getElementById('result').innerHTML = clicks;
}

/* Timer countdown */
var secs=5;
var counter=setInterval(timer, 1000);

function timer(){
 secs--;
 if (secs <= 0){
 clearInterval(counter);
 document.getElementById("click").disabled = true;

 document.getElementById("seconds").innerHTML=0;
 return;

 }
 document.getElementById("seconds").innerHTML=secs;
}

A: Simply declare the counter variable then check if it is set inside the function:
var counter;

function countClicks(){

    if( !counter ){//counter is not set

        counter = setInterval(timer, 1000);

    } else {

        document.getElementById('click').value = ++clicks;
        document.getElementById('result').innerHTML = clicks;
    }
}


text:
Q: Pip3 not working on Ubuntu Jammy I'm trying to install a pip3 package. When it run "pip3 install mitype", I get the following error in the terminal:
$ pip3 install mitype

Traceback (most recent call last):
  File "/home/trent/.local/bin/pip3", line 5, in <module>
    from pip import main
  File "/home/trent/.local/lib/python3.10/site-packages/pip/__init__.py", line 13, in <module>
    from pip.utils import get_installed_distributions, get_prog
  File "/home/trent/.local/lib/python3.10/site-packages/pip/utils/__init__.py", line 23, in <module>
    from pip._vendor import pkg_resources
  File "/home/trent/.local/lib/python3.10/site-packages/pip/_vendor/pkg_resources/__init__.py", line 32, in <module>
    import symbol
ModuleNotFoundError: No module named 'symbol'

On Stackoverflow, the solution for this seems to be to run pip3 install --upgrade pip3 setuptools or pip install --upgrade pip setuptools for Python 2. However, neither of these worked for me, I still got the same error. How can I fix this?


text:
Q: Calculating PPM from substance in enclosed but ventilated environment Firstly my apologies if this question doesn't have all required data or is impossible to answer!
I am interested in knowing if it is possible to determine the ppm of vapor from a particular liquid if left in an enclosed space at atmospheric pressure. I have a safety datasheet for the liquid showing a vapor pressure of 82.06mbar and density of $0.82\ g/cm^3$, at $20^\circ C$.
Is this enough to work out a PPM value in atmosphere, or is it not possible without actual in-situ ppm measurement?

A: This system is in equilibrium, which means that the partial pressure of the contaminant is 82.06 mbar.  In SI units, this equates to 8206 Pa.  Since standard atmospheric pressure is 101325 Pa, the ratio of these two pressures gives a mole fraction of 0.081, which is 8.1 mole%, which is equivalent to 8.1 vol%, assuming that the contaminant acts like an ideal gas.  Converting to ppm gives a value of 80,100 ppm on a volume basis.
Note that this concentration assumes equilibrium, which will be an unventilated condition.  A ventilated condition will definitely be non-equilibrium, and will depend on numerous variables, such as the concentration of the contaminant in the incoming air, the velocity and temperature of the ventilation air, whether that air blows directly on a puddle of the contaminant (aka location of the ventilation), etc.  A calculation based on a ventilated condition will depend on several assumptions, which will make the calculation uncertain.  For such a ventilated condition, it would make sense to actually make measurements.


text:
Q: How to convert string into fixed number of bytes? I want to create an 8 bytes sized variable that will include my string.
byte = 8_bytes_variable
str = 'hello'
# Put str inside byte while byte still remains of size 8 bytes.

A: You can format the string first by adding some space to the beginning of it. Here I assumed that each character takes 1 bit. (Chinese characters take more)
str = 'hello'
if len(str.encode('utf-8')) > 8:
    print("This is not possible!")
else:
    str2 = '{0: >8}'.format(str)    # adds needed space to the beginnig of str
    byte = str2.encode('utf-8')

In order to get the original string later, you can use lstrip():
str2 = byte.decode()
str = str2.lstrip()


text:
Q: Doctrine Extension bug with APCu : "ORM TreeListener does not support tree type:" I have a tree type entity configured with annotation in "nested" tree type.
I activated PHP5.5 APCu extension, and after some time, a weird exceptions is throwned:

ORM TreeListener does not support tree type:

(with nothing after the "type:")
The website works fine some hours and does this after.
If I clear the APCu cache, all works fine for several hours.
Here is the stacktrace :
Stacktrace (most recent call first):

File "[...]/vendor/gedmo/doctrine-extensions/lib/Gedmo/Tree/TreeListener.php", line 84, in getStrategy
  throw new \Gedmo\Exception\InvalidArgumentException($managerName." TreeListener does not support tree type: {$config['strategy']}");
File "[...]/vendor/gedmo/doctrine-extensions/lib/Gedmo/Tree/Entity/Repository/NestedTreeRepository.php", line 846, in validate
  return $this->listener->getStrategy($this->_em, $this->getClassMetadata()->name)->getName() === Strategy::NESTED;
File "[...]/vendor/gedmo/doctrine-extensions/lib/Gedmo/Tree/Entity/Repository/AbstractTreeRepository.php", line 52, in __construct
  if (!$this->validate()) {
File "[...]/vendor/doctrine/orm/lib/Doctrine/ORM/EntityManager.php", line 689, in getRepository
  $repository = new $repositoryClassName($this, $metadata);
File "[...]/app/cache/prod/jms_diextra/doctrine/EntityManager_520e1bbfadf9e.php", line 180, in getRepository
  $repository = $this->delegate->getRepository($className);
File "[...]/src/Mapado/ActivityFrontBundle/Controller/ActivityController.php", line 85, in viewAction
  $rubricRepo = $this->getDoctrine()->getManager('rubric')->getRepository('MapadoRubric:Rubric');
File "[...]/app/bootstrap.php.cache", line 2805, in handleRaw
  $response = call_user_func_array($controller, $arguments);
File "[...]/app/bootstrap.php.cache", line 2779, in handle
  return $this->handleRaw($request, $type);
File "[...]/app/bootstrap.php.cache", line 2908, in handle
  $response = parent::handle($request, $type, $catch);
File "[...]/app/bootstrap.php.cache", line 2210, in handle
  return $this->getHttpKernel()->handle($request, $type, $catch);
File "[...]/web/app.php", line 22, in null
  $response = $kernel->handle($request);

Do you have some hint that could help me resolve this bug ?
Thanks

A: Faced the same problem.
See this https://github.com/krakjoe/apcu/issues/35
Just set options apc.serializer to php


text:
Q: Añadir y eliminar atributos de hijos desde JavaScript Tengo un problema, resulta que tengo en html una lista de divs, en concreto un div padre que contiene todo y luego otros div que a su vez tienen hijos, esto con el fin de clasificarlos por tipo.
Y por parte de javascript, tengo un codigo que capta los click que se le hacen a estos, con el fin de que al hacer click en estos elementos, se les dibuje un marco o borde, y donde esta el problema, que al volver a hacer click se elimine este borde y aparezca en el que ha sido clickeado, dando la sensacion que el elemento es el que esta siendo seleccionado.

let sumar = [];
let div1 = "";
b.addEventListener("click", f);
let b2 = document.getElementsByTagName("b2");

function f(e) {
  div1 = e.target;
  sumar.push(e.target.id);
  let impar1 = (sumar.length) / 2;

  div1.setAttribute("style", "border:5px solid #000; ");
  if (Number.isInteger(impar1) == true) {
    b2.setAttribute("style", "*atributos del elemento*");
  }
}

f

nombre del producto

nombre del producto

 especificacion

g

nombre del producto

 especificacion

imagen

 nombre del producto

Está bastante cercana a funcionar y se porque no funciona;  con b2.setAttribute, le devuelvo los valores a cada div a los iniciales (sin el marco), el problema esta en que si capturo el elemento con getelementbyid, este solo toma el primero con ese id, y necesito que los tome todos, y si lo tomo con getelmentsbyclassname, me dice que es indefinido por la razón que explique en los comentarios. Saben como podría tomar todos los elementos con mismo id o solucionar el problema del getelementsbyclassname?.
Cabe destacar que las etiquetas (v1, v2 y v3) son padres, no deseo que el margen se cree al rededor de esta, sino del elemento hijo de estos al cual se le hace click.

A: Para la funcionalidad que quieres podrías definir una clase para cada contenedor (con el fin de escoger todos los contenedores) y justo antes de asignarle el borde al estilo que el usuario acaba de elegír eliminar el estilo de los anteriores, algo cómo así:

function clickerino(e) {

  for (let opcion of  document.getElementsByClassName("opcion")) {
    opcion.setAttribute("style", "border:none; ");
  }
  e.currentTarget.setAttribute("style", " border:5px solid #000; ");

}

f

nombre del producto

nombre del producto

 especificacion

g

nombre del producto

 especificacion

imagen

A: Podes usar las clases de css para tu caso , por ejemplo , si el item tiene la clase .border (ver css)
Los items que necesitas el borde pueden compartir una clase , para el ejemplo te agregue la clase .product , luego guardas esa coleccion de items con querySelectorAll , eso te permite recorrer esa lista de items y a cada uno de ellos le pasas la funcion del evento
y le decis de entrada remove la clase .border de todos los items y al e.target que es el item en cuestion el agregas la clase .border
Agregue una  validacion porque no habia visto que tambien necesitabas desmarcar el elemento si ya contenia el borde
if(e.target.classList.contains('border')){
//classList.contains devuelve true si contiene la clase y despues si es asi
la removes y escapas directamente de la funcion con return
e.target.classList.remove('border')
return

}

const  products = document.querySelectorAll(".product");

function borderSelected(e) {
if(e.target.classList.contains('border')){
  e.target.classList.remove('border')
  return

}
 products.forEach(product=> product.classList.remove('border'))
 e.target.classList.add('border')
}

products.forEach(product => {
product.addEventListener("click", borderSelected);
})
.product.border{
border:1px solid black
}

f

nombre del producto

nombre del producto

 especificacion

g

nombre del producto

 especificacion

imagen

 nombre del producto

*

*Document.querySelectorAll()

*Element.classList


text:
Q: How to install the same version of a package on different machines? I need to run cppcheck on several machines with different versions of Ubuntu. Normally I install cppcheck with sudo apt-get install cppcheck.
Well, one of the machines is running Ubuntu 16.04. An other is running Ubuntu 16.10.
I figured now out, that my installation process installs different versions on the machines. One machine has cppcheck 1.72-1, the other machine has cppcheck 1.75-2. I already found out, that this is a normal behavior. You can even check the installation candidates here.
Well, I need the same version an all machines. So I tried this: sudo apt-get install cppcheck=1.72-1. But then I get the error: E: Version '1.72-1' for 'cppcheck' was not found

A: You could use apt-get download cppcheck to download the deb-package file and install this on different machines with apt install ./cppcheck_1.72-1_amd64.deb
But this is not always working if (for example) decencies to library-versions or other packages are not met on one of the destination machines.


text:
Q: Are there generic Python libraries that provide 'signals' (event) capability like Django signals? I'd like to use something like Django signals in non-Django projects.  I thought I'd seen libraries like this in the past, but I've been unable to locate one via the usual searches.
Python's signal library doesn't offer the same capabilities.

A: There are a number of modules for this. Here are a few options, ordered by what I think their popularity is:

*

*The blinker module provides a signal/event mechanism

*PyDispatcher gives you event dispatch

*The PySignals module is the Django signals module without any dependency on Django

*SpiffSignal implements a signal/event framework, but its GitHub page seems to be missing


text:
Q: how to disable timestamps from perl warn command how do I get rid of the timestamp and script name from warn():
[Mon Jun 12 10:31:38 2017] db_insert.pl:  "subjects": ["Government - Comparative", "Politics / Current Events"], "revision": 4}

A: That message isn't generated by Perl's warn
If I generate a generic warning message, it looks like this
$ perl -e 'warn "Warning message"'
Warning message at -e line 1.

So it is your program that is building strings and passing them to warn. You have to look at that to remove the time stamp


text:
Q: How do I do a LIKE % query in ActiveRecord? I'm trying to find some items that contain a certain string. If I do:
MyModel.where("description LIKE ?",keyword)

it will generate a query for an exact match. I would like to make it generate a LIKE %keyword% query. How can I do that?

A: like_keyword = "%#{keyword}%"
MyModel.where("description LIKE ?", like_keyword)

A: MyModel.where("description LIKE (?)", "%#{keyword}%")

A: Model.where("name LIKE 'SH%'")

It will fetch all the name whose starting with only SH. It will work 100%.
eg. SH123,SH2343

A: You can use ILIKE for this
MyModel.where("description ILIKE (?)", "%#{keyword}%")

A: For PostgreSQL it will be
MyModel.where("description ILIKE ?", "%#{query}%")


text:
Q: I can't understand linux hook function return 1337? Now I loot at a article! I get the hook code. The code is here:
int system(const char *command){
    printf("HOOK: system(\"%s\")",command);
    return 1337;
}

int fork(void){
    return 1337;
}

Now I hava a question! Why the return is 1337?

Thanks to answer my question!

A: This depend on your sub-system, return code 1337 is what handled by others like cloud or somewhere in your internal code.
basically this we define for error handling or to determine the failure cases.
like calling thread might be called this as
if (1337 != system(command)) {
          /* error statement */
          printf("...");
}
So in short this is not specific to 1337 you can use any return value.


text:
Q: jquery form validation not executing i have a form with the following fields inputUser,inputEmail,inputPhoneNo,inputPassword,inputConfirmPassword
and one button with createRegistration
when ever on the blur condition the message should be displayed but is not displaying.
when i click the createRegistration button the form is not validating.still i makes a ajax request.
function validateForm(){

        $('#registerForm').validate({
        rules: {
          inputUser: {
            minlength: 2,
            required: true
          },
          inputEmail: {
            required: true,
            email: true
          },
          inputPhoneNo: {
            minlength: 2,
            required: true
          },
          inputPassword: {
            minlength: 5,
            required: true
          },
          inputConfirmPassword: {
            minlength: 5,
            required: true,
            equalTo: "#RinputPassword"
          }

        },
            highlight: function(element) {
                $(element).closest('.control-group').removeClass('success').addClass('error');
            },
            success: function(element) {
                element
                .text('OK!').addClass('valid')
                .closest('.control-group').removeClass('error').addClass('success');
            }
      });

}

$(document).ready(function() {
$('#createRegistration').click(

        function(){
            validateForm();
            var post = $(this).attr("name") + "=" + $(this).val();

            // get form key value pairs
           $queryString=$('#registerForm').serialize()+ "&" + post;

        $.post(
            'Registration.cgi',
            $queryString,
            function(data,status){
                var activationPattern = /activate/g;
                var EmailPattern = /Email/g;

                  if(activationPattern.test(data)) {
                      $('#RmailActivation').addClass("alert alert-sucess");
                      $('#RmailActivationSpan').html(data);
                  }else if(EmailPattern.test(data)){
                      $('#Remail').addClass("error");
                      $('#RemailError').html(data);
                  }else{
                      $('#Ruser').addClass("error");
                      $('#RuserError').html(data);
                  }
              }

        );

        });

});

A: You have a few popular issues and misconceptions regarding this plugin:

*

*.validate() is the plugin's initialization, not a method to repeatedly call to test the form's validity.  Instead, .validate() should be called once within the DOM ready event handler.  Then once initialized, the form is tested automatically using its various built-in events.

*You do not need a click handler.  The click event of the submit button is automatically captured by the plugin.

*As per the docs, you are supposed to put your ajax within the plugin's submitHandler callback option.

submitHandler:  Callback,  Default: default (native) form submit Callback for handling the actual submit when the form
  is valid. Gets the form as the only argument. Replaces the default
  submit. The right place to submit a form via Ajax after it
  validated.

Assuming your ajax is written properly, re-arrange your code into something more like this:
$(document).ready(function () {

    $('#registerForm').validate({
        rules: {
            inputUser: {
                minlength: 2,
                required: true
            },
            inputEmail: {
                required: true,
                email: true
            },
            inputPhoneNo: {
                minlength: 2,
                required: true
            },
            inputPassword: {
                minlength: 5,
                required: true
            },
            inputConfirmPassword: {
                minlength: 5,
                required: true,
                equalTo: "#RinputPassword"
            }
        },
        highlight: function (element) {
            $(element).closest('.control-group').removeClass('success').addClass('error');
        },
        success: function (element) {
            element.text('OK!').addClass('valid')
                .closest('.control-group').removeClass('error').addClass('success');
        },
        submitHandler: function (form) {
            var post = $('#createRegistration').attr("name") + "=" + $('#createRegistration').val();
            $queryString = $(form).serialize() + "&" + post;
            $.post(
                'Registration.cgi',
            $queryString,
            function (data, status) {
                var activationPattern = /activate/g;
                var EmailPattern = /Email/g;
                if (activationPattern.test(data)) {
                    $('#RmailActivation').addClass("alert alert-sucess");
                    $('#RmailActivationSpan').html(data);
                } else if (EmailPattern.test(data)) {
                    $('#Remail').addClass("error");
                    $('#RemailError').html(data);
                } else {
                    $('#Ruser').addClass("error");
                    $('#RuserError').html(data);
                }
            });
            return false;  // required (when using ajax) for blocking a regular submit
        }
    });

});

Very simple DEMO:  http://jsfiddle.net/jMdWY/
The same demo using a <button></button> in place of a <input type="submit"/>:  http://jsfiddle.net/jMdWY/2/

A: Try following code
HTML
<form id="registerForm" onsubmit="return false;">
    Username:<input type="text" name="inputUser" />

    Email:<input type="text" name="inputEmail" />

    Phone No:<input type="text" name="inputPhoneNo" />

    Password:<input type="text" name="inputPassword" id="RinputPassword"/>

    Confirm Password:<input type="text" name="inputConfirmPassword" />

    <input type="submit" id="createRegistration"/>
</form>

JS
$(document).ready(function () {
    $('#registerForm').validate({ // initialize the plugin
        rules: {
            inputUser: {
                required: true,
                minlength: 2
            },
            inputEmail: {
                required: true,
                email: true
            },
            inputPhoneNo: {
                required: true,
                minlength: 2
            },
            inputPassword: {
                required: true,
                minlength: 5
            },
            inputConfirmPassword: {
                required: true,
                minlength: 5,
                equalTo: "#RinputPassword"
            }
        },
    });

    $("#createRegistration").click(function(){
        var queryString = $('#registerForm').serialize();
        alert(queryString);
        // Add your AJAX request here
    });
});

Live Demo : http://jsfiddle.net/FkKUS/3/


text:
Q: Navbar/sidebar on a wordpress site not editable I am helping a non-profit modify their existing wordpress site. The site is very old (built in 2009) and so is the theme ('deFusion'). They wanted me to add a calendar to the sidebar and restructure the navbar. Although I see there are already added items on the sidebar, there is no place in the dashboard where I could add additional items to the the same sidebar. I could not edit the navbar either (add or remove menu items).
How do you deal with an old theme like this? I am not a wordpress expert nor have done any work with PHP. I have searched online but have not been able to find any relevant solution.


text:
Q: Reporting Solution in PHP / CodeIgniter - Server side logic vs client side I'm building a report for an end user.
They would like to see a list of all widgets... but then also like to see widgets with missing attributes, like missing names, or missing size.
So i was thinking of creating one method that returns json data containing all widgets... and then using javascript to let them filter the data for missing data, instead of requerying the database.
Ultimately, they need to be able to save all "reports" (filtered versions of data) inside a csv file.
These are the two options I'm mulling over:
Design 1
Create 3 separate methods in my controller/model like:
get_all_data()
get_records_with_missing_names()
get_records_with_missing_size()

And then when these methods are called, I would display the data on screen and give them a button to save to csv file.
Design 2
Create one method called get_all_data() and then somehow, give them tools in the view to filter the json data using tables etc... and then letting them save subsets of the data.
The reality is, in order to display all data, I still need to massage the data, and therefore, I know which records are missing attributes.  So i'd rather not create separate methods by each filter.
I'm not sure how I would do that just yet but at this point, i would like to know some pros/cons of each method.
Thanks.

A: Assuming your using Angular.JS, jQuery or similar, I would recommend loading all the data from the server at once, then writing controllers that are able to filter between the different types of lists.
This solution allows for the least amount of load on your server and makes the client do most of the work.  This along with the idea of having an application whose lag depends on the local machines filtering (local processing = fast) is much better that having an application that can lag due to network instabilities (network = slow).
That being said, if it is a massive amount of data (> 1 million records), migrating the logic from the client to the server may become reasonable.  At this point the local processing may/can take longer that it would be to request the data from the server.


text:
Q: How to write the query for below scenario? I am facing issue with group by in linq. You can see my code below.
Concern: I need to display status=completed and deleted=false then will get the IEnumerable below result .
Sample Data:
Id appName        role    Type    Status      createdAt
1  application1  role1   false    completed   25/05/2014 12.00.00
2  application1  role1   true     completed   25/05/2014 11.00.00
3  application1  role1   true     completed   25/05/2014 11.00.00
4  application2  role1   true     completed   25/05/2014 11.00.00
5  application2  role1   false    completed   25/05/2014 10.00.00

In above IEnumerable result I need the output like
Expected Output:
Id appName        role    Type    Status      createdAt
4  application2  role1   true     completed   25/05/2014 11.00.00

I have tried this as below Linq query:
Code:
var arr = from m in m_Repo.All().AsEnumerable()
          .Where(a => a.Status == Completed && a.ID== 12 && a.IsDeleted == false)
          group m by new { m.Name } into g
          select g.OrderByDescending(gg => gg.UpdatedAt).Take(1)
          .Where(dd => dd.Type == true);

But not giving the output. I am getting IEnumerable<IEnumerable> result.
Kindly help me how to achieve this?

A: var arr = from m in m_Repo.All().AsEnumerable()
          .Where(a => a.Status == Completed && a.ID== 12 && a.IsDeleted == false)
          group m by new { m.Name } into g
          select g.OrderByDescending(gg => gg.UpdatedAt).Take(1)
          .Where(dd => dd.Type == true).First();

A: var arr = m_Repo.All().AsEnumerable()
                .Where(a => a.Status == Completed && a.ID== 12 && !a.IsDeleted)
                //No need to group by new if you have only one property to group by
                .GroupBy(m => m.Name)
                .Select(g => g.OrderByDescending(x => x.UpdateAt))
                //this will give the first group (by name), with highest UpdateAt
                .First()
                //this will return the first element of this group with Type true
                .FirstOrDefault(dd => dd.Type);

or
var arr = m_Repo.All().AsEnumerable()
                .Where(a => a.Status == Completed && a.ID== 12 && !a.IsDeleted)
                .GroupBy(m => m.Name)
                .OrderByDescending(g => g.Select(x => x.UpdateAt))
                .First()
                .FirstOrDefault(a => a.Type);

You may need to do an OrderByDescending(x => x.Id)
between First() and FirstOrDefault() if you want the biggest Id.


text:
Q: How to make install Chrome extension for Firefox I read with great relief that I can add strikethrough formatting to Gmail with the add-on described here—the description says it works with Chrome and Firefox. But the link in that post takes me to the Chrome store, where I'm told to use Chrome. I already do, but prefer Firefox. Once I've installed the add-on to Chrome, how can I get it in Firefox? Many thanks to any and all who can enlighten me.

A: you may have some luck looking in the firefox extensions store...
Go to this website in firefox:
"about:addons"
Then on the right select get addons.
Now in the top right you can search for what you want :)
Hope I helped


text:
Q: Is there any way to reduce blg file (performance counter) read time? I am using Tx.Windows nuget package for reading performance counter blg file.
https://github.com/Microsoft/Tx
With small size file, the result is very immediate for below code, but as my file size grow, the time taken for read also increase. With big size file (say 500MB) the time taken for file read is very large.
Is there any way to reduce file reading time?
using System;
using System.Linq;
using System.Reactive.Linq;
using Tx.Windows;

namespace ConsoleApp3
{
class Program
{
    static void Main(string[] args)
    {
        var observable = PerfCounterObservable.FromFile(@"C:\Files\test.blg");

        var grouped = from a in observable
                      group a by new { a.Machine, a.Instance, a.Timestamp } into groups
                      from g in groups.ToArray()
                      select new
                      {
                          groups.Key.Machine,
                          groups.Key.Instance,
                          groups.Key.Timestamp,
                          Counters = g
                      };

        var all = grouped.ToEnumerable().ToArray();

        Console.ReadLine();
    }
}
}

The sample blg file at Microsoft Tx github location,
https://github.com/Microsoft/Tx/blob/master/Traces/BasicPerfCounters.blg
and Here test code,
https://github.com/Microsoft/Tx/blob/master/Test/Tx.Windows.Tests/PerfCounterTest.cs


text:
Q: Multiple instances of AM PM picker I have a HTML in which i have to use start time and end time. for doing this i am using the AM PM picker of jquery.But only one instance of this AM PM picker is working .i cant able to use multiple instances of this AM PM picker........How can i able to do that....
The whole source code is present in A Zip folder....
http://www.4shared.com/file/ZQy2A3DU/DateTime.html
alternativery you can have a look on the code thru
http://jsfiddle.net/premseoul/BjDYP/

A: Have a look at this
http://keith-wood.name/timeEntry.html


text:
Q: If writing to multiple files often, does file I/O remain costly in PowerShell? I have a large script that parses several computers for information. At the beginning of my script, I create several files to write output to as the script finds information.
Since I want my script to work at scale (hundreds or thousands of machines), I am wondering if it is too costly to write to the files each time the script identifies new information. In terms of performance, should I write to the files only once (after the script finishes), or do the writes to files become inexpensive after my first write?

A: That should not be an overhead if your system resource along with the DISK I/O allow you to do that.
I would recommend you to use .Net StreamWriter to write the file because thats pretty fast and effective way to accomplish the need:
$stream = [System.IO.StreamWriter] "t.txt"
1..100 | % {
      $stream.WriteLine($s)
}
$stream.close()

Avoid locking. Do not try to access the same file in parallel. That will reduce the complexity.
And it is completely feasible if you are making sure that other heavy applications are not using the Disk I/O that time.
Hope it helps.


text:
Q: selecting rows that have n foreign key conditions satisfied I'm trying to filter a master table rows based on 2-more conditions from the relative foreign key relation, i came up with this which is working fine, but i just can't convince my self that it's that much of a fuss
select r.pageid
from
((
select co.pageid
from (cmscontentpublished as co join cmsnode as cm on co.PageID = cm.ID)
where cm.parentid=365 and co.Title='Title' and co.Content like '%test%'
)
union all
(
select co.pageid
from (cmscontentpublished as co join cmsnode as cm on co.PageID = cm.ID)
where cm.parentid=365 and year(co.DateContent) =2012
)) as r
group by r.pageid
having COUNT(*)=2

any ideas on how to do correctly

A: Try if that works for you
SELECT page_id FROM
(
SELECT co.pageid , count(case when year(co.DateContent) =2012 THEN 1 END) AS cnt1,
count(CASE WHEN co.Title='Title' and co.Content like '%test%' THEN 1 END) AS cnt2
FROM cmscontentpublished as co
JOIN cmsnode as cm on co.PageID = cm.ID
WHERE cm.parentid=365 AND ((co.Title='Title' and co.Content like '%test%') OR
(year(co.DateContent) =2012))
)a
WHERE (cnt1 + cnt2 )= 2
-- if you want page_id only if each condition is satisfied exactly once,
-- then where should look "cnt1 = 1 and cnt2 =1"


text:
Q: Pandas reads the txt file as 1 column except header I have a txt file with following data;
"a" "b" "c" "d" "e" "f" "g" "h"
"2" "222" "0.111" "b1" "19.11" "17.96" "2.85" ""
"3" "333" "0.123" "b2" "42.79" "26.68" "2.85" ""
"4" "444" "0.105" "b3" "17.28" "16.50" "2.85" ""
"5" "555" "0.106" "b4" "18.74" "19.78" "2.88" ""
"6" "666" "0.107" "b5" "5.79" "9.93" "2.88" ""

I am trying to read file with pandas with following code;
df = pd.read_csv("test.txt",sep="\t",quotechar='"',quoting=csv.QUOTE_NONE)

When I try to get columns with room_file.columns it print this;
Index(['"uid" "raum_code" "tuerschild" "raumbezeichung" "raumflaeche" "raumumfang" "raumhoehe" "Comments"'], dtype='object')

But the df output looks just 1 column;
    "a" "b" "c" "d" "e" "f" "g" "h"
0   "2" "222" "0.111" "b1" "19.11" "17.96" "2.8...
1   "3" "333" "0.123" "b2" "42.79" ...
2   "4" "444" "0.105" "b3" "17.28" "16.50" "2...
3   "5" "555" "0.106" "b4" "18.74" "19.78" "2...
4   "6" "666" "0.107" "b5" "5.79"...

5 rows × 1 columns

But it supposed to be 5 rows × 8 columns
I already try:
Solution 1
Solution 2
And I also try like this:
df = pd.read_csv("test.txt",sep='\t',header=0)

But everything same. Can you please help to read the txt file as a dataframe.

A: Let file.txt content be
"uid" "raum_code" "tuerschild" "raumbezeichung" "raumflaeche" "raumumfang" "raumhoehe" "Comments"
"2" "222" "0.111" "Büro" "19.11" "17.96" "2.85" ""
"3" "333" "0.123" "Besprechungsraum" "42.79" "26.68" "2.85" ""
"4" "444" "0.105" "Büro" "17.28" "16.50" "2.85" ""
"5" "555" "0.106" "Büro" "18.74" "19.78" "2.88" ""
"6" "666" "0.107" "Fernmeldetechnik" "5.79" "9.93" "2.88" ""

observe that spaces are used for separating and everything (both string and numeric values) are quoted and first line is header, considering that suitable reading is
import csv
import pandas as pd
df = pd.read_csv("file.txt",sep=' ',quotechar='"',quoting=csv.QUOTE_ALL)
print(df.shape)  # (5, 8)
print(df)

output
   uid  raum_code  tuerschild    raumbezeichung  raumflaeche  raumumfang  raumhoehe  Comments
0    2        222       0.111              Büro        19.11       17.96       2.85       NaN
1    3        333       0.123  Besprechungsraum        42.79       26.68       2.85       NaN
2    4        444       0.105              Büro        17.28       16.50       2.85       NaN
3    5        555       0.106              Büro        18.74       19.78       2.88       NaN
4    6        666       0.107  Fernmeldetechnik         5.79        9.93       2.88       NaN

A: i try this and it shows correct result
df = pd.read_csv("test.txt", header=0, quotechar="\"", sep=" ")

print(df.columns)
print(df.shape)
print(df)


text:
Q: Multidimensional array search for value and add to specific key if found so what i have is just some data that should be fixed for printing, and i can't wrap my head around this one...
i have some finished products separated for each batch code (int_lot) with their quantities. You can select and give that values to the invoice, but what i need to do is calculate total of same product name (in relationship called FinishedProduct) and i get all finished products with relation that has quantities with:
DeliveryProductQuantity::where('delivery_note_id', $packingList->delivery_note_id)->with('FinishedProduct')->get();
then i get object like this:
    "id" => 12
    "finishedid" => "24"
    "quantity" => "116"
    "old_quantity" => "116"
    "delivery_note_id" => "52"

now when i load relationship with first() i get data like for each item in foreach:
            "id" => 12
            "finished_product_name" => "Product Name"
            "shift" => "Prva"
            "expiry_date" => "19042023/1"
            "user_id" => "6"

What i want to do first is just put all products with same finished_product_name. But finished_product_name is in relation and quantity is in array that's not in relationship.
So i need foreach item of first array of objects to check if relationships product name exists and then if it doesn't add a new entry in temporary array, if does just add quantity to the last one with same product name. What have i tried (besides many else):
        $total_data = [];

    foreach ($test2 as $product) {
        foreach ($product->FinishedProduct as $key => $value) {
            if(!in_array($product->FinishedProduct->first()->finished_product_name, $total_data)) {
                array_push($total_data,
                    [
                        'finished_product_name' => $product->FinishedProduct->first()->finished_product_name,
                        'expiry_date' => $product->FinishedProduct->first()->expiry_date,
                        'quantity' => $product->quantity,
                        'old_quantity' => $product->old_quantity,
                        'delivery_note_id' => $product->delivery_note_id
                    ]
                );
            }
            if(in_array($product->FinishedProduct->first()->finished_product_name, $total_data)) {
                foreach ($total_data as $key => $value) {
                    if($value['finished_product_name'] == $product->FinishedProduct->first()->finished_product_name) {
                        $total_data[$key]['quantity'] += $product->quantity;
                        $total_data[$key]['old_quantity'] += $product->old_quantity;
                    }
                }
            }
        }
    }


text:
Q: jshell continues executing my script after exception is thrown. How to make it stop? I tried writing some jshell scripts. When an exception is thrown, jshell still goes on to execute the next line.
How can I make my scripts behave more like normal java programs?
Edit: I simply run it like jshell SCR.jsh.
Using throw new Exception() or 1/0 does not prevent the next line from being executed.
The script includes statement like this:
System.out.println(1/0)
System.out.println("foo")
/exit

I thought the second line is unreachable. That's what I expected. But after the exception is printed, foo is also printed.

A: As per my understanding, the reason why jshell executes all the lines in your script even after one throws an Exception is since it treats your script as a list of Snippet.

All expressions are accepted as snippets. This includes expressions
  without side effects, such as constants, variable accesses, and lambda
  expressions:
1
a
x -> x+1
(String s) -> s.length()

as well as expressions with side effects, such as assignments and
  method invocations
System.out.println("Hello world");
new BufferedReader(new InputStreamReader(System.in))

So even one of the snippet throws an exception, the others must follow the Read-Eval-Print Loop(REPL) pattern. As also answered yourself converting the code as a block of statement marks it as a single Snippet which when throws the java.lang.ArithmeticException marks its completion thereby.
Though ideally, such statements should be instead defined as a declaration snippet.

A declaration snippet (ClassDeclaration, InterfaceDeclaration,
  MethodDeclaration, or FieldDeclaration) is a snippet that explicitly
  introduces a name that can be referred to by other snippets.

A: Finally I think I found a workaround:
{
    System.out.println(1/0);
    System.out.println("foo");
}
/exit

Now it's much closer to the familiar java code.
Not only exception works just as expected, but semicolons also become necessary inside the block.


text:
Q: Replace part of text in a file using batch The file 'MyFile.txt' has a line in it and a part of that line I need replaced.
Example:
The line in the file is like this
53544THOIN91111160000000

I want to replace '111116' from the existing line in 'MyFile.txt', the thing here is '111116' is a variable and would keep changing. Its basically a Date with the format YYMMDD, i want to read the modified date from another file and replace these numbers in 'MyFile.txt'
Here is the code i tried.
set b=MyFile.txt

for /f "tokens= 1" %%c in (%b%) do (set line=%%c)

Set OLDDate=%line:~11,6%

SET filename="AnotherFile.txt"
FOR %%f IN (%filename%) DO SET filedatetime=%%~tf

SET Month=%filedatetime:~0,2%
SET Date=%filedatetime:~3,2%
SET Year=%filedatetime:~8,2%

SET NEWDate=%Year%%Month%%date%

ECHO OLD DATE = %OLDDate%
ECHO NEW DATE = %NEWDate%

I need %OLDDate% to be replaced by %NEWDate% in 'MyFile.txt' in the position ~11,6

A: Any reason why powershell couldn't do it?
    # Example of PowerShell -replace parameter
    clear-Host
    $file = Get-ChildItem "D:\powershell\snippets\g*.txt"
    foreach ($str in $file)
    {
    $content = Get-Content -path $str
    $content | foreach {$_ -replace "the the", "the"} | Set-Content $str
    }
    write-Host "After replace `n"
    $file

In the foreach loop you can replace any string with another.
Date logic can be used as follows:
$anotherfile = gi anotherfile.txt

Retrieving date info
$year = $anotherfile.LastWriteTime.Year


text:
Q: creating objects for 1:n relation with prisma I have two models, Fish and BoardFish
with a 1:1 relation - BoardFish is a type of Fish
I created some seed Fish with named types.
how can I do this in Prisma? I think i have the schema setup, but inserting data isn't really documented apart from fancy/nested types.
schema:
model Fish {
    name      String      @id
    boardFish BoardFish[]
}

model BoardFish {
    id       Int    @id @default(autoincrement())
    name     String
    fishType Fish   @relation(fields: [name], references: [name])
}

try to create:
        let fishes = []
        for (let c = 0; c < fishCount; c++) {
            const fishType = await prisma.fish.findFirst({ where: { name: 'salmon' } })
            const fishData = {
                fishType: fishType!.name,
                // name: 'salmon',
                px: 0,
                py: 0,
            }
            const fish = await prisma.boardFish.create({ data: fishData })
            fishes.push(fish)
        }

but I'm unable to do the insertion:
→ 35 const fish = await prisma.boardFish.create({
       data: {
         fishType: 'salmon',
                   ~~~~~~~~
         px: 3,
         py: 5
       }
     })

Argument fishType: Got invalid value 'salmon' on prisma.createOneBoardFish. Provided String, expected FishCreateNestedOneWithoutBoardFishInput:
type FishCreateNestedOneWithoutBoardFishInput {
  create?: FishCreateWithoutBoardFishInput | FishUncheckedCreateWithoutBoardFishInput
  connectOrCreate?: FishCreateOrConnectWithoutBoardFishInput
  connect?: FishWhereUniqueInput
}

The types involved are pretty hard to follow, Prisma seems to really take the cake for most "magic" with thousands of lines of auto generated code, which I've been digging through without much luck.

A: If you want to have 1:1 relations, I think the schema needs to look more like this:
model Fish {
    name      String      @id
    boardFish BoardFish? // removed autogenerated `[]` and made optional
}

model BoardFish {
    id       Int    @id @default(autoincrement())
    name     String
    fishType Fish   @relation(fields: [name], references: [name])
}

When creating a related record, use prisma's connect api
const fish = await prisma.boardFish.create({
  data: {
    fishType: {
      connect: { name: 'salmon' }, // or `connectOrCreate` if it doesn't exist
    },
  }
})


text:
Q: WM_TIMER messages suppressed when clicking and holding the mouse over windows X button I'm working on a game where the client needs to continue processing windows messages or else the game can be exploited.  In order to solve this problem during window re-size and drag events, we have a WM_TIMER message that fires every 50ms which will restart the main event loop.
The problem is that this technique is not working when a user clicks and holds over the X or minimize button of a windowed client.  (So they don't complete the click, they just halt the client.)
Using Spy++, the last messages I see are:
<00731> 00160D3C P WM_NCLBUTTONDOWN nHittest:HTCLOSE xPos:1150 yPos:178
<00732> 00160D3C P WM_MOUSEMOVE fwKeys:MK_LBUTTON xPos:1014 yPos:-23

Followed by nothing until I move the mouse, and no WM_TIMER messages until I let go the mouse button.
So the question is, while I'm in the state of having my mouse down over the window's X button is there something I could key off of to get the client moving again? Or something I could do so our "watchdog" WM_TIMER messages fire?

A: Some system events such as system menu (as in your case) or window resizing stop regular window messages from being processed for a while. You need to re-think your architecture and maybe run a periodical operation in a secondary thread. There you can use WaitForSingleObject or just Sleep() instead of message-based timer.

A: I can think of a couple possibilities.

*

*When the button down happens on the non-client area, the system code may be running its own message loop until the button is released.  This message loop might not dispatch WM_TIMER messages.

*I believe WM_TIMER is special in that it's a lower priority message.  WM_TIMER is only retrieved from the queue when there's nothing else to retrieve (sort of similar to WM_PAINT).  Windows timers eventually fire, and never sooner than the specified period, but they're not very reliable if you need a regular heartbeat.
As another person suggested, you might need to rely on a second thread to keep things alive.

A: Consider using periodical waitable timer. It will run independently, in a separate thread.


text:
Q: window overflow in full width page I'm developing a website ( portfolio redesign ), and I'm working in full width. But I keep having the same problem and however I'm trying to fix it, it just doesn't work.
I would appreciate if someone could help me out with it, I will paste only the link here because there's to much CSS to paste and HTML markup, but I think by looking in console you can see what's going on in there.
Link: Website
The problem it's pretty obvious, you'll see that an horizontal scroll appears and if you scroll the content it's overflowed by nothing, just empty space, maybe about 60px wide I think. I tried adding padding: 0;, margin: 0; or anything I could think of, but with no success.
I know that adding overflow: hidden; would fix it, but I need the overflow there.

A: Try this , it should work.. tested it with firebug.. hope its cross browser
html {
color: #222222;
font-family: sans-serif;
overflow: hidden;
}

A: It might be a few things.
Since you're going full width, everythings set to 100%, right? But on the bottom you have six elements. 100/6 = 16.6666666666667 and so on. It doesn't divide nicely. I see you rounded down to 16.5, but that'll only make 99%. I've never had good luck with factions of percent. Could you ,aybe reduce your bottom nav to 5 elements for an even 20%?
You could also try using a sticky footer and relative positioning, like I did here.
HTML:

Testing

Testing

Testing

Testing

Testing

Testing

Testing

Testing

Testing

CSS:
html, body {
  width: 100%;
  height: 100%;
  background-color: #333333;
  position: relative;
}

#wrapper {
  min-height: 100%
  position: relative;
}

nav {
  width: 100%
}

nav li {
  display: block;
  background-color: #222222;
  width: 25%;
  float: left;
}

footer {
  position: absolute;
  bottom: 0;
  width: 100%;
}

footer li {
  display: block;
  float: left;
  width: 20%;
  background-color: #cccccc;
 }

Hope that helps.

A: In my browser I don't see any horizontal or vertical scroll bar. However, you can try using standard DOCTYPElike:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml-transitional.dtd">

and add the following at the beginning of your css:
html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, font, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td {
    background: transparent;
    border: 0;
    margin: 0;
    padding: 0;
    vertical-align: baseline;
}


text:
Q: What happens if we use async reset block with sync reset? Consider that I have a common verilog module that I want to be exported to 2 different kinds of designs - one on sync reset and the other on async reset.
What would be the right way to code an always block within this common module so that it works fine in both kinds of designs? I am thinking we can use the async reset block like this -
always @(posedge clk or negedge reset_) begin
  if(!reset_) temp <= 'd0;
  else <do something>
end

If i use sync reset then in async reset designs i have a problem if clocks start much later than reset assertion-deassertion so the required reset can be completely missed.
In sync reset we know the posedge of clk and negedge of reset_ will coincide always, so is there any issue with that?

A: You could do this:
always @(posedge clk or negedge async_reset) begin
  if(!async_reset)
    temp <= 'd0;
  else
    if (!sync_reset)
      temp <= 'd0;
    else
      <do something>
end

and then tie one or the other reset to INACTIVE (1'b1 in this case). If you're synthesising to an FPGA, I would imagine it would cost you nothing in area or speed. If you're synthesising to an IC, then I'd check what the synthesiser does with it.


text:
Q: Powershell: Multipart RAR extraction I have a folder with n number of rar files with some having .part01,.part02 as they are divided. the code i am currently using is given below.
$Rars = Get-ChildItem -path 'c:\demopath' -filter "*.rar"
$Destination = 'c:\demopath'
$WinRar = "C:\Program Files\WinRAR\WinRAR.exe"

foreach ($rar in $Rars)
{
&$Winrar x -y $rar.FullName $Destination
Get-Process winrar | Wait-Process
}

This code is running many times to extract same file again and again by the number of parts it has. example if the file is having 3 parts it will get extract same file 3 times (overwriting the previously extracted file). for single rar file there is no issue. if i only give "x" then it is giving popups for file already exists. need a solution which will not give any popups and extract only if same name file is not there in the directory.
can someone help me to fix this issue?

A: solved the issue with using unrar freeware in winrar directory.
all i needed was to use the "-o-" parameter to stop overwriting the existing extracted file. same command will work with winrar.exe as well
&$UnRAR x -o- $rar.FullName $Destination


text:
Q: Unable to find the Entity relative to a proxy I have a simple Request on a Contact table.
use App\Entity\Contact;
...
        $contact = $this->getUser()->getContact();
        $form = $this->createForm(ParentContactType::class,$contact);
        $form->handleRequest($request);

But when Handling the form, Symfony throws following Exception:
Unable to find the object manager associated with an entity of class "Proxies\__CG__\App\Entity\Contact".
The contact Class is a normal one,
<?php

namespace App\Entity;

use App\Repository\ContactRepository;
use Doctrine\ORM\Mapping as ORM;
use ApiPlatform\Core\Annotation\ApiResource;

/**
 * @ORM\Entity(repositoryClass=ContactRepository::class)
 */
#[ApiResource]
class Contact
{
    const FIRST_CONTACT = "Contact principal";
    const SECOND_CONTACT = "Second contact";
    const THIRD_CONTACT = "Troisième contact";

    public function __construct(){
    }

    /**
     * @ORM\Id
     * @ORM\GeneratedValue
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=100, nullable=true)
     */
    private $type;

    /**
     * @ORM\Column(type="string", length=3, nullable=true)
     */
    private $gender;
+ getter and setter

It used to be working fine, but I do not know how to debug the issue.
Any help would be great.


text:
Q: How to write the content in MS Excel 2007? Consider I have a Excel sheet and when I (typed the data in the A1 cell that
will automatically load on the Cell B1
How can I do that in the Microsoft Excel 2007?.. Please give a solution for that.. Thanks in advance..

A: Try typing =A1 in your B1 cell.


text:
Q: How can I change the icon of an application in the Unity launcher? I'm trying to change the icon of a specific application (Pidgin) in my Ubuntu 11.10 Unity launcher. I have tried searching in the options and in the Compiz settings but could locate no option for changing individual icons.
I can change the theme but that's not what I want.
I am willing to edit configuration files to get this change. It doesn't have to be a UI solution.

A: For Ubuntu 12.04

In addition to the excellent answer given by itnet7, I would like to add that in Ubuntu 12.04 I had to also add ~/.local/usr/applications/icons/hicolor/64x64/apps in order for Unity to see the icon.
To resize your custom icon, you can use the excellent imagemagick package.
sudo apt-get install imagemagick

Then run the command mogrify -resize 64x64! myImage.png in order to get your custom icons nicely scaled down to the desired resolutions.
If you run the command below after creating the desktop icon and locked the application to your launcher, it will update unity without a need for a reboot.
unity --replace &

as described here:
application locked to launcher without icon

A: For Ubuntu 11.10

The first thing you would need to do is take a .png icon file that you would like to use and copy it to the respective ~/.local/share/icons/hicolor/ directory. This will contain the following directories (which are the dimensions of the icons) : 16x16/apps/ 32x32/apps/ 48x48/apps/
I downloaded a free 16x16 free icon sampler and picked a 16x16 icon called Alien.png
I took the Alien.png file and copied it to ~/.local/share/icons/hicolor/16x16/apps, When you copy yours, you can do that through either the GUI or terminal.
From there you would need do the following in a terminal (you may need sudo to copy this over):
cp /usr/share/applications/pidgin.desktop ~/.local/share/applications/

Next edit the pidgin.desktop file:
vi ~/.local/share/applications/pidgin.desktop

Look for the line that says:
Icon=pidgin

This will need to change to the new icon name without the .png prefix...
Icon=Alien

Save your changes... Then logout and log back in.
Please let me know if this helps or if you need more assistance.

A: *

*Install Main Menu (AKA Alacarte) alacarte

*Open Main Menu

*Click on a program and select Properties in the right menu.

*Click on the icon

*Browse for your new icon and click Open

*Close your programs properties

*Close Main Menu
No logging out or reboot required ;)

A: For Ubuntu 14.04
In order to link an icon with a certain application that could be placed on the launcher, do the following on the command line:
Take e.g. an application called alpha_app with its icon alpha_app.png:

*

*execute:
 sudo cp alpha_app.png /usr/share/pixmaps/

The above command copies your icon with file name alpha_app.png to the appropriate folder.

*Execute:
 sudo gedit /usr/local/share/applications/alpha_app.desktop

*In gedit, change the name of the icon as follows:
 Icon=alpha_app.png

If the file alpha_app.desktop doesn't exist in /usr/local/share/applications/ or /usr/share/applications, execute locate alpha_app.desktop and copy it there. In the unlikely event that this is unsuccessful, it means that there is no alpha_app.desktop file anywhere in the disk and that you would need to create it yourself.

*Go to the dash and type the name of your application, in our example alpha_app.

*Pick the icon from Dash and move in onto Launcher.
Τέλος! The end!

A: I did this in Ubuntu 14.04.
I wanted to give a decent launcher icon to the "Dolphin" file manager (I wanted a dolphin for Dolphin).
I dread using complicated program and system file edits, because it is easy to mess up things. I like to keep it simple. So, instead of all these programming acrobatics ...

*

*I prepared my dolphin picture.
Best to use a picture with a transparent background (typically a png), because the desktop background will show through it nicely (it won't be in its isolated own rectangle). As for size, my picture's file size is about 200 kB with a dimension of about 560x640 pixels. This size matches the other icons nicely.
So, I had this picture ready in the normal "Pictures" folder.

*Then I typed into Terminal:
sudo nautilus /usr/share/applications

enter, and the panel with your applications comes up (represented by the current icons)

*Find the application you want to change the launch icon for, right click on its icon, then click on its "properties"

*At the top left of the properties panel you will see the current launch icon that you want to change to your own choice

*Now just left-click on that icon in the top left corner of the properties panel, and a new panel opens that asks you to select a custom icon to replace the old one with

*Find your prepared picture (it is like in a file manager), and select it

*Your selected new icon appears in the properties panel

*For the new icon to start showing among the launch icons, you need to restart your PC, and lo behold, there's your custom icon!

A: The way that I did it was go to /usr/share/applications/<whatever app your looking for> then right click to properties click on the icon on the left and select the image that you want to be the icon.
You will have to sudo nautilus to edit the icon. Then just exit and search the program in Unity and it will show up with the selected icon.

A: For Ubuntu 12.10

The directory that contains the following directories (which are the dimensions of the icons) has been changed to:

~/.local/share/icons/unity-webapps/apps

and if you do ls :
128  16  192  22  24  32  48  64  96

A: In 13.04 I installed Nemo to get rid of nautilus-for-armless-toy.
I wanted the icon folder-house in the launcher.
I opened ~/.local/share/applications/nemo.desktop with gedit to have a look, and found a line
icon=folder

(no path, no extension ???)
I tried searching in /usr/share/ for the usual default icon of nautilus which appeared to be called folder_home.png or .svg, I couldn't decide which. There were a bunch a files with the same name in various folders, so in the end I just changed the line to
icon=folder_home

and after logging out and back in the icon was changed.


text:
Q: How to remove tabindex focus on div click using angular? I have the following code. According to my requirement,

*

*If I press tab from keyboard, then
 element should be focused and (click) event should work - it is working fine currently

*but if I click the same
 element with mouse click, then this
 element should not be focused and (click) event should work - here
 element is focussing on first click only with the current code, don't know why ?
I am not sure what I am doing wrong here, Please help me to fix this issue. Thanks in advance.
Stackblitz
html:
<button>First</button>

Check Focus Out on Click

<button>Second</button>

component.ts:
import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular';
  func(){
    console.log("test message");
  }
}

directive.ts:
import { Directive, ElementRef, Renderer2, HostListener } from '@angular/core';

@Directive({
  selector: '[appDivfocusout]'
})
export class DivfocusoutDirective {

  constructor(private el: ElementRef, private renderer: Renderer2) { }

  @HostListener('click',['$event'])
  onClick(e){
    this.el.nativeElement.style.outline = 'none';
  }
}


text:
Q: How to remove nested object by Id from Formik? I am trying to remove an entire flight item from a nested array. I've tried setFieldvalue. Whenever I find a specific ID, i'd like to remove the entire item from Formik. For some reason the internet is sparse with solutions, even on SO.
console.log("Formik", formik.values.flightsById);
    for (let item in formik.values.flightsById){
      if(item === 'EF_700001132'){
        console.log("it's here: ", item)
        // React.useEffect(() => () => formik.setFieldValue(item, undefined), [])
        //formik.values.flightsById.remove

      }
    }
    console.log("Formik after del: ", formik.values.flightsById);

Console.log() results:

A: Some feedback:

*

*You referred to flightsById as a "nested array", but judging from your screenshot it's an object

*You have the right idea by using setFieldValue() to update flightsById, nice work

*Placing a useEffect inside an if statement will trigger an error because it breaks the rules of hooks

*If you want to completely remove they key EF_700001132 from the flightsById, you will need to clone flightsById except for that key, and then pass it into setFieldValue(). I used the rest operator (...otherFlights) to copy it without the key, but there's plenty of other methods detailed in other SO threads.

Here is an example of deleting a single flight when a button is clicked:
<button
  type="button"
  onClick={() => {
    const { EF_700001132, ...otherFlights } = formik.values.flightsById;
    formik.setFieldValue("flightsById", otherFlights);
  }}
>
  Delete Flight EF_700001132
</button>

Live Demo


text:
Q: How can I track and synchronize releases between products and components I found an odd situation at work and I'm trying to figure out where to start with a solution.
We have a custom hardware/software device which contains multiple boards, each with their own function and flavor of software (CPLD, bootloader, application, etc). Additionally, the device interacts with a specific web app and a PC application.
Each one of these components has a revision history, tracked individually. Particular devices (which of course are all featureless black boxes) potentially have different versions of any and all components, hardware and software- we're still in the prototype and test stages.
What I'd like is some kind of unified version tracking, where I can trace software builds against bugs and feature requests, have a history/schematics for the boards, and- most importantly- what versions of components were tested against which other versions of components. In other words, I know that bootloader version 1 passed test in conjunction with board version A, but was not necessarily tested against version B of the same board, even though it was extant at the time.
Individual rev tracking is relatively easy; we have a handful of developers working different software components. It's tying them together and being able to say that "PRODUCT VERSION 1.0" consists of this bag of components, tested against each other and not much else. That way, when we update, say, the bootloader, I can have it regression tested against the current versions of all other components, label the whole "PRODUCT VERSION 1.1", and know what that snapshot is, even though someone comes out with version 1.4 of the application code the same day.
Ideally I'd like to track revision history separately across all components, along with users being able to log bugs against specific components or against the product as a whole, after which developers can re-assign the bugs to whichever subsystem is appropriate.
Something web-based would be ideal as developers aren't physically colocated.
We're currently using Bugzilla, which is nowhere near up to the task.  I'm looking at Trac, but I'm not sure it's the right tool from the job.  It seems like there are a lot of source control systems, a lot of revision history systems, and a few project management systems out there, but I haven't found anything that handles everything I need.
It may sound more complicated that it is, but it's pretty complicated when we're down in the trenches with it. There has to be a solution to this!
Any ideas?

A: Have you tried quickbase by intuit? It does a great job at consolidated version tracking and you can add functionality for separate revision history. Trac is good, but lacks the robustness of quickbase (IMHO).


text:
Q: How to get noitemsep with etaremune? I have a document with lots of
\begin{enumerate}[noitemsep]
   \item ...
\end{enumerate}

but want to change that to reverse numbering. Great, the etaremune (funny name ;) ) package does this, but only almost: etaremune doesn't mix with noitemsep:
    \begin{etaremune}[noitemsep]
       \item ...
    \end{etaremune}

throws the error
    ! Package xkeyval Error: `noitemsep' undefined in families `template'.

Any suggestions to reduce the itemsep in an etaremune environment?

A: Ah, I figured it out. Use
    \begin{etaremune}[itemsep=0pt]
       \item ...
    \end{etaremune}


text:
Q: How to test if a weighted graph has a negative cycle I need to create a test that returns true if the graph (directed graph) as a parameter has a cycle of negative weight, false otherwise.
For now I created this. Theoretically should check if there are "generic" cycles, not if there are negative cycles. How can I change the method?
There's an easier or efficient?
//if there is a negative cycle, get out and return
public void bellmanFord(Graph<V, E> graph, V source, V dest) {
    ArrayList<V> vertices = (ArrayList<V>) graph.getVertices();
    HashMap<V, Boolean> visited = new HashMap<V, Boolean>(vertices.size());
    for(V v : vertices) {
        visited.put(v, false);
    }
    boolean cycle = hasNegativeCycle(graph, source, visited, vertices);
    if(cycle == true)
        return;
    else {
        ...
    }

}

public boolean hasNegativeCycle(Graph<V, E> graph, V source, HashMap<V, Boolean> visited, ArrayList<V> vertices) {
    visited.put(source, true);
    for(V u : vertices) {
      ArrayList<V> neigh_u = (ArrayList<V>) graph.getNeighbors(u);
      for(V v : neigh_u) {
        if(visited.get(v) == true || hasNegativeCycle(graph, v, visited, vertices)) {
          return true;
        }
      }
    }
    return false;
}

Thanks

EDIT: As you can see from the method name written on it, I'm trying to implement the algorithm of Bellman-Ford and I'm following this pseudocode:
BellmanFord(Graph G, Vertex start) {
    foreach(Vertex u of G) {
        dist[u] = ∞;
        prev[u] = -1;
    }
    prev[start] = s;
    dist[start] = 0;
    repeat n times {
        foreach(Vertex u of G) {
            foreach(Vertex v near u) {
                if(dist[u] + weigth_uv < dist[v]) {
                    prev[v] = u;
                    dist[v] = dist[u] + weigth_uv;
                }
            }
        }
    }
}

A: You may want to do a BFS traversal of the graph. At each node visit, record the node's unique id (.hashCode() for example, if implemented) into a HashSet. Whenever you are trying to insert an already present element into the hashset, you found a circle.
If you found a circle in say node F, you can count the circle's sum weight by traversing the tree upwards, until you find F again, and summing the weights.
Of course after determining the circle size, and it was positive, you must continue the BFS traversal, but without traversing F's children. If it was negative, return from the function, as you found a negative circle.
Edit: you can also keep track of the current sum weight during the BFS traversal steps, this way you don't have to traverse the tree upwards to calculate the total weight...As your graph is Directed, this method would fit also better...

A: You have to apply Bellman-Ford Algorithm.Wikipedia has proper pseudocode. If you apply this properly your problem will be solved.
function BellmanFord(list vertices, list edges, vertex source)
   ::distance[],predecessor[]

   // This implementation takes in a graph, represented as
   // lists of vertices and edges, and fills two arrays
   // (distance and predecessor) with shortest-path
   // (less cost/distance/metric) information

   // Step 1: initialize graph
   for each vertex v in vertices:
       if v is source then distance[v] := 0
       else distance[v] := inf
       predecessor[v] := null

   // Step 2: relax edges repeatedly
   for i from 1 to size(vertices)-1:
       for each edge (u, v) in Graph with weight w in edges:
           if distance[u] + w < distance[v]:
               distance[v] := distance[u] + w
               predecessor[v] := u

   // Step 3: check for negative-weight cycles
   for each edge (u, v) in Graph with weight w in edges:
       if distance[u] + w < distance[v]:
           error "Graph contains a negative-weight cycle"
   return distance[], predecessor[]