问:
How to format /etc/passwd file using perl formatting
I'm trying to format the /etc/passwd file by using perl formatting

This is what I have come up with so far:

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

use warnings;

format MYFORMAT =
@<<<<<<<<<<<<<<<| @<<<<<<<<<<<<<<<| @<<<<<<<<<<<<<<<
$username,        $UID,             $name
.

$username = `cut -d: -f1 /etc/passwd`;
$UID = `cut -d: -f3 /etc/passwd`;
$name = `cut -d: -f5 /etc/passwd`;

$~ = "MYFORMAT";
write;
</code>```

I receive no warnings or errors. The formatting works, but the issue is, it only displays the first line of the etc/passwd file. I only get root, 0, and root as the Username, UID and name respectively.

I need all usernames, UIDs, and names printed for each column. I don't know what I'm doing wrong, because when I run the bash command to get only the usernames inside the terminal, it displays all of them. It won't do it inside of the script though.

答:
You're not looping over the /etc/passwd file, you're getting back the first set of fields into your variables, but then only using the first.  Consider this:

```<code>#!/usr/bin/perl
$username = `cut -d: -f1 /etc/passwd`;
print $username;
</code>```

Instead try perl myscript.pl < /etc/passwd with this script:

```<code>#!/usr/bin/perl
use warnings;
use strict;
my $username;
my $UID;
my $name;

format =
@<<<<<<<<<<<<<<<| @<<<<<<<<<<<<<<<| @<<<<<<<<<<<<<<<
$username,        $UID,             $name
.

while (<>) {
    ($username, undef, $UID, undef, $name, undef) = split(':');
    write();
}
</code>```

Output looks like:

```<code>~/tmp$ perl t2.pl < /etc/passwd
root            | 0               | root
daemon          | 1               | daemon
bin             | 2               | bin
sys             | 3               | sys
sync            | 4               | sync
games           | 5               | games
</code>```

If you don't give your format a name, STDOUT is the default.  And you can read in each line from /etc/passwd and process individually.

Body:
I'm trying to format the /etc/passwd file by using perl formatting

This is what I have come up with so far:

#!/usr/bin/perl

use warnings;

format MYFORMAT =
@<<<<<<<<<<<<<<<| @<<<<<<<<<<<<<<<| @<<<<<<<<<<<<<<<
$username,        $UID,             $name
.

$username = `cut -d: -f1 /etc/passwd`;
$UID = `cut -d: -f3 /etc/passwd`;
$name = `cut -d: -f5 /etc/passwd`;

$~ = "MYFORMAT";
write;

I receive no warnings or errors. The formatting works, but the issue is, it only displays the first line of the etc/passwd file. I only get root, 0, and root as the Username, UID and name respectively.

I need all usernames, UIDs, and names printed for each column. I don't know what I'm doing wrong, because when I run the bash command to get only the usernames inside the terminal, it displays all of them. It won't do it inside of the script though.

Body:
You're not looping over the /etc/passwd file, you're getting back the first set of fields into your variables, but then only using the first.  Consider this:

#!/usr/bin/perl
$username = `cut -d: -f1 /etc/passwd`;
print $username;

Instead try perl myscript.pl < /etc/passwd with this script:

#!/usr/bin/perl
use warnings;
use strict;
my $username;
my $UID;
my $name;

format =
@<<<<<<<<<<<<<<<| @<<<<<<<<<<<<<<<| @<<<<<<<<<<<<<<<
$username,        $UID,             $name
.

while (<>) {
    ($username, undef, $UID, undef, $name, undef) = split(':');
    write();
}

Output looks like:

~/tmp$ perl t2.pl < /etc/passwd
root            | 0               | root
daemon          | 1               | daemon
bin             | 2               | bin
sys             | 3               | sys
sync            | 4               | sync
games           | 5               | games

If you don't give your format a name, STDOUT is the default.  And you can read in each line from /etc/passwd and process individually.


来源: stackexchange

问:
Onclick remove function jQuery
I have a website that I'm building and it has 2 jQueries each one with a different function.

The first one is to have sticky headers:

```<code>var stickyHeaders = (function() {

  var $window = $(window),
    $stickies;

  var load = function(stickies) {

    if (typeof stickies === "object" && stickies instanceof jQuery && stickies.length > 0) {

      $stickies = stickies.each(function() {

        var $thisSticky = $(this).wrap('<div class="followWrap" />');

        $thisSticky
          .data('originalPosition', $thisSticky.offset().top)
          .data('originalHeight', $thisSticky.outerHeight())
          .parent()
          .height($thisSticky.outerHeight());
      });

      $window.off("scroll.stickies").on("scroll.stickies", function() {
        _whenScrolling();
      });
    }
  };

  var _whenScrolling = function() {

    $stickies.each(function(i) {

      var $thisSticky = $(this),
        $stickyPosition = $thisSticky.data('originalPosition');

      if ($stickyPosition <= $window.scrollTop()) {

        var $nextSticky = $stickies.eq(i + 1),
          $nextStickyPosition = $nextSticky.data('originalPosition') - $thisSticky.data('originalHeight');

        $thisSticky.addClass("fixed");

        if ($nextSticky.length > 0 && $thisSticky.offset().top >= $nextStickyPosition) {

          $thisSticky.addClass("absolute").css("top", $nextStickyPosition);
        }

      } else {

        var $prevSticky = $stickies.eq(i - 1);

        $thisSticky.removeClass("fixed");

        if ($prevSticky.length > 0 && $window.scrollTop() <= $thisSticky.data('originalPosition') - $thisSticky.data('originalHeight')) {

          $prevSticky.removeClass("absolute").removeAttr("style");
        }
      }
    });
  };

  return {
    load: load
  };
})();

$(function() {
  stickyHeaders.load($(".followMeBar"));
});
</code>```

And the other one is to increase, decrease the font size:

```<code>$('#smallerFont').click(function() {
  var htmlFontSize = $('#content p').css("font-size");
  htmlFontSize = parseInt(htmlFontSize, 10);
  if (htmlFontSize > 14) {
    $('#content p').css("font-size", "-=2");
  }
  return false;
});
$('#largerFont').click(function() {
  var htmlFontSize = $('#content p').css("font-size");
  htmlFontSize = parseInt(htmlFontSize, 10);
  if (htmlFontSize < 24) {
    $('#content p').css("font-size", "+=2");
  }
  return false;
});
</code>```

What I want and need is to kill, unload, whatever the first function when I click the link that activates the second one:

```<code><a href="#" id="largerFont" class="ml-2">+A</a>
</code>```

This is because sticky headers get all messed up when the font is increased or decreased without refreshing. The objects that stick move out of place.

答:
Got to a solution.

```<code>$('#smallerFont').click(function() {
  $("div.chapter_header").removeClass("followMeBar");
  var htmlFontSize = $('#content p').css("font-size");
  htmlFontSize = parseInt(htmlFontSize, 10);
  if (htmlFontSize > 14) {
    $('#content p').css("font-size", "-=2");

  }
  return false;
});
</code>```

Removed the class the first function needed to work

ContentLicense: CC BY-SA 3.0

Title: Onclick remove function jQuery

Body:
I have a website that I'm building and it has 2 jQueries each one with a different function.

The first one is to have sticky headers:

var stickyHeaders = (function() {

  var $window = $(window),
    $stickies;

  var load = function(stickies) {

    if (typeof stickies === "object" && stickies instanceof jQuery && stickies.length > 0) {

      $stickies = stickies.each(function() {

        var $thisSticky = $(this).wrap('
');

        $thisSticky
          .data('originalPosition', $thisSticky.offset().top)
          .data('originalHeight', $thisSticky.outerHeight())
          .parent()
          .height($thisSticky.outerHeight());
      });

      $window.off("scroll.stickies").on("scroll.stickies", function() {
        _whenScrolling();
      });
    }
  };

  var _whenScrolling = function() {

    $stickies.each(function(i) {

      var $thisSticky = $(this),
        $stickyPosition = $thisSticky.data('originalPosition');

      if ($stickyPosition <= $window.scrollTop()) {

        var $nextSticky = $stickies.eq(i + 1),
          $nextStickyPosition = $nextSticky.data('originalPosition') - $thisSticky.data('originalHeight');

        $thisSticky.addClass("fixed");

        if ($nextSticky.length > 0 && $thisSticky.offset().top >= $nextStickyPosition) {

          $thisSticky.addClass("absolute").css("top", $nextStickyPosition);
        }

      } else {

        var $prevSticky = $stickies.eq(i - 1);

        $thisSticky.removeClass("fixed");

        if ($prevSticky.length > 0 && $window.scrollTop() <= $thisSticky.data('originalPosition') - $thisSticky.data('originalHeight')) {

          $prevSticky.removeClass("absolute").removeAttr("style");
        }
      }
    });
  };

  return {
    load: load
  };
})();

$(function() {
  stickyHeaders.load($(".followMeBar"));
});

And the other one is to increase, decrease the font size:

$('#smallerFont').click(function() {
  var htmlFontSize = $('#content p').css("font-size");
  htmlFontSize = parseInt(htmlFontSize, 10);
  if (htmlFontSize > 14) {
    $('#content p').css("font-size", "-=2");
  }
  return false;
});
$('#largerFont').click(function() {
  var htmlFontSize = $('#content p').css("font-size");
  htmlFontSize = parseInt(htmlFontSize, 10);
  if (htmlFontSize < 24) {
    $('#content p').css("font-size", "+=2");
  }
  return false;
});

What I want and need is to kill, unload, whatever the first function when I click the link that activates the second one:

+A

This is because sticky headers get all messed up when the font is increased or decreased without refreshing. The objects that stick move out of place.

Body:
Got to a solution.

$('#smallerFont').click(function() {
  $("div.chapter_header").removeClass("followMeBar");
  var htmlFontSize = $('#content p').css("font-size");
  htmlFontSize = parseInt(htmlFontSize, 10);
  if (htmlFontSize > 14) {
    $('#content p').css("font-size", "-=2");

  }
  return false;
});

Removed the class the first function needed to work

ContentLicense: CC BY-SA 4.0


问:
Python 3.6 connection to MS SQL Server for large dataframe
I am a new Python coder and also a new data scientist so please forgive any foolish sounding things here. I'll keep the details out unless anyone's curious but basically I need to connect to Microsoft SQL Server and upload a Pandas DF that is relatively large (~500k rows) and I need to do this almost every day as the project currently stands.

It doesn't have to be a Pandas DF - I've read about using odo for csv files but I haven't been able to get anything to work. The issue I'm having is that I can't bulk insert the DF because the file isn't on the same machine as the SQL Server instance. I'm consistently getting errors like the following:

pyodbc.ProgrammingError: ('42000', "[42000] [Microsoft][ODBC SQL
  Server Driver][SQL Server]Incorrect syntax near the keyword 'IF'.
  (156) (SQLExecDirectW)")

As I've attempted different SQL statements you can replace IF with whatever has been the first COL_NAME in the CREATE statement. I'm using SQLAlchemy to create the engine and connect to the database. This may go without saying but the pd.to_sql() method is just way too slow for how much data I'm moving so that's why I need something faster.

I'm using Python 3.6 by the way. I've put down here most of the things that I've tried that haven't been successful.

```<code>import pandas as pd
from sqlalchemy import create_engine
import numpy as np
df = pd.DataFrame(np.random.randint(0,100,size=(100, 1)), columns=list('test_col'))
address = 'mssql+pyodbc://uid:pw@server/path/database?driver=SQL Server'
engine = create_engine(address)
connection = engine.raw_connection()
cursor = connection.cursor()
# Attempt 1 <- This failed to even create a table at the cursor_execute statement so my issues could be way in the beginning here but I know that I have a connection to the SQL Server because I can use pd.to_sql() to create tables successfully (just incredibly slowly for my tables of interest)
create_statement = """
DROP TABLE test_table
CREATE TABLE test_table (test_col)
"""
cursor.execute(create_statement)
test_insert = '''
INSERT INTO test_table
(test_col)
values ('abs');
'''
cursor.execute(test_insert)

