问:
Select 3 random Words (records) - one of each letter count
I have a table with lots of words and also a field that holds the number of letters for each word.

EDIT: The example data set below is just showing the table layout - there are 65,000 rows of all combinations of lengths.

```<code>word_id,word,letter_count
54908,swanage,7
37338,natured,7
61637,untwisting,10
</code>```

I am trying to select three random words making sure there is one that is 4 letters, one that is 7 letters and one that is 10.

My SQL query is below.

```<code>SELECT * FROM password
WHERE letter_count = 4 OR letter_count = 7 OR letter_count = 10
ORDER BY RAND()
LIMIT 3
</code>```

The above will return 3 random records but may have any combination of 4, 7 or 10 letters.

Can anyone help?

Thanks,

John

答:
```<code>DROP TABLE IF EXISTS my_table;

CREATE TABLE my_table
(word_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY
,word VARCHAR(20) NOT NULL UNIQUE
);

INSERT INTO my_table VALUES
(1,'swanage'),
(2,'natured'),
(3,'untwisting'),
(4,'four'),
(5,'five'),
(6,'fifteen'),
(7,'blacksmith');

SELECT *
  FROM
     ( SELECT * FROM my_table WHERE CHAR_LENGTH(word) = 4 ORDER BY RAND() LIMIT 1 ) x
 UNION
     ( SELECT * FROM my_table WHERE CHAR_LENGTH(word) = 7 ORDER BY RAND() LIMIT 1 )
 UNION
     ( SELECT * FROM my_table WHERE CHAR_LENGTH(word) = 10 ORDER BY RAND() LIMIT 1) ;

+---------+------------+
| word_id | word       |
+---------+------------+
|       4 | four       |
|       1 | swanage    |
|       3 | untwisting |
+---------+------------+
</code>```

Body:
I have a table with lots of words and also a field that holds the number of letters for each word.

EDIT: The example data set below is just showing the table layout - there are 65,000 rows of all combinations of lengths.

word_id,word,letter_count
54908,swanage,7
37338,natured,7
61637,untwisting,10

I am trying to select three random words making sure there is one that is 4 letters, one that is 7 letters and one that is 10.

My SQL query is below.

SELECT * FROM password
WHERE letter_count = 4 OR letter_count = 7 OR letter_count = 10
ORDER BY RAND()
LIMIT 3

The above will return 3 random records but may have any combination of 4, 7 or 10 letters.

Can anyone help?

Thanks,

John


来源: stackexchange

问:
Function ord works only sometimes but sometimes not
I am trying to programm some kind of Caesar Cipher in Cobol. But somehow I get the following compile error:

Numeric function "INTEGER FUNCTION ORD" was not allowed in this context.

This error gets fired here (both lines)

```<code> 000048                  MOVE FUNCTION ORD("A") TO a
 000049                  display function ord("A")
</code>```

But NOT here

```<code> 000054                MOVE FUNCTION CHAR(FUNCTION MOD(
 000055                    FUNCTION ORD(outstring (i:1))
 000056                        - a + offset, 26) + a)
 000057                TO outstring (i:1)
</code>```

i is the position of the outstring we are looking at. a is the value of "a" or of "A" needed to make sure we stay in the 26 letters, defined as

```<code> 000018            03 a    pic S9(3).
</code>```

Where is the difference? Why does the second work and the first not?

答:
The second example works and the first doesn't because you're allowed to have numeric expressions as function arguments but you can't have numeric expressions as the subject of a MOVE statement. In your case, your compiler (IBM?) considers a numeric intrinsic function call to be a numeric expression. So you need to replace the MOVE with COMPUTE and change the function call in the DISPLAY to a.

```<code>000048                  COMPUTE a = FUNCTION ORD("A")
000049                  DISPLAY a
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to programm some kind of Caesar Cipher in Cobol. But somehow I get the following compile error:

Numeric function "INTEGER FUNCTION ORD" was not allowed in this context.

This error gets fired here (both lines)

 000048                  MOVE FUNCTION ORD("A") TO a
 000049                  display function ord("A")

But NOT here

 000054                MOVE FUNCTION CHAR(FUNCTION MOD(
 000055                    FUNCTION ORD(outstring (i:1))
 000056                        - a + offset, 26) + a)
 000057                TO outstring (i:1)

i is the position of the outstring we are looking at. a is the value of "a" or of "A" needed to make sure we stay in the 26 letters, defined as

 000018            03 a    pic S9(3).

Where is the difference? Why does the second work and the first not?

Body:
The second example works and the first doesn't because you're allowed to have numeric expressions as function arguments but you can't have numeric expressions as the subject of a MOVE statement. In your case, your compiler (IBM?) considers a numeric intrinsic function call to be a numeric expression. So you need to replace the MOVE with COMPUTE and change the function call in the DISPLAY to a.

000048                  COMPUTE a = FUNCTION ORD("A")
000049                  DISPLAY a


问:
Onelogin SAML with AWS load balancer
I am trying to get OneLogin Saml authentication working on my live servers and am running into a problem with my AWS load balancer setup. I think the problem is that I have a classic load balancer which is listening on both port 80 and 443 with a AWS wildcard HTTPS certificate. The load balancer forwards both ports to port 80 on my servers and adds the HTTP_X_FORWARDED_PROTO headers.

When I use my normal dev server (not behind load balancer) the SAML authentication works fine. I am getting a proper response back. But when I push to live the SAML response returns an empty POST dictionary without RELAY STATE.

Any idea why the POST would be empty?

My setup is:

Python social auth with the SAML connector

Works fine on Dev server

When I use my live servers behind the firewall, the response is empty

I suspect it has something to do with my SSL certificate or my load balancer forwarding the 443 to the server on port 80 with the additional header. I tried fixing this by creating the auth request by analyzing the forwarded headers:

```<code>def _create_saml_auth(self, idp):
    """Get an instance of OneLogin_Saml2_Auth"""

    config = self.generate_saml_config(idp)
    request_info = {
        'https': 'on' if self.strategy.request_is_secure() else 'off',
        'http_host': self.strategy.request_host(),
        'script_name': self.strategy.request_path(),
        'server_port': self.strategy.request_port(),
        'get_data': self.strategy.request_get(),
        'post_data': self.strategy.request_post(),
    }

    if 'HTTP_X_FORWARDED_PROTO' in self.strategy.request.META:
        request_info['https'] = 'on' if self.strategy.request.META.get('HTTP_X_FORWARDED_PROTO') == 'https' else 'off'
        request_info['server_port'] = self.strategy.request.META.get('HTTP_X_FORWARDED_PORT')
</code>```

But that still does return the empyy POST dictionary on the SAML response from Onelogin. The intial url is generated properly with HTTPS on though.

Has anyone had a similar issue. I am stuck and would love to get Onelogin to work.

Thanks so much for your time.

Cheers,

Phil

答:
You can check what's in the errors. i'm using code like this:

```<code>    auth = OneLogin_Saml2_Auth(saml_req, saml_settings)
    auth.process_response()

    if not auth.is_authenticated():
        error = auth.get_last_error_reason() # here's the error message
</code>```

i'm guessing you are bumping into the same issue with the ELB that i was, which will go something like Authentication error: The response was received at http://... instead of https://...

The solution is either to perform a https->https redirect, or to make pysaml think it received the response on https. Here's how i did it (in this case in a django app, but should be easy enough to modify for other environments):

```<code>    saml_req = {
        'http_host': request.META['HTTP_HOST'],
        'server_port': request.META['SERVER_PORT'],
        'script_name': request.META['PATH_INFO'],
        'get_data': request.GET.copy(),
        'post_data': request.POST.copy()
    }

    if settings.SAML_FUDGE_HTTPS:  # made a settings flag so it can be toggled
        saml_req['https'] = True  # this one forces https in the check url
        saml_req['server_port'] = None  # this one removes the port number (80)

    auth = OneLogin_Saml2_Auth(saml_req, saml_settings)
    auth.process_response()
</code>```

Update: as @smartin mentions in the comment - you might be able to sniff out HTTP_X_FORWARDED_FOR header and avoid creating a settings var

Title: Onelogin SAML with AWS load balancer

Body:
I am trying to get OneLogin Saml authentication working on my live servers and am running into a problem with my AWS load balancer setup. I think the problem is that I have a classic load balancer which is listening on both port 80 and 443 with a AWS wildcard HTTPS certificate. The load balancer forwards both ports to port 80 on my servers and adds the HTTP_X_FORWARDED_PROTO headers.

When I use my normal dev server (not behind load balancer) the SAML authentication works fine. I am getting a proper response back. But when I push to live the SAML response returns an empty POST dictionary without RELAY STATE.

Any idea why the POST would be empty?

My setup is:

Python social auth with the SAML connector

Works fine on Dev server

When I use my live servers behind the firewall, the response is empty

I suspect it has something to do with my SSL certificate or my load balancer forwarding the 443 to the server on port 80 with the additional header. I tried fixing this by creating the auth request by analyzing the forwarded headers:

def _create_saml_auth(self, idp):
    """Get an instance of OneLogin_Saml2_Auth"""

    config = self.generate_saml_config(idp)
    request_info = {
        'https': 'on' if self.strategy.request_is_secure() else 'off',
        'http_host': self.strategy.request_host(),
        'script_name': self.strategy.request_path(),
        'server_port': self.strategy.request_port(),
        'get_data': self.strategy.request_get(),
        'post_data': self.strategy.request_post(),
    }

    if 'HTTP_X_FORWARDED_PROTO' in self.strategy.request.META:
        request_info['https'] = 'on' if self.strategy.request.META.get('HTTP_X_FORWARDED_PROTO') == 'https' else 'off'
        request_info['server_port'] = self.strategy.request.META.get('HTTP_X_FORWARDED_PORT')

But that still does return the empyy POST dictionary on the SAML response from Onelogin. The intial url is generated properly with HTTPS on though.

Has anyone had a similar issue. I am stuck and would love to get Onelogin to work.

Thanks so much for your time.

Cheers,

Phil

Body:
You can check what's in the errors. i'm using code like this:

    auth = OneLogin_Saml2_Auth(saml_req, saml_settings)
    auth.process_response()

    if not auth.is_authenticated():
        error = auth.get_last_error_reason() # here's the error message

i'm guessing you are bumping into the same issue with the ELB that i was, which will go something like Authentication error: The response was received at http://... instead of https://...

The solution is either to perform a https->https redirect, or to make pysaml think it received the response on https. Here's how i did it (in this case in a django app, but should be easy enough to modify for other environments):

    saml_req = {
        'http_host': request.META['HTTP_HOST'],
        'server_port': request.META['SERVER_PORT'],
        'script_name': request.META['PATH_INFO'],
        'get_data': request.GET.copy(),
        'post_data': request.POST.copy()
    }

    if settings.SAML_FUDGE_HTTPS:  # made a settings flag so it can be toggled
        saml_req['https'] = True  # this one forces https in the check url
        saml_req['server_port'] = None  # this one removes the port number (80)

    auth = OneLogin_Saml2_Auth(saml_req, saml_settings)
    auth.process_response()

Update: as @smartin mentions in the comment - you might be able to sniff out HTTP_X_FORWARDED_FOR header and avoid creating a settings var


问:
Dynamic attribute name
I defined this constant:

```<code>constant('countries', [{
            NAME_IT: "Francia",
            NAME_US: "France"
        },
        {
            NAME_IT: "Italy",
            NAME_US: "Italia"
        }
    ]);
</code>```

I want to display the name of the country following a language (IT or US) that I define in my controller language:

```<code><ul>
    <li ng-repeat="cc in ctrl.countries">
        <!-- cc.NAME_US or cc.NAME_IT -->
    </li>
</ul>
</code>```

I can't find a way to display the dynamic attribute NAME_US or NAME_IT. How can I do that?

Thanks!

答:
You need to inject constant into controller and then and assign it to some $scope property of controller and then bind that scope property to you HTML.

For example : In controller:

```<code>app.controller("MyCtrl", ["$scope", "countries", function ($scope, countries) {
    $scope.countriesList = countries;
   //other code
}]);
</code>```

further in HTML, like :

```<code><li ng-repeat="cc in countriesList">
      {{cc.NAME_IT}} -{{cc.NAME_US}}
