text:
Q: Refactor big C++ application to prevent from bad pointer In application which has about 1.5 mln lines of code there is using many pointers as a class members and in other places in code. Classes are usually very huge.
It is possible to change to make it safer in quite fast way? Refactor it can take years. It will be hard to change all methods to check if pointer is not null and change pointers to reference where is it can be a reference. It is very important to keep the same performance.
I am looking for idea how to refactor it in quite simple and fast way to improve stability of application.

A: Unless you have a very comprehensive suite of automated tests covering all of the code you need to refactor, the odds of this effort passing without any issues is close to zero.   There's really no way to make this either simple or fast.
I'd recommend several things:

*

*Get to grips with the root cause - i.e. how on earth did anybody ever let the code get that bad?

*Understand how big the task is - how many 'Man years' might this take?

*Treat the remedial work like you would treat any new development work.

*Make sure everybody in your organisation is heading in the same way and that you're not battling against the tide.

Looking at root causes

*

*Why is the code so bad in the first place?

*What kind of mismanagement caused your code base to slip so deeply into entropy that you are now saddled with so much technical debt?

*Are the company's current processes (code reviews, developer training, etc.) sufficient to prevent the code base getting worse

*Do your co-workers really care, or are they content just adding more bad code into the mix?

Bottom Line This effort is pointless if you don't address the underlying causes; before you can really fix problems with entropy and technical debt, you need to put a stop to "technical borrowing", otherwise this will never end and you'll be fighting a losing battle.
Understanding the scale of the problem
You are probably going to be asked a very reasonable question by senior management: "So, exactly what are we getting in return for paying our development team to do this and how much will it cost?"
Even if you don't need to answer that question to your boss, you need to be able to define boundaries, otherwise the task starts to look like a never-ending project.

*

*Use a static code analysis tool such as LINT to evaluate the entire code base and let it generate reports for all the problems which you're interested in (e.g. possible memory leaks, possible dangling pointers, possible null dereferencing, etc.)

*Use your own knowledge of the code base to identify the problematic areas and concentrate on those which suffer from the most severe entropy

*Keep an eye out for ancient code which might have quick wins - for example, throwing away char* in favour of std::string/iterators, or anywhere in the code which uses anything from an old C header (e.g. scanf, sprintf, malloc, etc.)

*If you have automated tests covering the areas you find, great.  If you do not have automated tests, look carefully at the code to identify the edge cases which should cause the system to misbehave

*When you find an edge-case which the system cannot handle, define a test  (ideally automated) which can prove the existence of defects in that code.

*Document all of the specific problems you have found, including how to make them fail and why the code needs refactoring;  and use this to justify why it should receive attention.
Deciding whether to fix the problems
With such a large code base, you cannot solve everything; your bosses are likely to get nervous if too much money is spent on an effort which they probably already think is going to be like throwing money into a pit.
Do a risk assessment for each area of code which you've identified as being problematic:

*

*What happens if something in there breaks?

*Which customers are affected?   How disruptive is it to them?

*How much money is the company currently spending maintaining that area of code?

*If the refactoring fails and causes more problems, what's the worst-case scenario?  e.g. does it make the whole system unusable for everybody or does it only affect a minor feature rarely used by customers?

Deciding on the best remedy
Start a dialogue with your co-workers (Not just other developers, but anyone who has a stake in the system - especially the product owner) about the problems you've identified.  Decide which ones are severe enough to warrant time spent refactoring.

*

*Look at the requirement for the code where the problem exists;  do any of your customers even use that part of the system any more?  can that code just be deleted?

*Does the problem code generally fulfil the requirements it is intended for or does its design (or lack thereof) mean that there are some weird limitations and caveats?  Is it really just a dirty hack?  If so, should it be rewritten?

*Do any of the problem areas overlap with upcoming development work in the pipeline for your team?   Consider whether the refactoring effort should be managed as part of a near-future project where the code will need refactoring anyway.

*Is the overall design of the code just reinventing the wheel from the standard library (or Boost/POCO/etc.)?  If so, is it feasible to rip that out and replace it?

*Is the sitting right in the core of the whole system and too risky to touch?  If so, can you refactor pieces around the edges to reduce the coupling?
Getting everybody on board
Efforts like this cannot (or at least, should not) be done by a lone wolf developer.   You need the buy-in from everybody in your organisation who has a stake in this.
If it hasn't already happened, the company culture needs to be in a place where both developers and upper management understand the need for taking extra time to improve the quality of code.
Your bosses need to insist that bad code is unacceptable and that proper code reviews are always conducted.    Also, experienced developers in the team should be proactive in supporting the rest to raise standards of code being produced.
This is perhaps the hardest problem to solve, but your refactoring effort will fail if you can't get your co-workers on board.
Getting the work underway
I'd strongly recommend doing things slowly; small incremental improvements are significantly less destabilising and easier to test than making huge far-reaching changes across the whole code base.
Don't think of software analogies such as 'skyscraper construction' - that analogy, while commonly used, is heavily flawed because a piece of software is never really finished, and software architecture never fits neatly into an up-front vision or blueprint.
Software is always changing and evolving gradually over time; refactoring really shouldn't be any different.

A:
I am looking for idea how to refactor it in quite simple and fast way
  to improve stability of application.

Personally I would refactor away from the legacy code. Seek to design nice, safe interfaces which communicate with the old code and write automated tests for those new interfaces to ensure their integrity and assumptions. The interfaces can be implemented using the old code for now, but eventually they might stop needing the old code. Don't let the old code heavily influence the shape and design of these interfaces. Focus on the original software features at the user-end level and requirements and design fresh interfaces against those requirements. Take your time designing and testing these interfaces, develop some sense of confidence and pride in the design, but prioritize designing interfaces required for the features your team anticipates will need the most work or for the features your team is planning to add.
Trying to refactor millions of lines of old code is with the mindset of wanting to keep changing it and swimming inside of it against changing requirements in the future. After all, that's the only reason to seek to improve the engineering quality of existing code -- to seek to make it easier to change further down the line. In my opinion that isn't a desirable or very practical goal if there's a sea of code that drives you paranoid. I would seek to reduce the reasons for the old code to ever change in the future, and seek to lock it down using the above technique and possibly even weed it out. Basically start trying to make it work its way towards being increasingly like a third party library in the future, to be called and used if necessary, not modified. And, like any old third party library, if your code and your users becomes less dependent on it in favor of a new library and new features, you might eventually find fewer and fewer reasons to need the "third party library" as it works its way towards obsolescence until the dependencies disappear and you can remove it.
Stop Changing the Old
As you design those new interfaces and tests, even if they use the old nasty code for their implementation, what they do can be reliable and safe and robust as ensured by all the tests you write against these new, well-designed, well-documented, well-tested, safe interfaces that leave little room for common misuse. And that can give your team a big confidence boost as they start writing new code against these new interfaces and not the old, and the dependencies to the old code gradually begin to shrink, like a breath of fresh air after being drowned in a cloud of farts.
Refactoring is seeking to prepare code to better handle further changes. I'd seek the opposite mindset. Seek to increasingly minimize the amount of changes you ever need to make to the old code by seeking to make it stable (as in, lacking reasons for changes, bolted down, cemented in concrete), and seek to make the new code you introduce using the new interfaces you design unstable (the parts that will be fluid and changing against changing requirements). Old code should become increasingly stable and new code should become increasingly unstable. A lot of teams struggling with legacy codebases have this reversed -- their old code is the most unstable while the new code is the most stable, when it should be the opposite.
Code Should Become Stable With Age
In fact, I believe this even for old code which has top-notch engineering. In that case, if it's old, it should have passed the test of time already, proven to be extremely reliable, and should work its way towards a black box library of functionality you can just count on again and again without constantly finding reasons to tamper with it further. Even if you absolutely love working with this old code, there shouldn't be reasons for it to keep changing and changing. You should be able to lock it down with tests and stable interfaces with implementations that work beautifully for years to come instead of having it constantly consisting of moving parts. If you designed proper interfaces, not monoliths that aim to do everything imaginable in the entire world, with goals that can be achieved in a finite amount of time, then there's no reason for any class/library/package to need to be changed and changed indefinitely.
If it has horrid engineering, then there's even more reason to seek to make it stable since your engineers would hate to work in it on top of it being old. So seek stability for things that are starting to age. Seek to make age and stability proportionally related ideas. You should be spending more time working on changing and maintaining new code.

A: Let's be very honest: the number of lines of codes that you have will make such a refactoring anything else than easy !
The problem with bad pointers are multiple. For example:

*

*Abusive casting from a pointer of one type to a pointer of an incompatible type (including between types that have different alignment constraints

*Dereferencing a nullptr

*Dereferencing a pointer to an object that was freed in the meantime

The answer to the first point is to get rid of the c like casting and only use the stricter c++ casts (static_cast, dynamic_cast, and in last ressort with extreme care the reinterpret_cast which highlight potential risks). This can be done without disruption.
Then a lot of nasty pointer issues come with the non respect of the rule of 3 (or rule of 5 nowadays). Go through all your classes that have pointer members and make sure that the rule is enforced. This can be done without disruption.
Similar issues could occur in absence of virtual destructors in polymorphic types. Make sure that all the classes having a virtual function either have a virtual destructor or inherit from a class having its virtual destructor. Still without any disruption.
After these first cleaning steps you have the choice between two other strategies. These are more disruptive and require a heavier investment.
The first one is to opt for smart pointers, with unique_ptr for allocating an object which is owned (and no other than owner can delete this object), shared_ptr when several objects point to the same shared object, (which may be deleted only when no pointers point to it anymore), and weak_ptr which allow to share a pointer but without ownership (e.g. backpointers to parents in a tree). The overhead, thanks to compile time template instantiation and the optimiser, make the overhead minimal if any.  This refactoring approach avoids the need to manually delete objects and make the code more reliable (fighting problem 2 and 3). It requires however a good understanding of how each pointer is used.  In large code bases, a good option is to deploy this approach by pointed type.
Another more ambitious refactoring approach is to replace pointers and dynamic allocation as much as possible with standard containers (e.g use of string instead of char*, or use of vectors instead of allocating arrays). These containers take care of allocation/deallocation. The c++ move semantic reduces the need to copy objects in many cases. This allows to achieve similar performance as with pointers, but leaving the responsibility for the detailed implementation to the compiler (much more reliably than a human). I think that this would be the preferred refactoring approach but it requires a significant review of all the data structures, pointer usage, and parameter passing).
Both approaches are not mutually exclusive. In some cases you'd still need smart pointers (e.g to implement your own tree structure if a map can't do). In some cases you could opt for smart pointers instead of going for standard containers, especially if the pointers are not well encapsulated and used broadly accross the code.
Conversely, you could opt for smart pointer approach and spot some opportunities for container usage).
Personally, with millions of lines of code, after the first cleaning, if debugging with asserts is not sufficient and if defensive coding could really create a proven and significant overhead, I would opt for this last mixed approach.

