问:
Why php group $_FILES values in order of name, type instead of input filedname?
I'm getting the following array when I upload array of files.

```<code>array(1) {
    ["upload"]=>array(2) {
        ["name"]=>array(2) {
            [0]=>string(9)"file0.txt"
            [1]=>string(9)"file1.txt"
        }
        ["type"]=>array(2) {
            [0]=>string(10)"text/plain"
            [1]=>string(10)"text/html"
        }
        ...
    }
}
</code>```

What is reason (technical reason or any benefits) behind the array received in the above format instead of the following ?

```<code>array(1) {
    ["upload"]=>array(2) {
        [0]=>array(2) {
            ["name"]=>string(9)"file0.txt"
            ["type"]=>string(10)"text/plain"
            ...
        },
        [1]=>array(2) {
            ["name"]=>string(9)"file1.txt"
            ["type"]=>string(10)"text/html"
            ...
        }
    }
}
</code>```

答:
I think this is the basic way of how $_FILES provides array now if you want to convert that into the formate you specified i found the code form the  link

A nice trick to reorder the $_FILES array when you use a input name as array is:

```<code><?php
    function diverse_array($vector) {
        $result = array();
        foreach($vector as $key1 => $value1)
            foreach($value1 as $key2 => $value2)
                $result[$key2][$key1] = $value2;
                return $result;
    }
?>
</code>```

will transform this:

```<code>array(1) {
    ["upload"]=>array(2) {
        ["name"]=>array(2) {
            [0]=>string(9)"file0.txt"
            [1]=>string(9)"file1.txt"
        }
        ["type"]=>array(2) {
            [0]=>string(10)"text/plain"
            [1]=>string(10)"text/html"
        }
    }
}
</code>```

into:

```<code>array(1) {
    ["upload"]=>array(2) {
        [0]=>array(2) {
            ["name"]=>string(9)"file0.txt"
            ["type"]=>string(10)"text/plain"
        },
        [1]=>array(2) {
            ["name"]=>string(9)"file1.txt"
            ["type"]=>string(10)"text/html"
        }
    }
}
</code>```

just do:

```<code><?php $upload = diverse_array($_FILES["upload"]); ?>
</code>```

Body:
I'm getting the following array when I upload array of files.

array(1) {
    ["upload"]=>array(2) {
        ["name"]=>array(2) {
            [0]=>string(9)"file0.txt"
            [1]=>string(9)"file1.txt"
        }
        ["type"]=>array(2) {
            [0]=>string(10)"text/plain"
            [1]=>string(10)"text/html"
        }
        ...
    }
}

What is reason (technical reason or any benefits) behind the array received in the above format instead of the following ?

array(1) {
    ["upload"]=>array(2) {
        [0]=>array(2) {
            ["name"]=>string(9)"file0.txt"
            ["type"]=>string(10)"text/plain"
            ...
        },
        [1]=>array(2) {
            ["name"]=>string(9)"file1.txt"
            ["type"]=>string(10)"text/html"
            ...
        }
    }
}

Body:
I think this is the basic way of how $_FILES provides array now if you want to convert that into the formate you specified i found the code form the  link

A nice trick to reorder the $_FILES array when you use a input name as array is:

<?php
    function diverse_array($vector) {
        $result = array();
        foreach($vector as $key1 => $value1)
            foreach($value1 as $key2 => $value2)
                $result[$key2][$key1] = $value2;
                return $result;
    }
?>

will transform this:

array(1) {
    ["upload"]=>array(2) {
        ["name"]=>array(2) {
            [0]=>string(9)"file0.txt"
            [1]=>string(9)"file1.txt"
        }
        ["type"]=>array(2) {
            [0]=>string(10)"text/plain"
            [1]=>string(10)"text/html"
        }
    }
}

into:

array(1) {
    ["upload"]=>array(2) {
        [0]=>array(2) {
            ["name"]=>string(9)"file0.txt"
            ["type"]=>string(10)"text/plain"
        },
        [1]=>array(2) {
            ["name"]=>string(9)"file1.txt"
            ["type"]=>string(10)"text/html"
        }
    }
}

just do:

<?php $upload = diverse_array($_FILES["upload"]); ?>


来源: stackexchange

问:
Django didn't save form to database
How can I save a form to the database with an image? It all works fine if I comment the line imagen = modelImageField so I think there is the problem in model.py. All the other parts of the form save to the database. If I comment out the line, no errors show, but the form is not saved to the database. Can anyone help me with this?

This is my View

```<code>Views.py
class donacion_Form(CreateView):
template_name='App/donacion.html'
model=donacion
fields="__all__"
success_url=reverse_lazy('mi_donacion')
</code>```

This is the form

```<code>Forms.py
class donacion_Form(forms.ModelForm):
class Meta:
    model=donacion
    fields="__all__"
</code>```

This is the Model

```<code>Model.py
class donacion(models.Model):
nombre=models.CharField(max_length=50)
estados = (
('EC', 'Excelente condicion'),
('BP', 'Buena presentacin'),
('PD', 'Presenta desgaste'),
('MD', 'Muy desgastada'),
)
prendas = (
('TP', 'Tops'),
('BT', 'Bottoms'),
('CZ', 'Calzado'),
('AS', 'Accesorios'),
('CM', 'Chamarras'),
)
generos = (
('MJR', 'Mujer'),
('HMB', 'Hombre'),
('UXA', 'Unisex adulto'),
('CHO', 'Chicos'),
('CHA', 'Chicas'),
('UXI', 'Unisex infantil'),
('BEB', 'bebes'),
)
tallas = (
('EC', 'XS'),
('CH', 'S'),
('MD', 'M'),
('GD', 'L'),
('EG', 'XL'),
('SG', 'XXL'),
)
autor=models.CharField(max_length=25)
estado = models.CharField(
    max_length=2,
    choices=estados,
    default='EC',
)
genero = models.CharField(
    max_length=3,
    choices=generos,
    default='UXA',
)
prenda = models.CharField(
    max_length=2,
    choices=prendas,
    default='TP',
)
talla = models.CharField(
    max_length=2,
    choices=tallas,
    default='CH',
)
direccion = models.CharField(max_length=500)
/*if i comment this line imagen work fine*/
imagen = models.ImageField(null = False,blank=False)
descrip = models.TextField()

def __str__(self):
    return '{}'.format(self.autor)
</code>```

答:
```<code>imagen = models.ImageField(null = False,blank=False， upload_to='imagen/')
</code>```

Specify upload directory with upload_to，more info here.

```<code>class DonacionCreateView(CreateView):
    template_name='App/donacion.html'
    form_class = DonacionForm
    success_url=reverse_lazy('mi_donacion')

class DonacionForm(forms.ModelForm):
    class Meta:
        model=donacion
        fields="__all__"

<form class="form-horizontal" enctype="multipart/form-data"
      action="{% url 'donacion_create' %}"
      method="post">
    {% csrf_token %}
    {{ form.media }}
    {{ form.errors}}
    {{form}}

    <div class="form-group">
        <input class="btn" type="submit" value="Create"/>
    </div>
</form>
</code>```

Add form.errors to html,see if any error occur.
If still wrong,please update the phenomenon and error message.

ContentLicense: CC BY-SA 3.0

Title: Django didn't save form to database

Body:
How can I save a form to the database with an image? It all works fine if I comment the line imagen = modelImageField so I think there is the problem in model.py. All the other parts of the form save to the database. If I comment out the line, no errors show, but the form is not saved to the database. Can anyone help me with this?

This is my View

Views.py
class donacion_Form(CreateView):
template_name='App/donacion.html'
model=donacion
fields="__all__"
success_url=reverse_lazy('mi_donacion')

This is the form

Forms.py
class donacion_Form(forms.ModelForm):
class Meta:
    model=donacion
    fields="__all__"

This is the Model

Model.py
class donacion(models.Model):
nombre=models.CharField(max_length=50)
estados = (
('EC', 'Excelente condicion'),
('BP', 'Buena presentacin'),
('PD', 'Presenta desgaste'),
('MD', 'Muy desgastada'),
)
prendas = (
('TP', 'Tops'),
('BT', 'Bottoms'),
('CZ', 'Calzado'),
('AS', 'Accesorios'),
('CM', 'Chamarras'),
)
generos = (
('MJR', 'Mujer'),
('HMB', 'Hombre'),
('UXA', 'Unisex adulto'),
('CHO', 'Chicos'),
('CHA', 'Chicas'),
('UXI', 'Unisex infantil'),
('BEB', 'bebes'),
)
tallas = (
('EC', 'XS'),
('CH', 'S'),
('MD', 'M'),
('GD', 'L'),
('EG', 'XL'),
('SG', 'XXL'),
)
autor=models.CharField(max_length=25)
estado = models.CharField(
    max_length=2,
    choices=estados,
    default='EC',
)
genero = models.CharField(
    max_length=3,
    choices=generos,
    default='UXA',
)
prenda = models.CharField(
    max_length=2,
    choices=prendas,
    default='TP',
)
talla = models.CharField(
    max_length=2,
    choices=tallas,
    default='CH',
)
direccion = models.CharField(max_length=500)
/*if i comment this line imagen work fine*/
imagen = models.ImageField(null = False,blank=False)
descrip = models.TextField()

def __str__(self):
    return '{}'.format(self.autor)

Body:
imagen = models.ImageField(null = False,blank=False， upload_to='imagen/')

Specify upload directory with upload_to，more info here.

class DonacionCreateView(CreateView):
    template_name='App/donacion.html'
    form_class = DonacionForm
    success_url=reverse_lazy('mi_donacion')

class DonacionForm(forms.ModelForm):
    class Meta:
        model=donacion
        fields="__all__"

<form class="form-horizontal" enctype="multipart/form-data"
      action="{% url 'donacion_create' %}"
      method="post">
    {% csrf_token %}
    {{ form.media }}
    {{ form.errors}}
    {{form}}

    <div class="form-group">
        <input class="btn" type="submit" value="Create"/>
    </div>
</form>

Add form.errors to html,see if any error occur.
If still wrong,please update the phenomenon and error message.


问:
use pyodbc to read Microsoft access long binary data
I am using pyodbc driver to get long binary data from Microsoft Access i.e. .mdb file. Following is the code snippet and output.

code:

```<code>import pyodbc
conn = pyodbc.connect('DRIVER={Microsoft Access Driver (*.mdb)};DBQ=d:\\testarea\\test.mdb')

sqlcommand = 'select * from FORMULA_GROUP'

result = cur.execute(sqlcommand).fetchall()

result[0][0]
</code>```

