Q: Can I use spring boot datasource to get connection object so as to use it with conn.executeQuery() manually? I am working on spring boot application with Mysql backend and trying to use springboots datasource Bean to get connection object so as to use it with the following stmts:
stmt =conn.createStatement()
stmt.executeQuery("show tables");

which is expected to return the table list. Below is the code of connection class:
public class Test {

@Autowired
DataSource datasource;

public void test1(){
      System.out.println("Inside Test Method");
    try {
         Connection conn = datasource.getConnection();
         Statement stmt = conn.createStatement();
         ResultSet rs = stmt.executeQuery("show tables");
         while (rs.next()) {
             System.out.println(rs.getString("TableNames"));
         }
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch(NullPointerException e){
        System.out.println("Null Pointer exception");
    }

  }

}
But the datasource object is throwing null value and hence it doesnt return any connection object.
Following is the application.yml
spring:
 datasource:
 url: jdbc:mysql://localhost:3306/test
 driver-class-name: com.mysql.jdbc.Driver
 username: ****
 password: ****
 initial-size: 1
 max-idle: 2
 max-active: 3

Ideally the datasource object should read these properties and be able to return connection object. Not sure if my understanding is correct.
Can anyone help me out in figuring the issue pls ?

A: I think spring boot automated this process completely. One doesn't have to inject the data source manually & connection pool mechanism is also automated. Just adding the connection properties and pool properties in yaml file or properties file under src/main/resources. It will inject the data source for you.


Q: Do channel ids for guide categories (like music) change in the YouTube Data API? After fetching the list of channels from the guide with the guideCategories endpoint, a list of kind youtube#guideCategory is returned.  These IDs can be used to get a list of channels from the channels endpoint for the given category.
My question is do these IDs change?  Can I store this list of guide categories and reuse them for multiple languages/regions?

A: Assuming it works the same way as VideoCategories do, the IDs should work for and remain consistent across any region that supports it.
For example, when I used the API explorer and specified USA, Germany, or Australia for the region, the guideCategory ID for Music (GCTXVzaWM) was available for all three, so that guideCategory is supported in and will work for all three of those regions.


Q: set readonly property to false for an html text input on clicking on Edit I need to set readonly false when i click on Edit and when i click on edit button should change to save button. i made two input box type="submit". i need to make all the fields editable when i click on edit. please help me to find out the answer.
<form role="form" data-toggle="validator" method="post">

      <?php if(isset($account_list)){   print_r($account_list);exit;
}?>

                        <input type="text" name="RMName" value="<?= isset($accountList['name']) ? $accountList['name'] : '' ?>" id="inputName" readonly="readonly" class="readonlyinput"/>

                        <input type="email" id="inputEmail" name="inputEmail" value="<?= isset($accountList['email']) ? $accountList['email'] : '' ?>"  readonly="readonly" class="readonlyinput" />

                        <input type="text" name="dob" value="<?= isset($accountList['dob']) ? $accountList['dob'] : ''  ?>" id="InputDob" readonly="readonly" class="readonlyinput"/>

                        <input name="Phone" type="text"  id="InputNumber" value="<?= isset($accountList['phone_number']) ? $accountList['phone_number'] : '' ?>" readonly="readonly" class="readonlyinput"/>

                        <input type="text" name="OrgName" value="<?= isset($accountList['organisation']) ? $accountList['organisation'] : ''  ?>" id="InputOrgName" readonly="readonly" class="readonlyinput"/>

                        <input type="text" name="OrgId" value="<?= isset($accountList['organisation_id']) ? $accountList['organisation_id'] : '' ?>" id="InputOrgId" readonly="readonly" class="readonlyinput"/>

                        <input type="text" name="City" value="<?= isset($accountList['city']) ? $accountList['city'] : ''  ?>" id="InputCity" readonly="readonly" class="readonlyinput" />

                        <input type="text" name="State" value="<?= isset($accountList['state']) ? $accountList['state'] : '' ?>" id="InputState" readonly="readonly" class="readonlyinput" />

                        <input type="text" name="Country" value="<?= isset($accountList['country']) ? $accountList['country'] : '' ?>" id="InputCountry" readonly="readonly" class="readonlyinput" />

                  <input type="submit" class="button" title="Edit" value="EDIT" onclick="inputToggle()"/>
                  <input type="submit" class="button" title="Save" value="SAVE"  hidden="hidden"/>

    </form>

A: Use this function. Suppoesing .edit class of edit button
$('.edit').on('click', function(){
  $('input').prop('readonly',true);
});

But don't set this property initially

A: Use .prop to toggle readonly property of the :input elements.
Also note, e.preventDefault() as submit button will submit and relaod the form.

var edit = true;

function inputToggle(e) {
  e.preventDefault();
  $(':input').prop('readonly', edit = !edit);
}

<form role="form" data-toggle="validator" method="post">

            <input type="text" name="RMName" value="" id="inputName" readonly="readonly" class="readonlyinput" />

            <input type="email" id="inputEmail" name="inputEmail" value="" readonly="readonly" class="readonlyinput" />

            <input type="text" name="dob" value="" id="InputDob" readonly="readonly" class="readonlyinput" />

            <input name="Phone" type="text" id="InputNumber" value="" readonly="readonly" class="readonlyinput" />

            <input type="text" name="OrgName" value="" id="InputOrgName" readonly="readonly" class="readonlyinput" />

            <input type="text" name="OrgId" value="" id="InputOrgId" readonly="readonly" class="readonlyinput" />

            <input type="text" name="City" value="" id="InputCity" readonly="readonly" class="readonlyinput" />

            <input type="text" name="State" value="" id="InputState" readonly="readonly" class="readonlyinput" />

            <input type="text" name="Country" value="" id="InputCountry" readonly="readonly" class="readonlyinput" />

          <input type="submit" class="button" title="Edit" value="EDIT" onclick="inputToggle(event)" />

