问:
How to prevent deadlocks in the following C# code?
The following C# class is used in a multithreaded enviroment. I removed very much of the actual code. The problem occurs when calling MethodA and MethodB almost simultaneously. The order of the lock in the IsDepleted property doesn't solves the problem. Removing lock(WaitingQueue) from the IsDepleted property solves the deadlock, but this solution causes a problem when another thread adds/removes an item from the WaitingQueue between the WaitingQueue.Count == 0 and Processing.Count == 0 statements.</p>

```<code>using System.Collections.Generic;

class Example
{
    bool IsDepleted
    {
        get
        {
            lock (Processing)
            {
                lock (WaitingQueue)
        {
                    return WaitingQueue.Count == 0
             && Processing.Count == 0;
        }
            }
        }
    }

    private readonly List<object> Processing = new List<object>();
    private readonly Queue<object> WaitingQueue = new Queue<object>();

    public void MethodA(object item)
    {
        lock (WaitingQueue)
        {
            if (WaitingQueue.Count > 0)
            {
                if (StartItem(WaitingQueue.Peek()))
                {
                    WaitingQueue.Dequeue();
                }
            }
        }
    }

    public void MethodB(object identifier)
    {
        lock (Processing)
        {
            Processing.Remove(identifier);
            if (!IsDepleted)
            {
                return;
            }
        }
    //Do something...
    }

    bool StartItem(object item)
    {
        //Do something and return a value
    }
}
</code>```

答: Take the Processing lock in method A and the WaitingQueue lock in method B (in other words, make it look like the first block of code). That way, you always take the locks in the same order and you'll never deadlock.</p>

OwnerDisplayName: Vernicht

Body:
The following C# class is used in a multithreaded enviroment. I removed very much of the actual code. The problem occurs when calling MethodA and MethodB almost simultaneously. The order of the lock in the IsDepleted property doesn't solves the problem. Removing lock(WaitingQueue) from the IsDepleted property solves the deadlock, but this solution causes a problem when another thread adds/removes an item from the WaitingQueue between the WaitingQueue.Count == 0 and Processing.Count == 0 statements.

using System.Collections.Generic;

class Example
{
    bool IsDepleted
    {
        get
        {
            lock (Processing)
            {
                lock (WaitingQueue)
        {
                    return WaitingQueue.Count == 0
             && Processing.Count == 0;
        }
            }
        }
    }

    private readonly List<object> Processing = new List<object>();
    private readonly Queue<object> WaitingQueue = new Queue<object>();

    public void MethodA(object item)
    {
        lock (WaitingQueue)
        {
            if (WaitingQueue.Count > 0)
            {
                if (StartItem(WaitingQueue.Peek()))
                {
                    WaitingQueue.Dequeue();
                }
            }
        }
    }

    public void MethodB(object identifier)
    {
        lock (Processing)
        {
            Processing.Remove(identifier);
            if (!IsDepleted)
            {
                return;
            }
        }
    //Do something...
    }

    bool StartItem(object item)
    {
        //Do something and return a value
    }
}

OwnerDisplayName: Paul Betts


来源: stackexchange

问:
what is the purpose of using <html:text instead of <input type="text" in struts?
in struts programming we use <html:text instead of <input type="text" But we can use <input type="text" and it will work also what is the specific reason for using <html:text tag?
can any one answer me please?

答: It's just for convenience. You can easily write an regular input, supplying a proper name for binding, and a value - some EL that takes the current value from the request. You can take a look at the HTML generated by  to get a better idea.

ContentLicense: CC BY-SA 2.5

Body: It's just for convenience. You can easily write an regular input, supplying a proper name for binding, and a value - some EL that takes the current value from the request. You can take a look at the HTML generated by <html:text> to get a better idea.


问:
Is there any way in CakePHP3 to have an entity that inherits from a parent class but that parent doesn't have a corresponding table?
I want to be able to write to class2's table by calling class1.  Possible?</p>

```<code>public class1 extends Entity{
 public function save(){
 }
}

public class2 extends class1{
}

class class1Controller extends AppController{
public function test(){
    class1->save();
}
}
</code>```

答: If you have 2 formally associated models, calling saveAll on one will update the data in the other as well.  But note that what you show us declares no association..  </p>

ContentLicense: CC BY-SA 3.0

Body:
I want to be able to write to class2's table by calling class1.  Possible?

public class1 extends Entity{
 public function save(){
 }
}

public class2 extends class1{
}

class class1Controller extends AppController{
public function test(){
    class1->save();
}
}


问:
Sort DRF serializer output of nested Serializer field by child's field
I have two serializers, in which one refers to the other with a many=True relationship.

```<code>class AttributeInParentSerializer(ModelSerializer):
    masterdata_type = CharField(max_length=256, source='masterdata_type_id')

    class Meta:
        model = Attribute
        fields = ('uuid', 'masterdata_type')

class ArticleInArticleSetSerializer(ModelSerializer):
    attributes = AttributeInParentSerializer(many=True)

    class Meta:
        model = Article
        fields = ('uuid', 'attributes')
</code>```

The ordering of the attributes in the Article are not always the same, but I want to output them in the same order, so in this case ordering on the field masterdata_type. How can I accomplish this? Note that I do not want to change any client of the serializer if possible, and surely not any model.

答:
You can use order_by inside of your serializer like this:

```<code>class AttributeInParentSerializer(ModelSerializer):
    masterdata_type = CharField(max_length=256, source='masterdata_type_id')

    class Meta:
        model = Attribute
        fields = ('uuid', 'masterdata_type')
        order_by = (('masterdata_type',))
</code>```

Hope it helps!

UPDATE:

Looks like I am mistaken. Could not find it from the documentation and it does not seem to work. Now, I don't think serializers are the place to do ordering. Best way to do is in the model or in the view.

Body:
I have two serializers, in which one refers to the other with a many=True relationship.

class AttributeInParentSerializer(ModelSerializer):
    masterdata_type = CharField(max_length=256, source='masterdata_type_id')

    class Meta:
        model = Attribute
        fields = ('uuid', 'masterdata_type')

class ArticleInArticleSetSerializer(ModelSerializer):
    attributes = AttributeInParentSerializer(many=True)

    class Meta:
        model = Article
        fields = ('uuid', 'attributes')

The ordering of the attributes in the Article are not always the same, but I want to output them in the same order, so in this case ordering on the field masterdata_type. How can I accomplish this? Note that I do not want to change any client of the serializer if possible, and surely not any model.

Body:
You can use order_by inside of your serializer like this:

class AttributeInParentSerializer(ModelSerializer):
    masterdata_type = CharField(max_length=256, source='masterdata_type_id')

    class Meta:
        model = Attribute
        fields = ('uuid', 'masterdata_type')
        order_by = (('masterdata_type',))

Hope it helps!

UPDATE:

Looks like I am mistaken. Could not find it from the documentation and it does not seem to work. Now, I don't think serializers are the place to do ordering. Best way to do is in the model or in the view.


问:
C# save to SQLite from new form
I have a small project in SQLite. I show all of examples in ListViewlike this:

```<code>SQLiteConnection oSQLiteConnection =
                new SQLiteConnection("Data Source=database.s3db");
            SQLiteCommand oCommand = oSQLiteConnection.CreateCommand();
            oCommand.CommandText = "SELECT * FROM PERSONS";
            m_oDataAdapter = new SQLiteDataAdapter(oCommand.CommandText,
                oSQLiteConnection);
            SQLiteCommandBuilder oCommandBuilder =
                new SQLiteCommandBuilder(m_oDataAdapter);
            m_oDataSet = new DataSet();
            m_oDataAdapter.Fill(m_oDataSet);
            m_oDataTable = m_oDataSet.Tables[0];
            lstItems.DataContext = m_oDataTable.DefaultView;
</code>```

I also have a button wchich open new form with field like name, username and I want to click save (in that new open form) and save a new row to my database and update this view. How can I do that? In my "min" viewI can do ststaic like this

```<code>DataRow oDataRow = m_oDataTable.NewRow();
oDataRow[1] = "Name";
oDataRow[2] = "Username";
m_oDataTable.Rows.Add(oDataRow);
m_oDataAdapter.Update(m_oDataSet);
</code>```

How to save this from a new form? I can't do that :(

答:
Look hire
http://www.c-sharpcorner.com/UploadFile/718fc8/save-delete-search-and-update-record-in-ado-net/

I like to use entity framework

```<code> using (var context = new Db())
        {
            try
            {
               ...
                context.SaveChanges();
            }
            catch (Exception e)
            {

            }
        }
</code>```

Title: C# save to SQLite from new form

Body:
I have a small project in SQLite. I show all of examples in ListViewlike this:

SQLiteConnection oSQLiteConnection =
                new SQLiteConnection("Data Source=database.s3db");
            SQLiteCommand oCommand = oSQLiteConnection.CreateCommand();
            oCommand.CommandText = "SELECT * FROM PERSONS";
            m_oDataAdapter = new SQLiteDataAdapter(oCommand.CommandText,
                oSQLiteConnection);
            SQLiteCommandBuilder oCommandBuilder =
                new SQLiteCommandBuilder(m_oDataAdapter);
            m_oDataSet = new DataSet();
            m_oDataAdapter.Fill(m_oDataSet);
            m_oDataTable = m_oDataSet.Tables[0];
            lstItems.DataContext = m_oDataTable.DefaultView;

I also have a button wchich open new form with field like name, username and I want to click save (in that new open form) and save a new row to my database and update this view. How can I do that? In my "min" viewI can do ststaic like this

DataRow oDataRow = m_oDataTable.NewRow();
oDataRow[1] = "Name";
oDataRow[2] = "Username";
m_oDataTable.Rows.Add(oDataRow);
m_oDataAdapter.Update(m_oDataSet);

How to save this from a new form? I can't do that :(

Body:
Look hire
http://www.c-sharpcorner.com/UploadFile/718fc8/save-delete-search-and-update-record-in-ado-net/

I like to use entity framework

 using (var context = new Db())
        {
            try
            {
               ...
                context.SaveChanges();
            }
            catch (Exception e)
            {

            }
        }


问:
how to get the browser's size in node.js?
how would I get the browser size in node.js?
I want to send it to a jade template so it can place a unknown amount of divs on the page spaced equally.
if getting the users screen size is not the best way of doing it please let me know a different solution (its probably not the best way. but the only other thing i could think of is a script for each div this.width = window.width/number of divs and that also seems bad).

thanks,
Porad

答:
Alternatively, you can use https://www.npmjs.com/package/device, if all you need is maybe just checking what device user is using therefore, no need to check screen resolution at all.

Otherwise, you may just have to make a HTTP call to send that resolution to server side.

```<code>var device = require('device');
var mydevice = device('put here user-agent string');

if(mydevice.is('phone'))
    // do something...
else
    // do another thing...
</code>```

Body:
Alternatively, you can use https://www.npmjs.com/package/device, if all you need is maybe just checking what device user is using therefore, no need to check screen resolution at all.

Otherwise, you may just have to make a HTTP call to send that resolution to server side.

var device = require('device');
var mydevice = device('put here user-agent string');

if(mydevice.is('phone'))
    // do something...
else
    // do another thing...


问:
how to get the value after the second instance of a character in SQL Server?
I have these strings:

XXXXX - XXXX - XXX - XXXX

XXXX - XXX - XXXXXXX

I need to grab the value AFTER the second instance of '-'

so in the scenario above, I would get:

XXX - XXXX

XXXXXXX

how do I do this in SQL?