but I get this string as output

```<code>b'\x01\x06\xa4w\xae\xd6\xad\xe3\x01\x00\x04\x00\xff\xff\x01\x00\x08\x00CFormula\x05\x00\x080G9yHh>d\x02\x00\x00\x00\x01\x00\x00\x00\xc8B\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x16w\x82x\x8f\x8a\xe4@\x00\x07A\x04S\x06\x00\xff\xff\x01\x00\n\x00CDyeAmount\x02\x0cA3302||A3302\x120G;6QAfb||66455C17\n\xd7\xa3=\x01\x00\x03\x80\x02\x0cA3317||A3317\x120G;6Xdh0||151273AE\x17\xd9N?\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
</code>```

anyone know how to decode it??

答:
This is properties window:

So, I expected to get something like 'A4102 1.66;A4412 0.865;A4414 0.745' or some readable string

Body:
I am using pyodbc driver to get long binary data from Microsoft Access i.e. .mdb file. Following is the code snippet and output.

code:

import pyodbc
conn = pyodbc.connect('DRIVER={Microsoft Access Driver (*.mdb)};DBQ=d:\\testarea\\test.mdb')

sqlcommand = 'select * from FORMULA_GROUP'

result = cur.execute(sqlcommand).fetchall()

result[0][0]

but I get this string as output

b'\x01\x06\xa4w\xae\xd6\xad\xe3\x01\x00\x04\x00\xff\xff\x01\x00\x08\x00CFormula\x05\x00\x080G9yHh>d\x02\x00\x00\x00\x01\x00\x00\x00\xc8B\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x16w\x82x\x8f\x8a\xe4@\x00\x07A\x04S\x06\x00\xff\xff\x01\x00\n\x00CDyeAmount\x02\x0cA3302||A3302\x120G;6QAfb||66455C17\n\xd7\xa3=\x01\x00\x03\x80\x02\x0cA3317||A3317\x120G;6Xdh0||151273AE\x17\xd9N?\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'

anyone know how to decode it??


问:
is nodejs slow while reading more than 4 big files at the same time?
I remember it seems that nodejs by default is using 4 back-end threads, therefore the fifth reading action will wait until 1 thread is available.

But I can't find any testify-example in google. Could someone explain and find the example please? Thanks.

答: It's in this post, as referred in the post from jfriend00. Thanks.</p>


问:
How to tear down Selenium (3.8) and close IE browser window?
I simply cannot get Selenium to clean up after navigating to a page. (Without the Navigate().GoToURL(), it tears down nicely.) I understand the supposed difference between Close(), Quit(), and Dispose(). I've tried every combination I could think of. I must be missing something. If I have to shut them down myself --if that's the solution... I honestly have no clue, but that's fine. I would just like to know if I am missing something in terms of using Selenium. Any help greatly appreciated. </p>

```<code>// no iexplore windows open

IWebDriver f = new InternetExplorerDriver();

f.Navigate().GoToUrl("http://abcdxpq.com");

f.Close();
f.Quit();
f.Dispose();

// iexplore window left open (http://abcdxpq.com)
</code>```

答:
Looking at your code I feel we need to narrow down to a single line of code to process the tearDown() the IEDriverServer and the Browser instance of InternetExplorerDriver.

As per the current implementation, Driver.Dispose(); shouldn't be used to clean up the WebDriver instance. For a proper cleanup we must be using Driver.Quit();. It's worth to be mentioned that Driver.Quit(); internally calls Driver.Close();.

tearDown() Methods Comparision

Driver.Dispose();: It got deprecated currently.

Driver.Close(); : It is used to close the current page or the browser (if it is the only page/tab) which is having the focus.

Driver.Quit(); : It is used to call the /shutdown endpoint and subsequently kill the WebDriver and the Web Browser instance completely closing all the pages/tabs/windows.

You will get a more detailed discussion in this discussion PhantomJS web driver stays in memory

Body:
I simply cannot get Selenium to clean up after navigating to a page. (Without the Navigate().GoToURL(), it tears down nicely.) I understand the supposed difference between Close(), Quit(), and Dispose(). I've tried every combination I could think of. I must be missing something. If I have to shut them down myself --if that's the solution... I honestly have no clue, but that's fine. I would just like to know if I am missing something in terms of using Selenium. Any help greatly appreciated.

// no iexplore windows open

IWebDriver f = new InternetExplorerDriver();

f.Navigate().GoToUrl("http://abcdxpq.com");

f.Close();
f.Quit();
f.Dispose();

// iexplore window left open (http://abcdxpq.com)


问:
Python questions multiple print lines ran as one line
Modify the following four (4) lines of code so that the output looks like:

one, two, three, four

without removing any of the lines and only by adding s named argument.

```<code>print("one")
print("two")
print("three")
print("four")
</code>```

I'm currently in school and this is an introduction to programming. It's
online so all I really have is the book as a resource. If I'm not mistaken
an s named argument is a string, isn't it? If anyone could help me out with this I would really appreciate it.

Thanks.

答:
from documentation of print()

```<code>print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
</code>```

Print objects to the text stream file, separated by sep and followed
  by end. sep, end, file and flush, if present, must be given as keyword
  arguments.

As you can see default keyword argument for end statement is \n hence it is always printing your string from new line but if you just override argument with , as shown in below code you will get your desire output.

```<code>print("one", end=", ")
print("two", end=", ")
print("three", end=", ")
print("four")
</code>```

Output:

```<code>one, two, three, four
</code>```

Body:
Modify the following four (4) lines of code so that the output looks like:

one, two, three, four

without removing any of the lines and only by adding s named argument.

print("one")
print("two")
print("three")
print("four")

I'm currently in school and this is an introduction to programming. It's
online so all I really have is the book as a resource. If I'm not mistaken
an s named argument is a string, isn't it? If anyone could help me out with this I would really appreciate it.

Thanks.

Body:
from documentation of print()

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

Print objects to the text stream file, separated by sep and followed
  by end. sep, end, file and flush, if present, must be given as keyword
  arguments.

As you can see default keyword argument for end statement is \n hence it is always printing your string from new line but if you just override argument with , as shown in below code you will get your desire output.

print("one", end=", ")
print("two", end=", ")
print("three", end=", ")
print("four")

Output:

one, two, three, four


问:
Is it possible to run ARWorldTracking Session and ARFaceTracking Session at the same time on iPhoneX?
I'm trying to run ARWorldTracking Session and ARFaceTracking Session at the same time on iPhoneX,
 but the first running session stopped after the later session begun to run.

Is is impossible to implement?
This is my ViewController.swift code.

```<code>import UIKit
import ARKit

class ViewController: UIViewController, ARSCNViewDelegate,
ARSessionDelegate {
    @IBOutlet weak var frontView: ARSCNView!
    @IBOutlet weak var backView: ARSCNView!
    override func viewDidLoad() {
       super.viewDidLoad()
       startTracking()
    }

   func startTracking() {
       let backConfiguration = ARWorldTrackingConfiguration()
       backView.session.run(backConfiguration)

       let frontConfiguration = ARFaceTrackingConfiguration()
       frontConfiguration.isLightEstimationEnabled = true
       frontView.session.run(frontConfiguration)
  }
}
</code>```

答:
Nope. </p>

<p>ARKit relies upon the AVCapture system, and that doesn’t support using more than one capture device (camera) at a time. If you start a capture session using the front camera while another session is using the back camera, the existing session stops. </p>

Body:
I'm trying to run ARWorldTracking Session and ARFaceTracking Session at the same time on iPhoneX,
 but the first running session stopped after the later session begun to run.

Is is impossible to implement?
This is my ViewController.swift code.

import UIKit
import ARKit

class ViewController: UIViewController, ARSCNViewDelegate,
ARSessionDelegate {
    @IBOutlet weak var frontView: ARSCNView!
    @IBOutlet weak var backView: ARSCNView!
    override func viewDidLoad() {
       super.viewDidLoad()
       startTracking()
    }

   func startTracking() {
       let backConfiguration = ARWorldTrackingConfiguration()
       backView.session.run(backConfiguration)

       let frontConfiguration = ARFaceTrackingConfiguration()
       frontConfiguration.isLightEstimationEnabled = true
       frontView.session.run(frontConfiguration)
  }
}

Body:
Nope.

ARKit relies upon the AVCapture system, and that doesn’t support using more than one capture device (camera) at a time. If you start a capture session using the front camera while another session is using the back camera, the existing session stops.


问:
MongoDB: No unix socket support on windows
I use Robo 3T as a UI tool for MongoDB on a Windows 8 machine. Now I've deployed the DB to production on a Ubuntu 14 server in Amazon EC2 cloud. When I try to connect from the Windows machine to the Ubuntu one via Robo 3T, I receive the following error:

Cannot connect to the MongoDB at [http://12.345.678.90]:27017.

Error: No unix socket support on windows

Is that a problem I need to fix on my computer by installing something? or it's an issue of Mongo 3T?

If it's an issue on my Windows, what do I have to install in order to make it work?

If it's a Mongo 3T issue, do you know another UI that does support connecting from Windows to Ubuntu?

Perhaps an EC2 solution?

Or maybe some settings I need to change in Robo 3T?

I've tried changing "http" to "mongodb" to no avail. I've also tried removing the protocol prefix as suggested here but I ended up with the error:

Cannot connect to the MongoDB at 12.345.678.90:27017.

Error: Network is unreachable.

答:
Do you have a bindIP setting in your mongo configuration file? Probably that can cause the error.
Either remove the bindIp configuration or allow your IP to access mongo server.
(restart your service after changes the configuration).</p>


问:
Player Buffer remains at 0 but the videoElement Buffer changes?
I am using a custom receiver and a MPL. I am performing a live dash streaming.
As some of the segments are downloaded the HTML video Element buffer is updated but the player's buffer remains at 0. Why does this happen? How can I solve it? </p>

答:
The issue was fixed by adding a parameter to the manifest. </p>

```<code>MPD@mediaPresentationDuration
</code>```

<p>But some other player have played the content from same manifest without any trouble.  </p>

Body:
The issue was fixed by adding a parameter to the manifest.

MPD@mediaPresentationDuration

But some other player have played the content from same manifest without any trouble.


问:
Admob Failed to load ad: 0
I created my adMob ad unit around 12 hours ago and implemented it like so:

XML:

```<code>    <com.google.android.gms.ads.AdView
    android:id="@+id/bannerAdView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_alignParentBottom="true"
    ads:adSize="BANNER"
    ads:adUnitId="ca-app-pub-9378881698271837/3415450508">
</com.google.android.gms.ads.AdView>
</code>```

MainActivity.java:

```<code>    bannerAd = (AdView) findViewById(R.id.bannerAdView);
    AdRequest adRequest = new AdRequest.Builder().addTestDevice(MY_DEVICE_ID).build();
    bannerAd.loadAd(adRequest);
</code>```

Gradle dependencies:

```<code>dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.google.firebase:firebase-ads:11.0.1'
compile 'com.google.android.gms:play-services-ads:11.0.1'
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
    exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:26.0.0-alpha1'
testCompile 'junit:junit:4.12'
</code>```

}