            <input type="submit" class="button" title="Save" value="SAVE" hidden="hidden" />

</form>

Fiddle demo


Q: Bitnami GitLab 5.2.0: gitlab_sidekiq not running and could not be started We are using Bitnami GitLab 5.2.0.
We stumbled upon that we can't push into new repository, like
git@192.168.133.10:sandbox/testgit2.git,
but we can work with old ones. Closer investigation showed that gitlab_sidekiq is not running.
/opt/bitnami/ctlscript.sh restart gitlab_sidekiq
gitlab_sidekiq could not be started
Where to look? Should I update first?
UPDATE: Bitnami GitLab 5.2 server is broken down: can't push code into new repositories.
(While old repositories are unaffected)
TestProject4>git remote add origin git
@192.168.133.10:sandbox/testproject4.git

TestProject4>git push -u origin master

fatal: '/opt/bitnami/apps/gitlab/repositories/sandbox/testproject4.git' does not  appear to be a git repository
fatal: The remote end hung up unexpectedly

UPDATE WITH ANSWERS:
I am using virtual machine in VirtualBox on my PC (in 1 team as pilot moving the VM to some VM host)
Yes, I modified gitlab.yml
/opt/bitnami/apps/gitlab/htdocs/log/sidekiq.log has this lines in repetition, so they should give clue (look like some thing wrong when reading some file)
DEPRECATION WARNING: You have Rails 2.3-style plugins in vendor/plugins! Support for these plugins will be removed in Rails 4.0. Move them out and bundle them in your Gemfile, or fold them in to your app as lib/myplugin/* and config/initializers/myplugin.rb. See the release notes for more on this: http://weblog.rubyonrails.org/2012/1/4/rails-3-2-0-rc2-has-been-released. (called from <top (required)> at /opt/bitnami/apps/gitlab/htdocs/config/environment.rb:5)
/opt/bitnami/ruby/lib/ruby/1.9.1/psych.rb:203:in `parse': (<unknown>): found character that cannot start any token while scanning for the next token at line 73 column 1 (Psych::SyntaxError)
    from /opt/bitnami/ruby/lib/ruby/1.9.1/psych.rb:203:in `parse_stream'
    from /opt/bitnami/ruby/lib/ruby/1.9.1/psych.rb:151:in `parse'
    from /opt/bitnami/ruby/lib/ruby/1.9.1/psych.rb:127:in `load'
    from /opt/bitnami/ruby/lib/ruby/gems/1.9.1/gems/settingslogic-2.0.8/lib/settingslogic.rb:113:in `initialize'
    from /opt/bitnami/ruby/lib/ruby/gems/1.9.1/gems/settingslogic-2.0.8/lib/settingslogic.rb:71:in `new'
    from /opt/bitnami/ruby/lib/ruby/gems/1.9.1/gems/settingslogic-2.0.8/lib/settingslogic.rb:71:in `instance'
    from /opt/bitnami/ruby/lib/ruby/gems/1.9.1/gems/settingslogic-2.0.8/lib/settingslogic.rb:48:in `[]'
    from /opt/bitnami/apps/gitlab/htdocs/config/initializers/1_settings.rb:38:in `<top (required)>'
    from /opt/bitnami/ruby/lib/ruby/gems/1.9.1/gems/activesupport-3.2.13/lib/active_support/dependencies.rb:245:in `load'
    from /opt/bitnami/ruby/lib/ruby/gems/1.9.1/gems/activesupport-3.2.13/lib/active_support/dependencies.rb:245:in `block in load'
    from /opt/bitnami/ruby/lib/ruby/gems/1.9.1/gems/activesupport-3.2.13/lib/active_support/dependencies.rb:236:in `load_dependency'
    from /opt/bitnami/ruby/lib/ruby/gems/1.9.1/gems/activesupport-3.2.13/lib/active_support/dependencies.rb:245:in `load'
    from /opt/bitnami/ruby/lib/ruby/gems/1.9.1/gems/railties-3.2.13/lib/rails/engine.rb:588:in `block (2 levels) in <class:Engine>'
    from /opt/bitnami/ruby/lib/ruby/gems/1.9.1/gems/railties-3.2.13/lib/rails/engine.rb:587:in `each'
    from /opt/bitnami/ruby/lib/ruby/gems/1.9.1/gems/railties-3.2.13/lib/rails/engine.rb:587:in `block in <class:Engine>'
    from /opt/bitnami/ruby/lib/ruby/gems/1.9.1/gems/railties-3.2.13/lib/rails/initializable.rb:30:in `instance_exec'
    from /opt/bitnami/ruby/lib/ruby/gems/1.9.1/gems/railties-3.2.13/lib/rails/initializable.rb:30:in `run'
    from /opt/bitnami/ruby/lib/ruby/gems/1.9.1/gems/railties-3.2.13/lib/rails/initializable.rb:55:in `block in run_initializers'
    from /opt/bitnami/ruby/lib/ruby/gems/1.9.1/gems/railties-3.2.13/lib/rails/initializable.rb:54:in `each'
    from /opt/bitnami/ruby/lib/ruby/gems/1.9.1/gems/railties-3.2.13/lib/rails/initializable.rb:54:in `run_initializers'
    from /opt/bitnami/ruby/lib/ruby/gems/1.9.1/gems/railties-3.2.13/lib/rails/application.rb:136:in `initialize!'
    from /opt/bitnami/ruby/lib/ruby/gems/1.9.1/gems/railties-3.2.13/lib/rails/railtie/configurable.rb:30:in `method_missing'
    from /opt/bitnami/apps/gitlab/htdocs/config/environment.rb:5:in `<top (required)>'
    from /opt/bitnami/ruby/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:55:in `require'
    from /opt/bitnami/ruby/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:55:in `require'
    from /opt/bitnami/ruby/lib/ruby/gems/1.9.1/gems/sidekiq-2.8.0/lib/sidekiq/cli.rb:199:in `boot_system'
    from /opt/bitnami/ruby/lib/ruby/gems/1.9.1/gems/sidekiq-2.8.0/lib/sidekiq/cli.rb:47:in `parse'
    from /opt/bitnami/ruby/lib/ruby/gems/1.9.1/gems/sidekiq-2.8.0/bin/sidekiq:7:in `<top (required)>'
    from /opt/bitnami/ruby/bin/sidekiq:23:in `load'
    from /opt/bitnami/ruby/bin/sidekiq:23:in `<main>'

GitLab says it requires ruby 1.9.3, but here I see 1.9.1. Can that be problem?

A: It is strange. What are you using, the installer, the virtual machine or the cloud image? If the sidekiq server is not running it is possible that the repository was not created properly. Could you check if there is any error in the sidekiq log file?
/opt/bitnami/apps/gitlab/htdocs/logs/sidekiq.log
Did you modify any configuration file for GitLab?
EDITED:
The problem seems a wrong configuration in the gitlab.yml. It is also important the white spaces. Could you check your change in that file?
/opt/bitnami/ruby/lib/ruby/1.9.1/psych.rb:203:in `parse': (): found character that cannot start any token while scanning for the next token at line 73 column 1 (Psych::SyntaxError)
GitLab CI ships Ruby 1.9.3 latest stable version. The folder name uses 1.9.1 for backguard compatibility Why is my gem "INSTALLATION DIRECTORY:" ...1.9.1 when the "RUBY VERSION:" is 1.9.3
Please post the gitlab.yml file if you do not find the exact error.

A: In my case I had <tab> in my yml file.
It's quite strange error though!


Q: Group by and foreach I want to print only once the title and all related images id_post
table IMAGES
id_images | dir_image | post_id
     1      image1.jpg   1
     2      image2.jpg   1
     3      image3.jpg   1
     4      image4.jpg   1
     5      image5.jpg   2
     6      image6.jpg   2
     7      image7.jpg   2
     8      image8.jpg   2

table POSTS
id_post   |          slug        |   title
 1           title_post            Title Post
 2           title_post_2          Title Post 2

PHP code:
$slug = $_GET['slug'];
 $stmt = $DB_con->prepare("SELECT * FROM posts, images
                      WHERE posts.id_post = images.post_id
                      AND slug=:slug");
 $stmt->execute(array(":slug"=>$_GET['slug']));

 while($row=$stmt->fetch(PDO::FETCH_BOTH))
 {
 ?>

<?php print utf8_encode($row['title']);?>

<?php
}
?>

Accessing the page "Title post 2", the result is:
Title post 2
image5.jpg

Title post 2
image6.jpg

Title post 2
image7.jpg

Title post 2
image8.jpg

How to get the result:
Title post 2
image5.jpg
image6.jpg
image7.jpg
image8.jpg

How I enter the SQL statement the "group by" to group images:
SELECT * FROM posts, images
                     WHERE posts.id_post = images.post_id
                     AND slug=:slug

And then inside the while inserting a foreach with the images of the group by?
while($row=$stmt->fetch(PDO::FETCH_BOTH))
     {
     ?>

<?php print utf8_encode($row['title']);?>

    <?php
    }
    ?>

Inserting if not solve for me, it will be necessary to create several ifs

A: If you just want to do it in procedural PHP, you could do something like this:
$runningTitle = '';

while($row=$stmt->fetch(PDO::FETCH_BOTH)) {

    if ($row['title'] != $runningTitle) {
        $runningTitle = $row['title'];
        print "
";
        print utf8_encode($row['title']);
        print "
";
    }

    // now render images.

}

However I would recommend using a more object orientated approach to build the html string and then return it as a single string, to echo at the end, rather than rendering everything out procedurally. It's often tidier to complete all your program logic before rendering a page, rather than rendering while you are still asking the code to make decisions.
You are using PHP in it's traditional form - as a templating language. It has come a long way since then.

A: It's some easy and fast and if your "join" images are few, not many.
Your group by, use a GROUP BY and get all images concatenated by SEPARATOR with GROUP_CONCAT
SELECT
  posts.*,
  COUNT(0) total,
  GROUP_CONCAT(dir_image SEPARATOR '|') images
FROM
  posts
  INNER JOIN images ON (posts.id_post = images.post_id )
WHERE
  slug=:slug
GROUP BY
  id_post

This is your loop, create an array exploding the SEPARATOR over field "images" and do the loop
while ($row = $stmt->fetch(PDO::FETCH_BOTH)) {
    $aImages = explode('|', $row['images']);
    ?>

<?php print utf8_encode($row['title']); ?>

        <?php
            echo '
' . implode('

', $aImages) . '
'
        ?>

    <?php
}
?>

Or
while ($row = $stmt->fetch(PDO::FETCH_BOTH)) {
    $aImages = explode('|', $row['images']);
    ?>

<?php print utf8_encode($row['title']); ?>

        <?php
        foreach ($aImages as $sImage) {
        ?>
            <a href="<?php echo $sImage;?>"><?php echo $sImage; ?>
        <?php
        }
        ?>

    <?php
}
?>


Q: threading: function seems to run as a blocking loop although i am using threading I am trying to speed up web scraping by running my http requests in a ThreadPoolExecutor from the concurrent.futures library.
Here is the code:
import concurrent.futures
import requests
from bs4 import BeautifulSoup

urls = [
        'https://www.interactivebrokers.eu/en/index.php?f=41295&exch=ibfxcfd&showcategories=CFD',
        'https://www.interactivebrokers.eu/en/index.php?f=41634&exch=chix_ca',
        'https://www.interactivebrokers.eu/en/index.php?f=41634&exch=tase',
        'https://www.interactivebrokers.eu/en/index.php?f=41295&exch=chixen-be&showcategories=STK',
        'https://www.interactivebrokers.eu/en/index.php?f=41295&exch=bvme&showcategories=STK'
        ]

def get_url(url):
    print(url)
    r = requests.get(url)
    soup = BeautifulSoup(r.text, 'lxml')
    a = soup.select_one('a')
    print(a)

with concurrent.futures.ThreadPoolExecutor(max_workers=12) as executor:
    results = {executor.submit( get_url(url)) : url for url in urls}

    for future in concurrent.futures.as_completed(results):
        try:
            pass
        except Exception as exc:
            print('ERROR for symbol:', results[future])
            print(exc)

However when looking at how the scripts print in the CLI, it seems that the requests are sent in a blocking loop.
Additionaly if i run the code by using the below, i an see that it is taking roughly the same time.
for u in urls:
    get_url(u)

I have add some success in implementing concurrency using that library before, and i am at loss regarding what is going wrong here.
I am aware of the existence of the asyncio library as an alternative, but I would be keen on using threading instead.

A: You're not actually running your get_url calls as tasks; you call them in the main thread, and pass the result to executor.submit, experiencing the concurrent.futures analog to this problem with raw threading.Thread usage. Change:
results = {executor.submit( get_url(url)) : url for url in urls}

to:
results = {executor.submit(get_url, url) : url for url in urls}

so you pass the function to call and its arguments to the submit call (which then runs them in threads for you) and it should parallelize your code.


Q: mysql query show only 1 result i want to output the result based on todays date.
the problem is, the output only show 1 result?
database report table:
id  |  r_amount | id_therapist | date | time | t_tanning | t_deep

// this query works fine echoing all the result if i use while loop
$today = date('Y-m-d');
(1) $q = $db->query("SELECT * FROM report WHERE date='$today' ORDER BY date ASC")

// this query only show 1 output result?
(2) $q = $db->query("SELECT *, SUM(IF(t_tanning LIKE 'Pro Tan%', r_amount, 0)) AS totalProTan FROM report WHERE date='$today' ORDER BY date ASC")

while($r = $q->fetch_array(MYSQLI_ASSOC)) :
     // (1) echoing all result from database
     echo $r['r_amount'].'
';
     // (2) echoing only 1 result????
     echo $r['totalProTan'].'
';
endwhile;

A: If the date field is of type datetime, you'll have to do something like
SELECT ... WHERE DATE(date)=CURDATE()
Notice that I'm using curdate() in the query. There's no need to generate the date value in PHP. MySQL is perfectly capable of doing that itself.

A: Try adding a GROUP BY statement to the second SQL statement.

*

*you should group by the key of the elemnts you want to be shown in the end result

A: The use of the aggregate function SUM will result in a single result. You are asking the database to get all the rows then sum up a value and give you the value.
To see the result for many groups of values you have to add a group by clause.


Q: UISearchBar stays when seguing to another view controller via push I followed this guide: http://www.jhof.me/simple-uisearchcontroller-implementation/
The only difference in my code is
instead of self.tableView.tableHeaderView = self.searchController.searchBar;
I have self.navigationItem.titleView = self.searchController.searchBar;
When I segue from the results table view controller, the uisearchbar stays in the navigation bar.

A: I rewrite the sample from Apple, you can see I comment self.tableView.tableHeaderView = self.searchController.searchBar; then set it to navigation bar's title view, just like you. You can find search bar is here in snapshot.
- (void)viewDidLoad {
    [super viewDidLoad];

    APLResultsTableController *qresultsTableController = [[APLResultsTableController alloc] init];
    self.resultsTableController = qresultsTableController;
    _searchController = [[UISearchController alloc] initWithSearchResultsController:qresultsTableController];
    self.searchController.searchResultsUpdater = self;
    [self.searchController.searchBar sizeToFit];
//    self.tableView.tableHeaderView = self.searchController.searchBar;
    self.navigationItem.titleView = self.searchController.searchBar;
    self.searchController.hidesNavigationBarDuringPresentation = NO;

    // we want to be the delegate for our filtered table so didSelectRowAtIndexPath is called for both tables
    self.resultsTableController.tableView.delegate = self;
    self.searchController.delegate = self;
    self.searchController.dimsBackgroundDuringPresentation = NO; // default is YES
    self.searchController.searchBar.delegate = self; // so we can monitor text changes + others

    // Search is now just presenting a view controller. As such, normal view controller
    // presentation semantics apply. Namely that presentation will walk up the view controller
    // hierarchy until it finds the root view controller or one that defines a presentation context.
    //
    self.definesPresentationContext = YES;  // know where you want UISearchController to be displayed
}

snapshot is here,

UISearchBarController has a property named hidesNavigationBarDuringPresentation default is YES, set it to NO if you want to use it as navigation item's title view
self.searchController.hidesNavigationBarDuringPresentation = NO;

I have tested, it works. hope it helpful.


Q: how to fix "Error Connection Timed Out Error" of a codeigniter website on a godaddy server? I have uploaded a basic codeigniter website on godaddy server without any database connection. In the config file base url is set to the domain name, index_page is blank & uri_protocol is set to request_uri. I also have the .htaccess file with the code but not sure what to do in it. Here what should i do to remove this error?
I have tried playing with the base url and uri_protocol and also made changes to the .htaccess file but no help either.
My .htaccess code -

Options +FollowSymLinks
RewriteEngine on

# Send request via index.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/$1 [L]

A: Have your /folder/app/.htaccess like this:
<IfModule mod_rewrite.c>
    RewriteEngine on
    RewriteBase /folder/app/
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ /index.php/$1 [L]
</IfModule>

then in /folder/app/application/config/config.php you need to have this config:
$config['base_url']  = '';
$config['index_page'] = '';
$config['uri_protocol'] = 'AUTO';


Q: How can i format a string as currency in a data bound DataGrid in WPF C#? I have some data being shown in a DataGrid.  The data comes from SQL, where a "money" type can be null.  When i display this data, all is OK when i format the data in a double column format as currency.  ie:
internal void FillGrid()
        {
        bD = new DataTable();
        DataTable dt = EmployerQuery();  //queries the SQL DB

        bD.Columns.Add(new DataColumn("ID", typeof(int)));
        bD.Columns.Add(new DataColumn("EmployerName", typeof(string)));
        bD.Columns.Add(new DataColumn("FlatMinAmount", typeof(double)));
        bD.Columns.Add(new DataColumn("DistrictRate", typeof(double)));
        bD.Columns.Add(new DataColumn("VendorRate", typeof(double)));
        bD.Columns.Add(new DataColumn("Description", typeof(string)));
        bD.Columns.Add(new DataColumn("EmployeeCount", typeof(int)));

        foreach (DataRow sqlRow in dt.Rows)
        {
            var row = bD.NewRow();
            row["ID"] = sqlRow["ClientID"];
            row["EmployerName"] = sqlRow["OfficialName"];
            row["FlatMinAmount"] = sqlRow["FlatMinAmount"];
            row["DistrictRate"] = sqlRow["DistrictRate"];
            row["VendorRate"] = sqlRow["VendorRate"];
            row["Description"] = sqlRow["Description"];
            row["EmployeeCount"] = sqlRow["EmployeeCount"];

            bD.Rows.Add(row);

        }

However, I then save the data as a .csv file.  When i read that file back, the values for "FlatMinAmount" that were null are not allowed to be inserted into a column type double, so I cannot format the data columns as type double, since many are null.
<dg:DataGrid Name="newGrid" ItemsSource="{Binding ElementName=readGrid, Path=readGrid}" AutoGenerateColumns="False"
                 Margin="5" Height="175" Width="Auto" ColumnWidth="Auto">
        <dg:DataGrid.Columns>
            <dg:DataGridTextColumn Binding="{Binding ID}" Header="Employer ID" Width="Auto" IsReadOnly="True"/>
            <dg:DataGridTextColumn Binding="{Binding EmployerName}" Header="Employer Name" Width="Auto" IsReadOnly="True"/>
            <dg:DataGridTextColumn Binding="{Binding FlatMinAmount, StringFormat=C}" Header="FlatMinAmount" Width="Auto" IsReadOnly="True"/>
            <dg:DataGridTextColumn Binding="{Binding DistrictRate, StringFormat=C}" Header="District Rate" Width="Auto" IsReadOnly="True"/>
            <dg:DataGridTextColumn Binding="{Binding VendorRate, StringFormat=C}" Header="Vendor Rate" Width="Auto" IsReadOnly="True"/>
            <dg:DataGridTextColumn Binding="{Binding Description}" Header="Description" Width="Auto" IsReadOnly="True"/>
            <dg:DataGridTextColumn Binding="{Binding EmployeeCount}" Header="EmployeeCount" Width="*" IsReadOnly="True"/>
        </dg:DataGrid.Columns>
    </dg:DataGrid>

DataTable r = new DataTable();

        try
        {
            //string csv = string.Empty;

            //r.Columns.Add("ID", typeof(int));
            //r.Columns.Add("EmployerName", typeof(string));
            //r.Columns.Add("FlatMinAmount",typeof(double));
            //r.Columns.Add("DistrictRate", typeof(double));
            //r.Columns.Add("VendorRate", typeof(double));
            //r.Columns.Add("Description", typeof(string));
            //r.Columns.Add("EmployeeCount", typeof(int));

            r.Columns.Add("ID");
            r.Columns.Add("EmployerName");
            r.Columns.Add("FlatMinAmount");
            r.Columns.Add("DistrictRate");
            r.Columns.Add("VendorRate");
            r.Columns.Add("Description");
            r.Columns.Add("EmployeeCount");

            // Read sample data from CSV file
            using (CsvFileReader reader = new CsvFileReader(filename))
            {
                CsvRow row = new CsvRow();
                while (reader.ReadRow(row))
                {
                    //foreach (string s in row)
                    {
                        r.Rows.Add(row[0], row[1], row[2], row[3], row[4], row[5], row[6]);

                    }

                }
            }

(readGrid is then set to r in code-behind)
If they are string, then i cannot use the StringFormat=C in the binding to show $ etc.  Also, it seems I cannot style a DataGridTextColumn.  So, how can i display the values I read in from .csv as $xx.xx?

A: use Double.Parse() - http://msdn.microsoft.com/en-us/library/system.double.parse.aspx to format the value when you read it in.  This will allow you to use double and you can then apply the appropriate formatting for output.
Updated:
The issue you seem to be having that when reading from file the value is null and when reading from database it is DBNull.  By default DataTable allows for DBNull values.  If you want to mimic this for read, try the following
    DataTable r = new DataTable();
    try
    {
        r.Columns.Add("ID");
        r.Columns.Add("EmployerName");
        r.Columns.Add("FlatMinAmount");
        r.Columns.Add("DistrictRate");
        r.Columns.Add("VendorRate");
        r.Columns.Add("Description");
        r.Columns.Add("EmployeeCount");

        // Read sample data from CSV file
        using (CsvFileReader reader = new CsvFileReader(filename))
        {
            CsvRow row = new CsvRow();
            while (reader.ReadRow(row))
            {
                //foreach (string s in row)
                {
                    double d;
                    double? val2 = null;
                    double? val3 = null;
                    double? val4 = null;
                    if (Double.TryParse(row[2], out d)) val2 = d;
                    if (Double.TryParse(row[3], out d)) val3 = d;
                    if (Double.TryParse(row[4], out d)) val4 = d;

                    r.Rows.Add(row[0], row[1], val2, val3, val4, row[5], row[6]);
                }

            }
        }

A: Use the TargetNullValue attribute:
<dg:DataGridTextColumn Binding=""{Binding FlatMinAmount,TargetNullValue='Not Specified',StringFormat=C}" Header="FlatMinAmount" Width="Auto" IsReadOnly="True"/>

A: If you know the number is null, can't you just set the value of the column to DBNull?
row["FlatMinAmount"] = DBNull.Value;

Here's a little console app I ran to show this working:

class Program
    {
        static void Main(string[] args) {
            DataTable tbl = new DataTable();
            DataColumn col = new DataColumn("Blah", typeof(double));
            tbl.Columns.Add(col);

            DataRow row = tbl.NewRow();
            row["Blah"] = DBNull.Value;

            Console.WriteLine("Result: " + row["Blah"].ToString());
            Console.ReadKey();

        }
    }


Q: ag grid not retrieving data when mounted with vue using axios I have this strange case when trying to retrieve data from mongoDB using axios not showing on grid. It should be already successful given the data can already loaded into the view (already tested it), but it's nowhere inside beforeMount, mounted, or ready hook.
I already tried with
this.gridOptions.onGridReady = () => {
      this.gridOptions.api.setRowData(this.ticketData)
    }

but only yields partial success (unreliable),
here's a code snippet to show what I mean,
<template>
  <div class="ticketing">
    <ag-grid-vue  style="width: 100%; height: 350px;"
                  class="ag-fresh"
                  :gridOptions="gridOptions"
                  >
    </ag-grid-vue>
    {{testData}} <!--testData can be loaded-->
    <input type="button" @click.prevent="showData" value="test">  </div>
</template>

<script>
//import stuff

//header and url stuff

export default {
//component stuff

  data () {
    return {
      gridOptions: null,
      ticketData: [],
      testData: [] // only for testing purpose
    }
  },
  methods: {
     showData () {
      console.log('data shown')
      this.testData = this.ticketData // this is working
    }
  },
  beforeMount () {
    var vm = this
    axios.get(ticketingAPIURL, {'headers': {'Authorization': authHeader}})
      .then(function (response) {
        vm.ticketData = response.data
      }) // this is working
      .catch(function (error) {
        console.log(error)
      })
    this.gridOptions = {}
    this.gridOptions.rowData = this.ticketData // this is not working
    this.gridOptions.columnDefs = DummyData.columnDefs
  }
 // mount, ready also not working
}
</script>

To be more specific, I still can't determine what really triggers onGridReady of ag-grid in conjunction with Vue component lifecycle, or in other words, how can I replace button to show testData above with reliable onGridReady/Vue component lifecycle event?

A: You define vm.ticketData and after you call it like this.ticketData
You can change it by: this.rowData = vm.ticketData

A: You are setting this.gridOptions.rowData outside of the axios callback, so this.ticketData is still empty.
Set it inside the callback:
mounted() {
  var vm = this
  axios.get(ticketingAPIURL, {'headers': {'Authorization': authHeader}})
    .then(function (response) {
      vm.ticketData = response.data
      vm.gridOptions = {}
      vm.gridOptions.rowData = vm.ticketData
      vm.gridOptions.columnDefs = DummyData.columnDefs
    })
    .catch(function (error) {
      console.log(error)
    })
}

A: it is due to overlapped intialization between axios, ag-grid, and vue.
after much tinkering, I am able to solve it with using Vue's watch function:
  watch: {
    isAxiosReady(val) {
      if (val) {
        this.mountGrid() // initiate gridOptions.api functions
      }
    }
  }


Q: unexpected character '?' express When I run my server.js file I get a syntax error with something along the lines like the following:

Unexpected character ?  in the file @babel\core\lib\transformation\normalize-file.js:209

When I try to execute my server.js with following code:
import path from 'path';
import express from 'express';

var app = express();
var port = 3000;

app.get('/', (req, res) => res.send('Hello World!'))

app.listen(port, () => console.log(`Example app listening on port ${port}!`))

But its fine if I run it with following code:
import http from 'http';

http.createServer((req, res) => {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');
}).listen(1337, '127.0.0.1');

console.log('Server running at http://127.0.0.1:1337/');

There seems to be an issue with express and babel maybe?
I'll add the package.json and the .babelrc below:
package.json:
{
  "name": "counter",
  "version": "0.0.1",
  "private": true,
  "devDependencies": {
    "@babel/cli": "^7.0.0",
    "@babel/core": "^7.0.1",
    "@babel/node": "^7.0.0",
    "@babel/plugin-syntax-dynamic-import": "^7.0.0",
    "@babel/preset-env": "^7.0.0",
    "@babel/preset-react": "^7.0.0",
    "babel-plugin-dynamic-import-node": "^2.1.0",
    "enzyme": "^3.3.0",
    "enzyme-adapter-react-16": "^1.1.1",
    "express": "^4.16.3",
    "nodemon": "^1.18.4",
    "path": "^0.12.7",
    "react": "^16.5.1",
    "react-dom": "^16.5.1",
    "react-scripts": "^1.1.4"
  },
  "dependencies": {
    "prop-types": "^15.6.1",
    "react-redux": "^5.0.7",
    "redux": "^3.5.2"
  },
  "scripts": {
    "start": "nodemon --exec babel-node server\\server.js ",
    "build": "react-scripts build",
    "eject": "react-scripts eject",
    "test": "react-scripts test"
  }
}

.babelrc:
{
  "presets": ["@babel/preset-react","env"],
  "plugins": ["@babel/plugin-syntax-dynamic-import","dynamic-import-node"]
}


Q: Nested ALOGD statement I have situation where:
#define DBG_ALOGD(a)   ALOGD("%s:%d: ", __FUNCTION__, __LINE__); ALOGD a
#define DBG_MSG(a)    do { if (debuggable) {DBG_ALOGD(a);} } while (0)

DBG_MSG(a) used by the applications to print the logs.
DBG_MSG("Hi %d", 2);
will  print as
LOG_TAG: function_name:121
LOG_TAG: Hi 2

I wanted combine FUNCTION:LINE along with the "Hi 2" in single line.
I tried
#define DBG_ALOGD(a)   ALOGD("%s:%d:%s", __FUNCTION__, __LINE__, a)
#define DBG_MSG(a)    do { if (debuggable) {DBG_ALOGD(a);} } while (0)

It didn't worked as a is not a plain string it also have %d
Please suggest how can I change the #define to have a combination of these.

A: I think you can use the macro variable parameters (variadics) :
#include <stdio.h>

#define DBG_ALOGD(fmt, ...)   ALOGD("%s:%d: " fmt, __FUNCTION__, __LINE__, __VA_ARGS__ );
#define DBG_MSG(fmt, ...)    do { if (debuggable ) {DBG_ALOGD(fmt, __VA_ARGS__ );} } while (0)

int main(void)
{
    int debuggable = 1;
    DBG_MSG("%s(%d)\n", "test", 0);
    DBG_MSG("%s", "hello");

    return 0;
}

I tested it with printf function instead of ALOGD, but I think that the result will be the same.
Warning, you will not be able to call directly DBG_MSG("simple string") since the compiler will wait for something not empty in ...


Q: Symfony3 - Validation of an embedded form I have an embedded form like this:
-> Parent (class)
|---> Attribute 1 (collection) : children (class) : required
.......|-----> Attribute 1 : child_name (string) : required
.......|-----> Attribute 2 : child_description (string) : required
I want, when I send the form:

*

*There is at least one parent object sent (I mean the children attribute contains at least one row of (child_name and child_description)

If the data received will be like this :

*

*parent[children][__name__][child_name]=value1&parent[children][__name__][child_description]=value2
Where name is the iteration in the ArrayCollection of the attribute children
So when we send two children in the form, we get this data:

*

*parent[children][0][child_name]=value1&parent[children][0][child_description]=value2&parent[children][1][child_name]=value3&parent[children][1][child_description]=value4
I want that:

*If the user will send only nothing (empty form), he gets an error that the atribute children is required.

*If the user will send only the child_name (or the child_description) value, he gets an error that the child_description (or the child_name) is also required. I mean if he doesn't event send the varaible child_name (or child_description) in the form like this:

*

*parent[children][__name__][child_name]=value1 (without the name and the value of the variable parent[children][__name__][child_description])
I tried to validate this form from the Entity But I got some problems.
In the Parent Entity class:
/**
 * Parent
 *
 * @ORM\Table(name="parent")
 * @ORM\Entity
 */
class Parent
{

    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @var \Doctrine\Common\Collections\ArrayCollection
     *
     * @Assert\NotBlank(message="Error", groups={"Creation"})
     * @Assert\NotNull(message="Error", groups={"Creation"}))
     * @Assert\Count(
     *      min = 1,
     *      minMessage = "Error",
     *      groups={"Creation"}
     * )
     * @ORM\OneToMany(targetEntity="Children", mappedBy="parent", cascade={"ALL"}, orphanRemoval=true)
     */
    protected $children;

