问:
Android app with java ee backend
i'm asking if i can work with java ee and spring like a backend to developp an android application, also I wonder if I can execute an android app on iphone or it must be ios app to work on iphone thanks :)</p>

答:
You can write Android app in Java or Kotlin. Java EE that is mentioned in your question is a platform for developing enterprise software, it's not related to Android app development. Keep in mind that you are going to develop an app for the phone, so the app should take as little as possible memory. It's better to avoid some practices heavily used for the backend development, for example reflection. That might slow down your app.
If you need dependency injection framework you might be interested in dagger2. If you need http client you might be interested in okhttp and retrofit2 for calling webservices. Also there are several ORM frameworks for Android - room and greenDao. There are much more frameworks, I'm mentioning only the most popular ones. Most Java libraries are suitable for Android.

You can't execute native Android app on iOS. If you are interested in multiplatform app development you can try looking into react native

Title: Android app with java ee backend


来源: stackexchange

问:
Sending E-mail using C#
I need to send email via my C# app.

I come from a VB 6 background and had a lot of bad experiences with the MAPI control.
First of all, MAPI did not support HTML emails and second, all the emails were sent to my default mail outbox. So I still needed to click on send receive.

If I needed to send bulk html bodied emails (100 - 200), what would be the best way to do this in C#?

答:
The .NET framework has some built-in classes which allows you to send e-mail via your app.

You should take a look in the System.Net.Mail namespace, where you'll find the MailMessage and SmtpClient classes.
You can set the BodyFormat of the MailMessage class to MailFormat.Html.

It could also be helpfull if you make use of the AlternateViews property of the MailMessage class, so that you can provide a plain-text version of your mail, so that it can be read by clients that do not support HTML.

http://msdn.microsoft.com/en-us/library/system.net.mail.mailmessage.alternateviews.aspx

OwnerDisplayName: Shaun

ContentLicense: CC BY-SA 4.0

Title: Sending E-mail using C#

LastEditorDisplayName: Can Berk Güder

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Frederik Gheysels


问:
Can i retrieve array value not using loop?
is there a way to retrieve array value not using any loop function?
I have this sort of array</p>

```<code>$at=array(
    array(
        array('Title:','titl','s','c',$titles),
        array('First Name:','name','i','A',2,10 ),
    ),
</code>```

答:
Yes, you can.

for example $at[0], $at[1], $at[2]

When an array hasn't been assigned keys, the keys ( in the above example keys would be 0 1 and 2) ascend numerically from 0.

For an array with keys (such as $at = array('key' => 'value', 'key2' => 'value2') ), you can access the properties as $at['key'], $at['key2'] ( note the quotes wrapping the key name )

Hope this is of use to you!

Cheers!,
Pedro

Body:
is there a way to retrieve array value not using any loop function?
I have this sort of array

$at=array(
    array(
        array('Title:','titl','s','c',$titles),
        array('First Name:','name','i','A',2,10 ),
    ),


问:
How to set LinearGradients into ComposeShader
I am trying to make ComposeShader using LinearGradients but may have few problem.

1)  If I am only use one LinearGradient like

lgA = new LinearGradient(0, 0, 0, h, 0xff000000, 0xffffffff, Shader.TileMode.CLAMP);

then above part of the requirement correct

2)  If use  ComposeShader then result not like actual requirement

Actual Requirment :

Then how I can solve this problem please any one help me for this problem.

```<code>public class DrawGradient extends View {

    Paint paint;
    LinearGradient lgA;
    LinearGradient lgB;
    ComposeShader shader;

    public DrawGradient(Context context) {
        super(context);
        initView();
    }

    private void initView() {
        setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        paint = new Paint();
        paint.setAntiAlias(true);
        paint.setFilterBitmap(true);

    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        lgA = new LinearGradient(0, 0, w, h, 0xff000000, 0xffffffff, Shader.TileMode.CLAMP);
        lgB = new LinearGradient(0, h, w, 0, 0xffffffff, 0xff000000, Shader.TileMode.CLAMP);
        shader = new ComposeShader(lgA, lgB, PorterDuff.Mode.MULTIPLY);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        paint.setShader(shader);
        canvas.drawPaint(paint);
    }
}
</code>```

Code Output :

答:
Since this four months I imagine this will be of little help now, but here it is for anyone else with a similar problem.

The problem lies in these two lines:

```<code>lgA = new LinearGradient(0, 0, w, h, 0xff000000, 0xffffffff, Shader.TileMode.CLAMP);
lgB = new LinearGradient(0, h, w, 0, 0xffffffff, 0xff000000, Shader.TileMode.CLAMP);
</code>```

You've created two linear gradients; one going from top-left to bottom-left, the other going from bottom-left to top-right. What you are looking for is this:

```<code>lgA = new LinearGradient(0, 0, 0, h/2, Color.BLACK, Color.WHITE, Shader.TileMode.CLAMP);
lgB = new LinearGradient(0, h/2, 0, h, Color.WHITE, Color.BLACK, Shader.TileMode.CLAMP);
</code>```

With these changes, it worked for me. It's important to note that ComposeShader wouldn't work without the line:

```<code>setLayerType(View.LAYER_TYPE_SOFTWARE, null);
</code>```

For reasons explained here.

ComposeShader seems to be mostly used for overlaying Shaders, such as LinearGradients, rather than creating a three colour transition which you're looking for. Alternatively you could have used LinearGradient by itself, but with the other constructor, which can take more than two different colours. E.g.

```<code>int[] colors = {Color.BLACK,Color.WHITE,Color.BLACK};
float[] pos = {0.0f,0.5f,1.0f};
paint.setShader(new LinearGradient(0,0,0,h,colors,pos,Shader.TileMode.CLAMP));
</code>```

This would have given you the same effect, without needing ComposeShader. However I was using this method in my own project, but using Color.TRANSPARENT in the gradient and it was coming out black rather than transparent.

ContentLicense: CC BY-SA 3.0

Body:
I am trying to make ComposeShader using LinearGradients but may have few problem.

1)  If I am only use one LinearGradient like

lgA = new LinearGradient(0, 0, 0, h, 0xff000000, 0xffffffff, Shader.TileMode.CLAMP);

then above part of the requirement correct

2)  If use  ComposeShader then result not like actual requirement

Actual Requirment :

Then how I can solve this problem please any one help me for this problem.

public class DrawGradient extends View {

    Paint paint;
    LinearGradient lgA;
    LinearGradient lgB;
    ComposeShader shader;

    public DrawGradient(Context context) {
        super(context);
        initView();
    }

    private void initView() {
        setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        paint = new Paint();
        paint.setAntiAlias(true);
        paint.setFilterBitmap(true);

    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        lgA = new LinearGradient(0, 0, w, h, 0xff000000, 0xffffffff, Shader.TileMode.CLAMP);
        lgB = new LinearGradient(0, h, w, 0, 0xffffffff, 0xff000000, Shader.TileMode.CLAMP);
        shader = new ComposeShader(lgA, lgB, PorterDuff.Mode.MULTIPLY);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        paint.setShader(shader);
        canvas.drawPaint(paint);
    }
}

Code Output :

Body:
Since this four months I imagine this will be of little help now, but here it is for anyone else with a similar problem.

The problem lies in these two lines:

lgA = new LinearGradient(0, 0, w, h, 0xff000000, 0xffffffff, Shader.TileMode.CLAMP);
lgB = new LinearGradient(0, h, w, 0, 0xffffffff, 0xff000000, Shader.TileMode.CLAMP);

You've created two linear gradients; one going from top-left to bottom-left, the other going from bottom-left to top-right. What you are looking for is this:

lgA = new LinearGradient(0, 0, 0, h/2, Color.BLACK, Color.WHITE, Shader.TileMode.CLAMP);
lgB = new LinearGradient(0, h/2, 0, h, Color.WHITE, Color.BLACK, Shader.TileMode.CLAMP);

With these changes, it worked for me. It's important to note that ComposeShader wouldn't work without the line:

setLayerType(View.LAYER_TYPE_SOFTWARE, null);

For reasons explained here.

ComposeShader seems to be mostly used for overlaying Shaders, such as LinearGradients, rather than creating a three colour transition which you're looking for. Alternatively you could have used LinearGradient by itself, but with the other constructor, which can take more than two different colours. E.g.

int[] colors = {Color.BLACK,Color.WHITE,Color.BLACK};
float[] pos = {0.0f,0.5f,1.0f};
paint.setShader(new LinearGradient(0,0,0,h,colors,pos,Shader.TileMode.CLAMP));

This would have given you the same effect, without needing ComposeShader. However I was using this method in my own project, but using Color.TRANSPARENT in the gradient and it was coming out black rather than transparent.


问:
JS Client-Side Exif Orientation: Rotate and Mirror JPEG Images
Digital camera photos are often saved as JPEG with an EXIF "orientation" tag. To display correctly, images need to be rotated/mirrored depending on which orientation is set, but browsers ignore this information rendering the image. Even in large commercial web apps, support for EXIF orientation can be spotty 1. The same source also provides a nice summary of the 8 different orientations  a JPEG can have:

Sample images are available at 4.

The question is how to rotate/mirror the image on the client side so that it displays correctly and can be further processed if necessary?

There are JS libraries available to parse EXIF data, including the orientation attribute 2. Flickr noted possible performance problem when parsing large images, requiring use of webworkers 3.

Console tools can correctly re-orient the images 5. A PHP script solving the problem is available at 6

答:
In addition to @fareed namrouti's answer,

This should be used if the image has to be browsed from a file input element

```<code><input type="file" name="file" id="file-input"><br/>
image after transform: <br/>
<div id="container"></div>

<script>
    document.getElementById('file-input').onchange = function (e) {
        var image = e.target.files[0];
        window.loadImage(image, function (img) {
            if (img.type === "error") {
                console.log("couldn't load image:", img);
            } else {
                window.EXIF.getData(image, function () {
                    console.log("load image done!");
                    var orientation = window.EXIF.getTag(this, "Orientation");
                    var canvas = window.loadImage.scale(img,
                        {orientation: orientation || 0, canvas: true, maxWidth: 200});
                    document.getElementById("container").appendChild(canvas);
                    // or using jquery $("#container").append(canvas);
                });
            }
        });
    };
</script>
</code>```

Body:
In addition to @fareed namrouti's answer,

This should be used if the image has to be browsed from a file input element

<input type="file" name="file" id="file-input"><br/>
image after transform: <br/>
<div id="container"></div>

<script>
    document.getElementById('file-input').onchange = function (e) {
        var image = e.target.files[0];
        window.loadImage(image, function (img) {
            if (img.type === "error") {
                console.log("couldn't load image:", img);
            } else {
                window.EXIF.getData(image, function () {
                    console.log("load image done!");
                    var orientation = window.EXIF.getTag(this, "Orientation");
                    var canvas = window.loadImage.scale(img,
                        {orientation: orientation || 0, canvas: true, maxWidth: 200});
                    document.getElementById("container").appendChild(canvas);
                    // or using jquery $("#container").append(canvas);
                });
            }
        });
    };
