问:
Swift -> my prototype cell (UITableViewCell) doesn't show in my UIViewController with a UITableView
My storyboard looks like this

and my code is the following

UIViewController

class DownLoadSoundsViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

```<code>// MARK: View Controller Properties
let viewName = "DownLoadSoundsViewController"
@IBOutlet weak var visualEffectView: UIVisualEffectView!
@IBOutlet weak var dismissButton: UIButton!
@IBOutlet weak var downloadTableView: UITableView!

// MARK: Properties
var soundPacks = [SoundPack?]()  // structure for downloadable sounds

override func viewDidLoad() {
    super.viewDidLoad()

    downloadTableView.dataSource = self
    downloadTableView.delegate = self
    downloadTableView.register(DownLoadTableViewCell.self, forCellReuseIdentifier: "cell")
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return numberOfSoundPacks
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let method = "tableView.cellForRowAt"

    //if (indexPath as NSIndexPath).section == 0 {

    let cell = tableView.dequeueReusableCell(withIdentifier: "downloadTableViewCell", for: indexPath) as! DownLoadTableViewCell

    cell.backgroundColor = UIColor.green

    if soundPacks[(indexPath as NSIndexPath).row]?.price == 0 {
        cell.soundPackPriceUILabel.text = "FREE"
    } else {
        cell.soundPackPriceUILabel.text = String(format: "%.2", (soundPacks[(indexPath as NSIndexPath).row]?.price)!)
    }

    //cell.textLabel?.text = soundPacks[(indexPath as NSIndexPath).row]?.soundPackTitle
    cell.soundPackTitleUILabel.text = soundPacks[(indexPath as NSIndexPath).row]?.soundPackTitle
    cell.soundPackAuthorUILabel.text = soundPacks[(indexPath as NSIndexPath).row]?.author
    cell.soundPackShortDescription.text = soundPacks[(indexPath as NSIndexPath).row]?.shortDescription

    cell.soundPackImage.image = UIImage(named: "Placeholder Icon")
    DDLogDebug("\(viewName).\(method): table section \((indexPath as NSIndexPath).section) row \((indexPath as NSIndexPath).row))")

    return cell
    //}
}
</code>```

UItableViewCell

class DownLoadTableViewCell: UITableViewCell {

```<code>@IBOutlet weak var soundPackImage: UIImageView!
@IBOutlet weak var soundPackTitleUILabel: UILabel!
@IBOutlet weak var soundPackAuthorUILabel: UILabel!
@IBOutlet weak var soundPackShortDescription: UILabel!
@IBOutlet weak var soundPackPriceUILabel: UILabel!

let gradientLayer = CAGradientLayer()

override func awakeFromNib() {
    super.awakeFromNib()
    // Initialization code
}

override func setSelected(_ selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)

    // Configure the view for the selected state
}
</code>```

}

But I get the following;

I am sure I am doing something small incorrectly, but as of yet can't figure it out.  Looked through many examples included my own code where I have gotten this working before.

Not a single one of my settings for the tableview are getting invoked except the number of cells.  But everything in;

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{...}

is not working.

Help is appreciated.

答:
I think you need to reload the tableView after getting data from Firebase</p>

```<code>self.saveMixesTableView.reloadData()
</code>```

Body:
My storyboard looks like this

and my code is the following

UIViewController

class DownLoadSoundsViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

// MARK: View Controller Properties
let viewName = "DownLoadSoundsViewController"
@IBOutlet weak var visualEffectView: UIVisualEffectView!
@IBOutlet weak var dismissButton: UIButton!
@IBOutlet weak var downloadTableView: UITableView!

// MARK: Properties
var soundPacks = [SoundPack?]()  // structure for downloadable sounds

override func viewDidLoad() {
    super.viewDidLoad()

    downloadTableView.dataSource = self
    downloadTableView.delegate = self
    downloadTableView.register(DownLoadTableViewCell.self, forCellReuseIdentifier: "cell")
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return numberOfSoundPacks
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let method = "tableView.cellForRowAt"

    //if (indexPath as NSIndexPath).section == 0 {

    let cell = tableView.dequeueReusableCell(withIdentifier: "downloadTableViewCell", for: indexPath) as! DownLoadTableViewCell

    cell.backgroundColor = UIColor.green

    if soundPacks[(indexPath as NSIndexPath).row]?.price == 0 {
        cell.soundPackPriceUILabel.text = "FREE"
    } else {
        cell.soundPackPriceUILabel.text = String(format: "%.2", (soundPacks[(indexPath as NSIndexPath).row]?.price)!)
    }

    //cell.textLabel?.text = soundPacks[(indexPath as NSIndexPath).row]?.soundPackTitle
    cell.soundPackTitleUILabel.text = soundPacks[(indexPath as NSIndexPath).row]?.soundPackTitle
    cell.soundPackAuthorUILabel.text = soundPacks[(indexPath as NSIndexPath).row]?.author
    cell.soundPackShortDescription.text = soundPacks[(indexPath as NSIndexPath).row]?.shortDescription

    cell.soundPackImage.image = UIImage(named: "Placeholder Icon")
    DDLogDebug("\(viewName).\(method): table section \((indexPath as NSIndexPath).section) row \((indexPath as NSIndexPath).row))")

    return cell
    //}
}

UItableViewCell

class DownLoadTableViewCell: UITableViewCell {

@IBOutlet weak var soundPackImage: UIImageView!
@IBOutlet weak var soundPackTitleUILabel: UILabel!
@IBOutlet weak var soundPackAuthorUILabel: UILabel!
@IBOutlet weak var soundPackShortDescription: UILabel!
@IBOutlet weak var soundPackPriceUILabel: UILabel!

let gradientLayer = CAGradientLayer()

override func awakeFromNib() {
    super.awakeFromNib()
    // Initialization code
}

override func setSelected(_ selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)

    // Configure the view for the selected state
}

}

But I get the following;

I am sure I am doing something small incorrectly, but as of yet can't figure it out.  Looked through many examples included my own code where I have gotten this working before.

Not a single one of my settings for the tableview are getting invoked except the number of cells.  But everything in;

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{...}

is not working.

Help is appreciated.

Body:
I think you need to reload the tableView after getting data from Firebase

self.saveMixesTableView.reloadData()


来源: stackexchange

问:
Matlab cannot see some of my java classes (not all) in jar package
I have a problem that is driving me nuts.
Matlab sees only some of my classes embeded in a JAR file

If I compile the classes outside of a package and add the path to the class in Matlab using javaaddpath, I do not encounter any problem

When I compile the class in a package and then try to access them under Matlab, I have problems. Below some Matlab code

```<code>>>javaaddpath('/Users/me/Documents/workspace/EKGTest.jar');
>>clear java
>>import com.neurosky.thinkgear.*
>>methods('EkgSense')

Methods for class com.neurosky.thinkgear.EkgSense:

EkgSense                  getClass                  notify                    reset
addTemplate               getClassificationResults  notifyAll                  toString
equals                    hashCode                  processData               wait

>>methods('EkgEpoch')

No methods for class EkgEpoch or no class EkgEpoch
</code>```

Now, I look in the package, all of the classes are public. This is a result of jar -tf

```<code>osx:/Users/me/Documents/workspace> jar tf EKGTest.jar
META-INF/MANIFEST.MF
META-INF/REFACTORINGS.XML
com/
com/neurosky/
com/neurosky/thinkgear/
com/neurosky/thinkgear/EkgEpoch.class
com/neurosky/thinkgear/EkgEpoch.java
com/neurosky/thinkgear/EkgParameters.class
com/neurosky/thinkgear/EkgParameters.java
com/neurosky/thinkgear/EkgTemplate.class
com/neurosky/thinkgear/EkgTemplate.java
com/neurosky/thinkgear/Matlab.class
com/neurosky/thinkgear/Matlab.java
com/neurosky/thinkgear/EkgSense.class
com/neurosky/thinkgear/EkgSense.java
com/neurosky/thinkgear/DistanceArray.class
com/neurosky/thinkgear/DistanceArray.java
</code>```

and below of javap --classpath

```<code>osx:/Users/me/Documents/workspace> javap -classpath /Users/me/Documents/workspace/EKGTest.jar    com.neurosky.thinkgear.EkgEpoch
Compiled from "EkgEpoch.java"
public class com.neurosky.thinkgear.EkgEpoch extends java.lang.Object implements java.lang.Cloneable{
    public int numberOfSamples;
    public float[] data;
    public com.neurosky.thinkgear.EkgEpoch(int);
    public com.neurosky.thinkgear.EkgEpoch(int, float[]);
    public com.neurosky.thinkgear.EkgEpoch(float[]);
    public com.neurosky.thinkgear.EkgEpoch(com.neurosky.thinkgear.EkgEpoch);
    public com.neurosky.thinkgear.EkgEpoch(org.json.JSONArray);
    public org.json.JSONArray toJSONArray();
    public static float[] convolve(float[], float[]);
    public float getLineNoiseAmplitude();
    public com.neurosky.thinkgear.EkgEpoch subtract(com.neurosky.thinkgear.EkgEpoch);
    public com.neurosky.thinkgear.EkgEpoch subEpoch(int, int);
    public com.neurosky.thinkgear.EkgEpoch square();
    public com.neurosky.thinkgear.EkgEpoch subtract(float);
    public com.neurosky.thinkgear.EkgEpoch diff();
    public boolean exceedValue(float, int, int);
    public com.neurosky.thinkgear.EkgEpoch smooth(int);
    public float mean();
    public float sum();
    public float max();
    public float median();
    public com.neurosky.thinkgear.EkgEpoch clone();
    public com.neurosky.thinkgear.EkgEpoch sort();
    public int[] sortIndices(com.neurosky.thinkgear.EkgEpoch);
    public float std();
    public int find_heart_beats(int[], float);
    public com.neurosky.thinkgear.EkgEpoch detrend();
    public java.lang.Object clone()       throws java.lang.CloneNotSupportedException;
}

osx:/Users/me/Documents/workspace> javap -classpath /Users/me/Documents/workspace/EKGTest.jar  com.neurosky.thinkgear.EkgSense
Compiled from "EkgSense.java"
public class com.neurosky.thinkgear.EkgSense extends java.lang.Object{
    public com.neurosky.thinkgear.EkgParameters params;
    public com.neurosky.thinkgear.EkgTemplate[] templates;
    public com.neurosky.thinkgear.EkgTemplate currentData;
    public int lastTemplateInd;
    public float lastEpochValue;
    public com.neurosky.thinkgear.EkgSense(com.neurosky.thinkgear.EkgParameters);
    public void reset();
    public void addTemplate(java.lang.String, float[][]);
    public void addTemplate(com.neurosky.thinkgear.EkgTemplate);
    public java.lang.String getClassificationResults();
    public boolean processData(float[]);
}
</code>```