    public function __construct()
    {
        $this->children = new ArrayCollection();
    }

    /**
     * Add child
     *
     * @param Child $child
     * @return children
     */
    public function addChild(Child $child)
    {
        $this->children[] = $child;
        $child->setParent($this);
        return $this;
    }

    /**
     * Remove child
     *
     * @param Child $child
     */
    public function removeChild(Child $child)
    {
        $this->children->removeElement($child);
    }

    public function getChildren()
    {
        return $this->children;
    }

    /**
     * Get id.
     *
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }
}

Then, the Child Entity class:
/**
 * Child
 *
 * @ORM\Table(name="child")
 * @UniqueEntity(
 *     fields={"child_name","child_description"},
 *     message="already registred"
 * )
 */
class Child
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var Parent
     */
    private $parent;

        /**
         * @ORM\Column(name="child_name", type="string", length=255 )
         *
         * Assert\NotBlank(message="empty", groups={"Creation"})
         * Assert\NotNull(message="null", groups={"Creation"})
         * @Assert\Length(
         *     min=3,
         *     minMessage="too short",
         *     groups={"Creation"}
         * )
         * @Assert\Type(
         *     type="string",
         *     message="you need a string",
         *     groups={"Creation"}
         * )
         */
        private $child_name;

        /**
         * @ORM\Column(name="child_description", type="string", length=255 )
         *
         * Assert\NotBlank(message="empty", groups={"Creation"})
         * Assert\NotNull(message="null", groups={"Creation"})
         * @Assert\Length(
         *     min=3,
         *     minMessage="too short",
         *     groups={"Creation"}
         * )
         * @Assert\Type(
         *     type="string",
         *     message="you need a string",
         *     groups={"Creation"}
         * )
         */
        private $child_description;