</script>


问:
Why do we need a Scanner Object for taking input in java
To print output we simply use System.out stream while to take input, we have to pass System.in in Constructor of a Scanner object and then use that object only. </p>

<p>Why is it so ? Why is there no direct method like System.in.nextInt() or something alike? </p>

答:
One important difference between System.in and System.out is, that - although both are streams - one is a more specialized stream. Look at the class' documentation:

Field Summary

```<code>static InputStream in
static PrintStream out
</code>```

The counterpart of InputStream is an OutputStream, but the Java designers made the class variable out a PrintStream. This is the reason why you see more specialized methods for System.out than you do for System.in.

As for why this is the case, see @GhostCat's answer.

Body:
To print output we simply use System.out stream while to take input, we have to pass System.in in Constructor of a Scanner object and then use that object only.

Why is it so ? Why is there no direct method like System.in.nextInt() or something alike?

Body:
One important difference between System.in and System.out is, that - although both are streams - one is a more specialized stream. Look at the class' documentation:

Field Summary

static InputStream in
static PrintStream out

The counterpart of InputStream is an OutputStream, but the Java designers made the class variable out a PrintStream. This is the reason why you see more specialized methods for System.out than you do for System.in.

As for why this is the case, see @GhostCat's answer.


问:
How can I set the dpiAware property in a Windows application manifest to "per monitor" in Visual Studio?
I need to be able to set the dpiAware property in the manifest of my application to "per monitor".  The available choices in the properties are just to enable or disable DPI awareness.  Neither of these settings works for me.  I can get the behavior I want for my application if I don't embed the manifest in the exe, then edit the manifest manually.  I want to automatically generate and embed the manifest.  Is there something I am missing?  (I am using Visual Studio 2013.)</p>

答:
In Windows 10 1607 a new property named dpiAwareness was introduced. It allows choosing a fallback DPI scaling options and overrides dpiAware property, if present. For the best compatibility one should specify both of these and make sure your application works with all DPI-awareness levels.

The following manifest enables per-monitor DPI-awareness version 2 on Windows 10 1607+ and system DPI-awareness on Windows 7+:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1" xmlns:asmv3="urn:schemas-microsoft-com:asm.v3">
    <assemblyIdentity type="win32" name="MyApplication" version="1.0.0.0" processorArchitecture="amd64"/>

    <asmv3:application>
        <asmv3:windowsSettings>
            <dpiAware xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">true/pm</dpiAware>
            <dpiAwareness xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">PerMonitorV2</dpiAwareness>
            <gdiScaling xmlns="http://schemas.microsoft.com/SMI/2017/WindowsSettings">true</gdiScaling>
        </asmv3:windowsSettings>
    </asmv3:application>
</assembly>
```

To disable DPI-awareness, you can either simply leave DPI-awareness unspecified (the default is unaware), or specify dpiAware as false.

Also note the gdiScaling property, which was added in Windows 10 1607. It enables automatic GDI scaling if set to true. It's very useful if your application uses GDI for drawing things.

References:

High-DPI scaling since Windows 10 1607

Writing DPI-aware applications

Application manifests

Body:
In Windows 10 1607 a new property named dpiAwareness was introduced. It allows choosing a fallback DPI scaling options and overrides dpiAware property, if present. For the best compatibility one should specify both of these and make sure your application works with all DPI-awareness levels.

The following manifest enables per-monitor DPI-awareness version 2 on Windows 10 1607+ and system DPI-awareness on Windows 7+:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1" xmlns:asmv3="urn:schemas-microsoft-com:asm.v3">
    <assemblyIdentity type="win32" name="MyApplication" version="1.0.0.0" processorArchitecture="amd64"/>

    <asmv3:application>
        <asmv3:windowsSettings>
            <dpiAware xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">true/pm</dpiAware> <!-- fallback for Windows 7 and 8 -->
            <dpiAwareness xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">PerMonitorV2</dpiAwareness> <!-- adding v1 as fallback would result in v2 not being applied to dialogs on capable systems -->
            <gdiScaling xmlns="http://schemas.microsoft.com/SMI/2017/WindowsSettings">true</gdiScaling> <!-- enables GDI DPI scaling -->
        </asmv3:windowsSettings>
    </asmv3:application>
</assembly>

To disable DPI-awareness, you can either simply leave DPI-awareness unspecified (the default is unaware), or specify dpiAware as false.

Also note the gdiScaling property, which was added in Windows 10 1607. It enables automatic GDI scaling if set to true. It's very useful if your application uses GDI for drawing things.

References:

High-DPI scaling since Windows 10 1607

Writing DPI-aware applications

Application manifests


问:
Separating multiple if conditions with commas in Swift
We already know multiple optional bindings can be used in a single if/guard statement by separating them with commas, but not with && e.g.

```<code>// Works as expected
if let a = someOpt, b = someOtherOpt {
}
// Crashes
if let a = someOpt && b = someOtherOpt {
}
</code>```

Playing around with playgrounds, the comma-style format also seems to work for boolean conditions though I can't find this mentioned anywhere.  e.g.

```<code>if 1 == 1, 2 == 2 {
}
// Seems to be the same as
if 1 == 1 && 2 == 2 {
}
</code>```

Is this an accepted method for evaluating multiple boolean conditions, and is the behaviour of , identical to that of && or are they technically different?

答:
In Swift 3, the where keyword in condition clauses were replaced by a comma instead.

So a statement like if 1 == 1, 2 == 2 {} is saying "if 1 equals 1 where 2 equals 2..."

It's probably easiest to read a conditional statement with an && instead of a ,, but the results are the same.

You can read more about the details of the change in Swift 3 in the Swift Evolution proposal: https://github.com/apple/swift-evolution/blob/master/proposals/0099-conditionclauses.md

Body:
We already know multiple optional bindings can be used in a single if/guard statement by separating them with commas, but not with && e.g.

// Works as expected
if let a = someOpt, b = someOtherOpt {
}
// Crashes
if let a = someOpt && b = someOtherOpt {
}

Playing around with playgrounds, the comma-style format also seems to work for boolean conditions though I can't find this mentioned anywhere.  e.g.

if 1 == 1, 2 == 2 {
}
// Seems to be the same as
if 1 == 1 && 2 == 2 {
}

Is this an accepted method for evaluating multiple boolean conditions, and is the behaviour of , identical to that of && or are they technically different?


问:
Conditionally adding DOM elements with Reflex
I have a function that receives a Dynamic and has to display a dom element which will contain a different kind of child depending on the value in the Dynamic. Is there a way to do such thing using Reflex and Reflex-Dom? The code would look like this if the value in the dynamic could be unwrapped by pattern matching:</p>

```<code>myNode :: MonadWidget t m => Dynamic t Bool -> m (Event t ())
myNode (Dynamic True) = elClass "div" "foo" $
  elClass "div" "bar"
myNode (Dynamic False) = blank
</code>```

答: I've found the solution. The function dyn can be used in those situations. Also see this other stackoverflow question.</p>

Body:
I have a function that receives a Dynamic and has to display a dom element which will contain a different kind of child depending on the value in the Dynamic. Is there a way to do such thing using Reflex and Reflex-Dom? The code would look like this if the value in the dynamic could be unwrapped by pattern matching:

myNode :: MonadWidget t m => Dynamic t Bool -> m (Event t ())
myNode (Dynamic True) = elClass "div" "foo" $
  elClass "div" "bar"
myNode (Dynamic False) = blank


问:
C# equivalent of C++ std::string find_first_not_of and find_last_not_of
IndexOf, IndexOfAny and LastIndexOf, LastIndexOfAny dont seem to do these (or maybe they do). I'm looking for the equialent of std::string's find_first_not_of and find_last_not_of. I'm thinking about creating an extension class but I'm not sure if C# already provides this functionality.

答:
```<code>string source = "the quick brown fox jumps over the lazy dog";
string chars = "ogd hte";

int? firstNotOf = source.Select((x, i) => new { Val = x, Idx = (int?)i })
                        .Where(x => chars.IndexOf(x.Val) == -1)
                        .Select(x => x.Idx)
                        .FirstOrDefault();

int? lastNotOf = source.Select((x, i) => new { Val = x, Idx = (int?)i })
                       .Where(x => chars.IndexOf(x.Val) == -1)
                       .Select(x => x.Idx)
                       .LastOrDefault();
</code>```

Or, if you prefer some non-LINQ extension methods. These should have slightly better performance, especially for FindLastNotOf:

```<code>int? firstNotOf = source.FindFirstNotOf(chars);
int? lastNotof = source.FindLastNotOf(chars);

// ...

public static int? FindFirstNotOf(this string source, string chars)
{
    if (source == null) throw new ArgumentNullException("source");
    if (chars == null) throw new ArgumentNullException("chars");
    if (source.Length == 0) return null;
    if (chars.Length == 0) return 0;

    for (int i = 0; i < source.Length; i++)
    {
        if (chars.IndexOf(source[i]) == -1) return i;
    }
    return null;
}