Manifest permissions:

```<code>    <uses-permission android:name="android.permission.INTERNET" />
</code>```

I followed the Firebase and adMob integration documentation but it will not display ads on any device I run the app on.

答: if you connect with firebase than also add maven{url "https://maven.google.com"}in project module gradle and in admob account add the payment detail </p>

Title: Admob Failed to load ad: 0

Body:
I created my adMob ad unit around 12 hours ago and implemented it like so:

XML:

    <com.google.android.gms.ads.AdView
    android:id="@+id/bannerAdView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_alignParentBottom="true"
    ads:adSize="BANNER"
    ads:adUnitId="ca-app-pub-9378881698271837/3415450508">
</com.google.android.gms.ads.AdView>

MainActivity.java:

    bannerAd = (AdView) findViewById(R.id.bannerAdView);
    AdRequest adRequest = new AdRequest.Builder().addTestDevice(MY_DEVICE_ID).build();
    bannerAd.loadAd(adRequest);

Gradle dependencies:

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.google.firebase:firebase-ads:11.0.1'
compile 'com.google.android.gms:play-services-ads:11.0.1'
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
    exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:26.0.0-alpha1'
testCompile 'junit:junit:4.12'

}

Manifest permissions:

    <uses-permission android:name="android.permission.INTERNET" />

I followed the Firebase and adMob integration documentation but it will not display ads on any device I run the app on.


问:
Problems with background on UITableViewCell iPhone
I the following code in my class. When I launch my app on the simulator it works. However when launcing the app on an actual device(iPhone 1g, 3.1.3) it does not work. Any ideas?

(it's for making gradient background)

```<code>- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *MainScreenCellID = @"MainScreenCellID";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MainScreenCellID];

if (cell == nil) {
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:MainScreenCellID] autorelease];
}

cell.textLabel.text = [[[self.controllers objectAtIndex:[indexPath row]] navigationItem] title];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

UIImageView *bgimage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"cell_bg.png"]];
cell.backgroundView = bgimage;
[bgimage release];

for (UIView *view in cell.contentView.subviews) {
    view.backgroundColor = [UIColor clearColor];
}

return cell;
}
</code>```

(Black fields is added because the app is not done yet.)

EDIT:

I can add that on the UITableViewCell which this method work on I have made my own subclasses, but where I am using the UITableViewDefaultStyle it does not work.

答:
The good place for setting clearColor is

```<code>- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath { ... }
</code>```

I think you should set clearColor for contentView also.

ContentLicense: CC BY-SA 2.5

Body:
I the following code in my class. When I launch my app on the simulator it works. However when launcing the app on an actual device(iPhone 1g, 3.1.3) it does not work. Any ideas?

(it's for making gradient background)

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *MainScreenCellID = @"MainScreenCellID";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MainScreenCellID];

if (cell == nil) {
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:MainScreenCellID] autorelease];
}

cell.textLabel.text = [[[self.controllers objectAtIndex:[indexPath row]] navigationItem] title];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

UIImageView *bgimage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"cell_bg.png"]];
cell.backgroundView = bgimage;
[bgimage release];

for (UIView *view in cell.contentView.subviews) {
    view.backgroundColor = [UIColor clearColor];
}

return cell;
}

(Black fields is added because the app is not done yet.)

EDIT:

I can add that on the UITableViewCell which this method work on I have made my own subclasses, but where I am using the UITableViewDefaultStyle it does not work.

Body:
The good place for setting clearColor is

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath { ... }

I think you should set clearColor for contentView also.


问:
Couldn't find TextInput features documentation?
I'm new to react-native and having difficulty finding some features documentation regarding TextInput.

On react-native site it is mentioned about TextInput:

Props provide configurability for several features, such as
  auto-correction, auto-capitalization, placeholder text, and different
  keyboard types, such as a numeric keypad.

But I couldn't find documentation that explains these features auto-correction, auto-capitalization, placeholder text like what all the parameters they take? what are the deault values? are they required parameter? and how they exactly work.

Is there somewhere I can read about these features implementation?

I'm trying to set prop-types for these props and want to know what kind of data they expect?

Thanks.

答:
First of all, when TextInput is rendered it displays the default keyboard(ios and android), in which autocapitalization of first letter is already defined.

In order to remove auto-capitalisation of first letter, you write the property like this:

```<code><TextInput
 autoCapitalize={false} />
</code>```

Similarly, you can add properties like autoCorrect={false} if you need not auto correction of words.

Here are all the properties for TextInput you can use:
https://facebook.github.io/react-native/docs/next/textinput.html

Body:
First of all, when TextInput is rendered it displays the default keyboard(ios and android), in which autocapitalization of first letter is already defined.

In order to remove auto-capitalisation of first letter, you write the property like this:

<TextInput
 autoCapitalize={false} />

Similarly, you can add properties like autoCorrect={false} if you need not auto correction of words.

Here are all the properties for TextInput you can use:
https://facebook.github.io/react-native/docs/next/textinput.html


问:
docker: set running user while launch container
I use the official golang docker image to compile my go program and put the resulting executable on a volume mapped to my host directory.

The problem is that file generated by docker belongs to root:root, which is very annoying because I do not want to run my script via sudo.

I searched for solutions to make docker container run as non-root, but the method I found need to change Dockerfile and add user to the image, e.g.

http://gbraad.nl/blog/non-root-user-inside-a-docker-container.html

Is there a way to make docker container run as the CURRENT user on host machine, i.e., user A runs this image will generate file belongs to A:A, and user B generate file belongs to B:B, while A and B are both users defined on host machine (i.e. where the volume resides), without the need to add A and B into the image via Dockerfile?

答:
which I made by base alphine-golang plus the git tool), runs on my laptop with the -u arg, but if I run it on an debian virtual machine, it tells me No user exists for uid 1001

Ideally, you would make your own image (based on an existing one) with the right expected ID:

```<code>RUN useradd -r -u 1001 -g appuser appuser
USER appuser
</code>```

See "Understanding how uid and gid work in Docker containers", from Marc Campbell:

The OP adds:

I understand the reason because this is exactly what I try to avoid: add user into the image.

  If my problem was not solved, I will try to modify the container directly.

Actually, there is another alternative, which allows you to not modify an image and not add a user: userns or user remap (since docker 1.10). However, as I mention here, you would need docker 17.06 to avoid some bugs.

Body:
which I made by base alphine-golang plus the git tool), runs on my laptop with the -u arg, but if I run it on an debian virtual machine, it tells me No user exists for uid 1001

Ideally, you would make your own image (based on an existing one) with the right expected ID:

RUN useradd -r -u 1001 -g appuser appuser
USER appuser

See "Understanding how uid and gid work in Docker containers", from Marc Campbell:

The OP adds:

I understand the reason because this is exactly what I try to avoid: add user into the image.

  If my problem was not solved, I will try to modify the container directly.

Actually, there is another alternative, which allows you to not modify an image and not add a user: userns or user remap (since docker 1.10). However, as I mention here, you would need docker 17.06 to avoid some bugs.


问:
How to load gif using wxWidgets c++?
I need your help! Im currently really new to wxWidgets as a uni student. I am trying to load a .gif file using wxWidgets. I tried using the code below... but it only loads 1 frame, it doesn't move/ change to the other frames, it's basically a still picture. The file is .gif extension, and it has 3 frames or so. The location of the image is already correct. Help would be much appreciated!

Thank you

```<code>#include "ImageWindow.h"
#include <wx/stdpaths.h>
#include <wx/filename.h>
BEGIN_EVENT_TABLE(ImageWindow, wxWindow)
EVT_PAINT(ImageWindow::OnPaint)
END_EVENT_TABLE()
ImageWindow::ImageWindow(wxFrame *parent)
    : wxWindow(parent, wxID_ANY)
{
    this->SetBackgroundColour(wxColour(*wxWHITE));
    wxImageHandler *gifLoader = new wxGIFHandler();
    wxImage::AddHandler(gifLoader);
    this->LoadPotatoBitmap();
}
ImageWindow::~ImageWindow()
{
    delete potatoBitmap;
}
void ImageWindow::LoadPotatoBitmap()
{
    wxStandardPaths &stdPaths = wxStandardPaths::Get();
    wxString fileLocation = stdPaths.GetExecutablePath();
    wxImage image(wxT("A:\\Projects\\TestGif\\Assets\\Kuning.gif"),
        wxBITMAP_TYPE_GIF);
    potatoBitmap = new wxBitmap(image);
}
void ImageWindow::OnPaint(wxPaintEvent &event)
{
    wxPaintDC pdc(this);
    if (potatoBitmap != nullptr)
    {
        pdc.DrawBitmap(*potatoBitmap, wxPoint(150, 100), true);
    }
}
</code>```

答:
Use wxAnimationCtrl for playing gif animations
or

Use extract each frame from the gif image and draw one by one using wxTimer.

Title: How to load gif using wxWidgets c++?

Body:
I need your help! Im currently really new to wxWidgets as a uni student. I am trying to load a .gif file using wxWidgets. I tried using the code below... but it only loads 1 frame, it doesn't move/ change to the other frames, it's basically a still picture. The file is .gif extension, and it has 3 frames or so. The location of the image is already correct. Help would be much appreciated!

Thank you

