text:
Q: Distinguish view by background colors I want to distinguish the background color of a view but I don't know how to do it. Can anyone help me to accomplish the task.
Below is my DatabaseHelper.java class
public  List<HouseModal> get_Working_Area_Structures_House(int limit, int offset,String searched_Str) {
    if(database == null){
        database = getWritableDatabase();
    }
    List<HouseModal> list_krd= new ArrayList<>();

    String selectQuery = "SELECT DISTINCT\n" +
            "\tWAS.Para_Structure_ID,\n" +
            "\tWAS.Para_Code || '   ' || CAST (WAS.Structure_No AS int) AS Structure_No,\n" +
            "\tST.Family_Count AS Families,\n" +
            "\tFM.Family_Members_Count AS Family_Members, \n" +
            "\t FM.Family_Migration AS Family_Migration\n" +
            "FROM\n" +
            "\t (\n" +
            "\t\t SELECT\n" +
            "\t\t\tP.Para_Code,\n" +
            "\t\t\tPS.Para_Structure_ID,\n" +
            "\t\t\tPS.Structure_No \n" +
            "\t\tFROM\n" +
            "\t\t\tPara_Structure AS PS\n" +
            "\t\tINNER JOIN  Working_Area_Structures AS WAS ON PS.Para_Structure_ID = WAS.Para_Structure_ID\n" +
            "\t\tINNER JOIN  Field_Station_Paras AS P ON PS.Para_ID = P.Para_ID \n" +
            "\t) AS WAS,\n" +
            "\t (\n" +
            "\tSELECT\n" +
            "\t\t\tKH.Para_Structure_ID,\n" +
            "\t\t\tCOUNT(DISTINCT KH.House_Hold_ID) AS Family_Count \n" +
            "\t\tFROM\n" +
            "\t\t\tKhandan_Register_Header AS KH\n" +
            "\t\tLEFT JOIN  Family_Visit_History AS FVH ON KH.House_Hold_ID = FVH.House_Hold_ID \n" +
            "\t\tWHERE\n" +
            "\t\t(FVH.Visit_Status = 0 OR FVH.Visit_Status IS NULL)\n" +
            "\t\t--AND ((date(FVH.Visit_Date) >= (SELECT date(Starting_Date) FROM Working_Cycle WHERE DATE('NOW') BETWEEN date(Starting_Date)AND date(Ending_Date)) AND date(FVH.Visit_Date) <= (SELECT date(Ending_Date) FROM Working_Cycle WHERE DATE('NOW') BETWEEN date(Starting_Date)AND date(Ending_Date))) OR date(FVH.Visit_Date) IS NULL) \n" +
            "\t\t--AND (KH.House_Hold_ID NOT IN (SELECT DISTINCT House_Hold_ID FROM Family_Visit_History WHERE Visit_Status = 1)) \n" +
            "\t\tGROUP BY KH.Para_Structure_ID\n" +
            "\t) AS ST , (\n" +
            "\t\t SELECT\n" +
            "\t\t\tKH.Para_Structure_ID,\n" +
            "\t\t\tCOUNT(\n" +
            "\t\t\t\tDISTINCT KD.Family_Member_ID\n" +
            "\t\t\t) AS Family_Members_Count, \n" +
            "\t\t\tfmr.Family_Migration_ID AS Family_Migration \n" +
            "\t\tFROM\n" +
            "\t\t\tKhandan_Register_Detail AS KD\n" +
            "\t\tINNER JOIN  Khandan_Register_Header AS KH ON KD.House_Hold_ID = KH.House_Hold_ID\n" +
            "\t\tLEFT JOIN  Family_Visit_History AS FVH ON KH.House_Hold_ID = FVH.House_Hold_ID \n" +
            "\t\tleft join Family_Migration_Register as fmr on KH.House_Hold_ID = fmr.House_Hold_ID \n" +
            "\t\tWHERE\n" +
            "\t\t\t(\n" +
            "\t\t\t\tFVH.Visit_Status = 0\n" +
            "\t\t\t\tOR FVH.Visit_Status IS NULL\n" +
            "\t\t\t) \n" +
            "\t\t--AND ((date(FVH.Visit_Date) >= (SELECT date(Starting_Date)FROM Working_Cycle WHERE DATE('NOW') BETWEEN date(Starting_Date)AND date(Ending_Date)) \n" +
            "\t\t--AND date(FVH.Visit_Date) <= (SELECT date(Ending_Date) FROM Working_Cycle WHERE DATE('NOW') BETWEEN date(Starting_Date)AND date(Ending_Date))) OR date(FVH.Visit_Date) IS NULL) \n" +
            "\t\tAND (KH.House_Hold_ID NOT IN (SELECT DISTINCT House_Hold_ID FROM Family_Visit_History WHERE Visit_Status = 1 )) \n" +
            "\t\tGROUP BY\n" +
            "\t\t\tKH.Para_Structure_ID \n" +
            "\t) AS FM \n" +
            "WHERE\n" +
            "\tWAS.Para_Structure_ID = ST.Para_Structure_ID \n" +
            "\n" +
            "AND WAS.Para_Structure_ID = FM.Para_Structure_ID\n" +
            "\n" +
            "AND ST.Para_Structure_ID = FM.Para_Structure_ID\n" +
            "\n";
    if (!searched_Str.trim().equals("null") && !searched_Str.trim().equals(""))
    {
        selectQuery += " And WAS.Structure_No like '%"+searched_Str+"%'";
    }
    selectQuery += " ORDER BY WAS.Para_Code, Cast(WAS.Structure_No As int) limit "+limit+" offset "+offset;

    try{
        Cursor cursor = database.rawQuery(selectQuery, null);
        if (cursor.getCount() > 0) {
            if (cursor != null && cursor.moveToFirst()) {
                do {
                    HouseModal dkrd = new HouseModal();
                    dkrd.setStructureID(cursor.getInt(0));
                    dkrd.setStructureNo(cursor.getString(1));
                    dkrd.setFamilies(cursor.getInt(2));
                    dkrd.setMembers(cursor.getInt(3));
                    dkrd.setFamilyMigrationID(cursor.getString(4));
                    list_krd.add(dkrd);
                } while (cursor.moveToNext());
            }
        }
        cursor.close();
    }
    catch (Exception e){
        e.printStackTrace();
    }
    return list_krd;
}

This is my modal class
package pk.softech.sukh.modal;

public class HouseModal {

    private int structureID, families,members;
    private String migrationID;

    private String houseHoldID;
    private String structureNo ;

    public String getFamilyMigrationID() {
        return migrationID;
    }

    public void setFamilyMigrationID(String newMigrationID) {
        this.migrationID = newMigrationID;
    }

    public String getStructureNo() {
        return structureNo;
    }

    public void setStructureNo(String structureNo) {
        this.structureNo = structureNo;
    }

    public int getStructureID() {
        return structureID;
    }

    public void setStructureID(int structureID) {
        this.structureID = structureID;
    }

    public int getFamilies() {
        return families;
    }

    public void setFamilies(int families) {
        this.families = families;
    }

    public int getMembers() {
        return members;
    }

    public void setMembers(int members) {
        this.members = members;
    }

    public String getHouseHoldID() {
        return houseHoldID;
    }

    public void setHouseHoldID(String houseHoldID) {
        this.houseHoldID = houseHoldID;
    }
}

below is my adapter code, I'm getting data in a getter "getFamilyMigrationID". So the scenario is if this getter has a "null value" it will give a light gray background or in else condition if this getter has a value so it will give a light yellow background. I'm doing a mistake but don't know what the mistake is?
package pk.softech.sukh.adapter;

import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import java.util.List;

import pk.softech.sukh.R;
import pk.softech.sukh.modal.HouseModal;

public class HouseAdapter extends ArrayAdapter<HouseModal> {

    public HouseAdapter(Context context,List<HouseModal> items) {
        super(context,R.layout.view_house_item,items);
    }

    class ViewHolder{
        TextView totalAfrad,totalKhandan,structureID,migratedFamilies;
    }

    @Override
    public View getView(int position, View view, ViewGroup parent) {
        ViewHolder holder;

        HouseModal item = getItem(position);
        if(view == null){
            view = LayoutInflater.from(getContext()).inflate(R.layout.view_house_item,null);
            holder = new ViewHolder();
            holder.structureID = (TextView) view.findViewById(R.id.structureID);
            holder.totalAfrad = (TextView) view.findViewById(R.id.totalAfrad);
            holder.totalKhandan = (TextView) view.findViewById(R.id.totalKhandan);
            holder.migratedFamilies = (TextView) view.findViewById(R.id.families);

            if(item.getFamilyMigrationID() == null){
                view.findViewById(R.id.structureID).setBackgroundColor(Color.parseColor("#CFD8DC")); //light gray
            } else {
                view.findViewById(R.id.structureID).setBackgroundColor(Color.parseColor("#FDFDE9")); //light yellow
            }

            view.setTag(holder);
        }
        else{
            holder = (ViewHolder) view.getTag();
        }

        holder.structureID.setText(String.valueOf(item.getStructureNo()));
        holder.totalKhandan.setText(String.valueOf(item.getFamilies()));
        holder.totalAfrad.setText(String.valueOf(item.getMembers()));
        holder.migratedFamilies.setText(String.valueOf(item.getFamilyMigrationID()));

        return view;
    }

}

A: if your item is null how it is possible to change the color of it or how even possible to check it?

null is null.

you should Check Null for safety of Crashes not changing the color.
if you want Change color you should get a specific field from your database that shows this column has no value in it or its empty.
then you can check for its Color