A: The other answers here are really great. I'd like to expand on something mentioned in a few of the other answers. Namely using your tooling to help you get a grip on the problem.
Compiler Warnings
Get your compiler warnings under control. Ideally you should have no warnings when building your application. If you don't already have that, then make a concerted effort to address every single warning your compiler is telling you about. I've seen this done with a very large code base with thousands of warnings. It's possible to get under control, even if it seems helpless. Once you are compiling with no warnings, turn on the compiler setting that sets warnings to errors. This will keep you from ever getting anymore compiler warnings committed to your code base because the app just won't build if there are any warnings. And once you've done that, increase the warning level. Each time you increase the warning level, you fix a whole host of bugs just to get your application building again. Once you've done it once, do it again - turn up the warning level and start fixing.
Static Analysis
It was mentioned to use a linter or static analyzer. (Examples include clang, PVS-Studio, etc.) I could not agree more. Once you've cleared out compiler warnings, you'll still have a bunch of non-obvious issues. Your code will be semantically correct, but might not be doing what you think. A linter or static analyzer will point out things like, "when this value is less than x, y is null, and this later test fails, and memory is leaked." Fixing these sorts of issues gets you even further than fixing the compiler warnings.
Leak Detection & Memory Debugging
Additionally, you should use some sort of leak detection and memory debugging tools such as Instruments, Valgrind, mallocdebug, zombies, or whatever's appropriate for your system. They will tell you when you have allocated memory and not freed it, but no other objects are pointing to it. They will tell you when you are trying to access memory that has already been freed. They will tell you when you are accessing memory that was never allocated. They can find issues with writing past the end of an array or other buffer.
Other Tools
There are a host of other tools for every OS that can point out issues either in your code, or while running. Figure out what the biggest issues are for your users, then find a tool that helps analyze that issue and use it.


text:
Q: How to keep bound JTable up to date? I am using a bound JTable to display a list of entities.

    // selSteps is a List of entities.
    selStepsBound = ObservableCollections.observableList(selSteps);

    JTableBinding jTableBinding = SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, selStepsBound, tblSelSteps, "tblSelStepsBinding");
    ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${steporder}"));
    columnBinding.setColumnName("Order");
    columnBinding.setColumnClass(Integer.class);
    columnBinding.setEditable(false);
    columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${name}"));
    columnBinding.setColumnName("Description");
    columnBinding.setColumnClass(String.class);
    bindingGroup.addBinding(jTableBinding);
    jTableBinding.bind();

    bindingGroup.bind();

This works fine for displaying the original data. I can even remove items from the bound observableList and I automatically get the JTable UI updated.
The problem is when I change the property value of an entity, that value is not reflected in the JTable UI.
How do I notify the JTable about the changes?

A: I'm not super familiar with the SwingBindings stuff, but it appears that while your List is Observable (i.e. listeners will be notified of changes) your entity is not. So nobody is listening to the changes of your entity.
The way I'd typically notify JTable of a change in one of its entities would be to fire a TableModelEvent from the table's model. This is what the JTable is listening for to update itself. I typically extend from ABstractTableModel so that I can call nice functions like fireTableCellUpdated(row,col), etc. How this strategy can be blended with the SwingBindings stuff, I'm not quite sure though...

A: You need to add "property change support" to your entity.  So add a member variable...
final private PropertyChangeSupport changeSupport = new PropertyChangeSupport(this);

and the methods...
public void addPropertyChangeListener(PropertyChangeListener listener) {
    changeSupport.addPropertyChangeListener(listener);
}

public void removePropertyChangeListener(PropertyChangeListener listener) {
    changeSupport.removePropertyChangeListener(listener);
}

and then in each setter, add a line similar to this...
    changeSupport.firePropertyChange("myProperty", oldMyProperty, myProperty);