    public function __construct()
    {}

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set childName
     *
     * @param string $childName
     *
     * @return Child
     */
    public function setChildName($childName)
    {
        $this->child_name = $childName;

        return $this;
    }

    /**
     * Get childName
     *
     * @return string
     */
    public function getChildName()
    {
        return $this->child_name;
    }

    /**
     * Set childDescription
     *
     * @param string $childDescription
     *
     * @return Child
     */
    public function setChildDescription($childDescription)
    {
        $this->child_description = $childDescription;

        return $this;
    }

    /**
     * Get childDescription
     *
     * @return string
     */
    public function getDescription()
    {
        return $this->child_description ;
    }

In the Controller class:
public function postChildrenAction(Request $request)
{
    $result = new Parent();
    $em = $this->get('doctrine.orm.entity_manager');
    $form = $this->createForm(ParentType::class, $result, array(
            'validation_groups' => array('Creation', 'Default'),
    ));
    $form->submit($request->request->get($form->getName()));
    if ($form->isSubmitted() && $form->isValid()) {
        //persistance
    }
}

In the ParentType class :
class ParentType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('children', CollectionType::class,array(
                'entry_type' => ChildType::class,
                'required'=> true,
                'allow_add' => true,
                'allow_delete'  => true,
                'by_reference' => false,
                'constraints' => array(new Valid()), // __LINE_A__
                'entry_options' => array(
                        'validation_groups' => $options['validation_groups'],
                        'required'=> true,
                ),
        ));

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => 'Path\NameBundle\Entity\Parent',
            'csrf_protection' => false,
            'validation_groups' => array('Creation', 'Default'),
            'cascade_validation' => true,
            'error_bubbling' => false,
        ]);
    }
}