答:
SUBSTRING and CHARINDEX are your friends here.
Try this:

```<code>DECLARE @str VARCHAR(MAX) = 'XXXXX - XXXX - XXX - XXXX'

SELECT SUBSTRING( SUBSTRING( @str, CHARINDEX( '-', @str ) + 1, LEN( @str ) ), CHARINDEX( '-', @str ) + 1, LEN( @str ) )
</code>```

Returns XXX - XXXX

Body:
SUBSTRING and CHARINDEX are your friends here.
Try this:

DECLARE @str VARCHAR(MAX) = 'XXXXX - XXXX - XXX - XXXX'

SELECT SUBSTRING( SUBSTRING( @str, CHARINDEX( '-', @str ) + 1, LEN( @str ) ), CHARINDEX( '-', @str ) + 1, LEN( @str ) )

Returns XXX - XXXX


问:
Xamarin Android - how to access Activity context from an event handler?
I am running a call to a WCF service in a Xamarin.Android app like so:

```<code>WCF.TestCompleted += WCF_TestCompleted;
WCF.TestAsync("stringtest");
</code>```

It has an event handler like this:

```<code>        public static void WCF_TestCompleted(object sender, TestCompletedEventArgs e)
    {
       // various code
        ListAdapter = new OrdersAdapter(this, order, orderDetail);
    }
</code>```

However I cannot access my list adaptor in this even handler because "this" has no context and is expecting the Activity context.

How can I access the main context again?

From reading over posts on StackOverlfow I thought the answe would be:

```<code>ListAdapter = new OrdersAdapter(Application.context, order, orderDetail);
</code>```

But this returns an error:

Argument 1: cannot convert from 'Android.Content.Context' to 'Android.App.Activity'

答:
You could group the WCF object and a reference to the activity in a Facade like pattern class:

```<code>class WCFFacadeThingy()
{
    Activity myActivity;
    public WCF;
    WCFFacadeThingy(Activity activity)
    {
      myActivity = activity;

      initWCF(); //init the WCF instance in here
      WCF.TestCompleted += WCF_TestCompleted;
    }

     //Note not static method here
    public void WCF_TestCompleted(object sender,
     TestCompletedEventArgs e)
    {
       // various code
        ListAdapter list = new OrdersAdapter(myActivity, order, orderDetail);
    }
}
</code>```

And then somewhere in your activity:

```<code>WCFFacadeThingy w = new WCFFacadeThingy(this);
w.WCF.TestAsync("stringtest");
</code>```

It might also be worth making the activity a weak reference incase it needs to be destroyed to prevent memory leaks.

Body:
I am running a call to a WCF service in a Xamarin.Android app like so:

WCF.TestCompleted += WCF_TestCompleted;
WCF.TestAsync("stringtest");

It has an event handler like this:

        public static void WCF_TestCompleted(object sender, TestCompletedEventArgs e)
    {
       // various code
        ListAdapter = new OrdersAdapter(this, order, orderDetail);
    }

However I cannot access my list adaptor in this even handler because "this" has no context and is expecting the Activity context.

How can I access the main context again?

From reading over posts on StackOverlfow I thought the answe would be:

ListAdapter = new OrdersAdapter(Application.context, order, orderDetail);

But this returns an error:

Argument 1: cannot convert from 'Android.Content.Context' to 'Android.App.Activity'

Body:
You could group the WCF object and a reference to the activity in a Facade like pattern class:

class WCFFacadeThingy()
{
    Activity myActivity;
    public WCF;
    WCFFacadeThingy(Activity activity)
    {
      myActivity = activity;

      initWCF(); //init the WCF instance in here
      WCF.TestCompleted += WCF_TestCompleted;
    }

     //Note not static method here
    public void WCF_TestCompleted(object sender,
     TestCompletedEventArgs e)
    {
       // various code
        ListAdapter list = new OrdersAdapter(myActivity, order, orderDetail);
    }
}

And then somewhere in your activity:

WCFFacadeThingy w = new WCFFacadeThingy(this);
w.WCF.TestAsync("stringtest");

It might also be worth making the activity a weak reference incase it needs to be destroyed to prevent memory leaks.


问:
How to get view to fill remaining width in JavaFX
I'm using fxml in JavaFX and I want a list master/detail view. A list on the left of a fixed size, and a detail of a TextArea where the width grows with the window size.

This is my fxml:

```<code><?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.ListView?>
<?import javafx.scene.control.Menu?>
<?import javafx.scene.control.MenuBar?>
<?import javafx.scene.control.MenuItem?>
<?import javafx.scene.control.TextArea?>
<?import javafx.scene.layout.BorderPane?>
<?import javafx.scene.layout.HBox?>

<BorderPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="800.0" prefWidth="1280.0" xmlns="http://javafx.com/javafx/8.0.111" xmlns:fx="http://javafx.com/fxml/1">
   <top>
      <MenuBar prefWidth="671.0" BorderPane.alignment="CENTER">
        <menus>
          <Menu mnemonicParsing="false" text="File">
            <items>
              <MenuItem mnemonicParsing="false" text="Close" />
            </items>
          </Menu>
          <Menu mnemonicParsing="false" text="Edit">
            <items>
              <MenuItem mnemonicParsing="false" text="Delete" />
            </items>
          </Menu>
          <Menu mnemonicParsing="false" text="Help">
            <items>
              <MenuItem mnemonicParsing="false" text="About" />
            </items>
          </Menu>
        </menus>
      </MenuBar>
   </top>
   <center>
      <HBox BorderPane.alignment="CENTER">
         <children>
            <ListView prefHeight="754.0" prefWidth="236.0" />
            <TextArea />
         </children>
      </HBox>
   </center>
</BorderPane>
</code>```

This sample fxml looks like this:

You can see that the list is correct, and the textArea is showing and growing in height but not in width.

EDIT

Modified due to an answer.

This is the full code now. I only changed the max width and height of -Infinity to -1 but still no luck.

```<code><?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.ListView?>
<?import javafx.scene.control.Menu?>
<?import javafx.scene.control.MenuBar?>
<?import javafx.scene.control.MenuItem?>
<?import javafx.scene.control.TextArea?>
<?import javafx.scene.layout.BorderPane?>
<?import javafx.scene.layout.HBox?>

<BorderPane maxHeight="-1" maxWidth="-1" minHeight="-Infinity" minWidth="-Infinity" prefHeight="800.0" prefWidth="1280.0" xmlns="http://javafx.com/javafx/8.0.111" xmlns:fx="http://javafx.com/fxml/1">
    <top>
        <MenuBar prefWidth="671.0" BorderPane.alignment="CENTER">
            <menus>
                <Menu mnemonicParsing="false" text="File">
                    <items>
                        <MenuItem mnemonicParsing="false" text="Close" />
                    </items>
                </Menu>
                <Menu mnemonicParsing="false" text="Edit">
                    <items>
                        <MenuItem mnemonicParsing="false" text="Delete" />
                    </items>
                </Menu>
                <Menu mnemonicParsing="false" text="Help">
                    <items>
                        <MenuItem mnemonicParsing="false" text="About" />
                    </items>
                </Menu>
            </menus>
        </MenuBar>
    </top>
    <center>
        <HBox BorderPane.alignment="CENTER">
            <children>
                <ListView prefHeight="754.0" prefWidth="236.0" />
                <TextArea />
            </children>
        </HBox>
    </center>
</BorderPane>
</code>```

答:
Set the HBox.hgrow property of the text area:

<TextArea HBox.hgrow="ALWAYS"/>
```

Body:
I'm using fxml in JavaFX and I want a list master/detail view. A list on the left of a fixed size, and a detail of a TextArea where the width grows with the window size.

This is my fxml:

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.ListView?>
<?import javafx.scene.control.Menu?>
<?import javafx.scene.control.MenuBar?>
<?import javafx.scene.control.MenuItem?>
<?import javafx.scene.control.TextArea?>
<?import javafx.scene.layout.BorderPane?>
<?import javafx.scene.layout.HBox?>

<BorderPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="800.0" prefWidth="1280.0" xmlns="http://javafx.com/javafx/8.0.111" xmlns:fx="http://javafx.com/fxml/1">
   <top>
      <MenuBar prefWidth="671.0" BorderPane.alignment="CENTER">
        <menus>
          <Menu mnemonicParsing="false" text="File">
            <items>
              <MenuItem mnemonicParsing="false" text="Close" />
            </items>
          </Menu>
          <Menu mnemonicParsing="false" text="Edit">
            <items>
              <MenuItem mnemonicParsing="false" text="Delete" />
            </items>
          </Menu>
          <Menu mnemonicParsing="false" text="Help">
            <items>
              <MenuItem mnemonicParsing="false" text="About" />
            </items>
          </Menu>
        </menus>
      </MenuBar>
   </top>

      <HBox BorderPane.alignment="CENTER">
         <children>
            <ListView prefHeight="754.0" prefWidth="236.0" />
            <TextArea />
         </children>
      </HBox>

</BorderPane>

This sample fxml looks like this:

You can see that the list is correct, and the textArea is showing and growing in height but not in width.

EDIT

Modified due to an answer.

This is the full code now. I only changed the max width and height of -Infinity to -1 but still no luck.

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.ListView?>
<?import javafx.scene.control.Menu?>
<?import javafx.scene.control.MenuBar?>
<?import javafx.scene.control.MenuItem?>
<?import javafx.scene.control.TextArea?>
<?import javafx.scene.layout.BorderPane?>
<?import javafx.scene.layout.HBox?>

<BorderPane maxHeight="-1" maxWidth="-1" minHeight="-Infinity" minWidth="-Infinity" prefHeight="800.0" prefWidth="1280.0" xmlns="http://javafx.com/javafx/8.0.111" xmlns:fx="http://javafx.com/fxml/1">
    <top>
        <MenuBar prefWidth="671.0" BorderPane.alignment="CENTER">
            <menus>
                <Menu mnemonicParsing="false" text="File">
                    <items>
                        <MenuItem mnemonicParsing="false" text="Close" />
                    </items>
                </Menu>
                <Menu mnemonicParsing="false" text="Edit">
                    <items>
                        <MenuItem mnemonicParsing="false" text="Delete" />
                    </items>
                </Menu>
                <Menu mnemonicParsing="false" text="Help">
                    <items>
                        <MenuItem mnemonicParsing="false" text="About" />
                    </items>
                </Menu>
            </menus>
        </MenuBar>
    </top>

        <HBox BorderPane.alignment="CENTER">
            <children>
                <ListView prefHeight="754.0" prefWidth="236.0" />
                <TextArea />
            </children>
        </HBox>

</BorderPane>


问:
How to recode variables in table 1 using info from table 2 (in SAS)

The overal goal is to stratify quantitative variables based on their percentile. I would like to break it up into 10 levels (e.g. 10th, 20th, ...100th percentile) and recode it as 1 if it falls into the 10th percentile, 2 if it falls into the 20th percentile, etc. This method needs to be applicable across any data set I plug in and I want this process to be as automated as possible. Below I have generated some test data:

```<code>data test (drop=i);
do i=1 to 1000;
a=round(uniform(1)*4,.01);
b=round(uniform(1)*10,.01);
c=round(uniform(1)*7.5,.01);
output;
end;
stop;
run;
</code>```

The following macro is used to create a table of values that tells you the cut off for the 10 percentiles of each variable. I have added a picture of the example output below the code.

```<code>/*Recode variables based on quartiles from boxplot*/
%macro percentiles(var);
     /* Count the number of values in the strinrecode */
     %let count=%sysfunc(countw(&var));
     /* Loop throurecodeh the total number of values */
     %do i = 1 %to &count;
      %let variables=%qscan(&var,&i,%str(,));