A: Put
if(holder.structureID.isEmpty(){
                view.findViewById(R.id.structureID).setBackgroundColor(Color.parseColor("#CFD8DC")); //light gray
            } else {
                view.findViewById(R.id.structureID).setBackgroundColor(Color.parseColor("#FDFDE9")); //light yellow
            }

Outside of the if(view == null) and into the else block, so that it gets the change when it is redrawn because recyclerview will reuse the cells and anything that needs to be changed (text, values, colours) will need to be re-applied also
Edit : just to clarify - you will need your previous "colour changing if statement" in the if block still due to the way you have set it out, if you change the getView() method around so that you are only setting values for the viewHolder object in your if/else statement and then below that you change all the values you require on the view itself it will end up being cleaner and easier to read


text:
Q: What is included in MEF 2? I see work is still going on with new features on MEF (MEF Codeplex site) and they are shipping MEF 2 beta releases, however they do not have any decent documentation on what the new features are experimenting/exploring/building?
So, what are the new features (in a little bit of detail please, a sentance or two for each would be great) that are part of MEF 2?

A: I know one big feature is support for open generics.  This allows us to import parts that look like this:
IRepository<T>
{

}

using an import that looks like this
[Import(typeof(IRepository<>))]
private IRepository<Users> userRepository;

A: From the preview documentation

*

*Support for generic types.

*Convention-based programming model that enables you to create parts based on naming conventions rather than attributes.

*Multiple scopes.

redpajama_set_name: RedPajamaStackExchange


text:
Q: open source tool to generate Javadocs through Maven2 with automatic UML diagrams like ydoc I want to generate javadocs through maven's site generation plugin and I want to have automatic UML diagrams created and embedded in the javadoc.
The statsvn project uses yDoc to generate their UML documentation but I think they're using Maven1. yDoc is a commercial shareware product, so I'm unsure how the open source statsvn project integrates with it (or if there is a free version to use for javadoc generation).
Example svnstat yDoc javadoc:
ChurnPageMaker.java
svnstat includes ydoc as a plugin to their Maven1 report generation:
project.xml
    <reports>
            <report>maven-ydoc-plugin</report>
 ...
    </reports>

The yDoc documentation says you can use Maven2's custom javadoc doclet approach (but I can't figure out where to download yDoc or if it's free). It seems like the statsvn project is using yDoc so I'm guessing it's free?
Are there any other open source Javadoc doclet generators that integrate with Maven2 to generate javadocs with embedded class diagrams.

A: It looks like the APIViz doclet support Maven2 javadoc plugin to generate class diagrams in javadoc.
  <reporting>
    ...
    <plugins>
      ...
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-javadoc-plugin</artifactId>
        <version>2.5</version>
        <configuration>
          <doclet>org.jboss.apiviz.APIviz</doclet>
          <docletArtifact>
            <groupId>org.jboss.apiviz</groupId>
            <artifactId>apiviz</artifactId>
            <version>1.3.0.GA</version>
          </docletArtifact>
          <useStandardDocletOptions>true</useStandardDocletOptions>
          <charset>UTF-8</charset>
          <encoding>UTF-8</encoding>
          <docencoding>UTF-8</docencoding>
          <breakiterator>true</breakiterator>
          <version>true</version>
          <author>true</author>
          <keywords>true</keywords>
          <additionalparam>
            -sourceclasspath ${project.build.outputDirectory}
          </additionalparam>
        </configuration>
      </plugin>
      ...
    </plugins>
    ...
  </reporting>

A: For Maven 2, have a look at http://maven.apache.org/plugins/maven-javadoc-plugin/examples/alternate-doclet.html which describes how to include UmlGraph diagrams in the javadoc of your code (requires Graphviz binary on the PATH). Below a sample POM using UmlGraph as alternate doclet:
<project>
  ...
  <reporting> (or <build>)
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-javadoc-plugin</artifactId>
        <version>2.6.1</version>
        <configuration>
          <doclet>org.umlgraph.doclet.UmlGraphDoc</doclet>
          <!-- <docletPath>/path/to/UmlGraph.jar</docletPath> -->
          <docletArtifact>
            <groupId>org.umlgraph</groupId>
            <artifactId>doclet</artifactId>
            <version>5.1</version>
          </docletArtifact>
          <additionalparam>-views</additionalparam>
          <useStandardDocletOptions>true</useStandardDocletOptions>
        </configuration>
      </plugin>
    ...
    </plugins>
  </reporting> (or </build>)
  ...
</project>

A: I know you want java docs, but have you checked out Doxygen? Perhaps it can do what you want. Here's a question comparing Javadocs and Doxygen.


text:
Q: How to add Series to DataFrame has custom indexes in it I have the following DataFrame:
purchase_1 = pd.Series({'Name': 'Chris',
                        'Item Purchased': 'Dog Food',
                        'Cost': 22.50})
purchase_2 = pd.Series({'Name': 'Kevyn',
                        'Item Purchased': 'Kitty Litter',
                        'Cost': 2.50})
purchase_3 = pd.Series({'Name': 'Vinod',
                        'Item Purchased': 'Bird Seed',
                        'Cost': 5.00})
df = pd.DataFrame([purchase_1, purchase_2, purchase_3], index=['Store 1', 'Store 1', 'Store 2'])
df['Location'] = df.index
df = df.set_index(['Location', 'Name'])
df2 = df.copy()
print(df2)

                Cost Item Purchased
Location Name
Store 1  Chris  22.5       Dog Food
         Kevyn   2.5   Kitty Litter
Store 2  Vinod   5.0      Bird Seed

Then I have the following Series:
purchase_4 = pd.Series({'Name': 'Kevyn',
                        'Item Purchased': 'Kitty Food',
                        'Cost': 3.00,
                        'Location': 'Store 2'})

When I try to add this Series to my DF it works but has bunch of NaNs:
df2 = df2.append(purchase_4, ignore_index=True)

   Cost Item Purchased Location   Name
0  22.5       Dog Food      NaN    NaN
1   2.5   Kitty Litter      NaN    NaN
2   5.0      Bird Seed      NaN    NaN
3   3.0     Kitty Food  Store 2  Kevyn

A: You can use concat:
df2 = pd.concat([df2, purchase_4.to_frame().T.set_index(df.index.names)])
print (df2)
                Cost Item Purchased
Location Name
Store 1  Chris  22.5       Dog Food
         Kevyn   2.5   Kitty Litter
Store 2  Vinod     5      Bird Seed
         Kevyn     3     Kitty Food

Or loc, for set Multiindex use ():
df2.loc[(purchase_4['Location'], purchase_4['Name']),:] = purchase_4
print (df2)
                Cost Item Purchased
Location Name
Store 1  Chris  22.5       Dog Food
         Kevyn   2.5   Kitty Litter
Store 2  Vinod   5.0      Bird Seed
         Kevyn   3.0     Kitty Food

A: Alternative solution:
In [237]: df.append(purchase_4.to_frame().T.set_index(df.index.names))
Out[237]:
                Cost Item Purchased
Location Name
Store 1  Chris  22.5       Dog Food
         Kevyn   2.5   Kitty Litter
Store 2  Vinod     5      Bird Seed
         Kevyn     3     Kitty Food

A: df = df.set_index([df.index, 'Name'])
df.index.names = ['Location', 'Name']
df = df.append(pd.Series(data={'Cost': 3.00, 'Item Purchased': 'Kitty Food'}, name=('Store 2', 'Kevyn')))
df


text:
Q: Decomposition of polynomials like $1+x^4$ What is the "trick" to get from $1+x^4$ to $$(x^2-\sqrt{2}x+1)(x^2+\sqrt{2}x+1)?$$ Of course I can calculate it's true, but I don't understand what steps to take to get from one to the other.
Next to this specific question, I am also looking for the general rules for such decompositions?
Cheers!

A: Hint: It is $$1+x^4=(x^2+1)^2-2x^2$$ and then use $$a^2-b^2=(a-b)(a+b)$$

A: Use the binomial formula $x^4+1=(x^2+i)(x^2-i)$ and compute the roots of the factors
$$x_{1,2} = \pm \tfrac{1}{2}\sqrt{2}(1+i)$$
$$x_{3,4} = \pm \tfrac{1}{2}\sqrt{2}(1-i)$$
Now multiply
$$(x-x_1)(x-x_3) = x^2 - \sqrt{2}x +1$$
$$(x-x_2)(x-x_4) = x^2 + \sqrt{2}x +1$$

A: $$x^4+1= \underbrace{x^4+\color{red}{2x^2}+1}-\color{red}{2x^2} = (x^2+1)^2-2x^2=...$$

A: There is a general procedure to solve quartic equations. The first step is to depress the polynomial, i.e. translate the variable to cancel the cubic term. Your polynomial is already in depressed form.
Then you try a factorization of the form
$$(x^2-ax+b)(x^2+ax+c)=x^4+(-a^2+b+c)x^2+(ab-ac)x+bc$$
which is built to yield a depressed polynomial.
By identification with $x^4+1$,
$$a^2=b+c,\\b=c,\\bc=1,$$
which easily gives
$$a=\sqrt2,\\b=c=1.$$

In more general cases (more nonzero coefficients), the procedure leads to a cubic equation, for which there is also a systematic procedure. More at https://en.wikipedia.org/wiki/Quartic_function#Solution_methods.

A: By the factor theorem, the linear of $x^n + 1$ are of the form $x - a$, where $a$ is one of the $n$th roots of $-1$ in $\mathbb{C}$. These form complex conjugate pairs, and when two such paired factors multiply together, we get an irreducible quadratic over $\mathbb{R}$.
We know that $-1 = e^{i\pi}$, which makes the four roots of unity
\begin{align*}
e^{i\frac{\pi}{4}} &= \cos\left(-\frac{3\pi}{4}\right) + i\sin\left(-\frac{3\pi}{4}\right) = -\frac{1}{\sqrt{2}} - \frac{i}{\sqrt{2}} \\
e^{i\frac{\pi}{4}} &= \cos\left(-\frac{\pi}{4}\right) + i\sin\left(-\frac{\pi}{4}\right) = \frac{1}{\sqrt{2}} - \frac{i}{\sqrt{2}} \\
e^{i\frac{\pi}{4}} &= \cos\left(\frac{\pi}{4}\right) + i\sin\left(\frac{\pi}{4}\right) = \frac{1}{\sqrt{2}} + \frac{i}{\sqrt{2}} \\
e^{i\frac{3\pi}{4}} &= \cos\left(\frac{3\pi}{4}\right) + i\sin\left(\frac{3\pi}{4}\right) = -\frac{1}{\sqrt{2}} + \frac{i}{\sqrt{2}}.
\end{align*}
Thus, we have
\begin{align*}
x^4 + 1 &= \left(x + \frac{1}{\sqrt{2}} + \frac{i}{\sqrt{2}}\right)\left(x + \frac{1}{\sqrt{2}} - \frac{i}{\sqrt{2}}\right)\left(x - \frac{1}{\sqrt{2}} + \frac{i}{\sqrt{2}}\right)\left(x - \frac{1}{\sqrt{2}} - \frac{i}{\sqrt{2}}\right) \\
&= \left(\left(x + \frac{1}{\sqrt{2}}\right)^2 + \frac{1}{2}\right)\left(\left(x - \frac{1}{\sqrt{2}}\right)^2 + \frac{1}{2}\right) \\
&= (x^2 + \sqrt{2}x + 1)(x^2 - \sqrt{2}x + 1).
\end{align*}
Using similar methods, we can also factorise $x^{2n} + 1$. For example,
$$x^6 + 1 = (x^2 + \sqrt{3}x + 1)(x^2 + 1)(x^2 - \sqrt{3}x + 1).$$

A: You are trying to "complete the square" but in a different way. Usually, when you complete the square, you make sure that your square term "absorbs" the highest order term and the second highest order term. For example, you would write something like
$$ x^4+3x^2+1 = (x^2+3/2)^2 - 5/4$$
where outside the squared term, you only have the constant, which is (hopefully) negative so you can use $a^2-b^2=(a+b)(a-b)$. Here, however, there's no second highest order ($x^2$) term to "absorb" into the square, so you "absorb" the constant instead so that the $x^2$ term remains outside the square:
$$ x^4+1 = (x^2+1)^2-2x^2 $$
from which the conclusion follows. Note that we can technically write
$$ x^2+1 = (x+1)^2-2x = (x+\sqrt 2x^{-1/2}+1)(x-\sqrt2x^{-1/2}+1)$$
too, but since we have a noninteger power, people usually resolve to just saying that $x^2+1$ is not factorisable.


text:
Q: Getting Galvanic Skin Response from Microsoft Band via Android SDK I'm developing an Android-Band app using the Microsoft SDK in which is not mentioned the possibility to obtain the GSR value (even if the Band includes this sensor). Beside, searching on web, i've found an app (running on Windows Phone) able to show this value, "unlocking" all the "hidden" values of Band's sensors. Is there a chance to achieve a similar result on Android devices?
Link to WP app: http://www.windowsphone.com/en-us/store/app/band-sensor-monitor/68f97b41-de2f-4579-a473-5d476a5c5196
Thank you in advice and sorry for my bad English. I'm new here (even though i've been lurking on this site for a very long time :P)

A: A GSR not exposed by the SDK. You can add feature requests for future versions of the SDK at: http://microsofthealth.uservoice.com/