Attempt 2 <- From iabdb WordPress blog I came across
def chunker(seq, size):
    return (seq[pos:pos + size] for pos in range(0, len(seq), size))
records = [str(tuple(x)) for x in take_rates.values]

insert_ = """
INSERT INTO test_table
("A")
VALUES
"""

for batch in chunker(records, 2): # This would be set to 1000 in practice I hope
    print(batch)
    rows = str(batch).strip('[]')
    print(rows)
    insert_rows = insert_ + rows
    print(insert_rows)
    cursor.execute(insert_rows)
    #conn.commit() # don't know when I would need to commit

conn.close()

# Attempt 3 # From a related Stack Exchange Post
 create the table but first drop if it already exists
command = """DROP TABLE IF EXISTS test_table
CREATE TABLE test_table # these columns are from my real dataset
"Serial Number" serial primary key,
"Dealer Code" text,
"FSHIP_DT" timestamp without time zone,
;"""
cursor.execute(command)
connection.commit()

# stream the data using 'to_csv' and StringIO(); then use sql's 'copy_from' function
output = io.StringIO()
# ignore the index
take_rates.to_csv(output, sep='~', header=False, index=False)
# jump to start of stream
output.seek(0)
contents = output.getvalue()
cur = connection.cursor()
# null values become ''
cur.copy_from(output, 'Config_Take_Rates_TEST', null="")
connection.commit()
cur.close()
</code>```

It seems to me that MS SQL Server is just not a nice Database to play around with...
I want to apologize for the rough formatting - I've been at this script for weeks now but just finally decided to try to organize something for StackOverflow. Thank you very much for any help anyone can offer!

答:
'DROP TABLE IF EXISTS test_table' just looks like invalid tsql syntax.
you can do something like this:</p>

```<code>if (object_id('test_table') is not null)
DROP TABLE test_table
</code>```

Body:
I am a new Python coder and also a new data scientist so please forgive any foolish sounding things here. I'll keep the details out unless anyone's curious but basically I need to connect to Microsoft SQL Server and upload a Pandas DF that is relatively large (~500k rows) and I need to do this almost every day as the project currently stands.

It doesn't have to be a Pandas DF - I've read about using odo for csv files but I haven't been able to get anything to work. The issue I'm having is that I can't bulk insert the DF because the file isn't on the same machine as the SQL Server instance. I'm consistently getting errors like the following:

pyodbc.ProgrammingError: ('42000', "[42000] [Microsoft][ODBC SQL
  Server Driver][SQL Server]Incorrect syntax near the keyword 'IF'.
  (156) (SQLExecDirectW)")

As I've attempted different SQL statements you can replace IF with whatever has been the first COL_NAME in the CREATE statement. I'm using SQLAlchemy to create the engine and connect to the database. This may go without saying but the pd.to_sql() method is just way too slow for how much data I'm moving so that's why I need something faster.

I'm using Python 3.6 by the way. I've put down here most of the things that I've tried that haven't been successful.

import pandas as pd
from sqlalchemy import create_engine
import numpy as np
df = pd.DataFrame(np.random.randint(0,100,size=(100, 1)), columns=list('test_col'))
address = 'mssql+pyodbc://uid:pw@server/path/database?driver=SQL Server'
engine = create_engine(address)
connection = engine.raw_connection()
cursor = connection.cursor()
# Attempt 1 <- This failed to even create a table at the cursor_execute statement so my issues could be way in the beginning here but I know that I have a connection to the SQL Server because I can use pd.to_sql() to create tables successfully (just incredibly slowly for my tables of interest)
create_statement = """
DROP TABLE test_table
CREATE TABLE test_table (test_col)
"""
cursor.execute(create_statement)
test_insert = '''
INSERT INTO test_table
(test_col)
values ('abs');
'''
cursor.execute(test_insert)

Attempt 2 <- From iabdb WordPress blog I came across
def chunker(seq, size):
    return (seq[pos:pos + size] for pos in range(0, len(seq), size))
records = [str(tuple(x)) for x in take_rates.values]

insert_ = """
INSERT INTO test_table
("A")
VALUES
"""

for batch in chunker(records, 2): # This would be set to 1000 in practice I hope
    print(batch)
    rows = str(batch).strip('[]')
    print(rows)
    insert_rows = insert_ + rows
    print(insert_rows)
    cursor.execute(insert_rows)
    #conn.commit() # don't know when I would need to commit

conn.close()

# Attempt 3 # From a related Stack Exchange Post
 create the table but first drop if it already exists
command = """DROP TABLE IF EXISTS test_table
CREATE TABLE test_table # these columns are from my real dataset
"Serial Number" serial primary key,
"Dealer Code" text,
"FSHIP_DT" timestamp without time zone,
;"""
cursor.execute(command)
connection.commit()

# stream the data using 'to_csv' and StringIO(); then use sql's 'copy_from' function
output = io.StringIO()
# ignore the index
take_rates.to_csv(output, sep='~', header=False, index=False)
# jump to start of stream
output.seek(0)
contents = output.getvalue()
cur = connection.cursor()
# null values become ''
cur.copy_from(output, 'Config_Take_Rates_TEST', null="")
connection.commit()
cur.close()

It seems to me that MS SQL Server is just not a nice Database to play around with...
I want to apologize for the rough formatting - I've been at this script for weeks now but just finally decided to try to organize something for StackOverflow. Thank you very much for any help anyone can offer!

Body:
'DROP TABLE IF EXISTS test_table' just looks like invalid tsql syntax.
you can do something like this:

if (object_id('test_table') is not null)
DROP TABLE test_table


问:
Updating a hashmap within a hashmap with a class
Sorry about the title really struggling to name this.  Lets see how the question goes.....

In java I have a class called book which contains the following code.  Where name is the book name, the hashMap string is the critics name and the hashMap Integer is the critic score.

```<code>public class book {

    private String name;
    private HashMap<String, Integer> results = new HashMap<String, Integer>();
}
</code>```

I then have another class called bookRecord which contains the following code.

```<code>private HashMap<Integer, Book> bookRecord = new HashMap<Integer, Book>();
</code>```

I have written a UI that allows me to enter a new book and save that book into the bookRecord.

The Integer in bookRecord is an ID for the book.
I have written a query to search by the ID and return the name of the book.  Now I want to be able to update the book if a new critic and score is available.

I have been playing with a for each loop to find the right key in the book record and then if the key is found another for each loop but I have confused myself.

Any advice?

答:
You have two options:

First option you make the results HashMap public and can achieve something like this:

```<code>Book uBook = records.get(BOOK_ID_YOU_WANT_TO_UPDATE);
if (uBook != null) {
  uBook.results.put("New critic name", Critic_SCORE);
}
</code>```

Seconds option is to leave the results private but add a new method addCriticScore(String criticName, Integer score):

```<code>// In your class that updates the book
Book uBook = records.get(BOOK_ID_YOU_WANT_TO_UPDATE);

// In the Book class
public void addCriticScore(String criticName, Integer score) {
  this.results.put(criticName, score);
}
</code>```

P.S: Don't forget to rename your class book to Book. In java the class name is with capitals

Body:
Sorry about the title really struggling to name this.  Lets see how the question goes.....

In java I have a class called book which contains the following code.  Where name is the book name, the hashMap string is the critics name and the hashMap Integer is the critic score.

public class book {

    private String name;
    private HashMap<String, Integer> results = new HashMap<String, Integer>();
}

I then have another class called bookRecord which contains the following code.

private HashMap<Integer, Book> bookRecord = new HashMap<Integer, Book>();

I have written a UI that allows me to enter a new book and save that book into the bookRecord.

The Integer in bookRecord is an ID for the book.
I have written a query to search by the ID and return the name of the book.  Now I want to be able to update the book if a new critic and score is available.

I have been playing with a for each loop to find the right key in the book record and then if the key is found another for each loop but I have confused myself.

Any advice?

Body:
You have two options:

First option you make the results HashMap public and can achieve something like this:

Book uBook = records.get(BOOK_ID_YOU_WANT_TO_UPDATE);
if (uBook != null) {
  uBook.results.put("New critic name", Critic_SCORE);
}

Seconds option is to leave the results private but add a new method addCriticScore(String criticName, Integer score):

// In your class that updates the book
Book uBook = records.get(BOOK_ID_YOU_WANT_TO_UPDATE);

// In the Book class
public void addCriticScore(String criticName, Integer score) {
  this.results.put(criticName, score);
}

P.S: Don't forget to rename your class book to Book. In java the class name is with capitals


问:
How can I build bootimage without going through all Makefiles
I am currently working on the Linux kernel for an Android phone. My workflow is:

Make changes to kernel code

Build with make bootimage

Flash with fastboot flash boot

This works fine. However building takes unnecessary long because make bootimage first goes through the entire tree and includes all Android.mk files. This takes longer than actually compiling the kernel and creating a boot image. Including these files should not be necessary since there are no changes to them. To decrease turnaround time in my workflow, I would like to speed up the build step.

When building other other projects, there are ways to to not build dependencies and thus skip reading all Android.mk files (for instance mm).

There is a make target bootimage-nodeps which seems to do the right thing: It makes a new boot image without going through all Android.mk files. Unfortunately dependencies also include the kernel itself (which therefore does not get built although there are changes).

My question is: Is there a way to build the kernel and create a boot image withouth having to read all Android.mk files.

答:
In case you 're still looking into it, try using the showcommands goal at make, for example :

```<code>make bootimage showcommands
</code>```

The showcommands goals will show all commands needed to build the kernel and the bootimage. Some of the commands, including the one to create the bootimage have $(hide) in front and are not shown.

Once you know the commands and the arguments, next time you need to make the bootimage you can run the commands manually (without using make bootimage and without including all the makefiles).
I have exactly the same problem and this is the only working solution I've found.

Body:
In case you 're still looking into it, try using the showcommands goal at make, for example :

make bootimage showcommands

The showcommands goals will show all commands needed to build the kernel and the bootimage. Some of the commands, including the one to create the bootimage have $(hide) in front and are not shown.

Once you know the commands and the arguments, next time you need to make the bootimage you can run the commands manually (without using make bootimage and without including all the makefiles).
I have exactly the same problem and this is the only working solution I've found.


问:
Skip Condtion if value is null
This should be really simple; however, I cannot wrap my head around it using the CASE statement.

```<code>DECLARE @Test INT = NULL
SELECT *
FROM StoreImages
WHERE Quality = 1 AND Ready = @Test
</code>```

I would like to accomplish something similar to this:

```<code>DECLARE @Test INT = NULL
SELECT *
FROM StoreImages
CASE @Test IS NOT NULL
  WHERE Quality = 1 AND Ready = @Test
ELSE
  WHERE Quality = 1
</code>```

UPDATE

I created a schema sample for quickly testing provided answers

```<code>--create a temporary table
CREATE TABLE #ImagesTable(
Quality BIT,
Ready BIT)