</li>
</code>```

See this fiddle.

Title: Dynamic attribute name

Body:
I defined this constant:

constant('countries', [{
            NAME_IT: "Francia",
            NAME_US: "France"
        },
        {
            NAME_IT: "Italy",
            NAME_US: "Italia"
        }
    ]);

I want to display the name of the country following a language (IT or US) that I define in my controller language:

I can't find a way to display the dynamic attribute NAME_US or NAME_IT. How can I do that?

Thanks!

Body:
You need to inject constant into controller and then and assign it to some $scope property of controller and then bind that scope property to you HTML.

For example : In controller:

app.controller("MyCtrl", ["$scope", "countries", function ($scope, countries) {
    $scope.countriesList = countries;
   //other code
}]);

further in HTML, like :

<li ng-repeat="cc in countriesList">
      {{cc.NAME_IT}} -{{cc.NAME_US}}
</li>

See this fiddle.


问:
BLOB Storage - 100+ GB, MySQL, SQLite, or PostgreSQL + Python
I have an idea for a simple application which will monitor a group of folders, index any files it finds. A gui will allow me quickly tag new files and move them into a single database for storage and also provide an easy mechanism for querying the db by tag, name, file type and date. At the moment I have about 100+ GB of files on a couple removable hard drives, the database will be at least that big. If possible I would like to support full text search of the embedded binary and text documents. This will be a single user application.

Not trying to start a DB war, but what open source DB is going to work best for me? I am pretty sure SQLLite is off the table but I could be wrong.

答:
Pretty much any of them would work (even though SQLLite wasn't meant to be used in a concurrent multi-user environment, which could be a problem...) since you don't want to index the actual contents of the files.

The only limiting factor is the maximum "packet" size of the given DB (by packet I'm referring to a query/response). Usually these limit are around 2MB, meaning that your files must be smaller than 2MB. Of course you could increase this limit, but the whole process is rather inefficient, since for example to insert a file you would have to:

Read the entire file into memory

Transform the file in a query (which usually means hex encoding it - thus doubling the size from the start)

Executing the generated query (which itself means - for the database - that it has to parse it)

I would go with a simple DB and the associated files stored using a naming convention which makes them easy to find (for example based on the primary key). Of course this design is not "pure", but it will perform much better and is also easier to use.

OwnerDisplayName: Ethan Post

LastEditorDisplayName: Eddie

OwnerDisplayName: Cd-MaN

ContentLicense: CC BY-SA 2.5


问:
iPhone cannot create CGBitmapContext
I have a problem with creating a CGBitmapContext.

```<code>CGContextRef bitmapContext = CGBitmapContextCreate(nil, imageSize.width, imageSize.height, 8, imageSize.width * 4, CGColorSpaceCreateDeviceRGB(), kCGImageAlphaNoneSkipFirst)
</code>```

When I run my application normally it works. But when I run it in my 'Test application' (a running app that will perform my tests) the context is logged as (null) and I get the following errors:

```<code><Error>: CGContextSetFillColorWithColor: invalid context 0x0
<Error>: CGContextFillRects: invalid context 0x0
<Error>: CGContextDrawImage: invalid context 0x0
<Error>: CGContextDrawImage: invalid context 0x0
<Error>: CGBitmapContextCreateImage: invalid context 0x0
</code>```

My application doesn't crash. But apparently there is something wrong. (I know the errors are created by calling those methods with a nil context).

答:
This error often appears when the size of the bitmap you're trying to create is CGSizeZero. Check the actual value of imageSize.

Besides, you leak the CGColorSpaceRef you pass into the function.

Title: iPhone cannot create CGBitmapContext

Body:
I have a problem with creating a CGBitmapContext.

CGContextRef bitmapContext = CGBitmapContextCreate(nil, imageSize.width, imageSize.height, 8, imageSize.width * 4, CGColorSpaceCreateDeviceRGB(), kCGImageAlphaNoneSkipFirst)

When I run my application normally it works. But when I run it in my 'Test application' (a running app that will perform my tests) the context is logged as (null) and I get the following errors:

<Error>: CGContextSetFillColorWithColor: invalid context 0x0
<Error>: CGContextFillRects: invalid context 0x0
<Error>: CGContextDrawImage: invalid context 0x0
<Error>: CGContextDrawImage: invalid context 0x0
<Error>: CGBitmapContextCreateImage: invalid context 0x0

My application doesn't crash. But apparently there is something wrong. (I know the errors are created by calling those methods with a nil context).


答:
Write this in your controller:

```<code>.controller('YourController', ['countries', function(countries) {
    this.countries = countries;
}]
</code>```

Now, you can use it as you did in the view.

NOTE: It is highly recommended to define constant in uppercase. ie. COUNTRIES in your case

Title: Dynamic attribute name

Body:
Write this in your controller:

.controller('YourController', ['countries', function(countries) {
    this.countries = countries;
}]

Now, you can use it as you did in the view.

NOTE: It is highly recommended to define constant in uppercase. ie. COUNTRIES in your case


问:
Questions about create table in sqlite3 of python
I am using sqlite3 with Python 2.7. I am learning how to create table in a database, so when I want to see whether it is created or not I use command .tables but that gives me an error:

invalid syntax

Here is the code

```<code>import sqlite3
conn = sqlite3.connect('raman.db')
c = conn.cursor()
c.execute("CREATE table new(ID INT NOT NULL)")
</code>```

答:
Just execute:

```<code>c.execute("SELECT * FROM sqlite_master WHERE type='table'").fetchall()
</code>```

It will give you tables infor:

```<code>[(u'table', u'new', u'new', 2, u'CREATE TABLE new(ID INT NOT NULL)')]
</code>```

Update:
Put below code in you py file:

```<code>import sqlite3
conn = sqlite3.connect('raman.db')
c = conn.cursor()
c.execute("CREATE table new(ID INT NOT NULL)")
print c.execute("SELECT * FROM sqlite_master WHERE type='table'").fetchall()  #check table info new
c.execute("CREATE table Raman(ATOMIC NUMBER INT, SYMBOL TEXT, ROW INT , COLUMN INT)")
c.execute("INSERT INTO Raman VALUES(1,'H',1,'1')")
conn.commit()
print c.execute("select * from Raman").fetchall() #get data from table Raman
conn.close()
</code>```

Run the py file in your terminal, it will print:

```<code>[(u'table', u'new', u'new', 2, u'CREATE TABLE new(ID INT NOT NULL)')]
[(1, u'H', 1, 1)]
</code>```

Body:
I am using sqlite3 with Python 2.7. I am learning how to create table in a database, so when I want to see whether it is created or not I use command .tables but that gives me an error:

invalid syntax

Here is the code

import sqlite3
conn = sqlite3.connect('raman.db')
c = conn.cursor()
c.execute("CREATE table new(ID INT NOT NULL)")

Body:
Just execute:

c.execute("SELECT * FROM sqlite_master WHERE type='table'").fetchall()

It will give you tables infor:

[(u'table', u'new', u'new', 2, u'CREATE TABLE new(ID INT NOT NULL)')]

Update:
Put below code in you py file:

import sqlite3
conn = sqlite3.connect('raman.db')
c = conn.cursor()
c.execute("CREATE table new(ID INT NOT NULL)")
print c.execute("SELECT * FROM sqlite_master WHERE type='table'").fetchall()  #check table info new
c.execute("CREATE table Raman(ATOMIC NUMBER INT, SYMBOL TEXT, ROW INT , COLUMN INT)")
c.execute("INSERT INTO Raman VALUES(1,'H',1,'1')")
conn.commit()
print c.execute("select * from Raman").fetchall() #get data from table Raman
conn.close()

Run the py file in your terminal, it will print:

[(u'table', u'new', u'new', 2, u'CREATE TABLE new(ID INT NOT NULL)')]
[(1, u'H', 1, 1)]


问:
save multiple fields with same name in database using ajax
I want to save the table having multiple rows that is generated dynamically when i try to save a data only first letter is saved in database. and when i try to save the next row it says 500 error in console. i want to save all the data of all the rows one by one in a database how can i achive this?

Here is my code :

```<code> <!--    <form action="" method="POST">  -->
                    <?php $data = array(
                        'id'=>'inventory_form',
                        ); ?>
                    <?php  echo form_open('main/store',$data); ?>
                   <div class="table-responsive">
                        <table class="table table-bordered table-hover" id="inv_tbl">
                            <thead>
                                <th>No</th>
                                <th>~</th>
                                <th>Barcode</th>
                                <th>Product Name</th>
                                <th>SM</th>
                                <th>SPL</th>
                                <th>Quantity</th>
                                <th>Price</th>
                                <th>Discount</th>
                                <th>Amount</th>
                                <th><input type="button" value="+" id="add" class="btn btn-primary add_inv_row"></th>
                            </thead>
                            <tbody class="detail">
                                <tr>
                                    <td class="no">1</td>
                                    <td class="text-center"><input type="checkbox" id="till_check" class="is_checked" name="till_check[]" value="Bike"></td>

                                    <td>
                                        <select name="barcode[]" id="barcode" class="form-control selectpicker barcode" data-live-search="true">
                                        <option value="">Please select a barcode</option>
                                        <?php  foreach($barcodes as $barcode) :?>
                                        <option value="<?php echo $barcode->barcode; ?>"><?php echo $barcode->barcode; ?></option>
                                        <?php endforeach; ?>
                                        </select>
                                    </td>
                                    <td><input type="text" id="brcode_product" class="form-control productname" name="productname[]"></td>
                                    <td>
                                        <select name="sm[]" id="sm" class="form-control selectpicker sm" data-live-search="true">
                                        <option value="">Please select a Employee code</option>
                                        <?php  foreach($employee_codes as $employee_code) :?>
                                        <option value="<?php echo $employee_code->emp_code; ?>"><?php echo $employee_code->emp_code; ?></option>
                                        <?php endforeach; ?>
                                        </select>
                                    </td>
                                    <td><input type="text" id="spl" class="form-control spl" name="spl[]"></td>
                                    <td><input type="text" id="quantity" class="form-control quantity" name="quantity[]"></td>
                                    <td><input type="text" id="price" class="form-control price" name="price[]"></td>
                                    <td><input type="text" id="discount" class="form-control discount" name="discount[]"></td>
                                    <td><input type="text" id="amount" class="form-control amount" name="amount[]"></td>
                                    <td><a href="#" class="remove">Delete</a></td>

                                </tr>
                            </tbody>
                            <tfoot>
                                <th></th>
                                <th></th>
                                <th></th>
                                <th></th>
                                <th></th>
                                <th></th>
                                <th></th>
                                <th></th>

                                <th class="text-center"><button class="btn btn-success" id="save_btn" type="submit" name="sale_submit_btn">Save</button></th>
                                <th style="text-align:center;" class="total">0<b></b></th>

                            </tfoot>

                        </table>

                    </div>

                    <?php echo form_close(); ?>
                    <!--</form>-->
</code>```

My Javascript code :-

```<code>function total() {
    var t = 0;
    $('.amount').each(function (i, e) {
        var amt = $(this).val() - 0;
        t += amt;
    });
    $('.total').html(t);
}

function addnewrow() {
    var n = ($('.detail tr').length - 0) + 1;

    var tr = '<tr>' +
        '<td class="no">' + n + '</td>' +
        '<td><input type="checkbox" class="till_check" name="till_check[' + till_check_counter + ']" id="till_check[' + till_check_counter + ']"></td>' +
        '<td><select class="form-control barcode selectpicker  dyselect_' + product_barcode_counter + '" data-live-search="true" name="barcode[' + product_barcode_counter + ']" id="barcode[' + product_barcode_counter + ']">' + '<option>Please select a bar code</option>' + '</select></td>' +
        '<td><input type="text" class="form-control prdctn_' + product_name_counter + ' productname"  id="brcode_product['+product_name_counter+']"  name="productname[' + product_name_counter + ']" id="productname[' + product_name_counter + ']"></td>' +
        '<td><select class="form-control selectpicker dysm_' + sm_counter + ' sm " data-live-search="true" name="sm[' + sm_counter + ']" id="sm[' + sm_counter + ']">' + '<option>Please select a Employee code</option>' + '</select></td>' +
        '<td><input type="text" class="form-control spl" name="spl[' + spl_counter + ']" id="spl[' + spl_counter + ']"></td>' +
        '<td><input type="text" class="form-control quantity" name="quantity[' + product_quantity_counter + ']" id="quantity[' + product_quantity_counter + ']"></td>' +
        '<td><input type="text" class="form-control price" name="price[' + product_price_counter + ']" id="price[' + product_price_counter + ']"></td>' +
        '<td><input type="text" class="form-control discount" name="discount[' + product_discount_counter + ']" id="discount[' + product_discount_counter + ']"></td>' +
        '<td><input type="text" class="form-control amount" name="amount[' + product_amount_counter + ']" id="amount[' + product_amount_counter + ']"></td>' +
        '<td><a href="#" class="remove">Delete</td>' +
        '</tr>';
    $('.detail').append(tr);

    //increamenting the counter
    ++product_barcode_counter;
    ++till_check_counter;
    ++product_name_counter;
    ++product_quantity_counter;
    ++sm_counter;
    ++spl_counter;
    ++product_price_counter;
    ++product_discount_counter;
    ++product_amount_counter;

    //setting the validation rules for every product attribute by calling the function
    createValidation();
    get_barcodes();
    get_employee_codes();

}

    $('#save_btn').on('click', function () {
        var barcode = $('#barcode  option:selected').val();
        var productname = $('#brcode_product').val();
        var sm = $('#sm  option:selected').val();
        var spl = $('#spl').val();
        var quantity = $('#quantity').val();
        var price = $('#price').val();
        var discount = $('#discount').val();
        var amount = $('#amount').val();

        var dataString = 'barcode=' + barcode + '&productname=' + productname + '&sm=' + sm + '&spl=' + spl + '&quantity' + quantity + '&price=' + price + '&discount=' + discount + '&amount=' + amount;
        $.ajax({
        url: "http://localhost/retail/main/store",
        type: "POST",
        data: {
            /*barcode: barcode,
            productname: productname,
            sm: sm,
            spl: spl,
            quantity: quantity,
            price: price,
            discount: discount,
            amount: amount*/
            data:$('#inventory_form').serialize()
        },
        success: function (res) {
            alert(res);
        }

    });
</code>```

Here is my Conroller code :

```<code>public function store(){

            /* echo ($_POST['barcode']);
             echo "<br/>";
             echo ($_POST['productname']);
             echo "<br/>";
             echo ($_POST['smsm']);
             echo "<br/>";
             echo ($_POST['spl']);
             echo "<br/>";
             echo ($_POST['quantity']);
             echo "<br/>";
             echo ($_POST['price']);
             echo "<br/>";
             echo ($_POST['discount']);
             echo "<br/>";
             echo ($_POST['amount']);
             echo "<br/>";*/

        //echo $this->input->post('barcode');

    if ($this->session->userdata('status')== 1) {
         for ($i = 0; $i < count($_POST['productname']); $i++) {

         $order_id = $this->session->userdata('id');
         $product_name = $this->input->post('productname')[$i];
         $barcode = $this->input->post('barcode')[$i];
         $spl= $this->input->post('spl')[$i];
         $sm= $this->input->post('sm')[$i];
         $quantity = $this->input->post('quantity')[$i];
         $price = $this->input->post('price')[$i];
         $discount =$this->input->post('discount')[$i];
         $amount = $this->input->post('amount')[$i];

        $data = array(

             'order_id'=> $order_id,
             'product_name'=>$product_name,
             'barcode'=> $barcode,
             'sm'=> $sm,
             'spl'=> $spl,
             'quantity'=>$quantity,
             'price'=>$price,
             'discount'=> $discount,
             'amount'=> $amount,

        );

             $this->Sale_model->insert_sales_data($data);
             echo "Data inserted successfully!";

         }
      }

      else
      {
          redirect('login');
      }

    }
</code>```

I am using Codeigniter .Please tell me how can i  the functionality that i mentioned above?

答:
why are you getting single values in your ajax request?

```<code>var barcode = $('#barcode  option:selected').val();
var productname = $('#brcode_product').val();
var sm = $('#sm  option:selected').val();
var spl = $('#spl').val();
var quantity = $('#quantity').val();
var price = $('#price').val();
var discount = $('#discount').val();
var amount = $('#amount').val();
</code>```

why not just serialize your form and then pass that serialize data?

Body:
I want to save the table having multiple rows that is generated dynamically when i try to save a data only first letter is saved in database. and when i try to save the next row it says 500 error in console. i want to save all the data of all the rows one by one in a database how can i achive this?

Here is my code :

                    <?php $data = array(
                        'id'=>'inventory_form',
                        ); ?>
                    <?php  echo form_open('main/store',$data); ?>

                                No
                                ~
                                Barcode
                                Product Name
                                SM
                                SPL
                                Quantity
                                Price
                                Discount
                                Amount
                                <input type="button" value="+" id="add" class="btn btn-primary add_inv_row">

                                    1
                                    <input type="checkbox" id="till_check" class="is_checked" name="till_check[]" value="Bike">

                                        <select name="barcode[]" id="barcode" class="form-control selectpicker barcode" data-live-search="true">
                                        <option value="">Please select a barcode</option>
                                        <?php  foreach($barcodes as $barcode) :?>
                                        <option value="<?php echo $barcode->barcode; ?>"><?php echo $barcode->barcode; ?></option>
                                        <?php endforeach; ?>
                                        </select>

                                    <input type="text" id="brcode_product" class="form-control productname" name="productname[]">

                                        <select name="sm[]" id="sm" class="form-control selectpicker sm" data-live-search="true">
                                        <option value="">Please select a Employee code</option>
                                        <?php  foreach($employee_codes as $employee_code) :?>
                                        <option value="<?php echo $employee_code->emp_code; ?>"><?php echo $employee_code->emp_code; ?></option>
                                        <?php endforeach; ?>
                                        </select>

                                    <input type="text" id="spl" class="form-control spl" name="spl[]">
                                    <input type="text" id="quantity" class="form-control quantity" name="quantity[]">
                                    <input type="text" id="price" class="form-control price" name="price[]">
                                    <input type="text" id="discount" class="form-control discount" name="discount[]">
                                    <input type="text" id="amount" class="form-control amount" name="amount[]">
                                    Delete

                                <button class="btn btn-success" id="save_btn" type="submit" name="sale_submit_btn">Save</button>
                                0

                    <?php echo form_close(); ?>

My Javascript code :-

function total() {
    var t = 0;
    $('.amount').each(function (i, e) {
        var amt = $(this).val() - 0;
        t += amt;
    });
    $('.total').html(t);
}

function addnewrow() {
    var n = ($('.detail tr').length - 0) + 1;

    var tr = '
' +
        '' + n + '	' +
        '<input type="checkbox" class="till_check" name="till_check[' + till_check_counter + ']" id="till_check[' + till_check_counter + ']">	' +
        '<select class="form-control barcode selectpicker  dyselect_' + product_barcode_counter + '" data-live-search="true" name="barcode[' + product_barcode_counter + ']" id="barcode[' + product_barcode_counter + ']">' + '<option>Please select a bar code</option>' + '</select>	' +
        '<input type="text" class="form-control prdctn_' + product_name_counter + ' productname"  id="brcode_product['+product_name_counter+']"  name="productname[' + product_name_counter + ']" id="productname[' + product_name_counter + ']">	' +
        '<select class="form-control selectpicker dysm_' + sm_counter + ' sm " data-live-search="true" name="sm[' + sm_counter + ']" id="sm[' + sm_counter + ']">' + '<option>Please select a Employee code</option>' + '</select>	' +
        '<input type="text" class="form-control spl" name="spl[' + spl_counter + ']" id="spl[' + spl_counter + ']">	' +
        '<input type="text" class="form-control quantity" name="quantity[' + product_quantity_counter + ']" id="quantity[' + product_quantity_counter + ']">	' +
        '<input type="text" class="form-control price" name="price[' + product_price_counter + ']" id="price[' + product_price_counter + ']">	' +
        '<input type="text" class="form-control discount" name="discount[' + product_discount_counter + ']" id="discount[' + product_discount_counter + ']">	' +
        '<input type="text" class="form-control amount" name="amount[' + product_amount_counter + ']" id="amount[' + product_amount_counter + ']">	' +
        'Delete	' +
        '
';
    $('.detail').append(tr);

    //increamenting the counter
    ++product_barcode_counter;
    ++till_check_counter;
    ++product_name_counter;
    ++product_quantity_counter;
    ++sm_counter;
    ++spl_counter;
    ++product_price_counter;
    ++product_discount_counter;
    ++product_amount_counter;

    //setting the validation rules for every product attribute by calling the function
    createValidation();
    get_barcodes();
    get_employee_codes();

}

    $('#save_btn').on('click', function () {
        var barcode = $('#barcode  option:selected').val();
        var productname = $('#brcode_product').val();
        var sm = $('#sm  option:selected').val();
        var spl = $('#spl').val();
        var quantity = $('#quantity').val();
        var price = $('#price').val();
        var discount = $('#discount').val();
        var amount = $('#amount').val();

        var dataString = 'barcode=' + barcode + '&productname=' + productname + '&sm=' + sm + '&spl=' + spl + '&quantity' + quantity + '&price=' + price + '&discount=' + discount + '&amount=' + amount;
        $.ajax({
        url: "http://localhost/retail/main/store",
        type: "POST",
        data: {
            /*barcode: barcode,
            productname: productname,
            sm: sm,
            spl: spl,
            quantity: quantity,
            price: price,
            discount: discount,
            amount: amount*/
            data:$('#inventory_form').serialize()
        },
        success: function (res) {
            alert(res);
        }

    });

Here is my Conroller code :

public function store(){

            /* echo ($_POST['barcode']);
             echo "
";
             echo ($_POST['productname']);
             echo "
";
             echo ($_POST['smsm']);
             echo "
";
             echo ($_POST['spl']);
             echo "
";
             echo ($_POST['quantity']);
             echo "
";
             echo ($_POST['price']);
             echo "
";
             echo ($_POST['discount']);
             echo "
";
             echo ($_POST['amount']);
             echo "
";*/

        //echo $this->input->post('barcode');

    if ($this->session->userdata('status')== 1) {
         for ($i = 0; $i < count($_POST['productname']); $i++) {

         $order_id = $this->session->userdata('id');
         $product_name = $this->input->post('productname')[$i];
         $barcode = $this->input->post('barcode')[$i];
         $spl= $this->input->post('spl')[$i];
         $sm= $this->input->post('sm')[$i];
         $quantity = $this->input->post('quantity')[$i];
         $price = $this->input->post('price')[$i];
         $discount =$this->input->post('discount')[$i];
         $amount = $this->input->post('amount')[$i];

        $data = array(

             'order_id'=> $order_id,
             'product_name'=>$product_name,
             'barcode'=> $barcode,
             'sm'=> $sm,
             'spl'=> $spl,
             'quantity'=>$quantity,
             'price'=>$price,
             'discount'=> $discount,
             'amount'=> $amount,

        );

             $this->Sale_model->insert_sales_data($data);
             echo "Data inserted successfully!";

         }
      }

      else
      {
          redirect('login');
      }

    }

I am using Codeigniter .Please tell me how can i  the functionality that i mentioned above?

Body:
why are you getting single values in your ajax request?

var barcode = $('#barcode  option:selected').val();
var productname = $('#brcode_product').val();
var sm = $('#sm  option:selected').val();
var spl = $('#spl').val();
var quantity = $('#quantity').val();
var price = $('#price').val();
var discount = $('#discount').val();
var amount = $('#amount').val();

why not just serialize your form and then pass that serialize data?


问:
Localization on the fly with localized Storyboards
I'm working on an app that has a toggle button to switch between English and Arabic language and should be on the fly. I'm using the method in https://github.com/maximbilan/ios_language_manager and it works fine in all cases except if the storyboard is localized by interface not strings:

Now when I reload the root view controller like this:

```<code>   func reloadRootVC(){

    let delegate : AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate

    let storyboard = UIStoryboard(name: "Main", bundle: NSBundle.mainBundle())

    delegate.window?.rootViewController = (storyboard.instantiateInitialViewController())
}
</code>```

it reload the root with localized strings and in RTL but with the english storyboard not the arabic one.

Tried force loading the arabic one like this:

```<code>let storyboard = UIStoryboard(name: "Main", bundle: NSBundle(path: NSBundle.mainBundle().pathForResource(LanguageManager.currentLanguageCode(), ofType: "lproj")!))
</code>```

but unfortunately it loads the storyboard but with no images. It can't read any resource image.

答:
change the bundle which is used to init the storyboard:

```<code>        let path = Bundle.main.path(forResource: "ar", ofType: "lproj")
        let bundle = Bundle(path: path!)
        let delegate : AppDelegate = UIApplication.shared.delegate as! AppDelegate
        let storyboard = UIStoryboard(name: "Main", bundle: bundle)
        delegate.window?.rootViewController = (storyboard.instantiateInitialViewController())
</code>```

although this change the storyboard based on language but do not load images! :(

Body:
I'm working on an app that has a toggle button to switch between English and Arabic language and should be on the fly. I'm using the method in https://github.com/maximbilan/ios_language_manager and it works fine in all cases except if the storyboard is localized by interface not strings:

Now when I reload the root view controller like this:

   func reloadRootVC(){

    let delegate : AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate

    let storyboard = UIStoryboard(name: "Main", bundle: NSBundle.mainBundle())

    delegate.window?.rootViewController = (storyboard.instantiateInitialViewController())
}

it reload the root with localized strings and in RTL but with the english storyboard not the arabic one.

Tried force loading the arabic one like this:

let storyboard = UIStoryboard(name: "Main", bundle: NSBundle(path: NSBundle.mainBundle().pathForResource(LanguageManager.currentLanguageCode(), ofType: "lproj")!))

but unfortunately it loads the storyboard but with no images. It can't read any resource image.

Body:
change the bundle which is used to init the storyboard:

        let path = Bundle.main.path(forResource: "ar", ofType: "lproj")
        let bundle = Bundle(path: path!)
        let delegate : AppDelegate = UIApplication.shared.delegate as! AppDelegate
        let storyboard = UIStoryboard(name: "Main", bundle: bundle)
        delegate.window?.rootViewController = (storyboard.instantiateInitialViewController())

although this change the storyboard based on language but do not load images! :(


问:
What is the way to correctly build toolbar with hamburger on react-native?
What is the best way to make a toolbar with a hamburger and search (icon) with some drawer effect on the top of the screen for iOS and Android accordingly on react-native?</p>

答: React native has bridged the toolbar and the drawer layout from android so you can use both of them with no problem. https://facebook.github.io/react-native/docs/toolbarandroid.html If you want to build you app also for iOS I would take a look at React navigation witch mining’s native behavior and is cross platform.</p>


问:
Horizontal Menu with vertical Sub menu
I want a horizontal Menu with Vertical Submenus that are taken from SQl Server Database , I need the vertical Sub Menu with Scroll bars, Can someone give me link for such menu.

答:
I was needed same thing, so I can recommend to you following links:

Create your own drop down menu with nested submenus using CSS and a little JavaScript

Mega Dropdown Menu Generator
Responsive horizontal navigation menu using pure CSS

I hope you will find it usefull.

Title: Horizontal Menu with vertical Sub menu


问:
For same api gson is working but jackson cannot parse the repsonse, returning a null value to the variables
I am using Jackson converter factory for parsing, it returning null in response. But for the same api when I just used replced jackson converter Factory with gson, its working fine.

Json Response :

```<code>{
  "Politician_list": [

    {
      "Manifestos": [
        {
          "agenda": "All together",
          "document_url": "http://i.dailymail.co.uk/i/pix/2014/03/14/article-2581407-1C4D453500000578-736_306x352.jpg",
          "id": 2,
          "tagline": "Hathi ke sath",
          "targets": "literacy"
        }
      ],
      "Projects": [
        {
          "end_date": "20 January 2016",
          "id": 1,
          "project_details": "Reservoir construction",
          "project_image": "http://static.progressivemediagroup.com/uploads/imagelibrary/nri/water/floridaresproj.jpg",
          "start_date": "20 November 2015"
        },
        {
          "end_date": "13 February 2015",
          "id": 2,
          "project_details": "Dam construction",
          "project_image": "https://upload.wikimedia.org/wikipedia/en/e/ee/Tarbela_Dam,_KPK,_Pakistan.jpg",
          "start_date": "18 June 2014"
        }
      ],
      "address_data": {
        "address": "207 maitry",
        "city": "gurgaon",
        "country": "India",
        "landmark": "Home",
        "lat": "542354",
        "lon": "2345",
        "pincode": "122011",
        "state": "Haryana"
      },
      "age": 42,
      "assets": "Rs 3,27,05,761",
      "back_image_url": "http://www.palpalindia.com/2015/03/08/bulandshahr-UP-Human-Welfare-Committee-Jehangirabad-B-Chandrakala-SSP-Dev-Tiwari-news-in-hindi-india-87165.jpg",
      "birth_place": "Allahabad",
      "criminal_cases": 0,
      "current_party": "BSP",
      "current_position": "Member of Legislative Assembly",
      "dob": "14 January 1975",
      "education_qual": "Literate",
      "father_name": "Ranveer Singh",
      "gender": "M",
      "id": 1,
      "image_url": "http://newsratingpoint.com/wp-content/uploads/2015/12/Gajendra-Singh-BSP-UP-Anupshahr-167x171.jpg",
      "income": "Rs 6,84,202",
      "liabilities": "Rs 21,16,000",
      "marital_status": "Married",
      "mother_name": "Shanti",
      "name": "Gajendra Singh",
      "no_of_child": 3,
      "spouse_name": "Anita Singh"
    }
  ],
  "response": "success"
}
</code>```

When I used Jackson Converter Factory in retrofit 2, politician list returning me null but string response shows a 'success', but when I used Gson Converter Facrtory in retrofit 2, its working just fine.

Politician Main Response :

```<code>private List<DemographyPoliticianDetails> Politician_list;

private String response;
</code>```

DemographyPoliticianDetails class :

```<code>private int age;
private String assets;
private String birth_place;
private int criminal_cases;
private String current_position;
private String current_party;
private String dob;
private String education_qual;
private String father_name;
private String mother_name;
private String name;
private String gender;
private String image_url;
private int id;
private String income;
private String marital_status;
private String liabilities;
private int no_of_child;
private String spouse_name;
private String back_image_url;

private AddressDataModel address_data;
private List<ProjectsModel> Projects;
private List<ManifestoModel> Manifestos;
</code>```

答:
As i can see in your POJO that you have created some variables with inital capital letter and maybe Jackson converter factory while converting the JSON response face some issues regarding inflating the POJO object assuming that in java the variable name start with small case.

for instance variable name of Politician_list should be politician_list*

should follow the java naming convention of first letter small.

Body:
I am using Jackson converter factory for parsing, it returning null in response. But for the same api when I just used replced jackson converter Factory with gson, its working fine.

Json Response :

{
  "Politician_list": [

    {
      "Manifestos": [
        {
          "agenda": "All together",
          "document_url": "http://i.dailymail.co.uk/i/pix/2014/03/14/article-2581407-1C4D453500000578-736_306x352.jpg",
          "id": 2,
          "tagline": "Hathi ke sath",
          "targets": "literacy"
        }
      ],
      "Projects": [
        {
          "end_date": "20 January 2016",
          "id": 1,
          "project_details": "Reservoir construction",
          "project_image": "http://static.progressivemediagroup.com/uploads/imagelibrary/nri/water/floridaresproj.jpg",
          "start_date": "20 November 2015"
        },
        {
          "end_date": "13 February 2015",
          "id": 2,
          "project_details": "Dam construction",
          "project_image": "https://upload.wikimedia.org/wikipedia/en/e/ee/Tarbela_Dam,_KPK,_Pakistan.jpg",
          "start_date": "18 June 2014"
        }
      ],
      "address_data": {
        "address": "207 maitry",
        "city": "gurgaon",
        "country": "India",
        "landmark": "Home",
        "lat": "542354",
        "lon": "2345",
        "pincode": "122011",
        "state": "Haryana"
      },
      "age": 42,
      "assets": "Rs 3,27,05,761",
      "back_image_url": "http://www.palpalindia.com/2015/03/08/bulandshahr-UP-Human-Welfare-Committee-Jehangirabad-B-Chandrakala-SSP-Dev-Tiwari-news-in-hindi-india-87165.jpg",
      "birth_place": "Allahabad",
      "criminal_cases": 0,
      "current_party": "BSP",
      "current_position": "Member of Legislative Assembly",
      "dob": "14 January 1975",
      "education_qual": "Literate",
      "father_name": "Ranveer Singh",
      "gender": "M",
      "id": 1,
      "image_url": "http://newsratingpoint.com/wp-content/uploads/2015/12/Gajendra-Singh-BSP-UP-Anupshahr-167x171.jpg",
      "income": "Rs 6,84,202",
      "liabilities": "Rs 21,16,000",
      "marital_status": "Married",
      "mother_name": "Shanti",
      "name": "Gajendra Singh",
      "no_of_child": 3,
      "spouse_name": "Anita Singh"
    }
  ],
  "response": "success"
}

When I used Jackson Converter Factory in retrofit 2, politician list returning me null but string response shows a 'success', but when I used Gson Converter Facrtory in retrofit 2, its working just fine.

Politician Main Response :

private List<DemographyPoliticianDetails> Politician_list;

private String response;

DemographyPoliticianDetails class :

private int age;
private String assets;
private String birth_place;
private int criminal_cases;
private String current_position;
private String current_party;
private String dob;
private String education_qual;
private String father_name;
private String mother_name;
private String name;
private String gender;
private String image_url;
private int id;
private String income;
private String marital_status;
private String liabilities;
private int no_of_child;
private String spouse_name;
private String back_image_url;

private AddressDataModel address_data;
private List<ProjectsModel> Projects;
private List<ManifestoModel> Manifestos;


问:
Check whether cronjob has ran or not
I have one python script running in crontab, I want to check if it is running successfully or not? if not then send mail or another kind of notification. How do I notify based on Cron logs?

Things I already Tried:

All the Exception in python file I have already handled

Need: Notify user if Cron job is not running successfully?

答: In order to notify weather cron job running or not, you can set email id in cpanel <strong>'cron jobs'</strong> page. so you will receive email once file get executed. </p>

Title: Check whether cronjob has ran or not

Body: In order to notify weather cron job running or not, you can set email id in cpanel 'cron jobs' page. so you will receive email once file get executed.


问:
Django Rest Framework Post Nested Using Files with requests module example
Excuse me, i have a problem, can anyone help me.

I have models like:

```<code>from django.db import models
from django.contrib.auth.models import User
import uuid

def uuid_generator():
    return str(uuid.uuid4())

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile_user')
    mobile = models.CharField(max_length=20)
    alamat = models.TextField(blank=True)
    phone = models.CharField(max_length=20, blank=True)
    foto = models.ImageField(upload_to='profile', blank=True)

    def __str__(self):
        return self.user.username

class Rumah(models.Model):
    JENIS_CHOICES = (
        ('rumah', 'Rumah besar'),
        ('petakan', 'Rumah petakan'),
        ('apartement', 'Apartement'),
        ('kost', 'Kost-Kostan')
    )

    WAKTU_CHOICES = (
        ('bulanan', 'Bulanan'),
        ('tahunan', 'Tahunan'),
    )

    STATUS_CHOICES = (
        ('tersedia', 'Tersedia'),
        ('terisi', 'Sudah Terisi'),
        ('ditutup', 'Di Tutup'),
    )

    pemilik = models.ForeignKey(User, on_delete=models.CASCADE, related_name='rumah_user')
    kode = models.CharField(unique=True, max_length=150)
    jenis = models.CharField(max_length=12, choices=JENIS_CHOICES, default='rumah')
    waktu = models.CharField(max_length=10, choices=WAKTU_CHOICES, default='bulanan')
    harga = models.PositiveIntegerField()
    alamat = models.TextField()
    status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='tersedia')
    keterangan = models.TextField(blank=True)

    def __str__(self):
        return self.kode

    def save(self, *args, **kwargs):
        self.kode = uuid_generator()
        super(Rumah, self).save(*args, **kwargs)

class Foto(models.Model):
    rumah = models.ForeignKey(Rumah, on_delete=models.CASCADE, related_name='foto_rumah')
    penampakan = models.ImageField(upload_to='penampakan', blank=True)
    keterangan = models.TextField(blank=True)

    def __str__(self):
        return self.rumah.kode
</code>```

Note: Rumah like House in english and Foto like Picture in english.

I have a views like:

```<code>from django.contrib.auth.models import User
from produk.models import Profile, Rumah, Foto
from .serializers import UserSerializer, ProfileSerializer, RumahSerializer, FotoSerializer
from .permissions import IsOwnerOrReadOnly, IsHasProfile, IsRumahOrReadOnly
from rest_framework import mixins
from rest_framework import generics
from rest_framework import permissions

class UserList(generics.ListAPIView):
    queryset = User.objects.all()
    serializer_class = UserSerializer

class UserDetail(generics.RetrieveAPIView):
    queryset = User.objects.all()
    serializer_class = UserSerializer

class ProfileList(generics.ListCreateAPIView):
    queryset = Profile.objects.all()
    serializer_class = ProfileSerializer
    permission_classes = (permissions.IsAuthenticatedOrReadOnly,)

    def perform_create(self, serializer):
        serializer.save(user=self.request.user)

class ProfileDetail(generics.RetrieveUpdateDestroyAPIView):
    permission_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly)
    queryset = Profile.objects.all()
    serializer_class = ProfileSerializer

class RumahList(generics.ListCreateAPIView):
    queryset = Rumah.objects.all()
    serializer_class = RumahSerializer
    permission_classes = (permissions.IsAuthenticatedOrReadOnly,)

    def perform_create(self, serializer):
        serializer.save(pemilik=self.request.user)

class RumahDetail(generics.RetrieveUpdateDestroyAPIView):
    queryset = Rumah.objects.all()
    serializer_class = RumahSerializer
    permission_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly)