proc univariate data=test noprint;
   var &variables;
   output out=pcts pctlpts  = 10 20 30 40 50 60 70 80 90 100
                    pctlpre  = &variables;
run;
proc transpose data=pcts out=&variables (rename=(col1=&variables) drop=_NAME_ _LABEL_);
run;
     %end;
data percentiles (drop=i);
do i=1 to 10;
recode=i;
percentile=i*10;
output;
end;
stop;
run;

data pcts;
merge percentiles %sysfunc(tranwrd(&var.,%str(,),%str( )));
run;
%mend;
%percentiles(%str(a,b,c));
</code>```

output from above macro

The following code is how I am currently recoding my variables. I use the table generated in the above macro to fill in the cut off points for each percentile for each variable. As you can see, this is very tedious and will become prohibitive if I have a large number of variables to recode. Is there a better process for this or preferably a way I could automate this part?

```<code>data test;
set test;
if a <= .415 then recode_a = 1; else if a <= .785 then recode_a = 2; else if a <= 1.255 then recode_a = 3;
else if a <= 1.61 then recode_a = 4;   else if a <= 2.03 then recode_a = 5; else if a <= 2.42 then recode_a = 6;
else if a <= 2.76 then recode_a = 7; else if a <= 3.18 then recode_a = 8; else if a <= 3.64 then recode_a = 9;
else if a <= 3.99 then recode_a = 10;
if b <= .845 then recode_b = 1; else if b <= 1.88 then recode_b = 2; else if b <= 2.86 then recode_b = 3;
else if b <= 4.005 then recode_b = 4;   else if b <= 5.03 then recode_b = 5; else if b <= 6.07 then recode_b = 6;
else if b <= 6.995 then recode_b = 7; else if b <= 8.035 then recode_b = 8; else if b <= 9.16 then recode_b = 9;
else if b <= 10 then recode_b = 10;
if c <= .86 then recode_c = 1; else if c <= 1.58 then recode_c = 2; else if c <= 2.34 then recode_c = 3;
else if c <= 3.15 then recode_c = 4;   else if c <= 3.85 then recode_c = 5; else if c <= 4.615 then recode_c = 6;
else if c <= 5.315 then recode_c = 7; else if c <= 5.96 then recode_c = 8; else if c <= 6.75 then recode_c = 9;
else if c <= 7.5 then recode_c = 10;
run;

proc print data=test (obs=5);
run;
</code>```

sample of desired output

答:
The following should work for you dynamically with no hard-coding -- I edited to compact it into a single macro. Essentially it puts your desired variables into a list, creates a dataset using your output, and then uses the variable contents to put your data steps into long strings. These strings are then put into a macro variable and you can call it in your final data step. Again, no hard-coding involved. </p>

```<code>%MACRO stratify(library=,input=,output=);
%local varlist varlist_space data_step_list;

    ** get vars into comma-separated list and space-separated list **;
    proc sql noprint;
        select NAME
        into: varlist separated by ","
        from dictionary.columns
        where libname=upcase("&library.") and memname=upcase("&input.");

        select NAME
        into: varlist_space separated by " "
        from dictionary.columns
        where libname=upcase("&library.") and memname=upcase("&input.");
    quit;

    %percentiles(%bquote(&varlist.));

    ** put data into long format **;
    proc transpose data = pcts out=pcts_long;
        by recode percentile;
        var &varlist_space.;
    run;

    ** sort to get if-else order **;
    proc sort data = pcts_long;
        by _NAME_ percentile;
    run;

    ** create your if-then strings using data itself **;
    data str;
        length STR $100;
        set pcts_long;
        bin = percentile/10;
        by _NAME_;
        if first._NAME_ then do;
            STR = "if "||strip(_NAME_)||" <= "||strip(put(COL1,best.))||" then "||catx("_","recode",_NAME_)||" = "||strip(put(bin,best.))||";";
        end;
        else do;
            STR = "else if "||strip(_NAME_)||" <= "||strip(put(COL1,best.))||" then "||catx("_","recode",_NAME_)||" = "||strip(put(bin,best.))||";";
        end;
    run;

    ** put strings into a list **;
    proc sql noprint;
        select STR
        into: data_step_list separated by " "
        from STR;
    quit;

    ** call data step list in final data **;
    data &output.; set &input.;
        &data_step_list.;
    run;

    proc print data = &output.(obs=5);
    run;

%MEND;

%stratify(library=work,input=test,output=final);
</code>```

Body:
The overal goal is to stratify quantitative variables based on their percentile. I would like to break it up into 10 levels (e.g. 10th, 20th, ...100th percentile) and recode it as 1 if it falls into the 10th percentile, 2 if it falls into the 20th percentile, etc. This method needs to be applicable across any data set I plug in and I want this process to be as automated as possible. Below I have generated some test data:

data test (drop=i);
do i=1 to 1000;
a=round(uniform(1)*4,.01);
b=round(uniform(1)*10,.01);
c=round(uniform(1)*7.5,.01);
output;
end;
stop;
run;

The following macro is used to create a table of values that tells you the cut off for the 10 percentiles of each variable. I have added a picture of the example output below the code.

/*Recode variables based on quartiles from boxplot*/
%macro percentiles(var);
     /* Count the number of values in the strinrecode */
     %let count=%sysfunc(countw(&var));
     /* Loop throurecodeh the total number of values */
     %do i = 1 %to &count;
      %let variables=%qscan(&var,&i,%str(,));
proc univariate data=test noprint;
   var &variables;
   output out=pcts pctlpts  = 10 20 30 40 50 60 70 80 90 100
                    pctlpre  = &variables;
run;
proc transpose data=pcts out=&variables (rename=(col1=&variables) drop=_NAME_ _LABEL_);
run;
     %end;
data percentiles (drop=i);
do i=1 to 10;
recode=i;
percentile=i*10;
output;
end;
stop;
run;

data pcts;
merge percentiles %sysfunc(tranwrd(&var.,%str(,),%str( )));
run;
%mend;
%percentiles(%str(a,b,c));

output from above macro

The following code is how I am currently recoding my variables. I use the table generated in the above macro to fill in the cut off points for each percentile for each variable. As you can see, this is very tedious and will become prohibitive if I have a large number of variables to recode. Is there a better process for this or preferably a way I could automate this part?

data test;
set test;
if a <= .415 then recode_a = 1; else if a <= .785 then recode_a = 2; else if a <= 1.255 then recode_a = 3;
else if a <= 1.61 then recode_a = 4;   else if a <= 2.03 then recode_a = 5; else if a <= 2.42 then recode_a = 6;
else if a <= 2.76 then recode_a = 7; else if a <= 3.18 then recode_a = 8; else if a <= 3.64 then recode_a = 9;
else if a <= 3.99 then recode_a = 10;
if b <= .845 then recode_b = 1; else if b <= 1.88 then recode_b = 2; else if b <= 2.86 then recode_b = 3;
else if b <= 4.005 then recode_b = 4;   else if b <= 5.03 then recode_b = 5; else if b <= 6.07 then recode_b = 6;
else if b <= 6.995 then recode_b = 7; else if b <= 8.035 then recode_b = 8; else if b <= 9.16 then recode_b = 9;
else if b <= 10 then recode_b = 10;
if c <= .86 then recode_c = 1; else if c <= 1.58 then recode_c = 2; else if c <= 2.34 then recode_c = 3;
else if c <= 3.15 then recode_c = 4;   else if c <= 3.85 then recode_c = 5; else if c <= 4.615 then recode_c = 6;
else if c <= 5.315 then recode_c = 7; else if c <= 5.96 then recode_c = 8; else if c <= 6.75 then recode_c = 9;
else if c <= 7.5 then recode_c = 10;
run;

proc print data=test (obs=5);
run;

sample of desired output

Body:
The following should work for you dynamically with no hard-coding -- I edited to compact it into a single macro. Essentially it puts your desired variables into a list, creates a dataset using your output, and then uses the variable contents to put your data steps into long strings. These strings are then put into a macro variable and you can call it in your final data step. Again, no hard-coding involved.

%MACRO stratify(library=,input=,output=);
%local varlist varlist_space data_step_list;

    ** get vars into comma-separated list and space-separated list **;
    proc sql noprint;
        select NAME
        into: varlist separated by ","
        from dictionary.columns
        where libname=upcase("&library.") and memname=upcase("&input.");

        select NAME
        into: varlist_space separated by " "
        from dictionary.columns
        where libname=upcase("&library.") and memname=upcase("&input.");
    quit;

    %percentiles(%bquote(&varlist.));

    ** put data into long format **;
    proc transpose data = pcts out=pcts_long;
        by recode percentile;
        var &varlist_space.;
    run;

    ** sort to get if-else order **;
    proc sort data = pcts_long;
        by _NAME_ percentile;
    run;

    ** create your if-then strings using data itself **;
    data str;
        length STR $100;
        set pcts_long;
        bin = percentile/10;
        by _NAME_;
        if first._NAME_ then do;
            STR = "if "||strip(_NAME_)||" <= "||strip(put(COL1,best.))||" then "||catx("_","recode",_NAME_)||" = "||strip(put(bin,best.))||";";
        end;
        else do;
            STR = "else if "||strip(_NAME_)||" <= "||strip(put(COL1,best.))||" then "||catx("_","recode",_NAME_)||" = "||strip(put(bin,best.))||";";
        end;
    run;

    ** put strings into a list **;
    proc sql noprint;
        select STR
        into: data_step_list separated by " "
        from STR;
    quit;

    ** call data step list in final data **;
    data &output.; set &input.;
        &data_step_list.;
    run;

    proc print data = &output.(obs=5);
    run;

%MEND;

%stratify(library=work,input=test,output=final);


问:
Difference Windows Azure and GoDaddy
What are all the differences between Microsofts Window's azure and web hosting companies like   GoDaddy, hostgator ? </p>

答:
Here are a few key differences to consider:

Server usage. With a hoster like GoDaddy, servers are shared resources, and there's no way to figure out (or limit) the number of tenants sharing a given server with your app. With Azure, a given server, with its 8 cores, is allocated to specific VMs. At most, 8 virtual machines will be deployed to a given server.

SLA. With a shared-hoster like GoDaddy, there's no built-in way to scale your app, or to ensure availability with multiple servers running your app. With Azure, you can easily scale to 2 or more instances, ensuring at least 99.95% availability.

Virtual servers. As a clarification to the point above: GoDaddy now offers virtual servers, with cost starting at roughly $30 per month. However, this offering does not provide any scaling support.

Durable storage. Aside from SQL Azure (GoDaddy provides SQL Server hosting), Azure provides tables, blobs and queues, each triple-replicated. Further, Azure can deploy a new SQL Azure instance in a few seconds. SQL Azure is also triple-replicated.

Monitoring and diagnostics infrastructure. Azure provides a diagnostics infrastructure to capture things like performance counters, queue sizes, custom log files, etc. and consolidate them into easily accessible/queryable table and blob storage. You can then build app-monitoring apps around this set of diagnostics. Also, the Azure fabric itself monitors your application's health. In the event of a failed server, for instance, your app is restarted on another server automatically. I'm unaware of any automated health monitoring and recovery system built into cheap/shared hosting solutions such as those offered by GoDaddy.

Additional services on-demand. In Azure, you have access to several consumable services, such as SQL Azure, service bus, scalable storage (blobs, tables, queues), access control, caching (going live in 2011), and Reporting Services (going live in 2011).

Title: Difference Windows Azure and GoDaddy


问:
set tabbar item to custom image like instagram
I have been trying to look for this solution for a very long time, but I can not find any documentation or tutorials on it. I want to set a tabbar item to the user's profile picture. Each user can only log into the app through Facebook. The app then takes the user's profile picture from facebook and stores it in firebase storage. I want to retrieve that image and set it to a tabbar item, but unfortunately, it is not working. Here is the code I have so far:

```<code>override func awakeFromNib() {
        super.awakeFromNib()
        self.tabBarItem.title = "MY ACCOUNT"
        if self.loggedInUserUid != nil {

            let imageRef = FIRStorage.storage().reference().child((loggedInUserUid)!+"/profile_pic.jpg")

            imageRef.data(withMaxSize: 75 * 144 * 96, completion: { (data, error) -> Void in
                if error != nil {
                    print(error!)
                    return
                }
                DispatchQueue.main.async(execute: { () -> Void in
                    let image = UIImage(data: data!)
                    self.tabBarItem.image = image
                })

            }).resume()
}}
</code>```

i get the error:
Could not load the "" image referenced from a nib in the bundle with identifier

答:
In the storyboard click on the image. Go to the column on the right (activate it if it's not visible by clicking on the appropriate button) and find a place that says something like "identifier". Enter a short name there. Then use this identifier instead of the path you're using.
Based on the error message it looks like you've defined the image in your storyboard without an identifier. If that's true you don't need all the code to load the image manually.
You should pick one method or the other. But not both.
I'd love to be more specific but I'm away just now and on my phone. </p>

Body:
I have been trying to look for this solution for a very long time, but I can not find any documentation or tutorials on it. I want to set a tabbar item to the user's profile picture. Each user can only log into the app through Facebook. The app then takes the user's profile picture from facebook and stores it in firebase storage. I want to retrieve that image and set it to a tabbar item, but unfortunately, it is not working. Here is the code I have so far:

override func awakeFromNib() {
        super.awakeFromNib()
        self.tabBarItem.title = "MY ACCOUNT"
        if self.loggedInUserUid != nil {

            let imageRef = FIRStorage.storage().reference().child((loggedInUserUid)!+"/profile_pic.jpg")

            imageRef.data(withMaxSize: 75 * 144 * 96, completion: { (data, error) -> Void in
                if error != nil {
                    print(error!)
                    return
                }
                DispatchQueue.main.async(execute: { () -> Void in
                    let image = UIImage(data: data!)
                    self.tabBarItem.image = image
                })

            }).resume()
}}

i get the error:
Could not load the "" image referenced from a nib in the bundle with identifier


问:
Inserting an image in a QScintilla editor
EDIT:

The standard QScintilla software doesn't support this feature. But Matic Kukovec made some hacks to get it working anyhow. His solution is explained in his answer below, but also on this webpage: https://qscintilla.com/insert-images/

I would like to insert images in a QScintilla editor. Unfortunately, such a feature won't be added to the official Scintilla project anytime soon. Check out this post on the Scintilla-interest-group:

https://groups.google.com/forum/#!topic/scintilla-interest/Bwr4DY2Pv3Q

So I'll have to implement it myself. I have given it a try. Please copy-past the following code into a python-file and run it. Just make sure you have a qscintilla_logo.png image in the same folder, of around 80 x 80 pixels:

```<code>import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.Qsci import *