#include "ImageWindow.h"
#include <wx/stdpaths.h>
#include <wx/filename.h>
BEGIN_EVENT_TABLE(ImageWindow, wxWindow)
EVT_PAINT(ImageWindow::OnPaint)
END_EVENT_TABLE()
ImageWindow::ImageWindow(wxFrame *parent)
    : wxWindow(parent, wxID_ANY)
{
    this->SetBackgroundColour(wxColour(*wxWHITE));
    wxImageHandler *gifLoader = new wxGIFHandler();
    wxImage::AddHandler(gifLoader);
    this->LoadPotatoBitmap();
}
ImageWindow::~ImageWindow()
{
    delete potatoBitmap;
}
void ImageWindow::LoadPotatoBitmap()
{
    wxStandardPaths &stdPaths = wxStandardPaths::Get();
    wxString fileLocation = stdPaths.GetExecutablePath();
    wxImage image(wxT("A:\\Projects\\TestGif\\Assets\\Kuning.gif"),
        wxBITMAP_TYPE_GIF);
    potatoBitmap = new wxBitmap(image);
}
void ImageWindow::OnPaint(wxPaintEvent &event)
{
    wxPaintDC pdc(this);
    if (potatoBitmap != nullptr)
    {
        pdc.DrawBitmap(*potatoBitmap, wxPoint(150, 100), true);
    }
}


问:
ASP.NET MVC: Display a link to another action
```<code>@Html.ActionLink("Add a bill", "Create", new { controller = "Bill"});
</code>```

This is the code I used to add an link to Create method in Bill controller.

But in the view I saw

```<code>Add a bill (/Bill/Create):
</code>```

So, how can I remove the brackets? (/Bill/Create).

And, I also want this link to act as a button instead of a , how can I do that? Thanks for your help.

答:
It is strange what brackets you are talking about. Assuming the default routes both:

```<code>@Html.ActionLink("Add a bill", "Create", new { controller = "Bill" })
</code>```

and:

```<code>@Html.ActionLink("Add a bill", "Create", "Bill")
</code>```

are equivalent and should generate the following markup:

```<code><a href="/Bill/Create">Add a bill</a>
</code>```

As far as your question about the button is concerned you could use a form:

```<code>@using (Html.BeginForm("Create", "Bill"))
{
   <input type="submit" value="Add a bill" />
}
</code>```

Body:
@Html.ActionLink("Add a bill", "Create", new { controller = "Bill"});

This is the code I used to add an link to Create method in Bill controller.

But in the view I saw

Add a bill (/Bill/Create):

So, how can I remove the brackets? (/Bill/Create).

And, I also want this link to act as a button instead of a , how can I do that? Thanks for your help.

Body:
It is strange what brackets you are talking about. Assuming the default routes both:

@Html.ActionLink("Add a bill", "Create", new { controller = "Bill" })

and:

@Html.ActionLink("Add a bill", "Create", "Bill")

are equivalent and should generate the following markup:

<a href="/Bill/Create">Add a bill</a>

As far as your question about the button is concerned you could use a form:

@using (Html.BeginForm("Create", "Bill"))
{
   <input type="submit" value="Add a bill" />
}


问:
Pycharm/Django indentation error
I was asked in Pycharm some question along the lines of 'your code was was written with 4 spaces rather than tabs, press ok' but I cannot remember the exact wording.  I didn't know what the option meant but since I pressed that button I'm getting an ident error.  But I do not get an ident error in other locations.  Now I'm getting an indentation error at 'list_display_links' and the code looks just the same as it does on this tutorial.

```<code>from django.contrib import admin
from .models import Post

class PostModelAdmin(admin.ModelAdmin):
    list_display = ["title", "updated", "timestamp"]
    list_display_links = ['updated']
    class Meta:
        model = Post
</code>```

tutorial image

答: I had to hit reformat code on Pycharm, as seen here:

Title: Pycharm/Django indentation error

Body:
I was asked in Pycharm some question along the lines of 'your code was was written with 4 spaces rather than tabs, press ok' but I cannot remember the exact wording.  I didn't know what the option meant but since I pressed that button I'm getting an ident error.  But I do not get an ident error in other locations.  Now I'm getting an indentation error at 'list_display_links' and the code looks just the same as it does on this tutorial.

from django.contrib import admin
from .models import Post

class PostModelAdmin(admin.ModelAdmin):
    list_display = ["title", "updated", "timestamp"]
    list_display_links = ['updated']
    class Meta:
        model = Post

tutorial image


问:
How do I sort a bunch of letters and their corresponding frequencies from a string?
I am trying to write a function that can analyze a string and print the letters in the string and their corresponding frequencies. This part isn't too much of a challenge because I can just use ascii_lowercase to sort through the string then the count() method available in ascii. The difficult part is sorting the frequencies so that the most frequent letter is the beginning, and the least frequent is at the end. Here is what I have written so far:

```<code>def analyze(codebook):
lst = []
tmp = []
for c in ascii_lowercase:
   count = codebook.count(c)
   print("('%s', %d)" % (c.upper(), count), end=" ")
   lst.append(count)
   tmp.append(c)
lst.sort()
lst.reverse()
print(lst)
print(tmp)
</code>```

All this does is print the letter and it's corresponding frequencies in the order of the alphabet. Here is an example of the string that I am using:

```<code>pooiiiuuuuyyyyyttttttrrrrrrreeeeeeeewwwwwwwwwqqqqqqqqqq
</code>```

And here is an example of my desired output:

```<code>('Q', 10) ('W', 9) ('E', 8) ('R', 7) ('T', 6) ('Y', 5) ('U', 4) ('I', 3)

('O', 2) ('P', 1) ('A', 0) ('B', 0) ('C', 0) ('D', 0) ('F', 0) ('G', 0)

('H', 0) ('J', 0) ('K', 0) ('L', 0) ('M', 0) ('N', 0) ('S', 0) ('V', 0)

('X', 0) ('Z', 0)
</code>```

I have also tried using collections; however, that got confusing very quickly. Any help would be appreciated!

答:
The solution is a bit long, but you can modify it. Below is the code for your desired output:

```<code>import collections
import string
word = "pooiiiuuuuyyyyyttttttrrrrrrreeeeeeeewwwwwwwwwqqqqqqqqqq"
wordpair = collections.Counter(word)
# Getting Word Characters
wordchar = list(wordpair.keys())
wordchar = wordchar[::-1]
# Getting Word Count
wordcount = list(wordpair.values())
wordcount = wordcount[::-1]

for w,c in zip(wordchar,wordcount):
    print("('%s', %d)" % (w.upper(), c), end=" ")

for char in string.ascii_lowercase:
    if char not in wordchar:
        print("('%s', %d)" % (char.upper(), 0), end=" ")
</code>```

Output:

```<code>('Q', 10) ('W', 9) ('E', 8) ('R', 7) ('T', 6) ('Y', 5) ('U', 4) ('I', 3)
('O', 2) ('P', 1) ('A', 0) ('B', 0) ('C', 0) ('D', 0) ('F', 0) ('G', 0)
('H', 0) ('J', 0) ('K', 0) ('L', 0) ('M', 0) ('N', 0) ('S', 0) ('V', 0)
('X', 0) ('Z', 0)
</code>```

Body:
I am trying to write a function that can analyze a string and print the letters in the string and their corresponding frequencies. This part isn't too much of a challenge because I can just use ascii_lowercase to sort through the string then the count() method available in ascii. The difficult part is sorting the frequencies so that the most frequent letter is the beginning, and the least frequent is at the end. Here is what I have written so far:

def analyze(codebook):
lst = []
tmp = []
for c in ascii_lowercase:
   count = codebook.count(c)
   print("('%s', %d)" % (c.upper(), count), end=" ")
   lst.append(count)
   tmp.append(c)
lst.sort()
lst.reverse()
print(lst)
print(tmp)

All this does is print the letter and it's corresponding frequencies in the order of the alphabet. Here is an example of the string that I am using:

pooiiiuuuuyyyyyttttttrrrrrrreeeeeeeewwwwwwwwwqqqqqqqqqq

And here is an example of my desired output:

('Q', 10) ('W', 9) ('E', 8) ('R', 7) ('T', 6) ('Y', 5) ('U', 4) ('I', 3)

('O', 2) ('P', 1) ('A', 0) ('B', 0) ('C', 0) ('D', 0) ('F', 0) ('G', 0)

('H', 0) ('J', 0) ('K', 0) ('L', 0) ('M', 0) ('N', 0) ('S', 0) ('V', 0)

('X', 0) ('Z', 0)

I have also tried using collections; however, that got confusing very quickly. Any help would be appreciated!

Body:
The solution is a bit long, but you can modify it. Below is the code for your desired output:

import collections
import string
word = "pooiiiuuuuyyyyyttttttrrrrrrreeeeeeeewwwwwwwwwqqqqqqqqqq"
wordpair = collections.Counter(word)
# Getting Word Characters
wordchar = list(wordpair.keys())
wordchar = wordchar[::-1]
# Getting Word Count
wordcount = list(wordpair.values())
wordcount = wordcount[::-1]

for w,c in zip(wordchar,wordcount):
    print("('%s', %d)" % (w.upper(), c), end=" ")

for char in string.ascii_lowercase:
    if char not in wordchar:
        print("('%s', %d)" % (char.upper(), 0), end=" ")

Output:

('Q', 10) ('W', 9) ('E', 8) ('R', 7) ('T', 6) ('Y', 5) ('U', 4) ('I', 3)
('O', 2) ('P', 1) ('A', 0) ('B', 0) ('C', 0) ('D', 0) ('F', 0) ('G', 0)
('H', 0) ('J', 0) ('K', 0) ('L', 0) ('M', 0) ('N', 0) ('S', 0) ('V', 0)
('X', 0) ('Z', 0)


问:
validate user input and loop until correct
I have looked on here for an idea in order to loop the user's invalid input and I haven't found one.

Ok, I know how to loop the first_number and second_number together but I am a bit confused on how to loop the separately if need be. So if the user inputs a bad second_number and loops that instead of the whole thing again.

I've attached the part I need help with (yes this is a school assignment):

```<code>def get_numbers():
first_number = 0.0
second_number = 0.0

while True:
    try:
        first_number = float(input("Please enter the first number: "))
        second_number = float(input("Please enter the second number: "))
    except ValueError:
        print("Not a valid input, please try again.")
        continue

    return first_number, second_number
</code>```

答:
To use 1 loop, you may need to recognize the differences:

You use 2 simple variables for the results though you could use 1 list.

The input string is almost the same except for "first" and "second" words.

Concept:

First you want a list.

Then use a for loop to use "first", then "second" words.

Then use a while loop which processes the inputs and uses the list to extend with the replies. Use break to get out of the while loop after each good reply.

```<code>def get_numbers():
    result = []

    for item in ("first", "second"):
        while True:
            try:
                number = float(input("Please enter the " + item + " number: "))
            except ValueError:
                print("Not a valid input, please try again.")
            else:
                result += [number]
                break

    return tuple(result)
</code>```