e.g.
    public void setTotalWeight(Integer totalWeight) {
    Integer oldTotalWeight = this.totalWeight;

    this.totalWeight = totalWeight;

    changeSupport.firePropertyChange("totalWeight", oldTotalWeight, totalWeight);
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Getting null values in jq bash I have data.json which looks like this
{
  "type": "AdaptiveCard",
  "body": [
    {
      "type": "TextBlock",
      "text": "Monitoring",
      "wrap": true,
      "weight": "bolder",
      "size": "large"
    },
    {
      "type": "TextBlock",
      "text": "23-04-2022 20:00",
      "wrap": true,
      "size": "Small",
      "isSubtle": true
    },
    {
      "type": "RichTextBlock",
      "inlines": [
      ]
    }
  ],
  "": "http://adaptivecards.io/schemas/adaptive-card.json",
  "version": "1.5"
}

And I'm trying to add values dynamically to the inlines array
sample script
#!/bin/bash

cluster="live"

echo "$(jq --arg c "$cluster" '.body[2].inlines[2] += {"type": "TextRun","text": "Error: Failed Event in Activity Log $c" }' data.json)" > data.json
echo "$(jq '.body[2].inlines[2] += {"type": "TextRun","text": "VMs are in running state" }' data.json)"  > data.json
echo "$(jq '.body[2].inlines[2] += {"type": "TextRun","text": "VMs are  NOT in running state" }' data.json)" > data.json
echo "$(jq '.body[2].inlines[2] += {"type": "TextRun","text": "VMs are OFCOURSE in running state" }' data.json)" > data.json

I have got 2 problems.
first: I have tried finding solution to use dynamic values in the array but it doesn't expands it.
second: Only the last value is inserted, the previous value somehow becomes null
{
  "type": "AdaptiveCard",
  "body": [
    {
      "type": "TextBlock",
      "text": "OU Monitoring",
      "wrap": true,
      "weight": "bolder",
      "size": "large"
    },
    {
      "type": "TextBlock",
      "text": "23-04-2022 20:00",
      "wrap": true,
      "size": "Small",
      "isSubtle": true
    },
    {
      "type": "RichTextBlock",
      "inlines": [
        null,                                 <==
        null,                                 <==
        {
          "type": "TextRun",
          "text": "VMs are OFCOURSE in running state"
        }
      ]
    }
  ],
  "": "http://adaptivecards.io/schemas/adaptive-card.json",
  "version": "1.5"
}

A: First issue: If you have an empty array, then set a value at index 2 (as with .body[2].inlines[2]), the previous ones (namely index 0 and 1) will be set to null.
Second issue: You always modify the same item (namely .body[2].inlines[2]). += in this case will append the new object to the existing one, but as it's using the same keys, they will be overwritten.
Solution: Use += on the array, and wrap the new item in brackets (making it another array of one item). This way you can successively populate the existing array.
.body[2].inlines += [{"type": "TextRun","text": "Error: Failed Event in Activity Log $c"}]

Demo
You also may want to put your operations into just one jq call. Either use the pipe | to concatenate the single operations, or, especially in this case, add all items at once as you are adding arrays anyways.
cluster="live"
jq --arg c "$cluster" '
  .body[2].inlines += [{"type": "TextRun","text": "Error: Failed Event in Activity Log $c"}]
  | .body[2].inlines += [{"type": "TextRun","text": "VMs are in running state"}]
  | .body[2].inlines += [{"type": "TextRun","text": "VMs are  NOT in running state"}]
  | .body[2].inlines += [{"type": "TextRun","text": "VMs are OFCOURSE in running state"}]
' data.json

Demo
cluster="live"
jq --arg c "$cluster" '
  .body[2].inlines += [
    {"type": "TextRun","text": "Error: Failed Event in Activity Log $c"},
    {"type": "TextRun","text": "VMs are in running state"},
    {"type": "TextRun","text": "VMs are  NOT in running state"},
    {"type": "TextRun","text": "VMs are OFCOURSE in running state"}
  ]
' data.json

Demo
Output:
{
  "type": "AdaptiveCard",
  "body": [
    {
      "type": "TextBlock",
      "text": "Monitoring",
      "wrap": true,
      "weight": "bolder",
      "size": "large"
    },
    {
      "type": "TextBlock",
      "text": "23-04-2022 20:00",
      "wrap": true,
      "size": "Small",
      "isSubtle": true
    },
    {
      "type": "RichTextBlock",
      "inlines": [
        {
          "type": "TextRun",
          "text": "Error: Failed Event in Activity Log $c"
        },
        {
          "type": "TextRun",
          "text": "VMs are in running state"
        },
        {
          "type": "TextRun",
          "text": "VMs are  NOT in running state"
        },
        {
          "type": "TextRun",
          "text": "VMs are OFCOURSE in running state"
        }
      ]
    }
  ],
  "": "http://adaptivecards.io/schemas/adaptive-card.json",
  "version": "1.5"
}


text:
Q: How to make a query that filter out two AND conditions on same column Write a query that returns all pages that have been visited by at least one child (demo='child') and ALSO has been visited by at least one person aged 18-25 (demo='18-25').  Your query should return a set of urls.
I am not sure how to write a query that filters out results based on Two AND statements on the same column and it returns out an empty set.
These are the two tables:
User

uid
ip
demo

A
001
child

B
002
18-25

Visit

url
dt
uid
src
rev

A01
1890-05-14
A
A02
10

A01
002
B
A03
15

Select distinct V.url
from Visit V, [User] Z, [User] F
WHERE V.uid = Z.uid AND V.uid = F.uid
AND Z.demo = 'child' AND F.demo = '18-25'

This above code returns me an empty set.
I want it to return A01 as the url

A: First, you don't need to use User table twice in the select expression.
I think it can be solved by using nested queries or as called subquery.
In explanation: first you will query the items match the first condition (demo='child') then you will search on the results for the items that also match the second condition (demo='18-25').
Your code will be like this:
Select distinct V.url
from Visit V, [User] Z
WHERE V.uid = Z.uid AND Z.demo = 'child'
AND V.url IN (Select distinct V1.url
from Visit V1, [User] Z1
WHERE V1.uid = Z1.uid AND Z1.demo = '18-25')

A: One way is to join the users, GROUP BY the URL, sum the occurrences of children and 18 to 25 year olds and check that these sums each exceed 0 in a HAVING clause.
SELECT v.url
       FROM Visit v
            INNER JOIN User u
                       ON v.uid = u.uid
       GROUP BY v.url
       HAVING sum(CASE
                    WHEN u.demo = 'child' THEN
                      1
                    ELSE
                      0
                  END) > 0
              AND sum(CASE
                        WHEN u.demo = '18-25' THEN
                          1
                        ELSE
                          0
                      END) > 0;

(Note: In MySQL you don't need the CASE expressions but could directly use the Boolean = expressions. But a CASE doesn't harm there either and with a CASE it'll also work in other DBMS. And since it's not entirely clear which DBMS you use a CASE expression is a safer bet.)
Another approach is to use a conjunction of EXISTS' and correlated subqueries that join the users to the visits and picks the record with the URL and demo in question. It would help if you already had a table with only the URLs. I'll simulate that with a derived table aliased x.
SELECT x.url
       FROM (SELECT DISTINCT
                    v.url
                    FROM Visit v) x
            WHERE EXISTS (SELECT *
                                 FROM Visit v
                                      INNER JOIN User u
                                                 ON u.uid = v.uid
                                 WHERE v.url = x.url
                                       AND u.demo = 'child')
                  AND EXISTS (SELECT *
                                     FROM Visit v
                                          INNER JOIN User u
                                                     ON u.uid = v.uid
                                     WHERE v.url = x.url
                                           AND u.demo = '18-25');

A: It looks like you can JOIN on the User table twice: once to find a user that is "18-25", and another to find a user that is a "child". If you find both of those (as determined by the WHERE clause) then the Visit record will be included in the results:
SELECT
  DISTINCT V.url
  FROM
    Visit V
  LEFT JOIN User U ON (V.uid = U.uid AND U.demo = '18-25')
  LEFT JOIN User U2 on (V.uid = U2.uid AND U2.demo = 'child')
  WHERE
    U.uid IS NOT NULL AND U2.uid IS NOT NULL

A: You don't have to join User table twice and please use the more recommended JOIN operator over comma-join.
A comment from @stickybit made me realize that I misunderstand the question. Therefore I'll update my answer to something workable for the question requirement. I'll retain most of my original answer with little modifications just to make sure that it can return the desired result for the current set of OP data. Here's the query:

SELECT * FROM
(SELECT url,
       GROUP_CONCAT(demo) dd
  FROM Visit V
   JOIN User U
    ON V.uid = U.uid
GROUP BY url) A
WHERE dd LIKE '%child%18-25%' OR dd LIKE '%18-25%child%';

I know this is not the best solution but I've seen others have posted their version of query based on the same understanding. So, this is just another variant.
Check the updated demo fiddle


text:
Q: TeamCity command line build step can not find files So, when I attempt to run a script file in a TeamCity build step (Command line build step) I get the following error:
Step 1/8: Download provisioning profile (script file) (Command Line)
[12:23:07][Step 1/8] Starting: /Applications/TeamCity/buildAgent/work/83a21295522e711a/TeamCityCustomBuildScripts/DownloadProvisioningProfile.sh
[12:23:07][Step 1/8] in directory: /Applications/TeamCity/buildAgent/work/83a21295522e711a/Project
[12:23:07][Step 1/8] Cannot run process /Applications/TeamCity/buildAgent/work/83a21295522e711a/TeamCityCustomBuildScripts/DownloadProvisioningProfile.sh : file not found
[12:23:07][Step 1/8] Step Download provisioning profile (script file) (Command Line) failed with unexpected error

I can find and run the script manually at the exact place the build step tells me it can not find it.
What could be wrong here?

A: As commented, this appears to be a permission problem. Either on the file itself, or on one of the directories.
Which user does the teamcity agent run as?
Does that user have full access to the desired location?
Change the permissions so that the agent has access to the script and it should work.

A: It was apparently line endings.
I had created the .sh file on windows with the #!/bin/bash shebang in the first line but the interpreter could not be found since the line was not terminated properly.
The solution was changing the line endings on my windows machine (using Notepad++ Edit -> EOL Conversion -> Unix LF)


text:
Q: "Rest Assured" requests log: Duplicate requests prints I am working with InteliJ although I don't know if that is important...
When I debug a my code which uses "Rest Assured", every request is being printed twice to the Intelij Run\Debug window.
For example:
@testR
Feature: tests Feature
Run Before Feature
**Request method:   POST**
Request URI:    https://10.188.10.30:443/auth/api/login
Proxy:          <none>
Request params: <none>
Query params:   <none>
Form params:    username=admin
                password=admin
**Request method:   POST**
Request URI:    https://10.188.10.30:443/auth/api/login
Proxy:          <none>
Request params: <none>
Query params:   <none>
Form params:    username=admin
                password=admin
10:34:44: Step: Given Login to tenant "system" with username "admin" and password "admin"(Scenario: New Login)

I defined my requestSpecification as:
    requestSpecification =
            RestAssured
                    .with()
                    .baseUri(baseUri)
                    .port(port)
                    .filter(new ResponseLoggingFilter())
                    .filter(new RequestLoggingFilter())
                    .log().all();

A: Use either only one
 .filter(new RequestLoggingFilter())
                .log().all();


text:
Q: Can't connect mongoDB database to Atlas due to server and shell mismatch have a Node.js app deployed on Heroku and now I am trying to connect the database. I ran all steps smoothly until the time I had to connect them through Terminal using mongo "mongodb+srv://<app name>-da9ev.mongodb.net/test"  --username admin. The answer I received was intriguing because it said the shell and server do not match (and they do, tested that several times) and that there was an implicit session running:
cassiano$ mongo "mongodb+srv://<app name>-hugcu.gcp.mongodb.net/test"  --username admin
MongoDB shell version v4.2.1
Enter password:
connecting to: mongodb://<app name>-shard-00-00-hugcu.gcp.mongodb.net:27017,<app name>-shard-00-01-hugcu.gcp.mongodb.net:27017,<app name>-shard-00-02-hugcu.gcp.mongodb.net:27017/test?authSource=admin&compressors=disabled&gssapiServiceName=mongodb&replicaSet=<app name>-shard-0&ssl=true
2019-11-06T11:45:03.277+0100 I  NETWORK  [js] Starting new replica set monitor for <app name>-shard-0/<app name>-shard-00-00-hugcu.gcp.mongodb.net:27017,<app name>-shard-00-01-hugcu.gcp.mongodb.net:27017,<app name>-shard-00-02-hugcu.gcp.mongodb.net:27017
2019-11-06T11:45:03.278+0100 I  CONNPOOL [ReplicaSetMonitor-TaskExecutor] Connecting to <app name>-shard-00-01-hugcu.gcp.mongodb.net:27017
2019-11-06T11:45:03.278+0100 I  CONNPOOL [ReplicaSetMonitor-TaskExecutor] Connecting to <app name>-shard-00-02-hugcu.gcp.mongodb.net:27017
2019-11-06T11:45:03.278+0100 I  CONNPOOL [ReplicaSetMonitor-TaskExecutor] Connecting to <app name>-shard-00-00-hugcu.gcp.mongodb.net:27017
2019-11-06T11:45:03.402+0100 I  NETWORK  [ReplicaSetMonitor-TaskExecutor] Confirmed replica set for <app name>-shard-0 is <app name>-shard-0/<app name>-shard-00-00-hugcu.gcp.mongodb.net:27017,<app name>-shard-00-01-hugcu.gcp.mongodb.net:27017,<app name>-shard-00-02-hugcu.gcp.mongodb.net:27017
Implicit session: session { "id" : UUID("5987a296-2121-41ac-b671-0a57fda6da7a") }
MongoDB server version: 4.0.13
WARNING: shell and server versions do not match
MongoDB Enterprise <app name>-shard-0:PRIMARY>

Can someone help me to debug this? I can't say if its a version problem, some unfinished session or what. Thanks in advance for the availability
PS: Atlas documentation link containing URI option


text:
Q: Custom format integer as date in DataGrid I have an integer field in my database that contains a date value in the form yyyyMMdd. Is it possible to parse this as a date in the form dd/MM/yyyy as bound to a datagrid?
Currently the field is bound like this:
<asp:boundcolumn datafield="access_date" headertext="Last logged on"></asp:boundcolumn>

A: Why don't you use Date for dates in database ?
You can convert int to datetime using following sample code:
var sdate = intdate.ToString();
var date = DateTime.ParseExact(sdate, "yyy/MM/dd", CultureInfo.InvariantCulture);

A: Thanks to gor for guiding me through this.
His answer in itself was not the entire solution, but after some commenting back and forth, I ended up with a good solution.
Instead of using a asp:boundcolumn in the grid, I had to use asp:templatecolumn and display it through a binding expression (like gor explained in his comment, although I think he based his answer on using the asp:listview control, while I use the old asp:datagrid control).
In the <columns> collection of the asp:datagrid control:
<asp:TemplateColumn headertext="Last logged on" >
<ItemTemplate><%#DateStringFromInt(Eval("access_date"))%></ItemTemplate>
</asp:TemplateColumn>

In the code-behind:
protected string DateStringFromInt(object value)
{
    DateTime date;
    if (DateTime.TryParseExact(value.ToString(), "yyyyMMdd",
        CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal,
        out date))
    {
        return date.ToString("dd/MM/yyyy");
    }
    return value.ToString(); //Return original if not expected format
}


text:
Q: How do you set the "python" command to point to python2 instead of python3? Due to my own stupidity, I somehow set the python command to run python 3 instead of the default python 2. How do I undo this? I am on Ubuntu 18.04.
$ python -V
Python 3.7.6
$ python3 -V
Python 3.7.6

A: You can change the alias python="/usr/bin/python2.7",for example :
alias python="/usr/bin/python3.3"
python
Python 3.3.3 (v3.3.3:c3896275c0f6, Nov 16 2013, 23:39:35)

You can also add this line in your .bashrc file
echo "alias python=/usr/bin/python3.3" >> ~/.bashrc

A: You can list all the version of Python installed and change the default Python version Try the following commands on terminal.
$:~# update-alternatives --config python
There are 4 choices for the alternative python (providing /usr/local/bin/python).

  Selection    Path                Priority   Status
------------------------------------------------------------
  0            /usr/bin/python3     4         auto mode
  1            /usr/bin/python2.7   2         manual mode
* 2            /usr/bin/python3     4         manual mode
  3            /usr/bin/python3.7   3         manual mode
  4            /usr/bin/python3.8   4         manual mode

Press <enter> to keep the current choice[*], or type selection number: 4
update-alternatives: using /usr/bin/python3.8 to provide /usr/local/bin/python (python) in manual mode

Set the default python version using python version.
Finally, you can check the success of command as below.
root@kali:~# python --version
Python 3.8.2

It should show Python 2.x in your case.

A: On most Unix-Linux systems, python is a link or a symbolic link in /usr/bin or /usr/local/bin. You should search where it is with type python and control what it is.
If it is a link or a symlink, just remove it and make it point to your installation of python 2.

A: Use type python to check what it points to, then check your .bashrc for two things:

*

*whether the path from type python is somewhere included in PATH

*whether you defined an alias for python somewhere

A: To install python2, run:
sudo apt install python-minimal
To run python2,
python2


text:
Q: Mongo Db : elemMatch query on multiple array Please find below document structure of mongo Db
{ _id : 0,
   name : "Employee1",
   distributionList :[ { dlname : "ALLEmployee"}, {dlname:"financeall"} ],
   csrActivity : [ {activityname : "blooddonation"}, {activityname : "tree plantation"} ]

}

I want list of employee belonging to financeall distribution list and opted to volunteer tree plantation CSR activity.
Expected resultset as below
{ _id : 0,
   name : "Employee1",
   distributionList :[{dlname:"financeall"} ],
   csrActivity : [  {activityname : "tree plantation"} ]
}

But so far able to achieve below output from query
Query :
db.employee.find(
{name : "Employee1"},
{distributionList : {$eleMatch : {dlname : "financeall"}}}
)

Output :
{ _id : 0,
   name : "Employee1",
   distributionList :[{dlname:"financeall"} ]
}

Using $elemMatch to get the desired output but unable to find how to use it on multiple array within same document. Also tried certain combination but unable to get desired result.
Below query tried but not getting desired output
db.employee.find(
   {name : "Employee1"},
   {distributionList : {$eleMatch : {dlname : "financeall"}}},
   {csrActivity: {$eleMatch : {activityname : "tree plantation"}}}
)

Any help will be highly appreciated

A: You only misspelled the projection operator $elemMatch
The correct query is:
db.employee.find(
  {
    name: "Employee1"
  }, {
    distributionList: {
        $elemMatch: {
            dlname: "financeall"
        }
    },
    csrActivity: {
        $elemMatch: {
            activityname: "tree plantation"
        }
    }
  }
)


text:
Q: Execute powershell script on webserver when page is accessed I have a windows 7 Pro computer that is running XAMPP (apache, php).
What I need to do is execute a batch or powershell command on this computer (host) when a remote computer accesses a certain webpage on it.  is this possible?

A: Yes, there is a PHP function that will execute shell code.
Have a look in their documentation
Function: exec("command here");


text:
Q: Laravel Join tables and group by sum query too slow I am using Laravel query builder to get desired results from database. The following query if working perfectly but taking too much time to get results. Can you please help me with this?
select
  `amz_ads_sp_campaigns`.*,
  SUM(attributedUnitsOrdered7d) as order7d,
  SUM(attributedUnitsOrdered30d) as order30d,
  SUM(attributedSales7d) as sale7d,
  SUM(attributedSales30d) as sale30d,
  SUM(impressions) as impressions,
  SUM(clicks) as clicks,
  SUM(cost) as cost,
  SUM(attributedConversions7d) as attributedConversions7d,
  SUM(attributedConversions30d) as attributedConversions30d
from
  `amz_ads_sp_product_targetings`
  inner join `amz_ads_sp_report_product_targetings` on `amz_ads_sp_product_targetings`.`campaignId` = `amz_ads_sp_report_product_targetings`.`campaignId`
  inner join `amz_ads_sp_campaigns` on `amz_ads_sp_report_product_targetings`.`campaignId` = `amz_ads_sp_campaigns`.`campaignId`
where
  (
    `amz_ads_sp_product_targetings`.`user_id` = ?
    and `amz_ads_sp_product_targetings`.`profileId` = ?
  )
group by
  `amz_ads_sp_product_targetings`.`campaignId`

Result of Explain SQL

id  select_type table                   type    possible_keys   key     key_len     ref                         rows    Extra
1   SIMPLE      amz_ads_sp_report_product_targetings    ALL campaignId  NULL        NULL        NULL                            50061   Using temporary; Using filesort
1   SIMPLE      amz_ads_sp_campaigns            ref campaignId  campaignId  8       pr-amz-ppc.amz_ads_sp_report_product_targetings.ca...   1
1   SIMPLE      amz_ads_sp_product_targetings       ref campaignId  campaignId  8       pr-amz-ppc.amz_ads_sp_report_product_targetings.ca...   33  Using where

A: Your query could benefit from several indices to cover the WHERE clause as well as the join conditions:
CREATE INDEX idx1 ON amz_ads_sp_product_targetings (
    user_id, profileId, campaignId);

CREATE INDEX idx2 ON amz_ads_sp_report_product_targetings (
    campaignId);

CREATE INDEX idx3 ON amz_ads_sp_campaigns (campaignId);

The first index idx1 covers the entire WHERE clause, which might let MySQL throw away many records on the initial scan of the amz_ads_sp_product_targetings table.  It also includes the campaignId column, which is needed for the first join.  The second and third indices cover the join columns of each respective table.  This might let MySQL do a more rapid lookup during the join process.
Note that selecting amz_ads_sp_campaigns.* is not valid unless the campaignId of that table be the primary key.  Also, there isn't much else we can do speed up the query, as SUM, by its nature, requires touching every record in order to come up the result sum.


text:
Q: Secure copy uucp style I often have the case that I have to make a lot of hops to the remote host, just because there is no direct routing between my client and the remote host. When I need to copy files from a remote host two or more hops away, I always have to:
client$ ssh host1
host1$ ssh host2
host2$ scp host3:/myfile .
host2$ exit
host1$ scp host2:myfile .
host1$ exit
client$ scp host1:myfile .

Back when uucp still was being used this would be as simple as a
uucp host1!host2!host3 /myfile .

I know that there's uucp over ssh, but unfortunately I don't have the proper privileges on those machines to set it up. Also, I'm not sure if I really want to fiddle around with customer's machines.
Does anyone know of a method doing this tasks without the need to setup a lot of tunnels or deploying new software to remote hosts? Maybe some kind of recursive script which clones itself to all the remote hosts, doing the hard work for me?
Assume that authentication takes place with public keys and that all hosts do SSH Agent Forwarding.
Edit: I'm not looking for a way to automatically forwarding my interactive sesssion to the nexthop host. I want a solution to copy files bangpath-style using scp via multiple hops without the need to install uucp on any of those machines. I don't have the (legal) rights or the privileges to make permanent changes to the ssh-config. Also, I'm sharing this username and hosts with a lot of other people.
I'm willing to hack up my own script, but I wanted to know if anyone knows something which already does it. Minimum-invasive changes to hosts on the bangpath, simple invocation from the client.
Edit 2: To give you an impression of how it's properly been done in interactive sessions, have a look at the GXPC clustershell. This is basically a Python-script, which spwans itself over to all remote hosts which have connectivity and where your ssh-key is installed. The great thing about it is, that you can tell "I can reach HostC via HostB via HostA." It just works. I want to have this for scp.

A: ssh host1 ssh host2 ssh host3 cat /myfile > myfile ? :)
UPD. (2014-01-20): Recently I came across man dbclient which mentions: «…