# -----------------------------------
# | A sample of C-code, pasted into |
# | the QScintilla editor           |
# -----------------------------------
myCodeSample = r"""#include <stdio.h>

/*
 * I want an image
 * right here =>
 */

int main()
{
    char arr[5] = {'h', 'e', 'l', 'l', 'o'};

    int i;

    for(i = 0; i < 5; i++) {
        printf(arr[i]);
    }

    return 0;

}""".replace("\n","\r\n")

# --------------------------------------------------

class CustomMainWindow(QMainWindow):
    def __init__(self):
        super(CustomMainWindow, self).__init__()

        # ---------------------------
        # |      Window setup       |
        # ---------------------------

        # 1. Define the geometry of the main window
        # ------------------------------------------
        self.setGeometry(300, 300, 800, 400)
        self.setWindowTitle("QScintilla Test")

        # 2. Create frame and layout
        # ---------------------------
        self.__frm = QFrame(self)
        self.__frm.setStyleSheet("QWidget { background-color: #ffeaeaea }")
        self.__lyt = QVBoxLayout()
        self.__frm.setLayout(self.__lyt)
        self.setCentralWidget(self.__frm)
        self.__myFont = QFont("Consolas", 14, weight=QFont.Bold)
        self.__myFont.setPointSize(14)

        # 3. Place a button
        # ------------------
        self.__btn = QPushButton("Qsci")
        self.__btn.setFixedWidth(50)
        self.__btn.setFixedHeight(50)
        self.__btn.clicked.connect(self.__btn_action)
        self.__btn.setFont(self.__myFont)
        self.__lyt.addWidget(self.__btn)

        # ---------------------------
        # | QScintilla editor setup |
        # ---------------------------

        # 1. Make instance of QSciScintilla class
        # ----------------------------------------
        self.__editor = QsciScintilla()
        self.__editor.setText(myCodeSample)
        self.__editor.setLexer(None)
        self.__editor.setUtf8(True)  # Set encoding to UTF-8
        self.__editor.setFont(self.__myFont)  # Can be overridden by lexer

        # 2. Create an image
        # -------------------
        self.__myImg = QPixmap("qscintilla_logo.png")
        self.__myImgLbl = QLabel(parent=self.__editor)
        self.__myImgLbl.setStyleSheet("QLabel { background-color : white; }");
        self.__myImgLbl.setPixmap(self.__myImg)
        self.__myImgLbl.move(300,80)

        # 3. Add editor to layout
        # ------------------------
        self.__lyt.addWidget(self.__editor)

        self.show()

    ''''''

    def __btn_action(self):
        print("Hello World!")

    ''''''

''' End Class '''

if __name__ == '__main__':
    app = QApplication(sys.argv)
    QApplication.setStyle(QStyleFactory.create('Fusion'))
    myGUI = CustomMainWindow()

    sys.exit(app.exec_())

''''''
</code>```

When running the Python script, you should get the following result:

I'm actually adding a QLabel on top of the editor, and give it an absolute position:

```<code>        self.__myImgLbl = QLabel(parent=self.__editor)
        self.__myImgLbl.move(300,80)
</code>```

Unfortunately, the image won't move when scrolling down:

I think I know why. Let me explain. The editor is an object of the QsciScintilla class, which is a subclass of QsciScintillaBase, which is a subclass of QAbstractScrollArea:

I believe that the key to success is adding the QLabel to the widget inside the QAbstractScrollArea, not the scroll area itself. I have tried several things to find that widget, but didn't succeed.
If it were a QScrollArea, then the function widget() would be sufficient. But this function is not available on a QAbstractScrollArea.

EDIT 1:

The editor in the python code sample doesn't perform any syntax highlighting, and even doesn't have line numbers. That's because I want to focus only on the actual issue - adding an image. The code sample is based on: https://qscintilla.com/an-editor-in-a-gui/

EDIT 2:

Please, kindly refrain from giving opinions on whether inserting images in an editor is a good or bad idea. Let us just stick to the technical issue at hand.

答:
Hey Kristof try this (your example with some modifications):

```<code>import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.Qsci import *

# -----------------------------------
# | A sample of C-code, pasted into |
# | the QScintilla editor           |
# -----------------------------------
myCodeSample = r"""#include <stdio.h>

/*
 * I want an image
 * right here =>
 */

int main()
{
    char arr[5] = {'h', 'e', 'l', 'l', 'o'};

    int i;

    for(i = 0; i < 5; i++) {
        printf(arr[i]);
    }

    return 0;

}""".replace("\n","\r\n")

# --------------------------------------------------
class MyScintilla(QsciScintilla):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.image = QImage("qscintilla_logo.png")

    def paintEvent(self, e):
        super().paintEvent(e)
        # Get paint rectangle size
        current_parent_size = self.size()
        image_line = 4
        image_column = 17
        # Find the paint offset
        line_height = 20
        font_width = 10
        first_visible_line = self.SendScintilla(self.SCI_GETFIRSTVISIBLELINE)
        paint_offset_x = image_column * font_width
        paint_offset_y = (image_line - first_visible_line) * line_height
        # Paint the image
        painter = QPainter()
        painter.begin(self.viewport())
        painter.drawImage(QPoint(paint_offset_x,paint_offset_y), self.image)
        painter.end()

class CustomMainWindow(QMainWindow):
    def __init__(self):
        super(CustomMainWindow, self).__init__()

        # ---------------------------
        # |      Window setup       |
        # ---------------------------

        # 1. Define the geometry of the main window
        # ------------------------------------------
        self.setGeometry(300, 300, 800, 400)
        self.setWindowTitle("QScintilla Test")

        # 2. Create frame and layout
        # ---------------------------
        self.__frm = QFrame(self)
        self.__frm.setStyleSheet("QWidget { background-color: #ffeaeaea }")
        self.__lyt = QVBoxLayout()
        self.__frm.setLayout(self.__lyt)
        self.setCentralWidget(self.__frm)
        self.__myFont = QFont("Consolas", 14, weight=QFont.Bold)
        self.__myFont.setPointSize(14)

        # 3. Place a button
        # ------------------
        self.__btn = QPushButton("Qsci")
        self.__btn.setFixedWidth(50)
        self.__btn.setFixedHeight(50)
        self.__btn.clicked.connect(self.__btn_action)
        self.__btn.setFont(self.__myFont)
        self.__lyt.addWidget(self.__btn)

        # ---------------------------
        # | QScintilla editor setup |
        # ---------------------------

        # 1. Make instance of QSciScintilla class
        # ----------------------------------------
        self.__editor = MyScintilla()
        self.__editor.setText(myCodeSample)
        self.__editor.setLexer(None)
        self.__editor.setUtf8(True)  # Set encoding to UTF-8
        self.__editor.setFont(self.__myFont)  # Can be overridden by lexer

        # 3. Add editor to layout
        # ------------------------
        self.__lyt.addWidget(self.__editor)

        self.show()

    ''''''

    def __btn_action(self):
        print("Hello World!")

    ''''''

''' End Class '''

if __name__ == '__main__':
    app = QApplication(sys.argv)
    QApplication.setStyle(QStyleFactory.create('Fusion'))
    myGUI = CustomMainWindow()

    sys.exit(app.exec_())