A: GSR support was included in October update of SDK (https://developer.microsoftband.com/bandSDK) but only for Band 2

Microsoft Band SDK Release Notes
October 2015: Band SDK update for Windows Phone, Windows, iOS, and
  Android. New features:

*

*Works with both Microsoft Band and Microsoft Band 2.

*Introduces 5 new
  sensors for Microsoft Band 2.

According to change-list those "5 new sensors" are:

*

*MSBSensorAltimeterData

*MSBSensorAmbientLightData

*MSBSensorBarometerData

*MSBSensorGSRData

*MSBSensorRRIntervalData

Here author claims that

The following 5 new sensors are available with the Band 2 only. As a dev, your app will receive an error if you attempt to use these with a Band 1.


text:
Q: Dropzone + Laravel form in one place I have a laravel project which is classifieds site and every advert should have a few photos attached to it. I have made two models with two tables in db one for adverts another for pics, relations are set properly media table has foreign key advert_id Dropzonejs used in form but URL for it pointing to function from MediaController the addition of adverts is managed by AdvertController Now the issue is in these two separate working places when I upload images I don't know advert_id value, but I cannot figure how to make users save advert first and THEN upload images. I don't want to split form on two pages but have no idea how to manipulate user to do what I need.
Here is my code for managing dropzone:
$('.dropzone-stuff').dropzone({
    url: "{{ URL::to('upl') }}",
    paramName: 'file',
    autoProcessQueue: true,
    maxFiles: 5,
    addRemoveLinks: true,
    clickable: true,
    dictDefaultMessage: "{{ trans('custom.drop.dictDefaultMessage') }}",
    dictFallbackMessage: "{{ trans('custom.drop.dictFallbackMessage') }}",
    dictFallbackText: "{{ trans('custom.drop.dictFallbackText') }}",
    dictInvalidFileType: "{{ trans('custom.drop.dictInvalidFileType') }}",
    dictFileTooBig: "{{ trans('custom.drop.dictFileTooBig') }}",
    dictCancelUpload: "{{ trans('custom.drop.dictCancelUpload') }}",
    dictRemoveFile: "{{ trans('custom.drop.dictRemoveFile') }}",
    dictMaxFilesExceeded: "{{ trans('custom.drop.dictMaxFilesExceeded') }}",
});

Here is the portion that manages upload in MediaController:
public function uploadImages()
    {
        if (Sentry::check()) {
            $file = Input::file('file');
            $advert_id = Advert::orderby('id', 'desc')->first()->id;
            $destinationPath = public_path().'/uploads/'.Sentry::getUser()->username.'/';
            $filename = str_random(6);
            $extension =$file->getClientOriginalExtension();
            $filename = $filename.'.'.$extension;
            $upload_success = Input::file('file')->move($destinationPath, $filename);
            if( $upload_success ) {
                return Response::json('success', 200);
            } else {
                return Response::json('error', 400);
            }
        }
    }

Well, I think there would be too much code to post everything here but I will just tell the need - I must have advert ID BEFORE upload to use it for advert_id column in media table.

A: The way I am tackling a similar situation is to create the Entity (Advert) first then have a second page or step for the media you plan to add to it. Since the entity exists - and can be posted to the next page where you upload your media, you can just add this to your script
myDropzone.on("sending", function(file, xhr, formData) {
   formData.append('advert_id', <?php echo $advert_id; ?>);
});

Then in your upl file, you can associate it there.


text:
Q: Register an internal package on Pypi I read somewhere that if you make an internal Python package for proprietary work, you should still register the name on PyPi to avoid potential future dependency issues.
How do I do this without posting my code publicly? This package contains code to be used internally at my work. Should I make an empty python package using the name I want to reserve and upload that to PyPi? And then install my package at work using git instead of PyPi?
Uploading an empty package seems like a silly thing to do that would just annoy other people. But I can't find a way to just register the name.

A: Does not make to much sense to register in the community index a package that is not public for the community.
To reduce chances of future conflicts, I would prefix the package name with something related to your company (I.e: the name or alias). For instance: mycompany-eventualconflictingname.
Eventually, if you want to make the package public, you will need to update your internal clients requirements. But that seems less worrying than having a name conflict.

A: Since the register command is deprecated and not supported anymore, you will have to perform the following steps:

*

*Create a stub setup.py with empty package list, an initial version and the filled out metadata

*Build and upload the package

*Go to PyPI and delete the initial package version you just uploaded

This way, the package name will be reserved to you because you are registered as its owner now, but searching for the package will yield no results and any direct access will result in a 404.
Let's say you want to reserve the package name foo. Steps:

*

*Create a new setup.py stub. Make sure packages list is empty so you don't upload some code by accident:
from setuptools import setup

setup(
    name='foo',
    version='0.0.1',
    description='',
    long_description='',
    url='https://www.example.com',
    author='me',
    author_email='me@example.com',
    packages=[],
    classifiers=['Development Status :: 1 - Planning'],
)

*Build and upload the package:
$ python setup.py bdist_wheel upload
running bdist_wheel
running build
...
running upload
Submitting /tmp/foo/dist/foo-0.0.1-py3-none-any.whl to https://upload.pypi.org/legacy/
Server response (200): OK

*Delete the uploaded wheel: go to the project page https://pypi.python.org/pypi?%3Aaction=pkg_edit&name=foo, where you will find the list of uploaded wheels - select one you uploaded and press Remove.
Now you have reserved the project name, since no one else will be able to upload a package foo unless you give them administrator permissions on PyPI:
$ python setup.py bdist_wheel upload
running bdist_wheel
running build
...
running upload
Submitting /tmp/foo/dist/foo-0.0.2-py3-none-any.whl to https://upload.pypi.org/legacy/
Upload failed (403): The user 'bar' is not allowed to upload to project 'foo'. See https://pypi.org/help#project-name for more information.
error: Upload failed (403): The user 'bar' is not allowed to upload to project 'foo'. See https://pypi.org/help#project-name for more information.

$ twine upload dist/foo-0.0.2-py3-none-any.whl
Uploading distributions to https://upload.pypi.org/legacy/
Uploading foo-0.0.2-py3-none-any.whl
HTTPError: 403 Client Error: The user 'bar' is not allowed to
upload to project 'foo'. See https://pypi.org/help#project-name for
more information. for url: https://upload.pypi.org/legacy/

Any direct access attempts will end in a 404:
$ curl -I https://pypi.python.org/pypi/foo
HTTP/2 404

Installing via pip will fail as expected:
$ pip install foo
Collecting foo
  Could not find a version that satisfies the requirement foo (from versions: )
No matching distribution found for foo

PEP 541
Note that there is a PEP on Package Index Name Retention (PEP 541) that defines unreachable, abandoned, and invalid projects on the package index. In the section Name conflict resolution for active projects, it states:

None of the following qualify for package name ownership transfer:
...
User A owns a project X outside the Package Index. User B creates a package under the name X on the Index. After some time, User A wants to publish project X on the Index but realizes name is taken. This is true even if User A's project X gains notability and User B's project X is not notable.

So, although the PEP confirms that no one can take a name of an active project away from you, this is not guaranteed in the case of an inactive project which is a good countermeasure against name squatting. My understanding of this is that if you reserve a name now without developing anything and in the future, an open-source project emerges under that name and gets very popular, you can bet the project owner's rights will be taken away from you.
Also, note that empty packages or packages with no functionality can be qualified as an invalid package and be removed:

A project published on the Package Index meeting ANY of the following is considered invalid and will be removed from the Index:
...

*

*project is name squatting (package has no functionality or is empty);

*project name, description, or content violates the Code of Conduct; or

*project is abusing the Package Index for purposes it was not intended.


text:
Q: Is there any Listener for Media Recorder? Actually i am creating an application which starts recording when user start speaking and
stop recording automatically when user stop speaking.
so is there any way to find if user is speaking or not?
is there any listener for Media Recorder for this?

A: No, AFAIK there are no listeners or intents that would notify your app that sound level has gone above some threshold (e.g. user started talking).
You could use AudioRecord class to record the microphone audio and then analyze it to see the volume. However this would require your app to run at that time.


text:
Q: Aws Glue Crawler is not updating the table after 1st crawl I am adding a new file in parquet format which is created by a Glue Databrew in my S3 folder. The new file has the same schema as the previous file. But when I am running the Crawler for the 2nd time it is neither updating the table nor creating a new one in the data catalog. Also when I am crawling both the files together, both of them are getting added.
Log File is giving the following information:
INFO : Created partitions with values [[New file name]] for table
BENCHMARK : Finished writing to Catalog
I have tried with and without "Create a single schema for each S3 path". But the crawler is not updating the table with the new file. Sooner I will add new files on a daily basis to do my analysis. Any solution?

A: The best way to approach this issue in my opinion is to use AWS DataBrew output to Data Catalog directly. Data Catalog can be updated either by the crawler or by DataBrew directly but the recommended practice is that you employ any one of those mechanisms not both.
Can you try running the job with output as your data catalog and let Databrew manage your catalog? It should update your catalog table with right data/files.


text:
Q: how to query with a date referencing a range of dates in google sheets here is the link>
https://docs.google.com/a/auind.com/spreadsheets/d/1ZnV0uNwM-uS_kK3CQwx-EGy9c9PAK4enCzSIv0bCva0/edit
i want rows from sheet one to transfer over to sheet two but only show me the rows with column L with a value between 1-150000 and with Col C with a date between d3 and d4.
d3 and d4 change everyday so thus the data being imported over would change accordingly.
te formula should go into a6 on sheet two. since rows 1-5 on both sheets are frozen headers.

A: I would use FILTER function in this special case. Try this for the A6 cell on sheet two:
=FILTER('Foreclosure Leads'!A6:L,'Foreclosure Leads'!L6:L>=1,'Foreclosure Leads'!L6:L<=150000,'Foreclosure Leads'!C6:C>='Foreclosure Leads'!D3,'Foreclosure Leads'!C6:C<='Foreclosure Leads'!D4)
This does the following:

*

*'Foreclosure Leads'!A6:L - First it tells that we are investigating the rows from 'Foreclosure Leads' worksheet. First row is the 6th, the last is undefined. The columbs from A to L will be copied.

*Then there are the conditions:

*

*'Foreclosure Leads'!L6:L>=1 - The value in the L cell should be greater or equal to 1

*'Foreclosure Leads'!L6:L<=150000 - The value in the L cell should be less or equal to 150000

*'Foreclosure Leads'!C6:C>='Foreclosure Leads'!D3 - The value in the C cell should be greater or equal to the date in the D3 cell (which is today)

*'Foreclosure Leads'!C6:C<='Foreclosure Leads'!D4 - The value in the C cell should be less or equal to the date in the D4 cell

Hope it helps.


text:
Q: Find all locked files in TFS I would like to see all files that are locked.  so far, I've only found to use tf.exe status and look for anything with '!' because they are not reported as "lock, edit" as they are in the UI.  Any ideas?  thanks.

A: If you are trying to use TFS Sidekicks, and can't figure out how, it is under Tools, Team Foundation Sidekicks, Status Sidekick.  You will need to expand that window, but you will then be able to search for locks for a username.

A: I don't think this is possible using tf.exe or even tfpt.exe (The Power Tool command line).  You'll need to look through the pending changesets for changes that are locks.  You could do this in powershell using the Power Tool commandlets or you could do it using the following bit of .NET code that exercises the TFS API:
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.VersionControl.Client;

namespace TfsApiExample
{
  class Program
  {
    static void Main(string[] args)
    {
      GetLockedFiles("http://tfsserver:8080","$/TeamProject");
    }

    private static void GetLockedFiles(string serverUrl, string serverPath)
    {
      TeamFoundationServer tfs = new TeamFoundationServer(serverUrl);
      VersionControlServer vcServer = (VersionControlServer)tfs.GetService(typeof(VersionControlServer));

      // Search for pending sets for all users in all
      // workspaces under the passed path.
      PendingSet[] pendingSets = vcServer.QueryPendingSets(
          new string[] { serverPath },
          RecursionType.Full,
          null,
          null);

      Console.WriteLine(
          "Found {0} pending sets under {1}. Searching for Locks...",
          pendingSets.Length,
          serverPath);

      foreach (PendingSet changeset in pendingSets)
      {
        foreach(PendingChange change in changeset.PendingChanges)
        {
          if (change.IsLock)
          {
            // We have a lock, display details about it.
            Console.WriteLine(
                "{0} : Locked for {1} by {2}",
                change.ServerItem,
                change.LockLevelName,
                changeset.OwnerName);
          }
        }
      }

    }
  }
}

A: from your command prompt
>powershell

Then from powershell do:
PS > tf info * -recursive | &{
 begin{
  $out=@{}
  $prefix = "loc"
 }
 process{
  if ($_ -match "Local information"){
   if ($out.Count -gt 0) {
    [pscustomobject]$out
    $out=@{}
    $prefix = "loc"
   }
  } ElseIf ($_ -match "Server information"){
   $prefix = "svr"
  } else {
   $parts = $_.Split(':')
   if ($parts.Length -eq 2){
    $out.Add($prefix + $parts[0].Trim(), $parts[1].Trim())
   }
  }
 }
 end{
  if ($out.Count -gt 0) {
   [pscustomobject]$out
  }
 }
} | where {!($_.svrLock -eq 'none')}

A: If you have the power tools installed, it's a one-liner:
tfstatus . -r -user * | % { $_.pendingchanges } | ? { $_.islock } | select -unique serveritem

If you prefer GUIs to scripts, try TFS Sidekicks.

A: I've found a GUI option.

*

*Start Visual Studio

*Open file

*Go to source control

*Then workspaces

*Enter your credentials

*Check show remote workspaces

*Remove all unwanted workspaces

That simple :)