-B endhost:endport — "Netcat-alike" mode, where Dropbear will connect to the given host, then create a forwarded connection to endhost. This will  then  be  presented as dbclient's standard input/output.
Dropbear  will  also  allow  multiple "hops" to be specified, separated by commas. In this case a connection will be made to the first host, then a TCP forwarded connection will be made through that to the second host, and so on. Hosts other than the final destination will not see anything other than the encrypted SSH stream.  A port for a host can be specified with a slash (eg matt@martello/44 ).  This syntax can also be used with scp or rsync (specifying dbclient as the ssh/rsh command). A file can be "bounced" through multiple SSH hops, eg
         scp -S dbclient matt@martello,root@wrt,canyons:/tmp/dump .

Note that hostnames are resolved by the prior hop (so "canyons" would be resolved by the host "wrt") in the example above, the same  way  as other -L TCP forwarded hosts are. Host keys are checked locally based on the given hostname.

A: If your version of scp comes from a reasonably recent version of openssh then you may be able to use the ProxyJump option: scp -o Proxyjump=firsthop.example.com,secondhop.example.com /path/to/file  destination.example.com:/where/to/put/it This relies on forwarding one ssh connection over the other but in a transient fashion rather than by setting up a listening port.  Because of this it doesn't require any special set up on the intermediate hosts other than sshd allowing the ability to make connections to remote ports.

A: Even though you specifically mention that this is not what you are looking for, I'm going to insist that you try this because setting up a script on every host in the path to your destination is more complex and time consuming.
If you are on host laptop and you wish to copy something to host webserver, but you can access webserver only through companygatweay.org, then all you need to do is:
laptop$   ssh -L4444 companygateway.org:webserevr:22

This will open up port 4444 on your local machine directly through to the webserver on port 22.
copying with scp to webserver would look like:
laptop$    scp -P 4444 /some/files/here localhost:/to/some/files/on/webserver

to copy from the webserver:
laptop$    scp -P 4444 localhost:/tmp/remote/files /home/localusername/downloads


text:
Q: Customize label in stacked column chart extjs
i make columns chart like this but this make mismatch when data are low, that time i need to display it ouside ot the chart
like

is this possible to make outside label in extjs stacked columns chart..
code is here
ar store = Ext.create('Ext.data.JsonStore', {
    fields: ['name', 'data1', 'data2', 'data3', 'data4', 'data5'],
    data: [
        { 'name': 'metric one', 'data1': 4, 'data2': 12, 'data3': 14, 'data4': 8, 'data5': 13 },
        { 'name': 'metric two', 'data1': 7, 'data2': 8, 'data3': 16, 'data4': 10, 'data5': 3 },
        { 'name': 'metric three', 'data1': 5, 'data2': 2, 'data3': 14, 'data4': 12, 'data5': 7 },
        { 'name': 'metric four', 'data1': 2, 'data2': 14, 'data3': 6, 'data4': 1, 'data5': 4},
        { 'name': 'metric five', 'data1': 7, 'data2': 4, 'data3':4, 'data4': 13, 'data5': 4 }
    ]
});

Ext.create('Ext.chart.Chart', {
    renderTo: Ext.getBody(),
    width: 500,
    height: 300,
    animate: true,
    store: store,
    axes: [
        {
            type: 'Numeric',
            position: 'left',
            fields: ['data1', 'data2', 'data3'],
            label: {
                renderer: Ext.util.Format.numberRenderer('0,0')
            },
            title: 'Sample Values',
            grid: true,
            minimum: 0
        },
        {
            type: 'Category',
            position: 'bottom',
            fields: ['name'],
            title: 'Sample Metrics'
        }
    ],
    series: [
        {
            type: 'column',
            axis: 'left',
            highlight: true,

            label: {
                display: 'middle',
                'text-anchor': 'middle',
                field: ['data1', 'data2', 'data3'],
                renderer: Ext.util.Format.numberRenderer('0'),
                orientation: 'horizontal',
                contrast: true,
                color: '#333'
                field: ['data1', 'data2', 'data3'],

            },
stacked: true,
            xField: 'name',
            yField: ['data1', 'data2', 'data3']
        }
    ]
});

A: I'm Not sure about right side but, using this code, your data will show on chart, and if chart value are high, then data will go under chart, and also show Y-axis and X-axis data on mouse Hover.
    |-----|
    |  89 |                  50
    |     |      20       |-----|
    |     |    |-----|    |     |
    |     |    |     |    |     |
    |     |    |     |    |     |
    |     |    |     |    |     |