And finally the ChildType:
class ChildType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('child_name',TextType::class,array('required'=> true,'validation_groups'=>$options['validation_groups']));
        $builder->add('child_description',TextType::class,array('required'=> true,'validation_groups'=>$options['validation_groups']));
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => 'Path\NameBundle\Entity\Child',
            'csrf_protection' => false,
            'validation_groups' => array('Creation', 'Default'),
            'cascade_validation' => true,
            'error_bubbling' => false,
        ]);
    }
}

*The first problem is in the Parent Entity class: when I remove the Assert\Count() constraint from the children attribute, the validation will succeed. So why the constraints NotBlank and NotNull doesn't work ?

*If I comment the line 'constraints' => array(new Valid()) (__LINE_A__) in the ParentType, the constraint UniqueEntity of ChildType will not work. Why ?

*None of the 'required' => true options in the ParentType and ChildType worked. When I send only the child name without a description (or the inverse), I got an SQL error saying that there is a null value of the description.

*When the form is empty the validation will succeed but I need to get an error when some data is missing (for the child object or the parent object).

*The groups option from the Parent/Child Entity classes doesn't work if the form is sent with a missing variable even when I enable 'cascade_validation' => true.
This is too hard.
And to finish with this post, I want to know :

*The constraints that we define in the Entity classes aren't the ones that validates the form ? Because when I create the same constraints in validation.yml (using NotBlank with child_name and child_description) the validation works fine and fails if there is a missing variable/data.

Thank you even by answering me to one of these questions.


Q: Link one model more than once I have a function where a user can request a project. The request has 2 fields for other employees to be added.
It's got a field for a person who is responsible for the project (person_responsible) and the employee who is supposed to attend the opening meeting (person_attending).
What I want to know is, since both these fields (person_responsible and person_attending) will be pulling it's data from hr_employees table, how would I set this up in my Project-Model.
At the moment I have the one field set up like this:
public $belongsTo = array(
    'HrEmployee' => array(
        'className' => 'HrEmployee',
        'foreignKey' => 'responsible_person',
        'fields' => 'HrEmployee.employeename',
    )
);

How would I set up the other field?

A: What I do in this cases is to make two associations. Since cake allow to customize relations, you can have two relations to the same model with different names.
public $belongsTo = array(
    'ResponsibleEmployee' => array(
        'className' => 'HrEmployee',
        'foreignKey' => 'responsible_person',
        'fields' => 'HrEmployee.employeename',
    ),
    'AttendingEmployee' => array(
        'className' => 'HrEmployee',
        'foreignKey' => 'person_attending',
        'fields' => 'HrEmployee.employeename',
    )
);

Change the names to adjust your needs. Now, if your model is set as containable and you retrieve the Project model with those models in it, you'll get something like
array('Project' => array(/*data project*/),
      'ResponsibleEmployee' => array(/*name*/),
      'AttendingEmployee' => array(/*name*/)
)

(or another variation of that array depending on how the query was made).


Q: why xpath cannot get the target element? I am quite new in scraping with xpath. I am trying to scrape product information on Target. I use selenium and xpath successfully get the price and name. But xpath cannot return any value when scraping for product sizeproduct size and sales locationsales location.
For example, for this url"https://www.target.com/p/pataday-once-daily-relief-extra-strength-drops-0-085-fl-oz/-/A-83775159?preselect=81887758#lnk=sametab", xpath for size is:
//*[@id="pageBodyContainer"]/div[1]/div[2]/div[2]/div/div[3]/div/div[1]/text()

xpath for sales location is:
//*[@id="pageBodyContainer"]/div[1]/div[2]/div[2]/div/div[1]/div[2]/span

I also try to get these two elements by using requests but it also did not work. Do anyone know why it happened? Any help appreciated. Thanks.
Following is my code:
    def job_function():
        urlList = ['https://www.target.com/p/pataday-once-daily-relief-extra-strength-drops-0-085-fl-oz/-/A-83775159?preselect=81887758#lnk=sametab',
        'https://www.target.com/p/kleenex-ultra-soft-facial-tissue/-/A-84780536?preselect=12964744#lnk=sametab',
        'https://www.target.com/p/claritin-24-hour-non-drowsy-allergy-relief-tablets-loratadine/-/A-80354268?preselect=14351285#lnk=sametab',
        'https://www.target.com/p/opti-free-pure-moist-rewetting-drops-0-4-fl-oz/-/A-14358641#lnk=sametab'
        ]

        def ScrapingTarget(url):
            AArray = []
            wait_imp = 10
            CO = webdriver.ChromeOptions()
            CO.add_experimental_option('useAutomationExtension', False)
            CO.add_argument('--ignore-certificate-errors')
            CO.add_argument('--start-maximized')
            wd = webdriver.Chrome(r'D:\chromedriver\chromedriver_win32new\chromedriver_win32 (2)\chromedriver.exe',
                                  options=CO)

            wd.get(url)
            wd.implicitly_wait(wait_imp)
            sleep(1)

            #start scraping
            name = wd.find_element(by=By.XPATH, value="//*[@id='pageBodyContainer']/div[1]/div[1]/h1/span").text
            sleep(0.5)
            price = wd.find_element(by=By.XPATH, value="//*[@id='pageBodyContainer']/div[1]/div[2]/div[2]/div/div[1]/div[1]/span").text
            sleep(0.5)
            try:
                size = wd.find_element(by=By.XPATH, value="//*[@id='pageBodyContainer']/div[1]/div[2]/div[2]/div/div[3]/div/div[1]/text()").text
            except:
                size = "none"
            sleep(0.5)
            try:
                sales location = wd.find_element(by=By.XPATH, value="//*[@id='pageBodyContainer']/div[1]/div[2]/div[2]/div/div[1]/div[2]/span").text
            except:
                sales location = "none"
            tz = pytz.timezone('Etc/GMT-0')
            GMT = datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")

            AArray.append([name, price, size, sales location, GMT])

            with open(
                    r'C:\Users\12987\PycharmProjects\python\Network\priceingAlgoriCoding\export_Target_dataframe.csv',
                    'a', newline="", encoding='utf-8') as f:
                writer = csv.writer(f)
                writer.writerows(AArray)

        with concurrent.futures.ThreadPoolExecutor(4) as executor:
            executor.map(ScrapingTarget, urlList)

    sched = BlockingScheduler()
    sched.add_job(job_function,'interval',seconds=60)
    sched.start()


Q: IOS image sizes for buttons I've read the human interface guidelines provided by apple.
Navigation Bar and Toolbar Icon Size:
Target size :
             72px × 72px (24pt × 24pt @3x)
             48px × 48px (24pt × 24pt @2x)
Max size:
             84px × 84px (28pt × 28pt @3x)
             56px × 56px (28pt × 28pt @2x)
Does this apply to regular buttons as well?
I have a few regular buttons with images inside them that are set to Max size (above) but I find its still to small.
Can I change the size to anything I see fit?

A: No. You can choose whatever size you want, just make sure the button or other elements are within safeAreaLayoutGuide.
Besides, the guidelines are just Guidelines , they guide you as to what might look most appropriate as per apple, but these are not necessarily restrictions that must be enforced.

A: They are guidelines not rules, go crazy with it.


Q: Which namespace (IBM.WMQ vs. IBM.WMQAX) should be used in the .NET library for IBM MQ WebSphere (amqmdnet.dll) I am writing an application that gets data from IBM WebSphere MQ.  IBM supplies a DLL with classes to interact with MQ.  However, there appear to be two main namespaces; IBM.WMQ and IBM.WMQAX.  The latter seems to be a newer addition, but the former appears to be what vague answers on various web sites suggest using for .NET applications.  I was hoping someone here might be able to enumerate the real differences and what advantages/disadvantages the classes in each namespace offer.

A: From this thread:

The IBM.WMQ is IBM's version of Neil Kolban's original work of
  converting the Java classes for MQ to classes for the .NET framework.
The IBM.WMQAX is IBM's COM component for accessing MQ (ActiveX)
If you're coding in .NET, use IBM.WMQ since it's managed code. If
  you're coding in VB6 or VC++ then use the ActiveX com component.
You could use the COM component from .NET using COM Interop, but that
  really would only make sense, IF, the classes for .NET were NOT
  available. Seeing that they are, use IBM.WMQ.

A: You need to use IBM.WMQ namespace for developing .NET applications to interact with IBM MQ Queue Manager. The other one, IBM.WMQAX namespace is for ActiveX applications.

A: This thread, linked in the answer by @stuartd contains some valuable information.  While the part in his quote seems partially incorrect, additional comments in the thread do a better job clarifying.  While I never used VB script or ActiveX, and thus don't quite follow the problem that the IBM.WMQAX namespace was looking to solve, I can ascertain from the discussion that the namespace should be avoided when writing a new .NET application from scratch.


Q: How to get array element containing '/' in the string array I have a string array which I have split based on the white space. Now, as per my requirements, I have to get the array element which contains '/' in its contents, but I am not able to get it. I don't understand how to achieve it.
Here is the code that I have tried:
 string[] arrdate = currentLine.Split(' ');

How do I get the array element consisting of a /?

A: Try this:
 string[] arrdate = currentLine.Split(' ');
 var dateItems = arrdate.Where(item => item.Contains("/")).ToArray()

A: foreach (string s in arrdate)
{
   if (s.contains("/"))
   {
       //do something with s like add it to an array or if you only look for one string assign it and break out of the loop.
   }
}

A: if you want to get only one item then try this
// split on the basis of white space
string[] arrdate = currentLine.Split(' ');

// now find out element with '/' using lambda
string item = arrdate.Where(item => item.Contains("/")).FirstOrDefault();

// if you don't want to use lambda then try for loop
string item;
for(int i = 0; i < arrdate.Length; i++)
{
if(arrdate[i].Contains("/"))
{
item = arrdate[i]
}
}

A: // split on the basis of white space
string[] arrdate = currentLine.Split(' ');