public static int? FindLastNotOf(this string source, string chars)
{
    if (source == null) throw new ArgumentNullException("source");
    if (chars == null) throw new ArgumentNullException("chars");
    if (source.Length == 0) return null;
    if (chars.Length == 0) return source.Length - 1;

    for (int i = source.Length - 1; i >= 0; i--)
    {
        if (chars.IndexOf(source[i]) == -1) return i;
    }
    return null;
}
</code>```

(It's possible that you might get better performance -- in both the LINQ and non-LINQ versions -- if you convert chars to a HashSet<char>, or maybe even a plain char[] array. You'd need to benchmark to find out, though any difference is likely to be negligible unless chars gets pretty big.)

Body:
string source = "the quick brown fox jumps over the lazy dog";
string chars = "ogd hte";

int? firstNotOf = source.Select((x, i) => new { Val = x, Idx = (int?)i })
                        .Where(x => chars.IndexOf(x.Val) == -1)
                        .Select(x => x.Idx)
                        .FirstOrDefault();

int? lastNotOf = source.Select((x, i) => new { Val = x, Idx = (int?)i })
                       .Where(x => chars.IndexOf(x.Val) == -1)
                       .Select(x => x.Idx)
                       .LastOrDefault();

Or, if you prefer some non-LINQ extension methods. These should have slightly better performance, especially for FindLastNotOf:

int? firstNotOf = source.FindFirstNotOf(chars);
int? lastNotof = source.FindLastNotOf(chars);

// ...

public static int? FindFirstNotOf(this string source, string chars)
{
    if (source == null) throw new ArgumentNullException("source");
    if (chars == null) throw new ArgumentNullException("chars");
    if (source.Length == 0) return null;
    if (chars.Length == 0) return 0;

    for (int i = 0; i < source.Length; i++)
    {
        if (chars.IndexOf(source[i]) == -1) return i;
    }
    return null;
}

public static int? FindLastNotOf(this string source, string chars)
{
    if (source == null) throw new ArgumentNullException("source");
    if (chars == null) throw new ArgumentNullException("chars");
    if (source.Length == 0) return null;
    if (chars.Length == 0) return source.Length - 1;

    for (int i = source.Length - 1; i >= 0; i--)
    {
        if (chars.IndexOf(source[i]) == -1) return i;
    }
    return null;
}

(It's possible that you might get better performance -- in both the LINQ and non-LINQ versions -- if you convert chars to a HashSet<char>, or maybe even a plain char[] array. You'd need to benchmark to find out, though any difference is likely to be negligible unless chars gets pretty big.)


问:
Selenium send_keys with no response
When I run my code with PhantomJS and selenium ,and the res shows act, but in send_keys the code won't go on, just stay in, no wrong , no any answer and no keep in. I just want know why.</p>

```<code>res = re.findall(r'\<input id=\"([^\n]*)\" type=\"file\" style="font-size: 999px; opacity: 0; position: absolute; top: 0px; left: 0px; width: 100%; height: 100%;',pages)
dr = driver.find_element_by_id(res[0])
dr.send_keys('/Users/liangshengjun/Desktop/bin/2_0.jpg')
</code>```

答:
It happens because you've only selected file, you don't submit any form and didn't take any action. So you need either to click some submit button or send ENTER key with your file path like this:

```<code>from selenium.webdriver.common.keys import Keys
# your code here, then add this key on last step.
dr.send_keys('/Users/liangshengjun/Desktop/bin/2_0.jpg' + Keys.ENTER)
</code>```

And you really shouldn't use regexes to find an input, you'd better try xpath or may be css selectors.

And it's good approach to debug with some graphic browser like Firefox before switching to headless mode (Google Chrome --headless or PhantomJS as in your case).

Title: Selenium send_keys with no response

Body:
When I run my code with PhantomJS and selenium ,and the res shows act, but in send_keys the code won't go on, just stay in, no wrong , no any answer and no keep in. I just want know why.

res = re.findall(r'\<input id=\"([^\n]*)\" type=\"file\" style="font-size: 999px; opacity: 0; position: absolute; top: 0px; left: 0px; width: 100%; height: 100%;',pages)
dr = driver.find_element_by_id(res[0])
dr.send_keys('/Users/liangshengjun/Desktop/bin/2_0.jpg')

Body:
It happens because you've only selected file, you don't submit any form and didn't take any action. So you need either to click some submit button or send ENTER key with your file path like this:

from selenium.webdriver.common.keys import Keys
# your code here, then add this key on last step.
dr.send_keys('/Users/liangshengjun/Desktop/bin/2_0.jpg' + Keys.ENTER)

And you really shouldn't use regexes to find an input, you'd better try xpath or may be css selectors.

And it's good approach to debug with some graphic browser like Firefox before switching to headless mode (Google Chrome --headless or PhantomJS as in your case).


问:
Python: querying a list of results while processes are finishing
I am using the twitter API to capture the number of times a user has tweeted. I would like to get access to the list of results before all of the process have completed

```<code>def get_status_count(twitter_handle, output):

while True:
    try:
        auth = tweepy.OAuthHandler(consumer_keys, consumer_secret)
        auth.set_access_token(access_token, access_token_secret)
        client = tweepy.API(auth)
        twitter_handle = twitter_handle
        user = client.get_user(screen_name = twitter_handle)
        timeline = user.timeline()

        status = timeline[0]
        json_str = json.dumps(status._json)
        json_dict = json.loads(json_str)

        json_user_dict =  json_dict['user']
        total_tweets = json_user_dict['statuses_count']

        output.put(total_tweets)

        break

    except tweepy.error.TweepError as e:
        print "In the except method"
        print e
        time.sleep(5)
</code>```

I want to check twitter multiple times to see if the status count has changed. I've implemented this code.

```<code>processes = [mp.Process(target=get_status_count, args=('gregcharte',
output)) for x in range(10)]

# Run processes
for p in processes:
    p.start()

# Exit the completed processes
for p in processes:
    p.join()

results = [output.get() for p in processes]
print results
</code>```

which gives me a list [80, 80, 80, 80, 80, 80, 80, 80, 80, 80]. How can I instead get the list after each process finishes. For instance

[80]
[80, 80]
[80, 80, 80]

Any help would be greatly appreciated. I'm new to multiprocessing.

答:
If you just want it to print each piece of the list as it builds all you need to do is to put your print statement up into the loop. It would look something like this:

```<code>results = []
for p in processes:
    results = results.append([output.get])
    print results
</code>```

I haven't tested that you may need to tweak it but that should do it
also I would look into multithreading for checking the status of something while running

Body:
I am using the twitter API to capture the number of times a user has tweeted. I would like to get access to the list of results before all of the process have completed

def get_status_count(twitter_handle, output):

while True:
    try:
        auth = tweepy.OAuthHandler(consumer_keys, consumer_secret)
        auth.set_access_token(access_token, access_token_secret)
        client = tweepy.API(auth)
        twitter_handle = twitter_handle
        user = client.get_user(screen_name = twitter_handle)
        timeline = user.timeline()

        status = timeline[0]
        json_str = json.dumps(status._json)
        json_dict = json.loads(json_str)

        json_user_dict =  json_dict['user']
        total_tweets = json_user_dict['statuses_count']

        output.put(total_tweets)

        break

    except tweepy.error.TweepError as e:
        print "In the except method"
        print e
        time.sleep(5)

I want to check twitter multiple times to see if the status count has changed. I've implemented this code.

processes = [mp.Process(target=get_status_count, args=('gregcharte',
output)) for x in range(10)]

# Run processes
for p in processes:
    p.start()

# Exit the completed processes
for p in processes:
    p.join()

results = [output.get() for p in processes]
print results

which gives me a list [80, 80, 80, 80, 80, 80, 80, 80, 80, 80]. How can I instead get the list after each process finishes. For instance

[80]
[80, 80]
[80, 80, 80]

Any help would be greatly appreciated. I'm new to multiprocessing.

Body:
If you just want it to print each piece of the list as it builds all you need to do is to put your print statement up into the loop. It would look something like this:

results = []
for p in processes:
    results = results.append([output.get])
    print results

I haven't tested that you may need to tweak it but that should do it
also I would look into multithreading for checking the status of something while running


问:
Swift 3 : Stomp WebSocket library
I want to subscribe to a topic after successful connection, however I am not able to do so. I have tried all the libraries for eg.Starscream(only for WebSocket connection), StompClient, ActionCableClient, FayeSwift etc. but none seem to work. I want to connect and subscribe to Stomp Client WebSocket, Please suggest me some WebSocket library that can connect and subscribe to STOMP Client.</p>

答:
I could not work successfully with other libraries. That's why I've created StompClient library. I hope that helps.

Cocoapods:
https://cocoapods.org/pods/StompClientLib

Github:
https://github.com/wrathchaos/StompClientLib

Title: Swift 3 : Stomp WebSocket library


问:
Firebase storage folder delete
I have a folder in firebase storage where I upload users images to, however I can't delete this folder.

```<code>Storage.storage().reference().child("folder").delete();
</code>```

I get error code 404, message: Not found. Could not delete object.

答:
EDIT:

You can use the new List API to list files in storage with some common prefix.  The prefix is effectively the the path where the objects live.  You will have to them iterate each object you get from the API, and delete each one individually.  Also read this blog post about the API.

ORIGINAL ANSWER:

There is currently no way to programmatically delete an entire folder in Cloud Storage with the Firebase SDK.  It turns out, with Cloud Storage, there is not even any "folders" at all.  A storage bucket just a collection of objects that have names that look like file paths.  It is not a real "filesystem" in this respect.

If you want to delete all the files under a certain path, you will have to find all their names and remove them individually.  Typically, applications will store the paths of known objects in Realtime Database for this reason.

If you want to delete all objects under a path from the command line with gsutil, read the docs for "gsutil rm".

Title: Firebase storage folder delete

Body:
I have a folder in firebase storage where I upload users images to, however I can't delete this folder.

Storage.storage().reference().child("folder").delete();

I get error code 404, message: Not found. Could not delete object.


问:
Dominating Term between 2^logn and n^(5/2)
lets say in order to compute Big-O of these two functions and take log both sides fx<=c.gx log(2^logn) + log(n^(5/2)) <= log(n^(5/2)) which is log n + log n <= log n it satisfies for equals if any one function taken out from left side log n = log n. but not for less than condition. so in short can any of them be Dominating Term interchangeably.?</p>

答:
Depends on the base of the logarithm. Call it a:

So if

then

and vice versa.


问:
Convert pandas timestamp to month endate
I have the following code:

```<code>#!/usr/bin/python

import pandas as pd

df = pd.read_excel(io='http://www.iea.org/gtf/download/Export_GTF_IEA.xls', sheetname='Data', skip_footer=5, )

df = df.drop('Unnamed: 2', axis=1)
df = df.drop('Exit', axis=1)
df = df.drop('Entry', axis=1)
df = df.drop('MAXFLOW (Mm3/h)', axis=1)

df = df.T

df.to_csv('foo.csv', encoding='utf-8', sep='\t', header=False)
</code>```

#

A sample of the output looks like this:

```<code>print df
                              0        1           2           3        4    \
Borderpoint          Adriatic LNG  Almeria  Alveringem  Alveringem  Badajoz
2008-10-01 00:00:00             0        0           0           0   152.81
2008-11-01 00:00:00             0        0           0           0   183.31
2008-12-01 00:00:00             0        0           0           0    85.21
2009-01-01 00:00:00             0        0           0           0   199.16
2009-02-01 00:00:00             0        0           0           0   104.48
2009-03-01 00:00:00             0        0           0           0     9.17
</code>```

How do I convert the timestamp to a month-end date?

答:
Headers are not set properly so to set proper headers you can use

```<code>df.columns = df.iloc[0]
df.drop(df.index[:1], inplace=True)
</code>```

Den to change the timestamps to month end date you can use

```<code>df.index = df.index + pd.offsets.MonthEnd(0)
</code>```

Output :

```
Borderpoint Adriatic LNG  Almeria Alveringem Alveringem  Badajoz Badajoz
2008-10-31             0        0          0          0   152.81       0
2008-11-30             0        0          0          0   183.31       0
2008-12-31             0        0          0          0    85.21       0
2009-01-31             0        0          0          0   199.16       0
2009-02-28             0        0          0          0   104.48      12
2009-03-31             0        0          0          0     9.17       2
2009-04-30             0        0          0          0   190.49       0
2009-05-31             0        0          0          0        0       0