My Code (I use extjs 4.0 chart in extjs 3.4, so I need "ext-all-sandbox.js")
Ext4.create('Ext4.chart.Chart',{
 renderTo: 'divAverageChart2',
 width: 450,
 height: 380,
 style: 'background:#fff',
 animate: true,
 store: AverageChart2Store,
    items: [{
      type  : 'text',
      cls:'bold',
     // text  : 'Performance Matrix of Student Mayur Macwan Grade : 5th',
      font  : '14px Calibri',
      width : 100,
      height: 30,
      x : 80, //the sprite x position
      y : 370  //the sprite y position
   }],
    legend: {
         position: 'bottom',
         labelFont: 'tahoma'
    },
 axes: [{
    type: 'Numeric',
    position: 'left',
    minimum: 0,
    fields: ['data1'],
    label: {
       renderer: Ext.util.Format.numberRenderer('0')
    }
},{
    type: 'Category',
    position: 'bottom',
    fields: ['name']
}],
series: [{
    type: 'column',
    axis: 'left',
    showInLegend: false,
    xField: 'name',
    yField: ['data1'],
    title: ['Top 5 Products'],
    label: {
         display: 'outside',
         'text-anchor': 'middle',
         field: ['data1','data2','data3','data4'],
         renderer: Ext.util.Format.numberRenderer('0,0'),
         orientation: 'horizontal',
         color: '#333'
    },
    tips: {
      trackMouse: true,
      width: 140,
      height: 28,
      renderer: function(storeItem, item) {
        this.setTitle(item.value);
      }
    }
}],
    listeners: {
        afterrender: function(view){
            Ext.each(view.legend.items, function(item) {
                item.un("mousedown", item.events.mousedown.listeners[0].fn);
            })
        }
    }
});

Other Way (This works for me)
    <text id="ext-sprite-1222" style="font: 11px Helvetica,sans-serif;" zIndex="0" font="11px Helvetica, sans-serif" fill="#333" text-anchor="middle" text="37" x="110.206" y="228" transform="matrix(1,0,0,1,0,0)" hidden="false">
<tspan x="171.206" dy="3.5">37</tspan>
</text>

Here you have to change X-axis and Y-axis value as per your need.
change X-axis and dy value in below code as per your need code.
<tspan x="171.206" dy="3.5">37</tspan>


text:
Q: How to make QRadioButton to "read-only"? I want to use QRadioButton for displaying some state, which cannot be changed by the user; i.e. to use it in a "read-only mode". Which is better to use:
setCheckable() or empty functionality of    click()?

A: You can disable mouse event by:
wgt->setAttribute(Qt::WA_TransparentForMouseEvents, true);

When enabled, this attribute disables the delivery of mouse events to the widget and its children. Mouse events are delivered to other widgets as if the widget and its children were not present in the widget hierarchy; mouse clicks and other events effectively "pass through" them. This attribute is disabled by default.


text:
Q: Quadratic field such that a certain finite set of primes split Given a finite set $S$ of primes, is it possible to find an imaginary quadratic field $K$ such that all primes in $S$ are split completely in $K$?

A: Sure. Let me just assume WLOG that $S$ contains $2$. Let $D$ be squarefree. If $D \equiv 1 \bmod 4$, then $\mathbb{Q}(\sqrt{D})$ has ring of integers $\mathbb{Z}[x]/(x^2 - x - \frac{D-1}{4})$. Then $2$ splits if and only if $D \equiv 1 \bmod 8$. An odd prime $p$ splits if $D \equiv 1 \bmod p$, so it suffices to find a (negative) squarefree $D \equiv 1 \bmod 8$ such that $D \equiv 1 \bmod p$ for all odd primes $p \in S$. In fact a prime with this property exists by Dirichlet's theorem.


text:
Q: Responsive grid without streching I would like to create a grid with as many elements as possible in its width but without stretching the grid elements to fit 100% of the window.
So I'm using CSS grid with auto fill which works almost as I'd like.
I would like my grid elements not to be stretched to fill the whole page (so they have a static width), but to always have the same width, and if there is not enough space for a grid element, fill it with white space to the right (instead of stretching them so it fits 100% of the window).
here is my code:

.grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(10em, 1fr));
  }

  .cadres {
    background-color: red;
  }
.cadres:nth-child(2n+1){

  background-color: yellow
}

      a

      b

c

d

e

What I would like :

Thanks for the help

A: I know this is late, but for anyone else with this problem who would prefer to stick to grid rather than flex:
I ran into a similar issue where I used grid to align a few boxes of text but they would all stretch if one of them grew due to their content
I found using align-self: was the solution for me. By aligning the box that was growing to start then it would no longer stretch for the other one.
I found my solution here: https://css-tricks.com/snippets/css/complete-guide-grid/

A: Use flex box for this. Change display: grid; to display: flex and add flex-wrap: wrap;. With this, when your inner div will be too large to fit the remaining space, they will be shifted to the bottom row.
Here is the documentation of Flex Box
Here is the example:

.grid {
  display: flex;
  flex-wrap: wrap;
}

.cadres {
  background-color: red;
  width: 40%;
  margin: 5px;
}

.cadres:nth-child(2n+1) {
  background-color: yellow;
  width: 40%;
  margin: 5px;
}

      a

      b

c

d

e


text:
Q: Do not show comment flags in "declined in last 7 days" view I went to check my flag history, only to see this big banner:

I clicked on the button, and saw eight declined flags. Five of those were comment flags, which do not count towards bans (reconfirmed today by Shog).
I was testing out bugs in the new comment flagging functionality in order to report them, and initially thought that the declined comment flags (you can't retract comment flags) were the ones that caused me to get banned. However, according to the above links, this isn't the case.
Can we exclude comment flags from the view triggered by the banner, since those don't count towards bans?

A: I feel like this misses the point of the warning, which is to examine your declined flags to see if you can identify areas where your communication is ineffective.
...and not to identify areas in which miscommunication is ok.


text:
Q: How to subtract two hex color in C#? I want to subtract two hexadecimals in C#. How can I do that?
Something like this :
      #7ffffff - #000123

A: Hexadecimal literals are prefixed with 0x as in 0x7fffff. So you could assign each value to an integer and subtract them as such:
int color1 = 0x7fffff;
int color2 = 0x000123;

int difference = color1 - color2;

This is admittedly a naïve approach which will not work in a lot of cases, although given your comment, I'm thinking it will be sufficient. Consider what would happen if you subtracted a color with a larger attribute from a smaller, as in:
0xFF20FF - 0x003000 = 0xFEE0FF

I'm thinking that you would not want to borrow 1 from red, adding 0xFF to green. In a situation like that, I might want the result to be 0xFF00FF. In that case, you would want a method that subtracts the individual color elements with a floor of zero, as in:
int SubtractColors( int color1, int color2 )
{
    int red = Math.Max( 0,( color1 >> 16 ) - ( color2 >> 16 ) );
    int green = Math.Max( 0, ( ( color1 >> 8 ) & 0xFF ) - ( ( color2 >> 8 ) & 0xFF ) );
    int blue = Math.Max( 0, ( color1 & 0xFF ) - ( color2 & 0xFF ) );

    return ( red << 16 ) + ( green << 8 ) + blue;
}

We're doing some "bit bashing" here which a lot of less experienced programmers are not familiar with. If the code above doesn't entirely make sense, you may want to learn about:
>> right shift operator
<< left shift operator
& bitwise AND operator


text:
Q: Scale dash pattern with line width I would like to have dash patterns which scale proportionally to the active line width like shown in the following example:
\documentclass[tikz]{standalone}
\newdimen\gpdashlength
\begin{document}

\begin{tikzpicture}
\pgfsetlinewidth{2pt}
\gpdashlength=0.5\pgflinewidth
\tikzset{gp path/.style={dash pattern=on 7.5\gpdashlength off 7.5\gpdashlength}}

\draw[gp path] (1.012,3.528)--(11.947,5.469);

\pgfsetlinewidth{4pt}
\gpdashlength=0.5\pgflinewidth
\draw[gp path] (1.012,2.557)--(11.947,6.440);
\end{tikzpicture}
\end{document}

This works fine, but I would like to set some property of gp path once, so that it always selects the current line width scaled by some factor. I tried using gp path/.code, but that has no effect. The following document doesn't show anything:
\documentclass[tikz]{standalone}
\newdimen\gpdashlength
\begin{document}

\begin{tikzpicture}
\tikzset{gp path/.code={\gpdashlength=0.5\pgflinewidth},
         gp path/.style={dash pattern=on 7.5\gpdashlength off 7.5\gpdashlength}}

\pgfsetlinewidth{2pt}
\draw[gp path] (1.012,3.528)--(11.947,5.469);

\pgfsetlinewidth{4pt}
\draw[gp path] (1.012,2.557)--(11.947,6.440);
\end{tikzpicture}
\end{document}

It seems to me like the .code part is executed after the .style so that \gpdashlength isn't set properly.
Whats wrong with the second example?
Note that this is supposed to be used for gnuplot's lua tikz terminal, so an overall restructuring of the example may not be possible. That means, that the \pgflinewidth cannot be contained in the dash pattern definition, since this is located in a system-wide style file, and the scaling factor between the line width and the dash pattern can be changed from document to document.

A: The problem is that \gpdashlength is a length, not a macro, and then it is not expanded, but replaced by a length value. So, if you want to change that value, an assignment has to be made before the length is evaluated, and you cannot do it inside .code key because, as you guessed, it is not executed before evaluating the style.
A solution is to change \gpdashlength from a lengt to a macro, i.e:
\def\gpdashlength{0.5*\pgflinewidth}

This way, when this macro is found as part of the dash pattern, it is expanded, so the current value of \pgflinewidth is used at that point. You have to change the dash pattern to include the multiplication sign (*) before \gpdashlength. I.e:
\documentclass[tikz]{standalone}
\begin{document}

\def\gpdashlength{0.5*\pgflinewidth}
\begin{tikzpicture}
\tikzset{
         gp path/.style={dash pattern=on 7.5*\gpdashlength
                                     off 7.5*\gpdashlength}}

\draw[thin, gp path] (1.012,3.528)--(11.947,5.469);
\draw[very thick, gp path] (1.012,2.557)--(11.947,6.440);
\end{tikzpicture}
\end{document}

Which produces:

Note that this works because tikz parses the mathematical expression containing *. That is, after all expansions are performed, tikz "sees" the following dash pattern (assuming that, for example, \pgflinewidth is 0.8pt in this example):
 dash pattern=on 7.5*0.5*0.8pt off 7.5*0.5*0.8pt

Tikz parser is able to evaluate that product. Otherwise this won't work. You cannot generally change a length register by a macro as I did here.


text:
Q: What does a greevil egg contain? What are the all of the different greevils that can hatch from a greevil egg?  What essence combinations are required for each, and is it even possible to still get them after Diretide has ended?

A: Here is a great guide with images.
You can keep your essences in your inventory after diretide ends,but I don't know if you can trade them or what happens with your egg if you don't use it.
Red

*

*Ferocious Egg (Red type 1) : 1 Exort, Hatch outcome : Red Greevil Level 1

*Brutal Egg (Red type 2) : 2 Exort Essence, Hatch outcome : Red Greevil Level 2

*Merciless Egg (Red type 3) : 3 Exort Essence, Hatch outcome : Red Greevil Level 3

Yellow

*

*Anxious Egg (Yellow type 1) : 1 Wex, Hatch outcome : Yellow Greevil Level 1

*Eager Egg (Yellow type 2) : 2 Wex Essence, Hatch outcome : Yellow Greevil Level 2

*Spirited Egg (Yellow type 3) : 3 Wex Essence, Hatch outcome : Yellow Greevil Level 3

Blue

*

*Stubborn Egg (Blue type 1) : 1 Quas, Hatch outcome : Blue Greevil Level 1

*Resolute Egg (Blue type 2) : 2 Quas Essence, , Hatch outcome : Blue Greevil Level 2

*Determined Egg (Blue type 3) : 3 Quas Essence, Hatch outcome : Blue Greevil Level 3

Gren

*

*Covetous Egg (Green type 1) : 2 Quas/ 2 Wex, Hatch outcome : Green Greevil Level 2

*Greedy Egg (Green type 2) : 3 Quas/ 3 Wex, Hatch outcome : Green Greevil Level 3

Orange

*

*Ravenous Egg (Orange type 1) : 2 Exort / 2 Wex, Hatch outcome : Orange Greevil Level 2

*Voracious Egg (Orange type 2) : 3 Exort / 3 Wex, Hatch outcome : Orange Greevil Level 3

Purple

*

*Cruel Egg (Purple type 1) : 2 Exort / 2 Quas, Hatch outcome : Purple Greevil Level 2

*Wicked Egg (Purple type 2) : 3 Exort / 3 Quas, Hatch outcome : Purple Greevil Level 3

White

*

*Blessed Egg (White type 1) : 2 Quas/2 Wex/2 Exort, Hatch outcome : White Greevil Level 2

*Seraphic Egg (White type 2) : 3 Quas/3 Wex/ 3 Exort, Hatch outcome : White Greevil Level 3 (Source, Confirmed Thanks Treguard)

Black

*

*Dreaded Egg (Black type 1) : 1 Shadow Essence, Hatch outcome : Black Greevil Level 0

Natural

*

*Imbued Egg (Natural type 1): 1 essence of any type except shadow OR All other combinations, Hatch outcome : Normal Greevil Level 1 (Naked)


text:
Q: setting styleName attribute in ui.xml overwrites primaryStyleName set in constructor of widget I've written a custom widget with its own set of styles. These styles are defined in a little resource interface contained in the widget, and applied in the constructor of the widget.
I'd like to use the widget in a uibinder xml file, and apply additional styles there.  Unfortunately, setting the styleName attribute seems to remove the styles applied in the constructor, and indeed the setStyleName javadoc indicates that it clears other style names.
What's the best solution here? I could override setStyleName, but that takes away options later.  Is there a way to call addStyleName instead of setStyleName from the ui.xml file?

A: Did you try addStyleNames in your ui binder file?


text:
Q: Map With List is not holding multiple values per key I Have a map that includes a URL as the Key and a List of a custom object for the value. When two objects both have the same URL I would expect them both to be added to the List In the map. Right now the code is only returning 1 value for the URL. I originally had this functioning as a normal map that returns one value but Needed to add a way to tell if there were more than one Object for each URL. Code below.
        Set<String> urls = new Set<String>();
        for(Integer i=0; i < triggerNew.size(); i++){
        Case newCase = triggerNew[i];
            if(newCase.AppURL__c != null){
                urls.add(newCase.AppUrl__c); }
        }
    Map<String, List<MobileCloud_Website__c>> websites = new Map<String, List<MobileCloud_Website__c>>();
    List<MobileCloud_Website__c> webbys = new List<MobileCloud_Website__c>();

        for (MobileCloud_Website__c website : [
            SELECT Account__c, URL__C
            FROM MobileCloud_Website__c
            WHERE URL__c IN :urls AND Account__r.Account_Type_new__c != 'Inactive Customer'
        ]) {
            webbys.add(website);
            websites.put(website.URL__c, webbys);
        System.debug(webbys);
        }
    System.debug(websites);
    for(Integer i=0; i < triggerNew.size(); i++){
        Case newCase = triggerNew[i];
        List<MobileCloud_Website__c> website = websites.get(newCase.AppUrl__c);
        System.debug(website.size());
        If(website.size() == 1){
        newCase.AccountId = website[0].Account__c;
        }
    }

}