// now find out element with '/' using lambda
string item = arrdate.Where(item => item.Contains("/")).FirstOrDefault();

// if you don't want to use lambda then try for loop
string item;
for(int i = 0; i < arrdate.Length; i++)
{
if(arrdate[i].Contains("/"))
{
item = arrdate[i]
}
}


Q: how do i invoke 32 bit gdb installed on Centos 64 I have Centos7 and I see both 32 and 64 bit version of gdb are installed however /usr/bin/gdb is the 64bit version. How can I invoke 32bit gdb version since i need to debug application compiled with -m32 compiler option

A: The 64-bit GDB is perfectly capable of debugging both 64 and 32-bit programs. You don't need to invoke 32-bit GDB.


Q: Npm - fetch vs node-fetch? These package names are pretty confusing, they seem like they do the same thing yet 'fetch' looks to be abandoned yet not marked as deprecated (last commit 3 years ago). Judging from the download counts people are probably downloading 'fetch' when they should get the supported and maintained 'node-fetch' package.
If you're building a Reactjs app, is fetch already built in? If so, is it different than 'node-fetch'?
What is the suggested package npm users should use?
https://www.npmjs.com/package/fetch
https://www.npmjs.com/package/node-fetch

A: A bit of history
Fetch is a standard created in 2015 by the Web Hypertext Application Technology Working Group (WHATWG). It was meant to replace the old and cumbersome XMLHttpRequest as means for issuing web requests. As it was meant to replace XMLHttpRequest the standard was clearly targeted at browsers rather than Node runtime, however due to it's wide adoption and for cross compatibility reasons, it was decided that it should also be implemented in Node.
Nonetheless, it took Node team roughly 3 years to implement experimental fetch in Node v16. Although still experimental it is now enabled by default in Node v18.
Because it took Node dev team so long to implement the Fetch standard, the community took matter in their own hands and created the node-fetch package which implements the Fetch standard.
The fetch package that you have mentioned is just coincidentally named the same as the standard but it has nothing to do with it other than that they both aim to "fetch"/"request" resources from the web.
What should you use?
In the past browsers used XMLHttpRequest API and Node used its own http.request. We now have the opportunity to bring those two ecosystems closer still by having them both use the Fetch API. This increases code interoperability and even allows code sharing between the browser and Node in certain cases.
Now, there are other popular packages out there such as axios or requests that still don't use Fetch under the hood but rather continue using Node's http library. Not using Fetch reduces inter-compatibility and therefore I don't think you should keep using either of them unless they convert, which is unlikely in the near future.
Instead, you should consider using Node's native fetch or node-fetch package . Which one though? Well, my opinion is that the Node's fetch is still in early phases but given it has the support from the core Node team I would bet on that. I suppose node-fetch has a wider adoption of the Fetch standard but I think over time it will become redundant as the Node's native fetch becomes fully implemented.

A: Both does the same thing, only difference what i see is node-fetch is compatible API on Node.js runtime,
fetch is more specific to browser.


Q: Javascript ternary operator -- what is the condition? I read a handful of SOF posts on ternary operators but I'm still confused with this example:
var str = "I want to count";
var counts = {};
var ch, index, len, count;

for (index = 0; index < str.length; ++index) {
    ch = str.charAt(index);
    count = counts[ch];
    counts[ch] = count ? count + 1 : 1; // TERNARY
}

I know the syntax is
condition ? expression1 : expression2
But I am trying to practice and break up the ternary into an if-else.
I don't know what the condition is supposed to be
counts[ch] = count // this isn't a condition, it's assigning a value...

A: The ternary
counts[ch] = count ? count + 1 : 1;

The condition in this expression is not counts[ch] = count but just count and is equivalent to
if (count){
    counts[ch] = count + 1;
}
else {
    counts[ch] = 1;
}

The right hand side of an assignment expression is always evaluated first and the counts[ch] is assigned the result of count ? count + 1 ? 1.

A: You're conflating the ternary with the assignment expression.
The code
counts[ch] = count ? count + 1 : 1;

can also be written as
counts[ch] = (count ? count + 1 : 1);
// but not (counts[ch] = count) ? count + 1 : 1
// that does something entirely different

And then, writing the matching if/else becomes pretty clear
if (count) {
   counts[ch] = count + 1;
} else {
   counts[ch] = 1;
}


Q: My 3D racing game has some problems like wheels turning y axis and car not going anywhere My car's tires spin but the car doesn't move an inch and the wheels turn into y axis instead of left and right. Here is my code, i added rigidbody and boxcollider onto my car aswell maybe that's a problem causing the car not to move? (i made sure to put the collider above the wheels to make sure that they spin.)
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CarController : MonoBehaviour
{
    private float horizontalInput;
    private float verticalInput;
    private float steerAngle;
    private bool isBreaking;

    public WheelCollider FrontLeftCollider;
    public WheelCollider FrontRightCollider;
    public WheelCollider BackLeftCollider;
    public WheelCollider BackRightCollider;
    public Transform FrontLeftTransform;
    public Transform FrontRightTransform;
    public Transform BackLeftTransform;
    public Transform BackRightTransform;

    public float maxSteeringAngle = 30f;
    public float motorForce = 50f;
    public float brakeForce = 0f;

    private void FixedUpdate()
    {
        GetInput();
        HandleMotor();
        HandleSteering();
        UpdateWheels();
    }

    private void GetInput()
    {
        horizontalInput = Input.GetAxis("Horizontal");
        verticalInput = Input.GetAxis("Vertical");
        isBreaking = Input.GetKey(KeyCode.Space);
    }

    private void HandleSteering()
    {
        steerAngle = maxSteeringAngle * horizontalInput;
        FrontLeftCollider.steerAngle = steerAngle;
        FrontRightCollider.steerAngle = steerAngle;
    }

    private void HandleMotor()
    {
        FrontLeftCollider.motorTorque = verticalInput * motorForce;
        FrontRightCollider.motorTorque = verticalInput * motorForce;

        brakeForce = isBreaking ? 3000f : 0f;
        FrontLeftCollider.brakeTorque = brakeForce;
        FrontRightCollider.brakeTorque = brakeForce;
        BackLeftCollider.brakeTorque = brakeForce;
        BackRightCollider.brakeTorque = brakeForce;
    }

    private void UpdateWheels()
    {
        UpdateWheelPos(FrontLeftCollider, FrontLeftTransform);
        UpdateWheelPos(FrontRightCollider, FrontRightTransform);
        UpdateWheelPos(BackLeftCollider, BackLeftTransform);
        UpdateWheelPos(BackRightCollider, BackRightTransform);
    }

    private void UpdateWheelPos(WheelCollider wheelCollider, Transform trans)
    {
        Vector3 pos;
        Quaternion rot;
        wheelCollider.GetWorldPose(out pos, out rot);
        trans.rotation = rot;
        trans.position = pos;
    }

}

If needed i can send screenshots of things please don't be shy to ask.
I haven't tried anything too afraid to make it worse

A: A rigidbody will not move until some kind of force is applied to it, or you use it's MovePosition method. Here is a link ... https://docs.unity3d.com/ScriptReference/Rigidbody.MovePosition.html


Q: Embedded database in Java EE application Good day. I'm confused about storing the embedded database in a Java EE application. I've just resolved the problem with the .properties file which can be accessed via getResource method, but where should I put my database to support portability?

A: For portability, the appropriate way is to install the embedded database in the project directory & then specifying the relative path.
In general, you have to extract the content & specifying that path relative to the current directory as database url. Below are some examples.

*

*H2 Database - jdbc:h2:file:relative-database-path

*Apache Derby - By including required jars in classpath & configuring environment variable accordingly.

*HSQLDB - jdbc:hsqldb:file:relative-database-path


Q: Incorrect string value: '\xCC_a' for column when inserting I am attempting to run a sql query but get the following error:
Incorrect string value: '\xCC_a' for column

CSV File line that breaks mysql query:
Juan Gordon,GarcÃ_a,noman@gmail.com,,,,,,,,,,y,

SQL Error:

Error Number: 1366

Incorrect string value: '\xCC_a' for column 'last_name' at row 1

INSERT INTO `phppos_people` (`first_name`, `last_name`, `email`, `phone_number`, `address_1`, `address_2`, `city`, `state`, `zip`, `country`, `comments`) VALUES ('Juan Gordon', 'Garc�_a', 'noman@test.com', '', '', '', '', '', '', '', '')

Filename: /Library/WebServer/Documents/phppos/PHP-Point-Of-Sale/models/person.php

Line Number: 75

last_name is varchar(255) utf8_unicode_ci
$db['default']['char_set'] = 'utf8';
$db['default']['dbcollat'] = 'utf8_unicode_ci';

Example CSV code

?>

last_name = GarcÌ_a

UPDATE: I just learned that when saving the file as a .csv in excel the encoding is: Westren (Mac OS Roman) with CR as line breaks.
I think that file encoding might cause the problem. But I need to support it.

A: The only Excel that exports to Mac OS Roman apparently is MS Excel for OSX. Unfortunately I don't have this so I can't check how to export with the correct character set
You now have two choices
a) Convert the CSV to UTF-8 using iconv for example
iconv -f MACROMAN -t UTF8 < yourfile.csv > yourfile-utf8.csv

b) Set the connection charset to the character set of the file before you import
SET NAMES macroman;

In codeigniter this would look like this
$this->db->simple_query('SET NAMES \'macroman\'');

After your import is done, don't forget to set it back
$this->db->simple_query('SET NAMES \'utf8\'');

Explanation:
If your connection charset is UTF-8, your database excepts UTF-8 encoded data. If you set the connection charset to macroman and the columns you write to are UTF-8, MySQL will automatically convert this for you.

From http://dev.mysql.com/doc/refman/5.5/en/charset-connection.html
SET NAMES 'charset_name' [COLLATE 'collation_name']
SET NAMES indicates what character set the client will use to send SQL statements to the  server. Thus, SET NAMES 'cp1251' tells the server, “future incoming messages from this  client are in character set cp1251.” It also specifies the character set that the server  should use for sending results back to the client. (For example, it indicates what character set to use for column values if you use a SELECT statement.)