text:
Q: Units of Poynting vector after Fourier transform Suppose the electric and magnetic fields $e(x)$ and $h(x)$ with units $\left[\frac{V}{m}\right]$ and $\left[\frac{A}{m}\right]$ and their Fourier transforms $E(k)$ and $H(k)$ with units $\left[V\right]$ and $\left[A\right]$. Let's assume that the electric and magnetic field are perpendicular to each other, then the Poynting vector becomes $S(x)=e(x)h(x)$. The spatial average Poynting vector $S$ is then defined as the spatial avaverage of $e(x)h(x)$ and can be written in function of the Fourier transforms $E(k)$ and $H(k)$ as
\begin{align}
S &= \lim\limits_{X\to \infty} \frac{1}{X} \int\limits_{-X}^{X} e(x)h(x) dx \\
&= \lim\limits_{X\to \infty} \frac{1}{X} \int\limits_{-X}^{X} \int\limits_{-\infty}^{\infty} E(k)e^{ikx} dk  \int\limits_{-\infty}^{\infty} H(k')e^{ik'x} dk' dx \\
&=  \int\limits_{-\infty}^{\infty}  \int\limits_{-\infty}^{\infty}E(k) H(k')\left[ \lim\limits_{X\to \infty} \frac{1}{X} \int\limits_{-X}^{X}e^{i(k+k')x} dx \right] dk dk'  \\
&=  2 \int\limits_{-\infty}^{\infty}  \int\limits_{-\infty}^{\infty}E(k) H(k')\delta(k'+k) dk dk' \\
&=  2 \int\limits_{-\infty}^{\infty}  E(k) H(-k)dk \\
\end{align}
The question: the unit of the Poynting vector $S$ should be $\left[\frac{VA}{m^2}\right]$ whereas the unit of the final result is $\left[\frac{VA}{m}\right]$. How can this be and how to physically interpret it?
Example: if you know the Fourier transforms $E(k)$ and $H(k)$, and you want to calculate the average Poynting vector $S$, then you will use $S=2 \int\limits_{-\infty}^{\infty}  E(k) H(-k)dk$ but this will give another unit as expected?! So, then you have the wrong result?

A: You haven't written the time average of $S$, you've written the spatial average of $S$,  but that doesn't change your question.  In calculating the average, you are interpreting $e(x)h(x)$ as a density.    Poynting per meter.    The Fourier transform converts this into spatial frequency space, so it becomes a density in spatial frequency space.   That is, the F.T. is Poynting per wave number,  the "amount" of $S$ at each wave number.


text:
Q: QT, including a .dll using QTEditor I am new to using QT so I suppose this has an easy answer but it eludes me. I am porting an application into QT and I went about using the QTEditor to do that. My compiler is MinGw and QT version is 4.7.4 and the OS is Windows 7.
All happens fine in the compiling and linking. It is during running that I get the exit code 0xc0000135 which means a missing dependency. The dependency in question is a C library that I have made myself and is also compiled with mingw so there is no binary compatibility issue. In addition if I put the .dll in the same directory as the resulting executable the application runs fine.
Here is the relevant part of the .pro file:
win32:LIBS += C:\Projects_SourceCode\MyLib\Bin\Release\MyLib.dll
win32:INCLUDEPATH += C:\Projects_SourceCode\MyLib\

What am I missing? This compiles and links fine but later the executable fails to find the "MyLib.dll". I would like to avoid putting it in the path. Isn't there a way from within QTEditor to let the executable know where to search for the .dll?
I am used to using the Codeblocks IDE and from there it's really easy to do such a thing so I assume QTEditor also allows for such an option. Any help would be appreciated.

A: You could add it to PATH variable only for running environment (not in entire system) - you can manipulate run environment in projects screen. Obviously this will work only for debugging, not for production executable. For distributing your app consider putting dll in the same dir as main executable.
Where to look for dll is (at least on windows) not written in executable - the system firstly looks in executable directory, and then looking through PATH directories, so you cannot do it any other way. Where to look for dll is a matter of execution, not compilation, so don't expect qmake project file to help you with it.


text:
Q: Apt upgrade error: distro-info-data breaks distro-info I'm running a server that has been recently upgraded in place from 16.04 to 18.04. The upgrade has generally been successful, although I am now getting an error relating to the 'distro-info-data' and 'distro-info' packages. When I run sudo apt upgrade, I get the following error as part of the output:
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help resolve the situation:

The following packages have unmet dependencies:
 distro-info-data : Breaks: distro-info (< 0.18ubuntu0.18.04.1~) but 0.14ubuntu0.2 is to be installed
E: Broken packages

Full terminal output here:
https://pastebin.com/eEA8N8HQ
Now I should say that during the upgrade, when it came time to ask me if I wanted to remove the obsolete packages, I didn't get a chance to state my intent either way, because when I went to look at the list - and I was keying directly into the server, not using SSH - the keyboard and my state in the upgrade process decided to have a divorce. I couldn't get back to any kind of menu and I just rebooted and hoped 18.04 would come up. It did, and as far as the things the server needs to do to earn its keep, it is still doing them, but I would like to find a way to get this little glitch resolved.
(Well, it might be a little glitch that belies a large underlying problem... Ulp!)
Update: Running sudo dist-upgrade says that 'ubuntu-advantage-tools' has been kept back / not upgraded. This pastebin includes that as well as a grep from /etc/apt/, which indicates a lot of 'xenial' where one ought to see 'bionic': https://pastebin.com/TmCsd7qY
Thanks very much!

A: The problem appears to have been that apt was still tuned into "Xenial" (16.04) sources for everything, when I needed "Bionic" (18.04). I ask about this problem specifically and eventually find a fix here:
Apt: Can't upgrade packages, and system still showing 16.04 / Xenial sources, after upgrade to 18.04 / Bionic


text:
Q: Win Rate calculation - Php and api from leaguepedia i'm using the api from leaguepedia to receive the informations.
So I  have this code to show how many times a champion was picked in a tournament, its working fine, but
right now im trying to show the winrate and i'm having problems,
for example :
Syndra picked 4 Times - Won 3 times - winrate = 75%, thats the result i expect;
Gragas picked 3 Times - Won 3 times - winrate = 100%, thats the result i expect;
what im recieving is :
Syndra picked 4 Times - Won 1 time - winrate = 25%
Gragas picked 3 Times - Won 1 time - winrate = 33,33% , victory is showing 1 for every champion (image)
i know that my problem might be on the "switch / case", but i don't know how to fix
so how can i fix my code to show the properly win rate.
thanks
thats my code
<?php

// $Result is a CURL coming from leaguepedia api
$result = json_decode($file_contents);
$heroPicks = [];
$heroVictory = [];

// Double foreach to access the values from leaguepedia api

foreach ($result as $d) {
    foreach ($d as $data) {
        //$data->title->Team1Picks and

        // $data->title->Team2Picks  is coming from leaguepedia api
        //as a string separated by "," Ex:("Gragas,Shen,Maokai,etc")
        // So i need to explode and merge to an array to count.
        $picks1 = explode(",", $data->title->Team1Picks);
        $picks2 = explode(",", $data->title->Team2Picks);

        $picks = array_merge($picks1, $picks2);

        // this switch is to check if

        // $data->title->Winner == 1 , it means that
        //  $picks1 won the game else == 2 $picks2
        // won the game ($data->title->Winner is coming from api aswell)
        switch ($data->title->Winner) {
            case 1:
                $w = $picks1;
                break;

            case 2:
                $w = $picks2;
                break;
        }
        //foreach to count the times a champion was picked
        foreach ($picks as $pick) {
            $pick = trim($pick);
            if (!array_key_exists($pick, $heroPicks)) {
                $heroPicks[$pick] = 0;
            }
            $heroPicks[$pick] += 1;
        }
        //foreach to count how many times a champion won a game
        foreach ($w as $victory) {
            $victory = trim($victory);
            if (!array_key_exists($victory, $heroVictory)) {
                $heroVictory[$victory] = 0;
            }
            $heroVictory[$victory] += 1;
        }
    }
}
//sorting the arrays
uasort(
    $heroPicks,
    function ($a, $b) {
        return $a - $b;
    }
);

uasort(
    $heroVictory,
    function ($c, $d) {
        return $c - $d;
    }
);

$heroPicks = array_reverse($heroPicks);
$heroVictory = array_reverse($heroVictory);

//foreach to show the results
echo "Best picks:" . PHP_EOL . "
";
foreach ($heroPicks as $heroName => $pickCount) {
    foreach ($heroVictory as $heroVictoryName => $totalVictory) {
        $total = ($totalVictory * 100) / $pickCount;
    }

    echo $heroName . " - " . $pickCount . PHP_EOL . " - Victorys =  " . $totalVictory . " --  winrate :" . $total . "%" . "
";
}

?>

the $result variable  for @bassxzero

A: The outer foreach will loop through all of your heroes that were picked. This is what you want.
The inner foreach is looping through all of your heroes' victories, regardless of the hero the outer loop is currently processing. All the victories are set to 1 because that is how many victories the last hero in your victory array has. This is not what you want.
You don't want a second inner foreach. You just want to lookup the victory stats for the hero currently being processed by the outer foreach.
foreach ($heroPicks as $heroName => $pickCount) {
    $totalVictory = $heroVictory[$heroName] ?? 0;
    $total = ($totalVictory * 100) / $pickCount;

    echo $heroName . " - " . $pickCount . PHP_EOL . " - Victorys =  " . $totalVictory . " --  winrate :" . $total . "%" . "
";
}


text:
Q: outputting an array of links, with no overlapping! When outputting links dynamically, I cannot determine the Y-Pos dynamically.
It will work find if my links are single lined.
link_txt.y = i*20;
this will only work if the links are Single Lined. assuming they are 15px for height + 5 for spacing.
As soon as they are 2 lines, they overlap. I've tried different methods but unable to figure it out.
Any ideas?

A: If by "outputting links" you mean making a vertical list of links as implied by your code snippet, you could try something like this:
var field:TextField;
var prev:TextField;

for( var i:int = 0; i < _fields.length; i++ )
{
   field = _fields[i]
   field.y = prev ? ( prev.y + prev.height ) + padding : 0;
   prev = field;
}

The trick here is that the single line conditional will check to see if there is a valid reference to the prev var. If there it is will set the y position of the current field in the loop to the prev fields y + it's height + padding ( optional ). If there isn't a valid reference to the previous field then it will set the fields y to 0.

