Q: Inconsistent date between SSAS Cube and Tabular Model I have a very weird problem. I have built a tabular model which takes data from a SSAS cube. In the data source cube, there is a column called "Process Date" and it is in UK date format (dd/mm/yyyy). When I bring this column into my model, the dates are messed up, where the date and month values are swapped for some dates!
Below are the images to illustrate this and I have highlighted one particular date in red. In the data source SSAS cube, the date is 12/02/2019, and when it goes to the tabular model, this date beomces 02/12/2019. I have added a check_month column in the tabular model and found that the tabular model thinks its December i.e. the day/month has been swapped!
data source date
model date
Thank you
JC
Edit: This has been solved by changing the Locale Identifier in the connection. See the comment in the answer below by userfl89. This is due to the data source cube is using a different locale (US English) then what I am using in the model, changing the locale identifier will override this and hence solve the problem

A: The date format can be defined from SSDT.  Highlight the date column and go to the properties window (press F4).  For the Data Format property select the desired date format.  If you need a date format that's not listed a calculated column using the FORMAT function can be created based off the original column, with the data type of this column then set to Date.  An example of this is below.  Additionally, confirm the Locale Identifier (LCID) in SSDT.  This can by viewed by selecting Model > Existing Connections > Edit > Build > All > then the Locale Identifier property.  The Microsoft documentation provides details in regards to identifying the correct LCID.
=FORMAT('Process'[Process Date], "dd-MM-yyyy")


Q: How to properly consume a WCF Web Service in a Classic Xamarin Solution? I'm following the documentation on Consuming a WCF Web Service and need clarification on how best to do this in a Classic Xamarin (not Xamarin Forms) solution that uses a .NET Standard library.
Specifically, I need to understand whether separate API calls must be wrapped in the interface class e.g. ISoapService so that they can be made asynchronously?  The project already as an auto-generated Reference.cs class that documents all the available web service endpoints.  Does the interface class need to include all potential API calls?
How do ensure that my interface class is properly referenced from the Xamarin.Android and Xamarin.IOS projects?  Is there something specifically required aside from referencing the .NET Standard Project from the mobile projects?
I've looked high and low for WCF web service integration with Classic Xamarin but have not found any helpful samples Any links would be helpful.


Q: Thread scheduling in .NET regarding blocking calls Suppose I spawn 3 threads in a C# application: T1, T2 and T3 and issue Run calls for each.
Usually, the processor will schedule the threads in a round-robin fashion (single processor and all threads have same priority).
However, suppose Thread T1 issues a Blocking web service call.
Will it be preempted immediately or after completion of its time slice?
Basically does issuing the web service network call (or any other call) cause the thread to be in a blocked state?

A: Once a thread issues a blocking system call (any request to IO) it is suspended, and only marked as "Ready" (not yet running) when that system call completes.
So yes it will be preempted immediately.