On my freeBSD machine, MySQL has the macroman character set compiled in, I suppose you'll also have this.
mysql> SELECT * FROM information_schema.COLLATIONS WHERE CHARACTER_SET_NAME = 'macroman';
+---------------------+--------------------+----+------------+-------------+---------+
| COLLATION_NAME      | CHARACTER_SET_NAME | ID | IS_DEFAULT | IS_COMPILED | SORTLEN |
+---------------------+--------------------+----+------------+-------------+---------+
| macroman_general_ci | macroman           | 39 | Yes        | Yes         |       1 |
| macroman_bin        | macroman           | 53 |            | Yes         |       1 |
+---------------------+--------------------+----+------------+-------------+---------+

Also see http://dev.mysql.com/doc/refman/5.5/en/charset-charsets.html
Hope this helps


Q: If WPF Richtextbox Highlight word contains hyphen,thin line shown in the word? I am working in WPF RichTextBox.I have highlighted each word,using the below code.its works fine.But the word contains hyphen means,the highlighted word has some thin lines between the hyphen.
string SelectHighlightWord(RichTextBox rtb, int offset, int length)
{
    TextRange fullRange = new TextRange(rtb.Document.ContentStart, rtb.Document.ContentEnd);
    fullRange.ClearAllProperties();
    TextPointer startSelect = fullRange.Start.GetPositionAtOffset(offset);
    TextPointer endSelect = startSelect.GetPositionAtOffset(length);
    TextRange textRange = rtb.Selection;
    textRange.Select(startSelect, endSelect);
    textRange.ApplyPropertyValue(TextElement.BackgroundProperty, new SolidColorBrush(m_backgroundColor));
    textRange.ApplyPropertyValue(TextElement.ForegroundProperty, new SolidColorBrush(m_foregroundColor));
    FrameworkContentElement fce = (startSelect.Parent as FrameworkContentElement);
    if (fce != null)
    {
        fce.BringIntoView();
    }

    return rtb.Selection.Text;
}

Note : I have added images for better understanding.

A: Is your window setting TextOptions.TextFormattingMode on Ideal? If so, try setting Display.


Q: CSS add seperator after
*-Tag I'm tring to edit the Wordpress homepage of my friend.
He uses a free Template and want to add an seperator "|" after each of his menu items.
I tried it with this one.
#menu-mainmenu li + li:before {
    content: " | ";
    padding: 0 15px;
}

Format looks like this

...

...

...

...

The Pipes appear over the
*-Tag.

This is what I want to do

A: I had to make a lot of guesses here because you didn't include much code or explanation for what you are trying to achieve but I think I have managed to create the overall appearance of what you want.
I have created two ways that this works, one which should work for anyone and another which will work for everyone but work specifically in your case
Number one:

#menu-mainmenu li {
  position: relative;
  display: inline-block;
  float: left;
}

#menu-mainmenu li:not(:first-child):after {
  content: " | ";
  position: relative;
  display: inline-block;
  float: left;
  margin: 0 15px;
}

HOME

ABOUT

...

...

Number two:

#menu-mainmenu li {
  position: relative;
  display: inline-block;
  float: left;
}

#menu-mainmenu li.line {
  margin: 0 15px;
}

HOME

|

ABOUT

|

...

|

...

A: I would use :after instead of :before

#menu-mainmenu li {
  display: inline-block;
}

#menu-mainmenu > li:after {
    content: " | ";
    padding: 0 15px;
}

#menu-mainmenu > li:last-child:after {
  content: "";
}

Link 1

Link 2

Link 3

Link 4

A: Using your CSS example , you'll need the follow:
#menu-mainmenu li{
   display:inline-block;
}

Run this snippet:

#menu-mainmenu li {
  display: inline-block;
}

#menu-mainmenu li + li:before {
    content: " | ";
    padding: 0 15px;
}

Item 1

Item 2

Item 3

Item 4

https://jsfiddle.net/6936pon8/1/

A: So, since you were unable to share the code, I had to simulate the error, and my guess was that the
 has a fixed width, so in the first example we have the possible error, please verify if that's your case. If it is, the second example will give you the asnwer.
Posible Error

#menu-mainmenu li {
  display: inline-block;
  width: 40px;
}

#menu-mainmenu li + li:before {
    content: " | ";
    padding: 0 15px;
}

hola

...

cómo

está

Fix

#menu-mainmenu li {
  display: inline-block;
  width: 50px;
  position: relative;
}

#menu-mainmenu li + li:before {
    content: " | ";
    position: absolute;
    left: -10px;
}

hola

.........

cómo

está

You can play around with absolute positioned elements as long as its parent is a relative element.
One more time, please submit as much code as you can so we can help you out, otherwise if nobody finds an answer it will be a waste of time.

A: #menu-mainmenu li:after {
    content: " | ";
    padding: 0 15px;
}

#menu-mainmenu li:last-child:after {
  content:"";
}

A:
Hey! check this out :)

* {
 margin: 0;
 padding: 0;
 box-sizing: border-box;
 -webkit-box-sizing : border-box;
        list-style-type : none;
}

#menu-mainmenu li {
       display: inline-block;
       padding: 5px 10px;
}

#menu-mainmenu li:after {
      content : " | ";
      display: inline-block;
      width : 10px;
      height : 30px;
      padding-left : 5px;
      margin-left : 10px;
      background-color: yellow;
      font-size : 25px;
}

first

second

third

forth


Q: importing converted data using pandas I have a csv file that looks like this:
patient_id  age_in_years    CENSUS_REGION   URBAN_RURAL_STATUS  YEAR    MONTH   DAY_NUMBER_IN_MONTH race
11511   7   Northeast   Urban   2011    6   20  Other
9882613 73  South   Urban   2011    7   25  Unknown
32190339    49  West    Urban   2011    8   13  Caucasian
...

I have converted the categorical data in this file (e.g., race, census region, urban/rural status, etc.) into binary vector objects using the following method:
def URSTATUS_to_numeric(a):
if a == 'Urban':
    return [1, 0, 0]
if a == 'Rural':
    return [0, 1, 0]
if a == 'NULL':
    return [0, 0, 1]

df['URSTATUS_num'] = df['URBAN_RURAL_STATUS'].apply(URSTATUS_to_numeric)

I want to use these vectors for linear regression analysis but I'm unable to call them using the following the code:
def import_data(file_name):
 df = pd.read_csv(file_name).drop_duplicates()
 X_parameter = []
 #Y_parameter = []
 for alpha in zip(df['age_in_years']):
       X_parameter.append([float(alpha)])
       #Y_parameter.append(float(beta))
 return X_parameter#, Y_parameter

X = import_data(filename)

Y = df['URSTATUS_num']

The error that I'm getting is this:
TypeError: float() argument must be a string or a number

A: If you're just iterating over that series to build a list of floats, you could instead use astype(float).
It seems like you have some values in that column, though, that cannot be converted to float. For the sake of troubleshooting, maybe just try
for alpha in zip(df['age_in_years']):
    try:
       X_parameter.append([float(alpha)])
    except:
       print alpha

You should be able to replace that whole function using
X = pd.read_csv(file_name).drop_duplicates()['age_in_years'].astype(float)


Q: Incorrect path to S3 flysystem adapter in Laravel 5 I'm having an issue with Laravel 5's filesystem when uploading files to an S3 bucket. The line that is running to the filesystem is:
Storage::disk('s3')->put($slug, $img);

It works as it should for:
Storage::disk('local')->put($slug, $img);

But when I change the disk to S3 it throws the following error:
Class 'League\Flysystem\AwsS3v3\AwsS3Adapter' not found

As per the L5 docs, I have the following requirement in my composer.json
"league/flysystem-aws-s3-v2": "~1.0"

which installed league's aws flysystem adapter under:
League\flysystem-aws-s3-v2\

I have tried updating the path in the fileSystemManager.php in the filesystem vendor folder to the aws flysystem installation path but it still doesn't work. I can't seem to find anyone else who has experienced this behaviour.
A fresh pair of eyes or a knowledgeable head who might know more about Laravel than I would be great. I really can't seem to the issue.
UPDATE
I did a fresh install of the aws flysystem and not I get the following:
ErrorException in Util.php line 250:
fstat() expects parameter 1 to be resource, object given

A: Ok so I fixed the initial issue by removing aws/aws-sdk-php : "^2.8.* that I had in my composer.json and ran a fresh 'composer require league/flysystem-aws-s3-v3 ~1.0'. This fixed the initial error in finding the S3 flysystem.
The second error fstat() expects parameter 1 to be resource, object given related to my attempt to pass an image object to the put method:
Storage::disk('s3')->put($slug, $img);

when it expects a string. This was fixed by stringifying the $img object
Storage::disk('s3')->put($slug, $img->__toString());

Hope this helps somebody else who might encounter this issue.


Q: Excel CountIF on date AND time I see lots of examples of how to work with times OR dates, but not a lot seems to be done with date AND time values.
I have the following data:

And would like the sum of some weights between specific date and times (shift patterns):
So

*

*I need all the weights between "17/07/2014 06:00" and "17/07/2014 14:00"

*I need all the weights between "17/07/2014 14:00" and "17/07/2014 22:00"

*I need all the weights between "17/07/2014 22:00" and "18/07/2014 06:00"

Yes, I can split the dates and times and deal with them separately, but there must be an easier way (it gets rather convoluted in the 3rd scenario)
By the way, the date to compare against will be calculated using "=DATE(YEAR(NOW()),MONTH(NOW()),DAY(NOW())-1)" for yesterdays date (stored in F11)
I have an entire page of different variations of attempts at this, which I wont post all of, but mainly:
 =SUMIFS(
   Last36Hours!$K$2:$K$10000,
   Last36Hours!$T$2:$T$10000,">=" &
      DATE(YEAR(F11),MONTH(F11),DAY(F11)) &
      TIME(6,0,0)
 )

should give me everything after yesterday 6am, but i get absolutely squat.

A: Very Close. Excel stores dates and times as days and fractions of days since 1/1/1900 or 1/1/1904. You need to ADD the time to the date, not concatenate.  And you can simplify getting the Date portion from F11. Try:
=SUMIFS(
   Last36Hours!$K$2:$K$10000,
   Last36Hours!$T$2:$T$10000,">=" &
     INT(F11)+ TIME(6,0,0))