A: I believe what you are looking for is TextField's textHeight property.
LiveDocs TextField textHeight

A: var offsetY : Number = 0;
for (var i : int = 0; i < links.length; i++) {
 var link_txt : TextField = TextField(links[i]);
 link_txt.autoSize = TextFieldAutoSize.LEFT;
 link_txt.text = "http://www.google.be";
 link_txt.y = offsetY;
 offsetY += (link_txt.height + 5);
 addChild(link_txt);
}


text:
Q: The TEXT Function in Excel: Date to another date format In previous Excel version, we have dates such as 01.01.2012 that we automatically converted to this format using:
 =TEXT(C1;"yyyy-mm") to get : 2012-01
If I open the document in Excel 2013, I get this: yyyy-00.
Does anyone know where the error lies.  I have tried many different solutions to fix it , but cannot find it!
Thank you for any help:)

A: In some languages mm gives minutes but MM gives months, and you need yyyy to change too, so in German you would need this:
=TEXT(C1;"jjjj-MM")
Once you work out which format works in TEXT function I'd suggest that you use cell formatting rather than TEXT function, e.g. if you use just =C1 and then custom format with "jjjj-MM", or whatever works, then in future that will automatically update if regional settings are changed - TEXT function won't update


text:
Q: What is it called when your boss pretend to ask you to do a task? For example, they ask:

Would you like to do x?

When actually they want you to do x.
Or ask you:

Do you agree with this?

and expect you to obey

A: Asking someone to do something you could otherwise demand they do, is a standard way of telling someone to do something.  As FumbleFingers suggests in his comment, we call this politeness. It's a cultural thing.
You can demand much more from a person when you state your demand as question.  When stating a demand as a question you also leave the door open for a response of No I can't do that.  I have an appointment tomorrow. So not only is it polite from a cultural standpoint, it is polite from a practical standpoint.

A: You could express this using scare quotes (see Wikipedia). For instance:

My boss "asked" me if I "wanted" to do X.

A: As Kate said, being volunteered works well here, although informally, some use  being voluntold to emphasize the fact that it's mandatory.


text:
Q: How to remove spaces between numbers using python? I want to remove spaces between numbers using python. For example,
my_string = "take take , mouth ? 1 unit 1     2  3  1 mg 0 . 1 mg 1 . 1 mg 1 / 2 take . 5 unit and 00 . 5 unit"

My expected output is,
"take take , mouth ? 1 unit 1231 mg 0.1 mg 1.1 mg 1/2 take 0.5 unit and 0.5 unit"

NOTE: one zero was added before the decimal, and one was removed.
I have tried these,
Regex to remove spaces between numbers only
How to remove multiple spaces between numbers using a single re.sub
Thank you in advance.
But these doesn't for single digit numbers separated by spaces.

A: You do need not only removing spaces between digits but also . (dot) and / (slash), this can be accomplished as follows
import re
my_string = "take take , mouth ? 1 unit 1     2  3  1 mg 0 . 1 mg 1 . 1 mg 1 / 2 take . 5 unit and 00 . 5 unit"
no_spaces = re.sub(r'(?<=[0-9./])\s+(?=[0-9./])','',my_string)
print(no_spaces)

output
take take , mouth ? 1 unit 1231 mg 0.1 mg 1.1 mg 1/2 take .5 unit and 00.5 unit

\s denotes any whitespace (i.e. not only space, but also for example \t), you might elect to change it to   if you are sure you will only encounter spaces. (?<=...) and (?=...) are positive lookbehind and positive lookahead assertions, these are zero-length assertion and are used to made sure with only match spaces after digit/dot and before digit/dot, without matching said digits/dots. . when used inside [ and ] is literal . and thus does not require escaping.
To add leading zero before . followed by digit you can use again re.sub with zero-lenght assertion as follows
leading_zeros = re.sub(r'(?<=\s)(?=\.\d+)', '0', no_spaces)
print(leading_zeros)

output
take take , mouth ? 1 unit 1231 mg 0.1 mg 1.1 mg 1/2 take 0.5 unit and 00.5 unit

Explanation: put 0 between whitespace (\s) and literal dot (\.) followed by one or more (+) digits (\d). Observe that . needs escaping when used outside [ and ].
For further discussion of used features read re docs


text:
Q: Function not working in Colorbox On my site http://motiongraphicscollective.com/ i am using colorbox.
When you click on a thumbnail at the home screen i use this script to open my colorbox.
 jQuery.ajax({
        type: 'POST',
        url: 'http://motiongraphicscollective.com/wp-admin/admin-ajax.php',
        data: {
            action: 'myAjax',
            blog_id: blog,
            single_id: single,
        },
        beforeSend:function(data){ // Are not working with dataType:'jsonp'
            $("#"+single+"").find('.project-title').html('');
        },
        success: function(data, textStatus, XMLHttpRequest){
            $("#single-content").html('');
            $("#single-content").append(data);
            $(".single_popup").click();
        },
        error: function(MLHttpRequest, textStatus, errorThrown){
            alert(errorThrown);
        }
    });
    $(document).bind('cbox_closed', function(){
        $("#"+single+"").find('.project-title').html(title);
    });

As you can see i use Ajax to open my colorbox. The function myAjax will fill the div #single content.
function myAjax(){
global $bp;

//get data from our ajax() call
$blog_id = $_POST['blog_id'];
$single_id = $_POST['single_id'];

switch_to_blog($blog_id);
    $post_x = get_post($single_id);

    //Author Media
    $author = $post_x->post_author;
    $author_firstname =  get_the_author_meta('first_name',$author);
    $author_lastname =  get_the_author_meta('last_name',$author);
    $author_proffesion = get_user_meta( $author,'user_profession', true );

    if(!$author_firstname){
        $author_name =  get_the_author_meta('user_login',$author);
    } else {
        $author_name = $author_firstname . '
' . $author_lastname;
    }

     if ( is_user_logged_in() && !bp_is_my_profile() ){
        $metion = '@ mention';
    }

    $posttext = $post_x->post_content;
    $regular_expression = '~]*\ />~';
    $only_post_text = preg_replace( $regular_expression, '' , $posttext);

    $output =   '
' . videoBox($single_id) . '
';
    $output .=  '
'.
                '
'.
                    '
'.
                        '
' . bp_core_fetch_avatar( array( 'item_id' => $post_x->post_author, 'type'  => 'full' ) ) . '
'.
                    '

' . $author_name . '

'.
                    '
' . $author_proffesion .'
'.
                    '

'.
                    '
View more projects
'.
                    '
'.
                '
'.
                    '
'.
                        '
'.
                            '
'.
                                wdpv_get_vote_up_ms(true, $blog_id, $single_id) .
                            '
'.
                            '
'.
                                 wdpv_get_vote_result_ms(false, $blog_id, $single_id). 'Thumbs up'.
                            '
'.
                        '
'.
                        '
' . $post_x->post_title . '
'.
                        '

' . $only_post_text . '

'.
                    '
'.
                '
';

restore_current_blog();

// Return String
die($output);

}
Maybe not the best piece of Ajax but it works.
But not all works, the thumbs up button doesn't work. This is a Wordpress plugin that also works with Ajax. (working example here http://motiongraphicscollective.com/2013/we-think-things-reel-2013/)
How can i make the  thumbs up work within the colorbox?


text:
Q: Format date in PHP MMddyyyyHHmmss to m-d-y Date Format using PHP
Input date is '1568145593000', i need to convert into m-d-y format using php
Anyone knows how to convert this? Thanks =).

A: echo date('m-d-Y', 1568145593000 / 1000);

Divide the timestamp by 1000 to get the timestamp in seconds.
See:
PHP date https://www.php.net/manual/en/function.date.php
and for the formatting characters: https://www.php.net/manual/en/datetime.format.php (scroll down a bit)


text:
Q: Paasing a variable to triggered send email I would like to pass a variable to a triggered send email, what is the ampscript function I'd need to use to capture the variable (not a profile attribute) in my email body.

A: Use a Triggered Send Data Extension Template to create your Triggered Send Data Extension. Add the field to your Data Extension, "MyVar". Personalise as though it's an attribute - %%MyVar%%.
If you're firing the triggered send from SOAP or REST, you would pass the variable so...
SOAP
<CreateRequest xmlns="http://exacttarget.com/wsdl/partnerAPI">
 <Objects xsi:type="ns2:TriggeredSend" xmlns:ns2="http://exacttarget.com/wsdl/partnerAPI">
    <Client>
        <ID>12345</ID>
    </Client>
    <PartnerKey xsi:nil="true"/>
    <ObjectID xsi:nil="true"/>
    <TriggeredSendDefinition>
       <PartnerKey xsi:nil="true"/>
       <ObjectID xsi:nil="true"/>
       <CustomerKey>MyTriggeredSendCustomerKey</CustomerKey>
    </TriggeredSendDefinition>
    <Subscribers>
       <PartnerKey xsi:nil="true"/>
       <ObjectID xsi:nil="true"/>
       <EmailAddress>johndoe@hotmail.com</EmailAddress>
       <SubscriberKey>C1234566</SubscriberKey>
       <Attributes>
          <Name>MyVar</Name>
          <Value>Some value I want to personalise my email with</Value>
       </Attributes>
       <Attributes>
          <Name>MyVar2</Name>
          <Value>Some other value I need in my email</Value>
       </Attributes>
    </Subscribers>
 </Objects>
</CreateRequest>

REST
Host: https://www.exacttargetapis.com
POST /messaging/v1/messageDefinitionSends/key:MyTriggeredSendCustomerKey/send
Content-Type: application/json
Authorization: Bearer YOUR_ACCESS_TOKEN

{
    "From": {
        "Address": "updates@mycompany.com",
        "Name": "MyCompany Inc"
    },
    "To": {
        "Address": "johndoe@hotmail.com",
        "SubscriberKey": "C1234566",
        "ContactAttributes": {
            "SubscriberAttributes": {
                "MyVar": "Some value I want to personalise my email with",
                "MyVar2": "Some other value I need in my email",
            }
        }
    },
    "OPTIONS": {
        "RequestType": "SYNC"
    }
}


text:
Q: Electron reply error: An object could not be cloned I'm trying to ask the main application to find some kind of device, I have been trying to do it with ipc but couldn't make it work either with asynchronous send and sync send. I suspect that the main is trying to reply the promise.
Renderer:
const recognizedDevices = ipcRenderer.sendSync('findDevice');
console.log(recognizedDevices);

Main:
ipcMain.on('findDevice', (event) => findDevice(event));
const findDevice = async (event) => {
  let recognizedDevices = await findConnectedDevices();
  if(recognizedDevices){
  console.log("found");
  console.log(recognizedDevices);
  return event.returnValue = recognizedDevices;
  }
//TODO: If no device found
}

Result in main:
    found
[
  HID {
    _events: [Object: null prototype] { newListener: [Function (anonymous)] },
    _eventsCount: 1,
    _maxListeners: undefined,
    _raw: HID {},
    write: [Function: bound write],
    getFeatureReport: [Function: bound getFeatureReport],
    sendFeatureReport: [Function: bound sendFeatureReport],
    setNonBlocking: [Function: bound setNonBlocking],
    readSync: [Function: bound readSync],
    readTimeout: [Function: bound readTimeout],
    getDeviceInfo: [Function: bound getDeviceInfo],
    _paused: true,
    [Symbol(kCapture)]: false
  }
]

I was hoping to receive the same log result in the renderer, but unfortunately I am getting back Error: An object could not be cloned.
If I try to reply back with recognizedDevice.length I will indeed receieve "1" in the front end, so it seem like the communication between them is good. Seems like the problem is with sending the object.