''''''
</code>```

It is just subclassing the QsciScintilla class and overloading it's paintEvent method.
The trick is to get the coordinates of where the image is in relation to the view of the document. For the example I justed guessed the line height and font width, it can probably be obtained from the QScintilla.
The other thing is I just hard coded the position of the image with a line and column offset, it would probably be good to create a syntax that the editor could parse and insert the image automatically.

Regards

Body:
EDIT:

The standard QScintilla software doesn't support this feature. But Matic Kukovec made some hacks to get it working anyhow. His solution is explained in his answer below, but also on this webpage: https://qscintilla.com/insert-images/

I would like to insert images in a QScintilla editor. Unfortunately, such a feature won't be added to the official Scintilla project anytime soon. Check out this post on the Scintilla-interest-group:

https://groups.google.com/forum/#!topic/scintilla-interest/Bwr4DY2Pv3Q

So I'll have to implement it myself. I have given it a try. Please copy-past the following code into a python-file and run it. Just make sure you have a qscintilla_logo.png image in the same folder, of around 80 x 80 pixels:

import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.Qsci import *

# -----------------------------------
# | A sample of C-code, pasted into |
# | the QScintilla editor           |
# -----------------------------------
myCodeSample = r"""#include <stdio.h>

/*
 * I want an image
 * right here =>
 */

int main()
{
    char arr[5] = {'h', 'e', 'l', 'l', 'o'};

    int i;

    for(i = 0; i < 5; i++) {
        printf(arr[i]);
    }

    return 0;

}""".replace("\n","\r\n")

# --------------------------------------------------

class CustomMainWindow(QMainWindow):
    def __init__(self):
        super(CustomMainWindow, self).__init__()

        # ---------------------------
        # |      Window setup       |
        # ---------------------------

        # 1. Define the geometry of the main window
        # ------------------------------------------
        self.setGeometry(300, 300, 800, 400)
        self.setWindowTitle("QScintilla Test")

        # 2. Create frame and layout
        # ---------------------------
        self.__frm = QFrame(self)
        self.__frm.setStyleSheet("QWidget { background-color: #ffeaeaea }")
        self.__lyt = QVBoxLayout()
        self.__frm.setLayout(self.__lyt)
        self.setCentralWidget(self.__frm)
        self.__myFont = QFont("Consolas", 14, weight=QFont.Bold)
        self.__myFont.setPointSize(14)

        # 3. Place a button
        # ------------------
        self.__btn = QPushButton("Qsci")
        self.__btn.setFixedWidth(50)
        self.__btn.setFixedHeight(50)
        self.__btn.clicked.connect(self.__btn_action)
        self.__btn.setFont(self.__myFont)
        self.__lyt.addWidget(self.__btn)

        # ---------------------------
        # | QScintilla editor setup |
        # ---------------------------

        # 1. Make instance of QSciScintilla class
        # ----------------------------------------
        self.__editor = QsciScintilla()
        self.__editor.setText(myCodeSample)
        self.__editor.setLexer(None)
        self.__editor.setUtf8(True)  # Set encoding to UTF-8
        self.__editor.setFont(self.__myFont)  # Can be overridden by lexer

        # 2. Create an image
        # -------------------
        self.__myImg = QPixmap("qscintilla_logo.png")
        self.__myImgLbl = QLabel(parent=self.__editor)
        self.__myImgLbl.setStyleSheet("QLabel { background-color : white; }");
        self.__myImgLbl.setPixmap(self.__myImg)
        self.__myImgLbl.move(300,80)

        # 3. Add editor to layout
        # ------------------------
        self.__lyt.addWidget(self.__editor)

        self.show()

    ''''''

    def __btn_action(self):
        print("Hello World!")

    ''''''

''' End Class '''

if __name__ == '__main__':
    app = QApplication(sys.argv)
    QApplication.setStyle(QStyleFactory.create('Fusion'))
    myGUI = CustomMainWindow()

    sys.exit(app.exec_())

''''''

When running the Python script, you should get the following result:

I'm actually adding a QLabel on top of the editor, and give it an absolute position:

        self.__myImgLbl = QLabel(parent=self.__editor)
        self.__myImgLbl.move(300,80)

Unfortunately, the image won't move when scrolling down:

I think I know why. Let me explain. The editor is an object of the QsciScintilla class, which is a subclass of QsciScintillaBase, which is a subclass of QAbstractScrollArea:

I believe that the key to success is adding the QLabel to the widget inside the QAbstractScrollArea, not the scroll area itself. I have tried several things to find that widget, but didn't succeed.
If it were a QScrollArea, then the function widget() would be sufficient. But this function is not available on a QAbstractScrollArea.

EDIT 1:

The editor in the python code sample doesn't perform any syntax highlighting, and even doesn't have line numbers. That's because I want to focus only on the actual issue - adding an image. The code sample is based on: https://qscintilla.com/an-editor-in-a-gui/

EDIT 2:

Please, kindly refrain from giving opinions on whether inserting images in an editor is a good or bad idea. Let us just stick to the technical issue at hand.

Body:
Hey Kristof try this (your example with some modifications):

import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.Qsci import *

# -----------------------------------
# | A sample of C-code, pasted into |
# | the QScintilla editor           |
# -----------------------------------
myCodeSample = r"""#include <stdio.h>

/*
 * I want an image
 * right here =>
 */

int main()
{
    char arr[5] = {'h', 'e', 'l', 'l', 'o'};

    int i;

    for(i = 0; i < 5; i++) {
        printf(arr[i]);
    }

    return 0;

}""".replace("\n","\r\n")

# --------------------------------------------------
class MyScintilla(QsciScintilla):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.image = QImage("qscintilla_logo.png")

    def paintEvent(self, e):
        super().paintEvent(e)
        # Get paint rectangle size
        current_parent_size = self.size()
        image_line = 4
        image_column = 17
        # Find the paint offset
        line_height = 20
        font_width = 10
        first_visible_line = self.SendScintilla(self.SCI_GETFIRSTVISIBLELINE)
        paint_offset_x = image_column * font_width
        paint_offset_y = (image_line - first_visible_line) * line_height
        # Paint the image
        painter = QPainter()
        painter.begin(self.viewport())
        painter.drawImage(QPoint(paint_offset_x,paint_offset_y), self.image)
        painter.end()

class CustomMainWindow(QMainWindow):
    def __init__(self):
        super(CustomMainWindow, self).__init__()

        # ---------------------------
        # |      Window setup       |
        # ---------------------------

        # 1. Define the geometry of the main window
        # ------------------------------------------
        self.setGeometry(300, 300, 800, 400)
        self.setWindowTitle("QScintilla Test")

        # 2. Create frame and layout
        # ---------------------------
        self.__frm = QFrame(self)
        self.__frm.setStyleSheet("QWidget { background-color: #ffeaeaea }")
        self.__lyt = QVBoxLayout()
        self.__frm.setLayout(self.__lyt)
        self.setCentralWidget(self.__frm)
        self.__myFont = QFont("Consolas", 14, weight=QFont.Bold)
        self.__myFont.setPointSize(14)

        # 3. Place a button
        # ------------------
        self.__btn = QPushButton("Qsci")
        self.__btn.setFixedWidth(50)
        self.__btn.setFixedHeight(50)
        self.__btn.clicked.connect(self.__btn_action)
        self.__btn.setFont(self.__myFont)
        self.__lyt.addWidget(self.__btn)

        # ---------------------------
        # | QScintilla editor setup |
        # ---------------------------

        # 1. Make instance of QSciScintilla class
        # ----------------------------------------
        self.__editor = MyScintilla()
        self.__editor.setText(myCodeSample)
        self.__editor.setLexer(None)
        self.__editor.setUtf8(True)  # Set encoding to UTF-8
        self.__editor.setFont(self.__myFont)  # Can be overridden by lexer

        # 3. Add editor to layout
        # ------------------------
        self.__lyt.addWidget(self.__editor)

        self.show()

    ''''''

    def __btn_action(self):
        print("Hello World!")

    ''''''

''' End Class '''

if __name__ == '__main__':
    app = QApplication(sys.argv)
    QApplication.setStyle(QStyleFactory.create('Fusion'))
    myGUI = CustomMainWindow()

    sys.exit(app.exec_())

''''''

It is just subclassing the QsciScintilla class and overloading it's paintEvent method.
The trick is to get the coordinates of where the image is in relation to the view of the document. For the example I justed guessed the line height and font width, it can probably be obtained from the QScintilla.
The other thing is I just hard coded the position of the image with a line and column offset, it would probably be good to create a syntax that the editor could parse and insert the image automatically.

Regards


问:
Integrating ng-admin 2 into JHipser
I've been trying to use ng-admin 2 instead of standard admin panel in generated JHipster app but couldn't make it work. Has anyone ever swapped out the standard JHipster admin panel for something else for example ng-admin? </p>

答:
It is possible to change the frontend framework to something else, but there is no "really" switch, which acts like a single command turning the existing frontend to something different. The closest thing is a set of JHipster Modules, where people are offering similar things. There will be React support soon.

But if you want to use ng-admin, you will have to implement it manually. If you do so, you might consider doing that as a JHipster module

Title: Integrating ng-admin 2 into JHipser


问:
Switching from tensorflow on python 3.6 to python 3.5
This is my first question on stackoverflow, please bear with me as I will do my best to provide as much info as possible.

I have a windows 10, 6-bit processor.  My end goal is to use keras within spyder.  The first thing I did was update python to 3.6 and install tensorflow, which seemed to work.  When I attempted to get keras, however, it wasn't working, and I read that keras worked on python 3.5.  I successfully installed keras on python 3.5, which automatically installed theano as the backend.

But now I have two spyder environments, one running off of python 3.5, one off of 3.6.  The 3.5 reads keras but doesn't go through with any modules because it cannot find tensorflow.  The 3.6 can read tensorflow, but cannot find keras.

Please let me know what you would recommend.  Thank you!

答: Odd, the installation instructions say that TF only supports Python 3.5 on Windows. I would uninstall TF with pip uninstall tensorflow (if you installed it with pip to begin with) using pip from your Python 3.6 path, then re-install (pip install --upgrade tensorflow) making sure that you are running pip from your Python 3.5 path.


问:
how to label the bar charts in python
i am plotting a graph with bar charts in python using pandas and matplotlib and i need to change the label of my x axis.
here's my code :

```<code>data['impact'] = data['impact'].abs()
yearly = data.groupby(data.index.month)['impact'].mean()

print yearly
ttl = 'la moyenne mensuelle des impacts du 2006 a 2010'
ax = yearly.plot(kind='bar', title = ttl)
xlab = 'les mois du 2006 a 2010 '
ax.set_xlabel(xlab, fontsize=20, ha='center')
ylab = 'la moyenne des impacts'
ax.set_ylabel(ylab, fontsize=20, ha='center')
</code>```

it gives me this result :
click here to see my result

so now, my request is how can i change the label of months in the x axix from :

```<code>[1,2,3,4,...,12] to ['jan','Fev','Mar','Avr','Mai','Juin','Juil','Aout','Sep','Oct','Nov','Dec']
</code>```

I tried this :

```<code> labels = ['jan','Fev','Mar','Avr','Mai','Juin','Juil','Aout','Sep','Oct','Nov','Dec']
 plt.xticks(labels, rotation='vertical')