class FotoList(generics.ListCreateAPIView):
    queryset = Foto.objects.all()
    serializer_class = FotoSerializer
    permission_classes = (permissions.IsAuthenticatedOrReadOnly,)

class FotoDetail(generics.RetrieveUpdateDestroyAPIView):
    queryset = Foto.objects.all()
    serializer_class = FotoSerializer
    permission_classes = (permissions.IsAuthenticatedOrReadOnly, IsRumahOrReadOnly)
</code>```

I have a serializers like:

```<code>from django.contrib.auth.models import User
from rest_framework import serializers
from produk.models import Profile, Rumah, Foto

class UserSerializer(serializers.HyperlinkedModelSerializer):
    rumah_user = serializers.HyperlinkedRelatedField(many=True, view_name='rumah-detail', read_only=True)
    profile_user = serializers.HyperlinkedRelatedField(many=False, view_name='profile-detail', read_only=True)

    class Meta:
        model = User
        fields = ('id', 'username', 'email', 'is_active', 'rumah_user', 'profile_user')

class ProfileSerializer(serializers.ModelSerializer):
    user = serializers.ReadOnlyField(source='user.username')

    class Meta:
        model = Profile
        fields = ('id', 'user', 'alamat', 'mobile', 'phone', 'foto')

class FotoSerializer(serializers.ModelSerializer):
    # rumah = serializers.ReadOnlyField(source='rumah.kode')

    class Meta:
        model = Foto
        fields = ('id', 'rumah', 'penampakan', 'keterangan')