-- insert into the temporary table
INSERT INTO #ImagesTable(Quality,Ready)
VALUES (1, 1);
INSERT INTO #ImagesTable(Quality,Ready)
VALUES (1, 1);
INSERT INTO #ImagesTable(Quality,Ready)
VALUES (1, 1);
INSERT INTO #ImagesTable(Quality,Ready)
VALUES (1, 1);
INSERT INTO #ImagesTable(Quality,Ready)
VALUES (1, 1);
INSERT INTO #ImagesTable(Quality,Ready)
VALUES (1, 0);
INSERT INTO #ImagesTable(Quality,Ready)
VALUES (1, 0);
INSERT INTO #ImagesTable(Quality,Ready)
VALUES (1, 0);
INSERT INTO #ImagesTable(Quality,Ready)
VALUES (1, 0);
INSERT INTO #ImagesTable(Quality,Ready)
VALUES (1, 0);
</code>```

Declaring @Test as null should return all

Declaring @Test as 1 or 0 should return half records

答:
I would do it like:

```<code>DECLARE @Test INT = NULL
SELECT *
FROM #ImagesTable
WHERE (Quality = 1 AND Ready = @Test) OR Quality = 1;
</code>```

You can use CASE if there is a value can be in @Test instead of NULL like:

```<code>DECLARE @Test INT = NULL
SELECT *
FROM #ImagesTable
WHERE Quality = 1 AND Ready = (CASE WHEN @Test IS NULL THEN 1 ELSE @Test END);
</code>```

Update:

As I can see there is only two values 0 or 1 can be in your Ready column:

```<code>SELECT *
FROM #ImagesTable
WHERE (Quality = 1 AND Ready IN ( ISNULL(@Test, 0), ISNULL(@Test, 1) ) );
</code>```

Here is a Demo where you can play with.

Title: Skip Condtion if value is null

Body:
This should be really simple; however, I cannot wrap my head around it using the CASE statement.

DECLARE @Test INT = NULL
SELECT *
FROM StoreImages
WHERE Quality = 1 AND Ready = @Test

I would like to accomplish something similar to this:

DECLARE @Test INT = NULL
SELECT *
FROM StoreImages
CASE @Test IS NOT NULL
  WHERE Quality = 1 AND Ready = @Test
ELSE
  WHERE Quality = 1

UPDATE

I created a schema sample for quickly testing provided answers

--create a temporary table
CREATE TABLE #ImagesTable(
Quality BIT,
Ready BIT)

-- insert into the temporary table
INSERT INTO #ImagesTable(Quality,Ready)
VALUES (1, 1);
INSERT INTO #ImagesTable(Quality,Ready)
VALUES (1, 1);
INSERT INTO #ImagesTable(Quality,Ready)
VALUES (1, 1);
INSERT INTO #ImagesTable(Quality,Ready)
VALUES (1, 1);
INSERT INTO #ImagesTable(Quality,Ready)
VALUES (1, 1);
INSERT INTO #ImagesTable(Quality,Ready)
VALUES (1, 0);
INSERT INTO #ImagesTable(Quality,Ready)
VALUES (1, 0);
INSERT INTO #ImagesTable(Quality,Ready)
VALUES (1, 0);
INSERT INTO #ImagesTable(Quality,Ready)
VALUES (1, 0);
INSERT INTO #ImagesTable(Quality,Ready)
VALUES (1, 0);

Declaring @Test as null should return all

Declaring @Test as 1 or 0 should return half records

Body:
I would do it like:

DECLARE @Test INT = NULL
SELECT *
FROM #ImagesTable
WHERE (Quality = 1 AND Ready = @Test) OR Quality = 1;

You can use CASE if there is a value can be in @Test instead of NULL like:

DECLARE @Test INT = NULL
SELECT *
FROM #ImagesTable
WHERE Quality = 1 AND Ready = (CASE WHEN @Test IS NULL THEN 1 ELSE @Test END);

Update:

As I can see there is only two values 0 or 1 can be in your Ready column:

SELECT *
FROM #ImagesTable
WHERE (Quality = 1 AND Ready IN ( ISNULL(@Test, 0), ISNULL(@Test, 1) ) );

Here is a Demo where you can play with.


问:
which files are need to create .ipa for my application which is done in xcode
I am creating a simple application in xcode

Now i need to create ipa for that file.

By google i found some info regarding this.

create a folder named Payload and copy the app file,Zip the fine and rename zip to .ipa.

But i have a doubt in the this path users/username/library/application support/iphone simulator/4.1/Applications

i found a folder named with random alphabets and numbers.

In that i found documents,library,tmp folders along with my application.app.

is i need to copy all the 3 folders into payload or just my application.app is enough.

And i did n't get my icon in over the .ipa.

How can i get it.

can any one pls help me.

Thank u in advance.

答: Apart from using Build and Archive, you can also try dragging and dropping your .app file onto iTunes. Then when you do 'reveal in finder' for the app, you'd see the IPA.</p>

ContentLicense: CC BY-SA 2.5


问:
vue router.replace acts differently based on how input object is assembled
I encountered some weird behaviour with Vue Router where the router acts differently based on how it's input object is assembled. The code sample below is an except from a component's 'methods' property. See the comments in my code sample for more info.

```<code>switchLocale(newLocale) {
                // this solution works
                const route = {
                    name: this.$route.name,
                    query: {locale: newLocale},
                    params: this.$route.params,
                };
                console.log(JSON.stringify(route));
                // {"name":"v.support.help","query":{"locale":"en"},"params":{}}
                this.$router.replace(route);

                // this solution does not change the route. I would expect it to work exactly like the solution above
                /*
                const {name, query, params} = this.$route;
                let route = {name, query, params};
                route.query.locale = newLocale;
                console.log(JSON.stringify(route));
                // {"name":"v.support.help","query":{"locale":"en"},"params":{}}
                this.$router.replace(route);
                */
            }
</code>```

What could cause this to happen?

答:
In your second code, you're mutating the this.$route.query object directly and passing it to this.$router.replace. I'm guessing vue-router will not be able to detect if the query has changed because you mutated vue-router's internal state.

Do not mutate the this.$route object (or any of Vue's internal state for that matter) otherwise things may not work properly.

If you want to preserve the existing query parameters while introducing or changing another one, then you can do this:

```<code>this.$router.replace({
  query: Object.assign({}, this.$route.query, { locale: newLocale }),
  // No need to specify route name and params, they will be preserved
});
</code>```

Body:
I encountered some weird behaviour with Vue Router where the router acts differently based on how it's input object is assembled. The code sample below is an except from a component's 'methods' property. See the comments in my code sample for more info.

switchLocale(newLocale) {
                // this solution works
                const route = {
                    name: this.$route.name,
                    query: {locale: newLocale},
                    params: this.$route.params,
                };
                console.log(JSON.stringify(route));
                // {"name":"v.support.help","query":{"locale":"en"},"params":{}}
                this.$router.replace(route);

                // this solution does not change the route. I would expect it to work exactly like the solution above
                /*
                const {name, query, params} = this.$route;
                let route = {name, query, params};
                route.query.locale = newLocale;
                console.log(JSON.stringify(route));
                // {"name":"v.support.help","query":{"locale":"en"},"params":{}}
                this.$router.replace(route);
                */
            }

What could cause this to happen?

Body:
In your second code, you're mutating the this.$route.query object directly and passing it to this.$router.replace. I'm guessing vue-router will not be able to detect if the query has changed because you mutated vue-router's internal state.

Do not mutate the this.$route object (or any of Vue's internal state for that matter) otherwise things may not work properly.

If you want to preserve the existing query parameters while introducing or changing another one, then you can do this:

this.$router.replace({
  query: Object.assign({}, this.$route.query, { locale: newLocale }),
  // No need to specify route name and params, they will be preserved
});


问:
Using Regex or StringTokenizer inline with Stream
To parse a log file, I have the following:

```<code> try (Stream<String> stream = Files.lines(Paths.get(logFileName))) {

   List<LogMessage> sm = stream
          .map(line -> new LogMessage(...))  <-- fill in a data extracted from the line in the log file
          .collect(Collectors.toList());
        ...
    } catch (IOException e) {
        ...
    }
</code>```

There are two possible solutions to extract data from a log message. One is to use StringTokenizer. A sample of using it with Stream is on http://www.baeldung.com/java-stringtokenizer. A problem is that I only need some selected data in a log message, but not all data. For example, in a log message

```<code>09-Nov-2017 11:54:27.529 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Server version:        Apache Tomcat/8.5.23
</code>```

I only need the time stamp (09-Nov-2017 11:54:27.529), the log level (INFO), and a log message (Apache Tomcat/8.5.23).

The another one is to use Regex. But, how to use Regex in the inline form?

答:
Try this:

```<code>List<LogMessage> sm = stream
      .map(s -> s.split(" ", 6))
      .map(a -> new LogMessage(a[0], a[1], a[2], a[5]))
      .collect(toList());
</code>```

Note the use of the extra numeric parameter to split(), which limits the number of elements in the result to 6, which leaves the message intact.

This assumes a constructor that looks like:

```<code>public LogMessage(String date, String time, String level, String message) { ...
</code>```

You can fill in the rest.

Body:
To parse a log file, I have the following:

 try (Stream<String> stream = Files.lines(Paths.get(logFileName))) {

   List<LogMessage> sm = stream
          .map(line -> new LogMessage(...))  <-- fill in a data extracted from the line in the log file
          .collect(Collectors.toList());
        ...
    } catch (IOException e) {
        ...
    }

There are two possible solutions to extract data from a log message. One is to use StringTokenizer. A sample of using it with Stream is on http://www.baeldung.com/java-stringtokenizer. A problem is that I only need some selected data in a log message, but not all data. For example, in a log message

09-Nov-2017 11:54:27.529 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Server version:        Apache Tomcat/8.5.23

I only need the time stamp (09-Nov-2017 11:54:27.529), the log level (INFO), and a log message (Apache Tomcat/8.5.23).

The another one is to use Regex. But, how to use Regex in the inline form?

Body:
Try this:

List<LogMessage> sm = stream
      .map(s -> s.split(" ", 6))
      .map(a -> new LogMessage(a[0], a[1], a[2], a[5]))
      .collect(toList());

Note the use of the extra numeric parameter to split(), which limits the number of elements in the result to 6, which leaves the message intact.

This assumes a constructor that looks like:

public LogMessage(String date, String time, String level, String message) { ...

You can fill in the rest.


问:
How to get a substring from a string in mysql
Sorry if this has already been asked but I wasn't able to find an answer that can help with my issue.

I need to extract the name of a country from a string where the location of the string could be anywhere.

Example data strings

```<code>1) Location - Living in: United States, Age: 18+, (and so on)
2) Location: United Kingdom, Excluded Connections: France,
3) Age: 65+, Language: english, Living in: United States,
</code>```

So for those examples, I would just need

```<code>1) United States
2) United Kingdom
3) United States
</code>```

Its all comma separated but I can't seem to get it to find the value I need.

My current set up

```<code>Select bio,
SUBSTRING_INDEX(SUBSTRING_INDEX(a.`targeting`,'Location: ',-1),',',1) AS country
from table1
</code>```

Also sorry for the formatting! Having trouble formatting this correctly.

答:
Following query should work (I've tested on given sample data and it's working properly):

Also, I've assumed a.targeting is the column that contains these strings as per your query.

```<code>SELECT
 (case when LOCATE("Location - Living in", a.targeting) > 0
            then SUBSTRING_INDEX(SUBSTRING_INDEX(a.targeting,"Location - Living in: ",-1),",",1)
       when LOCATE("Location:", a.targeting) > 0
            then SUBSTRING_INDEX(SUBSTRING_INDEX(a.targeting,"Location:",-1),",",1)
       when LOCATE("Living in:", a.targeting) > 0
            then SUBSTRING_INDEX(SUBSTRING_INDEX(a.targeting,"Living in:",-1),",",1)
  end) AS country;