A: Data exchanged between the main process and the renderer process via IPC channels are serialized via the Structured Clone Algorithm. Functions and symbols are not serialisable yet you're trying to ship them over:
 [
   HID {
˟   _events: [Object: null prototype] { newListener: [Function (anonymous)] },
    _eventsCount: 1,
    _maxListeners: undefined,
    _raw: HID {},
˟   write: [Function: bound write],
˟   getFeatureReport: [Function: bound getFeatureReport],
˟   sendFeatureReport: [Function: bound sendFeatureReport],
˟   setNonBlocking: [Function: bound setNonBlocking],
˟   readSync: [Function: bound readSync],
˟   readTimeout: [Function: bound readTimeout],
˟   getDeviceInfo: [Function: bound getDeviceInfo],
    _paused: true,
˟   [Symbol(kCapture)]: false
   }
 ]


text:
Q: how to get attribute all dropdown values selected by the product in magento 2? I am trying to show the attribute's dropdown values selected in product. For that I am using this way.
<?php $parentIds = $objectManager->create('Magento\ConfigurableProduct\Model\ResourceModel\Product\Type\Configurable')->getParentIdsByChild($_product->getId());

if(count($parentIds)>0 && $_product->getTypeId() == "simple")
    {
        /*?><?php */
    }
else {
        foreach ($_productCollection as $_product) :
            $_p = $objectManager->get('Magento\Catalog\Model\Product')->load($_product->getId());
            $productList[] = $_p;
            $priceRuleCats = $_p->getprice_rule_category();

            if(!empty($priceRuleCats)){
                $priceRuleList = array_unique(array_merge($priceRuleList,explode(',',$priceRuleCats)));
            }
        endforeach;
    // save the full list
    $fullList = $productList;

    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    $price_rules = $objectManager->get('Startupready\PriceRules\Model\Quantitybreaks');
    $price_rules->load($priceRuleList);
    $price_rules->getPricingTables();

    $current_table = 0;
    $size_options = array();
    $price_breaks = array();

    // use first product from loop to see what the size options are & load price breaks for those options
    $firstProduct = array_shift($productList);

    // this product's price rule category
    $price_rule_category = $firstProduct->getprice_rule_category();

    // loop through simple products
    $conf = $objectManager->create('Magento\ConfigurableProduct\Model\Product\Type\Configurable')->setProduct($firstProduct);
    $simple_collection = $conf->getUsedProductCollection()->addAttributeToSelect('*')->addFilterByRequiredOptions();
    foreach($simple_collection as $simple){
        echo $simple->getsize_option();
        //also i tried like this
        //echo "
"; print_r($simple['size_option']); echo "
";
    }
?>

but when I am putting my code inside the list.phtml file, no any products are displaying on this page.
Meanwhile I am just trying to get that product attribute inside this array so that if a product have assigned this values (doropdown values) then I'll show those values in frontend. Kindly please help me to do this. Thank in advance.

A: First, I should start by saying that it is NOT recommended practice to directly instantiate the Object Manager. You can read more about that here. Although, it is not preventing your code from working.
Second, this logic does not belong in a template phtml file. You should be creating your own module, a small one, that runs through the logic and lets it echo out onto the page via a method call within your phtml file. Also, if you had a module, you could implement the necessary dependency injection to retrieve your data.
Thirdly, inside of the $_productCollection loop, you are calling $_p->load($_product->getId()). This is not only unnecessary but super inefficient.
Let it be known that the code sample below is enough to obtain the info you want to display, but by no means would I recommend implementing your custom code in this manner. So, once you get the data you seek, please see Alan Storm's Magento 2 Tutorial Series and patiently go through them from beginning to end. This will help you gain a better understanding as to how certain crucial elements on Magento 2 work.

Here is the quick and dirty way to get the data requested in your original question:
Find the line in the list.phtml file that looks like this <?php foreach($_productCollection as $_product): ?>. This is not the loop you created, but the loop that was already in the file before you edited it.
Completely replace this line:
<?php foreach($_productCollection as $_product): ?>

With this:
<?php
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
/** @var \Magento\ConfigurableProduct\Model\Product\Type\ConfigurableFactory $configurableFactory */
$configurableFactory = $objectManager->create('Magento\ConfigurableProduct\Model\Product\Type\ConfigurableFactory');
?>

<?php /** @var $_product \Magento\Catalog\Model\Product */ ?>
<?php foreach($_productCollection as $_product): ?>

    <?php
    if($_product->getTypeId() == \Magento\ConfigurableProduct\Model\Product\Type\Configurable::TYPE_CODE) {
        /** @var \Magento\ConfigurableProduct\Model\Product\Type\Configurable $configurable */
        $configurable = $configurableFactory->create();

        // 3 options to get attributes, but i am using
        # $attributes = $configurable->getConfigurableAttributes($_product);
        # $attributes = $configurable->getConfigurableAttributeCollection($_product);

        $attributes = $configurable->getConfigurableAttributesAsArray($_product);
        foreach($attributes as $attrId => $attribute){
            echo '
',print_r($attribute),'
';
        }
    }
    ?>

This will expose all of the available data for each product and then you can do whatever you need to.


text:
Q: How to load Pug templates in webpack without compiling to HTML? Both pug-loader and pug-html-loader seem to be focused on pre-compiling Pug templates to HTML.  I don't want to do that as I need some of the dynamic rendering capabilities that you only get when rendering templates, like being able to pass in a page's title, as a simple example.
What I would like to do, however, is use Webpack to process the Pug templates so as to go through them, figure out what images they use, and load those images over to the /dist folder.  I would like to also be able to use url-loader to inline data URLs into the Pug templates where possible, which means they will need to be copied over and modified in the process.

A: Try this :
{
      test: /.pug$/,
      use : [
        {
          loader : ['html-loader', 'pug-html-loader'],
          options : {
            attrs : ['img:src']
          }
        }
      ]
    }

A: I see how old this question is, but I struggled so much to attempt to fix this issue and I finally found a solution using html-webpack-pug-plugin which extends html-webpack-plugin
const HtmlWebpackPlugin = require('html-webpack-plugin')
const HtmlWebpackPugPlugin = require('html-webpack-pug-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')

module.exports = {
  entry: {
    home: "./src/index.js",
  },
  output: {
     path: path.resolve(__dirname, "./public"),
     filename: "[name].js",
     publicPath: "/public",
     clean: true,
  },
  module: {
    rules: [
       {
        test: /\.(css|sass|scss)$/,
        use: [MiniCssExtractPlugin.loader, "css-loader"],
      },
    ],
  },
  plugins: [
    new MiniCssExtractPlugin(),
    new HtmlWebpackPlugin({
      template: "./views/_head.pug",
      filename: "../views/head.pug",
      minify: false,
      inject: "head",
    }),
    new HtmlWebpackPugPlugin(),
  ],
};

You should only call HtmlWebpackPugPlugin once as said in the documentation https://github.com/negibouze/html-webpack-pug-plugin#usage
For code to be injected, the template _head.pug needs to have a body tag so that code gets injected For the code to be indented properly, it also needs to have a html tag
_head.pug
doctype html
html
  head

  body

After building: head.pug
doctype html
html
  head
    script(defer src="/public/home.js")
    link(href="/public/home.css" rel="stylesheet")

  body


text:
Q: Count the number of missing values in each column and sort them I am a very beginner. learning online courses. Can somebody please help me figure out what to fill in the blank? It required "Order them (increasing or decreasing) using sort_values".
missing.sort_values(by=___)

A: Assuming "missing" is a python DataFrame, you can sort_values by a column.
For example,
>>> df = pd.DataFrame({
...     'col1': ['A', 'A', 'B', np.nan, 'D', 'C'],
...     'col2': [2, 1, 9, 8, 7, 4],
...     'col3': [0, 1, 9, 4, 2, 3],
...     'col4': ['a', 'B', 'c', 'D', 'e', 'F']
... })

>>> df
  col1  col2  col3 col4
0    A     2     0    a
1    A     1     1    B
2    B     9     9    c
3  NaN     8     4    D
4    D     7     2    e
5    C     4     3    F

>>> df.sort_values(by=['col1'])
>>> df

  col1  col2  col3 col4
0    A     2     0    a
1    A     1     1    B
2    B     9     9    c
5    C     4     3    F
4    D     7     2    e
3  NaN     8     4    D

For further reference, you can see the docs here.

A: If you want to sort with the missing numbers NaN first you can specify na_position='first' (the default value is last).
missing.sort_values(by=['column_name'] ,na_position='first')


text:
Q: Cell note in jxls template is not deleted PoiTransformer transformer = PoiTransformer.createTransformer(is, os);
        AreaBuilder areaBuilder = new XlsCommentAreaBuilder(transformer, false);
        List<Area> xlsAreaList = areaBuilder.build();

        int curSheetSize = 3;
        for(int i = 1; i < 1; i++) {
            Area mainArea = xlsAreaList.get(i);
            Area loopArea = mainArea.getCommandDataList().get(0).getCommand().getAreaList().get(0);
            loopArea.addAreaListener(new JxlsAreaListener(transformer, i));

            switch (i) {
                case 1 :
                    mainArea.applyAt(new CellRef("KOR!A1"), context);
                    break;
                case 2 :
                    mainArea.applyAt(new CellRef("JPN!A1"), context);
                    break;
                case 3 :
                    mainArea.applyAt(new CellRef("FRA!A1"), context);
                    break;
                case 4 :
                    mainArea.applyAt(new CellRef("AUS!A1"), context);
                    break;
                case 5 :
                    mainArea.applyAt(new CellRef("UK!A1"), context);
                    break;
                case 6 :
                    mainArea.applyAt(new CellRef("CAN!A1"), context);
                    break;
                case 7 :
                    mainArea.applyAt(new CellRef("MEX!A1"), context);
                    break;
            }

            mainArea.processFormulas();
        }

       transformer.write();

        is.close();
        os.close();

I hope the memo is deleted in the Excel file made from template. please.
is templete
enter image description here
is Files created from templates
enter image description here


text:
Q: OOCSS - only use class to do styling I am practicing OOCSS now but I meet a problem.

a

b

c

If I want to style these 3
 items separately I will do:
li:nth-of-type(1) {}
li:nth-of-type(2) {}
li:nth-of-type(3) {}

But according to OOCSS we should use class to style the elements, like:

a

b

c

.li-1 {}
.li-2 {}
.li-3 {}

Now seems OK but what if I have 10
 I have to add 10 classes which looks dumb to me.
Which style should I use? Can I use those that other than classes to style the elements, based on OOCSS?

A: Well, technically I think what they are referring to is that you should use classes instead of html element identifiers.
So perhaps doing something like:

a

b

b

And then just use your original styles like:
.li:nth-of-type(1) {}
.li:nth-of-type(2) {}
.li:nth-of-type(3) {}

In your case you're basically using classes as you would use an id. Classes are supposed to identify multiple elements.


text:
Q: Adding and removing elements with HtmlUnit Well, I want to scrape a table out of my school website which contains the schedule for the day. The table changes according to what class you chose, so it uses javascript command that checks which class is selected. I found out that it is based on this list in the HTML code of the website:
<option selected="selected" value="52">1</option>
<option value="53">2</option>
<option value="54">3</option>
<option value="1">ז - 1</option>
<option value="2">ז - 2</option>
<option value="3">ז - 3</option>
<option value="4">ז - 4</option>
<option value="5">ז - 5</option>
<option value="6">ז - 6</option>
<option value="57">ז - 7</option>
<option value="9">ח - 1</option>
<option value="10">ח - 2</option>
<option value="11">ח - 3</option>
<option value="12">ח - 4</option>
<option value="13">ח - 5</option>
<option value="14">ח - 6</option>
<option value="15">ח - 7</option>
<option value="17">ט - 1</option>
<option value="18">ט - 2</option>
<option value="19">ט - 3</option>
<option value="20">ט - 4</option>
<option value="21">ט - 5</option>
<option value="22">ט - 6</option>
<option value="23">ט - 7</option>
<option value="26">י - 1</option>
<option value="27">י - 2</option>
<option value="28">י - 3</option>
<option value="29">י - 4</option>
<option value="30">י - 5</option>
<option value="31">י - 6</option>
<option value="32">יא - 1</option>
<option value="33">יא - 2</option>
<option value="34">יא - 3</option>
<option value="35">יא - 4</option>
<option value="36">יא - 5</option>
<option value="37">יא - 6</option>
<option value="38">יב - 1</option>
<option value="39">יב - 2</option>
<option value="40">יב - 3</option>
<option value="41">יב - 4</option>
<option value="42">יב - 5</option>
<option value="43">יב - 6</option>
<option value="56">יב - 7</option>
<option value="49">שכבה ז'</option>
<option value="50">שכבה ח'</option>
<option value="51">שכבה ט'</option>
<option value="48">שכבה י'</option>
<option value="46">שכבה י"א</option>
<option value="47">שכבה י"ב</option>

As you can see, the chosen option has additional element <option selected="selected" value="52">1</option> which called selected
Basically, I just want to remove that selected element from one option element and move it to another option element which will be the class that I want to choose.

A: This 'selected' thing is nothing special; it is the way html works (https://developer.mozilla.org/en-US/docs/Web/HTML/Element/select). And btw, if you like to scrape web pages some basic knowledge of Html might be helpful :-).
Regarding your select:

*

*you have to find the select control inside the page - usually you have a HtmlPage object and you have to use one of the selection methods offered by HtmlUnit(http://htmlunit.sourceforge.net/gettingStarted.html) to find the select element (without knowing your code i can't be more specific)

*then find the option (HtmlOption) inside the select you like to choose

*finally call HtmlOption#setSelected(true) for that option


text:
Q: What the different between those two ways to create an instance? private let firstVc: HZSViewController = {
  let vc = HZSViewController(type: .interaction)
  return vc
}()

private let secondVc = HZSViewController(type: .interaction)

the second way is seen easier, what's the different between them?

A: Both accomplish the same thing. The first is more often used when you want to set a number of properties associated with the object before returning it.  This is helpful when you have a certain configuration of the object that you want and want to ensure are set before being able to use the object.
In the second scenario, you are limited to the declared properties; any subsequent property changes you want would need to be declared in the lines of code following.


text:
Q: what does base.OnPreInit(e) mean? Any one could simply tell me what does base.OnPreInit(e) mean ?
Thank you

A: The OnPreInit method is called at the beginning of the page initialization stage.
When you are overriding this in your page, you'll have something like
protected override void OnPreInit(EventArgs e)
{
   base.OnPreInit(e);
   ...
   // do something else

}

where base.OnPreInit(e) calls the Page class's OnPreInit().
If you don't have extra functionality to add to your page then you don't have to override OnPreInit

A: When overriding methods e.g. OnPreInit in your example sometimes it is necessary to call the control/page base method, for this purposes you could just use base.OnPreInit(e) which will call the base class method.

A: base.OnPreInit(e) is a call to the OnPreInit() method of the base class for the page you are looking at.
'e' is the parameter that was passed in to your method (presumably OnPreInit() ) and it is passed through to the base class's method.


text:
Q: Sharing a video link on facebook ios I'm trying to share a link of a video that I uploaded in my website host. But the post doesn't show my video and a thumbnail image. I want my post to look like this image bellow:
http://i.stack.imgur.com/UcbTG.png
is there anyway to post my video like that?
I'm using facebook SDK 3.1.1, ARC, Cocos2d 2.0, IOS 5.1;

A: Yes, if you supply the correct Open Graph Tags as per https://developers.facebook.com/docs/opengraphprotocol/#audiovideo your video can embed in the News Feed post.
To accomplish the actual Sharing, you should use the Feed Dialog which is customizable and will work on desktop and mobile devices.


text:
Q: Access 2007 compact DB Sorry for my English, I write from Italy.
I use the Access 2007 DB in a business data management procedure in VB Net.
As is known, Access DBs expand during use and consequently I need to compact them when the program is closed.
I perform the compaction in this way
Dim MioEngine As New Microsoft.Office.Interop.Access.Dao.DBEngine

MioEngine.CompactDatabase(myAccesDB, newAccessDB,)
Application.DoEvents()

but often and not on all PCs on the network, the compaction does not finish and gives me the following error message:
The process cannot access the 'C:\myAccesDB.accdb' file because it is being used by another process
Analyzing in depth what happens, I see that when the error occurs, the .laccdb file is not closed at the time of compacting.
Is there any way other than the one I used to do the compacting safely?
I specify that all the PCs in our network are Windows 10 pro and all updated; when Windows 10 was in its infancy, I didn't get this error.

A: Since my comment was not enough, here's an answer:
The idea is to try to opetn .laccdb file before you try to compact the database. You can do something like this:
Dim file as System.IO.FileInfo = New System.IO.FileInfo("c:\myAccesDB.laccdb")
Dim stream As FileStream = Nothing
Try
    stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None)
    stream.Close()
    'if stream is successfully closed, file is not in use and database can be compacted
    MioEngine.CompactDatabase(myAccesDB, newAccessDB,)
Catch ex As Exception
    'show some message to user that file is in use so it can try again
End Try

I worked with VB and Access ages ago, so this is only a direction that you should take.

A: Thanks, I'll try.
I also had a look to this:
https://support.microsoft.com/en-us/topic/office-error-accdb-remains-locked-after-oledb-connection-is-closed-37d42348-9edf-4493-a5f4-35c685af3160?ui=en-us&rs=en-us&ad=us
Where I find:
This issue is now fixed.  If you launch Access, click 'File', then 'Account', then 'Update Options', and 'Update Now', this will ensure that you have the latest version, and all versions should have the fix available.
But I'm not able to find 'File' opening Access,....


text:
Q: Average of marks in examinations Is it statistically correct to find out final marks of a student in a paper by taking arithmetic mean only of 4 valuations of a single paper without an answer key, or any rectification measures for the outlier marks?
For eg. Marks obtained by Candidate in 4 valuations are 43, 45, 48 and 51 in a single paper in 4 different valuations. Final marks awarded by taking average of these 4 are 47. Is this method scientifically and statistically correct in an examination?

A: Welcome to the site! Mean, mode, and median are all among many valid measures of central tendency.
Here is a good link that explains how some of these compare and in what situations it makes sense to use one over the other.


text:
Q: Template for creating empty groups in Xcode Is there any way to create a template for creating empty groups in Project Navigator?
for example, I use MVVM design pattern in my applications, so I have modules lets say Login and inside I like to create groups like following: Models, ViewModels, Views. So every time I create a new module I have to create those groups manually.

So I thought if someone had found a workaround or maybe there is a shortcut to duplicate the group?
Thanks in Advance.


text:
Q: Invoice-like example to understand reactivity of nested object in arrays. Should I use a store for this? I'm trying my best to understand the idiomatic way to create an Invoice-like form with Svelte 3.
My REPL is here: https://svelte.dev/repl/7aca36569aea49bba38e5fb8b1b0835b?version=3.24.1.
QUESTIONS:

*

*Is this a good way to do it? Should I use a store perhaps?

*Is there a way to update amountDue when I change qty and price of my rows? (I know I can do it with rows = rows but it seems to me a bit not-idiomatic way, am I wrong?)

A: I don't think you need to use a store (probably useful for a large tree of components)
For the second question, You just need to do a component binding
https://svelte.dev/tutorial/component-bindings
{#each rows as row}
    <Row bind:row />
{:else}
    Still no rows.
{/each}

Notice how we use the bind keyword instead of just passing the prop

A: In case you need a more complete answer:

*

*No need to use a store. That's normally the case for when you want to communicate several components.

*As proposed earlier, you should bind the row value to the Row's row prop. You can use the shortcut bind:row as an alias of bind:row={row}.

*Minor: The logic to calculate amountDue total seems flawed as it ignores the row quantity to calculate the total price.

Here's a working REPL with the desired behavior: https://svelte.dev/repl/78fa09646005441a85061e6edf9886f9?version=3.24.1


text:
Q: Implementing bwmorph(image,'thin','inf') then finding number of branchpoints in c++ using opencv I would like to implement the following Matlab code for a given image in c++, which calculates the number of branch points in a medial axis skeleton representation of an image:
skelImg   = bwmorph(imageName, 'thin', 'inf');
branchImg = bwmorph(skelImg, 'branchpoints');
[row, column] = find(branchImg);
branchPts     = [row column];
cNumBranchPoints = length(branchPts);

I have seen this example: How to implement an function equivalent to bwmorph Matlab function in OpenCV which is similar in nature, although slightly different, in that I do not want to 'clean' the image, but rather 'thin' it. I also want to determine the number of branch points, not end points, as in the aforementioned example.
Anyone have an idea as to how I can do this in c++?
Best,
Ben


text:
Q: I want the old good star back! Can I haz the circle around the star back? Without circle, it looks tiny and not MSE-ish. Want it back.
Old design:

New design:

A: Personally, I like the new star because it seems to be a bit cleaner, but I can see from a UX perspective why it may not be as useful as the old button.
So, for those of you who hate change (or the lack of circles), here's a userscript that adds the circles back.
// ==UserScript==
// @name           Old Meta.SE Stars
// @namespace      http://greasyfork.org/
// @include        *://meta.stackexchange.com/questions/*
// @exclude        *://meta.stackexchange.com/questions/tagged
// @author         Cameron Bernhardt (AstroCB)
// @version        1.0
// @description    Reverts to the old Meta.SE star style
// ==/UserScript==
var newStyle = document.createElement("style");
newStyle.innerText = ".envelope-on, .envelope-off, .vote-up-off, .vote-up-on, .vote-down-off, .vote-down-on, .star-on, .star-off, .comment-up-off, .comment-up-on, .comment-flag, .edited-yes, .feed-icon, .vote-accepted-off, .vote-accepted-on, .vote-accepted-bounty, .badge-earned-check, .delete-tag, .grippie, .expander-arrow-hide, .expander-arrow-show, .expander-arrow-small-hide, .expander-arrow-small-show, .anonymous-gravatar, .badge1, .badge2, .badge3, .gp-share, .fb-share, .twitter-share, #notify-container span.notify-close, .migrated.to, .migrated.from { background-image: url('https://web.archive.org/web/20150221090806/http://meta.stackexchange.com/content/stackexchangemeta/img/sprites.png?v=145e63c0320f'); } .star-on, .star-off { height: 50px; } .votecell .vote-count-post { margin: 5px 0 17px 0;  }";

document.getElementsByTagName("head")[0].appendChild(newStyle);

A: I like the old one better from a 'user experience' point-of-view. The design itself doesn't matter a lot to me.
The old button is in line with the upvote and downvote buttons. Novice users will sooner see this is something to click, which is a good thing.

A: I'm going to agree that taking away that circle seems to make the feature a little less easy to discover. Then again, I'm not certain the star does the best job of advertising the feature with the circle either. From a design perspective I think I could go either way, so advertising the feature better is probably the best criteria.
Not declining or accepting, because I think we're going in circles here. Is the star (adorned with a glorious circle or not) really the best way to advertise this? The whole 'favorite' thing is a little strange to begin with because it's useful to apply to posts that you simply want to watch but don't necessarily have 'love' for (thus, a heart is out of the question).
While this has come up, multiple times in the past, I'm open to links to feature requests you were fond of that suggested an alternate icon. Not saying there are any plans of changing it, but another look at the feature itself is on my plate for this year so ..
I'm thinking more .. Watch and waypoint this post, which is essentially why people that know the button works click it in the first place, at least most of them.

A: Why? What does that circle add?
The new design (which is simply copied from MSO) is sharper and give more "professional" look to things in my opinion.

A: I really didn't think that many people would notice. There are two reasons the circle around the star was removed:

*

*Some of our sites have no circle around the star, and we're looking to normalize variables across network sites in order to be able to release new global features more easily in the future (like the new profile.)

*It was a logical decision — the thinking was that adding something to your favorites is a less important of an action than upvoting or downvoting. By removing the circle, the star gets less visual weight than the arrows, giving the voting icons more prominence.


text:
Q: ProviderIncompatibleException with entity framework 4 ctp5 and oracle express I encountered a ProviderIncompatibleException when I tried to connect on a Oracle express database with dotConnect for Oracle and entity framework 4 ctp5. I have Oracle Express 10g and I download the trial version for Oracle express today, so I have version number 6.0.86.0 of the dlls
Here's my config. Any idea how to solve the problem?

A: We have replied you at our forum here.
The code sample:
    public class MyOracleContext : DbContext {
  public DbSet<Product> Products { get; set; }
  public DbSet<ProductCategory> ProductCategories { get; set; }

  static MyOracleContext() {

    System.Data.Entity.Database.DbDatabase.SetInitializer<MyOracleContext>(null);
  }

  protected override void OnModelCreating(ModelBuilder modelBuilder) {

    base.OnModelCreating(modelBuilder);

    modelBuilder.Conventions.Remove<System.Data.Entity.ModelConfiguration.Conventions.Edm.Db.ColumnTypeCasingConvention>();
  }
}


text:
Q: An attitude of religious faith
An attitude of religious faith is attractive to many people. It makes the kind of arguments we have been considering irrelevant. Yet
at its most extreme, religious faith can make people completely blind
to the evidence against their views: it can become more like
stubbornness than a rational attitude.

I don't understand the meaning of the word "of" in the bold text. I think it means "showing"
https://www.oxfordlearnersdictionaries.com/definition/english/of?q=of
Could you explain it to me? Thanks

A: Normally, we would say someone has an attitude to, or towards something, as an attitude is a disposition. Also, "faith" isn't really an 'attitude', it is a belief. For example, you wouldn't say that someone has an "attitude of science".
However, in trying to understand what has been written, I would agree with comments that the use of "of" is to suggest that a specific attitude is based upon a religious belief. Whoever wrote it is probably trying to describe an attitude they think religious people have.


text:
Q: Intent to Play store? I want the button called "More Apps" to access my list of apps on the play store .
 This is the page link :
https://play.google.com/store/apps/developer?id=Jouni
??

A: Launch Google Play Store works fine with some Market URI:
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setData(Uri.parse(<market_uri>));
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NO_ANIMATION);

        startActivity(intent);

where uris can be

*

*market://details?id=

*market://search?q=pub:

But it's not working when you want to launch it on the welcome page , i.e., when you just want to Launch Google Play Store whitout specifying an app id or perform a query.
So I came up with this solution which also handles the case where 'market://' uris can't be processed by any app. In this case, use Web browser as a fall-back.
This solution is not the best, but it does the job.
public void launchPlayStore()
{
    // look for intent able to process 'market://' uris
    Intent market = new Intent(Intent.ACTION_VIEW, Uri.parse("market://search?q=dummy"));

    PackageManager packageManager = getPackageManager();

    ComponentName playStoreComponentName=null;

    for(ResolveInfo resolveInfo : packageManager.queryIntentActivities(market, 0))
    {
        ActivityInfo activityInfo = resolveInfo.activityInfo;

        String packageName = activityInfo.applicationInfo.packageName;

        // lokking for "com.android.vending", "com.google.android.finsky.activities.MainActivity"
        if (!packageName.contains("android"))// || !activityInfo.name.contains("android"))
            continue;

        // appname should be 'Play Store'
        // String appName = resolveInfo.loadLabel(packageManager).toString();
        playStoreComponentName =  new ComponentName(packageName, activityInfo.name);
        break;
    }

    if(playStoreComponentName!=null)
    {
        Intent intent = new Intent();
        intent.setComponent(playStoreComponentName);
        intent.setData(Uri.parse("market://"));
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NO_ANIMATION);

        // launch Google Play Store app :-)
        startActivity(intent);
    }
    else
    {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setData(Uri.parse("https://play.google.com/"));
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NO_ANIMATION);

        // fallback -> web browser
        startActivity(intent);
    }
}