class RumahSerializer(serializers.ModelSerializer):
    pemilik = serializers.ReadOnlyField(source='pemilik.username')
    #foto_rumah = serializers.HyperlinkedRelatedField(many=True, view_name='foto-detail', read_only=True)
    foto_rumah = FotoSerializer(many=True)

    class Meta:
        model = Rumah
        fields = ('id', 'pemilik', 'jenis', 'waktu', 'harga', 'alamat', 'status', 'keterangan', 'foto_rumah')

    def create(self, validated_data):
        fotos_data = validated_data.pop('foto_rumah')
        print(validated_data)
        rumah = Rumah.objects.create(**validated_data)
        for foto_data in fotos_data:
            Foto.objects.create(rumah=rumah, **foto_data)
        return rumah
</code>```

When i try it with requests module like:

```<code>import requests
from requests.auth import HTTPBasicAuth

url = 'http://127.0.0.1:8000/rumah/'

files = {'penampakan': open('C:\\Users\\yanz\\Pictures\\Campuran\\test.png', 'rb')}
data =  {
        "pemilik": "admin",
        "jenis": "rumah",
        "waktu": "bulanan",
        "harga": 3,
        "alamat": "r",
        "status": "tersedia",
        "keterangan": "4",
        "foto_rumah": [
            {
                "penampakan": files,
                "keterangan": "a"
            }
        ]
    }