I am running Matlab on OSX. I have tried with Matlab 7.7.0.471 (R2008b) and 7.11.0.584 (R2010b) and got the same problem. Both Matlab are using the native OSX Java (Java 1.6.0_26-b03-384-10M3425 with Apple Inc. Java HotSpot(TM) 64-Bit Server VM mixed mode) which should be the same as the one in Eclipse (I have checked and Eclipse compiles with 1.6).

Remember that I can see the missing class no problem when I remove the package statement and some imports at the top of the java files (in all the classes of course) and when I simply add the path to the .class files (not access them in a JAR file).

Any help would be greatly appreciated.
Thanks,

Jason

答:
I encountered the same problem just now.
The solution is to update matlab java version by setting a new envir parameter  mentioned here

https://cn.mathworks.com/matlabcentral/answers/130359-how-do-i-change-the-java-virtual-machine-jvm-that-matlab-is-using-on-windows

Matlab sucks at error message

ContentLicense: CC BY-SA 4.0

Body:
I have a problem that is driving me nuts.
Matlab sees only some of my classes embeded in a JAR file

If I compile the classes outside of a package and add the path to the class in Matlab using javaaddpath, I do not encounter any problem

When I compile the class in a package and then try to access them under Matlab, I have problems. Below some Matlab code

>>javaaddpath('/Users/me/Documents/workspace/EKGTest.jar');
>>clear java
>>import com.neurosky.thinkgear.*
>>methods('EkgSense')

Methods for class com.neurosky.thinkgear.EkgSense:

EkgSense                  getClass                  notify                    reset
addTemplate               getClassificationResults  notifyAll                  toString
equals                    hashCode                  processData               wait

>>methods('EkgEpoch')

No methods for class EkgEpoch or no class EkgEpoch

Now, I look in the package, all of the classes are public. This is a result of jar -tf

osx:/Users/me/Documents/workspace> jar tf EKGTest.jar
META-INF/MANIFEST.MF
META-INF/REFACTORINGS.XML
com/
com/neurosky/
com/neurosky/thinkgear/
com/neurosky/thinkgear/EkgEpoch.class
com/neurosky/thinkgear/EkgEpoch.java
com/neurosky/thinkgear/EkgParameters.class
com/neurosky/thinkgear/EkgParameters.java
com/neurosky/thinkgear/EkgTemplate.class
com/neurosky/thinkgear/EkgTemplate.java
com/neurosky/thinkgear/Matlab.class
com/neurosky/thinkgear/Matlab.java
com/neurosky/thinkgear/EkgSense.class
com/neurosky/thinkgear/EkgSense.java
com/neurosky/thinkgear/DistanceArray.class
com/neurosky/thinkgear/DistanceArray.java

and below of javap --classpath

osx:/Users/me/Documents/workspace> javap -classpath /Users/me/Documents/workspace/EKGTest.jar    com.neurosky.thinkgear.EkgEpoch
Compiled from "EkgEpoch.java"
public class com.neurosky.thinkgear.EkgEpoch extends java.lang.Object implements java.lang.Cloneable{
    public int numberOfSamples;
    public float[] data;
    public com.neurosky.thinkgear.EkgEpoch(int);
    public com.neurosky.thinkgear.EkgEpoch(int, float[]);
    public com.neurosky.thinkgear.EkgEpoch(float[]);
    public com.neurosky.thinkgear.EkgEpoch(com.neurosky.thinkgear.EkgEpoch);
    public com.neurosky.thinkgear.EkgEpoch(org.json.JSONArray);
    public org.json.JSONArray toJSONArray();
    public static float[] convolve(float[], float[]);
    public float getLineNoiseAmplitude();
    public com.neurosky.thinkgear.EkgEpoch subtract(com.neurosky.thinkgear.EkgEpoch);
    public com.neurosky.thinkgear.EkgEpoch subEpoch(int, int);
    public com.neurosky.thinkgear.EkgEpoch square();
    public com.neurosky.thinkgear.EkgEpoch subtract(float);
    public com.neurosky.thinkgear.EkgEpoch diff();
    public boolean exceedValue(float, int, int);
    public com.neurosky.thinkgear.EkgEpoch smooth(int);
    public float mean();
    public float sum();
    public float max();
    public float median();
    public com.neurosky.thinkgear.EkgEpoch clone();
    public com.neurosky.thinkgear.EkgEpoch sort();
    public int[] sortIndices(com.neurosky.thinkgear.EkgEpoch);
    public float std();
    public int find_heart_beats(int[], float);
    public com.neurosky.thinkgear.EkgEpoch detrend();
    public java.lang.Object clone()       throws java.lang.CloneNotSupportedException;
}

osx:/Users/me/Documents/workspace> javap -classpath /Users/me/Documents/workspace/EKGTest.jar  com.neurosky.thinkgear.EkgSense
Compiled from "EkgSense.java"
public class com.neurosky.thinkgear.EkgSense extends java.lang.Object{
    public com.neurosky.thinkgear.EkgParameters params;
    public com.neurosky.thinkgear.EkgTemplate[] templates;
    public com.neurosky.thinkgear.EkgTemplate currentData;
    public int lastTemplateInd;
    public float lastEpochValue;
    public com.neurosky.thinkgear.EkgSense(com.neurosky.thinkgear.EkgParameters);
    public void reset();
    public void addTemplate(java.lang.String, float[][]);
    public void addTemplate(com.neurosky.thinkgear.EkgTemplate);
    public java.lang.String getClassificationResults();
    public boolean processData(float[]);
}

I am running Matlab on OSX. I have tried with Matlab 7.7.0.471 (R2008b) and 7.11.0.584 (R2010b) and got the same problem. Both Matlab are using the native OSX Java (Java 1.6.0_26-b03-384-10M3425 with Apple Inc. Java HotSpot(TM) 64-Bit Server VM mixed mode) which should be the same as the one in Eclipse (I have checked and Eclipse compiles with 1.6).

Remember that I can see the missing class no problem when I remove the package statement and some imports at the top of the java files (in all the classes of course) and when I simply add the path to the .class files (not access them in a JAR file).

Any help would be greatly appreciated.
Thanks,

Jason

ContentLicense: CC BY-SA 3.0


问:
How to store text as paragraphs in SQLite database in a iPhone app?
In my iPhone app, I have a requirement to store a huge amount of text. I have paragraphs of text to be stored in my database along with the newline characters.

What should I do to store the text as paragraphs in SQLite database?

For example, I want to store paragraphs like the ones below in:

(the mother of the faithful believers) The commencement of the Divine Inspiration to Allah's Apostle was in the form of good dreams which came true like bright day light, and then the love of seclusion was bestowed upon him. He used to go in seclusion in the cave of Hira where he used to worship (Allah alone) continuously for many days before his desire to see his family. He used to take with him the journey food for the stay and then come back to (his wife) Khadija to take his food like-wise again till suddenly the Truth descended upon him while he was in the cave of Hira. The angel came to him and asked him to read. The Prophet replied, "I do not know how to read.

The Prophet added, "The angel caught me (forcefully) and pressed me so hard that I could not bear it any more. He then released me and again asked me to read and I replied, 'I do not know how to read.'

Basically I want to save the paragraphs in database in the same format with carriage returns.

答:
It depends on what you mean by huge and how you're planning on showing the data.  The SQLite TEXT field, by default, can store 1 billion bytes.