A: You need to create separate List objects for each key. Here's the pattern I use:
MobileCloud_Website__c[] webbys;
for (MobileCloud_Website__c website : [
    SELECT Account__c, URL__C
    FROM MobileCloud_Website__c
    WHERE URL__c IN :urls AND Account__r.Account_Type_new__c != 'Inactive Customer'
]) {
    if((webbys = websites.get(website.URL__c)) == null) {
        websites.put(website.URL__c, webbys = new MobileCloud_Website__c[0]);
    }
    webbys.add(website);
}


text:
Q: Doctrine Native query inside query builder join I am working on a query on Doctrine 2 (with Symfony 2.8)
I have this query giving me relevant info:
    $qb = $this->createQueryBuilder('ea');
            $qb->join('ea.entity_b', 'eb')
                ->join('ea.entity_c', 'ec')
                ->join('ec.entity_d', 'ed')
                ->join('MainBundle:Entity_E', 'ee','WITH', 'ee.column1 = ea.id')
                ->join('MainBundle:Entity_F', 'ef', 'WITH', 'ea.column1 = ef.id');

Now, I need to add extra info to that query, but it comes from a native SQL, something like this:
SELECT * FROM DS ORDER BY id DESC LIMIT 1

And make sure that the id of the result from the native query is equal to ef.id
I hope I made any sense.
Thanks

A: Do you know DQL ?
Similar to SQL but adapted for Doctrine.
http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/dql-doctrine-query-language.html
You can then do queries like :
<?php
$query = $em->createQuery("SELECT u FROM User u JOIN u.address a WHERE a.city = 'Berlin'");
$users = $query->getResult();


text:
Q: JS- Call a method from a generated button for a specific object I m new at coding , and I m searching for a way to launch a specific prototype method for each object of my array from a generated button
I've got json data to loop , and include each object on a js array.
//My data got 3 objects
var readArr = JSON.parse(myData)

var js_arr = [];

// loop on the array of object
for (var i = 0; i < readArr.length; i++) {

    var generatedObject = new Object();

//init method from prototype
    generatedObject.init(readArr[i].prop1, readArr[i].prop2, readArr[i].prop3, readArr[i].prop4, readArr[i].prop5,
            readArr[i].prop6, readArr[i].prop7, readArr[i].prop8);

    js_arr.push(generatedObject);

//generated a div which will contains a button for each occurence
    var newCntent = document.createElement('div');
    newCntent.id = readArr[i].prop1 + i;
    newCntent.className = "cntent";
    document.getElementById('zone_btn').appendChild(newCntent);

//create a button inside the div
    var newBtn = document.createElement('div');
    newBtn.id = i + readArr[i].prop1;
    newBtn.className = "etalonBtn";
    newBtn.innerHTML = readArr[i].prop1;
    document.getElementById(newCntent.id).appendChild(newBtn);

I've got a prototype method on my Object class and what I want is launch that method for each object linked with a button.
The first generated button will launch the method for js_arr[0], the second for js_arr[2],...how to code the fact that when I click on the button , the method must be call by "the object of the array which permetted your creation"
I don't have any clue on the way I can do this I tried several things:
newBtn.addEventListener('click', function () {

       read_arr[i].DisplayUpdate();
    });

};

(returning read_arr[i] is not defined), so I just want to change that read_arr[i] by this now famous :"the object of the array which permetted your creation" !
 and I really need help on this...
Thank you by anticipation and sorry for this preschool english.

A: The issue is that when you're getting to the click function (i.e. - when actually clicking the button) you're already out of the loop, so js doesn't know what 'read_arr[i]' is.
You need to pass 'read_arr[i]' as a parameter to the function.
Basically something like this:
newBtn.addEventListener('click', function (object) {
       object.DisplayUpdate();
    },js_arr[i]);

This will change the function's signiture to also take a parameter- object, and also pass js_arr[i] as that parameter.
Hope that helps

A: you could also assign and bind the function to call when you create the button in your loop:
var newBtn = document.createElement('div');
    newBtn.id = i + readArr[i].prop1;
    newBtn.className = "etalonBtn";
    newBtn.innerHTML = readArr[i].prop1;
    newBtn.onclick = jsArr[i];


text:
Q: django-tastypie: Loading fields based on request I have a resources structure in tastypie similar to the following:
class UserResource(ModelResource):
    class Meta:
        queryset = User.objects.all()

class ActivityResource(ModelResource):
    class Meta:
        queryset = Activity.objects.all()

class UserActivityResource(ModelResource):
    user = fields.ToOneField(UserResource, 'user')
    activity = fields.ToOneField(ActivityResource, 'activity', full=True)

    class Meta:
        queryset = UserActivity.objects.all()
        filtering = {
            'user': ALL_WITH_RELATIONS,
            'activity': ALL_WITH_RELATIONS
        }

It is clearly a many to many objects relation.
Sometimes I want to retrieve the data from UserActivity using an specific id for this object, which gives me in the result the specific fields from UserActivity + User data related + Activity data related, which is pretty good, for example:
GET /api/v1/user_activity/{user_activity_id}/

Other times I want to retrieve the data from UserActivity based on, for example the id of the related User object, for example:
GET /api/v1/user_activity/?user={user_id}

This request works pretty good also.
Now, let's say that the {user_id} sent in the request has 10 related activities (ActivityResource) in the join object. So, when I look into the request execution, I can notice that the system is running the following queries to build the result:
select count(*) from user_activity where {filters} (building meta...ok)

And for each activity related (10 times):
select user_activity.* from user_activity where {filters} (getting user_activity data...ok)
select activity.* from activity where {filters} (getting activity data...ok)
select user.* from user where id={user_id} (getting user data...ok?)

The thing is, I already know the user used to find the related activities, then, I don't need to query again its data, and of course I am not interested in execute the same query 10 times!
So, the question is...
Is there any way to optimize the process, so I can activate/deactivate the use of the related field user depending on the request to avoid useless queries? or in other words, to modify the related objects of the resource on the fly ?
Thank you.
BTW: I'm using django1.4, django-tastypie 0.9.11