r = requests.post(url, data=data, files=files, auth=HTTPBasicAuth('admin', 'password123'))

print(r.text)
</code>```

Result:

```<code>{"id":11,"pemilik":"admin","jenis":"rumah","waktu":"bulanan","harga":3,"alamat":"r","status":"tersedia","keterangan":"4","foto_rumah":[]}
</code>```

Foto (foto_rumah) data from the model Foto is not saved. what's the solution ? How to post nested data with files?

Thanks...

答:
Nested serializers don't work with form encoded data yet.
Uploading images only works with form encoded data out of the box.

I guess you'll need to upload images on a specific non nested entry point or use base64 encoded files within the JSON.
I remember I've seen a 3rd party about handling base64 files but can't find it again.

Body:
Excuse me, i have a problem, can anyone help me.

I have models like:

from django.db import models
from django.contrib.auth.models import User
import uuid

def uuid_generator():
    return str(uuid.uuid4())

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile_user')
    mobile = models.CharField(max_length=20)
    alamat = models.TextField(blank=True)
    phone = models.CharField(max_length=20, blank=True)
    foto = models.ImageField(upload_to='profile', blank=True)

    def __str__(self):
        return self.user.username

class Rumah(models.Model):
    JENIS_CHOICES = (
        ('rumah', 'Rumah besar'),
        ('petakan', 'Rumah petakan'),
        ('apartement', 'Apartement'),
        ('kost', 'Kost-Kostan')
    )

    WAKTU_CHOICES = (
        ('bulanan', 'Bulanan'),
        ('tahunan', 'Tahunan'),
    )

    STATUS_CHOICES = (
        ('tersedia', 'Tersedia'),
        ('terisi', 'Sudah Terisi'),
        ('ditutup', 'Di Tutup'),
    )

    pemilik = models.ForeignKey(User, on_delete=models.CASCADE, related_name='rumah_user')
    kode = models.CharField(unique=True, max_length=150)
    jenis = models.CharField(max_length=12, choices=JENIS_CHOICES, default='rumah')
    waktu = models.CharField(max_length=10, choices=WAKTU_CHOICES, default='bulanan')
    harga = models.PositiveIntegerField()
    alamat = models.TextField()
    status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='tersedia')
    keterangan = models.TextField(blank=True)

    def __str__(self):
        return self.kode

    def save(self, *args, **kwargs):
        self.kode = uuid_generator()
        super(Rumah, self).save(*args, **kwargs)

class Foto(models.Model):
    rumah = models.ForeignKey(Rumah, on_delete=models.CASCADE, related_name='foto_rumah')
    penampakan = models.ImageField(upload_to='penampakan', blank=True)
    keterangan = models.TextField(blank=True)

    def __str__(self):
        return self.rumah.kode

Note: Rumah like House in english and Foto like Picture in english.

I have a views like:

from django.contrib.auth.models import User
from produk.models import Profile, Rumah, Foto
from .serializers import UserSerializer, ProfileSerializer, RumahSerializer, FotoSerializer
from .permissions import IsOwnerOrReadOnly, IsHasProfile, IsRumahOrReadOnly
from rest_framework import mixins
from rest_framework import generics
from rest_framework import permissions

class UserList(generics.ListAPIView):
    queryset = User.objects.all()
    serializer_class = UserSerializer

class UserDetail(generics.RetrieveAPIView):
    queryset = User.objects.all()
    serializer_class = UserSerializer

class ProfileList(generics.ListCreateAPIView):
    queryset = Profile.objects.all()
    serializer_class = ProfileSerializer
    permission_classes = (permissions.IsAuthenticatedOrReadOnly,)

    def perform_create(self, serializer):
        serializer.save(user=self.request.user)

class ProfileDetail(generics.RetrieveUpdateDestroyAPIView):
    permission_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly)
    queryset = Profile.objects.all()
    serializer_class = ProfileSerializer

class RumahList(generics.ListCreateAPIView):
    queryset = Rumah.objects.all()
    serializer_class = RumahSerializer
    permission_classes = (permissions.IsAuthenticatedOrReadOnly,)

    def perform_create(self, serializer):
        serializer.save(pemilik=self.request.user)

class RumahDetail(generics.RetrieveUpdateDestroyAPIView):
    queryset = Rumah.objects.all()
    serializer_class = RumahSerializer
    permission_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly)

class FotoList(generics.ListCreateAPIView):
    queryset = Foto.objects.all()
    serializer_class = FotoSerializer
    permission_classes = (permissions.IsAuthenticatedOrReadOnly,)

class FotoDetail(generics.RetrieveUpdateDestroyAPIView):
    queryset = Foto.objects.all()
    serializer_class = FotoSerializer
    permission_classes = (permissions.IsAuthenticatedOrReadOnly, IsRumahOrReadOnly)

I have a serializers like:

from django.contrib.auth.models import User
from rest_framework import serializers
from produk.models import Profile, Rumah, Foto

class UserSerializer(serializers.HyperlinkedModelSerializer):
    rumah_user = serializers.HyperlinkedRelatedField(many=True, view_name='rumah-detail', read_only=True)
    profile_user = serializers.HyperlinkedRelatedField(many=False, view_name='profile-detail', read_only=True)

    class Meta:
        model = User
        fields = ('id', 'username', 'email', 'is_active', 'rumah_user', 'profile_user')

class ProfileSerializer(serializers.ModelSerializer):
    user = serializers.ReadOnlyField(source='user.username')

    class Meta:
        model = Profile
        fields = ('id', 'user', 'alamat', 'mobile', 'phone', 'foto')

class FotoSerializer(serializers.ModelSerializer):
    # rumah = serializers.ReadOnlyField(source='rumah.kode')

    class Meta:
        model = Foto
        fields = ('id', 'rumah', 'penampakan', 'keterangan')

class RumahSerializer(serializers.ModelSerializer):
    pemilik = serializers.ReadOnlyField(source='pemilik.username')
    #foto_rumah = serializers.HyperlinkedRelatedField(many=True, view_name='foto-detail', read_only=True)
    foto_rumah = FotoSerializer(many=True)

    class Meta:
        model = Rumah
        fields = ('id', 'pemilik', 'jenis', 'waktu', 'harga', 'alamat', 'status', 'keterangan', 'foto_rumah')

    def create(self, validated_data):
        fotos_data = validated_data.pop('foto_rumah')
        print(validated_data)
        rumah = Rumah.objects.create(**validated_data)
        for foto_data in fotos_data:
            Foto.objects.create(rumah=rumah, **foto_data)
        return rumah

When i try it with requests module like:

import requests
from requests.auth import HTTPBasicAuth

url = 'http://127.0.0.1:8000/rumah/'

files = {'penampakan': open('C:\\Users\\yanz\\Pictures\\Campuran\\test.png', 'rb')}
data =  {
        "pemilik": "admin",
        "jenis": "rumah",
        "waktu": "bulanan",
        "harga": 3,
        "alamat": "r",
        "status": "tersedia",
        "keterangan": "4",
        "foto_rumah": [
            {
                "penampakan": files,
                "keterangan": "a"
            }
        ]
    }
r = requests.post(url, data=data, files=files, auth=HTTPBasicAuth('admin', 'password123'))

print(r.text)

Result:

{"id":11,"pemilik":"admin","jenis":"rumah","waktu":"bulanan","harga":3,"alamat":"r","status":"tersedia","keterangan":"4","foto_rumah":[]}

Foto (foto_rumah) data from the model Foto is not saved. what's the solution ? How to post nested data with files?

Thanks...


问:
How to connect my LDAP with an existing ldap system in Laravel 5.4
I have to connect my ldap with an existing ldap system with the following conditions:
Domain used is 12.14.4.38
Username 0000001 and password 123456.

I've opened this link , but I still don't understand how to use it. This is my adldap.php code

```<code><?php