You could also hard code yesterday at 6AM by replacing
DATE(YEAR(F11),MONTH(F11),DAY(F11)) & TIME(6,0,0)

with
TODAY()-0.75

which is the same as:
TODAY() - 1 + TIME(6,0,0)


Q: List to varargs with pre-difined size or without size What is the better way to convert List to varargs to call below 'builder( String... s )' method.
builder( stringList.toArray( new String[stringList.size()] ) );//with pre-difined array size

or
builder( stringList.toArray( new String[0] ) );//without predifined size

for example
void test() {

  List<String> stringList = new ArrayList<>();
  builder( stringList.toArray( new String[stringList.size()] ) );//call builder method with pre-difining array size
  builder( stringList.toArray( new String[0] ) );//call builder method with array size 0

}

void builder( String... s )
{

}

I faced this question in a review and I was suggested that builder( stringList.toArray( new String[0] ) ) is more efficient than
using builder( stringList.toArray( new String[stringList.size()] ) ).
Is there a significant difference between these two?
Thanks

A: To my understanding
stringList.toArray( new String[stringList.size()] ) )

is more efficient. The reason:
The argument is needed to have an actual type (String) for a generic List<String>, where the generic type parameter is erased at run-time.
The argument is used for the resulting array if its size matches the list size.
If the size is 0, the passed array is discarded.
So passing a correct array saves one object creation.
Of course list.size() is called extra. So it might be slower. I doubt it.

Correction
See Arrays of Wisdom of the Ancients.
A correct benchmark shows the inverse: new String[0] being faster.
I just overflew the very interesting analysis, and it seems:

*

*(an extra short lived new String[0] is irrelevant;)

*doing the array copying local in the toArray method allows a different, faster array copy;

*(and then there is the extra call to size.)

Mind, I did not sufficiently thorough read the article; it really is interesting.
Conclusion (counter-intuitively): new T[0] is faster.
Mind that:

*

*code checkers might still think differently and issue a warning;

*this is with warming up: till the hotspot JIT kicks in, it may be the other way around.

A: builder(stringList.toArray(new String[0])) is slightly less efficient since you create an empty array that will be discarded and never used after the method returns. toArray will have to create a new array in order to store the elements of the List.
On the other hand, builder(stringList.toArray(new String[stringList.size()])) passes an array of the required length to the toArray method, and therefore that method will use that array instead of creating a new array.

A: There is a difference and it's mainly outlined by the Alexey Shipilev. Long story short:

toArray(new T[0]) seems faster, safer, and contractually cleaner, and therefore should be the default choice now

A: I thought that c.toArray(new String[c.size()])) is more efficient, because we define here an array with required size.
BUT!!
IntelliJ IDEA has Collection.toArray() inspection, which is on by default. This is description:

There are two styles to convert a collection to an array: either using
  a pre-sized array (like c.toArray(new String[c.size()])) or using an
  empty array (like c.toArray(new String[0]).
In older Java versions
  using pre-sized array was recommended, as the reflection call which is
  necessary to create an array of proper size was quite slow. However
  since late updates of OpenJDK 6 this call was intrinsified, making the
  performance of the empty array version the same and sometimes even
  better, compared to the pre-sized version. Also passing pre-sized
  array is dangerous for a concurrent or synchronized collection as a
  data race is possible between the size and toArray call which may
  result in extra nulls at the end of the array, if the collection was
  concurrently shrunk during the operation.
This inspection allows to follow the uniform style: either using an
  empty array (which is recommended in modern Java) or using a pre-sized
  array (which might be faster in older Java versions or non-HotSpot
  based JVMs).

So it seems, that after JDK6, we should use c.toArray(new String[0]). My personal opinion, is that it doesn't matter what aporoach to use this time. Only if profiler says that this is a bottle neck, then we should worry about it.


Q: Console Application - How to access the properties in JSON? I need to access the json properties so that I will be able to filter the result based on registers devices (either AEVL2020 or AEVL2021) but, I can't figure out how to access it. It seems like the RootObject can't access anything. I'm doing this for about 2 days now, so I need help.
Here is my json:
{
"registers":{
        "AEVL2020":[
            {
                "user_id": "1",
                "employee_id": "12",
                "name": "Juan Dela Cruz",
                "privilege": "0"
            },
            {
                "user_id": "2",
                "employee_id": "32",
                "name": "Pedro Dela Cruz",
                "privilege": "0"
            }
        ],
        "AEVL2021":[
            {
                "user_id": "1",
                "employee_id": "29",
                "name": "Maria Del Mundo",
                "privilege": "0"
            },
            {
                "user_id": "2",
                "employee_id": "222",
                "name": "Jay Del Mundo",
                "privilege": "0"
            }
        ]
    }
}

my C#:
static void Main(string[] args)
{
    using (StreamReader r = new StreamReader("C:\\Users\\Admin\\source\\repos\\Practice1\\Practice1\\company1.json"))
    {
        string json = r.ReadToEnd();
        var root = JsonConvert.DeserializeObject<RootObject>(json);

        // This is where the error, I can't access either AEVL2020 or AEVL2021
        foreach (var p in root.AEVL2020 || root.AEVL2021)
        {
            Console.WriteLine(p.user_id + p.name + p.employee_id + p.privilege);
        }
    }
}

public class AEVL2020
{
    public string user_id { get; set; }
    public string employee_id { get; set; }
    public string name { get; set; }
    public string privilege { get; set; }
}

public class AEVL2021
{
    public string user_id { get; set; }
    public string employee_id { get; set; }
    public string name { get; set; }
    public string privilege { get; set; }
}

public class Registers
{
    public List<AEVL2020> AEVL2020 { get; set; }
    public List<AEVL2021> AEVL2021 { get; set; }
}

public class RootObject
{
    public Registers registers { get; set; }
}

A: You can define single AEVL class for both AEVL2020  and AEVL2020  as follow:
public class AEVL
{
    public string user_id { get; set; }
    public string employee_id { get; set; }
    public string name { get; set; }
    public string privilege { get; set; }
}

public class Registers
{
    public List<AEVL> AEVL2020 { get; set; }
    public List<AEVL> AEVL2021 { get; set; }
}

Then your code would be like this and you can get items based on given string:
var aevlProp = root.registers.GetType().GetProperty("AEVL2020");
var values = (aevlProp.GetValue(root.registers, null) as List<AEVL>);

foreach (var p in values)
{
    Console.WriteLine(p.user_id + p.name + p.employee_id + p.privilege);
}

Output for  GetProperty("AEVL2020");
1Juan Dela Cruz120
2Pedro Dela Cruz320

Output for  GetProperty("AEVL2021");
1Maria Del Mundo290
2Jay Del Mundo2220

A: Something like this i guess
Given
public class SomeObject
{
   public string user_id { get; set; }
   public string employee_id { get; set; }
   public string name { get; set; }
   public string privilege { get; set; }
}

public class RootObject
{
   public Dictionary<string, List<SomeObject>> registers { get; set; }
}

Usage
var input = "{\r\n\"registers\":{\r\n        \"AEVL2020\":[\r\n            {\r\n                \"user_id\": \"1\",\r\n                \"employee_id\": \"12\",\r\n                \"name\": \"Juan Dela Cruz\",\r\n                \"privilege\": \"0\"\r\n            },\r\n            {\r\n                \"user_id\": \"2\",\r\n                \"employee_id\": \"32\",\r\n                \"name\": \"Pedro Dela Cruz\",\r\n                \"privilege\": \"0\"\r\n            }\r\n        ],\r\n        \"AEVL2021\":[\r\n            {\r\n                \"user_id\": \"1\",\r\n                \"employee_id\": \"29\",\r\n                \"name\": \"Maria Del Mundo\",\r\n                \"privilege\": \"0\"\r\n            },\r\n            {\r\n                \"user_id\": \"2\",\r\n                \"employee_id\": \"222\",\r\n                \"name\": \"Jay Del Mundo\",\r\n                \"privilege\": \"0\"\r\n            }\r\n        ]\r\n    }\r\n}";

var r= JsonConvert.DeserializeObject<RootObject>(input);

// choose the name you want here
var values = r.registers["<Name>"];

foreach (var p in values )
  Console.WriteLine(p.user_id + p.name + p.employee_id + p.privilege);


Q: BizTalk | Issue with Logical Existence functoid | source node doesn’t exist, still need output in the target I have a requirement to populate the output field in the destination schema though the source field does not exist in the input XML. If it does not exist, I have different logic to populate the target field. I tried using the 'Logical Existence' functoid but it is not giving me the desired output.


Q: Interthread communication between producer and consumer threads? I am trying to learn inter thread communication where I am using BlockingQueue.
I have written a producer which generate TaskId and insert it into BlockingQueue.
Now I have 2 consumers threads (name "1" and "0"). If taskId is odd, it is consumed by Thread "1" else "2".
@Override
    public void run() {
        while (true) {

                while (queue.peek() != null && !name.equals(String.valueOf(queue.peek().intValue() % 2 ))) {

                try {
                    System.out.println(name + ",consumed," + queue.take());
                } catch (InterruptedException e) {
                    e.printStackTrace();

                }
            }
        }
    }

How can i make that check also here?

A: One way I am thinking, there could be other better ways also:
@Override
    public void run() {
        String name = Thread.currentThread().getName();
        while (true) {

            while (queue.peek() == null) {
                //some sleep time
            }

            synchronized (lock) {
                while (queue.peek() != null && !name.equals(String.valueOf(queue.peek().intValue() % 2 ))) {
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                if(queue.peek() != null) {
                    try {
                        System.out.println(name + ",consumed," + queue.take());
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                lock.notify();
            }
        }
    }

Another Way: To have anotherLock that will be notified by producer thread whenever element is added to queue.
@Override
    public void run() {
        String name = Thread.currentThread().getName();
        while (true) {

            synchronized (anotherLock) {
                while (queue.peek() == null) {
                    anotherLock.wait();
                }
            }

            synchronized (lock) {
                while (queue.peek() != null && !name.equals(String.valueOf(queue.peek().intValue() % 2 ))) {
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                if(queue.peek() != null) {
                    try {
                        System.out.println(name + ",consumed," + queue.take());
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                lock.notify();
            }
        }
    }