</code>```

Hope it helps!

Body:
Sorry if this has already been asked but I wasn't able to find an answer that can help with my issue.

I need to extract the name of a country from a string where the location of the string could be anywhere.

Example data strings

1) Location - Living in: United States, Age: 18+, (and so on)
2) Location: United Kingdom, Excluded Connections: France,
3) Age: 65+, Language: english, Living in: United States,

So for those examples, I would just need

1) United States
2) United Kingdom
3) United States

Its all comma separated but I can't seem to get it to find the value I need.

My current set up

Select bio,
SUBSTRING_INDEX(SUBSTRING_INDEX(a.`targeting`,'Location: ',-1),',',1) AS country
from table1

Also sorry for the formatting! Having trouble formatting this correctly.

Body:
Following query should work (I've tested on given sample data and it's working properly):

Also, I've assumed a.targeting is the column that contains these strings as per your query.

SELECT
 (case when LOCATE("Location - Living in", a.targeting) > 0
            then SUBSTRING_INDEX(SUBSTRING_INDEX(a.targeting,"Location - Living in: ",-1),",",1)
       when LOCATE("Location:", a.targeting) > 0
            then SUBSTRING_INDEX(SUBSTRING_INDEX(a.targeting,"Location:",-1),",",1)
       when LOCATE("Living in:", a.targeting) > 0
            then SUBSTRING_INDEX(SUBSTRING_INDEX(a.targeting,"Living in:",-1),",",1)
  end) AS country;

Hope it helps!


问:
Java WebServices with Spring and OAS/OC4J
I'm having problems deploying a simple WebServices app (like "Hello World" simple) to OC4J. The same code works fine under Jetty, but breaks in OC4J, and I'm wondering if anyone else has faced the same issue. I'm using Enterprise Manager to deploy the app, but the deployment fails with this message:

```<code>    [Jan 23, 2009 8:46:20 AM] Binding TestWs web-module for application TestWs to site default-web-site under context root /TestWs
    [Jan 23, 2009 8:46:22 AM] Operation failed with error: Configuration problem: Unable to locate Spring NamespaceHandler for XML schema namespace [http://cxf.apache.org/jaxws]
Offending resource: ServletContext resource [/WEB-INF/beans.xml]
</code>```

Looking at the beans.xml, the offending code seems to be the XML namespace declarations:

```<code><beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:jaxws="http://cxf.apache.org/jaxws"
    xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd">

    <import resource="classpath:META-INF/cxf/cxf.xml" />
    <import resource="classpath:META-INF/cxf/cxf-extension-soap.xml" />
    <import resource="classpath:META-INF/cxf/cxf-servlet.xml" />

    <jaxws:endpoint
        id="helloService"
        implementor="com.test.endpoint.HelloImpl"
        address="/HelloWorld" />
</beans>
</code>```

The stack trace is not terribly illuminating:

```<code>    09/01/23 08:57:28 oracle.oc4j.admin.internal.DeployerException: Configuration problem: Unable to locate Spring NamespaceHandler for XML schema namespace [http://cxf.apache.org/jaxws]
    Offending resource: ServletContext resource [/WEB-INF/beans.xml]

    09/01/23 08:57:28   at org.springframework.beans.factory.parsing.FailFastProblemReporter.error(FailFastProblemReporter.java:68)
    09/01/23 08:57:28   at org.springframework.beans.factory.parsing.ReaderContext.error(ReaderContext.java:85)
    09/01/23 08:57:28   at org.springframework.beans.factory.parsing.ReaderContext.error(ReaderContext.java:80)
    09/01/23 08:57:28   at org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.error(BeanDefinitionParserDelegate.java:261)
    09/01/23 08:57:28   at org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.parseCustomElement(BeanDefinitionParserDelegate.java:1120)
...
</code>```

Has anyone else run into similar problems? And if so, what's the best way to go about fixing it? My XML skills are middling, and I'm a complete noob with WebServices. But this may be an OC4J issue.

Thanks in advance for your help!

EDIT: This is not, as far as I can tell, a classpath issue, unless OC4J is odd about what jars it want to see where (as I know Tomcat can be). My WEB-INF/lib folder has the CXF jar, the Spring jars (beans, context, core, and web), xml-resolver-1.2.jar, and XmlSchema-1.4.2.jar. If I need to list everything in the WEB-INF/lib folder, I will. But again, the program works in Jetty.

Another Edit: Based on what I'm reading here, this appears to be an issue between Spring and the CXF jar -- there's a NamespaceHandler class in the CXF jar (in org.apache.cxf.frontend.spring to be precise), but there seems to be a configuration issue preventing Spring from seeing it.

Last Edit: Thank you everyone for your help. I never ended up getting CXF working in OC4J, because my client is on version 10.1.3.3.0. It's not J2EE 5 compliant, and I'm pretty sure they're not going to go for unpacking their oc4j.jar in order to change the boot.xml. But without the document Daniel pointed me to, I never would have known that.

So I switched to XFire version 1.2.6, and got my test app working after a few hiccups. Along the way I learned some interesting things about OC4J:

When deploying in Enterprise Manager, make sure you choose to load the local classpath first.

OC4J uses non-standard XML files, so make sure your app is not using any of OC4J's native XML files (in the Deployment Settings, uncheck all the currently selected imports -- that way, you can ensure that the app is using only files you provide in WEB-INF/lib)

If you can, use another app server. :P

Thank you all again!

答:
Looks like a configuration issue with Spring:

```<code>Configuration problem: Unable to locate Spring NamespaceHandler for XML schema namespace [http://cxf.apache.org/jaxws]
Offending resource: ServletContext resource [/WEB-INF/beans.xml]
</code>```

Do you have anything in your web.xml to read that when the app starts up?  Do you see a NamespaceHandler declared for that namespace anywhere in your code?

OwnerDisplayName: rtperson

Body:
I'm having problems deploying a simple WebServices app (like "Hello World" simple) to OC4J. The same code works fine under Jetty, but breaks in OC4J, and I'm wondering if anyone else has faced the same issue. I'm using Enterprise Manager to deploy the app, but the deployment fails with this message:

    [Jan 23, 2009 8:46:20 AM] Binding TestWs web-module for application TestWs to site default-web-site under context root /TestWs
    [Jan 23, 2009 8:46:22 AM] Operation failed with error: Configuration problem: Unable to locate Spring NamespaceHandler for XML schema namespace [http://cxf.apache.org/jaxws]
Offending resource: ServletContext resource [/WEB-INF/beans.xml]

Looking at the beans.xml, the offending code seems to be the XML namespace declarations:

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:jaxws="http://cxf.apache.org/jaxws"
    xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd">

    <import resource="classpath:META-INF/cxf/cxf.xml" />
    <import resource="classpath:META-INF/cxf/cxf-extension-soap.xml" />
    <import resource="classpath:META-INF/cxf/cxf-servlet.xml" />

    <jaxws:endpoint
        id="helloService"
        implementor="com.test.endpoint.HelloImpl"
        address="/HelloWorld" />
</beans>

The stack trace is not terribly illuminating:

    09/01/23 08:57:28 oracle.oc4j.admin.internal.DeployerException: Configuration problem: Unable to locate Spring NamespaceHandler for XML schema namespace [http://cxf.apache.org/jaxws]
    Offending resource: ServletContext resource [/WEB-INF/beans.xml]

    09/01/23 08:57:28   at org.springframework.beans.factory.parsing.FailFastProblemReporter.error(FailFastProblemReporter.java:68)
    09/01/23 08:57:28   at org.springframework.beans.factory.parsing.ReaderContext.error(ReaderContext.java:85)
    09/01/23 08:57:28   at org.springframework.beans.factory.parsing.ReaderContext.error(ReaderContext.java:80)
    09/01/23 08:57:28   at org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.error(BeanDefinitionParserDelegate.java:261)
    09/01/23 08:57:28   at org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.parseCustomElement(BeanDefinitionParserDelegate.java:1120)
...

Has anyone else run into similar problems? And if so, what's the best way to go about fixing it? My XML skills are middling, and I'm a complete noob with WebServices. But this may be an OC4J issue.

Thanks in advance for your help!

EDIT: This is not, as far as I can tell, a classpath issue, unless OC4J is odd about what jars it want to see where (as I know Tomcat can be). My WEB-INF/lib folder has the CXF jar, the Spring jars (beans, context, core, and web), xml-resolver-1.2.jar, and XmlSchema-1.4.2.jar. If I need to list everything in the WEB-INF/lib folder, I will. But again, the program works in Jetty.

Another Edit: Based on what I'm reading here, this appears to be an issue between Spring and the CXF jar -- there's a NamespaceHandler class in the CXF jar (in org.apache.cxf.frontend.spring to be precise), but there seems to be a configuration issue preventing Spring from seeing it.

Last Edit: Thank you everyone for your help. I never ended up getting CXF working in OC4J, because my client is on version 10.1.3.3.0. It's not J2EE 5 compliant, and I'm pretty sure they're not going to go for unpacking their oc4j.jar in order to change the boot.xml. But without the document Daniel pointed me to, I never would have known that.

So I switched to XFire version 1.2.6, and got my test app working after a few hiccups. Along the way I learned some interesting things about OC4J:

When deploying in Enterprise Manager, make sure you choose to load the local classpath first.

OC4J uses non-standard XML files, so make sure your app is not using any of OC4J's native XML files (in the Deployment Settings, uncheck all the currently selected imports -- that way, you can ensure that the app is using only files you provide in WEB-INF/lib)

If you can, use another app server. :P

Thank you all again!

LastEditorDisplayName: rtperson

Body:
Looks like a configuration issue with Spring:

Configuration problem: Unable to locate Spring NamespaceHandler for XML schema namespace [http://cxf.apache.org/jaxws]
Offending resource: ServletContext resource [/WEB-INF/beans.xml]

Do you have anything in your web.xml to read that when the app starts up?  Do you see a NamespaceHandler declared for that namespace anywhere in your code?


问:
Python Error on Google Cloud Install. How do I properly set the environment variable?
I am trying to install the Google Cloud SDK on my Windows machine. I have Python 2.7 currently installed on this machine, and it's located in the System Variables Path like this -> C:\Python27\;

I am getting this error during installation:

ERROR: gcloud failed to load: DLL load failed: %1 is not a valid Win32
  application.

The error message also prompts me to check the Python executable by saying:

If it is not, please set the CLOUDSDK_PYTHON environment variable to
  point to a working Python 2.7 executable.

So, I'm trying to set the CLOUDSDK_PYTHON environment variable in the install.sh shell script...But nothing is working. Here is the code from that file:

```<code>echo Welcome to the Google Cloud SDK!

if [ -z "$CLOUDSDK_PYTHON" ]; then
 if [ -z "$(which python)" ]; then
  echo
  echo "To use the Google Cloud SDK, you must have Python installed and on your PATH."
  echo "As an alternative, you may also set the CLOUDSDK_PYTHON environment variable"
  echo "to the location of your Python executable."
  exit 1
 fi
 CLOUDSDK_PYTHON="python"
fi
</code>```

I have tried python2.7, and the path to the executable, C:\Python27, but I'm getting this error when I try to run the script with those variables:

```<code>install.sh: line 128: $'python\r': command not found
</code>```

I found this stack question, but none of the solutions worked for me. Any help would be great appreciated.

答:
I had the same issue when the sdk was pointing to the virtualenv python. I solved it by using the default python2.7 in Ubuntu

Type this in termimal

```<code>export CLOUDSDK_PYTHON=/usr/bin/python
</code>```

Body:
I am trying to install the Google Cloud SDK on my Windows machine. I have Python 2.7 currently installed on this machine, and it's located in the System Variables Path like this -> C:\Python27\;

I am getting this error during installation:

ERROR: gcloud failed to load: DLL load failed: %1 is not a valid Win32
  application.

The error message also prompts me to check the Python executable by saying:

If it is not, please set the CLOUDSDK_PYTHON environment variable to
  point to a working Python 2.7 executable.

So, I'm trying to set the CLOUDSDK_PYTHON environment variable in the install.sh shell script...But nothing is working. Here is the code from that file:

echo Welcome to the Google Cloud SDK!

if [ -z "$CLOUDSDK_PYTHON" ]; then
 if [ -z "$(which python)" ]; then
  echo
  echo "To use the Google Cloud SDK, you must have Python installed and on your PATH."
  echo "As an alternative, you may also set the CLOUDSDK_PYTHON environment variable"
  echo "to the location of your Python executable."
  exit 1
 fi
 CLOUDSDK_PYTHON="python"
fi

I have tried python2.7, and the path to the executable, C:\Python27, but I'm getting this error when I try to run the script with those variables:

install.sh: line 128: $'python\r': command not found

I found this stack question, but none of the solutions worked for me. Any help would be great appreciated.

Body:
I had the same issue when the sdk was pointing to the virtualenv python. I solved it by using the default python2.7 in Ubuntu

Type this in termimal

export CLOUDSDK_PYTHON=/usr/bin/python


问:
get the whole word string after finding the word in a text
i have a problem developing this function, i have this text..

```<code>Testing Function
ok
US.Cool
rwgehtrhjyw54 US_Cool
fhknehq is ryhetjuy6u24
gflekhtrhissfhejyw54i
</code>```

my function :

```<code>function TForm5.FindWordInString(sWordToFind, sTheString : String): Integer;
var
i : Integer; x:String;
begin
 Result := 0;
 for i:= 1 to Length(sTheString) do
   begin
    x := Copy(sTheString,i,Length(sWordToFind));
    if X = sWordToFind then
      begin
        if X.Length > sWordToFind.Length then
         begin
          Result := 100;
          break;
         end else

         begin
          Result := i;
          break;
         end;
       end;
   end;
end;
</code>```

now, i want X to be US.Cool, but here its always = US,  because i want to check the length of sWordToFind and X.

答:
After clarification, this question is about getting length of a word searched by its starting substring within a string. For example when having string like this:

```<code>fhknehq is ryhetjuy6u24
</code>```

When you execute a desired function for the above string with the following substrings, you should get results like:

hknehq → 0 → substring is not at the beginning of a word
fhknehq → 7 → length of the word because substring is at the beginning of a word
yhetjuy6u24 → 0 → substring is not at the beginning of a word
ryhetjuy6u24 → 12 → length of the word because substring is at the beginning of a word
```

<p>If that is so, I would do this:</p>

```function GetFoundWordLength(const Text, Word: string): Integer;
const
  Separators: TSysCharSet = [' '];
var
  RetPos: PChar;
begin
  Result := 0;
  { get the pointer to the char where the Word was found in Text }
  RetPos := StrPos(PChar(Text), PChar(Word));
  { if the Word was found in Text, and it was at the beginning of Text, or the preceding
    char is a defined word separator, we're at the beginning of the word; so let's count
    this word's length by iterating chars till the end of Text or until we reach defined
    separator }
  if Assigned(RetPos) and ((RetPos = PChar(Text)) or CharInSet((RetPos - 1)^, Separators)) then
    while not CharInSet(RetPos^, [#0] + Separators) do
    begin
      Inc(Result);
      Inc(RetPos);
    end;
end;
```

Body:
i have a problem developing this function, i have this text..

Testing Function
ok
US.Cool
rwgehtrhjyw54 US_Cool
fhknehq is ryhetjuy6u24
gflekhtrhissfhejyw54i

my function :

function TForm5.FindWordInString(sWordToFind, sTheString : String): Integer;
var
i : Integer; x:String;
begin
 Result := 0;
 for i:= 1 to Length(sTheString) do
   begin
    x := Copy(sTheString,i,Length(sWordToFind));
    if X = sWordToFind then
      begin
        if X.Length > sWordToFind.Length then
         begin
          Result := 100;
          break;
         end else

         begin
          Result := i;
          break;
         end;
       end;
   end;
end;

now, i want X to be US.Cool, but here its always = US,  because i want to check the length of sWordToFind and X.

Body:
After clarification, this question is about getting length of a word searched by its starting substring within a string. For example when having string like this:

fhknehq is ryhetjuy6u24

When you execute a desired function for the above string with the following substrings, you should get results like:

hknehq → 0 → substring is not at the beginning of a word
fhknehq → 7 → length of the word because substring is at the beginning of a word
yhetjuy6u24 → 0 → substring is not at the beginning of a word
ryhetjuy6u24 → 12 → length of the word because substring is at the beginning of a word

If that is so, I would do this:

function GetFoundWordLength(const Text, Word: string): Integer;
const
  Separators: TSysCharSet = [' '];
var
  RetPos: PChar;
begin
  Result := 0;
  { get the pointer to the char where the Word was found in Text }
  RetPos := StrPos(PChar(Text), PChar(Word));
  { if the Word was found in Text, and it was at the beginning of Text, or the preceding
    char is a defined word separator, we're at the beginning of the word; so let's count
    this word's length by iterating chars till the end of Text or until we reach defined
    separator }
  if Assigned(RetPos) and ((RetPos = PChar(Text)) or CharInSet((RetPos - 1)^, Separators)) then
    while not CharInSet(RetPos^, [#0] + Separators) do
    begin
      Inc(Result);
      Inc(RetPos);
    end;
end;


问:
Object deserialization error
Here is my json format :

```<code>{
  "groupe1": [
    {
      "nom": "tache1",
      "type": "Tache"
    },
    {
      "nom": "tache2",
      "type": "Tache"
    }
  ],...
}
</code>```

I want to deserialize this into these classes, Groupe and Item.
My code :

```<code>public static class Config
{
    public const string pathSharedFile = @"Config.json";

    public static List<string> ReadGroupes()
    {
        StreamReader sr = new StreamReader(pathSharedFile);
        List<Groupe> Groupes = JsonConvert.DeserializeObject<List<Groupe>>(sr.ReadToEnd());
        return new List<string>();
    }
}

public class Groupe
{
    public Item[] items { get; set; }
}
public class Item
{
    public string nom { get; set; }
    public string type { get; set; }
}
</code>```

An error is thrown when I try the cast. Can someone help me ?

答:
Remove the Groupe class and use a dictionary like this:

```<code>Dictionary<string, Item[]> Groupes =
          JsonConvert.DeserializeObject<Dictionary<string, Item[]>>(sr.ReadToEnd());
</code>```

As the properties are dynamic using a dictionary will allow you to access each group by key:

```<code>var groupContent = Groupes["groupe1"];

foreach(var item in groupContent)
   //Do whatever you want with the item
</code>```

Title: Object deserialization error

Body:
Here is my json format :

{
  "groupe1": [
    {
      "nom": "tache1",
      "type": "Tache"
    },
    {
      "nom": "tache2",
      "type": "Tache"
    }
  ],...
}

I want to deserialize this into these classes, Groupe and Item.
My code :

public static class Config
{
    public const string pathSharedFile = @"Config.json";

    public static List<string> ReadGroupes()
    {
        StreamReader sr = new StreamReader(pathSharedFile);
        List<Groupe> Groupes = JsonConvert.DeserializeObject<List<Groupe>>(sr.ReadToEnd());
        return new List<string>();
    }
}

public class Groupe
{
    public Item[] items { get; set; }
}
public class Item
{
    public string nom { get; set; }
    public string type { get; set; }
}

An error is thrown when I try the cast. Can someone help me ?

Body:
Remove the Groupe class and use a dictionary like this:

Dictionary<string, Item[]> Groupes =
          JsonConvert.DeserializeObject<Dictionary<string, Item[]>>(sr.ReadToEnd());

As the properties are dynamic using a dictionary will allow you to access each group by key:

var groupContent = Groupes["groupe1"];

foreach(var item in groupContent)
   //Do whatever you want with the item


问:
Get my Brand in the middle of my flexbox top bar
I am building a topbar above my navbar so this is not a nav and does not need the hamburger icon on small screens. I want the top bar to have an icon to the left end, a brand in the middle and 2 icons at the right end. I have been trying to use flexbox to achieve my goal but I can not get the central brand to be centered.

My code is

```<code><div class="container-fluid bg-light topbar">
<div id="compassicon" class="d-flex justify-content-end text-muted">
  <div class="text-muted fa fa-compass fa-2x"></div>
  <div id="townlabel" class="mr-auto p-2">Town</div>
  <div class="center">
  <p class="title-border title-text">Brand Name
  </p>
  </div>
  <div class="text-muted fa fa-user-o fa-2x"></div>
  <div class="text-muted fa fa-power-off fa-2x"></div>
</div>
</code>```

CSS

```<code>.title-border {
border: 1px solid black;
border-radius: 20px;
background: #3BA7A4;

}

.title-text {
color: white !important ;
 /*font-family: 'Shrikhand', cursive;*/
font-family: 'Jura', sans-serif;
font-size: 1.5em;

}

#townlabel * {
display: inline-block;
vertical-align: middle;
font-family: 'Jura', sans-serif;

}
#compassicon {
display: inline-block;
}

.topbar {
max-height: 41px;
}

.brand-heading {
 float: none;
}
</code>```

Any ideas?

答:
Would you want something like this? Then text-align:center on the parent element and display: inline-block on the text element

.title-border {
border: 1px solid black;
border-radius: 20px;
background: #3BA7A4;

}

.title-text {
color: white !important ;
 /*font-family: 'Shrikhand', cursive;*/
font-family: 'Jura', sans-serif;
font-size: 1.5em;

}

#townlabel * {
display: inline-block;
vertical-align: middle;
font-family: 'Jura', sans-serif;

}
#compassicon {
text-align: center;
}

.topbar {
max-height: 41px;
}

.brand-heading {
 float: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container-fluid bg-light topbar">
<div id="compassicon" class="d-flex justify-content-end text-muted">
  <div class="text-muted fa fa-compass fa-2x"></div>
  <div id="townlabel" class="mr-auto p-2">Town</div>
  <div class="center" style="display: inline-block;">
  <p class="title-border title-text">Brand Name
  </p>
  </div>
  <div class="text-muted fa fa-user-o fa-2x"></div>
  <div class="text-muted fa fa-power-off fa-2x"></div>
</div></code>```

Body:
I am building a topbar above my navbar so this is not a nav and does not need the hamburger icon on small screens. I want the top bar to have an icon to the left end, a brand in the middle and 2 icons at the right end. I have been trying to use flexbox to achieve my goal but I can not get the central brand to be centered.

My code is

Town

Brand Name

CSS

.title-border {
border: 1px solid black;
border-radius: 20px;
background: #3BA7A4;

}

.title-text {
color: white !important ;
 /*font-family: 'Shrikhand', cursive;*/
font-family: 'Jura', sans-serif;
font-size: 1.5em;

}

#townlabel * {
display: inline-block;
vertical-align: middle;
font-family: 'Jura', sans-serif;

}
#compassicon {
display: inline-block;
}

.topbar {
max-height: 41px;
}

.brand-heading {
 float: none;
}

Any ideas?

Body:
Would you want something like this? Then text-align:center on the parent element and display: inline-block on the text element

.title-border {
border: 1px solid black;
border-radius: 20px;
background: #3BA7A4;

}

.title-text {
color: white !important ;
 /*font-family: 'Shrikhand', cursive;*/
font-family: 'Jura', sans-serif;
font-size: 1.5em;

}

#townlabel * {
display: inline-block;
vertical-align: middle;
font-family: 'Jura', sans-serif;

}
#compassicon {
text-align: center;
}

.topbar {
max-height: 41px;
}

.brand-heading {
 float: none;
}

<div class="container-fluid bg-light topbar">
<div id="compassicon" class="d-flex justify-content-end text-muted">
  <div class="text-muted fa fa-compass fa-2x"></div>
  <div id="townlabel" class="mr-auto p-2">Town</div>
  <div class="center" style="display: inline-block;">
  <p class="title-border title-text">Brand Name
  </p>
  </div>
  <div class="text-muted fa fa-user-o fa-2x"></div>
  <div class="text-muted fa fa-power-off fa-2x"></div>
</div>


问:
How to convert dates from several formats into one single format?
I have several different formats of dates in one field.  It looks like this.

```<code>20200228

12/15/2021

7/6/2020

Oct 29 2017 12:00AM

Oct 31 20

08/01/18
</code>```

How can I get everything standardized as MM/DD/YYYY?

```<code>20200228 --> 02/28/2020

12/15/2021 --> no change

Oct 31 2017 12:00AM --> 10/31/2017

Oct 31 20 --> 10/31/2017

08/01/18 --> 08/01/2018
</code>```

I tried all kinds of Cast and Convert combinations, but I couldn't get anything to work.  Does anyone out there have a solution for this?  It doesn't have to be one pass in one query.  I'm sure it can be done in several iterations, but I don't know how to tackle it.

答:
Basically, you just try one conversion after another -- but convert to a date not to another format.  Here is one idea:

```<code>select coalesce(try_convert(date, col),
                try_convert(date, col, 100),
                try_convert(date, col, 101),
                try_convert(date, col, 102),
                try_convert(date, col, 107)
               )
</code>```

I'm not sure if this covers all your formats, but it is worth a try.

EDIT:

SQL Server is pretty flexible in reading dates.  The defaults appear to work for your examples:

```<code>with d as (
      select '20200228' as col union all
      select '12/15/2021' union all
      select '7/6/2020' union all
      select 'Oct 29 2017 12:00AM' union all
      select 'Oct 31 20' union all
      select '08/01/18'
     )
select cast(d.col as date)
from d;
</code>```

The SQL Fiddle is using SQL Server 2014.  I don't think the handling of casts of dates has changed (although that might have).

Body:
I have several different formats of dates in one field.  It looks like this.

20200228

12/15/2021

7/6/2020

Oct 29 2017 12:00AM

Oct 31 20

08/01/18

How can I get everything standardized as MM/DD/YYYY?

20200228 --> 02/28/2020

12/15/2021 --> no change

Oct 31 2017 12:00AM --> 10/31/2017

Oct 31 20 --> 10/31/2017

08/01/18 --> 08/01/2018

I tried all kinds of Cast and Convert combinations, but I couldn't get anything to work.  Does anyone out there have a solution for this?  It doesn't have to be one pass in one query.  I'm sure it can be done in several iterations, but I don't know how to tackle it.

Body:
Basically, you just try one conversion after another -- but convert to a date not to another format.  Here is one idea:

select coalesce(try_convert(date, col),
                try_convert(date, col, 100),
                try_convert(date, col, 101),
                try_convert(date, col, 102),
                try_convert(date, col, 107)
               )

I'm not sure if this covers all your formats, but it is worth a try.

EDIT:

SQL Server is pretty flexible in reading dates.  The defaults appear to work for your examples:

with d as (
      select '20200228' as col union all
      select '12/15/2021' union all
      select '7/6/2020' union all
      select 'Oct 29 2017 12:00AM' union all
      select 'Oct 31 20' union all
      select '08/01/18'
     )
select cast(d.col as date)
from d;

The SQL Fiddle is using SQL Server 2014.  I don't think the handling of casts of dates has changed (although that might have).


问:
How to check (and kill) javascript-scroll when bottom of webpage is reached
I've been working in Python for a couple of years and have recently started looking into Javascript (not jQuery or dependencies, just plain Javascript) for some browser automation tasks.

Scrolling sites with lazy load (like a Facebook-page, a Twitter-page or heck even the Wallmart site) in Python is straightforward using fx Selenium.

In Python a rough 'n' dirty solution could be a height-check and break out of a while-loop if the height stops increasing. Like so:

```<code>check_height = driver.execute_script("return document.body.scrollHeight;")
while True:
    browser.execute_script("window.scrollTo(0, document.body.scrollHeight);")
    time.sleep(2)
    height = driver.execute_script("return document.body.scrollHeight;")
    if height == check_height:
        break
    check_height = height
</code>```

So now I'm trying to accomplish the same thing in Javascript using the Chrome-console. So far a working code looks like this:

```<code>var scrollToBottom = function() {
    window.scrollTo(0, document.body.scrollHeight);
    }
var sleep = 1000;
var kill_ID = setInterval(scrollToBottom, sleep);
</code>```

The setInterval initiates a loop that goes on forever - with a second of sleep time between each call to scrollToBottom. And I can then - manually - kill it when no more content is loaded by issuing:

```<code>window.clearInterval(kill_ID);
</code>```

This is obviously not the best way to go about this. So there has to be a better way of accomplishing the task without having to manually kill the scrolling-process.

But the Python logic doesn't seem to work for me in Javascript. Anyone that will give me a couple of pointers as to how to accomplish this - I assume - basic task? Thanks in advance.

Update:
As there apparently are no easy fixes for this one, I went with a low tech solution and added an eventListener, that kills the scrolling when I click the mouse (trigger the clearInterval).

So an extra code snippet for this to work - fx as a bookmarklet - would just need to be:

```<code>window.addEventListener('click', function kill(){window.clearInterval(kill_ID)})
</code>```

Thanks for the helpfull comments, everyone.

答:
If I understand your problem, you are wanting to do something when the window scrolls, and then based on that do something else. You should be able to do this via eventListeners:

```<code>window.addEventListener('scroll', event => {
  // Do your checks to see if you need to
  // do your work or not
  if (doWork()) {
    doSomethingElse()
  }
})
</code>```

Here is a jsfiddle of an example that I think does what you are asking

If you wanted to add a dependency, this would become a little easier to do:

```<code><script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.5.2/Rx.js"></script>
<script>
  const { Observable } = Rx

  const scrollStream = Observable.fromEvent(window, 'scroll')

  const isTheScrollICareAboutSubscription = scrollStream
    .filter(e => {
      // return true or false if this is
      // an event we care about
      return doWork(e)
    })
    .subscribe(doSomethingElse)
</script>
</code>```

Body:
I've been working in Python for a couple of years and have recently started looking into Javascript (not jQuery or dependencies, just plain Javascript) for some browser automation tasks.

Scrolling sites with lazy load (like a Facebook-page, a Twitter-page or heck even the Wallmart site) in Python is straightforward using fx Selenium.

In Python a rough 'n' dirty solution could be a height-check and break out of a while-loop if the height stops increasing. Like so:

check_height = driver.execute_script("return document.body.scrollHeight;")
while True:
    browser.execute_script("window.scrollTo(0, document.body.scrollHeight);")
    time.sleep(2)
    height = driver.execute_script("return document.body.scrollHeight;")
    if height == check_height:
        break
    check_height = height

So now I'm trying to accomplish the same thing in Javascript using the Chrome-console. So far a working code looks like this:

var scrollToBottom = function() {
    window.scrollTo(0, document.body.scrollHeight);
    }
var sleep = 1000;
var kill_ID = setInterval(scrollToBottom, sleep);

The setInterval initiates a loop that goes on forever - with a second of sleep time between each call to scrollToBottom. And I can then - manually - kill it when no more content is loaded by issuing:

window.clearInterval(kill_ID);

This is obviously not the best way to go about this. So there has to be a better way of accomplishing the task without having to manually kill the scrolling-process.

But the Python logic doesn't seem to work for me in Javascript. Anyone that will give me a couple of pointers as to how to accomplish this - I assume - basic task? Thanks in advance.

Update:
As there apparently are no easy fixes for this one, I went with a low tech solution and added an eventListener, that kills the scrolling when I click the mouse (trigger the clearInterval).

So an extra code snippet for this to work - fx as a bookmarklet - would just need to be:

window.addEventListener('click', function kill(){window.clearInterval(kill_ID)})

Thanks for the helpfull comments, everyone.

Body:
If I understand your problem, you are wanting to do something when the window scrolls, and then based on that do something else. You should be able to do this via eventListeners:

window.addEventListener('scroll', event => {
  // Do your checks to see if you need to
  // do your work or not
  if (doWork()) {
    doSomethingElse()
  }
})

Here is a jsfiddle of an example that I think does what you are asking

If you wanted to add a dependency, this would become a little easier to do:

<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.5.2/Rx.js"></script>
<script>
  const { Observable } = Rx

  const scrollStream = Observable.fromEvent(window, 'scroll')

  const isTheScrollICareAboutSubscription = scrollStream
    .filter(e => {
      // return true or false if this is
      // an event we care about
      return doWork(e)
    })
    .subscribe(doSomethingElse)
</script>


问:
brew install i386-elf-gcc and error:contains conflicting version recursive dependencies
brew install i386-elf-gcc

==> Installing i386-elf-gcc from altkatz/gcc_cross_compilers
Error: altkatz/gcc_cross_compilers/i386-elf-gcc contains conflicting version recursive dependencies:
  gmp, gmp@4, mpfr, mpfr@2, libmpc, libmpc@0.8

View these with brew deps --tree altkatz/gcc_cross_compilers/i386-elf-gcc.

And the debs tree looks like:

```<code>altkatz/gcc_cross_compilers/i386-elf-gcc
├── gmp
├── libmpc
│   ├── gmp
│   └── mpfr
│       └── gmp
├── mpfr
│   └── gmp
└── i386-elf-binutils
</code>```

After I installed the gmp@4,mpfr@2,libmpc@0.8,gcc49 ,the error doesn't change .

答:
I installed it using MacPorts and it worked for me:</p>

```<code>sudo port install i386-elf-binutils
sudo port install i386-elf-gcc

cd /opt/local/bin
sudo ln -s i386-elf-gcc i386-elf-gcc-4.7.2
</code>```

Body:
brew install i386-elf-gcc

==> Installing i386-elf-gcc from altkatz/gcc_cross_compilers
Error: altkatz/gcc_cross_compilers/i386-elf-gcc contains conflicting version recursive dependencies:
  gmp, gmp@4, mpfr, mpfr@2, libmpc, libmpc@0.8

View these with brew deps --tree altkatz/gcc_cross_compilers/i386-elf-gcc.

And the debs tree looks like:

altkatz/gcc_cross_compilers/i386-elf-gcc
├── gmp
├── libmpc
│   ├── gmp
│   └── mpfr
│       └── gmp
├── mpfr
│   └── gmp
└── i386-elf-binutils

After I installed the gmp@4,mpfr@2,libmpc@0.8,gcc49 ,the error doesn't change .

Body:
I installed it using MacPorts and it worked for me:

sudo port install i386-elf-binutils
sudo port install i386-elf-gcc

cd /opt/local/bin
sudo ln -s i386-elf-gcc i386-elf-gcc-4.7.2


问:
R: how to check how many cores/CPU usage available
R is single-threaded.

Using R, how to check how many cores/threads are running R in Windows and Linux? (Or how many Rs are running)

Using R, how to check the usage of each core that is running R in Windows and Linux? (Or the percentage of CPU each R is using)

For example, if I have two R opened running projects. I would expect that there are 2 threads running R with some % of CPU for each thread. Then I open another R. How to use the third R to check the number of threads (2 in this case) and percentage of CPU being used by R?

答:
If you open multiple R windows, each window will be running on a different core up to the maximum number of cores that you have. This is automatically implemented on windows and mac computers. If you want to know how many cores you have, you can run:</p>

```<code>library(parallel)
detectCores()
</code>```

Body:
If you open multiple R windows, each window will be running on a different core up to the maximum number of cores that you have. This is automatically implemented on windows and mac computers. If you want to know how many cores you have, you can run:

library(parallel)
detectCores()


问:
Syntax error in bison when reading token
I have a file that will be read in by my parser:

test.txt

```<code>BEGINING.

XXX XY-1.

XXXX Y.

XXXX Z.

BODY.

PRINT "Please enter a number?".

END.
</code>```

The error is occurring around the PRINT token. In my lexical analyser, the string "Please enter a number?" is getting processed correctly, I know this because I outputted it to the console.

lexer.I

```<code>%{
#include <stdio.h>

#include "parser.tab.h"
#define YYSTYPE char *
%}

%option noyywrap
%option caseless

%%

(?i:BEGINING) return TERM_BEGINING;
(?i:BODY) return TERM_BODY;
(?i:END) return TERM_END;
(?i:MOVE) return TERM_MOVE;
(?i:TO) return TERM_TO;
(?i:ADD) return TERM_ADD;
(?i:INPUT) return TERM_INPUT;
(?i:PRINT) return TERM_PRINT;

[\t| ]+ // ignore whitespaces

\n // Ignore new line

[X]+ yylval.integer = yyleng; return TERM_SIZE;

[\"][^"]*[\"] yylval.string = strdup(yytext); printf("%s\n", yytext); return TERM_STR;

";" return TERM_SEPARATOR;

"." return TERM_FULLSTOP;

[0-9]+ yylval.integer = atoi(yytext); return TERM_INT;

[\_\-0-9][a-zA-Z][a-zA-Z0-9\-\_]* yylval.string = strdup(yytext); return TERM_INVALID_VARIABLE_NAME;

[A-Z][A-Z0-9\-]* yylval.string = strdup(yytext); return TERM_VARIABLE_NAME;

. return TERM_INVALID_TOKEN;

%%

//int main(int argc, char** argv) {
//  if (argc != 2) {
//      yyin = stdin;
//      yylex();
//  } else {
//      FILE* aFile = fopen(argv[1], "r");
//      if (!aFile) {
//          printf("Cannot open file!\n");
//          return -1;
//      } else {
//          yyin = aFile;
//          yylex();
//          fclose(yyin);
//      }
//  }
//}
</code>```

Now in the parser, for debugging purposes, when the PRINT keywor is returned from the lexical analyser I have decided to print out the word PRINT

parser.y

```<code>%{
//yylval - externalise variable in which yylex should place semantic value associated with a token
//yyparse - parser function produced by bison, call this to start parsing

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <unistd.h>

extern FILE* yyin;
typedef int bool;

#define true 1
#define false 0

//Cause an immediate syntax error
int yyerror(char *s) {
  fprintf(stderr, "%s\n", s);
  exit(0);
}

//Declare yylex, user supplied lexical analyzer function to get the next token
int yylex(void);

//yywrap text wrap
//When scanner recieves EOF it checks yywrap()
int yywrap(void) {
    return 1;
}

// Structure of variable
struct variable {
    char* varName;
    int varSize;
    int varValue;
};

typedef struct {
    struct variable* array;
    size_t used;
    size_t size;
} Array;

// Method declarations
void writeToWarning(char *aWarning);
void writeError(char *anError);
void writeToLog(char *alog);
bool checkIfDeclared(char* varName);

void initialiseArray(Array *a, size_t initialSize);
void insertArray(Array *a, struct variable *aVar);
void freeArray(Array *a);

void createVar(int size, char* varName);
void inputValues(char* varName);

%}

//each token is a terminal
%token TERM_BEGINING TERM_BODY TERM_END TERM_MOVE
        TERM_TO TERM_ADD TERM_INPUT TERM_PRINT
        TERM_SIZE TERM_STR TERM_SEPARATOR TERM_FULLSTOP
        TERM_INT TERM_INVALID_VARIABLE_NAME TERM_VARIABLE_NAME TERM_INVALID_TOKEN

//Everything that something can be
//yyvval array from lexer.l
%union {
    int integer;
    char* string;
}

//Define anything that the lexer can return as a string or integer
%type<integer> TERM_INT
%type<integer> TERM_SIZE
%type<string> TERM_STR
%type<string> TERM_SEPARATOR
%type<string> TERM_FULLSTOP
%type<string> TERM_VARIABLE_NAME
%type<string> TERM_INVALID_VARIABLE_NAME

%%

// Create grammer

program:
    /* empty */ |
    begin middle_declarations body grammar_s end {
        printf("Parsing complete\n");
        exit(0);
    };

begin:
    TERM_BEGINING TERM_FULLSTOP;

body:
    TERM_BODY TERM_FULLSTOP;

end:
    TERM_END TERM_FULLSTOP;

middle_declarations:
    /* empty */ |
    //Left recursive to allow for many declearations
    middle_declarations declaration TERM_FULLSTOP;

declaration:
    TERM_SIZE TERM_VARIABLE_NAME {
        createVar($1, $2);
    };

grammar_s:
    /* empty */ |
    grammar_s grammar TERM_FULLSTOP;

grammar:
    add | move | print | input;

add:
    TERM_ADD TERM_VARIABLE_NAME TERM_TO TERM_VARIABLE_NAME {
        //addVarToVar($2, $4);
    }

    TERM_ADD TERM_INT TERM_TO TERM_VARIABLE_NAME {
        //addNumToVar($2, $4);
    }

    ;

move:
    TERM_MOVE TERM_VARIABLE_NAME TERM_TO TERM_VARIABLE_NAME {
        //moveVarToVar($2, $4);
    }

    TERM_MOVE TERM_INT TERM_TO TERM_VARIABLE_NAME {
        //moveNumToVar($2, $4);
    }

    ;

print:
    TERM_PRINT rest_of_print {
        printf("PRINT\n");
    };

rest_of_print:
    /* empty */ |
    rest_of_print other_print;

other_print:
    TERM_VARIABLE_NAME {
        //printVarName($1);
    }

    TERM_INVALID_VARIABLE_NAME {
        //printInvalidVarName($1);
    }

    TERM_SEPARATOR {
        printf("%s", $1);
    }

    TERM_STR {
        printf("STRING%s%s", $1, "\n");
    }

    ;

input:
    // Fullstop declares grammar
    TERM_INPUT other_input;

other_input:

    /* empty */ |
    // Input var1
    TERM_VARIABLE_NAME {
        inputValues($1);
    }

    // Can be input var1
    TERM_VARIABLE_NAME TERM_SEPARATOR {
        //inputValues($2);
    }

    ;

%%

Array a;

void initialiseArray(Array *a, size_t initialSize) {
    a->array = (struct variable*) malloc(initialSize * sizeof(struct variable));
    a->used = 0;
    a->size = initialSize;
}

void insertArray(Array *a, struct variable *aVar) {
    if (a->used == a->size) {
        a->size *= 6;
        a->array = (struct variable*) realloc(a->array, a->size * sizeof(struct variable));
    }
    a->array[a->used++] = *aVar;
}

void freeArray(Array *a) {
    free(a->array);
    a->array = NULL;
    a->used = a->size = 0;
}

void createVar(int size, char* varName) {

    printf("SIZE: %d\n", size);
    printf("NAME: %s\n", varName);

    bool alreadyDeclared;
    alreadyDeclared = checkIfDeclared(varName);
    if (!alreadyDeclared) {
        struct variable aVar;
        aVar.varName = varName;
        aVar.varSize = size;
        aVar.varValue = 0;

        insertArray(&a, &aVar);

        writeToLog("Created variable succesfully\n");
    } else {
        writeToWarning("Variable has already been declared\n");
    }
}

bool checkIfDeclared(char* varName) {
    for (int i = 0; i < a.used; i++) {
        if (strcmp(a.array[i].varName, varName) == 0) {
            return 1;
        }
    }
    return 0;
}

void inputValues(char* varName) {
    printf("VAR_NAME: %s\n", varName);
}

int main(int argc, char* argv[]) {

    if (argc != 2) {
        yyin = stdin;
        yylex();
    } else {
        FILE* aFile = fopen(argv[1], "r");
        if (!aFile) {
            printf("Cannot open file!\n");
            return -1;
        } else {
            int i;
            initialiseArray(&a, 5);

            yyin = aFile;
            yyparse();
        }
    }

    fclose(yyin);
    freeArray(&a);

 // for (int i = 0; i < 10; i++) {
    //  struct variable aVar;
    //  aVar.varName = "TEST_VAR";
    //  aVar.varSize = 0;
    //  aVar.varValue = 0;

    //  insertArray(&a, &aVar);
    //}

    //for (int j = 0; j < a.used; j++) {
    //  printf("Name: %s\n", a.array[j].varName);
    //}
    //printf("Name: %s\n", a.array[9].varName);
    //printf("Used: %zu\n", a.used);

    //yyparse();

    //if (argc > 0) {
    //  freeArray(&a);
    //  fclose(yyin);
    //}
    return 0;
}

void writeToWarning(char *aWarning){
  printf("Warning : %s%s", aWarning,"\n");
}

void writeError(char *anError){
  printf("Error : %s%s", anError,"\n");
}

void writeToLog(char *alog){
  printf("Success : %s%s", alog,"\n");
}
</code>```

This is how I compile

```<code>bison -d parser.y -o parser.tab.c
flex -o lexer.yy.c lexer.I
gcc lexer.yy.c parser.tab.c -o parser
</code>```

This is how I run

```<code>./parser test.txt
</code>```

Then this is the output that I get

```<code>SIZE: 3 // this is output from the createVar function
NAME: XY-1
Success : Created variable succesfully

SIZE: 4
NAME: Y
Success : Created variable succesfully

SIZE: 4
NAME: Z
Success : Created variable succesfully

"Please enter a number?" // This is output for debugging from the lexer
PRINT // This is output for debugging from the parser,
syntax error
</code>```

答:
Leaving out the actions (which do not change the grammar) your other_print rule is:

```<code>other_print:
    TERM_VARIABLE_NAME TERM_INVALID_VARIABLE_NAME TERM_SEPARATOR TERM_STR
</code>```

That odd sequence of terminals is not present in your input file, so the production won't match, leading to a syntax error report.

It seems unlikely that you actually wanted that syntax; my guess is that you intended the four terminals to be alternatives rather than a concatenation. If so, you need to separate them with |s.

other_input has a similar issue.

Body:
I have a file that will be read in by my parser:

test.txt

BEGINING.

XXX XY-1.

XXXX Y.

XXXX Z.

BODY.

PRINT "Please enter a number?".

END.

The error is occurring around the PRINT token. In my lexical analyser, the string "Please enter a number?" is getting processed correctly, I know this because I outputted it to the console.

lexer.I

%{
#include <stdio.h>

#include "parser.tab.h"
#define YYSTYPE char *
%}

%option noyywrap
%option caseless

%%

(?i:BEGINING) return TERM_BEGINING;
(?i:BODY) return TERM_BODY;
(?i:END) return TERM_END;
(?i:MOVE) return TERM_MOVE;
(?i:TO) return TERM_TO;
(?i:ADD) return TERM_ADD;
(?i:INPUT) return TERM_INPUT;
(?i:PRINT) return TERM_PRINT;

[\t| ]+ // ignore whitespaces

\n // Ignore new line

[X]+ yylval.integer = yyleng; return TERM_SIZE;

[\"][^"]*[\"] yylval.string = strdup(yytext); printf("%s\n", yytext); return TERM_STR;

";" return TERM_SEPARATOR;

"." return TERM_FULLSTOP;

[0-9]+ yylval.integer = atoi(yytext); return TERM_INT;

[\_\-0-9][a-zA-Z][a-zA-Z0-9\-\_]* yylval.string = strdup(yytext); return TERM_INVALID_VARIABLE_NAME;

[A-Z][A-Z0-9\-]* yylval.string = strdup(yytext); return TERM_VARIABLE_NAME;

. return TERM_INVALID_TOKEN;

%%

//int main(int argc, char** argv) {
//  if (argc != 2) {
//      yyin = stdin;
//      yylex();
//  } else {
//      FILE* aFile = fopen(argv[1], "r");
//      if (!aFile) {
//          printf("Cannot open file!\n");
//          return -1;
//      } else {
//          yyin = aFile;
//          yylex();
//          fclose(yyin);
//      }
//  }
//}

Now in the parser, for debugging purposes, when the PRINT keywor is returned from the lexical analyser I have decided to print out the word PRINT

parser.y

%{
//yylval - externalise variable in which yylex should place semantic value associated with a token
//yyparse - parser function produced by bison, call this to start parsing

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <unistd.h>

extern FILE* yyin;
typedef int bool;

#define true 1
#define false 0

//Cause an immediate syntax error
int yyerror(char *s) {
  fprintf(stderr, "%s\n", s);
  exit(0);
}

//Declare yylex, user supplied lexical analyzer function to get the next token
int yylex(void);

//yywrap text wrap
//When scanner recieves EOF it checks yywrap()
int yywrap(void) {
    return 1;
}

// Structure of variable
struct variable {
    char* varName;
    int varSize;
    int varValue;
};

typedef struct {
    struct variable* array;
    size_t used;
    size_t size;
} Array;

// Method declarations
void writeToWarning(char *aWarning);
void writeError(char *anError);
void writeToLog(char *alog);
bool checkIfDeclared(char* varName);

void initialiseArray(Array *a, size_t initialSize);
void insertArray(Array *a, struct variable *aVar);
void freeArray(Array *a);

void createVar(int size, char* varName);
void inputValues(char* varName);

%}

//each token is a terminal
%token TERM_BEGINING TERM_BODY TERM_END TERM_MOVE
        TERM_TO TERM_ADD TERM_INPUT TERM_PRINT
        TERM_SIZE TERM_STR TERM_SEPARATOR TERM_FULLSTOP
        TERM_INT TERM_INVALID_VARIABLE_NAME TERM_VARIABLE_NAME TERM_INVALID_TOKEN

//Everything that something can be
//yyvval array from lexer.l
%union {
    int integer;
    char* string;
}

//Define anything that the lexer can return as a string or integer
%type<integer> TERM_INT
%type<integer> TERM_SIZE
%type<string> TERM_STR
%type<string> TERM_SEPARATOR
%type<string> TERM_FULLSTOP
%type<string> TERM_VARIABLE_NAME
%type<string> TERM_INVALID_VARIABLE_NAME

%%

// Create grammer

program:
    /* empty */ |
    begin middle_declarations body grammar_s end {
        printf("Parsing complete\n");
        exit(0);
    };

begin:
    TERM_BEGINING TERM_FULLSTOP;

body:
    TERM_BODY TERM_FULLSTOP;

end:
    TERM_END TERM_FULLSTOP;

middle_declarations:
    /* empty */ |
    //Left recursive to allow for many declearations
    middle_declarations declaration TERM_FULLSTOP;

declaration:
    TERM_SIZE TERM_VARIABLE_NAME {
        createVar($1, $2);
    };

grammar_s:
    /* empty */ |
    grammar_s grammar TERM_FULLSTOP;

grammar:
    add | move | print | input;

add:
    TERM_ADD TERM_VARIABLE_NAME TERM_TO TERM_VARIABLE_NAME {
        //addVarToVar($2, $4);
    }

    TERM_ADD TERM_INT TERM_TO TERM_VARIABLE_NAME {
        //addNumToVar($2, $4);
    }

    ;

move:
    TERM_MOVE TERM_VARIABLE_NAME TERM_TO TERM_VARIABLE_NAME {
        //moveVarToVar($2, $4);
    }

    TERM_MOVE TERM_INT TERM_TO TERM_VARIABLE_NAME {
        //moveNumToVar($2, $4);
    }

    ;

print:
    TERM_PRINT rest_of_print {
        printf("PRINT\n");
    };

rest_of_print:
    /* empty */ |
    rest_of_print other_print;

other_print:
    TERM_VARIABLE_NAME {
        //printVarName($1);
    }

    TERM_INVALID_VARIABLE_NAME {
        //printInvalidVarName($1);
    }

    TERM_SEPARATOR {
        printf("%s", $1);
    }

    TERM_STR {
        printf("STRING%s%s", $1, "\n");
    }

    ;

input:
    // Fullstop declares grammar
    TERM_INPUT other_input;

other_input:

    /* empty */ |
    // Input var1
    TERM_VARIABLE_NAME {
        inputValues($1);
    }

    // Can be input var1
    TERM_VARIABLE_NAME TERM_SEPARATOR {
        //inputValues($2);
    }

    ;

%%

Array a;

void initialiseArray(Array *a, size_t initialSize) {
    a->array = (struct variable*) malloc(initialSize * sizeof(struct variable));
    a->used = 0;
    a->size = initialSize;
}

void insertArray(Array *a, struct variable *aVar) {
    if (a->used == a->size) {
        a->size *= 6;
        a->array = (struct variable*) realloc(a->array, a->size * sizeof(struct variable));
    }
    a->array[a->used++] = *aVar;
}

void freeArray(Array *a) {
    free(a->array);
    a->array = NULL;
    a->used = a->size = 0;
}

void createVar(int size, char* varName) {

    printf("SIZE: %d\n", size);
    printf("NAME: %s\n", varName);

    bool alreadyDeclared;
    alreadyDeclared = checkIfDeclared(varName);
    if (!alreadyDeclared) {
        struct variable aVar;
        aVar.varName = varName;
        aVar.varSize = size;
        aVar.varValue = 0;

        insertArray(&a, &aVar);

        writeToLog("Created variable succesfully\n");
    } else {
        writeToWarning("Variable has already been declared\n");
    }
}

bool checkIfDeclared(char* varName) {
    for (int i = 0; i < a.used; i++) {
        if (strcmp(a.array[i].varName, varName) == 0) {
            return 1;
        }
    }
    return 0;
}

void inputValues(char* varName) {
    printf("VAR_NAME: %s\n", varName);
}

int main(int argc, char* argv[]) {

    if (argc != 2) {
        yyin = stdin;
        yylex();
    } else {
        FILE* aFile = fopen(argv[1], "r");
        if (!aFile) {
            printf("Cannot open file!\n");
            return -1;
        } else {
            int i;
            initialiseArray(&a, 5);

            yyin = aFile;
            yyparse();
        }
    }

    fclose(yyin);
    freeArray(&a);

 // for (int i = 0; i < 10; i++) {
    //  struct variable aVar;
    //  aVar.varName = "TEST_VAR";
    //  aVar.varSize = 0;
    //  aVar.varValue = 0;

    //  insertArray(&a, &aVar);
    //}

    //for (int j = 0; j  0) {
    //  freeArray(&a);
    //  fclose(yyin);
    //}
    return 0;
}

void writeToWarning(char *aWarning){
  printf("Warning : %s%s", aWarning,"\n");
}

void writeError(char *anError){
  printf("Error : %s%s", anError,"\n");
}

void writeToLog(char *alog){
  printf("Success : %s%s", alog,"\n");
}

This is how I compile

bison -d parser.y -o parser.tab.c
flex -o lexer.yy.c lexer.I
gcc lexer.yy.c parser.tab.c -o parser

This is how I run

./parser test.txt

Then this is the output that I get

SIZE: 3 // this is output from the createVar function
NAME: XY-1
Success : Created variable succesfully

SIZE: 4
NAME: Y
Success : Created variable succesfully

SIZE: 4
NAME: Z
Success : Created variable succesfully

"Please enter a number?" // This is output for debugging from the lexer
PRINT // This is output for debugging from the parser,
syntax error

Body:
Leaving out the actions (which do not change the grammar) your other_print rule is:

other_print:
    TERM_VARIABLE_NAME TERM_INVALID_VARIABLE_NAME TERM_SEPARATOR TERM_STR

That odd sequence of terminals is not present in your input file, so the production won't match, leading to a syntax error report.

It seems unlikely that you actually wanted that syntax; my guess is that you intended the four terminals to be alternatives rather than a concatenation. If so, you need to separate them with |s.

other_input has a similar issue.


问:
Configure Mulesoft shared distribution memory
I am working on Mulesoft application which I have deployed in Mule servers of two different physical machines.The servers are binded together to form a cluster.

In clustering mode, the servers are said to share common distributed memory such that if one machine goes down,the other machine takes up the task of the first machine.So,they maintain common distributed memory between them.

Is there any way to configure the memory for the common distributed memory the cluster leverages?
As the traffic/number of applications gets added up,I guess,there will be need to lift the threshold memory up for the respective cluster.

Or if not,do we ever have to modify the memory volume at all that Mulesoft cluster uses ?

Please help me out.
Thanks

答:
In clustered scenarios all object stores are replaced with clustered object stores. Clustered object stores use the shared memory grid created by the clustering code to persist information (meaning that there is no file system level persistence), in case of an outage with a node, other nodes in the cluster should remain active and maintain the OS information in the shared memory grid, thus making the persistence in the file system unnecessary

Additionally, since object stores use the name of the application as part of storage information, if you want to keep them across re-deployments, the newly deployed application must have the same name as the previous one. Please see below as a reference:

Scenario a:
1. Current application name: test
2. New application name: test
- Object store values will be preserved from 1 to 2.

Scenario b:
1. Current application name: test-v1
2. New application name: test-v2
- Object store values will not be preserved from 1 to 2.

Note, In-memory store – Prior to Mule 3.5.0, in-memory store was the default. As of Mule 3.5.0, persistent store is the default.


问:
Multiple query Joins in windows form application C# with MS Access not working
I have three tables in MS Access database

users,
  rooms,
  room_history

room_history contains both users,rooms id. when I try to join users with room_history data successfully retrieve same goes with rooms and room_history.
Here is my query for joining all three tables.

```<code>"SELECT users.*,rooms.room_id,rooms.room_name,rooms.type,room_history.start_date,room_history.end_date FROM users " +
                "LEFT JOIN room_history ON room_history.user_id= users.user_id " +
                "LEFT JOIN rooms ON room_history.room_id = rooms.room_id";
</code>```

Using above query following error occurs.

syntax error (missing operator) in query expression 'room_history.user_id = users.user_id LEFT JOIN rooms on room_history.room_id = rooms.room_i'

I check/change my database tables name, compact the database.

答:
Is it possible to get to fundamentals here - and design this query using the Access query design view tool? ... rather than attempting to resolve this using a text based sql statement...

Once you make the query in Access using the query design feature, and verify that it runs correctly in returning the correct record set - - then use the option to put it into SQL View (rather than Design View) in order to see the text based sql statement.

Body:
I have three tables in MS Access database

users,
  rooms,
  room_history

room_history contains both users,rooms id. when I try to join users with room_history data successfully retrieve same goes with rooms and room_history.
Here is my query for joining all three tables.

"SELECT users.*,rooms.room_id,rooms.room_name,rooms.type,room_history.start_date,room_history.end_date FROM users " +
                "LEFT JOIN room_history ON room_history.user_id= users.user_id " +
                "LEFT JOIN rooms ON room_history.room_id = rooms.room_id";

Using above query following error occurs.

syntax error (missing operator) in query expression 'room_history.user_id = users.user_id LEFT JOIN rooms on room_history.room_id = rooms.room_i'

I check/change my database tables name, compact the database.