return [

'connections' => [

    'default' => [

        'auto_connect' => true,

        'connection' => Adldap\Connections\Ldap::class,

        'schema' => Adldap\Schemas\ActiveDirectory::class,

        'connection_settings' => [

            'account_prefix' => env('ADLDAP_ACCOUNT_PREFIX', ''),

            'account_suffix' => env('ADLDAP_ACCOUNT_SUFFIX', ''),

            'domain_controllers' => explode(' ', env('ADLDAP_CONTROLLERS', '12.14.4.38')),

            'port' => env('ADLDAP_PORT', 389),

            'timeout' => env('ADLDAP_TIMEOUT', 5),

            'base_dn' => env('ADLDAP_BASEDN', 'dc=12.14.4.38'),

            'admin_account_suffix' => env('ADLDAP_ADMIN_ACCOUNT_SUFFIX', ''),

            'admin_username' => env('ADLDAP_ADMIN_USERNAME', '0000001'),
            'admin_password' => env('ADLDAP_ADMIN_PASSWORD', '123456'),

            'follow_referrals' => false,

            'use_ssl' => false,
            'use_tls' => false,

        ],

    ],

],

];

// Create a new Adldap Provider instance.
$provider = new \Adldap\Connections\Provider(connections);

$ad = new \Adldap\Adldap(connections);

try {
// Connect to the provider you specified in your configuration.
$provider = $ad->connect('default');

// Connection was successful.

// We can now perform operations on the connection.
$user = $provider->search()->users()->find('0000001');

} catch (\Adldap\Auth\BindException $e) {
die("Can't connect / bind to the LDAP server! Error: $e");
}
</code>```

答:
You didn't specify a dn/path nor did you enter a path for the admin

This is how it normally looks

```<code>Search host: 12.14.4.38
basedn: "ou=Users,dc=DRiski,dc=com"  <- I use your username as an example
admin:"cn=admin,ou=admins,dc=DRiski,dc=com"
password: just the regular password
</code>```

What is with the weird cn, dc, ou stuff... that is like a path/folder in wich it needs to look to find the user (or users/groups in the case of base dn)...
base dn: specifies where to look for the users, in this case: in the folder users, on the server Driski.com

That is also how you specify your admin (tell the server where to find the thing).

Solved?

If not, try connecting to your ldap using ldapadmin (or another administrative tool) such that you can see how it works, and what path to enter...

Body:
I have to connect my ldap with an existing ldap system with the following conditions:
Domain used is 12.14.4.38
Username 0000001 and password 123456.

I've opened this link , but I still don't understand how to use it. This is my adldap.php code

<?php

return [

'connections' => [

    'default' => [

        'auto_connect' => true,

        'connection' => Adldap\Connections\Ldap::class,

        'schema' => Adldap\Schemas\ActiveDirectory::class,

        'connection_settings' => [

            'account_prefix' => env('ADLDAP_ACCOUNT_PREFIX', ''),

            'account_suffix' => env('ADLDAP_ACCOUNT_SUFFIX', ''),

            'domain_controllers' => explode(' ', env('ADLDAP_CONTROLLERS', '12.14.4.38')),

            'port' => env('ADLDAP_PORT', 389),

            'timeout' => env('ADLDAP_TIMEOUT', 5),

            'base_dn' => env('ADLDAP_BASEDN', 'dc=12.14.4.38'),

            'admin_account_suffix' => env('ADLDAP_ADMIN_ACCOUNT_SUFFIX', ''),

            'admin_username' => env('ADLDAP_ADMIN_USERNAME', '0000001'),
            'admin_password' => env('ADLDAP_ADMIN_PASSWORD', '123456'),

            'follow_referrals' => false,

            'use_ssl' => false,
            'use_tls' => false,

        ],

    ],

],

];

// Create a new Adldap Provider instance.
$provider = new \Adldap\Connections\Provider(connections);

$ad = new \Adldap\Adldap(connections);

try {
// Connect to the provider you specified in your configuration.
$provider = $ad->connect('default');

// Connection was successful.

// We can now perform operations on the connection.
$user = $provider->search()->users()->find('0000001');

} catch (\Adldap\Auth\BindException $e) {
die("Can't connect / bind to the LDAP server! Error: $e");
}

Body:
You didn't specify a dn/path nor did you enter a path for the admin

This is how it normally looks

Search host: 12.14.4.38
basedn: "ou=Users,dc=DRiski,dc=com"  <- I use your username as an example
admin:"cn=admin,ou=admins,dc=DRiski,dc=com"
password: just the regular password

What is with the weird cn, dc, ou stuff... that is like a path/folder in wich it needs to look to find the user (or users/groups in the case of base dn)...
base dn: specifies where to look for the users, in this case: in the folder users, on the server Driski.com

That is also how you specify your admin (tell the server where to find the thing).

Solved?

If not, try connecting to your ldap using ldapadmin (or another administrative tool) such that you can see how it works, and what path to enter...


问:
using -knitr- to weave Rnw files in RStudio
This seems to be a recurrent problem for who is willing to write dynamic documents with knitr in RStudio (see also here for instance).
Unfortunately I haven't find a solution on Stack Overflow or by googling more in general.

Here is a toy example I am trying to compile in RStudio. It is the minimal-example-002.Rnw (link):

```<code>\documentclass{article}
\usepackage[T1]{fontenc}

\begin{document}

Here is a code chunk.

<<foo, fig.height=4>>=
1+1
letters
chartr('xie', 'XIE', c('xie yihui', 'Yihui Xie'))
par(mar=c(4, 4, .2, .2)); plot(rnorm(100))
@

You can also write inline expressions, e.g. $\pi=\Sexpr{pi}$, and \Sexpr{1.598673e8} is a big number.

\end{document}
</code>```

My problem is that I am not able to compile the pdf in RStudio by using knitr, while by changing the default weaving option to sweave I get the final pdf.

More specifically, I work in Windows 7, latest RStudio version (0.98.1103), I weave the file using the knitr option and I disabled the "always enable Rnw concordance" box.

Did this happen to you?
Any help would be highly appreciated, thank you very much.

EDIT

Apparently it is not an RStudio problem, as I tried to compile the document from R with:

```<code>library('knitr')
knit('minimal_ex.Rnw')
</code>```

and I get the same error:

```<code>processing file: minimal_ex.Rnw

  |
  |                                                                 |   0%
  |
  |......................                                           |  33%
  ordinary text without R code

  |
  |...........................................                      |  67%
label: foo (with options)
List of 1
 $ fig.height: num 4

Quitting from lines 8-10 (minimal_ex.Rnw)
Errore in data.frame(..., check.names = FALSE) :
  arguments imply differing number of rows: 3, 0
Inoltre: Warning messages:
1: In is.na(res[, 1]) :
  is.na() applied to non-(list or vector) of type 'NULL'
2: In is.na(res) : is.na() applied to non-(list or vector) of type 'NULL'
</code>```

EDIT 2:

This is my session info:

```<code>R version 3.1.1 (2014-07-10)
Platform: x86_64-w64-mingw32/x64 (64-bit)

locale:
[1] LC_COLLATE=Italian_Italy.1252  LC_CTYPE=Italian_Italy.1252    LC_MONETARY=Italian_Italy.1252 LC_NUMERIC=C
[5] LC_TIME=Italian_Italy.1252

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
[1] knitr_1.10.5

loaded via a namespace (and not attached):
[1] tools_3.1.1
</code>```

答: To add a little to this: It seems to be a bug with the echo parameter which defaults to TRUE. Setting it to false with knitr and pdfLaTeX as a renderer worked for me. In case you're in a situation where you can't update because of dependencies and/or rights issues, this input might be a helpful adhoc fix, since the error message is pretty useless.

Body:
This seems to be a recurrent problem for who is willing to write dynamic documents with knitr in RStudio (see also here for instance).
Unfortunately I haven't find a solution on Stack Overflow or by googling more in general.

Here is a toy example I am trying to compile in RStudio. It is the minimal-example-002.Rnw (link):

\documentclass{article}
\usepackage[T1]{fontenc}

\begin{document}

Here is a code chunk.

<<foo, fig.height=4>>=
1+1
letters
chartr('xie', 'XIE', c('xie yihui', 'Yihui Xie'))
par(mar=c(4, 4, .2, .2)); plot(rnorm(100))
@

You can also write inline expressions, e.g. $\pi=\Sexpr{pi}$, and \Sexpr{1.598673e8} is a big number.

\end{document}

My problem is that I am not able to compile the pdf in RStudio by using knitr, while by changing the default weaving option to sweave I get the final pdf.

More specifically, I work in Windows 7, latest RStudio version (0.98.1103), I weave the file using the knitr option and I disabled the "always enable Rnw concordance" box.

Did this happen to you?
Any help would be highly appreciated, thank you very much.

EDIT

Apparently it is not an RStudio problem, as I tried to compile the document from R with:

library('knitr')
knit('minimal_ex.Rnw')

and I get the same error:

processing file: minimal_ex.Rnw

  |
  |                                                                 |   0%
  |
  |......................                                           |  33%
  ordinary text without R code

  |
  |...........................................                      |  67%
label: foo (with options)
List of 1
 $ fig.height: num 4

Quitting from lines 8-10 (minimal_ex.Rnw)
Errore in data.frame(..., check.names = FALSE) :
  arguments imply differing number of rows: 3, 0
Inoltre: Warning messages:
1: In is.na(res[, 1]) :
  is.na() applied to non-(list or vector) of type 'NULL'
2: In is.na(res) : is.na() applied to non-(list or vector) of type 'NULL'

EDIT 2:

This is my session info:

R version 3.1.1 (2014-07-10)
Platform: x86_64-w64-mingw32/x64 (64-bit)

locale:
[1] LC_COLLATE=Italian_Italy.1252  LC_CTYPE=Italian_Italy.1252    LC_MONETARY=Italian_Italy.1252 LC_NUMERIC=C
[5] LC_TIME=Italian_Italy.1252

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
[1] knitr_1.10.5

loaded via a namespace (and not attached):
[1] tools_3.1.1


问:
Selectize - on change add URL parameter and refresh the page
URL using "http://localhost:8000/test.html"

I want to change URL to "http://localhost:8000/test.html?countrycode=SG" or "http://localhost:8000/test.html?countrycode=MY" or "http://localhost:8000/test.html?countrycode=IN" based on the selectize value selected.

Also, On select change it have get value and refresh the page.

Thanks

HTML:

```<code><div class="select-container">
  <select class="custom-select">
    <option value="SG">Singapore</option>
    <option value="MY">Malaysia</option>
    <option value="IN">India</option>
  </select>