A: Do this in your button OnClick
String url = "https://play.google.com/store/apps/developer?id=Jouni";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);


text:
Q: Is it good/bad style to use \label in preamble or package/class file? I would like to use \labels to organize a package file that has become too long to be navigated by simple scrolling.
It seems that this doesn't cause any errors, but I'm not sure if that's good coding style. After all, I can't reference the preamble/package/class, isn't it?
So, is this good style, or bad style? Are there any other/better ways to organize a style file so that my editor can aid me navigating it?

A: It's definitely bad style and when it works it only works by accident. There is no reference-able context set up before \begin{document} nor is theaux file opened for writing before \begin{document}. The reason it doesn't generate an error is that \label does a delayed write so that it can save the page number so the write is delayed until the first page is shipped out so in particular until after the aux file has been opened.
However the information saved by \label will always be {}{1} so ref of the label will return nothing and \pageref of the label will return 1, so there is no useful information  generated by the \label command in that position.

A: Yes, it is bad coding style.
However, it can easily be circumvented.
A good example where this is useful is when converting TeX files to use the newer biblatex. This has some other input mechanisms for adding .bib files to the search path. However, most editors rely on the old \bibliography macro to discover the entry.
Hence I can do this (with only one operation more)
% RefTeX does not read this
\addbibresource{text.bib}
\iffalse
  % RefTeX DOES read this
  \bibliography{text.bib}