</code>```

but i got this error :
ValueError: could not convert string to float: jan

any ideas ??

答:
Try this:</p>

```<code>ax.set_xticklabels(labels)
</code>```

Title: how to label the bar charts in python

Body:
i am plotting a graph with bar charts in python using pandas and matplotlib and i need to change the label of my x axis.
here's my code :

data['impact'] = data['impact'].abs()
yearly = data.groupby(data.index.month)['impact'].mean()

print yearly
ttl = 'la moyenne mensuelle des impacts du 2006 a 2010'
ax = yearly.plot(kind='bar', title = ttl)
xlab = 'les mois du 2006 a 2010 '
ax.set_xlabel(xlab, fontsize=20, ha='center')
ylab = 'la moyenne des impacts'
ax.set_ylabel(ylab, fontsize=20, ha='center')

it gives me this result :
click here to see my result

so now, my request is how can i change the label of months in the x axix from :

[1,2,3,4,...,12] to ['jan','Fev','Mar','Avr','Mai','Juin','Juil','Aout','Sep','Oct','Nov','Dec']

I tried this :

 labels = ['jan','Fev','Mar','Avr','Mai','Juin','Juil','Aout','Sep','Oct','Nov','Dec']
 plt.xticks(labels, rotation='vertical')

but i got this error :
ValueError: could not convert string to float: jan

any ideas ??

Body:
Try this:

ax.set_xticklabels(labels)


问:
Rails: How to "publish" a website
So, I am almost done with my website. I created it using ruby on rails on the Cloud9 IDE. Is there a way to publish it? To go on it, a user has to be signed on Cloud9 and then I need to run the code on the terminal...

```<code>rails server -b $IP -p $PORT
</code>```

How would I be able to publish my website? I am very new to rails and I have no idea.

答:
You will also need some deployment tools such as capistrano or mina.

If you're going to host your app in heroku, it's much easier to deploy. As simple as pushing your codes with git.

Title: Rails: How to "publish" a website

Body:
So, I am almost done with my website. I created it using ruby on rails on the Cloud9 IDE. Is there a way to publish it? To go on it, a user has to be signed on Cloud9 and then I need to run the code on the terminal...

rails server -b $IP -p $PORT

How would I be able to publish my website? I am very new to rails and I have no idea.


问:
Setting Nullable Integer to String Containing Nothing yields 0
I've been pulling my hair out over some unexpected behavior from nullable integers.

If I set an Integer to Nothing, it becomes Nothing as expected.

If I set an Integer? to a String that is Nothing, it becomes 0!

Of course I get this whether I explicitly cast the String to Integer? or not.

I realize I could work around this pretty easily but I want to know what I'm missing.

```<code>    Dim NullString As String = Nothing
    Dim NullableInt As Integer? = CType(NullString, Integer?) 'Expected NullableInt to be Nothing, but it's 0!
    NullableInt = Nothing 'This works, of course. NullableInt is Nothing.
</code>```

EDIT: Previously I had my code up here so without the explicit conversion to Integer? and everyone seemed to be fixated on/confused by that. There were a lot of suggestions that Option Strict On would catch this type of thing. However, this is actually a quirk of the string-to-integer conversion rules which predate nullable types, but still impact them.

答:
The reason why has to do with the VB.Net conversion rules here.  The String type is incompatible with Integer? and hence an conversion takes place.  The intermediate step though is converting String to Integer.  The VB.Net conversion rules will convert a Nothing or empty String into the Integer value 0.  This can be reproduced without nullables

```<code>Dim local1 As String = Nothing
Dim local2 As Integer = local1 ' It's 0
</code>```

This same conversion will then convert the Integer value 0 to the type Integer? which maintains the Integer value.

Body:
I've been pulling my hair out over some unexpected behavior from nullable integers.

If I set an Integer to Nothing, it becomes Nothing as expected.

If I set an Integer? to a String that is Nothing, it becomes 0!

Of course I get this whether I explicitly cast the String to Integer? or not.

I realize I could work around this pretty easily but I want to know what I'm missing.

    Dim NullString As String = Nothing
    Dim NullableInt As Integer? = CType(NullString, Integer?) 'Expected NullableInt to be Nothing, but it's 0!
    NullableInt = Nothing 'This works, of course. NullableInt is Nothing.

EDIT: Previously I had my code up here so without the explicit conversion to Integer? and everyone seemed to be fixated on/confused by that. There were a lot of suggestions that Option Strict On would catch this type of thing. However, this is actually a quirk of the string-to-integer conversion rules which predate nullable types, but still impact them.

Body:
The reason why has to do with the VB.Net conversion rules here.  The String type is incompatible with Integer? and hence an conversion takes place.  The intermediate step though is converting String to Integer.  The VB.Net conversion rules will convert a Nothing or empty String into the Integer value 0.  This can be reproduced without nullables

Dim local1 As String = Nothing
Dim local2 As Integer = local1 ' It's 0

This same conversion will then convert the Integer value 0 to the type Integer? which maintains the Integer value.


问:
Unable to trigger jquery function on checkbox check
I have built a form and am trying to trigger a function when the singular checkbox is clicked, but the function I am using as shown below does not work. Basically every response I could find related to this question points to using the same method that I am using from what I can tell, but I must be doing something wrong here.

```<code><form>
  <fieldset>
    <div class="row">
      <div class="col-sm-12">
        <div class="checkbox" id="check-3dAnimationVisualEffects">
          <input type="checkbox" id="filter-3dAnimationVisualEffects" name="3dAnimationVisualEffects" value="1" class="form-checkbox"/>
          <label for="filter-3dAnimationVisualEffects" data-toggle="tooltip" data-placement="top"><span>3D Animation Visual Effects</span></label>
        </div>
      </div>
    </div>
  </fieldset>
</form>

<script>
jQuery(document).ready(function($){
  if ($('#filter-3dAnimationVisualEffects').is(':checked')) {
    alert("Checked!");
  }
});
</script>
</code>```

How can I get this function to run when the checkbox is checked?

答:
You should attach event handler function for click event using .on() like:

jQuery(document).ready(function($){
  $('#filter-3dAnimationVisualEffects').on('click', function(){
    alert($(this).is(':checked'));
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <fieldset>
    <div class="row">
      <div class="col-sm-12">
        <div class="checkbox" id="check-3dAnimationVisualEffects">
          <input type="checkbox" id="filter-3dAnimationVisualEffects" name="3dAnimationVisualEffects" value="1" class="form-checkbox"/>
          <label for="filter-3dAnimationVisualEffects" data-toggle="tooltip" data-placement="top"><span>3D Animation Visual Effects</span></label>
        </div>
      </div>
    </div>
  </fieldset>
</form></code>```

Body:
I have built a form and am trying to trigger a function when the singular checkbox is clicked, but the function I am using as shown below does not work. Basically every response I could find related to this question points to using the same method that I am using from what I can tell, but I must be doing something wrong here.

<form>
  <fieldset>

          <input type="checkbox" id="filter-3dAnimationVisualEffects" name="3dAnimationVisualEffects" value="1" class="form-checkbox"/>
          3D Animation Visual Effects

  </fieldset>
</form>

How can I get this function to run when the checkbox is checked?

Body:
You should attach event handler function for click event using .on() like:

jQuery(document).ready(function($){
  $('#filter-3dAnimationVisualEffects').on('click', function(){
    alert($(this).is(':checked'));
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <fieldset>
    <div class="row">
      <div class="col-sm-12">
        <div class="checkbox" id="check-3dAnimationVisualEffects">
          <input type="checkbox" id="filter-3dAnimationVisualEffects" name="3dAnimationVisualEffects" value="1" class="form-checkbox"/>
          <label for="filter-3dAnimationVisualEffects" data-toggle="tooltip" data-placement="top"><span>3D Animation Visual Effects</span></label>
        </div>
      </div>
    </div>
  </fieldset>
</form>


问:
Weblogic FileNotFoundException Too many open files
We ran into an issue lately when trying to access weblogic console in Unix server, we would get:

Error 503--Service Unavailable

And in the log file it would state:

Caused By:java.io.FileNotFoundException: /opt/weblogic1036/wlserver_10.3/server/lib/co>nsoleapp/webapp/WEB-INF/weblogic.xml (Too many open files)

After some googling I ran into a solution that stated that the /etc/security/limits.conf file dictates the number of files a process can hold open, https://linux.die.net/man/5/limits.conf specifically nofile and it needs to be raised.
I also compared it to another server we have where the weblogic consoles do work where the nofile line was existing with a high enough value.

We added the two lines as well in the server where the issues happens:

* soft nofile 65536

* hard nofile 65536

And indeed it solved the issue and the console worked.
but now for some reason after restarting this weblogic the issue returned, and when checking the limits of the weblogic process we see that it has the old default value of 1024 files:

cat /proc/32203/limits
Limit                     Soft Limit           Hard Limit           Units
Max open files            1024                 1024                 files
...

A different weblogic console on the same server does work (after the fix mind you) and returns a "Max open files" of 65536

the limits file was not changed and still holds the new nofile value

Any idea why the issue could have returned ? it looks like the server for some reason "forgot" or "cleared" the max open files value for this specific weblogic after restarting it.

Any help would be appreciated.

答:
The link you shared quotes it is not permanent.

Also, please note that all limit settings are set per login. They are
  not global, nor are they permanent; existing only for the duration of
  the session.

In the limits configuration file, the '#' character introduces a
  comment - after which the rest of the line is ignored.

Try as stated in comment

```<code>ulimit -n 65536
</code>```

Body:
The link you shared quotes it is not permanent.

Also, please note that all limit settings are set per login. They are
  not global, nor are they permanent; existing only for the duration of
  the session.

In the limits configuration file, the '#' character introduces a
  comment - after which the rest of the line is ignored.

Try as stated in comment

ulimit -n 65536


问:
How to check the response assertion is passed or failed in Jmeter using beanshell
I want to save the request and response of the sample into a text file, if response assertion is failed.

Here I can save the request and response it to a text file. But I am struck where,

how to check the whether response assertion is passed or failed for the respective sample.

How to validate the is current "Http Request" sample is passed or failed?

Thanks In advance.

答:
Add Beanshell Listener as a child of your HTTP Request sampler which has Assertion(s)

Put the following code into "Script" area:

```<code>import org.apache.jmeter.assertions.AssertionResult;

for (AssertionResult assertionResult : sampleResult.getAssertionResults()) {
    if (assertionResult.isFailure()) {
        //do what you need here
    }
}
</code>```

As Listeners are executed after assertions the listener will have information regarding all assertion results therefore you will be able to conditionally store request/response details into a file.

Be aware that starting from JMeter version 3.0 the Groovy scripting engine is being shipped with JMeter so consider switching to JSR223 Listener and replacing all your Beanshell Test Elements with the JSR223 equivalents, performancewise it would be much better.

Body:
Add Beanshell Listener as a child of your HTTP Request sampler which has Assertion(s)

Put the following code into "Script" area:

import org.apache.jmeter.assertions.AssertionResult;

for (AssertionResult assertionResult : sampleResult.getAssertionResults()) {
    if (assertionResult.isFailure()) {
        //do what you need here
    }
}

As Listeners are executed after assertions the listener will have information regarding all assertion results therefore you will be able to conditionally store request/response details into a file.

Be aware that starting from JMeter version 3.0 the Groovy scripting engine is being shipped with JMeter so consider switching to JSR223 Listener and replacing all your Beanshell Test Elements with the JSR223 equivalents, performancewise it would be much better.


问:
Swift CoreData predicate
I'm quite new to programming in swift and have recently begun experimenting with persistent data. I have a problem with predicates for search requests.

My (test) application is a simple grade manager. It has Course entities that have a one-to-many relationship with Grade entities. When I want to display my grades in a tableview I want to fetch all grades that have a relation with a specific course. I made a function for this in my DatabaseController class (which I use to manage my CoreData), but when you actually fetch the return value of this function it's always empty.

```<code>class func returnFetchRequestGrades(course: Course) -> NSFetchRequest<Grade>{

    let fetchRequestGradesInCourse: NSFetchRequest<Grade> = Grade.fetchRequest()
    let predicateCourse = NSPredicate(format: "%@ == %@", "c.course.courseName", course)
    fetchRequestGradesInCourse.predicate = predicateCourse

    return fetchRequestGradesInCourse
}
</code>```

What can I do to solve this?

It does work when I use the following work-around: I create a fetch request without a predicate. I fetch the result. This gives me back a list of all grades. I then (using a for-loop) pick out all the correct grades.

答:
Is courseName a value for the Grade entity? If so your predicate might be wrong, try:

let predicateCourse = NSPredicate(format: "courseName == %@", course)

Title: Swift CoreData predicate

Body:
I'm quite new to programming in swift and have recently begun experimenting with persistent data. I have a problem with predicates for search requests.

My (test) application is a simple grade manager. It has Course entities that have a one-to-many relationship with Grade entities. When I want to display my grades in a tableview I want to fetch all grades that have a relation with a specific course. I made a function for this in my DatabaseController class (which I use to manage my CoreData), but when you actually fetch the return value of this function it's always empty.

class func returnFetchRequestGrades(course: Course) -> NSFetchRequest<Grade>{

    let fetchRequestGradesInCourse: NSFetchRequest<Grade> = Grade.fetchRequest()
    let predicateCourse = NSPredicate(format: "%@ == %@", "c.course.courseName", course)
    fetchRequestGradesInCourse.predicate = predicateCourse

    return fetchRequestGradesInCourse
}

What can I do to solve this?

It does work when I use the following work-around: I create a fetch request without a predicate. I fetch the result. This gives me back a list of all grades. I then (using a for-loop) pick out all the correct grades.


问:
Options with multiple arguments
Is it possible to have multiples options with more than one argument in docopt, without knowing the number of these arguments?

I would like to do something like this with a variable number of arguments:

```<code>Usage:
    myprog.py --option1 ARG1 ARG2... --option2 ARG3 ARG4 ARG5...
</code>```

I tried to use <arg>... but it only works as positional argument.

Thanks for help.

答:
You can give an option several times, but you have to specify the option each time. For example it could look like this:

```<code>"""Example of program with options repeated using docopt.
Usage:
  myprog.py [--options1=OPT]...
"""
from docopt import docopt

if __name__ == '__main__':
    arguments = docopt(__doc__)
    print(arguments)
</code>```

And the output would look like this:

```<code>$ python myprog.py --options1=test1 --options1=test2
{'--options1': ['test1', 'test2']}
</code>```

Title: Options with multiple arguments

Body:
Is it possible to have multiples options with more than one argument in docopt, without knowing the number of these arguments?

I would like to do something like this with a variable number of arguments:

Usage:
    myprog.py --option1 ARG1 ARG2... --option2 ARG3 ARG4 ARG5...

I tried to use <arg>... but it only works as positional argument.

Thanks for help.

Body:
You can give an option several times, but you have to specify the option each time. For example it could look like this:

"""Example of program with options repeated using docopt.
Usage:
  myprog.py [--options1=OPT]...
"""
from docopt import docopt

if __name__ == '__main__':
    arguments = docopt(__doc__)
    print(arguments)

And the output would look like this:

$ python myprog.py --options1=test1 --options1=test2
{'--options1': ['test1', 'test2']}


问:
How to disable the default context menu of pyqtgraph?
Can anyone help me to disable the context menu of pyqtgraph or remove some options from it? </p>

答:
Use the PlotItem.setMenuEnabled method. Something like:

```<code>    self.plot = pg.PlotItem()
    self.plot.setMenuEnabled(False)
</code>```

I have not found a way to remove options from it but perhaps it's possible. I would be interested in this as well.

Body:
Use the PlotItem.setMenuEnabled method. Something like:

    self.plot = pg.PlotItem()
    self.plot.setMenuEnabled(False)

I have not found a way to remove options from it but perhaps it's possible. I would be interested in this as well.


问:
Stream mp4 video in php file with speed limitation
I want to open a video/mp4 file in a php file to use it in the player. I want to limit the file upload speed to 100 kb/s.

```<code><?php
$file = 'video.mp4';
$fp = @fopen($file, 'rb');

$size   = filesize($file); // File size
$length = $size;           // Content length
$start  = 0;               // Start byte
$end    = $size - 1;       // End byte

header('Content-type: video/mp4');
header("Accept-Ranges: 0-$length");
if (isset($_SERVER['HTTP_RANGE'])) {

    $c_start = $start;
    $c_end   = $end;

    list(, $range) = explode('=', $_SERVER['HTTP_RANGE'], 2);
    if (strpos($range, ',') !== false) {
        header('HTTP/1.1 416 Requested Range Not Satisfiable');
        header("Content-Range: bytes $start-$end/$size");
        exit;
    }
    if ($range == '-') {
        $c_start = $size - substr($range, 1);
    }else{
        $range  = explode('-', $range);
        $c_start = $range[0];
        $c_end   = (isset($range[1]) && is_numeric($range[1])) ? $range[1] : $size;
    }
    $c_end = ($c_end > $end) ? $end : $c_end;
    if ($c_start > $c_end || $c_start > $size - 1 || $c_end >= $size) {
        header('HTTP/1.1 416 Requested Range Not Satisfiable');
        header("Content-Range: bytes $start-$end/$size");
        exit;
    }
    $start  = $c_start;
    $end    = $c_end;
    $length = $end - $start + 1;
    fseek($fp, $start);
    header('HTTP/1.1 206 Partial Content');
}
header("Content-Range: bytes $start-$end/$size");
header("Content-Length: ".$length);

$buffer = 1024 * 8;
while(!feof($fp) && ($p = ftell($fp)) <= $end) {

    if ($p + $buffer > $end) {
        $buffer = $end - $p + 1;
    }
    set_time_limit(0);
    echo fread($fp, $buffer);
    flush();
}

fclose($fp);
exit();
?>
</code>```

And it works fine, how to limit the speed of loading a file? And what are the optimal settings (so that the video loads smoothly, at a speed without jamming)

答: I have a page as a file server, it contains video files that I want to give you the opportunity to play. To maintain the server I want to force users to buy premium accounts to speed up video encoding</p>

Body:
I want to open a video/mp4 file in a php file to use it in the player. I want to limit the file upload speed to 100 kb/s.

<?php
$file = 'video.mp4';
$fp = @fopen($file, 'rb');

$size   = filesize($file); // File size
$length = $size;           // Content length
$start  = 0;               // Start byte
$end    = $size - 1;       // End byte

header('Content-type: video/mp4');
header("Accept-Ranges: 0-$length");
if (isset($_SERVER['HTTP_RANGE'])) {

    $c_start = $start;
    $c_end   = $end;

    list(, $range) = explode('=', $_SERVER['HTTP_RANGE'], 2);
    if (strpos($range, ',') !== false) {
        header('HTTP/1.1 416 Requested Range Not Satisfiable');
        header("Content-Range: bytes $start-$end/$size");
        exit;
    }
    if ($range == '-') {
        $c_start = $size - substr($range, 1);
    }else{
        $range  = explode('-', $range);
        $c_start = $range[0];
        $c_end   = (isset($range[1]) && is_numeric($range[1])) ? $range[1] : $size;
    }
    $c_end = ($c_end > $end) ? $end : $c_end;
    if ($c_start > $c_end || $c_start > $size - 1 || $c_end >= $size) {
        header('HTTP/1.1 416 Requested Range Not Satisfiable');
        header("Content-Range: bytes $start-$end/$size");
        exit;
    }
    $start  = $c_start;
    $end    = $c_end;
    $length = $end - $start + 1;
    fseek($fp, $start);
    header('HTTP/1.1 206 Partial Content');
}
header("Content-Range: bytes $start-$end/$size");
header("Content-Length: ".$length);

$buffer = 1024 * 8;
while(!feof($fp) && ($p = ftell($fp)) <= $end) {

    if ($p + $buffer > $end) {
        $buffer = $end - $p + 1;
    }
    set_time_limit(0);
    echo fread($fp, $buffer);
    flush();
}

fclose($fp);
exit();
?>

And it works fine, how to limit the speed of loading a file? And what are the optimal settings (so that the video loads smoothly, at a speed without jamming)


问:
Maintaining and organizing purchases on multiple platforms
I have an application for various platforms. Let them be iOS, Android and Windows. In order to use a app, a monthly fee needs to be paid, but it just needs to be paid once in order to use all platforms. It is the same as with Spotify, so by paying once, every platform can be used.

According to the guidelines of Google and Apple, I need to offer In-App Purchases for the monthly fee. The system is connected to user accounts, which are managed by a server, which is in my control. I am storing the subscription data of users, so if a user uses the In-App Purchases on iOS, the information is transmitted to the central server in order to unlock the Android-App as well (in case it has been paid on another platform already)

The problem is the following scenario:
A user has a valid subscription which has been payed via Google Play. The iOS and Windows apps are unlocked as well. Now the user uninstalls the Android app, goes to the Google Play website and cancels the subscription. In the current scenario, I am not able to detect this and the subscription will be valid for all other platforms.

The question is:
Is there any pattern to circumvent this problem? Spotify and co are solving this issue as well, so there must be a solution for this

答:
Well, the server that handles the authorization of the user (that is, your server) should query the Google Subscription API, to check if the current subscription is still valid. Each SubscriptionPurchase Resource contains information about when the subscription expires.

(see https://developers.google.com/android-publisher/api-ref/purchases/subscriptions)

For Apple, the same stuff applies: You will get a receipt, and with that receipt, you can query the server at any time to check if that subscription is still valid.

There is a slide which summarizes these points and the pitfalls very well: https://speakerdeck.com/rosapolis/the-recurring-nightmare-cross-platform-in-app-subscription-purchases

Bottom line: You won't be able to make that happen without a server that does the communication between the two stores. It comes with issues, though, as the slide shows.

Bonus: The talk from which the slides are taken is also on Youtube


问:
Codeigniter 404 page not found with form
So I just started to use Codeigniter, and can't understand why what I'm doing isn't working.

My controller is like that:

```<code>class Tienda extends CI_Controller {

    public function index(){
        $this->load->view('inicio_view');
    }
    public function entrar(){
        $nom= $this->input->post('nom');
        $pass= $this->input->post('pass');

        if($nom && $pass){
            $data['nom']=$nom;
            $data['pass']=$pass;
            $this->load->model('Login_model');
            $user=$this->Login_model->get_usuario($nom, $pass);

            var_dump($user);

            if ($user[0]['id']=='1'){
                $this->load->view('Catalogo_view');
            }
        }
    }
}
</code>```

My initial view

```<code>    <html>
    <head>
        <meta charset="utf-8">
        <title>TIENDA</title>
    </head>
    <body>
        <h1>TIENDA</h1>
        <div class="form">
            <form action="<?php echo base_url('Tienda/entrar');?>" method="post">
              Usuario: <input type="text" name="nom"/>
              <br/>
              Contraseña: <input type="text" name="pass"/>
              <br/>
             <input type="submit" value="Enviar" />
            </form>
        </div>

    </body>
    </html>
</code>```

And in the login_model I'm just calling to get the user and the pass

```<code>class Login_model extends CI_Model {

        public function get_usuario($nom,$pass){
            //$query = $this->db->get_where('usuarios',array('nom'=>$nom,'pass'=>$pass));
            $query = $this->db-> query('SELECT id FROM usuarios where nom = "'.$nom.'" and pass = "'.$pass.'";');
            return $query->result_array();
        }
}
</code>```

I don't know how many hours I've been searching and changing things, but it still doesn't work. Also, I checked almost every post of people who had that problem, but still can't make it work.

My catalog_view is just a h1 that says it works, because I just wanted to see if I can make it work but... I just don't know what it's happening.
If there's any help here, it would be appreciated!

答:
Posting the answer in case anyone needs it.
In config, I had to put "localhost/index.php/Tienda" so it works now.</p>

Body:
So I just started to use Codeigniter, and can't understand why what I'm doing isn't working.

My controller is like that:

class Tienda extends CI_Controller {

    public function index(){
        $this->load->view('inicio_view');
    }
    public function entrar(){
        $nom= $this->input->post('nom');
        $pass= $this->input->post('pass');

        if($nom && $pass){
            $data['nom']=$nom;
            $data['pass']=$pass;
            $this->load->model('Login_model');
            $user=$this->Login_model->get_usuario($nom, $pass);

            var_dump($user);

            if ($user[0]['id']=='1'){
                $this->load->view('Catalogo_view');
            }
        }
    }
}

My initial view

        <meta charset="utf-8">
        <title>TIENDA</title>

TIENDA

            <form action="<?php echo base_url('Tienda/entrar');?>" method="post">
              Usuario: <input type="text" name="nom"/>

              Contraseña: <input type="text" name="pass"/>

             <input type="submit" value="Enviar" />
            </form>

And in the login_model I'm just calling to get the user and the pass

class Login_model extends CI_Model {

        public function get_usuario($nom,$pass){
            //$query = $this->db->get_where('usuarios',array('nom'=>$nom,'pass'=>$pass));
            $query = $this->db-> query('SELECT id FROM usuarios where nom = "'.$nom.'" and pass = "'.$pass.'";');
            return $query->result_array();
        }
}

I don't know how many hours I've been searching and changing things, but it still doesn't work. Also, I checked almost every post of people who had that problem, but still can't make it work.

My catalog_view is just a h1 that says it works, because I just wanted to see if I can make it work but... I just don't know what it's happening.
If there's any help here, it would be appreciated!


问:
Swap! value doesn't resolve
While parsing an xml file, I normalize values and save them via swap! into an atom. Additional I build a tree to reflect the original structure.

When I call the function, it returns only a part of the data, but not the normalized values. When I deref the atom, the data is completely written.

Here the parts of the code, which seems to be critical to that behaviour.

```<code>(defn normalize-values
  "Save the dataset to the atom and returns the reference"
  [tour-id key value]
  (swap! db assoc-in [tour-id (query-key key :name) value] {:title value})
  {key [(query-key key) value]})

(defn extract-tags
  "Differs between unique and normalizable values"
  [node tour-id]
  (let [data (zip/xml-zip node)
        key (:tag node)
        value (zx/xml1-> data key zx/text)
        res (if (some #{key} [:sound :map :video :creator])
              (normalize-values tour-id key value)
              {key value})]
    res))

(defn panorama->map
  "Creates a panorama map from the xml data"
  [node tour-id]
  (let [xml-node (zip/node node)
        tag-values (into {} (map #(extract-tags % tour-id) (:content xml-node)))]
    (merge tag-values
           {:id     (get-file-id (:file tag-values))
            :hidden (read-string (get-in xml-node [:attrs :hidden]))})))

(defn menu->map
  "Loops over the xml tree and builds the structure"
  [tour-id menu]
  (for [entry menu]
    (let [children (childs-of-child entry)]
      (if (not-empty children)
        (let [{:keys [id] :as category-map} (category->map entry)]
          (swap! db assoc-in [tour-id (query-key :categorie :id) id] category-map)
          {:loc      [:categories/by-id id]
           :children (menu->map tour-id children)})

        (let [{:keys [id] :as panorama-map} (panorama->map entry tour-id)]
          (swap! db assoc-in [tour-id (query-key :pano :id) id] panorama-map)

          {:loc [:panos/by-id id]})))))

(defn parse-menu
  "Starting function which resets the db and saves all data to the atom "
  [path id]
  (swap! db dissoc id)
  (logging/debug "Parse Menu: " path)

  (let [xml (xml->map path)
        menu-data (menu->map id (:content xml))]

    (swap! db assoc-in [id :title] (tour-title xml))
    (swap! db assoc-in [id :tree] menu-data)

    (get @db id)))
</code>```

How can I realize, that the atom is resolved correctly?

答: for is lazy, and will not perform the side effects you have snuck into its body until you realize the elements of the sequence it produces. Your description "When I deref the atom, the data is completely written." is unclear, but I suspect you mean you deref it in the repl, causing its value to be printed, which forces the lazy seqs embedded in it, which causes their side effects to run.

Title: Swap! value doesn't resolve

Body:
While parsing an xml file, I normalize values and save them via swap! into an atom. Additional I build a tree to reflect the original structure.

When I call the function, it returns only a part of the data, but not the normalized values. When I deref the atom, the data is completely written.

Here the parts of the code, which seems to be critical to that behaviour.

(defn normalize-values
  "Save the dataset to the atom and returns the reference"
  [tour-id key value]
  (swap! db assoc-in [tour-id (query-key key :name) value] {:title value})
  {key [(query-key key) value]})

(defn extract-tags
  "Differs between unique and normalizable values"
  [node tour-id]
  (let [data (zip/xml-zip node)
        key (:tag node)
        value (zx/xml1-> data key zx/text)
        res (if (some #{key} [:sound :map :video :creator])
              (normalize-values tour-id key value)
              {key value})]
    res))

(defn panorama->map
  "Creates a panorama map from the xml data"
  [node tour-id]
  (let [xml-node (zip/node node)
        tag-values (into {} (map #(extract-tags % tour-id) (:content xml-node)))]
    (merge tag-values
           {:id     (get-file-id (:file tag-values))
            :hidden (read-string (get-in xml-node [:attrs :hidden]))})))

(defn menu->map
  "Loops over the xml tree and builds the structure"
  [tour-id menu]
  (for [entry menu]
    (let [children (childs-of-child entry)]
      (if (not-empty children)
        (let [{:keys [id] :as category-map} (category->map entry)]
          (swap! db assoc-in [tour-id (query-key :categorie :id) id] category-map)
          {:loc      [:categories/by-id id]
           :children (menu->map tour-id children)})

        (let [{:keys [id] :as panorama-map} (panorama->map entry tour-id)]
          (swap! db assoc-in [tour-id (query-key :pano :id) id] panorama-map)

          {:loc [:panos/by-id id]})))))

(defn parse-menu
  "Starting function which resets the db and saves all data to the atom "
  [path id]
  (swap! db dissoc id)
  (logging/debug "Parse Menu: " path)

  (let [xml (xml->map path)
        menu-data (menu->map id (:content xml))]

    (swap! db assoc-in [id :title] (tour-title xml))
    (swap! db assoc-in [id :tree] menu-data)

    (get @db id)))

How can I realize, that the atom is resolved correctly?


问:
Running Excel macros from R through RDCOMClient, error -2147418111
The objective is to add data to an existing excel file with OpenXLSX, then run macros in the same Excel file using RDCOMClient, saving it along the way, from an R script.

The Excel macros make changes to the pivot table filters and collapse points that must occur after the data is loaded.

This small, reproduction of the problem works without issue:

```<code>library(openxlsx)
library(RDCOMClient)

ds <- cars
tmpl <- './templates/templatetest.xlsm'
datatab <- 'data'
datarng <- 'pdata'
fn <- paste0("./WAR/", "test1.xlsm")

wb <- loadWorkbook(tmpl)
writeData(wb, datatab, ds)
saveWorkbook(wb, fn, overwrite = TRUE)
rm(wb)

# note this doesn't reveal the full actual UNC path
fn <- paste0("./WAR/",
             "test1.xlsm")

xlApp <- COMCreate("Excel.Application")
xlWbk <- xlApp$Workbooks()$Open(fn)

# run macros
xlApp$Run("clear_pt_filters")
xlApp$Run("CollapsePivotFields")
xlApp$Run("toggle_alcItems")

# Close the workbook and quit the app:
xlWbk$Close(TRUE)
xlApp$Quit()

# Release resources:
rm(xlWks, xlWbk, xlApp)
gc()
</code>```

However, when running in production, I get an error at the first macro line:

xlApp$Run("clear_pt_filters")

Error in .COM(x, name, ...) :    Cannot locate 0 name(s) Run in COM
  object (status = -2147418111)

I am suspicious that it is due to the time of loading the 1-2 MB file while R is proceeding without a signal that RDCOMClient is ready for the macro run request.

I manually resolve this by simply running the script again, starting from the same macro line. In the end, the error just prevents full automation, the spreadsheets turn out exactly as expected.

Edit: If I step through the 'production' version line by line, there is no error.

The questions that I have are 1) what is the the cause of the error, and 2) what can I do to resolve the issue in automation?

Thanks.

答:
The simplest solution found that I'm using is to insert a single second pause using Sys.sleep().

```<code>Sys.sleep(1)
</code>```

So, it looks like this, from above, edited:

```<code>xlApp <- COMCreate("Excel.Application")
xlWbk <- xlApp$Workbooks()$Open(fn)

# run macros
Sys.sleep(1)
xlApp$Run("clear_pt_filters")
xlApp$Run("CollapsePivotFields")
xlApp$Run("toggle_alcItems")

# Close the workbook and quit the app:
xlWbk$Close(TRUE)
xlApp$Quit()

# Release resources:
rm(xlWbk, xlApp)
gc()
</code>```

Credit to Is there a "pause" function in R?

Body:
The objective is to add data to an existing excel file with OpenXLSX, then run macros in the same Excel file using RDCOMClient, saving it along the way, from an R script.

The Excel macros make changes to the pivot table filters and collapse points that must occur after the data is loaded.

This small, reproduction of the problem works without issue:

library(openxlsx)
library(RDCOMClient)

ds <- cars
tmpl <- './templates/templatetest.xlsm'
datatab <- 'data'
datarng <- 'pdata'
fn <- paste0("./WAR/", "test1.xlsm")

wb <- loadWorkbook(tmpl)
writeData(wb, datatab, ds)
saveWorkbook(wb, fn, overwrite = TRUE)
rm(wb)

# note this doesn't reveal the full actual UNC path
fn <- paste0("./WAR/",
             "test1.xlsm")

xlApp <- COMCreate("Excel.Application")
xlWbk <- xlApp$Workbooks()$Open(fn)

# run macros
xlApp$Run("clear_pt_filters")
xlApp$Run("CollapsePivotFields")
xlApp$Run("toggle_alcItems")

# Close the workbook and quit the app:
xlWbk$Close(TRUE)
xlApp$Quit()

# Release resources:
rm(xlWks, xlWbk, xlApp)
gc()

However, when running in production, I get an error at the first macro line:

xlApp$Run("clear_pt_filters")

Error in .COM(x, name, ...) :    Cannot locate 0 name(s) Run in COM
  object (status = -2147418111)

I am suspicious that it is due to the time of loading the 1-2 MB file while R is proceeding without a signal that RDCOMClient is ready for the macro run request.

I manually resolve this by simply running the script again, starting from the same macro line. In the end, the error just prevents full automation, the spreadsheets turn out exactly as expected.

Edit: If I step through the 'production' version line by line, there is no error.

The questions that I have are 1) what is the the cause of the error, and 2) what can I do to resolve the issue in automation?

Thanks.

Body:
The simplest solution found that I'm using is to insert a single second pause using Sys.sleep().

Sys.sleep(1)

So, it looks like this, from above, edited:

xlApp <- COMCreate("Excel.Application")
xlWbk <- xlApp$Workbooks()$Open(fn)

# run macros
Sys.sleep(1)
xlApp$Run("clear_pt_filters")
xlApp$Run("CollapsePivotFields")
xlApp$Run("toggle_alcItems")

# Close the workbook and quit the app:
xlWbk$Close(TRUE)
xlApp$Quit()

# Release resources:
rm(xlWbk, xlApp)
gc()

Credit to Is there a "pause" function in R?