</div>
</code>```

JS:

```<code>$('.custom-select').selectize();
</code>```

答:
solution found for this question:

var urlpath =  window.location.origin + window.location.pathname;
        window.location = urlpath+'?countrycode=' + value;

Thanks

Body:
URL using "http://localhost:8000/test.html"

I want to change URL to "http://localhost:8000/test.html?countrycode=SG" or "http://localhost:8000/test.html?countrycode=MY" or "http://localhost:8000/test.html?countrycode=IN" based on the selectize value selected.

Also, On select change it have get value and refresh the page.

Thanks

HTML:

  <select class="custom-select">
    <option value="SG">Singapore</option>
    <option value="MY">Malaysia</option>
    <option value="IN">India</option>
  </select>

JS:

$('.custom-select').selectize();


问:
Windows OpenJDK doesn't match with Linux OpenJDK
I develop on Windows deploy on linux. I couldn't find the same version OpenJdk of windows and linux. So I installed openjdk_1.7.0_u80-unofficial for windows and openjdk-1.7.0.71.x86_64 for linux. Will there be a problem? Or please suggest a better way to do it.

Linux OS: RedHat 6.6

答: Probably not. Unless there are some bug that's been fixed in one version but not the other or new bugs have been introduced, you're likely not going to feel any effects; and even that's the case, you're unlikely to hit any of those bugs anyway.</p>


问:
leaflet use satellite view, drupal 8?

I need instead of a basic view in leaflet (it's a map of the world), the satellite view, but I still need to be able to switch between them? How does this work, can anyone explain this to me?

Installed modules:

https://www.drupal.org/project/gmap

https://www.drupal.org/project/leaflet_more_maps

答:
I made a more detailed example of my question, but @JulienV came close to what I meant, But it wasn't entirely what I wanted, plus I already found his exact answer in another post. What I wanted was to know how to add more or less maps to the view:

```<code>var osmLink = '<a href=\"https://openstreetmap.org\">OpenStreetMap</a>',
    thunLink = '<a href=\"https://thunderforest.com/\">Thunderforest</a>';

var osmUrl = 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
    osmAttrib = '© ' + osmLink + ' Contributors',
    landUrl = 'https://{s}.tile.thunderforest.com/landscape/{z}/{x}/{y}.png',
    thunAttrib = '© '+osmLink+' Contributors & '+thunLink;

var osmMap = L.tileLayer(osmUrl, {attribution: osmAttrib}),
    landMap = L.tileLayer(landUrl, {attribution: thunAttrib});

var roadmap = L.tileLayer('https://{s}.google.com/vt/lyrs=m&x={x}&y={y}&z={z}',{
    maxZoom: 20,
    subdomains:['mt0','mt1','mt2','mt3']
});

var satellite = L.tileLayer('https://{s}.google.com/vt/lyrs=s&x={x}&y={y}&z={z}',{
    maxZoom: 20,
    subdomains:['mt0','mt1','mt2','mt3']
});

var sat_text = L.tileLayer('https://{s}.google.com/vt/lyrs=s,h&x={x}&y={y}&z={z}',{
    maxZoom: 20,
    subdomains:['mt0','mt1','mt2','mt3']
});
</code>```

And then I added each map to the array like this:

```<code>if($map_layouts['get_roads']) {
    $roads = "\"Roads\": roadmap";

    if($baselist == "") {
        $baselist = $roads;
    } else {
        $baselist = $baselist . "," . $roads;
    }
}
</code>```

Then I needed to check if the $baselist wasn't empty:

```<code>if($baselist) {
    $base_layout = "var baseLayers = {".$baselist."};";
} else {
    $base_layout = "";
}
</code>```

And then of course add the layers to the map:

```<code>L.control.layers(baseLayers).addTo(map);
</code>```

I worked out the code with the google maps included. The osm and thun map was a nice example, but basically what this code does:

First I make if statements in php to see if the roads are included in the button I made. I pass the get_roads inside the array, so that the if statement returns true and then it sets $roads as the roadmap value, which is given in the map examples in the first code of this answer.

Then I check if $baselist isn't empty, because if it's empty it doesn't need a ,, but if it isn't empty, then it gets the $baselist, which would be the previous set value, then a comma and then the new value.

This was the markup of the layers and then I will pass the baseLayers as those values, which will create the maps inside the leaflet view, if the buttons are checked.

Title: leaflet use satellite view, drupal 8?

Body:
I made a more detailed example of my question, but @JulienV came close to what I meant, But it wasn't entirely what I wanted, plus I already found his exact answer in another post. What I wanted was to know how to add more or less maps to the view:

var osmLink = '<a href=\"https://openstreetmap.org\">OpenStreetMap</a>',
    thunLink = '<a href=\"https://thunderforest.com/\">Thunderforest</a>';

var osmUrl = 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
    osmAttrib = '&copy; ' + osmLink + ' Contributors',
    landUrl = 'https://{s}.tile.thunderforest.com/landscape/{z}/{x}/{y}.png',
    thunAttrib = '&copy; '+osmLink+' Contributors & '+thunLink;

var osmMap = L.tileLayer(osmUrl, {attribution: osmAttrib}),
    landMap = L.tileLayer(landUrl, {attribution: thunAttrib});

var roadmap = L.tileLayer('https://{s}.google.com/vt/lyrs=m&x={x}&y={y}&z={z}',{
    maxZoom: 20,
    subdomains:['mt0','mt1','mt2','mt3']
});

var satellite = L.tileLayer('https://{s}.google.com/vt/lyrs=s&x={x}&y={y}&z={z}',{
    maxZoom: 20,
    subdomains:['mt0','mt1','mt2','mt3']
});

var sat_text = L.tileLayer('https://{s}.google.com/vt/lyrs=s,h&x={x}&y={y}&z={z}',{
    maxZoom: 20,
    subdomains:['mt0','mt1','mt2','mt3']
});

And then I added each map to the array like this:

if($map_layouts['get_roads']) {
    $roads = "\"Roads\": roadmap";

    if($baselist == "") {
        $baselist = $roads;
    } else {
        $baselist = $baselist . "," . $roads;
    }
}

Then I needed to check if the $baselist wasn't empty:

if($baselist) {
    $base_layout = "var baseLayers = {".$baselist."};";
} else {
    $base_layout = "";
}

And then of course add the layers to the map:

L.control.layers(baseLayers).addTo(map);

I worked out the code with the google maps included. The osm and thun map was a nice example, but basically what this code does:

First I make if statements in php to see if the roads are included in the button I made. I pass the get_roads inside the array, so that the if statement returns true and then it sets $roads as the roadmap value, which is given in the map examples in the first code of this answer.

Then I check if $baselist isn't empty, because if it's empty it doesn't need a ,, but if it isn't empty, then it gets the $baselist, which would be the previous set value, then a comma and then the new value.

This was the markup of the layers and then I will pass the baseLayers as those values, which will create the maps inside the leaflet view, if the buttons are checked.


问:
How to set up and build Apache 2.4 on WINDOWS 7 Pro?
I have a project, and need to set up and build an Apache24 server on windows, but there is almost non of information on that, can you give some advice?</p>

答:
I found the answer, after a lot of searching, I found an acceptable way to do it.

Software Requirements:

```<code>Visual Studio 2013 (I use the Community Edition)
</code>```

Make a folder on C, call it BuildTools and install all the following programs there:

```<code>ActivePerl for Windows (64-bit, currently using 5.20.1.2000)
CMake for Windows (currently using 3.1.3)
GNU Awk for Windows (currently using 3.1.6-1)
GnuWin32 (any version from 2014+)
Netwide Assembler (NASM) (currently using 2.11.06)
</code>```

Source Code Packages (I don't use ZLIB for Apache or OpenSSL, or LUA/LIBXML2/EXPAT, therefore these are not included in the process):

```<code>httpd-2.4.12.tar.gz
apr-1.5.1.tar.gz
apr-util.1.5.4.tar.gz
openssl-1.0.2a.tar.gz (yes it works with 1.0.2a!)
pcre-8.36.tar.gz
</code>```

Here are the steps:

Extract all packages into their separate folders in your preferred source tree (e.g. C:\Development\Apache24\src)

Create custom build folders for Apache, PCRE, APR and APR-Util in your preferred build folder (e.g. C:\Development\Apache24\build

Your folder structure should resemble the below:

Make the following file changes so that ApacheMonitor gets built (without the Manifest error):

C:\Development\Apache24\src\httpd-2.4.12\CMakeLists.txt
Uncomment the section to build the ApacheMonitor utility (lines 769-775)
Find the following lines below, they will be in comments

```<code># getting duplicate manifest error with ApacheMonitor

ADD_EXECUTABLE(ApacheMonitor support/win32/ApacheMonitor.c support/win32/ApacheMonitor.rc)
SET(install_targets ${install_targets} ApacheMonitor)
SET(install_bin_pdb ${install_bin_pdb} ${PROJECT_BINARY_DIR}/ApacheMonitor.pdb)
SET_TARGET_PROPERTIES(ApacheMonitor PROPERTIES WIN32_EXECUTABLE TRUE)
SET_TARGET_PROPERTIES(ApacheMonitor PROPERTIES COMPILE_FLAGS "-DAPP_FILE -DLONG_NAME=ApacheMonitor -DBIN_NAME=ApacheMonitor.exe / ${EXTRA_COMPILE_FLAGS}")
TARGET_LINK_LIBRARIES(ApacheMonitor ${EXTRA_LIBS} ${HTTPD_SYSTEM_LIBS} comctl32 wtsapi32)
</code>```

Also

C:\Development\Apache24\src\httpd-2.4.12\support\win32\ApacheMonitor.rc
Comment out the line that includes ApacheMonitor.manifest (line 29)

```<code>//CREATEPROCESS_MANIFEST_RESOURCE_ID RT_MANIFEST  "ApacheMonitor.manifest"
</code>```

4.1 Create a set_path.bat file with the following code:

```<code>    SET VC_HOME=c:\Program Files (x86)\Microsoft Visual Studio 13.0\VC
    call VC_HOME\vcvarsall amd64
    SET BUILD_ROOT=C:\BuildTools
    SET PATH=%PATH%;%BUILD_ROOT%\cmake\bin
    SET PATH=%PATH%;%BUILD_ROOT%\gawk\bin
    SET PATH=%PATH%;%BUILD_ROOT%\nasm
    SET PATH=%PATH%;%BUILD_ROOT%\perl\bin

You will need to run that file later in the process.
</code>```

From the Start menu, launch the VS2013 x64 Native Tools Command Prompt found under Visual Studio 2013->Visual Studio Tools. Alternatively, but not recommended, from a Windows Command Prompt.

5.1 Go to GnuWin32, find his lib and the include folder,  and copy their content to the BuildTools/perl/lib folder, this should resolve some errors that came up in the process while I was doing this

5.2 This step, you can skip now, BUT, if there is an error that includes the expat.h and the expath_external.h files, Find an older version of Apache, and copy its expat_external.h to the apache24/include folder

```<code>Find expat.h file on this site
https://github.com/apache/apr-util/blob/0.9.x/xml/expat/lib/expat.h