You could in theory store all of it in a TEXT field in SQLite, then render it in a UIScrollView (or whatever it is you're using to render) and check the performance, memory usage, etc.

If the performance is unacceptable, you can try "chunking" the text into multiple rows and displaying only the records of the text required for the UI.

See the SQLite Limits document:

Maximum length of a string or BLOB

```<code>The maximum number of bytes in a string or BLOB in SQLite is defined by
</code>```

the preprocessor macro
  SQLITE_MAX_LENGTH. The default value
  of this macro is 1 billion (1 thousand
  million or 1,000,000,000). You can
  raise or lower this value at
  compile-time using a command-line
  option like this:

```<code>-DSQLITE_MAX_LENGTH=123456789
</code>```

Body:
It depends on what you mean by huge and how you're planning on showing the data.  The SQLite TEXT field, by default, can store 1 billion bytes.

You could in theory store all of it in a TEXT field in SQLite, then render it in a UIScrollView (or whatever it is you're using to render) and check the performance, memory usage, etc.

If the performance is unacceptable, you can try "chunking" the text into multiple rows and displaying only the records of the text required for the UI.

See the SQLite Limits document:

Maximum length of a string or BLOB

The maximum number of bytes in a string or BLOB in SQLite is defined by

the preprocessor macro
  SQLITE_MAX_LENGTH. The default value
  of this macro is 1 billion (1 thousand
  million or 1,000,000,000). You can
  raise or lower this value at
  compile-time using a command-line
  option like this:

-DSQLITE_MAX_LENGTH=123456789

ContentLicense: CC BY-SA 2.5


问:
WHEN I am trying to insert an image in database it's not showing any error but image is not inserting in table
I am trying to insert an image in database. It's not showing any error but image is not inserting in table result is printing "not"

CODE

```<code><?php
    if (isset($_POST['pic_upload'])) {

        if(getimagesize($_FILES['image']['tmp_name'])==False) {
            echo "select img";
        } else {
            $image = addslashes($_FILES['image']['tmp_name']);
            $name = addslashes($_FILES['image']['name']);
            $image = file_get_contents($image);
            $image = base64_encode($image);
            saveimage($name,$image);
        }
    }

    function saveimage($name,$image) {
        require 'db.php';
        $sql ="insert into blob(name,image) values('$name','$image')";
        $result=$conn->query($sql);
        if($result) {
            echo "done";
        } else {
            echo 'not';
        }
    }
 ?>
</code>```

答:
As mentioned, you need to use backticks if you're going to use a reserved word as a table name. Also you're escaping the file name, but not escaping any of the data, leaving yourself wide open to SQL injection attacks. Use prepared statements instead.</p>

```<code><?php
if (isset($_POST['pic_upload'])) {

    if(getimagesize($_FILES['image']['tmp_name'])==False) {
        echo "select img";
    } else {
        $name = $_FILES['image']['name'];
        $image = base64_encode(file_get_contents($_FILES['image']['tmp_name']));
        saveimage($name,$image);
    }
}

function saveimage($name,$image) {
    require 'db.php';
    $sql ="INSERT INTO `blob` (`name`, `image`) VALUES (?, ?)";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("sb", $name, $image);
    $result = $stmt->execute();
    if($result) {
        echo "done";
    } else {
        echo 'not';
    }
}
?>
</code>```

Body:
I am trying to insert an image in database. It's not showing any error but image is not inserting in table result is printing "not"

CODE

<?php
    if (isset($_POST['pic_upload'])) {

        if(getimagesize($_FILES['image']['tmp_name'])==False) {
            echo "select img";
        } else {
            $image = addslashes($_FILES['image']['tmp_name']);
            $name = addslashes($_FILES['image']['name']);
            $image = file_get_contents($image);
            $image = base64_encode($image);
            saveimage($name,$image);
        }
    }

    function saveimage($name,$image) {
        require 'db.php';
        $sql ="insert into blob(name,image) values('$name','$image')";
        $result=$conn->query($sql);
        if($result) {
            echo "done";
        } else {
            echo 'not';
        }
    }
 ?>

Body:
As mentioned, you need to use backticks if you're going to use a reserved word as a table name. Also you're escaping the file name, but not escaping any of the data, leaving yourself wide open to SQL injection attacks. Use prepared statements instead.

<?php
if (isset($_POST['pic_upload'])) {

    if(getimagesize($_FILES['image']['tmp_name'])==False) {
        echo "select img";
    } else {
        $name = $_FILES['image']['name'];
        $image = base64_encode(file_get_contents($_FILES['image']['tmp_name']));
        saveimage($name,$image);
    }
}

function saveimage($name,$image) {
    require 'db.php';
    $sql ="INSERT INTO `blob` (`name`, `image`) VALUES (?, ?)";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("sb", $name, $image);
    $result = $stmt->execute();
    if($result) {
        echo "done";
    } else {
        echo 'not';
    }
}
?>


问:
How to do when the activity back to the background forced to redraw the view
Help！
I want to re-draw the page in the app back to the background, but the addView method does not work, the system did not call the onDraw method。

I tried calling the invalidate method and the requestLayout method, but it did not have any effect. Is there any way to solve it? Here is the main code.

```<code>private Handler handler = new Handler(Looper.getMainLooper());
FragmentLayout view1 = (FrameLayout)getWindow().getDecorView();

@Override
protected void onPause() {
    super.onPause();
    handler.post(new Runnable() {
        @Override
        public void run() {
            addRenderScriptBitmap();
        }
    });
    getWindow().getDecorView().findViewById(android.R.id.content).invalidate();
    getWindow().getDecorView().findViewById(android.R.id.content).requestLayout();

}

private void addRenderScriptBitmap() {
    view1.setDrawingCacheEnabled(true);
    view1.buildDrawingCache();
    Bitmap bitmap = view1.getDrawingCache();

    ImageView imageView = new ImageView(MainActivity.this);
    imageView.setLayoutParams(new LinearLayoutCompat.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
    imageView.setImageBitmap(renderScriptBitmap(bitmap, MainActivity.this, 16.f));
    view1.addView(imageView);//This method does not work
}

public Bitmap renderScriptBitmap(Bitmap sentBitmap, Context context, float radius) {
    Bitmap bitmap = sentBitmap.copy(sentBitmap.getConfig(), true);

    final RenderScript rs = RenderScript.create(context);
    final Allocation input = Allocation.createFromBitmap(rs, sentBitmap, Allocation.MipmapControl.MIPMAP_NONE,
            Allocation.USAGE_SCRIPT);
    final Allocation output = Allocation.createTyped(rs, input.getType());
    final ScriptIntrinsicBlur script = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));
    script.setRadius(radius /* e.g. 3.f */);
    script.setInput(input);
    script.forEach(output);
    output.copyTo(bitmap);
    return bitmap;
}
</code>```

I want the application to fall back into the background when it becomes like this：
enter image description here

答:
```<code>@Override
protected void onResume() {
    super.onResume();
    handler.post(new Runnable()
    {
        @Override
        public void run()
        {
            addRenderScriptBitmap();
        }
    });
    getWindow().getDecorView().findViewById(android.R.id.content).invalidate();
    getWindow().getDecorView().findViewById(android.R.id.content).requestLayout();
}
</code>```

Body:
Help！
I want to re-draw the page in the app back to the background, but the addView method does not work, the system did not call the onDraw method。

I tried calling the invalidate method and the requestLayout method, but it did not have any effect. Is there any way to solve it? Here is the main code.

private Handler handler = new Handler(Looper.getMainLooper());
FragmentLayout view1 = (FrameLayout)getWindow().getDecorView();

@Override
protected void onPause() {
    super.onPause();
    handler.post(new Runnable() {
        @Override
        public void run() {
            addRenderScriptBitmap();
        }
    });
    getWindow().getDecorView().findViewById(android.R.id.content).invalidate();
    getWindow().getDecorView().findViewById(android.R.id.content).requestLayout();

}

private void addRenderScriptBitmap() {
    view1.setDrawingCacheEnabled(true);
    view1.buildDrawingCache();
    Bitmap bitmap = view1.getDrawingCache();

    ImageView imageView = new ImageView(MainActivity.this);
    imageView.setLayoutParams(new LinearLayoutCompat.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
    imageView.setImageBitmap(renderScriptBitmap(bitmap, MainActivity.this, 16.f));
    view1.addView(imageView);//This method does not work
}

public Bitmap renderScriptBitmap(Bitmap sentBitmap, Context context, float radius) {
    Bitmap bitmap = sentBitmap.copy(sentBitmap.getConfig(), true);

    final RenderScript rs = RenderScript.create(context);
    final Allocation input = Allocation.createFromBitmap(rs, sentBitmap, Allocation.MipmapControl.MIPMAP_NONE,
            Allocation.USAGE_SCRIPT);
    final Allocation output = Allocation.createTyped(rs, input.getType());
    final ScriptIntrinsicBlur script = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));
    script.setRadius(radius /* e.g. 3.f */);
    script.setInput(input);
    script.forEach(output);
    output.copyTo(bitmap);
    return bitmap;
}

I want the application to fall back into the background when it becomes like this：
enter image description here


问:
How to fix the while loop in this program?
Write a python program that will take 3 lists:

Name    Wage    Hours
Juan    7.50    35
Rae     11.00   41
Ivanna  18.25   26
Lilly   9.25    35
Robert  11.10   45

and use this logic:

An employee gets overtime when they have worked more than 40 hours

Overtime pay is calculated using this formula:

Gross Pay = (35*Wage) + ((Hours-35)*Wage*1.5)

Regular pay is calculated using this formula:

Gross Pay = (Hours*Wage)

Use a loop to process these lists.

Print each employee, their wages, Hours and gross pay.

I'm running this program and I have the for loop. The input works fine, but the while loop that its supposed to have the same output is not giving me any output at all. Here's my code.

```<code>`Name = ["Juan","Rae","Ivanna", "Lilly", "Robert"]
Hours = [35,41,26,35,45]
Wage = [7.5,11,18.25,9.25,11.1]
print ("Name\tWage\tHours\tGP")
for X in range(5):
   GP = 0
   if(Hours[X] > 40):
       GP = (35*Wage[X]) + ((Hours[X]-35)*Wage[X]*1.5)
   else:
       GP = Hours[X] * Wage[X]
   print (Name[X],"\t", Wage[X],"\t", Hours[X],"\t", GP)

Name = ["Juan","Rae","Ivanna", "Lilly", "Robert"]
Hours = [35,41,26,35,45]
Wage = [7.5,11,18.25,9.25,11.1]
print ("Name\tWage\tHours\tGP")
counter = 5
Y = 0
while (Y):
    if (Hours[Y] > 40):
        GP = (35*Wage[Y]) + ((Hours[Y]-35)*Wage[Y]*1.5)
    else:
        GP = Hours[Y] * Wage[Y]
print (Name[Y],"\t", Wage[Y],"\t", Hours[Y],"\t", GP)`
</code>```

my output is going as

```<code>Name    Wage    Hours   GP
Juan     7.5     35      262.5
Rae      11      41      484.0
Ivanna   18.25   26      474.5
Lilly    9.25    35      323.75
Robert   11.1    45      555.0
Name    Wage    Hours   GP
Juan     7.5     35      555.0
</code>```

I don't know where the error is in the while loop.

答:
Your last line needs to be indented. So instead of

```<code>while (Y):
    if (Hours[Y] > 40):
        GP = (35*Wage[Y]) + ((Hours[Y]-35)*Wage[Y]*1.5)
    else:
        GP = Hours[Y] * Wage[Y]
print (Name[Y],"\t", Wage[Y],"\t", Hours[Y],"\t", GP)
</code>```

it needs to be

```<code>while (Y):
    if (Hours[Y] > 40):
        GP = (35*Wage[Y]) + ((Hours[Y]-35)*Wage[Y]*1.5)
    else:
        GP = Hours[Y] * Wage[Y]
    print (Name[Y],"\t", Wage[Y],"\t", Hours[Y],"\t", GP)
</code>```

because right now the print is outside of the while loop, so it is only printing with the value Y=0.

Body:
Write a python program that will take 3 lists:

Name    Wage    Hours
Juan    7.50    35
Rae     11.00   41
Ivanna  18.25   26
Lilly   9.25    35
Robert  11.10   45

and use this logic:

An employee gets overtime when they have worked more than 40 hours

Overtime pay is calculated using this formula:

Gross Pay = (35*Wage) + ((Hours-35)*Wage*1.5)

Regular pay is calculated using this formula:

Gross Pay = (Hours*Wage)

Use a loop to process these lists.

Print each employee, their wages, Hours and gross pay.

I'm running this program and I have the for loop. The input works fine, but the while loop that its supposed to have the same output is not giving me any output at all. Here's my code.

`Name = ["Juan","Rae","Ivanna", "Lilly", "Robert"]
Hours = [35,41,26,35,45]
Wage = [7.5,11,18.25,9.25,11.1]
print ("Name\tWage\tHours\tGP")
for X in range(5):
   GP = 0
   if(Hours[X] > 40):
       GP = (35*Wage[X]) + ((Hours[X]-35)*Wage[X]*1.5)
   else:
       GP = Hours[X] * Wage[X]
   print (Name[X],"\t", Wage[X],"\t", Hours[X],"\t", GP)

Name = ["Juan","Rae","Ivanna", "Lilly", "Robert"]
Hours = [35,41,26,35,45]
Wage = [7.5,11,18.25,9.25,11.1]
print ("Name\tWage\tHours\tGP")
counter = 5
Y = 0
while (Y):
    if (Hours[Y] > 40):
        GP = (35*Wage[Y]) + ((Hours[Y]-35)*Wage[Y]*1.5)
    else:
        GP = Hours[Y] * Wage[Y]
print (Name[Y],"\t", Wage[Y],"\t", Hours[Y],"\t", GP)`

my output is going as

Name    Wage    Hours   GP
Juan     7.5     35      262.5
Rae      11      41      484.0
Ivanna   18.25   26      474.5
Lilly    9.25    35      323.75
Robert   11.1    45      555.0
Name    Wage    Hours   GP
Juan     7.5     35      555.0

I don't know where the error is in the while loop.

Body:
Your last line needs to be indented. So instead of

while (Y):
    if (Hours[Y] > 40):
        GP = (35*Wage[Y]) + ((Hours[Y]-35)*Wage[Y]*1.5)
    else:
        GP = Hours[Y] * Wage[Y]
print (Name[Y],"\t", Wage[Y],"\t", Hours[Y],"\t", GP)

it needs to be

while (Y):
    if (Hours[Y] > 40):
        GP = (35*Wage[Y]) + ((Hours[Y]-35)*Wage[Y]*1.5)
    else:
        GP = Hours[Y] * Wage[Y]
    print (Name[Y],"\t", Wage[Y],"\t", Hours[Y],"\t", GP)

because right now the print is outside of the while loop, so it is only printing with the value Y=0.


问:
How to Access DIV element inside Repeater using JQuery
So I have an ASP.NET repeater control with a textbox and a div with validation text that's hidden. I'm trying to display this div based on if special characters are entered in the textbox. I've managed to apply the jquery regex across all textboxes, but I'm trying to figure out how to apply the validation error to the textbox row where the input is being entered by the User, as I want the error div to display the message on this particular row. I can get it to work on the first row but since the repeater creates it's own control ID's in the HTML, I was wondering how to go about this. Here's my code:

```<code>$(function(){

$('[id*=txtbox1]').keyup(function()
{
    var Input = $(this).val();
    re = /[`~!@#$%^&*()_|+\-=?;:'",.<>\{\}\[\]\\\/]/gi;
    var SplChar = re.test(Input);
    if(SplChar)
    {
        var replchar = Input.replace(/[`~!@#$%^&*()_|+\-=?;:'",.<>\{\}\[\]\\\/]/gi, '');
        $(this).val(replchar);
                    $('#ErrorDiv').show();
    }
});});

<asp:Repeater ID="rptItems" runat="server">
<ItemTemplate>
            <asp:textbox ID="txtbox1" runat="server" Text='<%# Eval("Questions") %>' />
            <div id="ErrorDiv" style="display: none;">No special characters</div>
</ItemTemplate>
</code>```

Any Suggestions ? Appreciate the help.

答:
Add class to your textbox html like so

<asp:textbox ID="txtbox1" class="question" runat="server" Text='<%# Eval("Questions") %>' />

So you can replace

$('[id*=txtbox1]').keyup(function() ...

to this

$(".question").keyup(function() ...

And this #ErrorDiv will not work.. since ID must be unique and your repeater will create multiple div with the same ID. So change id="ErrorDiv" to class="errorDiv".

wrong

$('#ErrorDiv').show();

correct

```<code>// $('#ErrorDiv').show();
$(this).next(".errorDiv").show();
</code>```

Body:
So I have an ASP.NET repeater control with a textbox and a div with validation text that's hidden. I'm trying to display this div based on if special characters are entered in the textbox. I've managed to apply the jquery regex across all textboxes, but I'm trying to figure out how to apply the validation error to the textbox row where the input is being entered by the User, as I want the error div to display the message on this particular row. I can get it to work on the first row but since the repeater creates it's own control ID's in the HTML, I was wondering how to go about this. Here's my code:

$(function(){

$('[id*=txtbox1]').keyup(function()
{
    var Input = $(this).val();
    re = /[`~!@#$%^&*()_|+\-=?;:'",.<>\{\}\[\]\\\/]/gi;
    var SplChar = re.test(Input);
    if(SplChar)
    {
        var replchar = Input.replace(/[`~!@#$%^&*()_|+\-=?;:'",.<>\{\}\[\]\\\/]/gi, '');
        $(this).val(replchar);
                    $('#ErrorDiv').show();
    }
});});

<asp:Repeater ID="rptItems" runat="server">
<ItemTemplate>
            <asp:textbox ID="txtbox1" runat="server" Text='<%# Eval("Questions") %>' />

No special characters

</ItemTemplate>

Any Suggestions ? Appreciate the help.

Body:
Add class to your textbox html like so

<asp:textbox ID="txtbox1" class="question" runat="server" Text='<%# Eval("Questions") %>' />

So you can replace

$('[id*=txtbox1]').keyup(function() ...

to this

$(".question").keyup(function() ...

And this #ErrorDiv will not work.. since ID must be unique and your repeater will create multiple div with the same ID. So change id="ErrorDiv" to class="errorDiv".

wrong

$('#ErrorDiv').show();

correct

// $('#ErrorDiv').show();
$(this).next(".errorDiv").show();


问:
Trying to understand (function(func) { func(); } in JavaScript
Coming from C, every function needs a name that is used to call that specific function. but in the JavaScript code below. There is no name at all. So how does function(func) { func(); } calls the something.push(function() ?

Not to mention that something.push(function() doesn't even have an argument, which from C perspective, this is wrong

```<code>var something = [],
  object = {
    a: true,
    b: true,
    c: true
}

 for (let key in object){
   something.push(function() {
   console.log(key);
   });
 }

 something.forEach(function(func) { func(); }):
</code>```

答:
What you see is the usage of an anonymous function and a closure. It's pretty Javascript in a nutshell.

There I describe the code block per block :

We create an array (like in C) :

```<code>var something = [],
</code>```

We create an object (which is a collection of key=value)

```<code>object = {
    a: true,
    b: true,
    c: true
}
</code>```

We iterate through the elements of the object object

```<code>for (let key in object) {
</code>```

There the show is on :

```<code>something.push(function() {
</code>```

Each object has a push function that allow to put elements dynamically inside of it.
What you see here is a anonymous function being used as an argument; it means that for each executions of this push function, a function that do :

```<code>console.log(key);
</code>```

will be put inside the something array;

There after, the only thing that is done is a callback with func() :

```<code>something.forEach(function(func) { func(); }):
</code>```

This means forEach elements of something, you will treat it as a function resulting in calling the precedent function stored with push()

Body:
Coming from C, every function needs a name that is used to call that specific function. but in the JavaScript code below. There is no name at all. So how does function(func) { func(); } calls the something.push(function() ?

Not to mention that something.push(function() doesn't even have an argument, which from C perspective, this is wrong

var something = [],
  object = {
    a: true,
    b: true,
    c: true
}

 for (let key in object){
   something.push(function() {
   console.log(key);
   });
 }

 something.forEach(function(func) { func(); }):

Body:
What you see is the usage of an anonymous function and a closure. It's pretty Javascript in a nutshell.

There I describe the code block per block :

We create an array (like in C) :

var something = [],

We create an object (which is a collection of key=value)

object = {
    a: true,
    b: true,
    c: true
}

We iterate through the elements of the object object

for (let key in object) {

There the show is on :

something.push(function() {

Each object has a push function that allow to put elements dynamically inside of it.
What you see here is a anonymous function being used as an argument; it means that for each executions of this push function, a function that do :

console.log(key);

will be put inside the something array;

There after, the only thing that is done is a callback with func() :

something.forEach(function(func) { func(); }):

This means forEach elements of something, you will treat it as a function resulting in calling the precedent function stored with push()


问:
Javascript - create text file on website
So I have a web page, and I would like to programaticly create a text file (lets say it has the words 'hello, I am a text file' in it) on a new directory on my website. The program will be in another directory on the website.

e.g.
https://www.example.com/txtbuild.html is trying to programaticly make https://www.example.com/texts/hi.txt

Is there a way to do this with HTML/Javascript?

EDIT:
I am on Github

答:
You can use ActiveXObject, but it won't work in all browsers.

```<code>var fso = new ActiveXObject("Scripting.FileSystemObject");
var a = fso.CreateTextFile("c:\\testfile.txt", true);
a.WriteLine("This is a test.");
a.Close();
</code>```

https://msdn.microsoft.com/en-us/library/5t9b5c0c(v=vs.84).aspx

Body:
You can use ActiveXObject, but it won't work in all browsers.

var fso = new ActiveXObject("Scripting.FileSystemObject");
var a = fso.CreateTextFile("c:\\testfile.txt", true);
a.WriteLine("This is a test.");
a.Close();

https://msdn.microsoft.com/en-us/library/5t9b5c0c(v=vs.84).aspx


问:
Reading integers from txt file in C
I`m making a file reader that reads integers numbers line by line from a file. The problem is that is not working. I think I am using fscanf in a wrong way. Can someone help me?

I had already look for answers in others questions but I can`t find anything that explain why I my code is not working.

```<code>int read_from_txt(){
    FILE *file;
    file = fopen("random_numbers.txt", "r");
    //Counting line numbers to allocate exact memory
    int i;
    unsigned int lines = 0;
    unsigned int *num;
    char ch;
    while(!feof(file)){
        ch = fgetc(file);
        if (ch == '\n'){
            lines++;
        }
    }
    //array size will be lines+1
    num = malloc(sizeof(int)*(lines+1));
    //storing random_numbers in num vector
    for(i=0;i<=lines;i++){
        fscanf(file, "%d", &num[i]);
        printf("%d", num[i]);
    }
    fclose(file);
}
</code>```

The txt file is like:

```<code>12
15
32
68
46
...
</code>```

But the output of this code keeps giving "0000000000000000000..."

答:
You could try to use the getline function from standard IO and add the parsed numbers into the array using only one loop. See the code below.  Please check https://linux.die.net/man/3/getline

Also, you can use the atoi or strtoul functions to convert the read line to an integer. Feel free to check https://linux.die.net/man/3/atoi or https://linux.die.net/man/3/strtoul

The code below evaluate a file with a list of numbers and add those numbers to a C integer pointer

```<code>#include <stdlib.h>
#include <stdio.h>

int main(int argc, char ** argv) {
    FILE * file;

    file = fopen("./file.txt", "r");

    size_t read;
    char * line = NULL;
    size_t line_len = 0;

    size_t buffer_size = 10;
    int * buffer = (int *)malloc(sizeof(int) * buffer_size);

    int seek = 0;
    while((read = getline(&line, &line_len, file)) != -1) {
        buffer[seek++] = atoi(line);

        if (seek % 10 == 0) {
            buffer_size += 10;
            buffer = (int *)realloc(buffer, sizeof(int) * buffer_size);
        }
    }

    for (int i = 0; i < seek; i++) {
        printf("%d\n", buffer[i]);
    }

    free(buffer);
    fclose(file);
}
</code>```

If you aren't sure which conversion function should you use. You can check the difference between atoi and sscanf at What is the difference between sscanf or atoi to convert a string to an integer?

Title: Reading integers from txt file in C

Body:
I`m making a file reader that reads integers numbers line by line from a file. The problem is that is not working. I think I am using fscanf in a wrong way. Can someone help me?

I had already look for answers in others questions but I can`t find anything that explain why I my code is not working.

int read_from_txt(){
    FILE *file;
    file = fopen("random_numbers.txt", "r");
    //Counting line numbers to allocate exact memory
    int i;
    unsigned int lines = 0;
    unsigned int *num;
    char ch;
    while(!feof(file)){
        ch = fgetc(file);
        if (ch == '\n'){
            lines++;
        }
    }
    //array size will be lines+1
    num = malloc(sizeof(int)*(lines+1));
    //storing random_numbers in num vector
    for(i=0;i<=lines;i++){
        fscanf(file, "%d", &num[i]);
        printf("%d", num[i]);
    }
    fclose(file);
}

The txt file is like:

12
15
32
68
46
...

But the output of this code keeps giving "0000000000000000000..."

Body:
You could try to use the getline function from standard IO and add the parsed numbers into the array using only one loop. See the code below.  Please check https://linux.die.net/man/3/getline

Also, you can use the atoi or strtoul functions to convert the read line to an integer. Feel free to check https://linux.die.net/man/3/atoi or https://linux.die.net/man/3/strtoul

The code below evaluate a file with a list of numbers and add those numbers to a C integer pointer

#include <stdlib.h>
#include <stdio.h>

int main(int argc, char ** argv) {
    FILE * file;

    file = fopen("./file.txt", "r");

    size_t read;
    char * line = NULL;
    size_t line_len = 0;

    size_t buffer_size = 10;
    int * buffer = (int *)malloc(sizeof(int) * buffer_size);

    int seek = 0;
    while((read = getline(&line, &line_len, file)) != -1) {
        buffer[seek++] = atoi(line);

        if (seek % 10 == 0) {
            buffer_size += 10;
            buffer = (int *)realloc(buffer, sizeof(int) * buffer_size);
        }
    }

    for (int i = 0; i < seek; i++) {
        printf("%d\n", buffer[i]);
    }

    free(buffer);
    fclose(file);
}

If you aren't sure which conversion function should you use. You can check the difference between atoi and sscanf at What is the difference between sscanf or atoi to convert a string to an integer?


问:
Remove toggle class
This is my first time asking a question on here so lets see how it goes! I am using the Masonry grid layout for one of my sites (allworkedup.org), but can not figure out a toggle class issue. Basically, I want only one grid item open at a time, and for that grid item to go away once I click on another. Below is my code. Thanks!!</p>

```<code>var $grid = $('.grid').masonry({
  itemSelector: '.grid-item',
  columnWidth: '.grid-sizer',
  percentPosition: true

  });

  $grid.on( 'click', '.grid-item', function() {
  // change size of item via class
  $( this ).toggleClass('grid-item--gigante');
  // trigger layout
  $grid.masonry();
  //
  });

  $grid.on( 'layoutComplete', function( event, laidOutItems ) {
  console.log( 'Masonry layout complete with ' + laidOutItems.length + '   items' );
  });

// init Masonry
var $grid = $('.grid').masonry({
  // options...
});
// layout Masonry after each image loads
$grid.imagesLoaded().progress( function() {
  $grid.masonry('layout');
});
</code>```

答:
Rather than using a toggle class feature (which would require a user to click on the item to open and then again to close it), you can use something like:

```<code>$grid.on( 'click', '.grid-item', function() {
    // Close all other open items and open the one that was just clicked
    $( this ).siblings().removeClass('grid-item--gigante');
    $( this ).addClass('grid-item--gigante');
    // trigger layout
    $grid.masonry();
});
</code>```

This way, when a user clicks on one of the grid items, all the siblings of that item (so all the other boxes) are closed, and the one that was clicked will expand instead.

Title: Remove toggle class

Body:
This is my first time asking a question on here so lets see how it goes! I am using the Masonry grid layout for one of my sites (allworkedup.org), but can not figure out a toggle class issue. Basically, I want only one grid item open at a time, and for that grid item to go away once I click on another. Below is my code. Thanks!!

var $grid = $('.grid').masonry({
  itemSelector: '.grid-item',
  columnWidth: '.grid-sizer',
  percentPosition: true

  });

  $grid.on( 'click', '.grid-item', function() {
  // change size of item via class
  $( this ).toggleClass('grid-item--gigante');
  // trigger layout
  $grid.masonry();
  //
  });

  $grid.on( 'layoutComplete', function( event, laidOutItems ) {
  console.log( 'Masonry layout complete with ' + laidOutItems.length + '   items' );
  });

// init Masonry
var $grid = $('.grid').masonry({
  // options...
});
// layout Masonry after each image loads
$grid.imagesLoaded().progress( function() {
  $grid.masonry('layout');
});

Body:
Rather than using a toggle class feature (which would require a user to click on the item to open and then again to close it), you can use something like:

$grid.on( 'click', '.grid-item', function() {
    // Close all other open items and open the one that was just clicked
    $( this ).siblings().removeClass('grid-item--gigante');
    $( this ).addClass('grid-item--gigante');
    // trigger layout
    $grid.masonry();
});

This way, when a user clicks on one of the grid items, all the siblings of that item (so all the other boxes) are closed, and the one that was clicked will expand instead.


问:
C++ Put string in array
I keep seeing similar questions to mine, however, I can't seem to find one that helps my situation. Honestly, it seems like such a mundane question, I shouldn't be asking it, but here I am 2 weeks latter, still with no answer.

```<code>{
    string word;
    ArrayWithWords[d] = word;
    d++;
}
</code>```

Every time this loop runs, I want to put word in position d of the array. Other examples I've found only turn the string into char*.

The array will be used more than once and having a solid value, if that's what it's called, is far more preferred. I'd like to avoid using a pointer.

答:
Just use a vector of strings.</p>

```<code>#include <string>
#include <vector>

int main()
{
  std::vector<std::string> ArrayWithWords(10);
  size_t d = 5; // something between 0 and 9

  std::string word;
  ArrayWithWords[d] = word;
  d++;
}
</code>```

Title: C++ Put string in array

Body:
I keep seeing similar questions to mine, however, I can't seem to find one that helps my situation. Honestly, it seems like such a mundane question, I shouldn't be asking it, but here I am 2 weeks latter, still with no answer.

{
    string word;
    ArrayWithWords[d] = word;
    d++;
}

Every time this loop runs, I want to put word in position d of the array. Other examples I've found only turn the string into char*.

The array will be used more than once and having a solid value, if that's what it's called, is far more preferred. I'd like to avoid using a pointer.

Body:
Just use a vector of strings.

#include <string>
#include <vector>

int main()
{
  std::vector<std::string> ArrayWithWords(10);
  size_t d = 5; // something between 0 and 9

  std::string word;
  ArrayWithWords[d] = word;
  d++;
}


问:
Updating an HTML list using Js
So I have a js game like scrabble. Now when the user makes a new word, I would like the word to be added to a list that is displayed in a div on my page.
The issue is I quite don't understand, how I could keep my old word created and insert a new word with new formatting and everything in a list form.

I know there is a list tag --

```<code><ul>
     <li>apple</li>
     <li>ball</li>
</ul>
</code>```

but what I can't really figure out is how do I use java script to enter the word as a new list entry.

I have used js to display the word created by the following syntax

```<code>document.getElementById('currentword').innerHTML = word;
</code>```

where word is the variable that holds the current word created and currentword is the div id. but how do I use this kind of syntax for a list?
Please help!

Thanks

EDIT: I would also like the last entry to the list as the first item on my list. Seems like the list populates itself but the latest entry gets hidden and the list doesn't really auto scroll down as the items are added.
PS: Also incase someone knows how I could replace the tacky scroll bar option generated by CSS to a custom scroll bar. It would be great if you could point me in the correct direction!

答:
Given a list:

```<code><ul id="theList" >
     <li>apple</li>
     <li>ball</li>
</ul>
</code>```

you could add an
 like this (assuming that the variable word contains the word you want to add):

```<code>document.getElementById('theList').innerHTML += ('<li>'+word+'</li>');
</code>```

There are other ways too, but this one is probably the simplest.

Title: Updating an HTML list using Js

Body:
So I have a js game like scrabble. Now when the user makes a new word, I would like the word to be added to a list that is displayed in a div on my page.
The issue is I quite don't understand, how I could keep my old word created and insert a new word with new formatting and everything in a list form.

I know there is a list tag --

apple

ball

but what I can't really figure out is how do I use java script to enter the word as a new list entry.

I have used js to display the word created by the following syntax

document.getElementById('currentword').innerHTML = word;

where word is the variable that holds the current word created and currentword is the div id. but how do I use this kind of syntax for a list?
Please help!

Thanks

EDIT: I would also like the last entry to the list as the first item on my list. Seems like the list populates itself but the latest entry gets hidden and the list doesn't really auto scroll down as the items are added.
PS: Also incase someone knows how I could replace the tacky scroll bar option generated by CSS to a custom scroll bar. It would be great if you could point me in the correct direction!

Body:
Given a list:

<ul id="theList" >
     <li>apple</li>
     <li>ball</li>
</ul>

you could add an <li> like this (assuming that the variable word contains the word you want to add):

document.getElementById('theList').innerHTML += ('<li>'+word+'</li>');

There are other ways too, but this one is probably the simplest.


问:
how to select some fields from tables in CakePHP
I tried to make query in cakephp with joins, but i want to get more fileds,

Here the query sql :

```<code>SELECT
   sd.debut,
   sd.fin,
   fr.id,
   f.id as formtaion_id,
   s.id as seance_id,
   fr.nom as formateur,
   f.nom as formation,
   r.title,
   f.module,
   sd.module as partie ,
   f.couleur
FROM seances s
   INNER JOIN formations f on s.formation_id = f.id
   INNER JOIN seances_dates sd on s.id = sd.seance_id
   INNER JOIN salles sa on sa.id = s.salle_id
   INNER JOIN regions r on r.id = sa.region_id
   INNER JOIN presence_formateurs pf ON pf.seance_id = s.id
   INNER JOIN formateurs fr ON fr.id = pf.formateur_id
   WHERE fr.archived = 0
      AND fr.deleted is null
      AND (
            (sd.debut between '".$from."' and '".$to."')
            OR
            (sd.fin between '".$from."' and '".$to."')
          )
GROUP BY sd.id
ORDER BY sd.debut
</code>```

please help me to make that query in cakephp :

ClassRegistry::init('seance')->find('all'....

答:
You should read very carefully

1. How to Retrieve data in CakePHP and

2. How to make Relation with different table

Body:
I tried to make query in cakephp with joins, but i want to get more fileds,

Here the query sql :

SELECT
   sd.debut,
   sd.fin,
   fr.id,
   f.id as formtaion_id,
   s.id as seance_id,
   fr.nom as formateur,
   f.nom as formation,
   r.title,
   f.module,
   sd.module as partie ,
   f.couleur
FROM seances s
   INNER JOIN formations f on s.formation_id = f.id
   INNER JOIN seances_dates sd on s.id = sd.seance_id
   INNER JOIN salles sa on sa.id = s.salle_id
   INNER JOIN regions r on r.id = sa.region_id
   INNER JOIN presence_formateurs pf ON pf.seance_id = s.id
   INNER JOIN formateurs fr ON fr.id = pf.formateur_id
   WHERE fr.archived = 0
      AND fr.deleted is null
      AND (
            (sd.debut between '".$from."' and '".$to."')
            OR
            (sd.fin between '".$from."' and '".$to."')
          )
GROUP BY sd.id
ORDER BY sd.debut

please help me to make that query in cakephp :

ClassRegistry::init('seance')->find('all'....


问:
How I can create handler for dead-letter queue in Azure using MassTransit?
I need to process messages in dead-letter queue. How I can create handler for this? Also I need to handle messages from error queue that also fell into dead-letter.</p>

答:
You can use a tool like Service Bus Explorer to move messages from a dead-letter queue back into the queue, and likewise for messages in the error queue. There isn't a MassTransit-specific tool for this purpose.

If you have known errors that would cause messages to fail, you can use features of Service Bus such as scheduling messages for future delivery instead of throwing the exception all the way back to MassTransit and having it move to the error queue.


问:
using + in the variables passed to a url
I am trying to do a call to url

```<code>http://example.com/controller/action?var1=CD14+%20MDM%20in%20GM-CSF%203%20days%20then%203%20days%20IFN-%CE%B3&var2=56&var3=ENSG00000115415
</code>```

If you look at var1 that I am passing value 'CD14+ MDM in GM-CSF 3 days then 3days IFN-γ'.

When in the controller I try to get this var 1 using request.params.get("var1"), i get 'CD14  MDM in GM-CSF 3 days then 3days IFN-γ' with missing + and instead getting extra space after CD14

How can I pass + in my variable in url

答:
Try '%2B' (as other have stated).

But if you are in Javascript, you could just use the built-in method for doing URL encoding called "encodeURIComponent". Note you need that and not "encodeURI" which will not encode reserved characters like '+'. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent

Body:
I am trying to do a call to url

http://example.com/controller/action?var1=CD14+%20MDM%20in%20GM-CSF%203%20days%20then%203%20days%20IFN-%CE%B3&var2=56&var3=ENSG00000115415

If you look at var1 that I am passing value 'CD14+ MDM in GM-CSF 3 days then 3days IFN-γ'.

When in the controller I try to get this var 1 using request.params.get("var1"), i get 'CD14  MDM in GM-CSF 3 days then 3days IFN-γ' with missing + and instead getting extra space after CD14

How can I pass + in my variable in url


问:
SSRS switch and datediff
I am writing a report that needs to display a different datediff calculation based on a specific Value from a column. If the order is "Active" start time to Now or if the order is ceased start time to stop time.

The individual DateDiff expressions work but when I try to combine them in one expression using either switch or IIF I get errors.

Any suggestions would be great.

```<code>=IIF(Fields!OrderStatus.Value="Active", DateDiff("d",Fields!OrderStartTime.Value, "Now"()),
       IIF(Fields!OrderStatus.Value="Discontinued", DateDiff("d",Fields!OrderStartTime.Value, Fields!DiscontinueTime.Value)
       )
)

=Switch(Fields!OrderStatus.Value="Active",
DateDiff("d",Fields!OrderStartTime.Value, "Now"()),
Fields!OrderStatus.Value="Discontinued",
DateDiff("d",Fields!OrderStartTime.Value, Fields!DiscontinueTime.Value),
)
</code>```

答:
You are missing the third argument for your second iif statement (in this case, it'll be {Nothing}.  This should work:

=IIF(Fields!OrderStatus.Value="Active",DateDiff("d",Fields!OrderStartTime.Value,Today()),IIF(Fields!OrderStatus.Value="Discontinued",DateDiff("d",Fields!OrderStartTime.Value,Fields!DiscontinuedTime.Value),Nothing))

Title: SSRS switch and datediff

Body:
I am writing a report that needs to display a different datediff calculation based on a specific Value from a column. If the order is "Active" start time to Now or if the order is ceased start time to stop time.

The individual DateDiff expressions work but when I try to combine them in one expression using either switch or IIF I get errors.

Any suggestions would be great.

=IIF(Fields!OrderStatus.Value="Active", DateDiff("d",Fields!OrderStartTime.Value, "Now"()),
       IIF(Fields!OrderStatus.Value="Discontinued", DateDiff("d",Fields!OrderStartTime.Value, Fields!DiscontinueTime.Value)
       )
)

=Switch(Fields!OrderStatus.Value="Active",
DateDiff("d",Fields!OrderStartTime.Value, "Now"()),
Fields!OrderStatus.Value="Discontinued",
DateDiff("d",Fields!OrderStartTime.Value, Fields!DiscontinueTime.Value),
)


问:
How to specify top_terms_N rewrite using Nest SDK for Elastic?
Elastic version 5.2
I have this query in elastic DSL.

```<code>POST my-index/_search
{
  "query": {
    "wildcard": {
      "Author": {
        "value": "*joe*",
        "rewrite": "top_terms_15"
      }
    }
  }
}
</code>```

I want to write the same query using Nest SDK.

```<code>    private Nest.WildcardQuery CreateQuery()
    {
        Nest.WildcardQuery query = new Nest.WildcardQuery();
        query.Field = "Author";
        query.Value = "*joe*";

        query.Rewrite = Nest.RewriteMultiTerm.TopTermsN;
        //Now how to specify a value for N ?

        return query;
    }
</code>```

How can I specify a value for N ? (when using Nest.RewriteMultiTerm.TopTermsN)

Elastic version 5.2.1
Kibana version 5.2.1
Nest version 5.2.0

答:
This is a bug in Elastic SDK, and according to Elastic folks, this would be fixed in the next 5.x release.

Full details can be found on the elastic forum.

https://discuss.elastic.co/t/how-to-specify-top-terms-n-rewrite-using-nest-sdk/77743/3

According to that, there is a work around for this issue until a fix is available.

Work around
Use the low client exposed on NEST.

```<code>var response = client.LowLevel.Search<SearchResponse<object>>("my-index",
@"{
    ""query"": {
        ""wildcard"": {
            ""Author"": {
                ""value"": ""*joe*"",
                ""rewrite"": ""top_terms_15""
            }
        }
    }
}");

// a search response that you would be returned from a NEST search query
var nestResponse = response.Body;
</code>```

Body:
Elastic version 5.2
I have this query in elastic DSL.

POST my-index/_search
{
  "query": {
    "wildcard": {
      "Author": {
        "value": "*joe*",
        "rewrite": "top_terms_15"
      }
    }
  }
}

I want to write the same query using Nest SDK.

    private Nest.WildcardQuery CreateQuery()
    {
        Nest.WildcardQuery query = new Nest.WildcardQuery();
        query.Field = "Author";
        query.Value = "*joe*";

        query.Rewrite = Nest.RewriteMultiTerm.TopTermsN;
        //Now how to specify a value for N ?

        return query;
    }

How can I specify a value for N ? (when using Nest.RewriteMultiTerm.TopTermsN)

Elastic version 5.2.1
Kibana version 5.2.1
Nest version 5.2.0

Body:
This is a bug in Elastic SDK, and according to Elastic folks, this would be fixed in the next 5.x release.

Full details can be found on the elastic forum.

https://discuss.elastic.co/t/how-to-specify-top-terms-n-rewrite-using-nest-sdk/77743/3

According to that, there is a work around for this issue until a fix is available.

Work around
Use the low client exposed on NEST.

var response = client.LowLevel.Search<SearchResponse<object>>("my-index",
@"{
    ""query"": {
        ""wildcard"": {
            ""Author"": {
                ""value"": ""*joe*"",
                ""rewrite"": ""top_terms_15""
            }
        }
    }
}");

// a search response that you would be returned from a NEST search query
var nestResponse = response.Body;


问:
Getting duplicate entry error after adding branch.io to my android project
Everything was working fine, but after adding this to my android project error building apk started.Here is the error and dependency

```<code>Error:Execution failed for task ':app:transformClassesWithJarMergingForDebug'.
</code>```

com.android.build.api.transform.TransformException: java.util.zip.ZipException: duplicate entry: com/crashlytics/android/answers/shim/R.class

```<code> compile('io.branch.sdk.android:library:2.6.0@aar') {
    transitive = true;
    exclude module: 'answers-shim'
}
</code>```

tried excluding it also but error persists.
Here is my full gradle

```<code>buildscript {
repositories {
    maven { url 'https://maven.fabric.io/public' }
}

dependencies {
    classpath 'io.fabric.tools:gradle:1.+'
}
}
apply plugin: 'com.android.application'
apply plugin: 'io.fabric'

repositories {
maven { url 'https://maven.fabric.io/public' }
maven { url "https://dl.bintray.com/hani-momanii/maven"}
}

android {
compileSdkVersion 25
buildToolsVersion "25.0.2"
defaultConfig {
    applicationId "com.example.app"
    minSdkVersion 19
    targetSdkVersion 25
    multiDexEnabled true
    versionCode 1
    versionName "1.0"
    resConfigs "en_US", "hi_IN"
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
packagingOptions {
    exclude 'META-INF/LICENSE'
    exclude 'META-INF/DEPENDENCIES'
    exclude 'META-INF/LICENSE-FIREBASE.txt'
    exclude 'META-INF/NOTICE'
}

}

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile('com.digits.sdk.android:digits:2.0.6@aar') {
    transitive = true;

}
compile('com.crashlytics.sdk.android:crashlytics:2.6.7@aar') {
    transitive = true;
}
compile('io.fabric.sdk.android:fabric:1.3.10@aar') {
    transitive = true;
}
compile 'com.android.support:multidex:1.0.1'
compile 'com.android.support:appcompat-v7:25.3.1'
compile 'com.android.support:support-v13:25.3.1'
compile 'com.android.support:design:25.3.1'
compile 'com.android.support:gridlayout-v7:25.3.1'
compile 'com.android.support:cardview-v7:25.3.1'
compile 'com.android.support:recyclerview-v7:25.3.1'
compile 'com.android.support:support-annotations:25.3.1'
compile 'de.hdodenhof:circleimageview:1.3.0'
compile 'com.github.bumptech.glide:glide:3.7.0'
compile 'com.google.code.gson:gson:2.7'
compile 'com.google.android.gms:play-services-location:10.2.1'
compile 'com.google.android.gms:play-services-places:10.2.1'
compile 'com.amazonaws:aws-android-sdk-core:2.2.+'
compile 'com.amazonaws:aws-android-sdk-s3:2.2.+'
compile 'com.amazonaws:aws-android-sdk-ddb:2.2.+'
compile 'com.amazonaws:aws-android-sdk-lambda:2.2.+'
compile 'com.google.firebase:firebase-database:10.2.1'
compile 'com.google.firebase:firebase-core:10.2.1'
compile 'com.google.firebase:firebase-auth:10.2.1'
compile 'com.google.firebase:firebase-messaging:10.2.1'
compile 'com.google.firebase:firebase-crash:10.2.1'
compile 'com.firebaseui:firebase-ui-database:1.2.0'
compile 'com.google.firebase:firebase-storage:10.2.1'
compile 'com.google.firebase:firebase-appindexing:10.2.1'
compile 'com.github.clans:fab:1.6.4'
compile 'com.amazonaws:aws-android-sdk-cognito:2.3.9'
compile 'hani.momanii.supernova_emoji_library:supernova-emoji-library:0.0.2'
compile 'com.facebook.android:facebook-android-sdk:[4,5)'
compile('io.branch.sdk.android:library:2.6.0@aar') {
    transitive = true;
    exclude module: 'answers-shim'
}

}
apply plugin: 'com.google.gms.google-services'
</code>```

If i add the exclude statement to branch and digits then while entering the app it crashes,if added exclude to crashlytics the error persists.But without adding branch everything works perfect no error during apk build too.

答:
I was struggling with this all day today as well. What ended up fixing it for me was rolling back branch to 2.5.9. There obviously seems to be something wrong with the new 2.6.0 release.

Another note for branch I don't have the transitive aar include so it's just

```<code>compile ('io.branch.sdk.android:library:2.5.9') {
    exclude module: 'answers-shim';
}
</code>```

Body:
Everything was working fine, but after adding this to my android project error building apk started.Here is the error and dependency

Error:Execution failed for task ':app:transformClassesWithJarMergingForDebug'.

com.android.build.api.transform.TransformException: java.util.zip.ZipException: duplicate entry: com/crashlytics/android/answers/shim/R.class

 compile('io.branch.sdk.android:library:2.6.0@aar') {
    transitive = true;
    exclude module: 'answers-shim'
}

tried excluding it also but error persists.
Here is my full gradle

buildscript {
repositories {
    maven { url 'https://maven.fabric.io/public' }
}

dependencies {
    classpath 'io.fabric.tools:gradle:1.+'
}
}
apply plugin: 'com.android.application'
apply plugin: 'io.fabric'

repositories {
maven { url 'https://maven.fabric.io/public' }
maven { url "https://dl.bintray.com/hani-momanii/maven"}
}

android {
compileSdkVersion 25
buildToolsVersion "25.0.2"
defaultConfig {
    applicationId "com.example.app"
    minSdkVersion 19
    targetSdkVersion 25
    multiDexEnabled true
    versionCode 1
    versionName "1.0"
    resConfigs "en_US", "hi_IN"
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
packagingOptions {
    exclude 'META-INF/LICENSE'
    exclude 'META-INF/DEPENDENCIES'
    exclude 'META-INF/LICENSE-FIREBASE.txt'
    exclude 'META-INF/NOTICE'
}

}

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile('com.digits.sdk.android:digits:2.0.6@aar') {
    transitive = true;

}
compile('com.crashlytics.sdk.android:crashlytics:2.6.7@aar') {
    transitive = true;
}
compile('io.fabric.sdk.android:fabric:1.3.10@aar') {
    transitive = true;
}
compile 'com.android.support:multidex:1.0.1'
compile 'com.android.support:appcompat-v7:25.3.1'
compile 'com.android.support:support-v13:25.3.1'
compile 'com.android.support:design:25.3.1'
compile 'com.android.support:gridlayout-v7:25.3.1'
compile 'com.android.support:cardview-v7:25.3.1'
compile 'com.android.support:recyclerview-v7:25.3.1'
compile 'com.android.support:support-annotations:25.3.1'
compile 'de.hdodenhof:circleimageview:1.3.0'
compile 'com.github.bumptech.glide:glide:3.7.0'
compile 'com.google.code.gson:gson:2.7'
compile 'com.google.android.gms:play-services-location:10.2.1'
compile 'com.google.android.gms:play-services-places:10.2.1'
compile 'com.amazonaws:aws-android-sdk-core:2.2.+'
compile 'com.amazonaws:aws-android-sdk-s3:2.2.+'
compile 'com.amazonaws:aws-android-sdk-ddb:2.2.+'
compile 'com.amazonaws:aws-android-sdk-lambda:2.2.+'
compile 'com.google.firebase:firebase-database:10.2.1'
compile 'com.google.firebase:firebase-core:10.2.1'
compile 'com.google.firebase:firebase-auth:10.2.1'
compile 'com.google.firebase:firebase-messaging:10.2.1'
compile 'com.google.firebase:firebase-crash:10.2.1'
compile 'com.firebaseui:firebase-ui-database:1.2.0'
compile 'com.google.firebase:firebase-storage:10.2.1'
compile 'com.google.firebase:firebase-appindexing:10.2.1'
compile 'com.github.clans:fab:1.6.4'
compile 'com.amazonaws:aws-android-sdk-cognito:2.3.9'
compile 'hani.momanii.supernova_emoji_library:supernova-emoji-library:0.0.2'
compile 'com.facebook.android:facebook-android-sdk:[4,5)'
compile('io.branch.sdk.android:library:2.6.0@aar') {
    transitive = true;
    exclude module: 'answers-shim'
}

}
apply plugin: 'com.google.gms.google-services'

If i add the exclude statement to branch and digits then while entering the app it crashes,if added exclude to crashlytics the error persists.But without adding branch everything works perfect no error during apk build too.

Body:
I was struggling with this all day today as well. What ended up fixing it for me was rolling back branch to 2.5.9. There obviously seems to be something wrong with the new 2.6.0 release.

Another note for branch I don't have the transitive aar include so it's just

compile ('io.branch.sdk.android:library:2.5.9') {
    exclude module: 'answers-shim';
}


问:
Which Data Mining Method?
I have millions of confusion matrices. Which data mining method I should use to summarize them or find the relationship between these matrices?
I would be thankful if you can give me a hint that can be helpful for me.</p>

答:
A Confusion matrix is mostly used to give a numeric values on performance of a Classification model. It's both strange and interesting that you have millions of them!!! (It would be helpful if you add some explanation that from where did you end up having millions of confusion matrices!)

If your confusion matrices are coming from such procedure, then you might need to work on the rates they give (such as 'accuracy', 'precision', 'specificity', 'recall', etc) as your new features. And then, based on the those features, you may directly apply another classification/clustering model to achieve your ultimate goal, or start with some feature selection (using descriptive statistics for instance: Min, Max, Mean, Median, Var) or feature extraction to reduce the complexity (dimensionality) of your space.

Title: Which Data Mining Method?


问:
Why separate Voip certificate is required for Pushkit when APNS Universal Client SSL Certificate has been introduced?
Just a minor confusion. Why we need a separate Voip Service Certificate for Pushkit when we have Universal Client SSL certificate for APNS which supports primary app, voip etc?

As per latest Apple docs,

If my app supports multiple topics (voip/non-voip), is it not better to use single APNS SSL certificate rather than separate certificates? This will also make sure same connection (APNS Provider to APNS) can be used for delivering both Voip Push as well as standard Push.

答: You don't.  The universal will work with both APNS and PushKit.  Your server signals which one it wants by setting the appropriate "topic" on the push notification.</p>


问:
Set Shadow on Bottom UIView only
I want to create bottom only shadow on UIView. Right now with this function, will create shadow in top, bottom, left, and right.

```<code>func setCardView(view : UIView){
    view.layer.masksToBounds = false
    view.layer.shadowOffset = CGSize(width: 0, height: 0)
    view.layer.shadowRadius = 2
    view.layer.shadowOpacity = 0.5
}
</code>```

Is there anyway to only create shadow in the bottom?
Any help would be appreciated. Thank you!

答:
Change your shadowOffset

```<code> view.layer.shadowOffset = CGSize(width: 0, height: 3)
</code>```

Title: Set Shadow on Bottom UIView only

Body:
I want to create bottom only shadow on UIView. Right now with this function, will create shadow in top, bottom, left, and right.

func setCardView(view : UIView){
    view.layer.masksToBounds = false
    view.layer.shadowOffset = CGSize(width: 0, height: 0)
    view.layer.shadowRadius = 2
    view.layer.shadowOpacity = 0.5
}

Is there anyway to only create shadow in the bottom?
Any help would be appreciated. Thank you!

Body:
Change your shadowOffset

 view.layer.shadowOffset = CGSize(width: 0, height: 3)


问:
Can I browse web pages via html by PyCharm?
Can I browse a web page by PyCharm?

The web page is not in local but say, such as yahoo.com.
I want to take a look without changing the focused window in my computer.

答:
Short answer: No

Long answer: You used to have one but...

We used to have built-in browser in IDEA had to abandon it - it turned out that external browser was the better choice since

a) external browser is closer to the one needed for your target (e.g. targeting Chrome, Mobile Safari / Opera, etc)

b) embedded browser does not live well with Swing application (e.g. focus quirks).

It is worth mentioning you can view the raw HTML of a web page by going to: File > Open URL...


问:
Argument resolution inside Global Variable on Bat files
Is it possible to use an argument from inside a variable ?

I need to have a global var that will be used at the start of some bat files.

set variable

```<code>setx var "echo %~n0 %*"
</code>```

sample.bat

```<code>%var% > lastBatExecuted.txt
set /p last=<lastBatExecuted.txt
if "%last%"=="%~n0 %*" echo it worked
pause
</code>```

I know some ways to solve this problem with work arounds or simple copy paste, but would like to have a one liner that could be put inside a variable.

(length wouldn't be a problem, if i'm still able to just call %var%)

答:
Yes, this method works, but you need to define the variable value with double percent signs, and insert an additional call command in order to re-evaluate the percent signs after the first %var% expansion. See this test:

```<code>@echo off
setlocal

set "var=echo One: %%~n0 %%*"
%var%
call %var%

set "var=call echo Two: %%~n0 %%*"
%var%
</code>```

Usage example:

```<code>C:\> test Arg1 Arg2
</code>```

Output

```<code>One: %~n0 %*
One: test Arg1 Arg2
Two: test Arg1 Arg2
</code>```

The same behavior should work when the var is defined via setx command.

Body:
Is it possible to use an argument from inside a variable ?

I need to have a global var that will be used at the start of some bat files.

set variable

setx var "echo %~n0 %*"

sample.bat

%var% > lastBatExecuted.txt
set /p last=<lastBatExecuted.txt
if "%last%"=="%~n0 %*" echo it worked
pause

I know some ways to solve this problem with work arounds or simple copy paste, but would like to have a one liner that could be put inside a variable.

(length wouldn't be a problem, if i'm still able to just call %var%)

Body:
Yes, this method works, but you need to define the variable value with double percent signs, and insert an additional call command in order to re-evaluate the percent signs after the first %var% expansion. See this test:

@echo off
setlocal

set "var=echo One: %%~n0 %%*"
%var%
call %var%

set "var=call echo Two: %%~n0 %%*"
%var%

Usage example:

C:\> test Arg1 Arg2

Output

One: %~n0 %*
One: test Arg1 Arg2
Two: test Arg1 Arg2

The same behavior should work when the var is defined via setx command.


问:
Comma separated values join to master table
i want to display data when data from other table with two rows or more and to be one row with "for xml path", but alway null when use "for xml path". please look my sample table and my sql query now.

```<code>TCPAR :
IdCPAR | IdReferensi
1        '1','2'
2        '1','3','4'

TReferensi :
IdReferensi | Referensi
1              Alfa
2              Beta
3              Carlie
4              Delta

i want result like this:
IdCpar | IdReferensi | ReferensiName
1         '1','2'      'Alfa','Beta'
</code>```

and this is my sql query :

```<code>select
a.idCpar,
a.IdReferensi,
(
    SELECT LEFT(result, Len(result) - 1) FROM(SELECT '''' + Referensi + ''',' FROM TReferensi (NOLOCK)
    WHERE IdReferensi IN (a.IdReferensi)
    ORDER  BY Referensi FOR XML PATH ('')) x (result)
)as ReferensiName
from TCPAR as a
where a.IdCPAR=1

and the result:
idCpar | IdReferensi | ReferensiName
1          '1','2'     NULL
</code>```

Please help me... thanks...

答:
```<code>CREATE TABLE TReferensi
    ([IdReferensi] int, [Referensi] varchar(6))
;

INSERT INTO TReferensi
    ([IdReferensi], [Referensi])
VALUES
    (1, 'Alfa'),
    (2, 'Beta'),
    (3, 'Carlie'),
    (4, 'Delta')
;

CREATE TABLE TCPAR
    ([IdCPAR] int, [IdReferensi] varchar(100))
;

INSERT INTO TCPAR
    ([IdCPAR], [IdReferensi])
VALUES
    (1, '''1'',''2'''),
    (2, '''1'',''3'',''4''')
;

;with cte as
(
    select
        t1.IdCPAR, t2.IdReferensi
    from
    (
        select
            IdCPAR,
            IdReferensi = cast(cast(t2.c.query('data(.)') as varchar) as int)
        from
        (
            select
                IdCPAR,
                ReferensiXml = cast('<root><a>' + replace(REPLACE(IdReferensi,'''',''), ',', '</a><a>') + '</a></root>' as xml)
            from TCPAR
        ) t1
        cross apply ReferensiXml.nodes('/root/a') t2(c)
    ) t1
    join TReferensi t2 on t1.IdReferensi = t2.IdReferensi
)

SELECT T2.IdCPAR,T3.IdReferensi,
        STUFF((SELECT ','''+Referensi+''''
        FROM (
                select
                    t1.IdCPAR,t2.Referensi
                from cte t1
                INNER JOIN TReferensi t2
                ON  t2.IdReferensi = t1.IdReferensi
             )T1
        WHERE T2.IdCPAR = T1.IdCPAR
        FOR XML PATH('')),1,1,'') AS Referensi
FROM(
    select
        t1.IdCPAR,t2.Referensi
    from cte t1
    INNER JOIN TReferensi t2
    ON  t2.IdReferensi = t1.IdReferensi
 )T2
INNER JOIN TCPAR T3
 ON T3.IdCPAR = T2.IdCPAR
GROUP BY T2.IdCPAR,T3.IdReferensi
</code>```

Demo

Body:
i want to display data when data from other table with two rows or more and to be one row with "for xml path", but alway null when use "for xml path". please look my sample table and my sql query now.

TCPAR :
IdCPAR | IdReferensi
1        '1','2'
2        '1','3','4'

TReferensi :
IdReferensi | Referensi
1              Alfa
2              Beta
3              Carlie
4              Delta

i want result like this:
IdCpar | IdReferensi | ReferensiName
1         '1','2'      'Alfa','Beta'

and this is my sql query :

select
a.idCpar,
a.IdReferensi,
(
    SELECT LEFT(result, Len(result) - 1) FROM(SELECT '''' + Referensi + ''',' FROM TReferensi (NOLOCK)
    WHERE IdReferensi IN (a.IdReferensi)
    ORDER  BY Referensi FOR XML PATH ('')) x (result)
)as ReferensiName
from TCPAR as a
where a.IdCPAR=1

and the result:
idCpar | IdReferensi | ReferensiName
1          '1','2'     NULL

Please help me... thanks...

Body:
CREATE TABLE TReferensi
    ([IdReferensi] int, [Referensi] varchar(6))
;

INSERT INTO TReferensi
    ([IdReferensi], [Referensi])
VALUES
    (1, 'Alfa'),
    (2, 'Beta'),
    (3, 'Carlie'),
    (4, 'Delta')
;

CREATE TABLE TCPAR
    ([IdCPAR] int, [IdReferensi] varchar(100))
;

INSERT INTO TCPAR
    ([IdCPAR], [IdReferensi])
VALUES
    (1, '''1'',''2'''),
    (2, '''1'',''3'',''4''')
;

;with cte as
(
    select
        t1.IdCPAR, t2.IdReferensi
    from
    (
        select
            IdCPAR,
            IdReferensi = cast(cast(t2.c.query('data(.)') as varchar) as int)
        from
        (
            select
                IdCPAR,
                ReferensiXml = cast('<root><a>' + replace(REPLACE(IdReferensi,'''',''), ',', '</a><a>') + '</a></root>' as xml)
            from TCPAR
        ) t1
        cross apply ReferensiXml.nodes('/root/a') t2(c)
    ) t1
    join TReferensi t2 on t1.IdReferensi = t2.IdReferensi
)

SELECT T2.IdCPAR,T3.IdReferensi,
        STUFF((SELECT ','''+Referensi+''''
        FROM (
                select
                    t1.IdCPAR,t2.Referensi
                from cte t1
                INNER JOIN TReferensi t2
                ON  t2.IdReferensi = t1.IdReferensi
             )T1
        WHERE T2.IdCPAR = T1.IdCPAR
        FOR XML PATH('')),1,1,'') AS Referensi
FROM(
    select
        t1.IdCPAR,t2.Referensi
    from cte t1
    INNER JOIN TReferensi t2
    ON  t2.IdReferensi = t1.IdReferensi
 )T2
INNER JOIN TCPAR T3
 ON T3.IdCPAR = T2.IdCPAR
GROUP BY T2.IdCPAR,T3.IdReferensi

Demo


问:
Writing a custom NER and POS tagger in pyspark to use in the pipeline method for feature extraction of textual inputs
I am doing a text classification project and I am using the pipeline method from mllib to chain the feature extraction stages. My dataset consists of English sentences. I have the Tokenizer and the TFIDF Vectorizer libraries from mllib that I can directly use in the pipeline.

But as a part of the feature extraction process, I also need to extract POS tags and NER tags. Pyspark doesn't have a library for it and I don't know how can I write a custom transformer for NER and POS tagging. I am very new to Spark and Python. I am using Spark 1.6 and Python 2.7.

答:
You can try this:

class POSWordTagger(Transformer, HasInputCol, HasOutputCol):

    @keyword_only
    def __init__(self, inputCol=None, outputCol=None, stopwords=None):
        super(POSWordTagger, self).__init__()
        self.stopwords = Param(self, "stopwords", "")
        self._setDefault(stopwords=set())
        kwargs = self.__init__._input_kwargs
        self.setParams(**kwargs)

    @keyword_only
    def setParams(self, inputCol=None, outputCol=None, stopwords=None):
        kwargs = self.setParams._input_kwargs
        return self._set(**kwargs)

    def setStopwords(self, value):
        self._paramMap[self.stopwords] = value
        return self

    def getStopwords(self):
        return self.getOrDefault(self.stopwords)

    def _transform(self, dataset):

        def f(s):
        tokens = nltk.tokenize.wordpunct_tokenize(s)
        pos_tags = nltk.pos_tag(tokens)
        return pos_tags

        t = ArrayType(StringType())
        out_col = self.getOutputCol()
        in_col = dataset[self.getInputCol()]
        return dataset.withColumn(out_col, udf(f, t)(in_col))
```


问:
Seeming contradictory borrowing scenarios in Rust
This first Rust program won't compile because b is dropped before its reference r, which makes sense:

```<code>fn main() {
    let a = "a";
    let v;
    {
        let b = "b";
        v = &b;
    }
    println!("{}", v);
}
</code>```

In this second Rust program, a reference to b is retrieved via a function, and all of the sudden there's no issue:

```<code>fn getRef(b: &str) -> &str {
    b
}

fn main() {
    let a = "a";
    let v;
    {
        let b = "b";
        v = getRef(&b);
    }
    println!("{}", v);
}
</code>```

The thing is, v is still a reference to b, and b is out of scope for the println!().

Why are these two different?

答:
Because they aren't doing the same thing.

If you print the type of the variable, you'll see that in the first example, v is of type &&str, specifically & &'static str. In the second example, v is of type &str, specifically &'static str.

In the first example, you have a reference to a local value, which indeed goes out of scope.

In the second example, although you take a reference to b, producing a &&str, you then call a function that expects a &str. Deref coercion kicks in and automatically dereferences the value.

Thus the second example is equivalent to

```<code>fn main() {
    let a = "a";
    let v;
    {
        let b = "b";
        v = b;
    }
    println!("{}", v);
}
</code>```

That is, you are making a copy of an immutable reference to a string that will live the entire life of the program.

Body:
This first Rust program won't compile because b is dropped before its reference r, which makes sense:

fn main() {
    let a = "a";
    let v;
    {
        let b = "b";
        v = &b;
    }
    println!("{}", v);
}

In this second Rust program, a reference to b is retrieved via a function, and all of the sudden there's no issue:

fn getRef(b: &str) -> &str {
    b
}

fn main() {
    let a = "a";
    let v;
    {
        let b = "b";
        v = getRef(&b);
    }
    println!("{}", v);
}

The thing is, v is still a reference to b, and b is out of scope for the println!().

Why are these two different?

Body:
Because they aren't doing the same thing.

If you print the type of the variable, you'll see that in the first example, v is of type &&str, specifically & &'static str. In the second example, v is of type &str, specifically &'static str.

In the first example, you have a reference to a local value, which indeed goes out of scope.

In the second example, although you take a reference to b, producing a &&str, you then call a function that expects a &str. Deref coercion kicks in and automatically dereferences the value.

Thus the second example is equivalent to

fn main() {
    let a = "a";
    let v;
    {
        let b = "b";
        v = b;
    }
    println!("{}", v);
}

That is, you are making a copy of an immutable reference to a string that will live the entire life of the program.