```

Body:
I have the following code:

#!/usr/bin/python

import pandas as pd

df = pd.read_excel(io='http://www.iea.org/gtf/download/Export_GTF_IEA.xls', sheetname='Data', skip_footer=5, )

df = df.drop('Unnamed: 2', axis=1)
df = df.drop('Exit', axis=1)
df = df.drop('Entry', axis=1)
df = df.drop('MAXFLOW (Mm3/h)', axis=1)

df = df.T

df.to_csv('foo.csv', encoding='utf-8', sep='\t', header=False)

#

A sample of the output looks like this:

print df
                              0        1           2           3        4    \
Borderpoint          Adriatic LNG  Almeria  Alveringem  Alveringem  Badajoz
2008-10-01 00:00:00             0        0           0           0   152.81
2008-11-01 00:00:00             0        0           0           0   183.31
2008-12-01 00:00:00             0        0           0           0    85.21
2009-01-01 00:00:00             0        0           0           0   199.16
2009-02-01 00:00:00             0        0           0           0   104.48
2009-03-01 00:00:00             0        0           0           0     9.17

How do I convert the timestamp to a month-end date?

Body:
Headers are not set properly so to set proper headers you can use

df.columns = df.iloc[0]
df.drop(df.index[:1], inplace=True)

Den to change the timestamps to month end date you can use

df.index = df.index + pd.offsets.MonthEnd(0)

Output :

Borderpoint Adriatic LNG  Almeria Alveringem Alveringem  Badajoz Badajoz
2008-10-31             0        0          0          0   152.81       0
2008-11-30             0        0          0          0   183.31       0
2008-12-31             0        0          0          0    85.21       0
2009-01-31             0        0          0          0   199.16       0
2009-02-28             0        0          0          0   104.48      12
2009-03-31             0        0          0          0     9.17       2
2009-04-30             0        0          0          0   190.49       0
2009-05-31             0        0          0          0        0       0


问:
Apache redirect & rewrite
This is my page
http://example.com/index.html .
I would like to make it work like this.

I would like to take the user to http://def.com when he requests
http://example.com/index.html

Even if he requests http://example.com/index.html?headers=0, he should be taken
to http://def.com

But if he requests the same URL with other query parameters, say for example http://example.com/index.html?footer=1, then the redirect or rewrite shouldn't happen. He should still be seeing the response from http://example.com/index.html?footer=1

I have already tried

```<code>    RewriteCond %{QUERY_STRING} ^$
    RewriteRule ^/index.html$ http://def.com
</code>```

答:
Change your htaccess file to this:</p>

```<code>RewriteCond %{QUERY_STRING} ^$ [OR]
RewriteCond %{QUERY_STRING} !headers
RewriteRule ^index.html$ http://def.com [R=301,L]
</code>```

Title: Apache redirect & rewrite

Body:
This is my page
http://example.com/index.html .
I would like to make it work like this.

I would like to take the user to http://def.com when he requests
http://example.com/index.html

Even if he requests http://example.com/index.html?headers=0, he should be taken
to http://def.com

But if he requests the same URL with other query parameters, say for example http://example.com/index.html?footer=1, then the redirect or rewrite shouldn't happen. He should still be seeing the response from http://example.com/index.html?footer=1

I have already tried

    RewriteCond %{QUERY_STRING} ^$
    RewriteRule ^/index.html$ http://def.com

Body:
Change your htaccess file to this:

RewriteCond %{QUERY_STRING} ^$ [OR]
RewriteCond %{QUERY_STRING} !headers
RewriteRule ^index.html$ http://def.com [R=301,L]


问:
Yii2 sending emails in the background
I have a RESTful API which registers a user and later sends an email to that user for account activation.
This works just fine but there is a great delay, since my code has to send the account activation email which sometimes takes time. How can I schedule jobs to run later or in the background for that task?

This is what I am doing currently:

```<code>actionCreateUser(){

   //HERE REGISTRATION

  if($model->save()){  //successifull registration

    //send email here which takes time
    if($emailsent){
      return ["data"=>true];
     }else{
        return ["data"=>false];
     }
   }

}
</code>```

Then in the front-end I am checking the response of the POST request which is data(true or false).

How can I send the email in the background?

答:
I had the same problem not so long ago. The solution looks optimal for me.

You should install RabbitMQ message system. In Yii2 you can use webtoucher/yii2-amqp extension.

Define you own message component. Well, you can also redefine mailer component. Your component must send message to our RabbitMQ worker. In your web-application you have to use it instead of normal mailer.

use Yii;
use yii\base\Component;
use yii\base\InvalidConfigException;
use yii\base\ErrorException;
use PhpAmqpLib\Message\AMQPMessage;

use webtoucher\amqp\components\Amqp;

class MessengerComponent extends Component
{

    protected $_recipient;
    protected $_subject;
    protected $_message_view;
    protected $_params;
    protected $_to;

    public function send()
    {

        $msg = [
            'to' => $this->_to,
            'message_view' => $this->_message_view,
            'subject' => $this->_subject,
            'params' => $this->_params,
        ];

        try {
            if(! YII_ENV_TEST)
                Yii::$app->amqp->send('send-message', 'send_message', $msg, Amqp::TYPE_DIRECT);
            return true;
        } catch(\Exception $e) {
            return false;
        }
    }
}
```

<ol start="3">
<li><p>Set up your RabbitMQ worker in your console application of Yii2. Note, that worker is a permanent process but not a request-like. So, you cannot declare mailer component and use it. You have to create mailer object only for a short time. For example, only for one mail. You can do this like that:</p>

<pre class="lang-php prettyprint-override"><code>$mailer = Yii::createObject([
    'class' => 'yii\swiftmailer\Mailer',
    'viewPath' => '@common/mail',
    'transport' => [
        'class' => 'Swift_SmtpTransport',
        'host' => 'mail.host.domain',
        'username' => 'mail username',
        'password' => 'mail passwork',
        'port' => '465',
        'encryption' => 'SSL',
    ],
]);