copy its content over the file, you find in apache24/include folder Find an older version of Apache (don't know exactly witch version), and copy its expat_external.h to the apache24/include folder

Find expat.h file on this site
https://github.com/apache/apr-util/blob/0.9.x/xml/expat/lib/expat.h

copy its content over the file, you find in apache24/include folder
</code>```

5.3. Find the set_path.bat folder from the console and run it.
    this you need to do, to be able to run the next steps

Navigate into the build sub-folder for PCRE, run CMAKE to generate a suitable Makefile, then compile and install

```<code>cd /D C:\Development\Apache24\build\pcre
cmake -G "NMake Makefiles" -DCMAKE_INSTALL_PREFIX=C:\Apache24 -DCMAKE_BUILD_TYPE=RelWithDebInfo -DBUILD_SHARED_LIBS=ON -DPCRE_BUILD_TESTS=OFF -DPCRE_BUILD_PCRECPP=OFF -DPCRE_BUILD_PCREGREP=OFF -DPCRE_SUPPORT_PCREGREP_JIT=OFF -DPCRE_SUPPORT_UTF=ON -DPCRE_SUPPORT_UNICODE_PROPERTIES=ON -DPCRE_NEWLINE=CRLF -DINSTALL_MSVC_PDB=OFF ..\..\src\pcre-8.36
nmake
nmake install
</code>```

Navigate into the source sub-folder for OpenSSL, configure the build environment for compiling with NASM, then compile and install

```<code> cd /D C:\Development\Apache24\src\openssl-1.0.2a
 perl Configure VC-WIN64A --prefix=C:\Apache24 --openssldir=C:\Apache24\conf enable-camellia no-idea no-mdc2 no-ssl2 no-ssl3 no-zlib
 ms\do_win64a.bat
 nmake /f ms\ntdll.mak
 nmake /f ms\ntdll.mak install
</code>```

Navigate into the build sub-folder for APR, run CMAKE to generate a suitable Makefile, then compile and install

```<code>cd /D C:\Development\Apache24\build\apr
cmake -G "NMake Makefiles" -DCMAKE_INSTALL_PREFIX=C:\Apache24 -DCMAKE_BUILD_TYPE=RelWithDebInfo -DMIN_WINDOWS_VER=0x0600 -DAPR_HAVE_IPV6=ON -DAPR_INSTALL_PRIVATE_H=ON -DAPR_BUILD_TESTAPR=OFF -DINSTALL_PDB=OFF ..\..\src\apr-1.5.1
nmake
nmake install
</code>```

Navigate into the build sub-folder for APR-Util, run CMAKE to generate a suitable Makefile, then compile and install

```<code>ActivePerl for Windows (64-bit, currently using 5.20.1.2000)
CMake for Windows (currently using 3.1.3)
GNU Awk for Windows (currently using 3.1.6-1)
GnuWin32 (any version from 2014+)
Netwide Assembler (NASM) (currently using 2.11.06)
</code>```0

Navigate into the build sub-folder for Apache, run CMAKE to generate a suitable Makefile, then compile and install

```<code>ActivePerl for Windows (64-bit, currently using 5.20.1.2000)
CMake for Windows (currently using 3.1.3)
GNU Awk for Windows (currently using 3.1.6-1)
GnuWin32 (any version from 2014+)
Netwide Assembler (NASM) (currently using 2.11.06)
</code>```1

Finally, confirm everything is working

```<code>ActivePerl for Windows (64-bit, currently using 5.20.1.2000)
CMake for Windows (currently using 3.1.3)
GNU Awk for Windows (currently using 3.1.6-1)
GnuWin32 (any version from 2014+)
Netwide Assembler (NASM) (currently using 2.11.06)
</code>```2

These are the steps and the problems I encountered, and I followed the steps from this site:

```<code>https://www.apachelounge.com/viewtopic.php?t=6462
</code>```

Also I added a few more steps and solutions that I needed to do to make it work.

I hope this will help someone else in the future.

Body:
I found the answer, after a lot of searching, I found an acceptable way to do it.

Software Requirements:

Visual Studio 2013 (I use the Community Edition)

Make a folder on C, call it BuildTools and install all the following programs there:

ActivePerl for Windows (64-bit, currently using 5.20.1.2000)
CMake for Windows (currently using 3.1.3)
GNU Awk for Windows (currently using 3.1.6-1)
GnuWin32 (any version from 2014+)
Netwide Assembler (NASM) (currently using 2.11.06)

Source Code Packages (I don't use ZLIB for Apache or OpenSSL, or LUA/LIBXML2/EXPAT, therefore these are not included in the process):

httpd-2.4.12.tar.gz
apr-1.5.1.tar.gz
apr-util.1.5.4.tar.gz
openssl-1.0.2a.tar.gz (yes it works with 1.0.2a!)
pcre-8.36.tar.gz

Here are the steps:

Extract all packages into their separate folders in your preferred source tree (e.g. C:\Development\Apache24\src)

Create custom build folders for Apache, PCRE, APR and APR-Util in your preferred build folder (e.g. C:\Development\Apache24\build

Your folder structure should resemble the below:

Make the following file changes so that ApacheMonitor gets built (without the Manifest error):

C:\Development\Apache24\src\httpd-2.4.12\CMakeLists.txt
Uncomment the section to build the ApacheMonitor utility (lines 769-775)
Find the following lines below, they will be in comments

# getting duplicate manifest error with ApacheMonitor

ADD_EXECUTABLE(ApacheMonitor support/win32/ApacheMonitor.c support/win32/ApacheMonitor.rc)
SET(install_targets ${install_targets} ApacheMonitor)
SET(install_bin_pdb ${install_bin_pdb} ${PROJECT_BINARY_DIR}/ApacheMonitor.pdb)
SET_TARGET_PROPERTIES(ApacheMonitor PROPERTIES WIN32_EXECUTABLE TRUE)
SET_TARGET_PROPERTIES(ApacheMonitor PROPERTIES COMPILE_FLAGS "-DAPP_FILE -DLONG_NAME=ApacheMonitor -DBIN_NAME=ApacheMonitor.exe / ${EXTRA_COMPILE_FLAGS}")
TARGET_LINK_LIBRARIES(ApacheMonitor ${EXTRA_LIBS} ${HTTPD_SYSTEM_LIBS} comctl32 wtsapi32)

Also

C:\Development\Apache24\src\httpd-2.4.12\support\win32\ApacheMonitor.rc
Comment out the line that includes ApacheMonitor.manifest (line 29)

//CREATEPROCESS_MANIFEST_RESOURCE_ID RT_MANIFEST  "ApacheMonitor.manifest"

4.1 Create a set_path.bat file with the following code:

    SET VC_HOME=c:\Program Files (x86)\Microsoft Visual Studio 13.0\VC
    call VC_HOME\vcvarsall amd64
    SET BUILD_ROOT=C:\BuildTools
    SET PATH=%PATH%;%BUILD_ROOT%\cmake\bin
    SET PATH=%PATH%;%BUILD_ROOT%\gawk\bin
    SET PATH=%PATH%;%BUILD_ROOT%\nasm
    SET PATH=%PATH%;%BUILD_ROOT%\perl\bin

You will need to run that file later in the process.

From the Start menu, launch the VS2013 x64 Native Tools Command Prompt found under Visual Studio 2013->Visual Studio Tools. Alternatively, but not recommended, from a Windows Command Prompt.

5.1 Go to GnuWin32, find his lib and the include folder,  and copy their content to the BuildTools/perl/lib folder, this should resolve some errors that came up in the process while I was doing this

5.2 This step, you can skip now, BUT, if there is an error that includes the expat.h and the expath_external.h files, Find an older version of Apache, and copy its expat_external.h to the apache24/include folder

Find expat.h file on this site
https://github.com/apache/apr-util/blob/0.9.x/xml/expat/lib/expat.h

copy its content over the file, you find in apache24/include folder Find an older version of Apache (don't know exactly witch version), and copy its expat_external.h to the apache24/include folder

Find expat.h file on this site
https://github.com/apache/apr-util/blob/0.9.x/xml/expat/lib/expat.h

copy its content over the file, you find in apache24/include folder

5.3. Find the set_path.bat folder from the console and run it.
    this you need to do, to be able to run the next steps

Navigate into the build sub-folder for PCRE, run CMAKE to generate a suitable Makefile, then compile and install

cd /D C:\Development\Apache24\build\pcre
cmake -G "NMake Makefiles" -DCMAKE_INSTALL_PREFIX=C:\Apache24 -DCMAKE_BUILD_TYPE=RelWithDebInfo -DBUILD_SHARED_LIBS=ON -DPCRE_BUILD_TESTS=OFF -DPCRE_BUILD_PCRECPP=OFF -DPCRE_BUILD_PCREGREP=OFF -DPCRE_SUPPORT_PCREGREP_JIT=OFF -DPCRE_SUPPORT_UTF=ON -DPCRE_SUPPORT_UNICODE_PROPERTIES=ON -DPCRE_NEWLINE=CRLF -DINSTALL_MSVC_PDB=OFF ..\..\src\pcre-8.36
nmake
nmake install

Navigate into the source sub-folder for OpenSSL, configure the build environment for compiling with NASM, then compile and install

 cd /D C:\Development\Apache24\src\openssl-1.0.2a
 perl Configure VC-WIN64A --prefix=C:\Apache24 --openssldir=C:\Apache24\conf enable-camellia no-idea no-mdc2 no-ssl2 no-ssl3 no-zlib
 ms\do_win64a.bat
 nmake /f ms\ntdll.mak
 nmake /f ms\ntdll.mak install

Navigate into the build sub-folder for APR, run CMAKE to generate a suitable Makefile, then compile and install

cd /D C:\Development\Apache24\build\apr
cmake -G "NMake Makefiles" -DCMAKE_INSTALL_PREFIX=C:\Apache24 -DCMAKE_BUILD_TYPE=RelWithDebInfo -DMIN_WINDOWS_VER=0x0600 -DAPR_HAVE_IPV6=ON -DAPR_INSTALL_PRIVATE_H=ON -DAPR_BUILD_TESTAPR=OFF -DINSTALL_PDB=OFF ..\..\src\apr-1.5.1
nmake
nmake install

Navigate into the build sub-folder for APR-Util, run CMAKE to generate a suitable Makefile, then compile and install

cd /D C:\Development\Apache24\build\apr-util
cmake -G "NMake Makefiles" -DCMAKE_INSTALL_PREFIX=C:\Apache24 -DOPENSSL_ROOT_DIR=C:\Apache24 -DCMAKE_BUILD_TYPE=RelWithDebInfo -DAPU_HAVE_CRYPTO=ON -DAPR_BUILD_TESTAPR=OFF -DINSTALL_PDB=OFF ..\..\src\apr-util-1.5.4
nmake
nmake install

Navigate into the build sub-folder for Apache, run CMAKE to generate a suitable Makefile, then compile and install

cd /D C:\Development\Apache24\build\httpd
cmake -G "NMake Makefiles" -DCMAKE_INSTALL_PREFIX=C:\Apache24 -DCMAKE_BUILD_TYPE=RelWithDebInfo -DENABLE_MODULES=i -DINSTALL_PDB=OFF ..\..\src\httpd-2.4.12
nmake
nmake install

Finally, confirm everything is working

cd /D C:\Apache24\bin
openssl version
httpd -V

These are the steps and the problems I encountered, and I followed the steps from this site:

https://www.apachelounge.com/viewtopic.php?t=6462

Also I added a few more steps and solutions that I needed to do to make it work.

I hope this will help someone else in the future.

ContentLicense: CC BY-SA 4.0


问:
Quandl wiki data different than Yahoo or Bloomberg data
Does anyone notice quandl WIKI or EOD data are different than Yahoo or Bloomberg? I notice this when I was comparing data providers, which I am using AAPL as a test. AAPL split its stock 7 for 1 on Jun 9, 2014, so I think it is an ideal candidate to compare data.

Here is a picture of data comparison:

Do you know why they are different and which one I should trust? If I should trust neither, is there any other free data provider I can trust?

答:
It depends on whether you adjust the dividends too (the series starting at 52 is adjusted for dividends, the series starting at 58 is not).

For reference, Bloomberg data:

```<code>            Unadjusted price    Adjusted for split  Adjusted for split & div
27/12/2011      406.53                58.0757            52.4533
28/12/2011      402.64                57.52              51.9514
29/12/2011      405.12                57.8743            52.2714
etc.
</code>```

Body:
It depends on whether you adjust the dividends too (the series starting at 52 is adjusted for dividends, the series starting at 58 is not).

For reference, Bloomberg data:

            Unadjusted price    Adjusted for split  Adjusted for split & div
27/12/2011      406.53                58.0757            52.4533
28/12/2011      402.64                57.52              51.9514
29/12/2011      405.12                57.8743            52.2714
etc.