Returning as a tuple as you have done.

Body:
I have looked on here for an idea in order to loop the user's invalid input and I haven't found one.

Ok, I know how to loop the first_number and second_number together but I am a bit confused on how to loop the separately if need be. So if the user inputs a bad second_number and loops that instead of the whole thing again.

I've attached the part I need help with (yes this is a school assignment):

def get_numbers():
first_number = 0.0
second_number = 0.0

while True:
    try:
        first_number = float(input("Please enter the first number: "))
        second_number = float(input("Please enter the second number: "))
    except ValueError:
        print("Not a valid input, please try again.")
        continue

    return first_number, second_number

Body:
To use 1 loop, you may need to recognize the differences:

You use 2 simple variables for the results though you could use 1 list.

The input string is almost the same except for "first" and "second" words.

Concept:

First you want a list.

Then use a for loop to use "first", then "second" words.

Then use a while loop which processes the inputs and uses the list to extend with the replies. Use break to get out of the while loop after each good reply.

def get_numbers():
    result = []

    for item in ("first", "second"):
        while True:
            try:
                number = float(input("Please enter the " + item + " number: "))
            except ValueError:
                print("Not a valid input, please try again.")
            else:
                result += [number]
                break

    return tuple(result)

Returning as a tuple as you have done.


问:
Getting Warning in wordpress plugin post-my-contact-form-7 after updating to the PHP 7.2.0
I am Working on a wordpress project it's working fine

When i Update the PHP version 7.2.0 I am getting warning like this:

Warning: Use of undefined constant WP_GURUS_DEBUG - assumed
  'WP_GURUS_DEBUG' (this will throw an Error in a future version of PHP)
  in
  C:\wamp\www\wordpress1\wp-content\plugins\post-my-contact-form-7\includes\wordpress-gurus-debug-api.php
  on line 9

My wordpress version is 4.9.1

My plugin:

Post My CF7 Form
  Version 3.2.0

Here is the plugin file:

```<code><?php
/**
* Error logging and notices
* @since 1.0.0
* @var string $message to log if in debug mode
*/

if( !function_exists('debug_msg') ){
  if (true === WP_DEBUG || true === WP_GURUS_DEBUG) {
     $debug_msg_last_line='';
     $debug_msg_last_file='';
   }
  function debug_msg($message,$prefix='') {
      if (true === WP_DEBUG || true === WP_GURUS_DEBUG) {
        global $debug_msg_last_line,$debug_msg_last_file;
          $backtrace = debug_backtrace();
          $file = $backtrace[0]['file'];
          $files = explode('/',$file);
          $dirs = explode('/',plugin_dir_path( __FILE__ ));
          $files = array_diff($files,$dirs);
          $file = implode('/',$files);
          $line = $backtrace[0]['line'];
          if($file != $debug_msg_last_file && $line != $debug_msg_last_line){
            error_log("DEBUG_MSG: [".$line."]./".$file);
            $debug_msg_last_file=$file;
            $debug_msg_last_line=$line;
          }else{
            //error_log("CF7_2_POST: ");
          }
          if (is_array($message) || is_object($message)) {
              error_log("          + ".$prefix.print_r($message, true));
          } else {
              error_log("          + ".$prefix.$message);
          }
      }
  }
} ?>
</code>```

How to resolve this warning?

答:
EDIT: I informed the plugin maintainer, and this issue should now be resolved simply by updating the plugin.

Aurovrata Venet wrote:

oops, my bad!  Fixed in v3.2.1

Post Link:
  https://wordpress.org/support/topic/warning-use-of-undefined-constant-wp_gurus_debug/#post-9777594

WP_DEBUG is already defined (as false, by default), but WP_GURUS_DEBUG apparently isn't defined by the plugin by default. Attempting to use an undefined constant will be considered an error in future versions of PHP, but as a heads-up they are displaying it as a warning to give developers a chance to update their code.

The plugin maintainers need to update line

if (true === WP_DEBUG || true === WP_GURUS_DEBUG) {

to check if the constants are defined with something like:

if ( ( defined( 'WP_DEBUG' ) AND true === WP_DEBUG ) || ( defined( 'WP_GURUS_DEBUG' ) AND true === WP_GURUS_DEBUG ) ) {

Body:
I am Working on a wordpress project it's working fine

When i Update the PHP version 7.2.0 I am getting warning like this:

Warning: Use of undefined constant WP_GURUS_DEBUG - assumed
  'WP_GURUS_DEBUG' (this will throw an Error in a future version of PHP)
  in
  C:\wamp\www\wordpress1\wp-content\plugins\post-my-contact-form-7\includes\wordpress-gurus-debug-api.php
  on line 9

My wordpress version is 4.9.1

My plugin:

Post My CF7 Form
  Version 3.2.0

Here is the plugin file:

<?php
/**
* Error logging and notices
* @since 1.0.0
* @var string $message to log if in debug mode
*/

if( !function_exists('debug_msg') ){
  if (true === WP_DEBUG || true === WP_GURUS_DEBUG) {
     $debug_msg_last_line='';
     $debug_msg_last_file='';
   }
  function debug_msg($message,$prefix='') {
      if (true === WP_DEBUG || true === WP_GURUS_DEBUG) {
        global $debug_msg_last_line,$debug_msg_last_file;
          $backtrace = debug_backtrace();
          $file = $backtrace[0]['file'];
          $files = explode('/',$file);
          $dirs = explode('/',plugin_dir_path( __FILE__ ));
          $files = array_diff($files,$dirs);
          $file = implode('/',$files);
          $line = $backtrace[0]['line'];
          if($file != $debug_msg_last_file && $line != $debug_msg_last_line){
            error_log("DEBUG_MSG: [".$line."]./".$file);
            $debug_msg_last_file=$file;
            $debug_msg_last_line=$line;
          }else{
            //error_log("CF7_2_POST: ");
          }
          if (is_array($message) || is_object($message)) {
              error_log("          + ".$prefix.print_r($message, true));
          } else {
              error_log("          + ".$prefix.$message);
          }
      }
  }
} ?>

How to resolve this warning?


问:
Creating an image histogram from a csv
So I have a csv file like this:

```<code>0,0
1,0
2,0
3,0
4,0
...
250,1
251,0
252,0
253,2
254,2
255,9
</code>```

It represents the histogram of a greyscale image. The file indicates that color 255 occurs 9 times, color 250 occurs 1 time, etc.

I read the file in:

```<code>df <- read.csv("/tmp/hist.csv", header= F, dec=",")
</code>```

And then tried to plot it:

```<code>hist(df$V2)
</code>```

the output looks like this:

But what I rather would like to have is to be the colors from 0-255 on the x-axis and the frequency represented by the y-axis. How can I tell R to … turn the axis "around"?

答:
No, hist(df$V2) creates a histogram (count table) of the occurrences of occurrences. So what you're plotting is the same as table(df$V2) (you should confirm this to understand what's going on). I assume this is not what you want.

Instead, I assume you want to plot the distribution of colour occurrences across all 256 colours.

You can do this in base R using barplot:

```<code># Barplot base R
barplot(df[, 2], names.arg = df[, 1]);
</code>```

Or using ggplot2:

```<code># (gg)plot
colnames(df) <- c("colour", "count");
ggplot(df, aes(x = as.factor(colour), y = count)) + geom_bar(stat = "identity");
</code>```

Sample data

```<code># Your sample data
df <- read.csv(text =
    "0,0
     1,0
     2,0
     3,0
     4,0
     250,1
     251,0
     252,0
     253,2
     254,2
     255,9", header = T)
</code>```

Title: Creating an image histogram from a csv

Body:
So I have a csv file like this:

0,0
1,0
2,0
3,0
4,0
...
250,1
251,0
252,0
253,2
254,2
255,9

It represents the histogram of a greyscale image. The file indicates that color 255 occurs 9 times, color 250 occurs 1 time, etc.

I read the file in:

df <- read.csv("/tmp/hist.csv", header= F, dec=",")

And then tried to plot it:

hist(df$V2)

the output looks like this:

But what I rather would like to have is to be the colors from 0-255 on the x-axis and the frequency represented by the y-axis. How can I tell R to … turn the axis "around"?

Body:
No, hist(df$V2) creates a histogram (count table) of the occurrences of occurrences. So what you're plotting is the same as table(df$V2) (you should confirm this to understand what's going on). I assume this is not what you want.

Instead, I assume you want to plot the distribution of colour occurrences across all 256 colours.

You can do this in base R using barplot:

# Barplot base R
barplot(df[, 2], names.arg = df[, 1]);

Or using ggplot2:

# (gg)plot
colnames(df) <- c("colour", "count");
ggplot(df, aes(x = as.factor(colour), y = count)) + geom_bar(stat = "identity");

Sample data