text:
Q: Run-time error '1004': Method 'Range' of object ' Worksheet' failed - VBA The below code works perfectly when I run it manually, but when I call it in a change event I get Run-time error '1004': Method 'Range' of object 'Worksheet failed.
I am just pasting some row data in a sheet and need this code to "fix" some data which would be otherwise hard to read:
Sub PortfolioFixer()
Dim ws As Worksheet, dataLastRow As Long, Cell As Range, MyCov As Range, MyRng As Range, MyID As Range, MyCurrent As Range
Set ws = ThisWorkbook.Worksheets("Portfolio")
Application.ScreenUpdating = False
dataLastRow = ws.Range("F" & Rows.Count).End(xlUp).Row
Set MyRng = ws.Range("F2:F" & dataLastRow)
Set MyID = ws.Range("B2:B" & dataLastRow)
Set MyCurrent = ws.Range("G2:G" & dataLastRow)
'   Loop through column B
For Each Cell In MyID
Cell.NumberFormat = "General"
Next Cell
'   Loop through column G
For Each Cell In MyCurrent
Cell.NumberFormat = "[$$-409]#,##0"
Next Cell
'   Loop through column F
For Each Cell In MyRng
If Cell = "" And Cell.Offset(0, 1) = 0 And (Cell.Offset(0, -2) = "BML Rate" Or Cell.Offset(0, -2) = "Availability") Then
            Cell = "Shopped"
ElseIf Cell = "" And Cell.Offset(0, 1) > 0 And (Cell.Offset(0, -2) = "BML Rate" Or Cell.Offset(0, -2) = "BML Availability") Then
            Cell = "Action Required"
ElseIf Cell >= 0 And (Cell.Offset(0, -2) = "BML Rate" Or Cell.Offset(0, -2) = "BML Availability") Then
Cell.NumberFormat = "0.00%"
 Else
End If
Next Cell
Application.ScreenUpdating = True
End Sub

It seems that everything has been referenced but Excel says no and cannot figure out why.


text:
Q: Transact SQL Pivot a Split String into appropriate columns My company is using a generic logging database among many products. To prevent the need for a lot of cross database queries some info is stored in delimited fields within the generic data columns for the logging.
I'm wanting to write query's on the data, but I'm unsure how to use Pivot/Unpivot to get the data into appropriate columns?
Below is a generic example using static data for what I'm wanting to do, but not sure how to do it. We unfortunately don't have the built in split string function in SqlServer 2016 so dbo.fnSplitString is my written equivalent which works fine.
 DECLARE @Columns TABLE (
     CustomerNumber VARCHAR(MAX) NOT NULL,
     FirstName VARCHAR(MAX) NOT NULL,
     LastName VARCHAR(MAX) NOT NULL);

/* This isn't valid SQL ... unsure how to get this to work */
INSERT INTO @Columns PIVOT SELECT * FROM dbo.fnSplitString('STUFF1,STUFF2,STUFF3',',');

SELECT * FROM @Columns;

Edit:
Using the examples here and https://technet.microsoft.com/en-us/library/ms177410(v=sql.105).aspx I was able to come up with a solution. The split string function also needs to output a position. This was inspired by one of the solutions below just 'OrdinalPosition' needed to be added to the function. The resulting query works.
DECLARE @Columns TABLE (CustomerNumber VARCHAR(MAX) NOT NULL, FirstName VARCHAR(MAX) NOT NULL, LastName VARCHAR(MAX) NOT NULL);

INSERT INTO @Columns select [0], [1], [2] from (SELECT position, splitdata FROM  dbo.fnSplitString('STUFF1,STUFF4,STUFF3',',')) split pivot (MAX(splitdata) FOR position in ([0],[1],[2])) piv;

SELECT * FROM @Columns;

A: Is this what you are looking for:
I just used "item" as column name. Replace it with the name corresponding to your name that is returned from fnSplitString function.
DECLARE @Columns TABLE (CustomerNumber VARCHAR(MAX) NOT NULL, FirstName
VARCHAR(MAX) NOT NULL, LastName VARCHAR(MAX) NOT NULL);

 INSERT INTO @Columns
select STUFF1,STUFF2,STUFF3 from (SELECT  item FROM
dbo.fnSplitString('STUFF1,STUFF2,STUFF3',',')) d
pivot ( max(item)  for item in (STUFF1,STUFF2,STUFF3) ) piv;

SELECT * FROM @Columns;

A: If your function fnSplitString returns a table then simply
INSERT INTO @Columns
SELECT * FROM dbo.fnSplitString('STUFF1,STUFF2,STUFF3',',')
PIVOT
(
MAX(ParsedValue)
FOR OrdinalPosition in ([0], [1], [2], [3])
) x


text:
Q: Trying to make a discord bot but on.message or message.content not working I want the bot to use the gpt-3 API to answer questions but for some reason on.message is not working
import openai
import discord

openai.api_key = "apikey"

client = discord.Client()

@client.event

async def on_ready():
 print('online')

async def on_message(message):

    if message.content.startswith("!ask"):
        print('I read the message')

        question = message.content[5:]

        response = openai.Completion.create(
            engine="text-davinci-002",
            prompt=f"{question}\n",
            temperature=0.7,
            max_tokens=1024,
            top_p=1,
            frequency_penalty=0,
            presence_penalty=0
        )

        await message.channel.send(response.choices[0].text)

client.run('token')

Everything works fine and the 'online' appears but after that i don't know what's happening since i am not getting any errors (Sorry if its something obvious i am just now learning)
the
client.run('token')
open.api_key="apikey"

are obviously replaced with the real ones in my code

A: You need to use @client.event for every event
@client.event
async def on_ready():
 print('online')

@client.event # <- this is new
async def on_message(message):
   # ...

A: If you want to register an event, you have to put the client.event decorator on top of the event functions. Your on_message function certainly doesn't have one, so just put one on it.
@client.event
async def on_message(message):
    ...


text:
Q: Call java class function in FTL - Apache I am trying to call a java class function in a ftl file of the same project:
Class:
public class ShoppingCart<statics> implements Iterable<ShoppingCartItem>{

public String testfct(){
return "Hello";
}

}

In the ftl file I want to call this function by using:
<fieldset>
    ${testfct}
</fieldset>

This doesn't work :-(


text:
Q: asp.net razor Model Binding Dynamic List in Form submission I am trying to create an order form for input.
I need the user to be able to add multiple line items then update. I was trying to
use the shopping cart class (where user creates   a cart item and adds a
 list item, multiple lines can be added to the list item).
I didn't get through with that. I am using asp.net razor am using
 webmatrix to build site. Webmatrix is saying that it doesnt recognise Cart().
@{
if (Session["cart"] == null)
{
Session["cart"] = new Cart();
}
Cart cart = (Cart)Session["cart"];

}

Product
Size
Price

@foreach (var item in cart.Items)
{

@item.ProductID
@item.Size
£@item.Price

}

Is there a better way to do this? All help is greatly appreciated

A: There IS a way to bind dynamic list elements
@foreach (i=0; i< cart.Items.count; i++)
{

    <input type="hidden" name="cart.item[@i].ProductID">
    <input type="text" name="cart.item[@i].Size">
   £ <input type="text" name="cart.item[@i].Price">

}

Webmatrix is saying that it doesnt recognise Cart()

I strongly recommend you place your Models in the Models folder and make them part of the Models namespace. Then they should be available automatically. Otherwise, you may have to reference cart by it's complete reference path (if it is not in your Models folder). example
Datalayer.Entities.Cart cart = (Datalayer.Entities.Cart)Session["cart"];

Final Note:
You are not passing your Cart as a Model to your View
example
@model {Project}.Entities.Cart

This is a better practice using the MVC 3 framework. You would have discovered whatever reference problem earlier and would have the option to use tightly bound Helpers

A: I recommend using the Visual Studio 2012 Express over WebMatrix for MVC development.  Furthermore, I would also suggest using jQuery (javascript) if you wish to let users add line items on the fly via the same page.  I can share an example with you if you like.
One more note:  You tagged this with both MVC and WebForms, which are two very different platforms.
Edit:
I think Dave A's solution may be better, but to do this with jQuery:
1 Put your add button and hidden div in a form
<form action="/MyController/MyAction" method="post" id="addListItemForm">
<button id="addListItemButton">Add List Item</button>

<input type="text" name="product" id="product" />
<button id="addButton">Add</button>

<input type="submit" text="Submit" />
</form>

2 Show the form fields on button click
$('#addListItemButton').click(function(){
  $('#addListItemForm div').show();
});

3 Add hidden field on add button click
$('#addButton').click(function(){
  var product = $('#addListItemForm #product').val();
  $("input").attr({
            name : "productListItems[]",
            type : "hidden",
            value : product
        }).after('#addListItemForm');
});

4 When the form submits, you will have various product names in the productListItems array passed via POST method.
Note:  You'll have to play with this a little bit, but it would be a good learning exercise...   I am not exactly sure what you are trying to do, but this is my best guess.


text:
Q: Let machine access my server after loosing machines public ssh key I have currently lost my servers data and needed to restore the server from the backup. But the backup is too old for the server to know the machines ssh key.
                Server ----------------------------------- Machine

(doesn't know public key of machine) --------------------- (has private and public key)

Machine tries to connect to the server, every 10 seconds. I can see the attempts in the log.
How can I give the machine (at least temporarily) access to the server? Disabling authentication doesn't seem to be possible with ssh?
The machine is too far away, so that i can't go there and get the public key again and can't give it a new key.
So is there any chance to let the machine connect to my server?
Note that the machine is out in the wilderness, so no human can easily access it.

A: No, loss of ssh keys means a user cannot log in.
If the private key is known, derive the public key from private. However, this doesn't help if the server doesn't have the public key, leaving the client still with no way to log in.
If a user who can become root can log in, use the privilaged account to install a new public key provided by the user.
If no one at all can log in remotely, use out of band management access to get a shell. Serial consoles, IPMI, a tech physically there to provide remote hands, however you need to get in.

And fix backups to cover the required recovery objective. Actually do restore tests.

A: Your only option is get a KVMoIP or similar device. If your colocating this thing a NoC tech can normally do this for you on "first come, first served" basis, at a fee or at remote hand rates.


text:
Q: Python to js word to phonetics script is there a way to do this in javascript?
if('a' in array[index] or 'A' in array[index] ):
    print(bArray[0], end = ' ')

(search array for a string, return index for that string, and then console.log(bArray[location];)

A: Yes
// Convert the string to lower case so that it will match both 'a' and "A"
const aIndex = array[index].toLowerCase().indexOf('a');
if(aIndex !== -1) {
    console.log(aIndex);
}

A: This is easiest to accomplish via regex match:
let match = s.match(/[a]/i);
if (match) console.log(match.index, match[0]);

If you want a more generic version:
let matcher = s => {
  let regex = new RegExp(s, 'i');
  let match = s.match(regex);
  return match && [match.index, match[0]];
};


text:
Q: Release build is corrupted when updating support gradle plugins as 28.0.0-alpha1 My release build was corrupted when I using android support version as 28.0.0-alpha. But release build working fine with support version 27.1.1.
Additional Info : version name and code is missed on release build with support version 28.0.0-alpha
so How to resolve it?

A: FYI
alpha is a version of a piece of software that is made available for testing.

28.0.0-alpha1 is a pre-release version to support the Android P developer preview. Its API surface is subject to change, and it does
  not necessarily include features or bug fixes from the latest stable
  versions of Support Library.

You should use stable version (27.1.1) for Release build.


text:
Q: How to remove a programmatically created subview by pressing a button within the subview I currently have a barbutton:
UIBarButtonItem *doneButton = [[UIBarButtonItem alloc] initWithTitle:@"Done" style:UIBarButtonItemStyleBordered target:self action:@selector(doneDate:)];

It calls the following action:
- (IBAction)doneDate:(id)sender{
[self removeDateView]
}

Which calls the following method:
- (void)removeDateView{

NSLog(@"subviews of view3.view: %@",self.View3.subviews);
[self.View3.subviews. makeObjectsPerformSelector: @selector(removeFromSuperview)];

}
The subview that I'm trying to remove is
UIView *containerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 44.0 + 210)];