$mailer
    ->compose(
        ['html' => $html, 'text' => $text],
        $this->params
    )
    ->setFrom([Yii::$app->params['systemEmail'] => Yii::t('app', '{service} email title', [ 'service' => Yii::$app->name]
    ->setTo($this->email)
    ->setSubject($this->subject)
    ->send();
</code>```

Title: Yii2 sending emails in the background

Body:
I have a RESTful API which registers a user and later sends an email to that user for account activation.
This works just fine but there is a great delay, since my code has to send the account activation email which sometimes takes time. How can I schedule jobs to run later or in the background for that task?

This is what I am doing currently:

actionCreateUser(){

   //HERE REGISTRATION

  if($model->save()){  //successifull registration

    //send email here which takes time
    if($emailsent){
      return ["data"=>true];
     }else{
        return ["data"=>false];
     }
   }

}

Then in the front-end I am checking the response of the POST request which is data(true or false).

How can I send the email in the background?

Body:
I had the same problem not so long ago. The solution looks optimal for me.

You should install RabbitMQ message system. In Yii2 you can use webtoucher/yii2-amqp extension.

Define you own message component. Well, you can also redefine mailer component. Your component must send message to our RabbitMQ worker. In your web-application you have to use it instead of normal mailer.

use Yii;
use yii\base\Component;
use yii\base\InvalidConfigException;
use yii\base\ErrorException;
use PhpAmqpLib\Message\AMQPMessage;

use webtoucher\amqp\components\Amqp;

class MessengerComponent extends Component
{

    protected $_recipient;
    protected $_subject;
    protected $_message_view;
    protected $_params;
    protected $_to;

    public function send()
    {

        $msg = [
            'to' => $this->_to,
            'message_view' => $this->_message_view,
            'subject' => $this->_subject,
            'params' => $this->_params,
        ];

        try {
            if(! YII_ENV_TEST)
                Yii::$app->amqp->send('send-message', 'send_message', $msg, Amqp::TYPE_DIRECT);
            return true;
        } catch(\Exception $e) {
            return false;
        }
    }
}

Set up your RabbitMQ worker in your console application of Yii2. Note, that worker is a permanent process but not a request-like. So, you cannot declare mailer component and use it. You have to create mailer object only for a short time. For example, only for one mail. You can do this like that:

$mailer = Yii::createObject([
    'class' => 'yii\swiftmailer\Mailer',
    'viewPath' => '@common/mail',
    'transport' => [
        'class' => 'Swift_SmtpTransport',
        'host' => 'mail.host.domain',
        'username' => 'mail username',
        'password' => 'mail passwork',
        'port' => '465',
        'encryption' => 'SSL',
    ],
]);

$mailer
    ->compose(
        ['html' => $html, 'text' => $text],
        $this->params
    )
    ->setFrom([Yii::$app->params['systemEmail'] => Yii::t('app', '{service} email title', [ 'service' => Yii::$app->name]
    ->setTo($this->email)
    ->setSubject($this->subject)
    ->send();


问:
Errors with my python code
My python cod keeps giving me errors like indention and syntax which I keep fixing them but to no avail. So here is the code I'm using I'm still not sure what I'm doing wrong here (BTW this is just due to an argument with a friend about what I can't do)</p>

```<code>import requests
import subprocess
import json
import sys
import threading
import time
from Queue import Queue

numberOfViewers = int(sys.argv[1])
builderThreads = int(sys.argv[2])
startTime = time.time()
numberOfSockets = 0
concurrent = 25
urls = []
urlsUsed = []

def getURL(): # Get tokens
  output = subprocess.Popen(["livestreamer", "twitch.tv/CHANNEL_NAME", "-j"], stdout=subprocess.PIPE).communicate()[0]
        return json.loads(output)['streams']['worst']['url'] # Parse json and return the URL parameter

def build(): # Builds a set of tokens, aka viewers
        global numberOfSockets
        global numberOfViewers
        while True:
                if numberOfSockets < numberOfViewers:
                        numberOfSockets += 1
                        print "Building viewers " + str(numberOfSockets) + "/" + str(numberOfViewers)
                        urls.append(getURL())

def view(): # Opens connections to send views
        global numberOfSockets
        while True:
                url=q.get()
                requests.head(url)
                if (url in urlsUsed):
                        urls.remove(url)
                        urlsUsed.remove(url)
                        numberOfSockets -= 1
                else:
                        urlsUsed.append(url)
                q.task_done()

if __name__ == '__main__':
        for i in range(0, builderThreads):
                threading.Thread(target = build).start()

        while True:
                while (numberOfViewers != numberOfSockets): # Wait until sockets are built
                        time.sleep(1)

                q=Queue(concurrent*2)
                for i in range(concurrent):
                        try:
                                t=threading.Thread(target=view)
                                t.daemon=True
                                t.start()
                        except:
                                print 'thread error'
                try:
                        for url in urls:
                                print url
                                q.put(url.strip())
                                q.join()
                except KeyboardInterrupt:
                        sys.exit(1)
</code>```

答:
You need to indent your code. Python doesn't like it when you do this for example:

```<code>def main():
print "Hello World!"
</code>```

Python wants indents (I think it's 4 spaces)

```<code>def main():
    print "Hello World!"
</code>```

What line number is it where you have syntax and indent errors? by the way?

Title: Errors with my python code

Body:
My python cod keeps giving me errors like indention and syntax which I keep fixing them but to no avail. So here is the code I'm using I'm still not sure what I'm doing wrong here (BTW this is just due to an argument with a friend about what I can't do)

import requests
import subprocess
import json
import sys
import threading
import time
from Queue import Queue

numberOfViewers = int(sys.argv[1])
builderThreads = int(sys.argv[2])
startTime = time.time()
numberOfSockets = 0
concurrent = 25
urls = []
urlsUsed = []

def getURL(): # Get tokens
  output = subprocess.Popen(["livestreamer", "twitch.tv/CHANNEL_NAME", "-j"], stdout=subprocess.PIPE).communicate()[0]
        return json.loads(output)['streams']['worst']['url'] # Parse json and return the URL parameter

def build(): # Builds a set of tokens, aka viewers
        global numberOfSockets
        global numberOfViewers
        while True:
                if numberOfSockets < numberOfViewers:
                        numberOfSockets += 1
                        print "Building viewers " + str(numberOfSockets) + "/" + str(numberOfViewers)
                        urls.append(getURL())

def view(): # Opens connections to send views
        global numberOfSockets
        while True:
                url=q.get()
                requests.head(url)
                if (url in urlsUsed):
                        urls.remove(url)
                        urlsUsed.remove(url)
                        numberOfSockets -= 1
                else:
                        urlsUsed.append(url)
                q.task_done()

if __name__ == '__main__':
        for i in range(0, builderThreads):
                threading.Thread(target = build).start()

        while True:
                while (numberOfViewers != numberOfSockets): # Wait until sockets are built
                        time.sleep(1)

                q=Queue(concurrent*2)
                for i in range(concurrent):
                        try:
                                t=threading.Thread(target=view)
                                t.daemon=True
                                t.start()
                        except:
                                print 'thread error'
                try:
                        for url in urls:
                                print url
                                q.put(url.strip())
                                q.join()
                except KeyboardInterrupt:
                        sys.exit(1)

Body:
You need to indent your code. Python doesn't like it when you do this for example:

def main():
print "Hello World!"

Python wants indents (I think it's 4 spaces)

def main():
    print "Hello World!"

What line number is it where you have syntax and indent errors? by the way?


问:
Is there a way to ignore backspace key in java?
Whenever I press backspace in the text box this code is triggered.

```<code>private void txtAgeKeyTyped(java.awt.event.KeyEvent evt) {
        char agetext= evt.getKeyChar();
        if(!(Character.isDigit(agetext))){
            evt.consume();
            JOptionPane.showMessageDialog(null,"Age is only written in Numbers!");
        }
}
</code>```

It should only be triggered if I typed Alphabets instead of Numbers only.

For some reason it is triggering whenever I press the Backspace Key.

Is there a way for me to use backspace without triggering this block of code?

I'm sorry this is the first time i fiddled with Key Events

答:
The backspace character is just \b. As you can see, the VK_BACK_SPACE constant is defined like this:

```<code>public static final int VK_BACK_SPACE     = '\b';
</code>```

The constant is defined in the java.awt.event.KeyEvent class btw. If you use IntelliJ it will automatically and statically import it for you.

You can check whether agetext is \b. If it is, return from the method:

```<code>private void txtAgeKeyTyped(java.awt.event.KeyEvent evt) {
    char agetext= evt.getKeyChar();
    if (agetext == VK_BACK_SPACE) return;
    if(!(Character.isDigit(agetext))){
        evt.consume();
        JOptionPane.showMessageDialog(null,"Age is only written in Numbers!");
    }
}
</code>```

Body:
Whenever I press backspace in the text box this code is triggered.

private void txtAgeKeyTyped(java.awt.event.KeyEvent evt) {
        char agetext= evt.getKeyChar();
        if(!(Character.isDigit(agetext))){
            evt.consume();
            JOptionPane.showMessageDialog(null,"Age is only written in Numbers!");
        }
}

It should only be triggered if I typed Alphabets instead of Numbers only.

For some reason it is triggering whenever I press the Backspace Key.

Is there a way for me to use backspace without triggering this block of code?

I'm sorry this is the first time i fiddled with Key Events

Body:
The backspace character is just \b. As you can see, the VK_BACK_SPACE constant is defined like this:

public static final int VK_BACK_SPACE     = '\b';

The constant is defined in the java.awt.event.KeyEvent class btw. If you use IntelliJ it will automatically and statically import it for you.

You can check whether agetext is \b. If it is, return from the method:

private void txtAgeKeyTyped(java.awt.event.KeyEvent evt) {
    char agetext= evt.getKeyChar();
    if (agetext == VK_BACK_SPACE) return;
    if(!(Character.isDigit(agetext))){
        evt.consume();
        JOptionPane.showMessageDialog(null,"Age is only written in Numbers!");
    }
}


问:
Check if Model is empty
I am doing below query to fetch data to view however if AccountMediaServerKey table is empty. Model is throwing null exception error in view. Any idea how to check if model is null when NO data fetched from database

```<code>var MediaKey = (from p in db.AccountMediaServerKey
                where p.Tagger == USID && p.TagTo == USID
                select new MediaServerHomeModel
                {
                    Stream=p.Stream,
                    Event = p.Event,
                    Status = p.Status

                }).FirstOrDefault();
</code>```

答:
The method FirstOrDefault returns the first item in the collection or NULL. So if your table is empty, the variable MediaKey will have NULL value. If you are passing that to the view, make sure you do a null check before accessing any properties.

```<code>@model MediaServerHomeModel
<h1>Index</h1>
@if(Model!=null)
{
  <p>Model is not null</p>
  <!-- Access Model safely now -->
}
</code>```

You have to do the same thing for other reference type properties to prevent null reference exception. For example if Stream property is a reference type, It is possible that it could be null. So it is safe to do a null check before using that as well.

```<code>@if(Model!=null && Model.Stream!=null)
{
  <p>Model.Stream is not null</p>
  <!-- Access Model.Stream safely now -->
}
</code>```

Title: Check if Model is empty

Body:
I am doing below query to fetch data to view however if AccountMediaServerKey table is empty. Model is throwing null exception error in view. Any idea how to check if model is null when NO data fetched from database

var MediaKey = (from p in db.AccountMediaServerKey
                where p.Tagger == USID && p.TagTo == USID
                select new MediaServerHomeModel
                {
                    Stream=p.Stream,
                    Event = p.Event,
                    Status = p.Status

                }).FirstOrDefault();

Body:
The method FirstOrDefault returns the first item in the collection or NULL. So if your table is empty, the variable MediaKey will have NULL value. If you are passing that to the view, make sure you do a null check before accessing any properties.

@model MediaServerHomeModel
<h1>Index</h1>
@if(Model!=null)
{
  <p>Model is not null</p>
  <!-- Access Model safely now -->
}

You have to do the same thing for other reference type properties to prevent null reference exception. For example if Stream property is a reference type, It is possible that it could be null. So it is safe to do a null check before using that as well.

@if(Model!=null && Model.Stream!=null)
{
  <p>Model.Stream is not null</p>
  <!-- Access Model.Stream safely now -->
}


问:
Find duplicate elements in 2d array
Suppose I have a 3*3 array(2D array):

1 2 4

1 5 7

2 4 8

So 1,2 and 4 appear more than once. The result I want to get is 3.
How can I do that?

答:
Here is the solution to find count of duplicate elements in a 2D matrix without using collection
public class DuplicateElementsCountIn2DMetrixWithoutUsingCollections{

```<code>public static void main(String args[]){
    String[][] matrix = {{"1","2","1","3",},{"7","6","null","2",},{"5","6","3","null",},{"3","10","9","5",}};
    System.out.println(findDuplicate(matrix));
}

public static int findDuplicate(String[][] matrix){
    String strArr[] = new String[(matrix.length)*(matrix[0].length)];
    int count = 0;
    for(int i = 0; i < matrix.length; i++){
        for(int j = 0; j < matrix[0].length; j++){
            for(int k = 0; k < matrix.length; k++){
                for(int l = 0; l < matrix[0].length; l++){
                    if((i!=k || j!=l)){
                        if(matrix[i][j] == matrix[k][l]){
                            int x = 0;
                            boolean flag = false;
                            while(strArr[x] != null){
                                if(null != matrix[i][j] && matrix[i][j].equals(strArr[x])){
                                    flag = true;
                                }
                                x++;
                            }
                            if(flag==false){
                                strArr[count] = matrix[i][j];
                                count++;
                            }
                        }
                    }
                }
            }
        }
    }
    return count;
}
</code>```

}

Output

6

Note : 1, 2, 3, 6, null are duplicate in matrix, hence count is 6

Title: Find duplicate elements in 2d array

Body:
Here is the solution to find count of duplicate elements in a 2D matrix without using collection
public class DuplicateElementsCountIn2DMetrixWithoutUsingCollections{

public static void main(String args[]){
    String[][] matrix = {{"1","2","1","3",},{"7","6","null","2",},{"5","6","3","null",},{"3","10","9","5",}};
    System.out.println(findDuplicate(matrix));
}

public static int findDuplicate(String[][] matrix){
    String strArr[] = new String[(matrix.length)*(matrix[0].length)];
    int count = 0;
    for(int i = 0; i < matrix.length; i++){
        for(int j = 0; j < matrix[0].length; j++){
            for(int k = 0; k < matrix.length; k++){
                for(int l = 0; l < matrix[0].length; l++){
                    if((i!=k || j!=l)){
                        if(matrix[i][j] == matrix[k][l]){
                            int x = 0;
                            boolean flag = false;
                            while(strArr[x] != null){
                                if(null != matrix[i][j] && matrix[i][j].equals(strArr[x])){
                                    flag = true;
                                }
                                x++;
                            }
                            if(flag==false){
                                strArr[count] = matrix[i][j];
                                count++;
                            }
                        }
                    }
                }
            }
        }
    }
    return count;
}

}

Output

6

Note : 1, 2, 3, 6, null are duplicate in matrix, hence count is 6


问:
How to unfreeze an object in Ruby?
In Ruby, there is Object#freeze, which prevents further modifications to the object:

```<code>class Kingdom
  attr_accessor :weather_conditions
end

arendelle = Kingdom.new
arendelle.frozen? # => false
arendelle.weather_conditions = 'in deep, deep, deep, deep snow'
arendelle.freeze
arendelle.frozen? # => true
arendelle.weather_conditions = 'sun is shining'
  # !> RuntimeError: can't modify frozen Kingdom

script = 'Do you want to build a snowman?'.freeze
script[/snowman/] = 'castle of ice'
  # !> RuntimeError: can't modify frozen String
</code>```

However, there is no Object#unfreeze. Is there a way to unfreeze a frozen kingdom?

答:
As noted above copying the variable back into itself also effectively unfreezes the variable.

As noted this can be done using the .dup method:

var1 = var1.dup

This can also be achieved using:

var1 = Marshal.load(Marshal.dump(var1))

I have been using Marshal.load(Marshal.dump(  ... )

I have not used .dup and only learned about it through this post.

I do not know what if any differences there are between Marshal.load(Marshal.dump(  ... )

If they do the same thing or .dup is more powerful, then stylistically I like .dup better. .dup states what to do -- copy this thing, but it does not say how to do it, whereas Marshal.load(Marshal.dump(  ... ) is not only excessively verbose, but states how to do the duplication -- I am not a fan of specifying the HOW part if the HOW part is irrelevant to me. I want to duplicate the value of the variable, I do not care how.

Title: How to unfreeze an object in Ruby?

Body:
In Ruby, there is Object#freeze, which prevents further modifications to the object:

class Kingdom
  attr_accessor :weather_conditions
end

arendelle = Kingdom.new
arendelle.frozen? # => false
arendelle.weather_conditions = 'in deep, deep, deep, deep snow'
arendelle.freeze
arendelle.frozen? # => true
arendelle.weather_conditions = 'sun is shining'
  # !> RuntimeError: can't modify frozen Kingdom

script = 'Do you want to build a snowman?'.freeze
script[/snowman/] = 'castle of ice'
  # !> RuntimeError: can't modify frozen String

However, there is no Object#unfreeze. Is there a way to unfreeze a frozen kingdom?


问:
Mass removal of content and properties from divs
I've got a huge grid of divs that randomly generates content and background images and I want to create a function that will generate it again randomly, but before that it will obviously clear all text content and background images.

I tried doing it with:

```<code>document.getElementsByClassName("isq").innerHTML = null;
</code>```

Also tried with textContent = "", nothing helped. I was also unable to use

```<code>document.getElementsByClassName("isq").style.backgroundImage = "none";
</code>```

What am I doing wrong? Here is my html(just 1/4 of it, but it's basically the same:

```<code>    <div class="row r1">
    <div class="square o1">
        <div class="isq i1"></div>
        <div class="isq i2"></div>
        <div class="isq i3"></div>
        <div class="isq i4"></div>
        <div class="isq i5"></div>
        <div class="isq i6"></div>
        <div class="isq i7"></div>
        <div class="isq i8"></div>
        <div class="isq i9"></div>
    </div>
    <div class="square o2">
        <div class="isq i1"></div>
        <div class="isq i2"></div>
        <div class="isq i3"></div>
        <div class="isq i4"></div>
        <div class="isq i5"></div>
        <div class="isq i6"></div>
        <div class="isq i7"></div>
        <div class="isq i8"></div>
        <div class="isq i9"></div>
    </div>
    <div class="square o3">
        <div class="isq i1"></div>
        <div class="isq i2"></div>
        <div class="isq i3"></div>
        <div class="isq i4"></div>
        <div class="isq i5"></div>
        <div class="isq i6"></div>
        <div class="isq i7"></div>
        <div class="isq i8"></div>
        <div class="isq i9"></div>
    </div>
</div>
</code>```

If it's somehow crucial for me to show how I generated the content and background for the divs let me know and I will simpilfy the JS code to show it but I dont think its necessary

答:
Try this:

```<code>document.getElementByID(elementId).innerHTML = "";
</code>```

For a class:

```<code>document.getElementsByClassName("someClass").innerHTML = "";
</code>```

Body:
I've got a huge grid of divs that randomly generates content and background images and I want to create a function that will generate it again randomly, but before that it will obviously clear all text content and background images.

I tried doing it with:

document.getElementsByClassName("isq").innerHTML = null;

Also tried with textContent = "", nothing helped. I was also unable to use

document.getElementsByClassName("isq").style.backgroundImage = "none";

What am I doing wrong? Here is my html(just 1/4 of it, but it's basically the same:

If it's somehow crucial for me to show how I generated the content and background for the divs let me know and I will simpilfy the JS code to show it but I dont think its necessary

Body:
Try this:

document.getElementByID(elementId).innerHTML = "";

For a class:

document.getElementsByClassName("someClass").innerHTML = "";


问:
Array property in Javascript object is undefined
I'm using Node.js to loop through an array of Artist results I obtain from Mongoose:

```<code>User.find({UserType: "Artist"}, '_id Firstname BIO list_artworks').then((artists) =>{
    for (var i=0; i < artists.length; i++){
        console.log(artists[i]);
    }
})
</code>```

The above code works find and prints out all three properties of Artists that I asked for.

EDIT: Here's an example of what I see in console:

```<code>{
    _id: 'T8fdSmf0e1ua',
    BIO: 'This is Susan's bio...\n',
    Firstname: 'Susan',
    list_artworks: [
        'ID ONE',
        'ID TWO',
        ...
    ]
}
</code>```

However, when I try to access a property that is an array of Artwork ids, everything is undefined using console.log():

```<code>for (var i=0; i < artists.length; i++){
    console.log(artists[i].list_artworks);
}
</code>```

When I access the other properties of my Artist, like BIO or Firstname, it prints successfully to my console:

```<code>for (var i=0; i < artists.length; i++){
    console.log(artists[i].BIO);
}
</code>```

Why is this the case? I don't think it has to do with async code in this case given that all objects are return in the then() chain. The list_artworks property is clearly there if I print the entire artist object, but why is it undefined when I attempt to access it?

Here's another example. I print out each property, and then the object itself:

```<code>console.log(artist.BIO);
console.log("---------------")
console.log(artist.Firstname);
console.log("---------------")
console.log(artist.list_artworks);
console.log("---------------")
console.log(artist)
</code>```

And here's what is printed on my console:

---------------
Mike
---------------
undefined // <--- when I access the property itself
---------------
{
  _id: '599asdsdasd232d23d2',
  Firstname: 'Mike',
  BIO: '',
  list_artworks: // <-- why does it show up here?
   [ '6cohpx7d23asu',
     'W4Fgs23X5aXds',...
```

<p>Here is my entire code base:</p>

```setTimeout(function(){

     User.find({UserType: "Artist"}, '_id Firstname BIO list_artworks').then((artists) =>{
         console.log(artists.length);

        for (var i=0; i < artists.length; i++){
            artist = artists[i];
             console.log(artist.BIO);
             console.log("---------------")
             console.log(artist.Firstname);
             console.log("---------------")
            console.log(artist['list_artworks']);
             console.log("---------------")
             console.log(artist)
            }
        }

     ).catch((err)=>{console.log(err)});
}, constants.NLP_TRAINING_INTERVAL);
```

答:
Call toObject on the artist:

```<code>artist = artists[i].toObject();
</code>```

Body:
I'm using Node.js to loop through an array of Artist results I obtain from Mongoose:

User.find({UserType: "Artist"}, '_id Firstname BIO list_artworks').then((artists) =>{
    for (var i=0; i < artists.length; i++){
        console.log(artists[i]);
    }
})

The above code works find and prints out all three properties of Artists that I asked for.

EDIT: Here's an example of what I see in console:

{
    _id: 'T8fdSmf0e1ua',
    BIO: 'This is Susan's bio...\n',
    Firstname: 'Susan',
    list_artworks: [
        'ID ONE',
        'ID TWO',
        ...
    ]
}

However, when I try to access a property that is an array of Artwork ids, everything is undefined using console.log():

for (var i=0; i < artists.length; i++){
    console.log(artists[i].list_artworks);
}

When I access the other properties of my Artist, like BIO or Firstname, it prints successfully to my console:

for (var i=0; i < artists.length; i++){
    console.log(artists[i].BIO);
}

Why is this the case? I don't think it has to do with async code in this case given that all objects are return in the then() chain. The list_artworks property is clearly there if I print the entire artist object, but why is it undefined when I attempt to access it?

Here's another example. I print out each property, and then the object itself:

console.log(artist.BIO);
console.log("---------------")
console.log(artist.Firstname);
console.log("---------------")
console.log(artist.list_artworks);
console.log("---------------")
console.log(artist)

And here's what is printed on my console:

---------------
Mike
---------------
undefined // <--- when I access the property itself
---------------
{
  _id: '599asdsdasd232d23d2',
  Firstname: 'Mike',
  BIO: '',
  list_artworks: // <-- why does it show up here?
   [ '6cohpx7d23asu',
     'W4Fgs23X5aXds',...

Here is my entire code base:

setTimeout(function(){

     User.find({UserType: "Artist"}, '_id Firstname BIO list_artworks').then((artists) =>{
         console.log(artists.length);

        for (var i=0; i < artists.length; i++){
            artist = artists[i];
             console.log(artist.BIO);
             console.log("---------------")
             console.log(artist.Firstname);
             console.log("---------------")
            console.log(artist['list_artworks']);
             console.log("---------------")
             console.log(artist)
            }
        }

     ).catch((err)=>{console.log(err)});
}, constants.NLP_TRAINING_INTERVAL);

Body:
Call toObject on the artist:

artist = artists[i].toObject();


问:
React Navigation: Applying separate transitions to scenes
I want to apply different transitions to scenes in my StackNavigator in React Navigation, for my React Native (iOS) app.

```<code>export const AppNavigator = StackNavigator({
  Home: { screen: Home },
  NewChild: { screen: NewChild },
  Journal: { screen: Journal }
});
</code>```

I might want NewChild to load from the bottom up, like a modal. Or I might want it to slide in from right to left. It would great if this could be customised. From the documentation, it seems you can only set your StackNavigation to either card or modal for the whole thing.

答:
As you already saw in the docs, it's not possible right now. You can track this issue and this issue requesting this feature. It's on the roadmap for v2, but since v1 isn't even released yet, your best bet is probably to either:

Implement your own transitionConfig that somehow handles this per screen. I'm not sure if this is possible.

Fork an implement something using the ideas from the main issue. Or simple make your fork specific to your code and maintain it until that issue is resolved.

Body:
I want to apply different transitions to scenes in my StackNavigator in React Navigation, for my React Native (iOS) app.

export const AppNavigator = StackNavigator({
  Home: { screen: Home },
  NewChild: { screen: NewChild },
  Journal: { screen: Journal }
});

I might want NewChild to load from the bottom up, like a modal. Or I might want it to slide in from right to left. It would great if this could be customised. From the documentation, it seems you can only set your StackNavigation to either card or modal for the whole thing.


问:
How do I put extra number at the end of username if duplicate
Hard to explain, and let me show an example.

If username foo already exists in MySQL I want php script will allow it but to be foo1

Then if foo1 exists too, script will generate the username will be foo2

If foo2 existed then become foo3

How to make like that?

Like Col. Shrapnel said Natural increment which seems more sensible. just like "New Folder(3)" stuff in Windows

答:
First, lock the table so no other table will write to it at the same time. then do something like this:

```<code>$name = 'foo';
$first_name = $name;
$i = 0;
do {
  //Check in the database here
  $exists = exists_in_database($name);
  if($exists) {
    $i++;
    $name = $first_name . $i;
  }
}while($exists);
//save $name
</code>```

Another method is to select all names in the table starting with "foo" and ending in a number and then finding the largest number. This can be done in SQL.

The first method is better for use cases with only a small risk of collision, since the pattern matching may be slow, but if you have a lot of collisions the latter may be better.

Body:
First, lock the table so no other table will write to it at the same time. then do something like this:

$name = 'foo';
$first_name = $name;
$i = 0;
do {
  //Check in the database here
  $exists = exists_in_database($name);
  if($exists) {
    $i++;
    $name = $first_name . $i;
  }
}while($exists);
//save $name

Another method is to select all names in the table starting with "foo" and ending in a number and then finding the largest number. This can be done in SQL.

The first method is better for use cases with only a small risk of collision, since the pattern matching may be slow, but if you have a lot of collisions the latter may be better.


问:
My own Validation Methods( CodeIgniter ) always returns an error even when i think it shouldn't
Could someone please take a look at my code and tell me what am doing wrong!

here is my view file ( html form )

```<code><?php $attrib = array('class'=>'form-horizontal col-lg-6')?>

                  <?php
                        if( isset( $_POST['save'] ) )
                        {
                            echo validation_errors('<div class="alert alert-danger">', '</div>');
                        }
                  ?>
                  <?=form_open('basic_info/edit_basic', $attrib )?>

                    <div class="form-group">
                      <div class="input-group">
                        <div class="input-group-addon" id="label">First Name</div>
                        <input type="text" name="fname" class="form-control" value="<?=$fname?>">
                      </div>
                    </div>

                    <div class="form-group">
                      <div class="input-group">
                        <div class="input-group-addon" id="label">Middle Name</div>
                        <input type="text" name="mname" class="form-control" value="<?=$mname?>">
                      </div>
                    </div>

                    <div class="form-group">
                        <div class="input-group">
                          <div class="input-group-addon" id="label">Last Name</div>
                          <input type="text" name="lname" class="form-control" value="<?=$lname?>">
                        </div>
                    </div>

                    <div class="form-group">
                        <div class="input-group">
                          <div class="input-group-addon"id="label">Date of birth</div>
                          <input type="text" name="dob" class="form-control" value="<?=$dob?>">
                        </div>
                    </div>

                    <div class="form-group">
                        <div class="input-group">
                          <div class="input-group-addon" id="label">Gender</div>
                          <select name="gender" class="form-control">
                              <?php if( $gender == true ){ ?>
                                <option class="form-control" value="male" selected="selected">Male</option>
                                <option class="form-control" valu="female">Female</option>
                              <?php }else{ ?>
                                <option class="form-control" valu="female" selected="selected">Female</option>
                                <option class="form-control" value="male">Male</option>
                              <?php } ?>
                          </select>
                        </div>
                    </div>

                    <div class="form-group">
                        <div class="">
                          <button type="submit" name="save" class="btn btn-primary">Save</button>
                        </div>
                      </div>
                  <?=form_close()?>
</code>```

here is my controller ( form validation ) file-> /basic_info/edit_basic

```<code>defined('BASEPATH') OR exit('No direct script access allowed');
class Basic_info extends MX_Controller {

public function index()
{
    if( $this->session->userdata('is_logged') )
    {
        $this->load->model('basic_info/edit_account');

        $data = $this->edit_account->get_account_info();

        $data->dob = date("d-m-Y", strtotime($data->dob));

        $this->load->view('basic_info', $data);

    }else{
        redirect( 'welcome' );
    }
}

public function edit_basic()
{
    $config = array(
        array(
            'field'=>'fname',
            'label'=>'First name',
            'rules'=>'alpha|min_length[2]|max_length[150]',
            'errors'=>array(
                'alpha'=>'Sorry a name can only have alphabets',
                'min_length'=>'Sorry a name can\'t be this short',
                'max_length'=>'Sorry a name can\'t be this logng'
            ),
        ),

        array(
            'field'=>'mname',
            'label'=>'Middle name',
            'rules'=>'alpha|min_length[2]|max_length[150]',
            'errors'=>array(
                'alpha'=>'Sorry a name can only have alphabets',
                'min_length'=>'Sorry a name can\'t be this short',
                'max_length'=>'Sorry a name can\'t be this logng'
            ),
        ),

        array(
            'field'=>'lname',
            'label'=>'Last name',
            'rules'=>'alpha|min_length[2]|max_length[150]',
            'errors'=>array(
                'alpha'=>'Sorry a name can only have alphabets',
                'min_length'=>'Sorry a name can\'t be this short',
                'max_length'=>'Sorry a name can\'t be this logng'
            ),
        ),

        array(
            'field'=>'dob',
            'label'=>'Date of birth',
            'rules'=>'exact_length[10]|callback_date_valid',
            'errors'=>array(
                'exact_length'=>'Sorry! invalid length for a date',
                'date_valid'=>'Sorry! invalid date format',
            ),
        ),

        array(
            'field'=>'gender',
            'label'=>'Gender',
            'rules'=>'alpha|max_length[6]|min_length[4]',
            'errors'=>array(
                'alpha'=>'Sorry! Invalid gener',
            ),
        ),
    );

    $this->form_validation->set_rules( $config );

    if( $this->form_validation->run() == FALSE )
    {
        $this->load->model('basic_info/edit_account');

        $data = $this->edit_account->get_account_info();

        $this->load->view('basic_info', $data);

    }else{

        $this->load->model('basic_info/edit_account');
        $this->edit_account->edit_basic();

        $this->load->model('basic_info/edit_account');

        $data = $this->edit_account->get_account_info();

        $this->load->view('basic_info', $data);
    }
}

public function date_valid()
{
    $date = $this->input->post( 'dob' );

    if( strpos( $date, '/') != FALSE  )
    {
       list( $day, $month, $year ) = explode("/",$date);

       if( $this->tarehe( $day, $month, $year ) )
       {
           return true;
       }else{
           return false;
       }

    }elseif( strpos( $date, '-') != FALSE ){

        list( $day, $month, $year ) = explode("-",$date);

        if( $this->tarehe( $day, $month, $year ) )
        {
            return true;
        }else{
            return false;
        }
    }
    elseif( strpos( $date, '.') != FALSE )
    {

        list( $day, $month, $year ) = explode(".",$date);

        if( $this->tarehe( $day, $month, $year ) )
        {
            return true;
        }else{
            return false;
        }
    }else{
        return false;
    }
}

public function tarehe( $day, $month, $year )
{
    $first = $day[0];
    $second = $day[1];

    if( $first < 0 ){
        $day = $second;
    }

    if( $day > 0 && $day <= 31 )
    {

        $first = $month[0];
        $second = $month[1];

        if( $first < 0 ){
            $month = $second;
        }
        if( $month > 0 && $month <= 12  )
        {
            $limit_down = date('Y') - 17;
            $limit_up = date('Y') - 50;

            if( $year < $limit_down && $year > $limit_up )
            {
                return true;
            }else{
                return false;
            }
        }else{
           return false;
        }
    }else{
        return false;
    }
}
</code>```

}

I tried so many variations of dates but it always gives the error i'm frustrated already i don't see the problem with that field ( dob ), please help!

答:
Taking the code you have provided and having a play with it. I got the following...

I have made some slight modifications. Spot the differences!

The View - test_form.php

```<code><?php $attrib = array('class' => 'form-horizontal col-lg-6') ?>

<?php
if (isset($_POST['save'])) {
    echo validation_errors('<div class="alert alert-danger">', '</div>');
}
?>
<?= form_open('welcome/form', $attrib); ?>
    <div class="form-group">
        <div class="input-group">
            <div class="input-group-addon" id="label">Date of birth</div>
            <input type="text" name="dob" class="form-control" value="<?= isset($dob)?$dob:'' ?>">
        </div>
    </div>

    <div class="form-group">
        <div class="">
            <button type="submit" name="save" class="btn btn-primary">Save</button>
        </div>
    </div>
<?= form_close(); ?>
</code>```

The Controller - welcome.php

```<code><?php
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * Class Welcome
 *
 *
 * @property CI_Form_validation form_validation
 * @property CI_Input           input
 */
class Welcome extends CI_Controller {

    public function __construct() {
        parent::__construct();
        $this->load->helper('form');
        $this->load->library('form_validation');
    }

    public function test() {
        $date = '2017/12/01';
        echo $date;
        echo '<br>';
        var_dump($this->date_valid($date)); // returns false

        $date = '01/03/1970';
        echo $date;
        echo '<br>';
        var_dump($this->date_valid($date)); // returns true

        $date = '01-03-1970';
        echo $date;
        echo '<br>';
        var_dump($this->date_valid($date)); // returns true

    }

    public function form() {
        $config = array(
            array(
                'field'  => 'dob',
                'label'  => 'Date of birth',
                'rules'  => 'exact_length[10]|callback_date_valid',
                'errors' => array(
                    'exact_length' => 'Sorry! invalid length for a date',
                    'date_valid'   => 'Sorry! invalid date format',
                )
            )
        );

        $this->form_validation->set_rules($config);
        if ($this->input->post('save') !== NULL) {
            if ($this->form_validation->run() == TRUE) {
                echo "Updating the Database";
            }
        }

        $this->load->view('test_form');
    }

    public function date_valid($date) {
        if (strpos($date, '/') != FALSE) {
            list($day, $month, $year) = explode("/", $date);
            if ($this->tarehe($day, $month, $year)) {
                return TRUE;
            } else {
                return FALSE;
            }

        } elseif (strpos($date, '-') != FALSE) {
            list($day, $month, $year) = explode("-", $date);
            if ($this->tarehe($day, $month, $year)) {
                return TRUE;
            } else {
                return FALSE;
            }
        } elseif (strpos($date, '.') != FALSE) {

            list($day, $month, $year) = explode(".", $date);

            if ($this->tarehe($day, $month, $year)) {
                return TRUE;
            } else {
                return FALSE;
            }
        } else {
            return FALSE;
        }
    }

    public function tarehe($day, $month, $year) {

        $first = $day[0];
        $second = $day[1];

        if ($first < 0) {
            $day = $second;
        }

        if ($day > 0 && $day <= 31) {
            $first = $month[0];
            $second = $month[1];

            if ($first < 0) {
                $month = $second;
            }

            if ($month > 0 && $month <= 12) {
                $limit_down = date('Y') - 17;
                $limit_up = date('Y') - 50;
                if ($year < $limit_down && $year > $limit_up) {

                    return TRUE;
                } else {

                    return FALSE;
                }
            } else {

                return FALSE;
            }
        } else {

            return FALSE;
        }
    }
}
</code>```

So I have added your code to my welcome.php controller.

Created a test method to test your date formats /welcome/test to test your callback code and the tarehe method... to test the formats and values...

I have the form method to test your form for dob with the callback.

welcome/form

You seriously need to look at the code in your $this->form_validation_>run() section of your controller... Why the same code for both the True and False conditions and what does that code do?

Is that your real problem?

Body:
Could someone please take a look at my code and tell me what am doing wrong!

here is my view file ( html form )

<?php $attrib = array('class'=>'form-horizontal col-lg-6')?>

                  <?php
                        if( isset( $_POST['save'] ) )
                        {
                            echo validation_errors('
', '
');
                        }
                  ?>
                  <?=form_open('basic_info/edit_basic', $attrib )?>

First Name

                        <input type="text" name="fname" class="form-control" value="<?=$fname?>">

Middle Name

                        <input type="text" name="mname" class="form-control" value="<?=$mname?>">

Last Name

                          <input type="text" name="lname" class="form-control" value="<?=$lname?>">

Date of birth

                          <input type="text" name="dob" class="form-control" value="<?=$dob?>">

Gender

                          <select name="gender" class="form-control">
                              <?php if( $gender == true ){ ?>
                                <option class="form-control" value="male" selected="selected">Male</option>
                                <option class="form-control" valu="female">Female</option>
                              <?php }else{ ?>
                                <option class="form-control" valu="female" selected="selected">Female</option>
                                <option class="form-control" value="male">Male</option>
                              <?php } ?>
                          </select>

                          <button type="submit" name="save" class="btn btn-primary">Save</button>

                  <?=form_close()?>

here is my controller ( form validation ) file-> /basic_info/edit_basic

defined('BASEPATH') OR exit('No direct script access allowed');
class Basic_info extends MX_Controller {

public function index()
{
    if( $this->session->userdata('is_logged') )
    {
        $this->load->model('basic_info/edit_account');

        $data = $this->edit_account->get_account_info();

        $data->dob = date("d-m-Y", strtotime($data->dob));

        $this->load->view('basic_info', $data);

    }else{
        redirect( 'welcome' );
    }
}

public function edit_basic()
{
    $config = array(
        array(
            'field'=>'fname',
            'label'=>'First name',
            'rules'=>'alpha|min_length[2]|max_length[150]',
            'errors'=>array(
                'alpha'=>'Sorry a name can only have alphabets',
                'min_length'=>'Sorry a name can\'t be this short',
                'max_length'=>'Sorry a name can\'t be this logng'
            ),
        ),

        array(
            'field'=>'mname',
            'label'=>'Middle name',
            'rules'=>'alpha|min_length[2]|max_length[150]',
            'errors'=>array(
                'alpha'=>'Sorry a name can only have alphabets',
                'min_length'=>'Sorry a name can\'t be this short',
                'max_length'=>'Sorry a name can\'t be this logng'
            ),
        ),

        array(
            'field'=>'lname',
            'label'=>'Last name',
            'rules'=>'alpha|min_length[2]|max_length[150]',
            'errors'=>array(
                'alpha'=>'Sorry a name can only have alphabets',
                'min_length'=>'Sorry a name can\'t be this short',
                'max_length'=>'Sorry a name can\'t be this logng'
            ),
        ),

        array(
            'field'=>'dob',
            'label'=>'Date of birth',
            'rules'=>'exact_length[10]|callback_date_valid',
            'errors'=>array(
                'exact_length'=>'Sorry! invalid length for a date',
                'date_valid'=>'Sorry! invalid date format',
            ),
        ),

        array(
            'field'=>'gender',
            'label'=>'Gender',
            'rules'=>'alpha|max_length[6]|min_length[4]',
            'errors'=>array(
                'alpha'=>'Sorry! Invalid gener',
            ),
        ),
    );

    $this->form_validation->set_rules( $config );

    if( $this->form_validation->run() == FALSE )
    {
        $this->load->model('basic_info/edit_account');

        $data = $this->edit_account->get_account_info();

        $this->load->view('basic_info', $data);

    }else{

        $this->load->model('basic_info/edit_account');
        $this->edit_account->edit_basic();

        $this->load->model('basic_info/edit_account');

        $data = $this->edit_account->get_account_info();

        $this->load->view('basic_info', $data);
    }
}

public function date_valid()
{
    $date = $this->input->post( 'dob' );

    if( strpos( $date, '/') != FALSE  )
    {
       list( $day, $month, $year ) = explode("/",$date);

       if( $this->tarehe( $day, $month, $year ) )
       {
           return true;
       }else{
           return false;
       }

    }elseif( strpos( $date, '-') != FALSE ){

        list( $day, $month, $year ) = explode("-",$date);

        if( $this->tarehe( $day, $month, $year ) )
        {
            return true;
        }else{
            return false;
        }
    }
    elseif( strpos( $date, '.') != FALSE )
    {

        list( $day, $month, $year ) = explode(".",$date);

        if( $this->tarehe( $day, $month, $year ) )
        {
            return true;
        }else{
            return false;
        }
    }else{
        return false;
    }
}

public function tarehe( $day, $month, $year )
{
    $first = $day[0];
    $second = $day[1];

    if( $first < 0 ){
        $day = $second;
    }

    if( $day > 0 && $day <= 31 )
    {

        $first = $month[0];
        $second = $month[1];

        if( $first < 0 ){
            $month = $second;
        }
        if( $month > 0 && $month <= 12  )
        {
            $limit_down = date('Y') - 17;
            $limit_up = date('Y') - 50;

            if( $year < $limit_down && $year > $limit_up )
            {
                return true;
            }else{
                return false;
            }
        }else{
           return false;
        }
    }else{
        return false;
    }
}

}

I tried so many variations of dates but it always gives the error i'm frustrated already i don't see the problem with that field ( dob ), please help!

Body:
Taking the code you have provided and having a play with it. I got the following...

I have made some slight modifications. Spot the differences!

The View - test_form.php

<?php $attrib = array('class' => 'form-horizontal col-lg-6') ?>

<?php
if (isset($_POST['save'])) {
    echo validation_errors('<div class="alert alert-danger">', '</div>');
}
?>
<?= form_open('welcome/form', $attrib); ?>
    <div class="form-group">
        <div class="input-group">
            <div class="input-group-addon" id="label">Date of birth</div>
            <input type="text" name="dob" class="form-control" value="<?= isset($dob)?$dob:'' ?>">
        </div>
    </div>

    <div class="form-group">
        <div class="">
            <button type="submit" name="save" class="btn btn-primary">Save</button>
        </div>
    </div>
<?= form_close(); ?>

The Controller - welcome.php

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * Class Welcome
 *
 *
 * @property CI_Form_validation form_validation
 * @property CI_Input           input
 */
class Welcome extends CI_Controller {

    public function __construct() {
        parent::__construct();
        $this->load->helper('form');
        $this->load->library('form_validation');
    }

    public function test() {
        $date = '2017/12/01';
        echo $date;
        echo '<br>';
        var_dump($this->date_valid($date)); // returns false

        $date = '01/03/1970';
        echo $date;
        echo '<br>';
        var_dump($this->date_valid($date)); // returns true

        $date = '01-03-1970';
        echo $date;
        echo '<br>';
        var_dump($this->date_valid($date)); // returns true

    }

    public function form() {
        $config = array(
            array(
                'field'  => 'dob',
                'label'  => 'Date of birth',
                'rules'  => 'exact_length[10]|callback_date_valid',
                'errors' => array(
                    'exact_length' => 'Sorry! invalid length for a date',
                    'date_valid'   => 'Sorry! invalid date format',
                )
            )
        );

        $this->form_validation->set_rules($config);
        if ($this->input->post('save') !== NULL) {
            if ($this->form_validation->run() == TRUE) {
                echo "Updating the Database";
            }
        }

        $this->load->view('test_form');
    }

    public function date_valid($date) {
        if (strpos($date, '/') != FALSE) {
            list($day, $month, $year) = explode("/", $date);
            if ($this->tarehe($day, $month, $year)) {
                return TRUE;
            } else {
                return FALSE;
            }

        } elseif (strpos($date, '-') != FALSE) {
            list($day, $month, $year) = explode("-", $date);
            if ($this->tarehe($day, $month, $year)) {
                return TRUE;
            } else {
                return FALSE;
            }
        } elseif (strpos($date, '.') != FALSE) {

            list($day, $month, $year) = explode(".", $date);

            if ($this->tarehe($day, $month, $year)) {
                return TRUE;
            } else {
                return FALSE;
            }
        } else {
            return FALSE;
        }
    }

    public function tarehe($day, $month, $year) {

        $first = $day[0];
        $second = $day[1];

        if ($first < 0) {
            $day = $second;
        }

        if ($day > 0 && $day <= 31) {
            $first = $month[0];
            $second = $month[1];

            if ($first < 0) {
                $month = $second;
            }

            if ($month > 0 && $month <= 12) {
                $limit_down = date('Y') - 17;
                $limit_up = date('Y') - 50;
                if ($year < $limit_down && $year > $limit_up) {

                    return TRUE;
                } else {

                    return FALSE;
                }
            } else {

                return FALSE;
            }
        } else {

            return FALSE;
        }
    }
}

So I have added your code to my welcome.php controller.

Created a test method to test your date formats /welcome/test to test your callback code and the tarehe method... to test the formats and values...

I have the form method to test your form for dob with the callback.

welcome/form

You seriously need to look at the code in your $this->form_validation_>run() section of your controller... Why the same code for both the True and False conditions and what does that code do?

Is that your real problem?


答:
Since document.getElementsByClassName("isq") is an array, you should do the following:

```<code>var arr = document.getElementsByClassName("isq");

for(var i=0; i<arr.length; i++)
    arr[i].innerHTML = null;
</code>```

Title: Mass removal of content and properties from divs

Body:
Since document.getElementsByClassName("isq") is an array, you should do the following:

var arr = document.getElementsByClassName("isq");

for(var i=0; i<arr.length; i++)
    arr[i].innerHTML = null;