# Your sample data
df <- read.csv(text =
    "0,0
     1,0
     2,0
     3,0
     4,0
     250,1
     251,0
     252,0
     253,2
     254,2
     255,9", header = T)


问:
Pattern for dealing with mapping API objects to UI model objects
I am switching to use the new HttpClient in angular.

The API am calling returns json data in one format. I want to take this data and transform it into a  typescript model class suitable for the UI to work with.

The way I did this before was by using the map function e.g.

```<code>        return this.httpClient.get(url, { headers: headers })
        .map(mapFunction)
        .catch(errorFunction);
</code>```

Where the map function does the heavy lifting of transforming the api response intro a model object e.g.

```<code> const mapFunction =
            (response: Response) => {
                const data = response.json();
                const contacts: Contact[] = [];
                let i = 0;
                for (const result of data.resourceResults) {
                    i = i + 1;
                    const contact: Contact = new Contact();
                    contact.role = result.r
</code>```

To me this seems quite cumbersome and I am basically looking for a way to map objects from the api response type to the ui model type without having to use a custom map function for each request.

答:
I'm completely unfamiliar with angular at the moment, but this should still apply because of typescript.  Sorry for my pseudo-angular code. One of the easiest ways is to map your objects to interfaces.  Thus if I have JSON response:

```<code>{
  Id: 1,
  Name: "Bob",
  Age: 21
}
</code>```

Because of TypeScript I can just create a matching interface:

```<code>export interface IPerson
{
  Id: number,
  Name: string,
  Age: number
}
</code>```

And I can just pass the value around as the interface without having to map value to classes.

```<code>return (this.httpClient.get(url, { headers: headers })) as IPerson;
</code>```

Granted, if you have to extend the JSON this isn't the correct solution.

Body:
I am switching to use the new HttpClient in angular.

The API am calling returns json data in one format. I want to take this data and transform it into a  typescript model class suitable for the UI to work with.

The way I did this before was by using the map function e.g.

        return this.httpClient.get(url, { headers: headers })
        .map(mapFunction)
        .catch(errorFunction);

Where the map function does the heavy lifting of transforming the api response intro a model object e.g.

 const mapFunction =
            (response: Response) => {
                const data = response.json();
                const contacts: Contact[] = [];
                let i = 0;
                for (const result of data.resourceResults) {
                    i = i + 1;
                    const contact: Contact = new Contact();
                    contact.role = result.r

To me this seems quite cumbersome and I am basically looking for a way to map objects from the api response type to the ui model type without having to use a custom map function for each request.

Body:
I'm completely unfamiliar with angular at the moment, but this should still apply because of typescript.  Sorry for my pseudo-angular code. One of the easiest ways is to map your objects to interfaces.  Thus if I have JSON response:

{
  Id: 1,
  Name: "Bob",
  Age: 21
}

Because of TypeScript I can just create a matching interface:

export interface IPerson
{
  Id: number,
  Name: string,
  Age: number
}

And I can just pass the value around as the interface without having to map value to classes.

return (this.httpClient.get(url, { headers: headers })) as IPerson;

Granted, if you have to extend the JSON this isn't the correct solution.


问:
Query to fetch data from two tables using order by and < operator
SQL gurus - I need some help

```<code>Table A ( number , name , subject , col 4 )
Table B ( number , name , subject , col 4 , col 5 etc )
</code>```

For every row in Table A,  I want the following row from table B:

```<code>(a.name = b.name
a.subject = b.subject
b.number < a.number) order by desc and rownum = 1
</code>```

Basically, the row in table B, whose number value is closet to the number value in table A.

```<code>Table A ( 3 rows )
20171208001735 xxx username1
20171208004123 yyy username1
20171209053231 xxx username2

Table B ( n rows )
20171209083227 yyy username2
20171209083216 aaa username2
20171209053142 xxx username2 <---- tag to row 3 from Table A
20171209025647 yyy username1
20171209002611 bbb username1
20171209002609 ccc username1
20171208002602 yyy username1 <---- tag to row 2 from table A
20171209002315 ddd username1
20171209002302 ggg username1
20171208001523 xxx username1 <---- tag to row 1 from table A
20171209001806 zzz username1
</code>```

Thanks

答:
One approach here is to perform the join between the two tables using the conditions you mentioned, and then introduce ROW_NUMBER to find the single record of interest for each record in table A.  The criteria for the match, since the A number is strictly greater than the B number, is that we want the highest number from the B table.  So the ordering in ROW_NUMBER is given by the B number in descending order.

```<code>SELECT *     -- this can be replaced with an actual list of columns you want
FROM
(
    SELECT a.*, b.*,
        ROW_NUMBER() OVER (PARTITION BY a.name, a.subject ORDER BY b.number DESC) rn
    FROM tableA a
    LEFT JOIN tableB b
        ON a.name = b.name AND
           a.subject = b.subject AND
           a.number > b.number
) t
WHERE t.rn = 1;
</code>```

Body:
SQL gurus - I need some help

Table A ( number , name , subject , col 4 )
Table B ( number , name , subject , col 4 , col 5 etc )

For every row in Table A,  I want the following row from table B:

(a.name = b.name
a.subject = b.subject
b.number < a.number) order by desc and rownum = 1

Basically, the row in table B, whose number value is closet to the number value in table A.

Table A ( 3 rows )
20171208001735 xxx username1
20171208004123 yyy username1
20171209053231 xxx username2

Table B ( n rows )
20171209083227 yyy username2
20171209083216 aaa username2
20171209053142 xxx username2 <---- tag to row 3 from Table A
20171209025647 yyy username1
20171209002611 bbb username1
20171209002609 ccc username1
20171208002602 yyy username1 <---- tag to row 2 from table A
20171209002315 ddd username1
20171209002302 ggg username1
20171208001523 xxx username1 <---- tag to row 1 from table A
20171209001806 zzz username1

Thanks

Body:
One approach here is to perform the join between the two tables using the conditions you mentioned, and then introduce ROW_NUMBER to find the single record of interest for each record in table A.  The criteria for the match, since the A number is strictly greater than the B number, is that we want the highest number from the B table.  So the ordering in ROW_NUMBER is given by the B number in descending order.

SELECT *     -- this can be replaced with an actual list of columns you want
FROM
(
    SELECT a.*, b.*,
        ROW_NUMBER() OVER (PARTITION BY a.name, a.subject ORDER BY b.number DESC) rn
    FROM tableA a
    LEFT JOIN tableB b
        ON a.name = b.name AND
           a.subject = b.subject AND
           a.number > b.number
) t
WHERE t.rn = 1;


问:
How to write to a text file without having repeating data on lines?
Okay so basically I'm trying to access a text file that contains data like this:

```<code>John 01
Steve 02
Adam 15
</code>```

I'm accessing it, splitting the integers from each line and subtracting one from each one in the variable "days". Then after subtracting one from each line, I'm running an if statment to see if any line contains "0", if the line contains 0 it should remove the entire line (number and name), and then reprint the names with the new days - 1. My code below runs perfectly in console, and the names print out perfectly, as well as deleting, I'm just having trouble with the fact that each line is printing the last days value instead of it's own. For example:

```<code>Steve 14
Adam 14
</code>```

Although Steve should be on 01, he took adam's 14. My code is attached below:

```<code>global days
global names
with open('tracker.txt', 'r') as f:
    for line in f:
        days = line.strip()[-2:]
        names = line.strip()[:-3]
        days = int(days) - 1
        print(names +" "+str(days))

        if days == 0:
            f = open("tracker.txt","r")
            lines = f.readlines()
            f.close()
            f = open("tracker.txt","w")
            for line in lines:
                if line!=str(names)+ " 01" +"\n":
                    f.write(line[:-3]+ "" + str(days) + "\n")
            f.close()
    f.close()
</code>```

答:
OK. I'm not sure I understand what you are trying to do but let's try:

```<code>import os

# The file name of our source file and the temporary file where we keep
# our filtered data before copying back over source file
source_file_name = 'tracker.txt'
temporary_file_name = 'tracker_temp.txt'

# Opening the source file using a context manager
with open(source_file_name, mode='r') as source_file:
    # Opening our temporary file where we will be writing
    with open(temporary_file_name, mode='w') as temporary_file:
        # Reading each line of the source file
        for current_line in source_file:
            # Extracting the information from our source file
            line_splitted = current_line.split()
            current_name = line_splitted[0]
            current_days = int(line_splitted[1])

            # Computing and print the result
            future_days = current_days - 1
            print(current_name, future_days)

            # Writing the name and the computed value
            # to the temporary file
            if future_days != 0:
                output_line = "{} {:02}\n".format(current_name, future_days)
                temporary_file.write(output_line)

# After we went through all the data in the source file
# we replace our source file with our temporary file
os.replace(temporary_file_name, source_file_name)
</code>```

So tell me. Is that what's you were trying to do? No? Well then give us more details!

Body:
Okay so basically I'm trying to access a text file that contains data like this:

John 01
Steve 02
Adam 15

I'm accessing it, splitting the integers from each line and subtracting one from each one in the variable "days". Then after subtracting one from each line, I'm running an if statment to see if any line contains "0", if the line contains 0 it should remove the entire line (number and name), and then reprint the names with the new days - 1. My code below runs perfectly in console, and the names print out perfectly, as well as deleting, I'm just having trouble with the fact that each line is printing the last days value instead of it's own. For example:

Steve 14
Adam 14

Although Steve should be on 01, he took adam's 14. My code is attached below:

global days
global names
with open('tracker.txt', 'r') as f:
    for line in f:
        days = line.strip()[-2:]
        names = line.strip()[:-3]
        days = int(days) - 1
        print(names +" "+str(days))

        if days == 0:
            f = open("tracker.txt","r")
            lines = f.readlines()
            f.close()
            f = open("tracker.txt","w")
            for line in lines:
                if line!=str(names)+ " 01" +"\n":
                    f.write(line[:-3]+ "" + str(days) + "\n")
            f.close()
    f.close()

Body:
OK. I'm not sure I understand what you are trying to do but let's try:

import os

# The file name of our source file and the temporary file where we keep
# our filtered data before copying back over source file
source_file_name = 'tracker.txt'
temporary_file_name = 'tracker_temp.txt'

# Opening the source file using a context manager
with open(source_file_name, mode='r') as source_file:
    # Opening our temporary file where we will be writing
    with open(temporary_file_name, mode='w') as temporary_file:
        # Reading each line of the source file
        for current_line in source_file:
            # Extracting the information from our source file
            line_splitted = current_line.split()
            current_name = line_splitted[0]
            current_days = int(line_splitted[1])

            # Computing and print the result
            future_days = current_days - 1
            print(current_name, future_days)

            # Writing the name and the computed value
            # to the temporary file
            if future_days != 0:
                output_line = "{} {:02}\n".format(current_name, future_days)
                temporary_file.write(output_line)

# After we went through all the data in the source file
# we replace our source file with our temporary file
os.replace(temporary_file_name, source_file_name)

So tell me. Is that what's you were trying to do? No? Well then give us more details!


问:
Java Complex Sorting
I am stuck in that I have an Object Book that got three variables

```<code>String title
int Year
String authorName
</code>```

I must sort the books by one, two or all three of the variables in ascending or descending order, I implemented the title ordering but I am stuck as to what to do when people choose more than one variable to order.

Here is some of my code:

Book Class:

```<code>import java.util.ArrayList;

public class Book{

String title;
String authorName;
int editionYear;

public Book(String title, String authorName, int editionYear){
    this.title = title;
    this.authorName = authorName;
    this.editionYear = editionYear;

}

public String getBookInfo(){

    ArrayList bookInfo = new ArrayList();
    bookInfo.add(this.title);
    bookInfo.add(this.authorName);
    bookInfo.add(this.editionYear);
    return bookInfo.toString();
}

}
</code>```

BookSorter Class:

```<code>import java.util.Arrays;
import java.util.Comparator;

public class BookSorter{

private String sortkey;
private String order;
Book[] Books;

public BookSorter(Book Book1, Book Book2, Book Book3, Book Book4){
    this.Books = new Book[] {Book1, Book2, Book3, Book4};
}

public Book[] sortByTitle(boolean sortorder){
    Comparator<Book> byTitle = new TitleComparator(sortorder);
    Arrays.sort(Books, byTitle);
    for(int i=0;i<4;i++) System.out.println(Books[i].title);
    return Books;
}
}
</code>```

TitleComparator:

```<code>import java.util.Comparator;

class TitleComparator implements Comparator<Book> {

boolean ascending;

public TitleComparator(boolean ascending){
    this.ascending = ascending;
}

public int compare(Book Book1, Book Book2){
    if(ascending == true){
        if(Book1.title.compareToIgnoreCase(Book2.title) > 0) return 1;
        else if(Book1.title.compareToIgnoreCase(Book2.title) < 0) return -1;
        else return 0;
    }else{
        if(Book2.title.compareToIgnoreCase(Book1.title) < 0) return -1;
        else if(Book2.title.compareToIgnoreCase(Book1.title) > 0) return 1;
        else return 0;
    }
}
}
</code>```

I though I could work a little more on the comparator but I am really stuck on how to model such a thing, Thanks in advance

答:
This sounds like a homework problem. So I am going to provide you with some hints.</p>

```<code>1. First see if Title1==Title2.
    1.1 if YES then see if year1==year2
            1.1.1 if YES then see if authorName1==authorName2
              1.1.1.1 If YES then they are equal (return 0)
              1.1.1.2 else if NO compare author1 and author2 (return 1 or -1)
     1.2 else if NO then compare year1 and year2 (return 1 or -1)
2. else if NO then compare title1 and title2 (return 1 or -1)
</code>```

Title: Java Complex Sorting

Body:
I am stuck in that I have an Object Book that got three variables

String title
int Year
String authorName

I must sort the books by one, two or all three of the variables in ascending or descending order, I implemented the title ordering but I am stuck as to what to do when people choose more than one variable to order.

Here is some of my code:

Book Class:

import java.util.ArrayList;

public class Book{

String title;
String authorName;
int editionYear;

public Book(String title, String authorName, int editionYear){
    this.title = title;
    this.authorName = authorName;
    this.editionYear = editionYear;

}

public String getBookInfo(){

    ArrayList bookInfo = new ArrayList();
    bookInfo.add(this.title);
    bookInfo.add(this.authorName);
    bookInfo.add(this.editionYear);
    return bookInfo.toString();
}

}

BookSorter Class:

import java.util.Arrays;
import java.util.Comparator;

public class BookSorter{

private String sortkey;
private String order;
Book[] Books;

public BookSorter(Book Book1, Book Book2, Book Book3, Book Book4){
    this.Books = new Book[] {Book1, Book2, Book3, Book4};
}

public Book[] sortByTitle(boolean sortorder){
    Comparator<Book> byTitle = new TitleComparator(sortorder);
    Arrays.sort(Books, byTitle);
    for(int i=0;i<4;i++) System.out.println(Books[i].title);
    return Books;
}
}

TitleComparator:

import java.util.Comparator;

class TitleComparator implements Comparator<Book> {

boolean ascending;

public TitleComparator(boolean ascending){
    this.ascending = ascending;
}

public int compare(Book Book1, Book Book2){
    if(ascending == true){
        if(Book1.title.compareToIgnoreCase(Book2.title) > 0) return 1;
        else if(Book1.title.compareToIgnoreCase(Book2.title) < 0) return -1;
        else return 0;
    }else{
        if(Book2.title.compareToIgnoreCase(Book1.title) < 0) return -1;
        else if(Book2.title.compareToIgnoreCase(Book1.title) > 0) return 1;
        else return 0;
    }
}
}

I though I could work a little more on the comparator but I am really stuck on how to model such a thing, Thanks in advance

Body:
This sounds like a homework problem. So I am going to provide you with some hints.

1. First see if Title1==Title2.
    1.1 if YES then see if year1==year2
            1.1.1 if YES then see if authorName1==authorName2
              1.1.1.1 If YES then they are equal (return 0)
              1.1.1.2 else if NO compare author1 and author2 (return 1 or -1)
     1.2 else if NO then compare year1 and year2 (return 1 or -1)
2. else if NO then compare title1 and title2 (return 1 or -1)


问:
Xamarin.Forms UWP with .NetStandard 2.0 and null resources
We are currently moving our Xamarin projects from PCL to .Net Standard 2.0, also core library project format. Most things works well. We use resx-files in the core project for localization. This works fine on iOS and Android.

On UWP I get null as value, if I try to access the string ressources

```<code>var buttonText = AppResources.Cancel; // => null
</code>```

The PCL version the same code worked well. Is there some initialization needed?

On debug I can see that the resource manager has a null ResourceSet, but _WinRTResourceManager is filled.

答:
Finally I found the reason.

By converting PCL library to .Net Standar normally the file AssemblyInfo.cs is not there. So the neutral language definition get lost.

We use German (de-DE) as default language. As soon as I change the default langugage in Package.appxmanifest from the default value en-US to de-DE the resources from .Net Standard library could not be read.

The fix is, to define explixit the NeutralResourcesLanguage for the .Net Standard library (to the same as UWP project). This can be done in manually created AssemblyInfo.cs (do not forget to turn off auto generation of AssemblyInfo) or declare this info in one of the exsisting classes with [assembly: NeutralResourcesLanguage("de-DE")].

After this fix the resources from .Net Standard library are used correctly also in UWP.

Body:
We are currently moving our Xamarin projects from PCL to .Net Standard 2.0, also core library project format. Most things works well. We use resx-files in the core project for localization. This works fine on iOS and Android.

On UWP I get null as value, if I try to access the string ressources

var buttonText = AppResources.Cancel; // => null

The PCL version the same code worked well. Is there some initialization needed?

On debug I can see that the resource manager has a null ResourceSet, but _WinRTResourceManager is filled.


问:
Dash Streaming fails as new segments are not being downloaded
I am trying to perform live dash streaming on chrome cast using the google media player.The stream starts off just fine.There after it downloads around 20 seconds worth of data and plays, but no more segment requests are generated.After this it autoPauses dues to Underflow.Once underflow is detected the segments are requested and playback can only be resumed after getting about 20 seconds worth of data.

Even after downloading a few segments(less than 20 seconds worth), the    player continues to detect underflow. In other words playback does not occur while segments are downloaded.

2.Requests for download are not created during playback(after the first 20 sec).

So the whole process seems like download 20 seconds - play - pause - download - play - etc.

autoPauseDuration is 1 second

autoResumeDuration is 2 seconds

autoResumeNumberOfSegments is 2

The same live source is tested on chrome cast using another player and works successfully.

答:
The issue was fixed by adding a parameter to the manifest.

```<code>MPD@mediaPresentationDuration
</code>```

But some other player have played the content from same manifest without any trouble.

Body:
The issue was fixed by adding a parameter to the manifest.

MPD@mediaPresentationDuration

But some other player have played the content from same manifest without any trouble.


问:
What should be the order of filters in query to optimize queries to use Indexing
I have few doubts. I have heard from some of my colleagues that, if we have created composite Nonclustured index on following table order of all the filters should be in order of Indexed column then Filter.

MyTable (T1, T2, T3, T4, T5)

  Non
  Clustured index(T1, T2) in the order
  T1 then T2

Questions

Which of the queries works faster ?

Does order of Indexed column affects
performance ?

Should Indexed Columns
come first to optimize queries ?

What is the order of processing a
query. Which filter is taken first
while processing a query ? Does it
starts from Last filter and goes on
to first filter ?

Query 1

```<code>Select * from MyTable WHERE T1=1 AND T2=2 AND T3=1
--(Indexing will be used) Fastest as T3 has been included after indexed columns
</code>```

Query 2

```<code>Select * from MyTable WHERE T2=1 AND T1=2 AND T3=1
--(No Indexing will be used)
</code>```

Query 3

```<code>Select * from MyTable WHERE T3=1 AND T1=1 AND T2=2
--(Indexing will be used) slower than Query 1 as indexed columns included afterwards
</code>```

Query 4

```<code>Select * from MyTable WHERE T3=1 AND T2=1 AND T1=2
--(No Indexing will be used) slower than Query 2 as indexed columns occurs after non indexed column condition
</code>```

EDIT :

Query 5

```<code>Select * from MyTable WHERE T3=1 AND T2=1
</code>```

Query 6

```<code>Select * from MyTable WHERE T3=1 AND T1=1
</code>```

Query 7

```<code>Select * from MyTable WHERE T3=1 AND T2=1 OR T1=2
</code>```

Query 8

What does the following order in SSMS index creation means i.e. which filter should come first ?

When I tried to shuffle the order of columns shown in index columns. I saw Bookmark lookups were increasing and Clustured index scan was being used.
But when I uses the same order as shown in image. Then bookmark lookup got removed and also got Index Seek. So I can see order of Columns in index is playing some vital role here but could not sense how.

答:
Q8 (not numbered) What does the following order in SSMS index creation means i.e. which filter should come first ?

The order of index creation has nothing to do with which index will be used.  The indexes, once created, just sit alongside the table data in index pages ready for use whenever it suits the query, whichever suits best rather than which was created first (chronologically).

Q   1.     Which of the queries works faster ?

The order of the OR clauses in the query does not matter.  SQL Server will inspect all of them and use whatever index it can so all your first 4 queries will use exactly the same plan, therefore the same performance.

Q   2.      Does order of Indexed column affects performance ?

Not in the query, but it does if you are creating a composite index.  Index on (A,B) will be good for queries that involve A, cannot (normally) be used for queries that involve B only.  Index on (B,A) first groups by B, then by A in the index pages, so a query Where A=1 cannot use it.  There are some special cases such as when the query only needs A and B in either SELECT/JOIN/WHERE clauses, so it may still use the index on (B,A) because it is easier to collect than the clustered key.

Q   3.      Should Indexed Columns come first to optimize queries ?

Same as answer to 1.

Q   4.      What is the order of processing a query. Which filter is taken first while processing a query ? Does it starts from Last filter and goes on to first filter ?

Same as answer to 1.

For EDITed questions 5-7

Q7 is the only one that is different.  The others involve a straight AND, so the condition is agnostic to the order of the fields.  The last one actually has two groups of conditions (A and B) or (C), so an index on both (A,B) and/or index on (C) will be used, if they are selective enough (will filter the data to a sufficiently smaller subset).  If both indexes exist, two result streams may be collected and compared (hash/merge) to result in the final output.

Body:
I have few doubts. I have heard from some of my colleagues that, if we have created composite Nonclustured index on following table order of all the filters should be in order of Indexed column then Filter.

MyTable (T1, T2, T3, T4, T5)

  Non
  Clustured index(T1, T2) in the order
  T1 then T2

Questions

Which of the queries works faster ?

Does order of Indexed column affects
performance ?

Should Indexed Columns
come first to optimize queries ?

What is the order of processing a
query. Which filter is taken first
while processing a query ? Does it
starts from Last filter and goes on
to first filter ?

Query 1

Select * from MyTable WHERE T1=1 AND T2=2 AND T3=1
--(Indexing will be used) Fastest as T3 has been included after indexed columns

Query 2

Select * from MyTable WHERE T2=1 AND T1=2 AND T3=1
--(No Indexing will be used)

Query 3

Select * from MyTable WHERE T3=1 AND T1=1 AND T2=2
--(Indexing will be used) slower than Query 1 as indexed columns included afterwards

Query 4

Select * from MyTable WHERE T3=1 AND T2=1 AND T1=2
--(No Indexing will be used) slower than Query 2 as indexed columns occurs after non indexed column condition

EDIT :

Query 5

Select * from MyTable WHERE T3=1 AND T2=1

Query 6

Select * from MyTable WHERE T3=1 AND T1=1

Query 7

Select * from MyTable WHERE T3=1 AND T2=1 OR T1=2

Query 8

What does the following order in SSMS index creation means i.e. which filter should come first ?

When I tried to shuffle the order of columns shown in index columns. I saw Bookmark lookups were increasing and Clustured index scan was being used.
But when I uses the same order as shown in image. Then bookmark lookup got removed and also got Index Seek. So I can see order of Columns in index is playing some vital role here but could not sense how.


问:
sed or awk command to merge two line into a single line
I have a text file with the following format.

12345

abcdefg

I need this to be in the same line. So the output should look like this...

12345 abcdefg

How should i proceed ? using sed or awk ?

答:
If you want to join every line[i] and line[i+1] with a space,
you could use paste:

```<code>paste -d' ' - - < file
</code>```

Body:
If you want to join every line[i] and line[i+1] with a space,
you could use paste:

paste -d' ' - - < file


问:
Check if there is someone logged in Django
I have a new django project I am working on. I am integrating Djangos user login and logout service that comes with the framework. I have a view and within the view, I want to check and see if there is a user object in the request.user. if there is not, I want to redirect to login page. If there is a user in the request.user, I want to display the users home page. how can I do this. Here is my code:

```<code>def home(request):
    if not request.user:
        return redirect('login')
    else:
        User = request.user
        profile = Profile.objects.get(user = User)
        parameters = {
            'user':User,
            'profile':profile,
        }
        return render(request, 'user/home.html', parameters)
</code>```

It works if there is a user logged in but doesnt work if there is no user logged in...

答:
```<code>def home(request):
    if not request.user.is_authenticated:
        return redirect('login')
    else:
        User = request.user
        profile = Profile.objects.get(user = User)
        parameters = {
            'user':User,
            'profile':profile,
        }
        return render(request, 'user/home.html', parameters)
</code>```

you need to check whether the user is authenticated or not, if you check request.user django will return anonymous user as default

Body:
I have a new django project I am working on. I am integrating Djangos user login and logout service that comes with the framework. I have a view and within the view, I want to check and see if there is a user object in the request.user. if there is not, I want to redirect to login page. If there is a user in the request.user, I want to display the users home page. how can I do this. Here is my code:

def home(request):
    if not request.user:
        return redirect('login')
    else:
        User = request.user
        profile = Profile.objects.get(user = User)
        parameters = {
            'user':User,
            'profile':profile,
        }
        return render(request, 'user/home.html', parameters)

It works if there is a user logged in but doesnt work if there is no user logged in...

Body:
def home(request):
    if not request.user.is_authenticated:
        return redirect('login')
    else:
        User = request.user
        profile = Profile.objects.get(user = User)
        parameters = {
            'user':User,
            'profile':profile,
        }
        return render(request, 'user/home.html', parameters)

you need to check whether the user is authenticated or not, if you check request.user django will return anonymous user as default


问:
How to trigger method in controller when element is clicked in view for Rails?
The drop down list elements that I want to click on are

```<code><select class="store-select">
  <option value="" selected="selected">Please select</option>
  <option value="1">Administrator</option>
  <option value="2">User</option>
  <option value="3">Editor</option>
</select>
</code>```

And I want it to trigger an action in the controller based on the option that was clicked.  So one of the things I'm hoping to learn is how to access that value in the controller.  I also want to redirect the page after an option is clicked.  I'm able to redirect the page when other links are clicked in my view, but when I click on an element in the drop down list, it doesn't redirect.  It doesn't even go to the view for that method.  When an element in the drop down list is clicked it just stays on the current page.

```<code>def practice  # the redirect doesn't work in this method but works in others
    # redirect_to "https://tosbourn.com"
    render "ibotta/show"
end
</code>```

My application.js file looks as the following

```<code>$('.store-select').on('change', function() {
  $.ajax({
    url : '/users',
    type : 'GET',
    data : { user_id: this.value },
    dataType:'script'
  });
})
</code>```

My routes.rb file contains the following

```<code>get 'users' => 'smiths#practice'
</code>```

Let me know if there is anything I'm missing that you want to know about this problem.  Thank you.

答:
if you are using ruby on rails then you can do this one short line for example: -

```<code><%your_options = [['Please select', ''],['Administrator','1'],['User','2'],['Editor','3']]%>

<%= select_tag "store-selects", options_for_select(your_options),:onchange => "self.location='/users/'+this.options[this.selectedIndex].value", class: "your_class" %>
</code>```

and your routes should be

```<code>get 'users/:id' => 'smiths#practice'
</code>```

thank you.

Body:
The drop down list elements that I want to click on are

<select class="store-select">
  <option value="" selected="selected">Please select</option>
  <option value="1">Administrator</option>
  <option value="2">User</option>
  <option value="3">Editor</option>
</select>

And I want it to trigger an action in the controller based on the option that was clicked.  So one of the things I'm hoping to learn is how to access that value in the controller.  I also want to redirect the page after an option is clicked.  I'm able to redirect the page when other links are clicked in my view, but when I click on an element in the drop down list, it doesn't redirect.  It doesn't even go to the view for that method.  When an element in the drop down list is clicked it just stays on the current page.

def practice  # the redirect doesn't work in this method but works in others
    # redirect_to "https://tosbourn.com"
    render "ibotta/show"
end

My application.js file looks as the following

$('.store-select').on('change', function() {
  $.ajax({
    url : '/users',
    type : 'GET',
    data : { user_id: this.value },
    dataType:'script'
  });
})

My routes.rb file contains the following

get 'users' => 'smiths#practice'

Let me know if there is anything I'm missing that you want to know about this problem.  Thank you.

Body:
if you are using ruby on rails then you can do this one short line for example: -

<%your_options = [['Please select', ''],['Administrator','1'],['User','2'],['Editor','3']]%>

<%= select_tag "store-selects", options_for_select(your_options),:onchange => "self.location='/users/'+this.options[this.selectedIndex].value", class: "your_class" %>

and your routes should be

get 'users/:id' => 'smiths#practice'

thank you.


问:
Using C# to add columns to SQL server database not working
Whenever I call this function to run this query....

```<code>  public static void AddUsernameAndPassword()
    {

        SqlConnection connection = MedicalDB.EstConnection();
        connection.Open();

        string alterStatement = "ALTER TABLE PATIENT_TBL ADD USER_NAME VARCHAR(50) NULL," +
                                " PASSWORD VARCHAR(50) NULL";

        SqlCommand alterCommand =
            new SqlCommand(alterStatement, connection);
        alterCommand.ExecuteNonQuery();
        connection.Close();
    }
</code>```

through here

```<code> private void loginButton_Click(object sender, EventArgs e)
    {
        PatientDB.AddUsernameAndPassword();
        //getPatient(1);

        passTextBox.Text = patient.userName;

    }
</code>```

It tells me

Invalid column name 'USER_NAME'.

The properties are set accordingly. Please advise.

答:
Your SQL command seems correct.
So, check whether your connection is established.
Also, I think it has already created a column in that name.

But, why to add a new column to the DB everytime you click on the button.
You could first initialize the columns in the constructor like an Init(), and then you could insert values to it every time you click on the button.

Body:
Whenever I call this function to run this query....

  public static void AddUsernameAndPassword()
    {

        SqlConnection connection = MedicalDB.EstConnection();
        connection.Open();

        string alterStatement = "ALTER TABLE PATIENT_TBL ADD USER_NAME VARCHAR(50) NULL," +
                                " PASSWORD VARCHAR(50) NULL";

        SqlCommand alterCommand =
            new SqlCommand(alterStatement, connection);
        alterCommand.ExecuteNonQuery();
        connection.Close();
    }

through here

 private void loginButton_Click(object sender, EventArgs e)
    {
        PatientDB.AddUsernameAndPassword();
        //getPatient(1);

        passTextBox.Text = patient.userName;

    }

It tells me

Invalid column name 'USER_NAME'.

The properties are set accordingly. Please advise.


问:
How to read images from MySQL database using PHP?
How to read images from MySQL database using PHP?

If the images are stored in a BLOB in the database, how to use the binary data that I get and turn it into an image using src in
 or using the CSS property background-image?

Thanks.

答:
What you should probably do, if storing images as BLOBs, is provide a URL that calls your script in a way that it can determine what image to return.

Use that URL as the src, or background-image: url(...) and in the script, read the BLOB from the database in to a variable.

Then output the variable after appropriate header information, telling the browser it is to receive an image, for instance:

```<code>header('Content-Type: image/jpeg');
</code>```

Sending a Content-Length header and sensible information on caching/expiry would also be wise.

NB. Having said all that, I tend to be wary of using BLOBs in databases, they tend to cripple performance.  When I want to store images, I store then in some directory structure and reference them in the database in some fashion.

Body:
What you should probably do, if storing images as BLOBs, is provide a URL that calls your script in a way that it can determine what image to return.

Use that URL as the src, or background-image: url(...) and in the script, read the BLOB from the database in to a variable.

Then output the variable after appropriate header information, telling the browser it is to receive an image, for instance:

header('Content-Type: image/jpeg');

Sending a Content-Length header and sensible information on caching/expiry would also be wise.

NB. Having said all that, I tend to be wary of using BLOBs in databases, they tend to cripple performance.  When I want to store images, I store then in some directory structure and reference them in the database in some fashion.