Q: Force login for a subdirectory within wordpress install I am using a simple force login plugin that works great "Force Login
By Kevin Vess".
I have a subfolder (right now in /wp-content/subdir/") that i want to also force login for but cant figure how.
Is there a way to accomplish this?

A: This was easier than i thought
<body>

<?php

chdir( '../' );
include 'wp-load.php';

if ( is_user_logged_in() ) :  ?>

// Do stuff

<?php endif; ?>


Q: android : LayoutInflater in static method i want to call LayoutInflater from static method as below :
    private static void inflateLayout_keluarga_pp(int counter2, String name) {
            LayoutInflater inflater = (LayoutInflater)getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rowView = inflater.inflate(R.layout.layoutkeluarga, null);
..................
..................
}

this is how i call method inflateLayout_keluarga_pp :
    public static void onRetrieve(int position){
    List<ModelKeluargaPP> mk = helper.getSelectTable_Marital();
        for (int i=0; i<mk.size();i++){
        inflateLayout_keluarga_pp(i,mk.get(position).getAnggota_pp());

  }
}

but i got error in getActivity(), they said : Cannot make a static reference to the non-static method getActivity() from the type Fragment i need to make this method into static. how to fix it? i hope someone can help to solve my problem, thank you.

A: getActivity() belongs to the instance of the current Fragment; it cannot be part of a static context.
When you declare a method static, you are stating that this method will not belong to each particular instance of the Class; it belongs to the Class itself. Since the static method will be available regardless if you instantiate an object of the Class, you cannot guarantee that object members and methods (that are not static) will be available. Hence you cannot reference "things" that will be available only when the object is instantiated inside a static method that will always be available.
Like Jems said, if you need to access the Fragment you need to always make it available within the method's scope. This can be accomplished by either passing a Fragment to the static method or by instantiating it inside the static method.

A: If it must be static, pass a reference to the Fragment you want to call getActivity on into the method.
private static void inflateLayout_keluarga_pp(int counter2, String name, Fragment myFragment) {
            LayoutInflater inflater = (LayoutInflater)myFragment.getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);


Q: Create a Mobile Responsive Version of a PowerBI report that is Published to the Web I've recently published a specific PowerBI report and despite creating a 'Phone' View on PowerBI Desktop this didn't show up in the final embed code.
I've looked into PowerBI Embedded Playground and managed to generate the relevant access tokens and even try it out, but still couldn't figure out how to modify the code in such a way to generate a mobile view.
The questions and answers below somehow didn't give me the insight I needed, still somehow need some additional work:
Mobile view is not being shown for embedded powerbi report
Create Report in Embed View via PowerBI API
Power BI RS web embedding in mobile web browser
What do I need to do to get started? Which documentation do I need to look into exactly? I need to embed this report in a Sharepoint 2010 Page and I need it to be mobile responsive on page load and not via a seperate link.

A: This isn't related to the access token in any way. It is generated before configuring the embedding process. To embed the report in phone view, you must specify MobilePortrait layout type in the embed configuration, i.e. something like this:
var config = {
    .....
    settings: {
        filterPaneEnabled: true,
        navContentPaneEnabled: true,
        layoutType: models.LayoutType.MobilePortrait <-- THIS ONE
    }
};

If you omit layoutType, it will be shown in the landscape view (i.e. like in the desktop). For more information about the configuration see Embed Configuration Details, and for embedding in general you should start from Embedding Basics.


Q: Replace NULL with SUBTOTAL and TOTAL in a ROLLUP I have tried to use IFNULL to replace the NULL fields returned by ROLLUP for subtotals and totals but it doesn't appear to be working.
Query:
select IFNULL(usergroups.name, 'GROUP') AS DEALER,
IFNULL(users.name, 'TOTAL') AS SERVICE_ADVISOR,
COUNT(DISTINCT vcrs.uid) AS COMPLETED,
..........
..........
and vcrs.vcrSubStatus = 4
group by DEALER, SERVICE_ADVISOR with ROLLUP;

Output:
DEALER          SERVICE_ADVISOR COMPLETED   IDENTIFIED  AUTHORISED
Aston Martin    Chris           3           664.56      0
Aston Martin    Graham          6           0           0
Aston Martin    (NULL)          15          664.56      0
Bentley         Sukraj          1           0           0
Bentley         Terry           4           0           0
Bentley         (NULL)          5           0           0
Jaguar          Emma            10          2448        1224
Jaguar          Paul            1           0           0
Jaguar          Simon           7           2754        918
Jaguar          (NULL)          18          5202        2142
(NULL)          (NULL)          2611        96591.62    42130.14

Desired Output:
DEALER          SERVICE_ADVISOR COMPLETED   IDENTIFIED  AUTHORISED
Aston Martin    Chris           3           664.56      0
Aston Martin    Graham          6           0           0
Aston Martin    TOTAL           15          664.56      0
Bentley         Sukraj          1           0           0
Bentley         Terry           4           0           0
Bentley         TOTAL           5           0           0
Jaguar          Emma            10          2448        1224
Jaguar          Paul            1           0           0
Jaguar          Simon           7           2754        918
Jaguar          TOTAL           18          5202        2142
GROUP           TOTAL           2611        96591.62    42130.14

A: To resolve the issue with COALESCE/IFNULL still returning NULL for the WITH ROLLUP placeholders, you need to GROUP BY the table column names, rather than the aliased column expressions.
The issue is caused by the GROUP BY clause being specified on the aliased column expressions, because the aliases are assigned after the column expression is processed.
Resulting in the WITH ROLLUP NULL placeholders not being in the recordset to be evaluated by COALESCE.
Meaning the aliases DEALER, SERVICE_ADVISOR in the GROUP BY do not exist until after IFNULL/COALESCE have already been executed.
See MySQL Handling of GROUP BY for more details.
Example DB-Fiddle
CREATE TABLE foo (
  `amount` INTEGER,
  `created` INTEGER
);

INSERT INTO foo
  (`amount`, `created`)
VALUES
  ('1', '2019'),
  ('2', '2019');

Query #1 (Reproduce Issue)
SELECT
    SUM(amount) AS amounts,
    COALESCE(created, 'Total') AS created_coalesce
FROM foo
GROUP BY created_coalesce WITH ROLLUP;

| amounts | created_coalesce |
| ------- | ---------------- |
| 3       | 2019             |
| 3       |                  |

Query #2 (Corrected)
SELECT
    SUM(amount) AS amounts,
    COALESCE(created, 'Total') AS created_coalesce
FROM foo
GROUP BY foo.created WITH ROLLUP;

| amounts | created_coalesce |
| ------- | ---------------- |
| 3       | 2019             |
| 3       | Total            |

Use-Case Specific
Example DB-Fiddle
SELECT
    COALESCE(usergroups.name, 'GROUP') AS DEALER,
    COALESCE(users.name, 'TOTAL') AS SERVICE_ADVISOR,
    COUNT(DISTINCT vcrs.uid) AS COMPLETED,
/* ... */
GROUP BY usergroups.name, users.name WITH ROLLUP;

Query #1 (Original)
SELECT
    COALESCE(usergroups.name, 'GROUP') AS DEALER,
    COALESCE(users.name, 'TOTAL') AS SERVICE_ADVISOR,
    COUNT(DISTINCT vcrs.uid) AS COMPLETED
/* ... */
GROUP BY DEALER, SERVICE_ADVISOR WITH ROLLUP;

| DEALER | SERVICE_ADVISOR | COMPLETED |
| ------ | --------------- | --------- |
| Foo    | Jane Doe        | 1         |
| Foo    | John Doe        | 1         |
| Foo    |                 | 2         |
|        |                 | 2         |

Query #2 (Corrected)
SELECT
    COALESCE(usergroups.name, 'GROUP') AS DEALER,
    COALESCE(users.name, 'TOTAL') AS SERVICE_ADVISOR,
    COUNT(DISTINCT vcrs.uid) AS COMPLETED
/* ... */
GROUP BY usergroups.name, users.name WITH ROLLUP;

| DEALER | SERVICE_ADVISOR | COMPLETED |
| ------ | --------------- | --------- |
| Foo    | Jane Doe        | 1         |
| Foo    | John Doe        | 1         |
| Foo    | TOTAL           | 2         |
| GROUP  | TOTAL           | 2         |

Considerations

*

*

With MySQL 5.7+ and ONLY_FULL_GROUP_BY enabled, selected
non-aggregate columns that are not specified in the GROUP BY clause
will fail.  Meaning the following query will not work as expected: DB-Fiddle
SELECT COALESCE(YEAR(foo), 'foo') /* ... */ GROUP BY YEAR(foo) WITH ROLLUP
-> ER_WRONG_FIELD_WITH_GROUP: Expression #2 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'test.foo_bar.foo' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by

*

COALESCE,
IFNULL,
IF(... IS NULL)
and CASE WHEN ... IS NULL
will all function
similarly. Where IFNULL is the proprietary to MySQL and is a less
functional replacement of COALESCE. As COALESCE can accept more
than two parameters to check against NULL, returning the first non-NULL value.
mysql> SELECT COALESCE(NULL, NULL, 1, NULL);
       -> 1

mysql> SELECT IFNULL(NULL, 1);
       -> 1

mysql> SELECT IF(NULL IS NULL, 1, '');
       -> 1

mysql> SELECT CASE WHEN NULL IS NULL THEN 1 END;
       -> 1

*

nullable columns in the GROUP BY as either aliases or column names, will result in the NULL values being
displayed as the WITH ROLLUP placeholder. This applies to using WITH ROLLUP in general. For example if
users.name can return NULL. DB-Fiddle
| DEALER | SERVICE_ADVISOR | COMPLETED |
| ------ | --------------- | --------- |
| Foo    | TOTAL           | 1         |
| Foo    | Jane Doe        | 1         |
| Foo    | John Doe        | 1         |
| Foo    | TOTAL           | 3         |
| GROUP  | TOTAL           | 3         |

Prevent NULL column values from being displayed
To ensure that nullable columns are not accidentally included, you would need to specify in the criteria to exclude them.
Example DB-Fiddle
SELECT
    COALESCE(usergroups.name, 'GROUP') AS DEALER,
    COALESCE(users.name, 'TOTAL') AS SERVICE_ADVISOR,
    COUNT(DISTINCT vcrs.uid) AS COMPLETED
FROM vcrs
LEFT JOIN users
ON users.id = vcrs.uid
LEFT JOIN usergroups
ON usergroups.id = users.group_id
WHERE vcrs.vcrSubStatus = 4
AND users.name IS NOT NULL
GROUP BY usergroups.name, users.name
WITH ROLLUP;

Result
| DEALER | SERVICE_ADVISOR | COMPLETED |
| ------ | --------------- | --------- |
| Foo    | Jane Doe        | 1         |
| Foo    | John Doe        | 1         |
| Foo    | TOTAL           | 2         |
| GROUP  | TOTAL           | 2         |

Since LEFT JOIN is used on the vcrs table, IS NOT NULL must be
applied to the WHERE clause, instead of the ON clause. As LEFT JOIN returns NULL for non-matching criteria. To circumvent the
issue, use an INNER JOIN to limit the resultset to only those with
matching ON criteria.

/* ... */
INNER JOIN users
ON users.id = vcrs.uid
AND users.name IS NOT NULL
/* ... */
WHERE vcrs.vcrSubStatus = 4
GROUP BY usergroups.name, users.name
WITH ROLLUP;

Include NULL columns values
To explicitly include nullable column values, without duplicating the WITH ROLLUP placeholder name, you would need to utilize a derived table subquery to substitute the NULL value as a textual value.
Example DB-Fiddle
SELECT
    COALESCE(v.usergroup_name, 'GROUP') AS DEALER,
    COALESCE(v.user_name, 'TOTAL') AS SERVICE_ADVISOR,
    COUNT(DISTINCT v.uid) AS COMPLETED
FROM (
  SELECT
      usergroups.name AS usergroup_name,
      COALESCE(users.name, 'NULL') AS user_name,
      vcrs.uid
  FROM vcrs
  LEFT JOIN users
  ON users.id = vcrs.uid
  LEFT JOIN usergroups
  ON usergroups.id = users.group_id
  WHERE vcrs.vcrSubStatus = 4
) AS v
GROUP BY v.usergroup_name, v.user_name
WITH ROLLUP;

Result
| DEALER | SERVICE_ADVISOR | COMPLETED |
| ------ | --------------- | --------- |
| Foo    | Jane Doe        | 1         |
| Foo    | John Doe        | 1         |
| Foo    | NULL            | 1         |
| Foo    | TOTAL           | 3         |
| GROUP  | TOTAL           | 3         |

You can also optionally replace the 'NULL' textual placeholder as desired and even display it as NULL.
SELECT
    COALESCE(v.usergroup_name, 'GROUP') AS DEALER,
    CASE v.user_name WHEN 'NULL' THEN NULL ELSE COALESCE(v.user_name, 'TOTAL') END AS SERVICE_ADVISOR,
    COUNT(DISTINCT v.uid) AS COMPLETED
FROM (
    /* ... */
) AS v
GROUP BY v.usergroup_name, v.user_name
WITH ROLLUP;

A: I'm only 2 years too late, but since I came across the same issue as @the_gimlet I thought I'd post the answer.
So don't know if this is a mySQL versioning or something, but using mysql 5.6 I get the same problem... ifnull will not replace the rollup 'nulls'.
Simply get around this by making your rollup a subquery, and doing the ifnulls in the main select... annoying to repeat the select, but it works!
e.g. for example above
SELECT
  IFNULL(`DEALER`, 'GROUP') AS DEALER,
  IFNULL(`SERVICE_ADVISOR`, 'TOTAL') AS SERVICE_ADVISOR,
  `COMPLETED`,
  /* .......... */
FROM (SELECT
        usergroups.name AS DEALER,
        users.name AS SERVICE_ADVISOR,
        COUNT(DISTINCT vcrs.uid) AS COMPLETED,
      /* .......... */
      AND       vcrs.vcrSubStatus = 4
      GROUP BY  DEALER, SERVICE_ADVISOR with ROLLUP);

A: Do you want something like this?
SELECT COALESCE(usergroups.name, 'GROUP') AS DEALER,
COALESCE(users.name, IF(usergroups.name IS NULL, 'TOTAL', 'SUBTOTAL')) AS SERVICE_ADVISOR,
COUNT(DISTINCT vcrs.uid) AS COMPLETED,
..........
..........
AND vcrs.vcrSubStatus = 4
GROUP BY DEALER, SERVICE_ADVISOR with ROLLUP;

Test:
mysql;root@localhost(playground)> select * from t;
+------+----------+-------+--------+
| id   | car      | state | tstamp |
+------+----------+-------+--------+
|    1 | toyota   | new   |   1900 |
|    2 | toyota   | old   |   1950 |
|    3 | toyota   | scrap |   1980 |
|    4 | mercedes | new   |   1990 |
|    5 | mercedes | old   |   2010 |
|    6 | tesla    | new   |   2013 |
+------+----------+-------+--------+
6 rows in set (0.04 sec)

mysql;root@localhost(playground)> select car, sum(tstamp) from t group by car with rollup;
+----------+-------------+
| car      | sum(tstamp) |
+----------+-------------+
| mercedes |        4000 |
| tesla    |        2013 |
| toyota   |        5830 |
| NULL     |       11843 |
+----------+-------------+
4 rows in set (0.03 sec)

mysql;root@localhost(playground)> select coalesce(car, 'huhu'), sum(tstamp) from t group by car with rollup;
+-----------------------+-------------+
| coalesce(car, 'huhu') | sum(tstamp) |
+-----------------------+-------------+
| mercedes              |        4000 |
| tesla                 |        2013 |
| toyota                |        5830 |
| huhu                  |       11843 |
+-----------------------+-------------+
4 rows in set (0.00 sec)

A: What you're looking for is a case statement.
What you're saying is that under a certain condition replace the found value with the one specified. You can use multiple when/then statements depending on how customised you'd like the replacements to be.
select IFNULL(usergroups.name, 'GROUP') AS DEALER,
case when(users.name is null) then 'TOTAL' else users.name end AS SERVICE_ADVISOR,
COUNT(DISTINCT vcrs.uid) AS COMPLETED,
..........
..........
and vcrs.vcrSubStatus = 4
group by DEALER, SERVICE_ADVISOR with ROLLUP;


Q: Laravel: One relation, multiple models I have a model "User", and each user has "Posts". Now there are different types of posts, like "TextPost", "VideoPost", etc.
I want to get all posts of a user like this:
$user->posts()->get()
This should return an array of objects with the correct class, so e.g. an array like this:
[App\VideoPost{}, App\TextPost{}]
I tried to use polymorphic relationships as described in the docs, but it doesn't work. Any ideas?

A: There isn't really a relationship type in Laravel for your specific use case. The easiest thing you can do in this case is create a separate hasMany relationship for each of your post types, and then write a function that returns a combination of all the results.
So you'd end up with something like this in your User class:
public function videoPosts()
{
  return $this->hasMany(App\VideoPost::class);
}

public function textPosts()
{
  return $this->hasMany(App\TextPost::class);
}

public function getPosts()
{
  return $this->textPosts->concat($this->videoPosts);
}

You can then just keep chaining concat calls for every other post type you may want to add.


Q: OpenXML excel sheet creation. Formula does not work automatically when I use Indirect to reference a list I am creating an excel template using OpenXML through c# for users to populate and import into our system.
Part of the process is for the user to select options from dropdowns and hidden columns are populated with the Id's of those selections using VLOOKUP formula. All of the ones with direct list references work fine.
I have one instance where the selection from a list called "Application Group" drives what list is used in the next column called "Application". This is done using the INDIRECT function in excel and works fine. The problem comes when trying to get the id for the dynamic list. I will post the code below but put simply opening the excel and selecting an option from application group correctly puts the correct list in Application. Selecting application does not populate the applicationid column automatically. If I select the applicationid column to see the formula is is fine. If I click into the edit box at the top of excel and then tab out of it the formula then triggers and will work from then on. Once again this is a VLOOKUP using the INDIRECT to creat the reference to the list.
I've done a few tests and it seems the INDIRECT is the issue as if I hard code the list name the vlookup triggers as it should.
I also removed the substitute functions but this did not make any difference.
I've checked the calculation mode on the column and it is set to automatic.
I've already searched online but found nothing relevant
                // Application Group
                cell = new Cell() { CellReference = "AI" + rownumber };
                cell.CellValue = new CellValue();
                cellFormula = new CellFormula()
                {
                    Text = "VLOOKUP(AH" + rownumber.ToString() + " ,ApplicationGroupList,2,FALSE)"
                };
                cell.CellFormula = cellFormula;
                row.Append(cell);

                // Application
                cell = new Cell() { CellReference = "AK" + rownumber };
                cell.CellValue = new CellValue();
                cellFormula = new CellFormula()
                {
                    Text = "VLOOKUP(AJ" + rownumber.ToString() + ",INDIRECT(SUBSTITUTE(SUBSTITUTE(AH" + rownumber.ToString() + ",\" \",\"\"),\"/\",\"\") & \"Id\") ,2,FALSE)"
                };
                cell.CellFormula = cellFormula;
                row.Append(cell);

There are no error messages and the formula is correct as simply clicking in the edit box triggers the formula and it works from then on. It seems like excel is not recognising it as a formula even though it was set up in the same way as others that work fine. See the code above. Application group works fine. Application doesn't but the formula created is fine syntactically and functionally.
Does anyone have any experience of something similar and how to get the formula to work as all the others do.

A: Ok well as seems often to be the case I've spent ages looking at this myself. Exhausted all the options, or so I thought. Just after I post this I think I'll just try this thing I've not had to do for any of the other formula just in case. Bingo!
So I had to add
cellFormula.CalculateCell = true;
And this seemed to solve the problem. Why I needed it I don't know as everything else seems to work without explicitly setting this flag but problem seems to be solved.


Q: Looking for distance history using google API (or other) I've been searching and i thought i could ask you directly in here.
I'm looking for an API (maybe Google) that does the same work as Google fit history API as of recording every distance you made and the transportation mode. It is not necessary for me to get the exact latitude or longitude by at least the number of kilometer/meter(or miles) made by day in cars/foot/run/bike by a user(using an Android App). Google fit History API is great but, if i'm correct, it only records physical activities such as foot/run/bike.
I've look for Google ActivityRecognitionClient API that gives me a way to know the transportation mode and confidence % for a certain time but still, i need to have the distance made with this transportation mode.
What i need is something like :
Date : 2019-04-24
Activity : 1
TransportationMode : Foot
distance : 10km

Date : 2019-04-24
Activity : 2
TransportationMode : car
distance : 100km
etc.

Any of you know a way to do this?

A: I don't know about an API that you can use. However I found a research paper on ML model that predicts travel mode on the basis of GPS information. If you have sufficient time to develop your own AI model you may try this:
AI model Predicting travel mode


Q: F# Type providers and Sky Biometry Has anyone used the F# type providers with Sky Biometry?
A majority of the calls work great with the type providers.  However, when I call the faces/recognize method, I am getting fails using both the Json and the Xml type provider.
Using the Json one, I declare the type like this:
type skybiometryJsonFaceRecognition = JsonProvider<"http://api.skybiometry.com/fc/faces/recognize.json?uids=default@ImageComparer&urls=https://lg2014dev.blob.core.windows.net/d69bdda9-d934-448c-acae-99019f3a564f/01ee184f-ff0b-426f-872a-cbc81ef58d90.jpg&api_key=XXXXX&api_secret=yyyyy">

When I try and use the type in my code, it is failing on the last part of the graph:
let recognition = skybiometryJsonFaceRecognition.Load(stringBuilder.ToString())

It should be:
recognition.Photos.[0].Tags.[0].Uids.[0].confidence

But instead I get:
recognition.Photos.[0].Tags.[0].Uids.[0].JsonValue

I then swapped over to the Xml type provider for just this one call and I am getting intellisense working:
let recognition = skybiometryXmlFaceRecognition.Load(stringBuilder.ToString())
recognition.Photos.Photo.Tags.Tag.Uids.Uid.Confidence

But when I run it, I get
System.Xml.XmlException: Data at the root level is invalid. Line 1, position 1.
Looking at the XML in a call from my browser, it sure looks fine to me:

Does anyone have any suggestions?  Thanks

A: Thanks to ntr's suggestion, I changed the type def to use local storage.  The Json TP then found all of the props and the actual call worked as expected.  Thanks everyone.


Q: How to do WHERE IN with sqlalchemy? Here is what I'm trying to do. The database is Postgres.
numbers is a Python set() or some other iterable.
session.execute(table.update().\
                        where(func.substring(table.c.number,1 ,5) in numbers).\
                        values(provider="testprovider")

The problem with this is that in numbers doesn't seem to work. It will work for a single number if I do something like where(func.substring(table.c.number,1, 5)== '12345')
I've googled a lot on how to do WHERE IN with sqlalchemy, but all of them are with a SELECT query or do use the .in_() function on the column itself. For example this answer: link
The documentation also says the .in_() only works on the columns.
So, I don't really know how to proceed here. How can I write this expression?

A: Ah nevermind, although the documentation doesn't say it, I can use the .in_() function on the result of func.substring.
So
where(func.substring(table.c.number, 1, 5).in_(numbers))

worked.


Q: JPA 2: mapping a map where the key is an entity, value is Boolean We are trying to map a relation where an entity has a map where the key is another entity and the value is a Boolean:
    @Id Long id;
    @ElementCollection
    @CollectionTable(name = "APPROVALS_PRODUCT_APPROVALS", joinColumns = @JoinColumn(name = "PRODUCT_APPROVAL_ID", referencedColumnName = "ID"))
    @Column(name = "EXCLUDED")
    private Map<Approval, Boolean> approvals = new HashMap<Approval, Boolean>();

For some reason, Eclipselink gives a BigDecimal for each value in the map, instead of Boolean.
approvals.get(testApproval); // returns a BigDecimal :-(

Is there anything that doesn't look right? Is this us, or is this a bug in Eclipselink?
EDIT:
Tried this (Approval has 2 @Id fields):
    @ElementCollection
    @CollectionTable(name = "APPROVALS_PRODUCT_APPROVALS", joinColumns = @JoinColumn(name = "PRODUCT_APPROVAL_ID", referencedColumnName = "ID"))
    @Column(name = "EXCLUDED")
    @MapKeyJoinColumns({ @MapKeyJoinColumn(name = "CREDENTIAL_VALUE", referencedColumnName = "CREDENTIAL_VALUE"), @MapKeyJoinColumn(name = "CREDENTIAL_TYPE", referencedColumnName = "CREDENTIAL_TYPE") })
    private Map<Approval, Boolean> approvals = new HashMap<Approval, Boolean>();

and got the same result (BigDecimal instead of Boolean)
EDIT2:
We are using Eclipselink 2.3.0, also tried with 2.3.2 with same result.

A: Your code is wrong,
targetClass on ElementCollection is for specifying an Embeddable class (if generics are not used), so should be not used.
You also need a @MapKeyJoinColumn if you want the Map key to be another object (or @MapKeyClass if it is an Embeddable.
Most databases do not have a Boolean type, so booleans are normally stored as numbers, 0/1.  So you may be missing a conversion somehow.  You can define an @Convert with a @TypeConverter for this, although it should be getting defaulted, so you may log a bug for that.


Q: I'm getting java.lang.IllegalStateException: sequencer not open. What's the solution? This is the code I'm trying to run but I keep getting IllegalStateException. I'm relatively new to java and I need some help figuring this out. Thanks:)
This is the code:
import javax.sound.midi.*;

public class MiniMusicApp {
    public static void main(String[] args){
        MiniMusicApp mini = new MiniMusicApp();
        mini.play();
    }//Close main

    public void play(){
        try{
            Sequencer player = MidiSystem.getSequencer();
            Sequence seq = new Sequence(Sequence.PPQ, 4);
            Track track = seq.createTrack();

            ShortMessage b = new ShortMessage();
            b.setMessage(128, 1, 44, 100);
            MidiEvent noteOff = new MidiEvent(b, 16);
            track.add(noteOff);

            player.setSequence(seq);
            player.start();
        }catch(Exception ex){
            ex.printStackTrace();
        }
    }//close play
}//close class

And I'm getting this:
java.lang.IllegalStateException: sequencer not open
    at java.desktop/com.sun.media.sound.RealTimeSequencer.start(RealTimeSequencer.java:232)
    at MiniMusicApp.play(MiniMusicApp.java:21)
    at MiniMusicApp.main(MiniMusicApp.java:6)
    at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:104)
    at java.base/java.lang.reflect.Method.invoke(Method.java:577)
    at jdk.compiler/com.sun.tools.javac.launcher.Main.execute(Main.java:421)
    at jdk.compiler/com.sun.tools.javac.launcher.Main.run(Main.java:192)
    at jdk.compiler/com.sun.tools.javac.launcher.Main.main(Main.java:132)

A: For demonstration only, don't do this
As @Abra said, you need to call the open method:
import javax.sound.midi.*;

public class MiniMusicApp {
    public static void main(String[] args){
        MiniMusicApp mini = new MiniMusicApp();
        mini.play();
    }//Close main

    public void play(){
        try{
            Sequencer player = MidiSystem.getSequencer();
            player.open();
            Sequence seq = new Sequence(Sequence.PPQ, 4);
            Track track = seq.createTrack();

            ShortMessage b = new ShortMessage();
            b.setMessage(128, 1, 44, 100);
            MidiEvent noteOff = new MidiEvent(b, 16);
            track.add(noteOff);

            player.setSequence(seq);
            player.start();
        }catch(Exception ex){
            ex.printStackTrace();
        }
    }//close play
}//close class

However you should also close it at the end:
import javax.sound.midi.*;

public class MiniMusicApp {
    public static void main(String[] args){
        MiniMusicApp mini = new MiniMusicApp();
        mini.play();
    }//Close main

    public void play(){
        Sequencer player = null;
        try{
            player = MidiSystem.getSequencer();
            player.open();
            Sequence seq = new Sequence(Sequence.PPQ, 4);
            Track track = seq.createTrack();

            ShortMessage b = new ShortMessage();
            b.setMessage(128, 1, 44, 100);
            MidiEvent noteOff = new MidiEvent(b, 16);
            track.add(noteOff);

            player.setSequence(seq);
            player.start();
        }catch(Exception ex){
            ex.printStackTrace();
        }
        finally {if(player!=null) player.close();}
    }//close play
}//close class

The correct way
But this way is error prone, so in modern Java you should use try-with-resource to close it automatically:
import javax.sound.midi.*;

public class MiniMusicApp {
    public static void main(String[] args){
        MiniMusicApp mini = new MiniMusicApp();
        mini.play();
    }//Close main

    public void play(){
        Sequencer debug = null; // just for demonstrating that it is really closed at the end
        try(Sequencer player = MidiSystem.getSequencer())
        {
            debug = player;
            player.open();
            Sequence seq = new Sequence(Sequence.PPQ, 4);
            Track track = seq.createTrack();

            ShortMessage b = new ShortMessage();
            b.setMessage(128, 1, 44, 100);
            MidiEvent noteOff = new MidiEvent(b, 16);
            track.add(noteOff);

            player.setSequence(seq);
            player.start();
        }catch(Exception ex){
            ex.printStackTrace();
        }
        System.out.println(debug.isOpen());
    }//close play
}//close class

A: You forgot to open the Sequencer, which is why you got an exception. To open the player
Sequencer player = MidiSystem.getSequencer();
player.open();


Q: Diff: ignoring lines with just tabs I'm trying to diff files, and determine if they are the same, but ignoring ALL whitespace.
When using diff, the -b tells diff to ignore whitespace on a given line.  The -B option tells it to ignore all blank lines.  But, if you have a line which contains only spaces, the -B and -b don't seem to work together.
I've resorted to using the -I option, where I want diff to ignore all lines which only contain whitespaces, which works fine when the line contains only spaces, but the \t doesn't seem to match tab characters.
I found one reference online that mentioned that you need to use POSIX regexp, but POSIX states that :blank: will match any whitespace (including tab).  That does not work either.
Here's a sample of what I'm trying to do.  Ideally, my diff line would state that t1.txt, t2.txt and t3.txt were all the same.
bash#> echo hi > t1.txt
bash#> echo hi > t2.txt
bash#> echo hi > t3.txt
bash#> echo " " >> t2.txt
bash#> echo -e "\t" >> t3.txt
bash#> diff -BbaNq -I "^[ \t]*$" t1.txt t2.txt
bash#> diff -BbaNq -I "^[ \t]*$" t1.txt t3.txt
Files t1.txt and t3.txt differ
bash#> diff -BbaNq -I "^[:blank:]*$" t1.txt t3.txt
Files t1.txt and t3.txt differ
bash#>

Any help in what the syntax for diff would be would be very helpful.

A: try this:
diff -wBt -u t1.txt t2.txt


Q: Google Maps Marker Clusterer: markers never cluster I don't know why the marker clusterer don't show my markers grouped, like here: http://media.svennerberg.com/2009/01/screenshot_clusterereffect.jpg
I am facing a problem in Google map marker clustering. I am using api v3, but due to some reasons, which I am not able to figure out, I cannot apply marker clustering. I'd be thankful for any help and suggestions.
My Code is like this:

<!DOCTYPE HTML>

  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <meta charset="utf-8"/>
  <meta http-equiv="X-UA-Compatible" content="IE=edge"/>

Map:

A: Looking at the example in the documentation and your code, probably the simplest "fix" is to instantiate the marker clusterer inside your display markers routine, then add each marker to the clusterer as it is created:
Comments:

*

*you have have a callback specified in you script include (&callback=myMap), but no function of that name (just remove that from your script include).  Causes this error in the console:

"myMap is not a function"

*There is a javascript error Uncaught ReferenceError: marker is not defined on this line: var markerCluster = new MarkerClusterer(map, marker, because there is no variable marker available in that scope (and as @MrUpsidown observed in his comment, that should be the array of markers).  To address that I suggest using the MarkerClusterer.addMarker method to add markers to it in displayMarkers, and changing your createMarker function to return the marker it creates.

  function displayMarkers() {
    // marker clusterer to manage the markers.
    var markerCluster = new MarkerClusterer(map, [], {
      imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'
    });
    var bounds = new google.maps.LatLngBounds();
    for (var i = 0; i < markersData.length; i++) {
      var latlng = new google.maps.LatLng(markersData[i].lat, markersData[i].lng);
      var name = markersData[i].name;
      var address1 = markersData[i].address1;
      var address2 = markersData[i].address2;
      var address3 = markersData[i].address3;
      var address4 = markersData[i].address4;
      var image = markersData[i].ikona;
      var wwwsite = markersData[i].wwwsite;

      markerCluster.addMarker(createMarker(latlng, name, address1, address2, address3, address4, image, wwwsite));
      bounds.extend(latlng);
    }
    map.fitBounds(bounds);
  }

  function createMarker(latlng, name, address1, address2, address3, address4, image, wwwsite) {
    var marker = new google.maps.Marker({
      map: map,
      position: latlng,
      title: name,
      icon: image
    });
    google.maps.event.addListener(marker, 'click', function() {
      var iwContent = '
' +
        '
' + name + '
' +
        '
' + address1 + '
' +
        address2 + '
' + address3 + '
' + address4 + '
' +
        wwwsite + '

';
      infoWindow.setContent(iwContent);
      infoWindow.open(map, marker);
    });
    return marker;
  }

proof of concept fiddle

code snippet:

html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}

Map:


Q: How to call methods from other class?
I am trying to write a Java program to book hotel rooms. I have written methods in one class and am trying to call it from my main class, but I don't know how to do it.
The program asks the user to input necessary info for the methods, but I just don't know how to execute it.
I also want to know how to change the status of a room to "B" - for booked, when the user enters the RoomId and confirms their booking and then to print the information using the print() method in Room.java. Any help would be great. Thanks
Room.java
package utilities;

public class Room
{

 private String roomId;
 private String description;
 private String status;
 private double dailyRate;
 private DateTime bookingStartDate;
 private DateTime bookingEndDate;

 public Room(String roomId, String description, double dailyRate)
 {
  this.setRoomId(roomId);
  this.setDescription(description);
  this.setDailyRate(dailyRate);
  this.status = "A";
 }

 public boolean bookRoom (String customerID, int nightsRequired)
 {
     if (status.equals('A'))
     {
         System.out.println("You have booked the room");
         status = "B";
         return true;
     }
     else
     {
         System.out.println("This room cannot be booked");
         return false;
     }
 }

 public void print()
 {
     System.out.println("Room ID: " + getRoomId());
     System.out.println("Description: "+ getDescription());
     System.out.println("Status: " + status);
     System.out.println("Daily Rate: " + getDailyRate());
     if (status.equals('B'))
     {
         System.out.println(bookingStartDate);
         System.out.println(bookingEndDate);
     }
     else{
     }

 }

/**
 * @return the dailyRate
 */
public double getDailyRate() {
    return dailyRate;
}

/**
 * @param dailyRate the dailyRate to set
 */
public void setDailyRate(double dailyRate) {
    this.dailyRate = dailyRate;
}

/**
 * @return the description
 */
public String getDescription() {
    return description;
}

/**
 * @param description the description to set
 */
public void setDescription(String description) {
    this.description = description;
}

/**
 * @return the roomId
 */
public String getRoomId() {
    return roomId;
}

/**
 * @param roomId the roomId to set
 */
}

TestRoom.java
package stuff;

import java.util.Scanner;

import utilities.Room;

public class TestRoom {

 public static void main(String[] args)
 {
     Room [] rooms =
          {
            new Room("GARDEN0001", "NorthWest Garden View", 45.00),
            new Room("GARDEN0002", "SouthEast Garden View", 65.0),
            new Room("GARDEN0003", "North Garden View", 35.00),
            new Room("GARDEN0004", "South Garden View", 52.0),
            new Room("GARDEN0005", "West Garden View", 35.00),
            new Room("GARDEN0006", "East Garden View", 35.00)

          };
  Scanner userInput = new Scanner(System.in);

  System.out.println("Input a lower price range. ");
  int lower = userInput.nextInt();

  System.out.println("Input an upper price range. ");
  int upper = userInput.nextInt();

  if (lower < 65)
  {
      for ( int i = 0; i < rooms.length; i++ )
      {
          if (rooms[i].getDailyRate() > lower && rooms[i].getDailyRate() < upper )
          {
              System.out.println("ID: \t" + rooms[i].getRoomId() );
              System.out.println("DESC: \t" + rooms[i].getDescription() );
              System.out.println("RATE: \t" + rooms[i].getDailyRate() + "\n");
          }
      }
  }
  else
  {
      System.out.println("There are no rooms that fit your criteria.");
  }

  System.out.println("Input the ID of the room you wish to book.");
  String roomId = userInput.next();

  System.out.println("Please enter your customer ID");
  String customerID = userInput.next();

  System.out.println("Please enter the amount of nights you wish to stay.");
  int nightsRequired = userInput.nextInt();

  // Code to actually make the booking. I don't know what goes here.

A: Just get the instance of the Room and call the method.
The hard-coding method will be like this:
Room toBook = null;
for (Room r : rooms) {
    if (r.getRoomId().equals(roomId))
        toBook = r;
}

if (toBook != null) {
    if (toBook.bookRoom(customerID, nightsRequired)) {
         // room booked succesfully
    } else {
         // can't book the room
    }
} else {
    // room does not exists
}

But, as long as this will be a bigger app I recommend you to code your own equals method then Arrays.contains() will find the Room.
Room toBook = new Room(roomid);
if (rooms.contains(toBook) && toBook.bookRoom(customerID, nightsRequired)){
    // room booked succesfully
} else if (rooms.contains(toBook)) {
    // can't book the room
} else {
    // room does not exists
}

A: Add the code at the end of the main() method in Test class
    Room r=null;
    boolean val=false;
    for(int i=0;i<rooms.length;i++){
        if(rooms[i].getRoomId().equals(roomId)){
            r=new Room(rooms[i].getRoomId(), rooms[i].getDescription(), rooms[i].getDailyRate());
            r.bookRoom(customerID, nightsRequired);
            val=true;
            break;
        }
    }
    if(val){
         r.print();
    }


Q: How do I create a proxy object that forwards method calls in c#? I'm trying to use selenium to run tests; seems like there isn't a good way to run the same set of unit tests on multiple browsers.
I read this post about running tests in parallel:
http://slmoloch.blogspot.com/2009/12/design-of-selenium-tests-for-aspnet_19.html
However, I'm using the visual studio unit testing framework.
I can create a proxy class like this:
public class SeleniumProxy {
    private List<DefaultSelenium> targets;
    public SeleniumProxy() {
        targets = new List<DefaultSelenium>();
        targets.Add(new DefaultSelenium(... "firefox"...));
        targets.Add(new DefaultSelenium(... "iexplore"...));
    }
    public void Open(String url) {
        foreach (var i in targets) {
            i.Open(url);
        }
    }
    ...
}

My question is this? How can I do it without having to rewrite the entire class as a proxy?
I thought maybe passing a lamda in to map arguments, or passing by a function that takes the name of the method to invoke, but these all seem like pretty lame ideas.
What I really want is to add a member like:
public class SeleniumProxy {
    public dynamic proxy;
    ....
}

And invoke this like:
var selenium = getProxy();
selenium.proxy.Open("...");

Does c# allow this kind of syntax for dynamic objects?
Or some kind of meta-handler for classes that lets them catch no-such-method exceptions and handle them manually?
Basically:
How can I create a proxy object that dynamically invokes methods on an internal member of the class?
(Edit: perhaps... using reflection on the DefaultSelenium object and creating function stubs on the dynamic proxy object for each entry..?)

A: If I understand what you're attempting, I think you can extend DynamicObject to achieve this.
class Proxy : System.Dynamic.DynamicObject
{
    public Proxy(object someWrappedObject) { ... }

    public override bool TryInvokeMember(System.Dynamic.InvokeMemberBinder binder, object[] args, out object result)
    {
      // Do whatever, binder.Name will be the called method name
    }
}

//Do whatever... would become some code that pokes at some other object's internal members (via reflection, presumably) using binder.Name as part of the lookup process.
There are TryGetMember and TryGetIndex methods to override if you need to wrap up anything fancier that simple method invokes.
You will have to cast instances of Proxy to dynamic after construction to make arbitrary calls, just like when dealing with ExpandoObject.

A: You could leverage inheritance and have your tests defined in an abstract base class with a factory method to create your selenium instance, then inherit this for each type of browser you want to model. The tests will then be run for each inherited class with the appropriate browser. Using NUnit as an example:
public abstract class AbstractTests
{
    protected abstract DefaultSelenium CreateSelenium();

    [Test]
    public void TestSomethingA()
    {
        DefaulSelenium selenium = CreateSelenium();

        //Do some testing with selenium.
    }
}

[TestFixture]
public class IETests : AbstractTests
{
    protected override DefaultSelenium CreateSelenium()
    {
        return new DefaultSelenium("iexplore");
    }
}

[TestFixture]
public class FirefoxTests : AbstractTests
{
    protected override DefaultSelenium CreateSelenium()
    {
        return new DefaultSelenium("firefox");
    }
}


Q: Rails weird result with find and where Can someone point me the reason for following:
JobType.find 17
#=>
#<JobType id: 17, title: "some_title", description: "one description", reward: #    <BigDecimal:1009bbb48,'0.1E1',9(18)>, min_payout: 0.019999999552965164, min_skill_score: 0.6000000238418579, max_payout: 1.0, max_skill_score: 0.9300000071525574, difficulty_level: 2.0, variable_reward: true>
JobType.where(id: 17).first
#=>
#<JobType id: 17, title: "some_title", description: "one description", reward: #<BigDecimal:1009bbb48,'0.1E1',9(18)>, min_payout: 0.02, min_skill_score: 0.6, max_payout: 1.0, max_skill_score: 0.93 difficulty_level: 2.0, variable_reward: true>

In database, The values for min_payout is 0.6, max_skill_score is 0.93, but the find returns that weird long float.
SQL queries logged:
# find
JobType Load (0.5ms)  SELECT `job_types`.* FROM `job_types` WHERE `job_types`.`id` = ? LIMIT [["id", 17]]

# where
JobType Load (0.6ms)  SELECT `job_types`.* FROM `job_types` WHERE `job_types`.`id` = 17

Why is find behaving like that.
I am using rails 3.2.13 and mysql gem.

A: This is due to the use floating point numbers. Floating point numbers involve a binary representation, in which some numbers that can be exactly represented in decimal notation easily are not stored exactly.
For example, 0.6 in decimal is (approximately) 0.111111000110011001100110011010 in binary. When converted back to decimal this number is (approximately) 0.6000000238418579.
Due to this, when you store 0.6 in a float column, the value returned to you will be (slightly) different. The exact value you receive depends on the specific handling that the value has gone through, which may differ depending on a variety of factors.
In order to avoid this, you would be better off using a BigDecimal, and setting the storage type on that column to :decimal.


Q: my cloud front URL redirect to S3 URL my cloud front distribution's origin is my S3 bucket . to access a S3 bucket object we put a url in such as like "cloudfront_domainname/object_name" it should be show the object if the object is public . but in my case the cloud front URL in the URL bar redirects a S3 URL, the data retrieved from S3 not from cloud front distribution. why it cause ?

A: You can optionally secure the content in your Amazon S3 bucket so users can access it through CloudFront but cannot access it directly by using Amazon S3 URLs. This prevents anyone from bypassing CloudFront and using the Amazon S3 URL to get content that you want to restrict access to. This step isn't required to use signed URLs, but we recommend it.
To require that users access your content through CloudFront URLs, you perform the following tasks:

*

*Create a special CloudFront user called an origin access identity.

*Give the origin access identity permission to read the objects in your bucket.

*Remove permission for anyone else to use Amazon S3 URLs to read the objects.

Please see documentation here


Q: C# dependecies aren't being included with publish I'm trying to publish a web API built in .NET Core to a Ubuntu server but am having difficulty with the dependencies. I am new to doing this in C# and haven't found a concise answer to how dependencies are included with the publish command. I was lead to believe that they were complied into a .dll but I am getting this error when running my app
Error:
An assembly specified in the application dependencies manifest (api.deps.json) was not found:
    package: 'Newtonsoft.Json', version: '11.0.2'
    path: 'lib/netstandard2.0/Newtonsoft.Json.dll'

Shouldn't that have been included in the "Release" directory after being published?
I'm using .NET Core on a Mac and then publishing to an Ubuntu sever should that affect anything here.
.csproj:
<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>netcoreapp2.0</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <Folder Include="wwwroot\" />
  </ItemGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.0" />
    <PackageReference Include="Newtonsoft.Json" Version="11.0.2" />
  </ItemGroup>

  <ItemGroup>
    <DotNetCliToolReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="2.0.0" />
  </ItemGroup>

</Project>

A:
Shouldn't that have been included in the "Release" directory after being published?

No.
When you publish a project, you specify a different directory for the publish output when creating the publish profile.

The Release directory is only for assets that are used during debugging. During development, the NuGet dependencies are not in the Release folder, they are in the NuGet cache. So, you cannot always just copy the Release folder and expect it to run.
After publishing, the entire application (including all dependencies) are output to the publish location. Do note that the publish output doesn't necessarily have to be a folder. For example, depending on the type of project it may be published to IIS with web deploy or to an FTP location.


Q: Keep receving segmentation fault when using scanf on an array inside a struct I m kind of new at C and i try to learn data structures by doing exercises. This is the code I've written. I don t understand why it dosen't even enter the for loop.
/*  Define a structure to store the name, an array
marks[] which stores the marks of three different
subjects, and a character grade. Write a program
to display the details of the student whose name
is entered by the user.*/

#include <stdio.h>

int main()
{
    struct stud_info
    {
       char name[20];
       int marks [2][5];
       int char_grade;
    };

    struct stud_info array[20];
    struct stud_info stud1;
    int i,j;
    printf("Enter name of student:\n");
    scanf("%s",stud1.name);
    printf("Enter student char_grade:\n");
    scanf("%d",stud1.char_grade);
    for( i=0;i<=2;i++)
        for( j=0;j<=5;j++)
        {
            printf("Enter grade for [%d]st subject:\n",i);
            scanf("%d",&stud1.marks[i][j]);
        }

    return 0;
}


Q: q.all for angular2 observables is there something like q.all to resolve all http api requests in angular2?
In angular1, I can do something like this:
var promises = [api.getA(),api.getB()];
$q.all(promises).then(function(response){
    // response[0]  --> A
    // response[1]  --> B
})

In angular2, the http module returns Observable,
api.getA().subscribe(A => {A})
api.getB().subscribe(B => {B})

But I want to resolve A and B together, then do something.

A: You will need the .forkJoin operator for that
Observable.forkJoin([observable1,observable2])
       .subscribe((response) => {
          console.log(response[0], response[1]);
       });

You can import the Observable with;
import {Observable} from 'rxjs/Rx';

A: Angular < 6:
import {Observable} from 'rxjs/Observable';
    ...
    return Observable.forkJoin(
        this.http.get('someurl'),
        this.http.get('someotherurl'));

Angular >= 6:
import {forkJoin} from 'rxjs';
...
return forkJoin(
    this.http.get('someurl'),
    this.http.get('someotherurl'));


Q: How to handle jOOQ depreciation warning on procedure that returns a trigger? I use the following stored procedure to maintain the edit time on a few tables via triggers on those tables:
        CREATE OR REPLACE FUNCTION maintain_edit_time()
        RETURNS TRIGGER AS $t_edit_time$
        BEGIN
        NEW.edit_timestamp = NOW();
        RETURN NEW;
        END;
        $t_edit_time$ LANGUAGE plpgsql;

When generating jOOQ objects for the database in question, I get the following generated code:
 /**
 * @deprecated Unknown data type. Please define an explicit {@link org.jooq.Binding} to specify how this type should be handled. Deprecation can be turned off using <deprecationOnUnknownTypes/> in your code generator configuration.
 */
@java.lang.Deprecated
public static Object maintainEditTime(Configuration configuration) {
    MaintainEditTime f = new MaintainEditTime();

    f.execute(configuration);
    return f.getReturnValue();
}

/**
 * @deprecated Unknown data type. Please define an explicit {@link org.jooq.Binding} to specify how this type should be handled. Deprecation can be turned off using <deprecationOnUnknownTypes/> in your code generator configuration.
 */
@java.lang.Deprecated
public static Field<Object> maintainEditTime() {
    MaintainEditTime f = new MaintainEditTime();

    return f.asField();
}

I assume this is because I do not have a jOOQ binding between TRIGGER and a Java object.  However, I do not have a clue what I would define this binding as, nor do I have any need for a binding to exist.
Left alone, though, this generates a compile warning.  What's the cleanest, easiest way to resolve this?
Options seem to include turning off deprecation, using ignoreProcedureReturnValues, or creating a binding.  Ideally, I'd like to simply not generate a Java object for this procedure, but I could not find a way to do that.
Using ignoreProcedureReturnValues globally effects the project just because of this, which is fine for now, I don't have other procedures at all, much less others with a return value.  But, I hate to limit future use.  Also, I'm unclear one what the comment "This feature is deprecated as of jOOQ 3.6.0 and will be removed again in jOOQ 4.0." means on the jOOQ site under this flag.  Is the flag going away, or is support for stored procedure return types going away?  A brief dig through the jOOQ github issues didn't yield me an answer.
Tempted to simply turn off deprecation.  This also seems like a global and not beneficial change, but it would serve the purpose.
If I created a binding, I have no idea what it would do, or how to define it since TRIGGER really isn't a sensible thing to bind a Java object to.  I assume I'd specify  as TRIGGER in the forcedType element, but then the Java binding seems like a waste of time at best and misleading at worst.

A: Well, after noting that an ideal way to do this would be to ignore that procedure, I did find how to ignore the procedure by name in the generally excellent jOOQ website documentation.  Don't know how I missed in on first pass.  If I needed to call this procedure in Java, I'm unclear which of the above options I would have used.
Luckily, there was no need for this procedure to be referenced in code, and I excluded it as shown below in in the jOOQ XML configuration.
<excludes>
    databasechangelog.*
    | maintain_edit_time
</excludes>

A: You've already found the perfect solution, which you documented in your own answer. I'll answer your various other questions here, for completeness' sake

Using ignoreProcedureReturnValues globally effects the project just because of this, which is fine for now, I don't have other procedures at all, much less others with a return value. But, I hate to limit future use. Also, I'm unclear one what the comment "This feature is deprecated as of jOOQ 3.6.0 and will be removed again in jOOQ 4.0." means on the jOOQ site under this flag. Is the flag going away, or is support for stored procedure return types going away? A brief dig through the jOOQ github issues didn't yield me an answer.

That flag has been introduced because of a backwards incompatible change in the code generator that affected only SQL Server: https://github.com/jOOQ/jOOQ/issues/4106
In SQL Server, procedures always return an INT value, just like functions. This change allowed for fetching this INT value using jOOQ generated code. In some cases, it was desireable to not have this feature enabled when upgrading from jOOQ 3.5 to 3.6. Going forward, we'll always generate this INT return type on SQL Server stored procedures.
This is why the flag has been deprecated from the beginning, as we don't encourage its use, except for backwards compatibility usage. It probably won't help you here.
Stored procedure support is definitely not going to be deprecated.

Tempted to simply turn off deprecation. This also seems like a global and not beneficial change, but it would serve the purpose.

Why not. A quick workaround. You don't have to use all the generated code. The deprecation is there to indicate that calling this generated procedure probably won't work out of the box, so its use is discouraged.

If I created a binding, I have no idea what it would do, or how to define it since TRIGGER really isn't a sensible thing to bind a Java object to. I assume I'd specify as TRIGGER in the forcedType element, but then the Java binding seems like a waste of time at best and misleading at worst.

Indeed, that wouldn't really add much value to your use cases as you will never directly call the trigger function in PostgreSQL.
Again, your own solution using <exclude> is the ideal solution here. In the future, we might offer a new code generation configuration flag that allows for turning on/off the generation of trigger functions, with the default being off: https://github.com/jOOQ/jOOQ/issues/9270


Q: Arduino w/ PWM expander and DC motor issue I am new to the forum. so.. Hi everyone
I am trying to control several DC 3-5v motor/pump with Arduino, using PCA9685 PWM expander.
I have connected one such motor, with a rectifying diode (IN4007), to 5V using a BC547 transistor, 2.2K resistor, the PCA9685 module, Arduino Due and 3.3V and 5V sources (with common ground). as in the diagram below.
The program on it runs a sweep on 0-100% and back on port 0.
Now..
IF I do NOT connect the motor, but instead put some random resistor load, everything works fine. I can measure across the load resistor a voltage going up from 0 to 5 and back down. All works 100% fine.
HOWEVER..
IF instead, I connected the motor where it should be, the program goes crazy as soon as the load across the motor gets to about 2-3 volts (or about 1.5V on the port 0 PWM).
The PWM stops updating and the serial console debugging clearly shows that something drags down the Arduino (the console stats updating slowly instead of the regular speed), due to I2C communication issues apparently (which hints that the PWM expander module went crazy). The Arduino can't seem to communicate with it anymore.
Disconnecting the motor at this stage doesn't help. Even then, the PWM doesn't update. The voltage on the 0 port remains stuck at the same level.. same for the motor. Things just get stuck.
Resetting the Arduino doesn't help.
If I disconnect the PWM module, the console logging goes back to regular speed (again, hinting that the PWM module went "crazy" and it is what is causing the console log drag).
Also, plugging the PWM module back in, doesn't solve the issue right away all the time, even at the beginning. It sometimes needs to "rest" for a bit. Then, once plugged in again it resumes working again like before.. meaning, only for the first second or so, until it goes crazy again.
I have no idea what is going on.
At first, I thought it has to do with a voltage created by the engine.. so I've added the rectifying diode. But that didn't help. Same issue.
I've also added a diode on the base, thinking maybe for some reason there is a current trying to flow back into the PWM module through the (orange) PWM port. But that also didn't help.
Why would the PWM module go crazy like that?
What causes it?
How do I fix it?


Q: HorizontalAlignment not working for Image inside Button (UWP) I have a button with an Image inside it
        <Button BorderThickness="0" Background="Black"  Grid.Column="0" Width="400" >
        <Image HorizontalAlignment="Right" Height="20" Source="ms-appx:///Assets/LockScreenLogo.scale-200.png" Width="20"  />
    </Button>

I want the image to be on the right end of the button so gave HorizontalAlignment="Right". But the Image always comes in the middle of the button. How can I fix this?

A: In the default style of Button, there is a ContentPresenter control to display the content of Button, it uses HorizontalContentAlignment property to control the horizontal alignment of the control's content. The default value is Center. So if you want to put the image in the right of Button, you can change the HorizontalContentAlignment to Right.
<Button HorizontalContentAlignment="Right" BorderThickness="0" Background="Black"  Grid.Column="0" Width="400" >
    <Image Height="20" Source="ms-appx:///Assets/LockScreenLogo.scale-200.png" Width="20"  />
</Button>


Q: Need to build a java file through ANT This is my java file.
package test;

import org.junit.Assert;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class MyTest{
    @Test
    public void startWebDriver(){
            WebDriver driver;
            driver = new FirefoxDriver();
            driver.navigate().to("http://google.com");
            Assert.assertTrue("title should start with google",driver.getTitle().startsWith("Google"));
            driver.close();
            driver.quit();
        }
}

I have stored all the selenium and Junit dependencies in a file named Xjars.
This is my build.xml
<?xml version="1.0"?>
<project name="AntSelenium" default="main" basedir=".">
  <!-- Sets variables which can later be used. -->
  <!-- The value of a property is accessed via ${} -->
  <property name="src.dir" location="src" />

  <property name="build.dir" location="classes" />

  <!-- Variables used for JUnit testin -->
  <property name="test.dir" location="src" />
  <property name="test.report.dir" location="testreport" />
  <property name="jar.dir" location="Xjars"/>
  <path id="classpath">
      <pathelement path="${basedir}"/>
      <fileset dir="${jar.dir}" >
          <include name="**/*.jar"/>
          </fileset>

  </path>

  <!-- Define the classpath which includes the junit.jar and the classes after compiling-->
  <path id="junit.class.path">

    <pathelement location="Xjars/junit-4.8.2.jar" />
    <pathelement location="${build.dir}" />
  </path>

  <!-- Deletes the existing build, docs and dist directory-->
  <target name="clean">
    <delete dir="${build.dir}" />
    <delete dir="${test.report.dir}" />
  </target>

  <!-- Creates the  build, docs and dist directory-->
  <target name="makedir">
    <mkdir dir="${build.dir}" />
    <mkdir dir="${test.report.dir}" />
  </target>

  <!-- Compiles the java code (including the usage of library for JUnit -->
  <target name="compile" depends="clean, makedir">
    <javac srcdir="${src.dir}" destdir="${build.dir}" classpathref="classpath" includeantruntime="false" />

      <!-- <pathelement path="Xjars/cglib-nodep-2.1_3.jar"/>
        <pathelement path="Xjars/commons-codec-1.10.jar"/>
        <pathelement path="Xjars/commons-collections-3.2.1.jar"/>
        <pathelement path="Xjars/commons-exec-1.3.jar"/>
        <pathelement path="Xjars/commons-io-2.4.jar"/>
        <pathelement path="Xjars/commons-lang3-3.4.jar"/>
        <pathelement path="Xjars/commons-logging-1.2.jar"/>
        <pathelement path="Xjars/cssparser-0.9.16.jar"/>
        <pathelement path="Xjars/gson-2.3.1.jar"/>
        <pathelement path="Xjars/guava-18.0.jar"/>
        <pathelement path="Xjars/htmlunit-2.18.jar"/>
        <pathelement path="Xjars/htmlunit-core-js-2.17.jar"/>
        <pathelement path="Xjars/httpclient-4.5.1.jar"/>
        <pathelement path="Xjars/httpcore-4.4.3.jar"/>
        <pathelement path="Xjars/httpmime-4.5.jar"/>
        <pathelement path="Xjars/jetty-io-9.2.12.v20150709.jar"/>
        <pathelement path="Xjars/jetty-util-9.2.12.v20150709.jar"/>
        <pathelement path="Xjars/jna-4.1.0.jar"/>
        <pathelement path="Xjars/jna-platform-4.1.0.jar"/>
        <pathelement path="Xjars/junit-4.8.2.jar"/>
        <pathelement path="Xjars/junit-4.8.2-sources.jar"/>
        <pathelement path="Xjars/nekohtml-1.9.22.jar"/>
        <pathelement path="Xjars/netty-3.5.2.Final.jar"/>
        <pathelement path="Xjars/sac-1.3.jar"/>
        <pathelement path="Xjars/selenium-api-2.48.2.jar"/>
        <pathelement path="Xjars/selenium-chrome-driver-2.48.2.jar"/>
        <pathelement path="Xjars/selenium-edge-driver-2.48.2.jar"/>
        <pathelement path="Xjars/selenium-firefox-driver-2.48.2.jar"/>
        <pathelement path="Xjars/selenium-htmlunit-driver-2.48.2.jar"/>
        <pathelement path="Xjars/selenium-java-2.48.2.jar"/>
        <pathelement path="Xjars/selenium-leg-rc-2.48.2.jar"/>
        <pathelement path="Xjars/selenium-remote-driver-2.48.2.jar"/>
        <pathelement path="Xjars/selenium-safari-driver-2.48.2.jar"/>
        <pathelement path="Xjars/selenium-support-2.48.2.jar"/>
        <pathelement path="Xjars/serializer-2.7.2.jar"/>
        <pathelement path="Xjars/webbit-0.4.14.jar"/>
        <pathelement path="Xjars/websocket-api-9.2.12.v20150709.jar"/>
        <pathelement path="Xjars/websocket-client-9.2.12.v20150709.jar"/>
        <pathelement path="Xjars/websocket-common-9.2.12.v20150709.jar"/>
        <pathelement path="Xjars/xalan-2.7.2.jar"/>
        <pathelement path="Xjars/xercesImpl-2.11.0.jar"/>
        <pathelement path="Xjars/xml-apis-1.4.01.jar"/> -->

  </target>

  <!-- Run the JUnit Tests -->
  <!-- Output is XML, could also be plain-->
  <target name="junit" depends="compile">
    <junit printsummary="on"  haltonfailure="yes">
      <classpath refid="junit.class.path" />
      <formatter type="plain" usefile="false" />
      <batchtest todir="${test.report.dir}">
        <fileset dir="${src.dir}">
          <include name="**/*Test*.java" />
        </fileset>
      </batchtest>
    </junit>
  </target>

  <target name="main" depends="compile, junit">
    <description>Main target</description>
  </target>

</project>

But finally I'm getting this error Buildfile:
 C:\Users\manish\workspace\AntSelenium\build.xml clean:    [delete]
 Deleting directory C:\Users\manish\workspace\AntSelenium\classes
 [delete] Deleting directory
 C:\Users\manish\workspace\AntSelenium\testreport makedir:
     [mkdir] Created dir: C:\Users\manish\workspace\AntSelenium\classes
     [mkdir] Created dir: C:\Users\manish\workspace\AntSelenium\testreport compile:
     [javac] Compiling 2 source files to C:\Users\manish\workspace\AntSelenium\classes junit:
     [junit] Running test.MyTest
     [junit] Testsuite: test.MyTest
     [junit] Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0 sec
     [junit] Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0 sec
     [junit]    Caused an ERROR
     [junit] org/openqa/selenium/WebDriver
     [junit] java.lang.NoClassDefFoundError: org/openqa/selenium/WebDriver
     [junit]    at java.lang.Class.forName0(Native Method)
     [junit]    at java.lang.Class.forName(Unknown Source)
     [junit]    at org.eclipse.ant.internal.launching.remote.EclipseDefaultExecutor.executeTargets(EclipseDefaultExecutor.java:36)
     [junit]    at org.eclipse.ant.internal.launching.remote.InternalAntRunner.run(InternalAntRunner.java:452)
     [junit]    at org.eclipse.ant.internal.launching.remote.InternalAntRunner.main(InternalAntRunner.java:139)
     [junit] Caused by: java.lang.ClassNotFoundException: org.openqa.selenium.WebDriver
     [junit]    at java.lang.ClassLoader.loadClass(Unknown Source)

 BUILD FAILED C:\Users\manish\workspace\AntSelenium\build.xml:94: Test
 test.MyTest failed

 Total time: 4 seconds Ant is not able to find the org.openqa.selenium.WebDriver class,

although the jar which I have included is a part of Xjars folder.

A: putting here for clarity but its more a comment than an answer
add this in your ant build file to debug the classpath used
  <target name="compile" depends="clean, makedir">
    <property name="myclasspath" refid="classpath"/>
    <echo message="Classpath = ${myclasspath}"/>

    <javac srcdir="${src.dir}" destdir="${build.dir}" classpathref="classpath" includeantruntime="false" />
  </target>

It will print out the classpath and help you debug if the jars are correctly picked up


Q: while loop to read from file skips first line i have to read data from a file into a struct array line by line, but it skips the first line. i found somewhere else that because of the fgets and the sscanf combo the 2nd line is the first read, but i dont understand why or how i can fix this. any suggestions or pointing in the right direction would be awesome!
void readData(){
    char line[50];
    char name1[1][50];
    int O, M, R, W;

    input = fopen("input2.dat", "r");

    //count = 0;
    while(fgets(line, 50, input) != NULL){
        hasReadData = 1;
        sscanf_s(line, "%20s %d %d %d %d", name1[0], 50, &O, &M, &R, &W);

        for(i=0; i<200; i++){
            if(strcmp(name1[0], player_arr[i].name) == 0){
                if(O<0 || M<0 || R<0 || W<0){
                    printf_s("%s %d %d %d %d", name1[0], O, M, R, W);
                    printf_s("\tNegative value, data invalid\n");
                    break;
                }
                if(O<M){
                    printf_s("%s %d %d %d %d", name1[0], O, M, R, W);
                    printf_s("\tOvers less than Maidens, data invalid\n");
                    break;
                }
                if(W>10){
                    printf_s("%s %d %d %d %d", name1[0], O, M, R, W);
                    printf_s("\tWickets greater than 10, data invalid\n");
                    break;
                }

                player_arr[i].oversOverall += O;
                player_arr[i].maidensOverall += M;
                player_arr[i].runsOverall += R;
                player_arr[i].wicketsOverall += W;

                player_arr[i].oversLatest = O;
                player_arr[i].maidensLatest = M;
                player_arr[i].runsLatest = R;
                player_arr[i].wicketsLatest = W;
            }
        }
    }
    fclose(input);
}

A: If your while is skipping first line while reading from the file then use this command inside the while loop:
file_pointer.seekg(0,ios::beg);
This file pointer will set your pointer to the beginning of the file.


Q: Converting csv to xls using Data::Table::Excel? How do you use Data::Table::Excel for converting .csv to .xls file format.
I want to do the conversion with the tables2xls subroutine:
my $t = Data::Table::fromFile("testresults-2013-07-01.csv");
my @arr = $t->csv;
Data::Table::Excel::tables2xls("results.xls", $t ,\@arr);

I tried the code above but I was not able get what I expected.

A: Last line must be:
Data::Table::Excel::tables2xls("results.xls", [$t] ,["Sheet name for your Table"]);

And here is colors example like you want:
Data::Table::Excel::tables2xls("results.xls", [$t] ,["Sheet name for your Table"], [["white","silver","gray"]]);


Q: im using ajax but its not executing asynchronously function send(seat_id, seat, seat_name, seat_price, seat_class){

      if(ing_order_yn == "y"){
            alert("결제창 이동 중 입니다. 좌석 변경이 불가능합니다.");

            return false;

        }
        var data1_val = "";
        var data1_val_f = "";
        var e_id    = $('input[name=e_id]').val();  //사용자가 선택한 event_id
        var floor   = $('input[name=floor_value]').val();//층
        var seat_list;

        $.ajax({
            url: '/seat_catch.do?group_id=<%=group_id%>',
            type : 'POST',
            data : { 'event_id' : e_id, 'seat_id' : seat_id },
            datatype : 'html',
            async : true,
            success : function( data1 ){
                    data1_val = data1.trim().substring(0,4);
                    data1_val_f = data1.trim().substring(0,6); //[선택불가]
                    //로그인 세션이없는 경우 ajax 리턴 값은 "session_out" 이다.

                    if(data1.trim() == "session_out"){
                        alert('로그아웃 된 상태입니다.\n로그인 후 사용해 주시기 바랍니다.')

                        document.location.href="/login.do";

                    }else{
                            if(data1_val == "담기성공"){
                            document.getElementById(seat).className  = "sel";

                                //클릭 한 좌석 정보 레이어 보여주기

                                $('#msg_popup2').html(seat_name + "<br>" + seat_price +"원");
                                    $('#msg_popup2').show();
                                    $('#msg_popup2').delay(5000).fadeOut(1000);
                                var e_id = $('input[name=e_id]').val(); //사용자가 선택한 event_id
                                    //좌석 선점 처리 후. 좌석 현행화
                                    orderSeatOp(e_id,'1',floor, function(htmll)
                                        alert(htmll);
                                        $('#seat').html(htmll);
                                    });
                                    <%-- $.ajax({
                                        url : '/seat.do',
                                        type : 'POST',
                                        async : true,
                                        data : { 'event_id' : e_id ,'group_id' : <%=group_id%> , 'floor' : floor },

                                        success : function( res ){
                                        $('#seat').html(res);

                                        return false;
                                    }

                                });

                             --%>

I think it has a problem in code for last section.
I did this two way

*

*one way is ajax code(annotating in last section)

*callback function.

$('#seat').html(res); it takes whole jsp code of layer popup and makes refresh. I want to make it as asynchronously but it still execute for refresh.
I don't know what can I do. please help me.
and sorry for my shortly English.


Q: Unable to mount drive as read-write I have a 1TB HDD (/dev/sda1, mount point /run/media/<name>/4733A97E4133EADF) that I'm trying to mount as read-write, but I can only get it to mount as read-only.
System:
$ uname -a
Linux <hostname> 4.10.6-1-ARCH #1 SMP PREEMPT Mon Mar 27 08:28:22 CEST 2017 x86_64 GNU/Linux
$ lsblk -f
NAME   FSTYPE LABEL       UUID                                 MOUNTPOINT
sda
└─sda1 ntfs               4733A97E4133EADF                     /run/media/<name>/4733A97E4133EADF
sdb
├─sdb1 swap               d9cea12d-5273-49ef-8950-3cd662fe63c7 [SWAP]
└─sdb2 ext4               e09a8578-53e9-4c26-9a97-a47b6350a1ab /
...

What I've tried

*

*Adding a fstab entry to automount the drive on boot:

$ cat /etc/fstab
#
# /etc/fstab: static file system information
#
# <file system>                 <dir>                   <type>      <options>           <dump>  <pass>
# /dev/sdb2
UUID=e09a8578-53e9-4c26-9a97-a47b6350a1ab   /                       ext4        rw,relatime,data=ordered    0   1

# /dev/sdb1
UUID=d9cea12d-5273-49ef-8950-3cd662fe63c7   none                    swap        defaults            0   0

# /dev/sda1
UUID=4733A97E4133EADF               /run/media/<name>/4733A97E4133EADF  ntfs        defaults,users,user     0   0

I've tried with defaults, defaults,users, and defaults,users,user. Rebooted after each change, but the drive is still mounted as read-only:
$ ls -l /run/media/<name>
...
dr-x------ 1 root  root  4096 Mar 28 17:35 4733A97E4133EADF
...

*

*Manually remounting:

$ sudo mount -o remount,rw /dev/sda1 /run/media/<name>/4733A97E4133EADF
mount: cannot remount /dev/sda1 read-write, is write-protected
$ sudo umount /run/media/<name>/4733A97E4133EADF
$ sudo mount -o rw /dev/sda1 /run/media/<name>/4733A97E4133EADF

At this point, the command just hanged for a few minutes, so I terminated it.
$ sudo umount /run/media/<name>/4733A97E4133EADF
$ sudo mount /dev/sda1 /run/media/<name>/4733A97E4133EADF

No change.
As of yet, I have not been able to write to the drive at all (from this system, at least), even as root.
chown, chmod have no effect because the filesystem is read-only.

What must I do to (auto)mount this drive as read-write, with normal (non-root) user access?

Have tried solutions from the following:

*

*How do I remount a filesystem as read/write? | Ask Ubuntu

*Ubuntu remount a root mount that's changed to ro as rw without rebooting | Server Fault

A: Although @ingopingo answered the question in one of the comments, i am going to write an answer with further information now.
By default the Linux kernel only supports reading from the NTFS file system. For read/write access you will need a read-write NTFS driver like the ntfs-3g package from extra repository.
After installation with sudo pacman -S ntfs-3g you are able to mount your NTFS partitions the usual way with sudo mount /path/to/ntfs /mount/point. This is possible due to a symlink of /usr/bin/mount.ntfs to /usr/bin/ntfs-3g.

Note: You need to have root privilegs to mount the filesystem.
  Requirements for an exception are listed in the ntfs-3g-FAQ.

Using the default settings the NTFS-partition will be mounted at boot. Put the following in your /etc/fstab:
/path/to/ntfs  /mount/point  ntfs-3g   defaults          0       0
To be able to read-write with a non-root user, you have to set some additional options (username has to be changed to your username):
/path/to/ntfs  /mount/point  ntfs-3g   uid=username,gid=users,umask=0022    0       0

A: I also had a read only mount problem and already used ntfs-3g. If someone else experiences this, check out ntfsfix /dev/yourPartitionToMount. It comes with the ntfsprogs under arch linux. This fixed my issue. I found it in the arch linux forum


Q: Serve static files with Node/Express I created a node express app and defined a path for static resources in my express app, app.ts:
app.use(express.static(path.join(__dirname, 'public')));

My static files are well served when I am on a main level, for example localhost:3000/products but I get a 404 return code on secondary paths, for example localhost:3000/products/details with this instruction:

What am I doing wrong?
Thank you in advance for your help.

A: Don't use relative paths for your URLs in the page.  Start them all with a /.  Change this:

to this:

When the path does not start with a /, then the browser adds the path of the containing page URL to the URL before requesting it from the server because ALL requests to the server must be absolute URLs.  That makes things break as soon as you are no longer on a top level page.  But, if your URLS always start with /, then the browser doesn't have to mess with the path of the URL before requesting it.


Q: How to deserialize the following JSON? I have a json in a string which I want to deserialize.
{
    "Envelope": {
        "Body": {
            "ObtainDecisionDataResponse": {
                "ObtainDecisionDataResult": {
                    "response_message_list": {
                        "message_info": {
                            "message_code": "0x8004278f",
                            "message_detail": "cvc-pattern-valid: Value '14620999' is not facet-valid with respect to pattern '((\d{5}|[A-Z]\d[A-Z]\d[A-Z]\d)?)' for type '#AnonType_business_business_infoAddress'."
                        },
                        "transaction_status_code": "300",
                        "transaction_status_text": "Unsuccessful"
                    }
                }
            }
        }
    }
}

The json value is assigned to String jsonContent.
String jsonContent = XmlToJSON.convertxmlToJson(jsonValue);
Map<String, Object> mapFromXmlContent = (Map<String, Object>) JSON.deserializeUntyped(jsonContent); // deserialization fails here

I am getting a common.apex.runtime.impl.ExecutionException when trying to deserialize the json string. There seems to be some problem with the json. I think it's the presence of single quote character ('14620999') which is causing the deserialization to fail, but I am not sure.  I have tried using  escapeSingleQuotes method but still it doesn't work like -
Map<String, Object> mapFromXmlContent = (Map<String, Object>) JSON.deserializeUntyped(String.escapeSingleQuotes(jsonContent));
How can I successfully deserialize it ? Should I modify the json string first before trying to deserialize it ?

A: Using e.g. https://codebeautify.org/jsonvalidator, the problem seems to be the \d which is not a valid escaped sequence according to e.g. https://www.json.org/. E.g. \n is OK.
So the string you have posted is not valid JSON; if the JSON is generated using a decent library, then that library would have transformed those into \\d i.e. a literal backslash followed by a d.
If someone else is generating the JSON, ask them to fix that. As a last resort, you could do a hacky search and replace before you parse.

A: The following works:
String value = '{ "Envelope": { "Body": { "ObtainDecisionDataResponse": { "ObtainDecisionDataResult": { "response_message_list": { "message_info": { "message_code": "0x8004278f", "message_detail": "cvc-pattern-valid: Value \'14620999\' is not facet-valid with respect to pattern \'((\\\\d{5}|[A-Z]\\\\d[A-Z]\\\\d[A-Z]\\\\d)?)\' for type \'#AnonType_business_business_infoAddress\'." }, "transaction_status_code": "300", "transaction_status_text": "Unsuccessful" } } } } } }';
System.debug(JSON.deserializeUnTyped(value));

Keep in mind that if you're trying out the JSON in an Apex string, you need to double up on the escapes \ again in order to get what should be the correct JSON, which itself would be \\d to represent a \d. It's likely you got an error because \d isn't a valid Apex string escape, which is why you got the error.
Also note that, for testing purposes, I also had to escape the ' characters in the JSON as well. JSON itself won't require them to be escaped, so this is fine.
The actual JSON should have \\ for a literal \, and Apex needs \\ for a literal \, so you end up needing a quadruple backslash sequence.


Q: Docker run: uwsgi gives permission denied This is so weid… I have a docker image that runs a web app. WHen I run it, nothing shows in containers… no error. Nothing under docker ps -a.
I ran docker events& and tried again, and it reported an error 1… which is apparently an app error, Okay.
So, I re-ran as:

docker run -it --entrypoint /bin/bash -p 80:80 --name NAME -d
NAME:latest -s

And then ran each item in the runall.sh
The first three items gave a permission denied:

uwsgi --http-socket 127.0.0.1:3009 --file
/var/www/cgi-bin/tireorder/main.wsgi --processes 1 --uid root
--enable-threads -b 32768 --daemonize /var/www/cgi-bin/tireorder/tireorder.log --pidfile
/var/www/cgi-bin/tireorder/tireorder.pid

Looking this up, and it appears to be a user permission, but all the directories and files are full access to root.
What is really freaky is that, I get it to run in windows and a mint linux VM… but in production(RHEL)) or on my linode VMs(Centos 8, Debian 10, Ubuntu 21) is gives the same permission denied!?
here's the docker file.
FROM lovato/python-2.6.6:latest

WORKDIR /

COPY trotta.tar.gz /

COPY runall.sh /

RUN chmod ugo+x runall.sh

RUN apt-get update

RUN apt-get install haproxy python python-pip python-dev nginx python-paste python-pastewebkit python-babel -y

RUN ["tar", "-xvzf", "trotta.tar.gz"]

RUN ["rm", "/etc/nginx/sites-enabled/default"]

RUN ["cp", "-R", "/usr/lib/python2.6/site-packages/Muntjac-1.1.2-py2.6.egg/muntjac", "/usr/lib/python2.7/dist-packages/"]

COPY uwsgi /usr/local/bin/

COPY /etc/default.conf /etc/nginx/conf.d/

COPY /etc/tireorder.conf /etc/

CMD ./runall.sh

Here is the runall.sh:
uwsgi --http-socket 127.0.0.1:3009 --file /var/www/cgi-bin/tireorder/main.wsgi --processes 1 --uid root --enable-threads -b 32768 --daemonize /var/www/cgi-bin/tireorder/tireorder.log --pidfile /var/www/cgi-bin/tireorder/tireorder.pid
uwsgi --http-socket 127.0.0.1:3310 --file /var/www/cgi-bin/tireorder2/main.wsgi --processes 1 --uid root --enable-threads -b 32768 --daemonize /var/www/cgi-bin/tireorder2/tireorder.log --pidfile /var/www/cgi-bin/tireorder2/tireorder.pid --chdir /var/www/cgi-bin/tireorder2
uwsgi --http-socket 127.0.0.1:3610 --file /var/www/cgi-bin/tireorder3/main.wsgi --processes 1 --uid root --enable-threads -b 32768 --daemonize /var/www/cgi-bin/tireorder3/tireorder.log --pidfile /var/www/cgi-bin/tireorder3/tireorder.pid --chdir /var/www/cgi-bin/tireorder3
service nginx start
/usr/sbin/haproxy -f /etc/haproxy/haproxy.cfg -p /var/run/haproxy.pid
tail -f /var/www/cgi-bin/tireorder/tireorder.log &
tail -f /var/www/cgi-bin/tireorder2/tireorder.log &
tail -f /var/www/cgi-bin/tireorder3/tireorder.log

A: Per Ashok:
Add RUN chmod -R 775  above the CMD command in your dockerfile
This resolved it when applied the folders and the uwsgi.


Q: Add/remove JFXPanel on Swing JFrame I want to add and remove JFXPanel on JFrame container but not able to do that. I am stuck here and get no proper solution on button click I want to add and remove the JFXPanel  control.
What is the wrong in this code?
  public class abc extends JFrame
  {
  JFXPanel fxpanel;
  Container cp;
  public abc()
  {
  cp=this.getContentPane();
  cp.setLayout(null);
  JButton b1= new JButton("Ok");
  JButton b2= new JButton("hide");
  cp.add(b1);
  cp.add(b2);
  b1.setBounds(20,50,50,50);
  b2.setBounds(70,50,50,50);
  b1.addActionListener(this);
  b2.addActionListener(this);
  fxpanel= new JFXPanel();
  cp.add(fxpanel);
  fxpanel.setBounds(600,200,400,500);
 }

  public void actionPerformed(ActionEvent ae)
 {
 if(ae.getActionCommand().equals("OK"))
  {
    fxpanel= new JFXPanel();
    cp.add(fxpanel);
    fxpanel.setBounds(600,200,400,500);

   }
  if(ae.getActionCommand().equals("hide"))
   {
    cp.remove(fxpanel);
    }
   }
    public static void main(String args[])
   {

      abc f1= new abc();
      f1.show();
    }
   }

A: *

*Dont extend JFrame call unnecessarily

*Dont use null/Absolute LayoutManager

*why use show() to set JFrame visible? you should be using setVisible(true)

*Dont forget Swing components should be created a manipulated on  Event Dispatch Thread via SwingUtilities.invokeXXX and JavaFX components via Platform.runLater()
Besides the above the biggest problem you have is that you dont refresh GUI/container after adding/removing components,thus no changes are shown.:
call revalidate() and repaint() on JFrame instance to reflect changes after adding/removing components from a visible container.


Q: How to remove excess whitespace from a string by jQuery and only count the actual number of characters? today I want to design a block text more than 70 characters will hide the extra text and appear show more
But I can't predict if the user will add extra blank lines, which will cause them to be counted as a character. How do I remove the extra white space and count only the parts that actually have words?

$(function(){
    let len = 70
    $('.demo').each(function(){
        if($(this).html().length >len){
            var str=$(this).html().substring(0,len-1)+"...顯示更多";
            $(this).html(str);
        }
    });
});
.content{
  display: flex;
  justify-content:space-between;
  border:1px solid #222;
  padding:10px;
}

.demo{
  overflow:hidden;
  text-overflow:clip;
  display:-webkit-box;
  -webkit-box-orient:vertical;
  -webkit-line-clamp:2;
}

.photo{
  width: 100px;
  height: 100px;
  border:1px;
  border-radius:16px;
  margin-left: 10px;
}

.more{
  text-decoration:none;
  color:blue;
}

    Lorem ipsum dolor sit amet consectetur Lore

A: You can use .trim() as in if ($(this).html().trim().length > len) {
Demo

$(function() {
  let len = 70
  $('.demo').each(function() {
    if ($(this).html().trim().length > len) {
      var str = $(this).html().substring(0, len - 1) + "...顯示更多";
      $(this).html(str);
    }
  });
});
.content {
  display: flex;
  justify-content: space-between;
  border: 1px solid #222;
  padding: 10px;
}

.demo {
  overflow: hidden;
  text-overflow: clip;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
}

.photo {
  width: 100px;
  height: 100px;
  border: 1px;
  border-radius: 16px;
  margin-left: 10px;
}

.more {
  text-decoration: none;
  color: blue;
}

    Lorem ipsum dolor sit amet consectetur Lore


Q: Boost::regex_match isn't firing I have some boost Regex code which I think should fire. I'm new to boost but I know a little bit of Regex. Here's the code that I'm using.
re = boost::basic_regex<TCHAR>(_T("-+\\s+Original\\s+Message\\s+-+"), boost::regex_constants::icase);
boost::match_results<TSTRING::const_iterator> result;
if(boost::regex_match(RawBody, result, re))

and here is the test string I'm using.
this is a test

-------- Original Message --------

everything under here should disappear

My code compiles and runs, it just doesn't trigger the if statement. I tried debugging into the boost code and ... yeah...

A: regex_match

The algorithm regex_match determines whether a given regular
  expression matches all of a given character sequence denoted by a pair
  of bidirectional-iterators, the algorithm is defined as follows, the
  main use of this function is data input validation.

regex_search

The algorithm regex_search will search a range denoted by a pair of
  bidirectional-iterators for a given regular expression. The algorithm
  uses various heuristics to reduce the search time by only checking for
  a match if a match could conceivably start at that position. The
  algorithm is defined as follows:

So, use boost::regex_search. Example.
http://liveworkspace.org/code/fa35778995c4bd1e191c785671ab94b6


Q: What is the mangle table in iptables? I am using iptable rules to filter & manipulate packets in my Ubuntu server.
but I cannot understand the mangle table.
Quoting from this iptables tutorial:

This table should as we've already noted mainly be used for mangling packets. In other words, you may freely use the mangle matches etc that could be used to change TOS (Type Of Service) fields and so on.
You are strongly advised not to use this table for any filtering; nor will any DNAT, SNAT or Masquerading work in this table.

Can anybody describe to me the mangle table, and provide some examples to understand when I should use it?

A: Further to the other good answers, I recently had to use the mangle table to adjust for MTU (maximum transmission unit) discrepancies caused by traffic being brought through PPPoE, PPP, and ATM, each of which adds overhead that reduces the payload available for IP from the usual 1500 bytes of an Ethernet frame.
Systems on each end of the pipe, as is normal, would have their MTU at the regular default of 1500 and so they would try to send IP frames that large.  Since the actual payload size available was smaller, this would have caused packet fragmentation, except that often the sender will request that packets not be fragmented, and as such they end up getting dropped entirely.
In an ideal world, path MTU discovery would have allowed the endpoints to adjust their MTU down as needed, but this discovery depends upon ICMP, and networks outside of my control were often configured to drop ICMP for security reasons.
The only choice was to use packet mangling in my router in order to modify TCP SYN packets to lower the maximum segment size at the transport layer:
iptables -t mangle -A FORWARD -p tcp --tcp-flags SYN,RST SYN -j TCPMSS --set-mss 1452

This sort of thing is messy and ideally should be avoided, but I had no other options and this did solve the problem.
Hope these examples help, as well as the man page.

A: I recently found a good explanation here. It is basically used to set specific headers for IP packets to affect the routing decision made further on. If any, the TTL option is probably the most interesting:

The TTL target is used to change the TTL (Time To Live) field of the
packet. We could tell packets to only have a specific TTL and so on.
One good reason for this could be that we don't want to give ourself
away to nosy Internet Service Providers. Some Internet Service
Providers do not like users running multiple computers on one single
connection, and there are some Internet Service Providers known to
look for a single host generating different TTL values, and take this
as one of many signs of multiple computers connected to a single
connection.

The other targets are TOS, MARK, SECMARK, CONNSECMARK.

A: There is a good deep dive but not too difficult to understand tutorial on iptables here.

The mangle table is used to alter the IP headers of the packet in various ways. For instance, you can adjust the TTL (Time to Live) value of a packet, either lengthening or shortening the number of valid network hops the packet can sustain. Other IP headers can be altered in similar ways.
This table can also place an internal kernel "mark" on the packet for
  further processing in other tables and by other networking tools. This
  mark does not touch the actual packet, but adds the mark to the
  kernel's representation of the packet.

Helped me a lot, as it also clearly explains how all the parts fit together and interract with one another.

A: As an iptables noob, I'd say:
The mangle table allows to modify some special entries in the header of packets.
(such: Type of Service, Time To Live )
(it also allows to set special marks and security context marks)


Q: How to fix inconvertible types in Android Studio I am trying to start an application based on google maps in Android Studio. I followed the instructions and started an Google Maps activity.
Then I created according to the instructions an API key and enabled the maps SDK android for android and copied the key into the app.
but then when I'm trying to run the app (didnt change a thing) I get this error:
Inconvertible types; cannot cast 'android.support.v4.app.Fragment' to 'com.google.android.gms.maps.SupportMapFragment'

for this line of code:
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
and this error: Manifest merger failed : Attribute application@appComponentFactory value=(android.support.v4.app.CoreComponentFactory) from [com.android.support:support-compat:28.0.0] AndroidManifest.xml:22:18-91
    is also present at [androidx.core:core:1.0.0] AndroidManifest.xml:22:18-86 value=(androidx.core.app.CoreComponentFactory).
    Suggestion: add 'tools:replace="android:appComponentFactory"' to <application> element at AndroidManifest.xml:12:5-42:19 to override.
in the event.

Here is the code:
package com.example.android.myfirstmap;

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

    private GoogleMap mMap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        // Add a marker in Sydney, Australia, and move the camera.
        LatLng sydney = new LatLng(-34, 151);
        mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
    }

I looked around to see if there is a solution that fixes also my problem but none of what I tried was the right one.
does anyone knows how to fix it? evreything is updated.

A: Support Map Fragment extends androidx.fragment.app.Fragment.
You are importing android.support.v4.app.FragmentActivity which uses android.support.v4.app.Fragment. These are two different classes so they are incompatible.
You need to migrate your app to Android X: https://developer.android.com/jetpack/androidx/migrate
Then, in your build.gradle file, replace com.android.support:support-fragment with androidx.fragment:fragment.
Hope that helps!