At the moment it just deletes everything within that View, I can't seem to remove the view called containerView which has the datepicker and toolbar.

A: As erhnby stated, you could use a tag - which is a great method, but I always try to shy away from looping through a view's subviews whenever I can. Personally, I would make the view you are going to remove an instance variable, and when you want to remove it you can call remove directly on it... Just made a simple example that does this:
.h file:
#import <UIKit/UIKit.h>

@interface TestViewController : UIViewController {
    UIView *_containerView;
}

@end

.m file:
#import "TestViewController.h"

@interface TestViewController ()

@end

@implementation TestViewController

- (id)init {
    self = [super init];

    // create the bar button and set it as the right bar button on the navigation bar
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Done" style:UIBarButtonItemStyleBordered target:self action:@selector(removeDoneDate)];

    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    // create the container view and add it as a subview
    _containerView = [[UIView alloc] initWithFrame:CGRectMake(20, 100, 100, 100)];
    _containerView.backgroundColor = [UIColor redColor];
    [self.view addSubview:_containerView];

}

- (void)removeDoneDate {
    // remove it
    [_containerView removeFromSuperview];
}

@end

Results in this to start:

Press button...

(sorry, didn't realize the white on white would be that hard to see)

A: set tag for that will remove view
UIView *containerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 44.0 + 210)];
[containerView setTag:100];

and find it and removeFromSuperView
for (UIView*  view in self.View3.subviews) {
        if ([view isKindOfClass:[UIView class]] && view.tag == 100) {
            [view removeFromSuperview];
        }
    }


text:
Q: How do I securely store and set password for use by SmtpClient class? I am writing a C# class that needs to send SMTP emails. I found code in this SO question which gave me what I needed to send the email (SO Question)
For convenience, here is the code I am modifying from an answer to the above question:
using System.Net;
using System.Net.Mail;

var fromAddress = new MailAddress("from@gmail.com", "From Name");
var toAddress = new MailAddress("to@example.com", "To Name");
const string fromPassword = "fromPassword";
const string subject = "Subject";
const string body = "Body";

var smtp = new SmtpClient
           {
               Host = "smtp.gmail.com",
               Port = 587,
               EnableSsl = true,
               DeliveryMethod = SmtpDeliveryMethod.Network,
               UseDefaultCredentials = false,
               Credentials = new NetworkCredential(fromAddress.Address, fromPassword)
           };
using (var message = new MailMessage(fromAddress, toAddress)
                     {
                         Subject = subject,
                         Body = body
                     })
{
    smtp.Send(message);
}

The problem I have is that the code in that question requires the smtp password to be stored in the plain-text C# source file. Problem one is that this code will be checked in to team foundation service so the whole team would have to/get to know the credentials. Problem two is that obfuscation is possible but it doesn't fix problem 1.
The closest to a solution i have found is encryption of an app config as an installation step. This doesn't get around problem 1 but if necessary can be done.
Does this situation come up in production applications, and what best practices are used to store passwords needed to instantiate C# classes?

A: We solve this issue using our build server, TeamCity.  The build system contains production secrets (passwords, API Keys, etc), which can only be set up by a few trusted individuals. Our build system is then responsible for altering the configuration (and other sensitive) files just before/after compilation using scripts and/or Password Build Parameters.
This frees us up to commit staging/test values for our secrets, but know that production builds will get production secrets.  App/Web.Config transforms can take care of URL switching (dev/qa/stage/prod), so we only use the build server for the parts that we don't want included in source control, ever.

A: It only accept plain text, ie
Credentials = new NetworkCredential(fromAddress.Address, "MY Password" )

When you deploy the project, no one will be able to see your password. If you save it to a text file then you can use an encryption method to prevent others from viewing your password, but if you parse it as a parameter to the Credentials, then you have to parse it as a plain text. It's the usual way we professionally do. If you are unwilling to give your mail password ,then create another email account for test and place it's credentials in there.


text:
Q: Scala: Is my `equals` method correct? I wrote an equals method for class A.
class A(x: Int, s: String) {
  override def equals(that: Any) = that match {
    case a: A => this.x == a.x && this.s == a.s
    case _    => false
  }
}

Is it correct?

A: Yes that is correct. However you should also override the hashCode method to reflect equality. That is, if you have two instances a and b where a == b, you should ensure that a.hashCode == b.hashCode.
The simplest way to achieve the two is to use a case-class:
case class A(private val x: Int, private val s: String)

This gives you correct equals and hashCode for "free".

If you plan for the possibility that there are sub-classes of A, you may look at Odersky's idea of canEqual (also here).

A: a better approach is defining on companion object of A an Ordering[A] instance.
object A{
    implicit object aOrdering extends Ordering[A]{
        override def compare(x:A,y:A):Int = ......
    }
}

than on you equals method you should write:
override def equals(that: Any) = that match {
  case a: A => {
        val ordering = implicitly[Ordering[A]]
        ordering.compare(this,a) == 0
 }
  case _    => false
}

this way you can reuse your code i.e scala collections and other places that you need Ordering for this class.


text:
Q: Google Sheets Query Function not in as tow tables
semn
rserv
but i want elements not exist in second table
=QUERY(semn!A:A;rserv!A:A;"select semn!A:A WHERE A NOT IN rserv!A:A ")

A: See if this works
=FILTER(semn!A:A; isna(match(semn!A:A; rserv!A:A; 0)))


text:
Q: Variable body width I have a simple HTML page with 3 "columns" (300px x 100%) that all have a vertical scrollbar. This works fine when having a window of at least 900 pixels in width. However, when I resize the window to be smaller than the columns take, one (or more) of the columns jump down to fit the window vertically. This is not what I want, because it would require the user to scroll all the way down before being able to see the other column.
What I want is pretty simple: a way to force the browser to fit the columns horizontally, even if it doesn't fit. width: 900px; on the body isn't a solution I want to use because the number of columns (and their width) is variable.
In other words: how do I force a browser to put my elements horizontally on a page and stop moving elements?
[edit]
My current code (well, it's not the actual code, but it does show what the problem is):
<!DOCTYPE html>

        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

A: The three "columns" need to be in a single container with the container's CSS set to 'nowrap'

A: <!DOCTYPE html>

A: AFAIK there's no cross browser way to force semantic columns (without JavaScript).
here is the answer I gave to a similar question.
HTML:

...

...

...

CSS
.parent
{
  display: table-row;
}

.child
{
  display: table-cell;
  width: 300px;
}

I believe IE < 9 has issues with this, so you'll need to set the sizing and positioning manually with JS for IE.


text:
Q: Form of function constant on a closed curve Suppose that a continuous function $f : (0,2\pi)^2 \to \mathbb{R}$ is constant along the closed curve
$$ \gamma(t) = (\theta_0 + t \mod{2\pi}, \phi_0 + q t \mod{2\pi}) $$
where $q \in \mathbb{Q} - \{0\}$ is rational, that is
$$ \partial_t f(\gamma(t)) = 0, $$
how can we show that $f$ has the form
$$ f(\theta,\phi) = h(q\theta - \phi) $$
where $h : \mathbb{R} \to \mathbb{R}$ is continuous?

A: In general, $f$ doesn't have to be of that form, unless it is constant on all curves of the form that you've given (for any choice of $\theta_0$ and $\phi_0$).
In such a case, you can notice that for every point $(\theta,\phi)$ it lies on the same curve as point $(0, \phi-q\theta)$. You can therefore define $h(z)=f(0,-z)$. If $f$ is constant on each curve, we have $$f(\theta, \phi)=f(0, \phi-q\theta)=h(q\theta-\phi)$$.


text:
Q: How to handle unserialize data cla is an array that I save into the database (MySQL) using php
$input = serialize($_POST['cla']);

//in the database I have:
a:3:{s:6:"t9ffj7";s:27:"Paul";s:7:"71ciz86";s:27:"Peter";s:7:"awez69g";s:27:"Marie";}

To get the array from the database, I unserialize it and apply the var_dump() to it.
<?php
$output = var_dump(unserialize($row['li_file']));
echo $output;
?>

then, I get  this as output:
array (size=3)
  't9ffj7' => string 'Paul' (length=4)
  '71ciz86' => string 'Peter' (length=5)
  'awez69g' => string 'Marie' (length=5)

I would like to used each key to get the corresponding value.
so that, e.g.
$first_element = array['t9ffj7'];
echo $first_element; //I expect **Paul**

Could someone help me ?

A: <?php
    $output = unserialize($row['li_file']);
    foreach($output as $key=>$val){
        //echo $val; or
        echo $output[$key];
    }
?>


text:
Q: swift hide container view I have a UITableView in the main view which looks like this:

This table goes all the way to the bottom of the screen
I have a container view which looks like this:

The container view shows only when i hit a textfield on the top so I can pick an entry.  In the storyboard the container view is set to Hidden.
Here is how the storyboard looks like:

The problem I have is that I cant select any row where the container takes up even if its hidden.  I even tried to set the container view height to 0 when after I have made the selection and clicked on the done button just to see if I can select the row after its hidden:
self.view.frame.size.height = 0
self.view.hidden = true

The Container view is hidden again but I cant select "District 3 - 1st Watch" on down rows because the Container View is still there even after I set the size and hidden it
Update: 5/7/2015
OK Nothing seems to be working.  What I have noticed is that if I check off the hidden in the storyboard for the container view then it works (as you can see from my screenshot).  But if I dont set hidden then it doesnt work.  I would be fine with not setting the hidden in the storyboard but setting the container view hidden to false doesnt do anything.  I call this method when I tap on the textfield
func showContainer(tableSource: [DistrictSubscriptionSource])
{
    println("showContainer")
    self.view.hidden = false
}

A: I think the problem here is container view having multiple layers of views in the hierarchy.
When using container view, you have a view in the parent view and over that view, another view which is a main view in child scene is placed (this view is accessed with self.view from child controller).
So even when you are setting self.view.hidden to be true, you are not actually hiding the main container view that is present in parent view in your case, table view. So table view is not allowing your table rows to be checked.
You can verify your view placement by going to Debug>View Debugging>Capture View Hierarcy

A: If the container view is in fact covering it, just do this:
self.view.userInterfactionEnabled = false