\fi

you can employ the exact same thing in your class/package.
\iffalse
  \label{critical point}
\fi

A: For organizing stuff (and being able to find it in my longuish preamble) I just use plain LaTeX comments. E.g.
%% AMS stuff here
...
%% Handle page format
...

Using %% (or even %%%% or so) makes the comments stand out, and makes them easily searchable. Probably can persuade emacs to fold each part (or mark each piece as a fold), but not that complex a preamble yet...


text:
Q: Why does setting a MessageListener on a MessageConsumer not cause the program to continue after the main thread dies? I am setting up a MessageListener and expect that the program will still run (since the listening thread is still alive), but after "Finished" is printed on the screen, the program is terminated. Any idea why this happens and how to fix it?
    MessageListener messageListener = new DelegationReceiver();
    Properties p = PropertiesLoader.getProperties("jms.properties");
    InitialContext cntxt = new InitialContext();

    cntxt.addToEnvironment(Context.INITIAL_CONTEXT_FACTORY, p.getProperty("namingFactory"));
    cntxt.addToEnvironment(Context.URL_PKG_PREFIXES, p.getProperty("urlPackages"));
    cntxt.addToEnvironment(Context.PROVIDER_URL,p.getProperty("providerURL"));
    cntxt.addToEnvironment(Context.SECURITY_PRINCIPAL,"default");
    cntxt.addToEnvironment(Context.SECURITY_CREDENTIALS,"password");
    ConnectionFactory tfact = (ConnectionFactory) cntxt.lookup(p.getProperty("topicFactory"));
    Topic topic = (Topic) cntxt.lookup(p.getProperty("myTopic"));
    Connection connection = tfact.createConnection();
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageConsumer mc = session.createConsumer(topic);
    mc.setMessageListener(messageListener);
    connection.start();
    System.out.println("Finished");


text:
Q: Percona xtrabackup transaction log corrupted I am attempting to prepare and restore a full backup taken through xtrabackup via a scheduling script called surrogate.
I have tarred and gzipped the backup, transferred to a local machine running the same setup (aside from a slight version difference in xtrabackup - 2.2.12 on source, 2.3.9 local).
Upon extracting I am running the following command to prepare the backup for restore:
innobackupex --use-memory=1G --apply-log /home/matthew/full_2017-08-13_0700/

This is responding:
  innobackupex version 2.3.9 based on MySQL server 5.6.24 Linux (x86_64) (revision id: fde0e3e)
  xtrabackup: cd to /home/matthew/full_2017-08-13_0700/
  xtrabackup: This target seems to be not prepared yet.
  xtrabackup: xtrabackup_logfile detected: size=2097152, start_lsn=(661464509389)
  xtrabackup: using the following InnoDB configuration for recovery:
  xtrabackup:   innodb_data_home_dir = ./
  xtrabackup:   innodb_data_file_path = ibdata1:12M:autoextend
  xtrabackup:   innodb_log_group_home_dir = ./
  xtrabackup:   innodb_log_files_in_group = 1
  xtrabackup:   innodb_log_file_size = 2097152
  xtrabackup: using the following InnoDB configuration for recovery:
  xtrabackup:   innodb_data_home_dir = ./
  xtrabackup:   innodb_data_file_path = ibdata1:12M:autoextend
  xtrabackup:   innodb_log_group_home_dir = ./
  xtrabackup:   innodb_log_files_in_group = 1
  xtrabackup:   innodb_log_file_size = 2097152
  xtrabackup: Starting InnoDB instance for recovery.
  xtrabackup: Using 1073741824 bytes for buffer pool (set by --use-memory parameter)
  InnoDB: Using atomics to ref count buffer pool pages
  InnoDB: The InnoDB memory heap is disabled
  InnoDB: Mutexes and rw_locks use GCC atomic builtins
  InnoDB: Memory barrier is not used
  InnoDB: Compressed tables use zlib 1.2.8
  InnoDB: Using CPU crc32 instructions
  InnoDB: Initializing buffer pool, size = 1.0G
  InnoDB: Completed initialization of buffer pool
  InnoDB: The first specified data file ./ibdata1 did not exist: a new database to be created!
  InnoDB: Setting file ./ibdata1 size to 12 MB
  InnoDB: Database physically writes the file full: wait...
  InnoDB: Setting log file ./ib_logfile101 size to 2 MB
  InnoDB: Renaming log file ./ib_logfile101 to ./ib_logfile0
  InnoDB: New log files created, LSN=45781
  InnoDB: Doublewrite buffer not found: creating new
  InnoDB: Doublewrite buffer created
  InnoDB: 1 rollback segment(s) are active.
  InnoDB: Waiting for purge to start
  InnoDB: 5.6.24 started; log sequence number 0

  xtrabackup: error: The transaction log file is corrupted.
  xtrabackup: error: The log was not applied to the intended LSN!
  xtrabackup: Log applied to lsn 0
  xtrabackup: The intended lsn is 661464919534

Any idea what this is and how I overcome it?

A: DISCLAIMER : Not xtrabackup expert
Your situation is quite similar to a Jan 27, 2016 post on the Percona Forums. The poster, dbaffaleuf, was running percona server 5.6.24-72.2-log, innobackupex 2.3.3 Linux (x86_64).
After encountering your same message, dbaffaleuf wrote

Interestingly the xtrabackup_logfile file has been deleted from the backup path. If I save the xtrabackup_logfile before running the prepare, and restore it after, the first prepare crashes with transaction log corrupted, the next try to prepare works:
Restore the xtrabackup_log file for previous copy after full backup
$ cp /tmp/xtrabackup_logfile /my/path/to/backup/timestamp/

Run the prepare again:
$ /home/products/xtrabackup/bin/innobackupex --use-memory=1G --apply-log /my/path/to/backup/timestamp/ | tee -a /my/path/to/prepare/log/file.log

You may have to do the same

*

*Save the xtrabackup_logfile before running the prepare

*Restore the xtrabackup_log file for previous copy after full backup

*Run the prepare again