text:
Q: libobjc.A.dylib at objc_msgSend:15 crash Anyone have any insight as to what is causing the following crash?

CLASS:
SIGNAL
FILE:
libobjc.A.dylib at objc_msgSend:15
IOS:
5.1

0libobjc.A.dylib 0x30f7ef78 objc_msgSend 15
1libobjc.A.dylib 0x30f80175 _objc_rootRelease 36
2UIKit 0x3713542d -[UILayoutContainerView _endFastMode] 132
3UIKit 0x37135279 -[UILayoutContainerView setUseFastMode:] 68
4UIKit 0x37090129 -[UIView(FastModeAdditions) _setContainerLayoutViewForFastMode:] 104
5UIKit 0x36ef637b -[UIView dealloc] 574
6UIKit 0x371e0491 -[UIDropShadowView dealloc] 92
7libobjc.A.dylib 0x30f80175 _objc_rootRelease 36
8CoreFoundation 0x36b9c2e7 CFRelease 94
9CoreFoundation 0x36c18b37 __CFDictionaryStandardReleaseValue 70
10CoreFoundation 0x36c6c3bc __CFBasicHashDrain 264
11CoreFoundation 0x36b9c39b CFRelease 274
12libobjc.A.dylib 0x30f81e57 objc_release 38
13libobjc.A.dylib 0x30f80ead _ZN12_GLOBAL__N_119AutoreleasePoolPage3popEPv 224
14libobjc.A.dylib 0x30f80dc9 _objc_autoreleasePoolPop 12
15CoreFoundation 0x36ba3cff _CFAutoreleasePoolPop 18
16CoreFoundation 0x36c262b3 __CFRunLoopRun 1274
17CoreFoundation 0x36ba94a5 CFRunLoopRunSpecific 300
18CoreFoundation 0x36ba936d CFRunLoopRunInMode 104
19GraphicsServices 0x30c8b439 GSEventRunModal 136
20UIKit 0x36efae7d UIApplicationMain 1080

A: I would suspect you are releasing an object that is already released (implicitly within the autorelease pool). You need to enable zombies and add breakpoints on objc_exception_throw, etc.
Source: trojanfoe comment

A: This crash sounds like it happened in UIKit framework while sending the message using objc_msgSend function (part of Objective-C).
You should compile your source code with the debug symbols and generate another more detailed backtrace. Use also debuggers such as dtrace/dtruss to further check problems with your code.
This could be a iOS bug with scrolling as mentioned in here: App crashes when Back button tapped while scrolling table view.
See also: objc_msgSend at ridiculousfish


text:
Q: Not Resolving dart dependencies I am trying to build a dart maven application and When I execute maven clean install it only showing Resolving dependencies... and doesn't happen anything. I am using the dart 1.12.1 version.
EDIT:
When I run pub get commend result is the same as previous it only showing Resolving dependencies.

redpajama_set_name: RedPajamaStackExchange


text:
Q: H2 database script cannot be imported into MySQL I have created a local H2 database which I always opened in MySQL mode to insert data. Now, I want to export it with SCRIPT, in order to import it with phpMyAdmin on a remote MySQL database on a remote server. I get the following:
SET LOCK_MODE 3;
;
CREATE USER IF NOT EXISTS SA SALT '...' HASH '...' ADMIN;
CREATE CACHED TABLE PUBLIC.RAWVALUEITEM(
    LANGUAGE VARCHAR(2) NOT NULL SELECTIVITY 1,
    RAWVALUE VARCHAR(40) NOT NULL SELECTIVITY 99,
    STRIPPED VARCHAR(40) NOT NULL SELECTIVITY 96
);
...

Unfortunately, phpMyAdmin import is not happy:
#1193 - Unknown system variable 'LOCK_MODE'

When I manually remove the set instruction, I get further errors:
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'IF NOT EXISTS SA SALT '...' HASH '...' at line 1

The code I use to export the database as a script is:
public static final String DB_DIR_LOCATION = "E:/Temp/FWDB/";
public static final String H2_CONNECTION = "jdbc:h2:file:"
    + DB_DIR_LOCATION + "FWDB_PHP_TEST" + "Mode=MySQL;IFEXISTS=TRUE";

public static void main(String[] args) throws SQLException {

    Connection conn = DriverManager.
        getConnection(H2_CONNECTION, "sa", "");

    PreparedStatement ps;

    ps = conn.prepareStatement("SCRIPT TO 'E:/Temp/FWDB/FWDB_EXPORT.gz' "
        + "COMPRESSION GZIP");
    ps.execute();

}

How can generate a script from my DB which will be imported successfully by phpMyAdmin on my remote server?

A: The SQL script generated by the SCRIPT TO command is not cross-platform. A better solution might be to use a database tool such as the SQuirreL DB Copy Plugin or another database tool.


text:
Q: Looking for loading more scene when node goes above Y I am looking for a way to make my game load more SKScene when my node (ball) goes above certain Y position.
I'm looking for a way to make the loading a little bit like ColorSwitch game where you tap and the ball loads more screen once you hit a certain Y position.

A: Use SKCameraNode and have it centered on your scene (or wherever it is you want to look at). Check documentation or search here for more help on setting up your camera.
In update() simply check the position of ball's y value ball!.position.y, if it's past a threshold such as view!.bounds.y, move your camera up by however much camera!.runAction(SKAction.moveBy...)
If you want to scroll back down, it would be a bit more complicated, but the same principles would apply.
(note: I have my stuff as Optionals so your code may not have !)
https://developer.apple.com/reference/spritekit/skcameranode
You could also use invisible boxes and collision detection, but that seems more complicated of an approach to me >.>
If you post some code we can help you get it up and running. Unfortunately, there will be some degree of math involved x[


text:
Q: Ember - Sending particular values in PUT request I have a form which I am using to edit details via form. Ember does a PUT request like required but I need it to only send particular values and not everything within the JSON object. The object is structured as:
{
  consoles: {
    "id": "1",
    "name": "Street Fighter",
    "type":"Beat-em-up"
    "versions": "10",
    "consoles": [
      {
        "id": "1",
        "name": "Microsoft",
        "console": "Xbox 360"
      },{
        "id": "2",
        "name": "Microsoft",
        "console": "Xbox One"
      },{
        "id": "3",
        "name": "Sony",
        "console": "Playstation 4"
      }
    ],
    "Characters":[],
    "Reviews":[]
  }
}

The only editable values within my form are:

*

*name

*type

*versions

When I press the update button, everything is sent in a PUT request. Is it possible for ONLY name, type and versions to be sent in the request?
I'm aware of overriding updateRecord but I wouldn't know where to start if this was what I needed to do.

A: You can write your own Serializer to only send specific attributes up to the server.
See the docs here


text:
Q: how to run some suites using specific capability in Protractor I have a website both for desktop browsers and mobile browsers, and obviously they have different UI. In my protractor config file, some suites need to be ran using plain(desktop) user agent, and some other suites need to be ran using mobile user agent.
I know there is a option called multiCapabilities:
multiCapabilities: [{
        'browserName': 'chrome'
    }, {
        'browserName': 'chrome',
        'chromeOptions': {
            'args':['--user-agent="iphone"']
        }
    }],

using config like this can run all the suites both on these two browsers(one for desktop, another for mobile), but I want to know is there a method that I can run some suites using first capabilities and run others using second one?
For example, can I manually set user agent is the specific Spec file using js code?

A: Continuing from @AndresD's comment since I can't comment yet, why doesn't this work for you?
multiCapabilities: [{
  'browserName': 'chrome',
  specs: ['specsA_for_browser1.js', 'specsB_for_browser1.js']
}, {
  'browserName': 'chrome',
  'chromeOptions': {
    'args':['--user-agent="iphone"']
  },
  specs: ['specsA_for_browser2.js', 'specsB_for_browser2.js']
}],


text:
Q: Matrix Representation of Softmax Derivatives in Backpropagation I have a simple multilayer fully connected neural network for classification. At the last layer I have used softmax activation function. So I have to propagate the error through the softmax layer. Suppose, I have 3 softmax units at the output layer. Input to these 3 logits can be described by the vector
 $z =\begin{pmatrix}z1\\z2\\z3\end{pmatrix}$. Now let's say those 3 logits output $y = \begin{pmatrix}y1\\y2\\y3\end{pmatrix}$. Now I want to calculate $
\frac{\partial y}{\partial z}$. Which is simply: $ $ $$\begin{equation} \\
 \frac{\partial }{\partial z} softmax(z)
\end{equation}
$$
I know the derivatives of the softmax function are really $y(\delta_{ij}-y)$. Here $\delta$ is Kronecker delta. I can actually break down this expression and write down into two matrices( maybe here I am going wrong):
 $$\texttt{matrix_a} =\begin{bmatrix}y1(1-y) & 0 & 0 \\0 & y2(1-y2) & 0\\0 &0 & y3(1-y3)\end{bmatrix}$$ and
$$\texttt{matrix_b} =\begin{bmatrix}0 & -y1y2 & -y1y3 \\-y1y2 & 0 & -y2y3\\-y1y3 &-y2y3 & 0\end{bmatrix}$$.
So finally, then I add these matrices to get the following matrix:
$$\texttt{matrix_c} =\begin{bmatrix}y1(1-y1) & -y1y2 & -y1y3 \\-y1y2 & y2(1-y2) & -y2y3\\-y1y3 &-y2y3 & y3(1-y3)\end{bmatrix}$$
Now if I take the sum over the rows I should get the column matrix of $\frac{\partial y}{\partial z}$. So the final column matrix containing the derivatives for $z$ is:
$$\texttt{matrix} =\begin{pmatrix}y1(1-y1)-y1y2-y1y3 \\-y1y2+y2(1-y2)-y2y3\\-y1y3-y2y3+y3(1-y3)\end{pmatrix}$$
But this is definitely wrong as $y1+y2+y3 = 1.0$ so I get the derivative for each of the softmax unit 0. Can you please tell me where I am doing it wrong and how I can make it correct? Thanks for reading.

A: The final matrix is already a matrix of derivatives $\frac{\partial y}{\partial z}$. Every element $i, j$ of the matrix correspond to the single derivative of form $\frac{\partial y_i}{\partial z_j}$.
One usually expects to compute gradients for the backpropagation algorithm but those can be computed only for scalars. In this case the $y$ is a vector hence we stack the gradients of it's components (a single component of $y$ vector is a scalar) forming a Jacobian matrix:
$$
\frac{\partial y}{\partial z} =
\begin{bmatrix}
\frac{\partial y_1}{\partial z} \\
\frac{\partial y_2}{\partial z} \\
\frac{\partial y_3}{\partial z}
\end{bmatrix} =
\begin{bmatrix}
\frac{\partial y_1}{\partial z_1} &  \frac{\partial y_1}{\partial z_2} & \frac{\partial y_1}{\partial z_3} \\
\frac{\partial y_2}{\partial z_1} &  \frac{\partial y_2}{\partial z_2} & \frac{\partial y_2}{\partial z_3} \\
\frac{\partial y_3}{\partial z_1} &  \frac{\partial y_3}{\partial z_2} & \frac{\partial y_3}{\partial z_3}
\end{bmatrix} =
\begin{bmatrix}y_1(1-y_1) & -y_1y_2 & -y_1y_3 \\-y_1y_2 & y_2(1-y_2) & -y_2y_3\\-y_1y_3 &-y_2y_3 & y_3(1-y_3)\end{bmatrix}
$$
Note however that in backpropagation we would usually compute the gradient of some loss function $L$. Since it is a scalar we can compute it's gradient wrt. $z$:
$$
\frac{\partial L}{\partial z} = \frac{\partial L}{\partial y} \frac{\partial y}{\partial z}
$$
The component $\frac{\partial L}{\partial y}$ is a gradient (i.e. vector) which should be computed in the previous step of the backpropagation and depends on the actual loss function form (e.g. cross-entropy or MSE). The second component is the matrix shown above. By multiplying the vector $\frac{\partial L}{\partial y}$ by the matrix $\frac{\partial y}{\partial x}$ we get another vector $\frac{\partial L}{\partial x}$ which is suitable for another backpropagation step.
Note that the formula for $\frac{\partial L}{\partial z}$ might be a little difficult to derive in the vectorized form as shown above. It should be easier to start by computing the derivatives for single elements and vectorizing the equation later:
$$
\frac{\partial L}{\partial z_j} = \sum_i \frac{\partial L}{\partial y_i} \frac{\partial y_i}{\partial z_j}
$$
The above equation for a single element of $\frac{\partial L}{\partial z}$ is equivalent to the vectorized form above. One could convince himself/herself by  comparing this equation to the way the vector-matrix multiplication works.

A: You don't need a vector from the softmax derivative; I fell in the same mistake too. You can leave it in matrix form. Consider you have: $ y_{i} \in \mathbb{R}^{1 \times n} $ as your network prediction and have $ t_{i} \in \mathbb{R}^{1 \times n} $ as the desired target. With squared error as loss function you're looking at:
$$ \frac{\partial L}{\partial y_{i}} * \frac{\partial y_{i}}{\partial z_{i}} $$
where $ \frac{\partial L}{\partial y_{i}} \in \mathbb{R}^{1 \times n} $ and $
\frac{\partial y_{i}}{\partial z_{i}} \in \mathbb{R}^{n \times n} $. Now in order to get $ \delta_{i} $ you need to multiply those two derivatives together which gives you: $ \mathbb{R}^{1 \times n} \mathbb{R}^{n \times n} = \mathbb{R}^{1 \times n} $ and you can continue your standard backpropagation.


text:
Q: Django Change Form FIlter How to create field filters for the Django change form in admin site?  The list filter seems to be only applicable to the change list. This is for Django version 1.9.x.

A: Download admin_tools from
   https://github.com/django-admin-tools/django-admin-tools
and adminsortable from https://github.com/iambrandontaylor/django-admin-sortable
or just use
pip install django-admin-tools
pip install django-admin-sortable

in your INSTALLED_APPS include:
'admin_tools',
'admin_tools.menu',
'admin_tools.dashboard',
'admin_tools.liststyle',
'adminsortable',

So then if you have, say, a model Profile in your models, in your admin.py
class ProfileAdmin(admin.ModelAdmin):
    fieldsets = ((None, {'fields': ['username', 'email',
                                    'name', 'is_cleared',
                                    'first_name', 'last_name',
                                    'cell_phone','business_phone',
                                    'address1','address2',
                                    'address2','zip','state','city',
                                    'country']}),)

    list_display = ('id','username', 'email',
                                    'name', 'is_cleared',
                                    'first_name', 'last_name',
                                    'cell_phone','business_phone',
                                    'address1','address2',
                                    'address2','zip','state','city',
                                    'country')
    list_editable = ('username','email','first_name','last_name','address1','address2')
    search_fields = ('username','email','first_name','last_name','address1','address2')

    class Meta:
        verbose_name = 'User Profile'
        verbose_name_plural = 'User Profiles'

Of course, adjust the fields to match your model.


text:
Q: Try to fill with " " in case of error in loop of html_nodes I'm trying to extract data by text mining with html_nodes using urls that I have saved into an object called url. I have created a loop which reads and scrapes each url.
library(rvest)
for (i in url) {
  tex <- read_html(i)
  p_text <- tex %>%
    html_nodes("p") %>%
    html_text()
  a <- p_text
}

Because some url isn't working, the following message appears:

Error in open.connection(x, "rb") : Could not resolve host: app.lo

I want to introduce in the loop the following: if the url doesn't work, assume the text blank, and let the loop continue. This is a really a problem because the loop is stopping and I was trying to eliminate some urls, but I have around 200,000 htmls.

A: This can be achieved by a simple tryCatch and error handling. I also introduced a list a in which you can store your outputs (currently you will be overwriting your output in each loop.)
library(rvest)
a <- list()
for (i in 1:length(url)) {
  url_use = url[[i]]
  a[[i]] <-
    tryCatch({
        read_html(url_use) %>%
            html_nodes("p") %>%
            html_text()
    }, error = function(e) NA)
}

Let me know if this is not what you had in mind.

A: You should be able to just switch to html_node instead of html_nodes.
html_node will return NA if nothing is matched.
Without any sample URLs, I can't test, however.
See these Q&A for more reference

*

*Equivalent of which in scraping?

*Different number of nodes

*Reading in html with R rvest. How do I check if a CSS selector class contains anything?

*Scraping a table from a section in Wikipedia

*Why does xpath find excluded nodes again?


text:
Q: Return a string from a web scraping function in swift Ok so I am scraping some basic data of a web page. I wanted to refactor out my code to another class and return a string from what I retrieved but it is difficult with the asynchronous function and I'm new with swift.
I now realize that this function is incapable of returning a string but I can't quite figure out how to configure the completion handler and how to call the function after from the main class using the completion handler.
Any help would be greatly appreciated, thanks.
func getNameFromProfileUrl(profileUrl: NSURL) -> String {

        var playerName = ""

        let task = NSURLSession.sharedSession().dataTaskWithURL(profileUrl,     completionHandler: { (data, response, error) -> Void in

            if error == nil {
                var urlContent = NSString(data: data, encoding: NSUTF8StringEncoding) as NSString!

                var urlContentArray = urlContent.componentsSeparatedByString("<title>")

                var statusArray = urlContentArray[1].componentsSeparatedByString("</title>")

                playerName = statusArray[0] as! String

            }

        })
        task.resume()
        return playerName
    }

A: Essentially, you'll want to provide a completion handler to this function from the main class that can handle just the return of the player name (or not). You'd change the function to not have a return value, but to accept a second parameter that is a completion handler:
func getNameFromProfileUrl(profileUrl: NSURL, completionHandler: (String?) -> Void) {
    let task = NSURLSession.sharedSession().dataTaskWithURL(profileUrl, completionHandler: { (data, response, error) -> Void in
        if error == nil {
            var urlContent = NSString(data: data, encoding: NSUTF8StringEncoding) as NSString!
            var urlContentArray = urlContent.componentsSeparatedByString("<title>")
            var statusArray = urlContentArray[1].componentsSeparatedByString("</title>")
            let playerName = statusArray[0] as? String

            completionHandler(playerName)
        } else {
            completionHandler(nil)
        }
    })
    task.resume()
}

From your main class, you'd then call it with something like this:
myWebScraper.getNameFromProfileUrl(profileURL) { playerName in
    // always update UI from the main thread
    NSOperationQueue.mainQueue().addOperationWithBlock {
        if let playerName = playerName {
            playerNameField.text = playerName
        } else {
            playerNameField.text = "Player Not Found"
        }
    }
}


text:
Q: Problem with my block diagram: Error 5002 occurred at Init.vi I'm making a heart rate analyze, but I'm having a real problem with that. When I'm press to start the programm doesn't work, so, I've press to stop the running program and it shows me in the section where it's ready to close or finish the connection:

Error 5002 occurred at Init.vi.  Unable to establish connection with
  Arduino.  Please ensure that you have selected the correct COM port
  and that you have flashed the Arduino with the correct firmware.
This error code is undefined. Undefined errors might occur for a
  number of reasons. For example, no one has provided a description for
  the code, or you might have wired a number that is not an error code
  to the error code input.
Additionally, undefined error codes might occur because the error
  relates to a third-party object, such as the operating system or
  ActiveX. For these third-party errors, you might be able to obtain a
  description of the error by searching the Web for the error code
  (5002) or for its hexadecimal representation (0x0000138A).

This is my VI diagram:

And this is my control panel:

And the connections to my arduino:

So:

*

*how can I solve this problem?

*Where can I find more information to get this

Thanks for your help, but I'm new on this world (Arduino and Labview)

A: Follow the suggestion given in error message. First of all, make sure that you could communicate with Arduino using some simple serial line terminal, like RealTerm, or HTerm. In case if you couldn't send any command using serial line terminal, check out which firmware do you have on Arduino.
This is the way, how you could troubleshoot this issue...

A: You can ignore the second and third paragraphs of that error message; they're generated because the Arduino VI's you're using are generating a custom error code that they haven't registered with the LabVIEW development environment, so its automated error handling doesn't know what they mean. The information you need is in the first paragraph though.
As kosist's answer says, the first thing to check is that you can communicate with the Arduino at all. Before you even start with LabVIEW, have you tried using the Arduino IDE to program your device with a simple program like the 'blink' example?
If that works, then the next step is to make sure you've programmed your Arduino with the firmware it needs to communicate with the LabVIEW VIs you're using (can you link to where you got them from?) and then try a much simpler test program in LabVIEW - again, just get the Arduino to do something simple like turn the buzzer on and off. If you hit a problem with any of those, I suggest asking a new question with details of exactly what you tried and what errors you saw.


text:
Q: Check for Wordpress Thumbnail and display dummy if not there got another question to ask:
I would like to display post thumbnails with the post title underneath. I have managed to work that out through asking on here, however now I would like to add a function that checks for a thumbnail and if none is available displays a dummy image.
Here is my try, which does display the thumbnail (if there) but not the dummy (if no thumbnail is attached):

<?php query_posts( $args ); if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>

        <a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>">

                <?php if ( has_post_thumbnail() ) {
                    the_post_thumbnail('thumbnail'); }
                else {
                    echo
                    ''
                ; } ?>

                    <?php the_title(); ?>

<?php endwhile; else : ?>

<?php _e( 'Sorry, no posts matched your criteria.' ); ?>

<?php endif; ?>
<?php wp_reset_query(); ?>

What am I doing wrong here?

A: This code works for me.  Yours is virtually identical.
<?php if ( has_post_thumbnail() ) : ?>

        <?php the_post_thumbnail(); ?>

    <?php else : ?>

  <img src="<?php echo get_template_directory_uri(); ?>/images/sunlit_path_banner.jpg" alt="Sunlit Path" />

    <?php endif; ?>

Note:   I also cut and pasted your code and tested on my WP install, and it worked fine.
Or... try this alternative to the if condition:
<?php if ( get_the_post_thumbnail( get_the_ID() ) ) {
                    the_post_thumbnail('thumbnail'); }
                else {
                    echo
                    ''
                ; } ?>


text:
Q: Error after analyzing adding C# custom rule on SonarQube I developed a custom rule for C# using Roslyn in VS2015, I deployed it under SonarQube 6.4 and activated it in my quality profile.
Then, I analyzed several .cs files under the same directory using sonar-scanner. But I got this error
ERROR: Error during SonarQube Scanner execution
java.lang.IllegalArgumentException: Custom and 3rd party Roslyn analyzers are only by MSBuild 14. Either use MSBuild 14, or disable the custom/3rd party Roslyn analyzers in your quality profile.
    at org.sonar.plugins.csharp.CSharpSensor.analyze(CSharpSensor.java:141)
    at org.sonar.plugins.csharp.CSharpSensor.executeInternal(CSharpSensor.java:112)
    at org.sonar.plugins.csharp.CSharpSensor.execute(CSharpSensor.java:79)
    at org.sonar.scanner.sensor.SensorWrapper.analyse(SensorWrapper.java:53)
    at org.sonar.scanner.phases.SensorsExecutor.executeSensor(SensorsExecutor.java:57)
    at org.sonar.scanner.phases.SensorsExecutor.execute(SensorsExecutor.java:49)
    at org.sonar.scanner.phases.AbstractPhaseExecutor.execute(AbstractPhaseExecutor.java:74)
    at org.sonar.scanner.scan.ModuleScanContainer.doAfterStart(ModuleScanContainer.java:175)
    at org.sonar.core.platform.ComponentContainer.startComponents(ComponentContainer.java:143)
    at org.sonar.core.platform.ComponentContainer.execute(ComponentContainer.java:128)
    at org.sonar.scanner.scan.ProjectScanContainer.scan(ProjectScanContainer.java:262)
    at org.sonar.scanner.scan.ProjectScanContainer.scanRecursively(ProjectScanContainer.java:257)
    at org.sonar.scanner.scan.ProjectScanContainer.doAfterStart(ProjectScanContainer.java:247)
    at org.sonar.core.platform.ComponentContainer.startComponents(ComponentContainer.java:143)
    at org.sonar.core.platform.ComponentContainer.execute(ComponentContainer.java:128)
    at org.sonar.scanner.task.ScanTask.execute(ScanTask.java:47)
    at org.sonar.scanner.task.TaskContainer.doAfterStart(TaskContainer.java:86)
    at org.sonar.core.platform.ComponentContainer.startComponents(ComponentContainer.java:143)
    at org.sonar.core.platform.ComponentContainer.execute(ComponentContainer.java:128)
    at org.sonar.scanner.bootstrap.GlobalContainer.executeTask(GlobalContainer.java:118)
    at org.sonar.batch.bootstrapper.Batch.executeTask(Batch.java:117)
    at org.sonarsource.scanner.api.internal.batch.BatchIsolatedLauncher.execute(BatchIsolatedLauncher.java:63)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.sonarsource.scanner.api.internal.IsolatedLauncherProxy.invoke(IsolatedLauncherProxy.java:60)
    at com.sun.proxy.$Proxy0.execute(Unknown Source)
    at org.sonarsource.scanner.api.EmbeddedScanner.doExecute(EmbeddedScanner.java:233)
    at org.sonarsource.scanner.api.EmbeddedScanner.runAnalysis(EmbeddedScanner.java:151)
    at org.sonarsource.scanner.cli.Main.runAnalysis(Main.java:123)
    at org.sonarsource.scanner.cli.Main.execute(Main.java:77)
    at org.sonarsource.scanner.cli.Main.main(Main.java:61)

Once the rule deactivated, I can analyze my .cs files normally
I cannot use SonarQube Scanner for MSBuild, because it requires a whole project to analyze, but in my case, I can only have a directory of .cs files, this is why I need to use sonar-scanner
I saw here that a solution has been developed, but is it available currently?
Is there a solution I can analyze my files with my new rule under sonar-scanner?

A: Using the Scanner for MSBuild is a requirement for any analysis of .Net code with SonarQube. For reasons you've already made clear in fact:

*

*C# rules (e.g. from SonarC#) rely on the Roslyn framework

*Roslyn is a Microsoft framework, which kicks in during compilation of the code

*Roslyn-based analyzers therefore require msbuild execution

*SonarQube analysis of .Net code therefore requires to use the Scanner for MSBuild (which integrates with msbuild)

For all above reasons, it is not possible to analyze individual .cs files with any other scanner.


text:
Q: Azure AD B2C Local Account Password stops working after a few hours I have created custom policies for social and local accounts based on the example from the Active Directory B2C custom policy starter pack for social and local accounts. I have enabled the login with Microsoft and Google and tested that both work, I have also enabled logging in with a local account.
The problem I am seeing is the local account.  I can create one and the password works fine for a few hours (not sure exactly how long), then starts giving a generic "Invalid username or password." error.  When I type in the wrong password for the same user I get a different message "Your password is incorrect" (this corresponds to a relevant log entry).
I have enabled application insights and can only find the following exceptions.
Any help on how to clear up these 2 errors would be great.
""Statebag"": {
    ""Complex-CLMS"": {},
    ""ValidationRequest"": {
      ""ContentType"": ""Unspecified"",
      ""Created"": ""2017-10-04T19:17:49.2510644Z"",
      ""Key"": ""ValidationRequest"",
      ""Persistent"": true,
      ""Value"": ""client_id=307&resource=cf87&username=user%domain.com&password=fakep@ss!123&grant_type=password&scope=openid&nca=1;1;login-NonInteractive;False""
    },
    ""ValidationResponse"": {
      ""ContentType"": ""Json"",
      ""Created"": ""2017-10-04T19:17:49.2510644Z"",
      ""Key"": ""ValidationResponse"",
      ""Persistent"": true,
      ""Value"": ""{\""error\"":\""invalid_grant\"",\""error_description\"":\""AADSTS65001: The user or administrator has not consented to use the application with ID '307' named 'IdentityExperienceFramework'. Send an interactive authorization request for this user and resource.\\r\\nTrace ID: 7c4\\r\\nCorrelation ID: 3cc\\r\\nTimestamp: 2017-10-04 19:17:49Z\"",\""error_codes\"":[65001],\""timestamp\"":\""2017-10-04 19:17:49Z\"",\""trace_id\"":\""7c4\"",\""correlation_id\"":\""3cc\""};1;login-NonInteractive;False""
    },
    ""ComplexItems"": ""_MachineEventQ, REPRM, TCTX, M_EXCP""
  }

Here is the 2nd exception
""Key"": ""Exception"",
            ""Value"": {
              ""Kind"": ""Handled"",
              ""HResult"": ""80131500"",
              ""Message"": ""The technical Profile with id \""AAD-UserWriteUsingLogonEmail\"" in Policy id \""B2C_1A_signup_signin of Tenant id \""xxx.onmicrosoft.com\"" requires that an error be raised if a claims principal record already exists for storing claims. A claims principal of type \""User\"" with identifier claim type id \""signInNames.emailAddress\"" does already exist."",
              ""Data"": {
                ""IsPolicySpecificError"": true,
                ""TenantId"": ""xxx.onmicrosoft.com"",
                ""PolicyId"": ""B2C_1A_signup_signin"",
                ""TechnicalProfile.Id"": ""AAD-UserWriteUsingLogonEmail"",
                ""ClaimsPrincipal.IdentifierClaim.ClaimTypeId"": ""signInNames.emailAddress"",
                ""ClaimsPrincipal.PrincipalType"": ""User"",
                ""CreateClaimsPrincipalIfItDoesNotExist"": ""True"",
                ""RaiseErrorIfClaimsPrincipalAlreadyExists"": ""True"",
                ""RaiseErrorIfClaimsPrincipalDoesNotExist"": ""False""
              }
            }

Here is the content of the TrustFrameworkExtensions.xml file.  The only difference between it and the example is that I am using 2 providers instead of 1.
<?xml version="1.0" encoding="utf-8" ?>
<TrustFrameworkPolicy
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:xsd="http://www.w3.org/2001/XMLSchema"
  xmlns="http://schemas.microsoft.com/online/cpim/schemas/2013/06"
  PolicySchemaVersion="0.3.0.0"
  TenantId="xxx.onmicrosoft.com"
  PolicyId="B2C_1A_TrustFrameworkExtensions"
  PublicPolicyUri="http://xxx.onmicrosoft.com/B2C_1A_TrustFrameworkExtensions">

  <BasePolicy>
    <TenantId>xxx.onmicrosoft.com</TenantId>
    <PolicyId>B2C_1A_TrustFrameworkBase</PolicyId>
  </BasePolicy>
  <BuildingBlocks>

  </BuildingBlocks>

  <ClaimsProviders>

    <ClaimsProvider>
      <DisplayName>Local Account SignIn</DisplayName>
      <TechnicalProfiles>
        <TechnicalProfile Id="login-NonInteractive">
          <Metadata>
            <Item Key="client_id">307</Item>
            <Item Key="IdTokenAudience">cf8</Item>
          </Metadata>
          <InputClaims>
            <InputClaim ClaimTypeReferenceId="client_id" DefaultValue="307" />
            <InputClaim ClaimTypeReferenceId="resource_id" PartnerClaimType="resource" DefaultValue="cf8" />
          </InputClaims>
        </TechnicalProfile>
      </TechnicalProfiles>
    </ClaimsProvider>

    <ClaimsProvider>
        <Domain>Employee SignIn with Azure AD</Domain>
        <DisplayName>Employee Login</DisplayName>
        <TechnicalProfiles>
            <TechnicalProfile Id="AzureADProfile">
                <DisplayName>Employee Login</DisplayName>
                <Description>Login with your GP account</Description>
                <Protocol Name="OpenIdConnect"/>
                <OutputTokenFormat>JWT</OutputTokenFormat>
                <Metadata>
                    <Item Key="METADATA">https://login.windows.net/yyy.onmicrosoft.com/.well-known/openid-configuration</Item>
                    <Item Key="ProviderName">https://sts.windows.net/7de/</Item>
                    <Item Key="client_id">f19</Item>
                    <Item Key="IdTokenAudience">f19</Item>
                    <Item Key="response_types">id_token</Item>
                    <Item Key="UsePolicyInRedirectUri">false</Item>
                </Metadata>
                <CryptographicKeys>
                    <Key Id="client_secret" StorageReferenceId="B2C_1A_AzureADAppSecret"/>
                </CryptographicKeys>
                <OutputClaims>
                    <OutputClaim ClaimTypeReferenceId="socialIdpUserId" PartnerClaimType="oid"/>
                    <OutputClaim ClaimTypeReferenceId="tenantId" PartnerClaimType="tid"/>
                    <OutputClaim ClaimTypeReferenceId="givenName" PartnerClaimType="given_name" />
                    <OutputClaim ClaimTypeReferenceId="surName" PartnerClaimType="family_name" />
                    <OutputClaim ClaimTypeReferenceId="displayName" PartnerClaimType="name" />
                    <OutputClaim ClaimTypeReferenceId="authenticationSource" DefaultValue="contosoAuthentication" />
                    <OutputClaim ClaimTypeReferenceId="identityProvider" DefaultValue="AzureADContoso" />
                </OutputClaims>
                <OutputClaimsTransformations>
                    <OutputClaimsTransformation ReferenceId="CreateRandomUPNUserName"/>
                    <OutputClaimsTransformation ReferenceId="CreateUserPrincipalName"/>
                    <OutputClaimsTransformation ReferenceId="CreateAlternativeSecurityId"/>
                    <OutputClaimsTransformation ReferenceId="CreateSubjectClaimFromAlternativeSecurityId"/>
                </OutputClaimsTransformations>
                <UseTechnicalProfileForSessionManagement ReferenceId="SM-Noop"/>
            </TechnicalProfile>
        </TechnicalProfiles>
    </ClaimsProvider>

    <ClaimsProvider>
      <Domain>google.com</Domain>
      <DisplayName>Google</DisplayName>
      <TechnicalProfiles>
        <TechnicalProfile Id="Google-OAUTH">
            <DisplayName>Employee Login</DisplayName>
            <Protocol Name="OAuth2" />
            <Metadata>
            <Item Key="ProviderName">google</Item>
            <Item Key="authorization_endpoint">https://accounts.google.com/o/oauth2/auth</Item>
            <Item Key="AccessTokenEndpoint">https://accounts.google.com/o/oauth2/token</Item>
            <Item Key="ClaimsEndpoint">https://www.googleapis.com/oauth2/v1/userinfo</Item>
            <Item Key="scope">email</Item>
            <Item Key="HttpBinding">POST</Item>
            <Item Key="UsePolicyInRedirectUri">0</Item>
            <Item Key="client_id">zzz.apps.googleusercontent.com</Item>
            </Metadata>
            <CryptographicKeys>
            <Key Id="client_secret" StorageReferenceId="B2C_1A_GoogleSecret" />
            </CryptographicKeys>
            <OutputClaims>
            <OutputClaim ClaimTypeReferenceId="socialIdpUserId" PartnerClaimType="id" />
            <OutputClaim ClaimTypeReferenceId="email" PartnerClaimType="email" />
            <OutputClaim ClaimTypeReferenceId="givenName" PartnerClaimType="given_name" />
            <OutputClaim ClaimTypeReferenceId="surname" PartnerClaimType="family_name" />
            <OutputClaim ClaimTypeReferenceId="displayName" PartnerClaimType="name" />
            <OutputClaim ClaimTypeReferenceId="identityProvider" DefaultValue="google.com" />
            <OutputClaim ClaimTypeReferenceId="authenticationSource" DefaultValue="socialIdpAuthentication" />
            </OutputClaims>
            <OutputClaimsTransformations>
            <OutputClaimsTransformation ReferenceId="CreateRandomUPNUserName" />
            <OutputClaimsTransformation ReferenceId="CreateUserPrincipalName" />
            <OutputClaimsTransformation ReferenceId="CreateAlternativeSecurityId" />
            <OutputClaimsTransformation ReferenceId="CreateSubjectClaimFromAlternativeSecurityId" />
            </OutputClaimsTransformations>
            <UseTechnicalProfileForSessionManagement ReferenceId="SM-SocialLogin" />
            <ErrorHandlers>
            <ErrorHandler>
                <ErrorResponseFormat>json</ErrorResponseFormat>
                <ResponseMatch>$[?(@@.error == 'invalid_grant')]</ResponseMatch>
                <Action>Reauthenticate</Action>
                <!--In case of authorization code used error, we don't want the user to select his account again.-->
                <!--AdditionalRequestParameters Key="prompt">select_account</AdditionalRequestParameters-->
            </ErrorHandler>
            </ErrorHandlers>
        </TechnicalProfile>
      </TechnicalProfiles>
    </ClaimsProvider>

  </ClaimsProviders>

  <UserJourneys>
      <UserJourney Id="SignUpOrSignInUsingAzureAD">
      <OrchestrationSteps>

        <OrchestrationStep Order="1" Type="CombinedSignInAndSignUp" ContentDefinitionReferenceId="api.signuporsignin">
          <ClaimsProviderSelections>
            <ClaimsProviderSelection ValidationClaimsExchangeId="LocalAccountSigninEmailExchange" />
            <ClaimsProviderSelection TargetClaimsExchangeId="GoogleExchange" />
            <ClaimsProviderSelection TargetClaimsExchangeId="AzureADExchange" />
          </ClaimsProviderSelections>
          <ClaimsExchanges>
            <ClaimsExchange Id="LocalAccountSigninEmailExchange" TechnicalProfileReferenceId="SelfAsserted-LocalAccountSignin-Email" />
          </ClaimsExchanges>

        </OrchestrationStep>

        <!-- Check if the user has selected to sign in using one of the social providers -->
        <OrchestrationStep Order="2" Type="ClaimsExchange">
          <Preconditions>
            <Precondition Type="ClaimsExist" ExecuteActionsIf="true">
              <Value>objectId</Value>
              <Action>SkipThisOrchestrationStep</Action>
            </Precondition>
          </Preconditions>
          <ClaimsExchanges>
            <ClaimsExchange Id="GoogleExchange" TechnicalProfileReferenceId="Google-OAUTH" />
            <ClaimsExchange Id="AzureADExchange" TechnicalProfileReferenceId="AzureADProfile" />
            <ClaimsExchange Id="SignUpWithLogonEmailExchange" TechnicalProfileReferenceId="LocalAccountSignUpWithLogonEmail" />
          </ClaimsExchanges>
        </OrchestrationStep>

        <!-- For social IDP authentication, attempt to find the user account in the directory. -->
        <OrchestrationStep Order="3" Type="ClaimsExchange">
          <Preconditions>
            <Precondition Type="ClaimEquals" ExecuteActionsIf="true">
              <Value>authenticationSource</Value>
              <Value>localAccountAuthentication</Value>
              <Action>SkipThisOrchestrationStep</Action>
            </Precondition>
          </Preconditions>
          <ClaimsExchanges>
            <ClaimsExchange Id="AADUserReadUsingAlternativeSecurityId" TechnicalProfileReferenceId="AAD-UserReadUsingAlternativeSecurityId-NoError" />
          </ClaimsExchanges>
        </OrchestrationStep>

        <!-- Show self-asserted page only if the directory does not have the user account already (i.e. we do not have an objectId).
          This can only happen when authentication happened using a social IDP. If local account was created or authentication done
          using ESTS in step 2, then an user account must exist in the directory by this time. -->
        <OrchestrationStep Order="4" Type="ClaimsExchange">
          <Preconditions>
            <Precondition Type="ClaimsExist" ExecuteActionsIf="true">
              <Value>objectId</Value>
              <Action>SkipThisOrchestrationStep</Action>
            </Precondition>
          </Preconditions>
          <ClaimsExchanges>
            <ClaimsExchange Id="SelfAsserted-Social" TechnicalProfileReferenceId="SelfAsserted-Social" />
          </ClaimsExchanges>
        </OrchestrationStep>

        <!-- This step reads any user attributes that we may not have received when authenticating using ESTS so they can be sent
          in the token. -->
        <OrchestrationStep Order="5" Type="ClaimsExchange">
          <Preconditions>
            <Precondition Type="ClaimEquals" ExecuteActionsIf="true">
              <Value>authenticationSource</Value>
              <Value>socialIdpAuthentication</Value>
              <Action>SkipThisOrchestrationStep</Action>
            </Precondition>
          </Preconditions>
          <ClaimsExchanges>
            <ClaimsExchange Id="AADUserReadWithObjectId" TechnicalProfileReferenceId="AAD-UserReadUsingObjectId" />
          </ClaimsExchanges>
        </OrchestrationStep>
        <!-- The previous step (SelfAsserted-Social) could have been skipped if there were no attributes to collect
             from the user. So, in that case, create the user in the directory if one does not already exist
             (verified using objectId which would be set from the last step if account was created in the directory. -->
        <OrchestrationStep Order="6" Type="ClaimsExchange">
          <Preconditions>
            <Precondition Type="ClaimsExist" ExecuteActionsIf="true">
              <Value>objectId</Value>
              <Action>SkipThisOrchestrationStep</Action>
            </Precondition>
          </Preconditions>
          <ClaimsExchanges>
            <ClaimsExchange Id="AADUserWrite" TechnicalProfileReferenceId="AAD-UserWriteUsingAlternativeSecurityId" />
          </ClaimsExchanges>
        </OrchestrationStep>

        <OrchestrationStep Order="7" Type="SendClaims" CpimIssuerTechnicalProfileReferenceId="JwtIssuer" />

      </OrchestrationSteps>
      <ClientDefinition ReferenceId="DefaultWeb" />
    </UserJourney>
    </UserJourneys>

</TrustFrameworkPolicy>

A: Since the actual error could be due to a combination of policy and application configuration in the directory, I'll explain why these applications are required to be setup this way, and what could potentially be the issue. I am hoping that even if my guess on the root cause is wrong, this explanation will allow you to debug the issue further.
Think of an application that needs to validate a password for a user. Since the application does not have access to the password, one of the ways is to send an authentication request to login.microsoftonline.com with user's ID and password, and see if a token is successfully issued.
However, when this application sends a request, it must specify some resource, and must also have permissions on user's behalf to access that resource. A common workaround is for the administrator to grant permissions (i.e. consent) on behalf of all users.
IEF uses the same model. Your policy has two applications, one acts as client that gets a token on user's behalf to the resource. If you followed instructions on the "Custom Policies Get Started Page", then ProxyIdentityExperienceFramework is the client, and IdentityExperienceFramework is the resource. As per those instructions, only ProxyIdentityExperienceFramework can get a token to IdentityExperienceFramework on user's behalf and not vice versa.
Based on the error message in your logs, it seems that you may have reversed the IDs for the client and the resource:

The user or administrator has not consented to use the application
  with ID '307' named 'IdentityExperienceFramework'

That is, the client called IdentityExperienceFramework does not have access to get a token.
So you will need to check in the Azure AD portal which application has access to which application and update client ID and resource ID.
The second exception may really be by design, it's just telling you that the user that is being created in the directory already exists. This typically happens in sign up and, based on your policy settings, it will typically render an error message to the user indicating that the account already exists and they should instead sign in.

A: This error
The user or administrator has not consented to use the application with ID '307' named 'IdentityExperienceFramework'.

have you pressed the Grant Permissions button on this app within the AZURE AD blade within Azure
2nd exception
It looks like you are trying to write the user principal again and in your metadata it has the RaiseErrorIfUserPrincipalExists set to rue
The strange thing is neither really helps me to understand why your password doesnt work after a few hours
Best bet is to copy the policy here and we can attempt to tell you why your trying a write instead of a read


text:
Q: Golden ratio as a property of conic section (is it known?) I am looking for a proof of a discovery as follows:

Let $ABC$ be arbitrary triangle and $(\Omega)$ be an arbitrary circumconic of $ABC$ let  $A'B'C'$ is its tangential triangle of $ABC$ respect to $(\Omega)$. Let $BB'$ meet $AC$ at $D$ and $CC'$ meet $AB$ at $E$, let $DE$ meet the circumconic at $F$. A line through $F$ and parallel to $B'C'$ meets $AB$, $AC$ at $H$, $G$ (see Figure) then:
$$\frac{HG}{GF}=\frac{\sqrt{5}+1}{2}.$$

A: Consider generalizing the last line to

Let $I$ be a point on $B'C'$, and let $FI$ meet $AB$, $AC$ at $H$,
$G$.
Then the cross ratio of $H,F,G,I$ is the negative golden ratio: $$\frac{HG\cdot FI}{FG\cdot HI}=-\frac{1+\sqrt{5}}{2} = -\phi$$

The original version is the limit of the general version as $I$ goes to infinity.
But the general version is projectively invariant, so we can prove it using coordinates where $A$ is at vertical infinity, the conic is $y=x^2$, and the tangent at $A$ is the line at infinity.
Then the first coordinates are simple:
\begin{align}
A &= \infty(0,1)\\
B &= (b,\ b^2)\\
C &= (c,\ c^2)\\
A' &= ((b+c)/2,\ bc)\\
B' &= \infty(1,2c)\\
C' &= \infty(1,2b)\\
D &= (c,\ (b-c)^2+c^2)\\
E &= (b,\ (b-c)^2+b^2)\\
F &= ((1-\phi)b+\phi c,\ ((1-\phi)b+\phi c)^2)\\
\end{align}
and we can stop computing coordinates there. The graphic below shows the case $b=-1$, $c=2$.

(There is also another solution for $F$, not mentioned in the original question, which leads to switching $\phi$ and $1-\phi$ in the above and the below.)
We want to evaluate the cross ratio $(HG\cdot FI)/(FG \cdot HI)$. Since $I$ is a point at infinity, the $FI$ and $HI$ terms will cancel. Then we can compute the directed quotient $HG/FG$ from the $x-$coordinates, which are $c$ and $b$ for $G$ and $H$. This gives us the desired result:
$$\frac{HG\cdot FI}{FG \cdot HI}=\frac{HG}{FG}=\frac{b-c}{(b-c)(1-\phi)}=-\phi$$


text:
Q: search with list of comma seperated values using linq to sql What is the best way to handle the following database search scenario using asp.net mvc, sql server and linq to sql?
I have a simple search for people, by their first name and last name.  Based on the results, I would like to dynamically filter the results base on the people's City and Business.  This could be multiple cities or businesses (Denver, New York, etc. and Business A, Business B ect.)
Here is some psudeo code of what I need to do:
_db.People.where(p => p.City.Contains(Denver, New York, multiple parameters)
&& p.Business.contains(Denver, New York, multiple parameters);

I am passing these values back, separated by commas to be searched.  Current I am looping through each value to search the database and using the linq to sql .addrange function to build my updated lists.  I'm not sure if this is the best way to do this.  Is there a way instead to pass in a full list of comma separated values to compare?  I'm open to any options, Full Text Search or Stored Proceduce, I'm just not sure where to start.

A: var cities = commaSeparatedList.Split(',').Select(p => p.Trim());
var q = _db.People.Where(c => cities.Contains(c.City));


text:
Q: GL_TRIANGLE_STRIP and transparency problems I want to draw transparent polygon(a pyramid for example). Some faces appear transparent where as some faces appear opaque.
Im drawing using GL_TRIANGLE_STRIP.
I have enabled blend mode, but no luck.
Please see the attached image,

A: This happens because of the draw order of the triangles. Some triangles get drawn first, these write their depth values to the depth texture, then the next triangle comes along and checks if there's something in front of it. If there is, then it won't render.
If a triangle that is at the back renders first, then there's no problem, the triangle in front of it looks at the depth texture, sees that it has a greater z value so it gets correctly rendered, these are the places where the color is less transparent.
The problem arises when the triangle at the front renders first. It writes it's depth value to the depth buffer, then the triangle in the back comes along, sees that there's already something in front of it, so it doesn't get rendered.
You have multiple ways to solve this, you can disable depth testing, sort the triangles so they come in order or use an algorithm like depth peeling. Each of these algorithms have side effects or are simply very complex, this is why you don't see too much transparency in games.


text:
Q: Javascript / jquery function returning undefined If I do this:
test();

function test(){
  $('img').load(function(){
  alert(this.width);
 })
}

An alert is shown with the correct image width.
But, when I do this:
alert(test());

function test(){
  $('img').load(function(){
  return this.width;
 })
}

... the alert shows 'undefined'
Both examples are run from within the $(document).ready function. I think it got something to do with load(). But I can't figure out why alert works, but return doesn't.
thx!

A: Your test function always returns undefined because it doesn't have return statement.
return in your code belongs to the anonymous callback function.

A: I am not a JS ninja yet but I feel this has something to do with scopes. Im suspecting the this keyword in both situations are pointing to different objects.
final: in the second example at the moment alert is called, there is nothing to return to it for it to display anything. This is because the return is defined asynchronously; it will return whenever the image is finished loading.

A: Images are loaded asynchronously, so you better forget about return in this case. (See a detailed explanation at How do I return the response from an asynchronous call?).
If you have to handle the image's dimensions after loading, do it from the callback:
function test(){
    $('img').load(function(){
        // If you need to use this.width or this.height, do it from here
    });
}

You can also pass a callback to test:
function test(callback){
    $('img').load(callback);
}
function doSomething() {
    alert(this.width);
}
test(doSomething);


text:
Q: Could I avoid Array's "Object is possibly 'undefined'" of Typescript Error I got an error of error TS2532: Object is possibly 'undefined'. in typescript compile with strictNullChecks mode.
interface Hoge {
    num?: number;
}

const hoge: Hoge[] = [{ num: 1 }];

if (!!hoge && hoge.length > 0 && !!hoge[0] && !!hoge[0].num) {
    hoge[0].num.toString()
}

playground (please check strictNullChecks)
However, I thought these condition have completely avoided undefined typed hoge already.
I guess non-null assertion operator works well: hoge[0].num!, but I'm wondering if there are other type safed ways.


text:
Q: Action after a form is submitted Is there a way in which after a form is submitted you can change the value of a field?
I have a form where a select field is disabled, in order to post the form I enable it but immediately after I want it to be set back to disabled is true. This is my code:
    $("Form").submit(function() {
    $("#done", this).prop("disabled", false);
});

A: I cannot test it right now but try this approach:
$('Form').submit(function (e) {
   e.preventDefault();                        // don't submit multiple times
    $('Form.select').prop('disabled', true);  // Enable the select
   this.submit();                             // use the native submit method
   $('Form.select').prop('disabled', false);  // Disable the select
});

Let me know how this works out.
OR
    $('Form').submit(function (e) {
       e.preventDefault();                        // don't submit multiple times
       $('Form.select').prop('disabled', true);  // Enable the select
       $.post('action.php', $('Form').serialize());  // AJAX submit
       $('Form.select').prop('disabled', false);  // Disable the select
    });

Good luck!


text:
Q: VBA Excel split the string apart based on the last comma I would like to split my string in Excel between the address and postcode. I want to keep the postcode separately.
By selecting the option - Data -Text to column - delimited - comma-separated - the whole string is divided by 4 pieces, as 3 commas occur.
1 - 21 Willow Court,  1192 Christchurch Road, Bournemouth, BH7 6EG
I found, that it can be done in VBA Excel.
There are a few approaches below:
Excel VBA- remove part of the string
https://www.thespreadsheetguru.com/the-code-vault/2014/2/28/remove-last-character-from-string
How to delete last character in a string with VBA?
Removing last characters vba
How to i remove a text after '*' or '-' character using VBA in excel?
I prepared the VBA code like below:
   Sub Textremove()
   Dim c As Variant
   For Each c In Range("D1:D100")
   c.Value = Left(c.Value, InStr(c.Value, ",") - 1)
   Next c
   End Sub

I am receiving only:
1 - 21 Willow Court
and the error Invalid procedure call or argument, debugging the following line:
     c.Value = Left(c.Value, InStr(c.Value, ",") - 1)

So the breakdown occurs after the first comma instead of the last one.
I found an answer regarding this error:
invalid procedure call or argument left
And when my code looks like this:
  Sub Textremove()
  Dim c As Variant
  For Each c In Range("D1:D100")
  If InStr(c.Value, ",") > 0 Then
  c.Value = Left(c.Value, InStr(c.Value, ",") - 1)
  End If
  Next c
  End Sub

Then error doesn't occur anymore, but I am still getting the stuff until the first comma instead of the last one.
When I change the code a bit:
 Sub Textremove()
 Dim c As Variant
 For Each c In Range("D1:D100")
 If InStr(c.Value, ",") > 0 Then
 c.Value = Right(c.Value, InStr(c.Value, ","))
 End If
 Next c
 End Sub

I am getting 2 sentences from the right
Bournemouth, BH7 6EG
which are not fixed and change depending on the total length of the string.
How can I receive the string till the last comma instead of the first one?
How can I split the whole string between the address and postcode separately?
A good example is here:
https://trumpexcel.com/vba-split-function/
  Sub CommaSeparator()
  Dim TextStrng As String
  Dim Result() As String
  Dim DisplayText As String
  Dim i As Long
  TextStrng = Sheets("Final").Range("D1")
  Result = Split(TextStrng, ",", 1)
  For i = LBound(Result()) To UBound(Result())
  DisplayText = DisplayText & Result(i) & vbNewLine
  Next i
  MsgBox DisplayText
  End Sub

It admittedly splits the whole address, but it is counted still from the first comma.

A: In my case that works. I just added the UBound(Result())-1.
Sub CommaSeparator()
  Dim TextStrng As String
  Dim Result() As String
  Dim DisplayText As String
  Dim i As Long
  TextStrng = Sheets("Final").Range("D1")
  Result = Split(TextStrng, ",")
  For i = LBound(Result()) To UBound(Result()) - 1
  DisplayText = DisplayText & Result(i) & vbNewLine
  Next i
  MsgBox DisplayText
End Sub

A: In case you need VBA, maybe use:
Sub Test()

Dim str As String
Dim arr As Variant

str = "1 - 21 Willow Court, 1192 Christchurch Road, Bournemouth, BH7 6EG"
arr = Split(StrReverse(Replace(StrReverse(str), ",", "|", , 1)), "|")

End Sub

I reversed the whole string through StrReverse(), then used Replace() to replace only the 1st comma with a pipe-symbol (note the use of the Count parameter), reversed the string back and used a Split(). This returns:

An alternative would be to make use of the worksheetfunction REPLACE() instead of the VBA function which inconveniently is called the same.
Sub Test()

Dim str As String: str = "1 - 21 Willow Court, 1192 Christchurch Road, Bournemouth, BH7 6EG"
Dim arr As Variant

arr = Split(Application.Replace(str, InStrRev(str, ","), 1, "|"), "|")

End Sub

The main difference is now that Application.Replace does take a parameter to start the replacement at without cutting of the preceding text. We can find our starting position using InstrRev().

Both options return:

Just for fun I'll chuck in an regex solution:
Sub Test()

Dim str As String: str = "1 - 21 Willow Court, 1192 Christchurch Road, Bournemouth, BH7 6EG"
Dim arr As Variant

With CreateObject("vbscript.regexp")
    .Global = True
    .Pattern = "^.*(?=,)|[^,]+$"
    Set arr = .Execute(str)
End With

End Sub

This will return a "MatchCollectionObject" where you can call your results through: arr(0) and arr(1). A little bit of explaination of the pattern:

*

*^ - Start string anchor.

*.* - A greedy match of anything other than newline up to:

*(?=,) - Positive lookahead for a comma.

*| - Or match:

*[^,]$ - Anything other than comma up to the end string anchor.

See the online demo

A: Use the array returned by Split to rebuild the string however you like it e.g.:
Sub DoSplit()

s = "1 - 21 Willow Court, 1192 Christchurch Road, Bournemouth, BH7 6EG"
a = Split(s, ",")
finalString = a(0) & a(1) & a(2) & ", " & a(3)
MsgBox finalString

End Sub

A: I have sorted this in a different, 2-steps way.
First of all, I split a whole address, by using the formula from here:
Split address field in Excel
Sub Split()
  Dim MyArray() As String
  Dim Ws As Worksheet
  Dim lRow As Long, i As Long, j As Long, c As Long

  '~~> Change this to the relevant sheet name
  Set Ws = ThisWorkbook.Sheets("Final")

  With Ws
    lRow = .Range("E" & .Rows.Count).End(xlUp).Row

    For i = 1 To lRow
        If InStr(1, .Range("E" & i).Value, ",", vbTextCompare) Then
            MyArray = Split(.Range("E" & i).Value, ",")
            c = 1
            For j = 0 To UBound(MyArray)
                .Cells(i, c).Value = MyArray(j)
                c = c + 1
            Next j
        End If
      Next i
   End With
 End Sub

and next, I merged what I needed by using this hint:
Excel macro to concatenate one row at a time to end of file
Sub Merge()
Dim LastRow As Long
Dim Ws As Worksheet

Set Ws = Sheets("Final")

LastRow = Ws.Range("A" & Ws.Rows.Count).End(xlUp).Row

'~~> If your range doesn't have a header
Ws.Range("H1:H" & LastRow).Formula = "=A1&B1&C1"

'~~> If it does then
Ws.Range("H2:H" & LastRow).Formula = "=A2&B2&C2"
End Sub

and finally, I received:
1 - 10 Haviland Court  104 Haviland Road Bournemouth


text:
Q: Kubuntu 14.04 crashes on boot on Asus PC After successfully installing Kubuntu 13.10 (64bit) on my Asus PC, I tried to upgrade to 14.04.  After the upgrade completed and I tried to restart, the boot process crashes with a kernel panic, see screenshot below:

The same problem occurs when I try and boot directly from a USB stick  from the .iso image.
Version 13.10 however works just fine (I have to reinstall this old version now)

A: I'll be upgrading my ASUS eee to 14.04 (32bit) next week. I had problems with past kernal images. On a working version or from the command line I use;
Linux Image clean
lsb_release -a; uname -a; dpkg -l | grep linux-image
sudo apt-get --purge remove linux-image-3.11.0-12-generic
sudo apt-get --purge autoremove
sudo apt-get clean

The 1st line gives you all the images stored on your system. Remove all except for the most current. This has been resolving the problem for me. But once again - I'm using the 32bit not the 64bit version.
If it's remains an issue - file a bug report; and ask to extend the support life of 13.10 until the issues with 14.04 are resolved.


text:
Q: Fast hash function with collision possibility near SHA-1 I'm using SHA-1 to detect duplicates in a program handling files. It is not required to be cryptographic strong and may be reversible. I found this list of fast hash functions https://code.google.com/p/xxhash/ (list has been moved to https://github.com/Cyan4973/xxHash)
What do I choose if I want a faster function and collision on random data near to SHA-1?
Maybe a 128 bit hash is good enough for file deduplication? (vs 160 bit sha-1)
In my program the hash is calculated on chuncks from 0 - 512 KB.

A: Maybe this will help you:
https://softwareengineering.stackexchange.com/questions/49550/which-hashing-algorithm-is-best-for-uniqueness-and-speed

collisions rare: FNV-1, FNV-1a, DJB2, DJB2a, SDBM & MurmurHash

I don't know about xxHash but it looks also promising.
MurmurHash is very fast and version 3 supports 128bit length, I would choose this one. (Implemented in Java and Scala.)

A: Since the only relevant property of hash algorithms in your case is the collision probability, you should estimate it and choose the fastest algorithm which fulfills your requirements.
If we suppose your algorithm has absolute uniformity, the probability of a hash collision among n files using hashes with d possible values will be:

For example, if you need a collision probability lower than one in a million among one million of files, you will need to have more than 5*10^17 distinct hash values, which means your hashes need to have at least 59 bits. Let's round to 64 to account for possibly bad uniformity.
So I'd say any decent 64-bit hash should be sufficient for you. Longer hashes will further reduce collision probability, at a price of heavier computation and increased hash storage volume. Shorter caches like CRC32 will require you to write some explicit collision handling code.

A: Google developed and uses (I think) FarmHash for performance-critical hashing. From the project page:

FarmHash is a successor to CityHash, and includes many of the same tricks and techniques, several of them taken from Austin Appleby's MurmurHash.
...
On CPUs with all the necessary machine instructions, about six different hash functions can contribute to FarmHash's lineup. In some cases we've made significant performance gains over CityHash by using newer instructions that are now commonly available. However, we've also squeezed out some more speed in other ways, so the vast majority of programs using CityHash should gain at least a bit when switching to FarmHash.

(CityHash was already a performance-optimized hash function family by Google.)
It was released a year ago, at which point it was almost certainly the state of the art, at least among the published algorithms. (Or else Google would have used something better.) There's a good chance it's still the best option.

A: The facts:

*

*Good hash functions, specially the cryptographic ones (like SHA-1),
require considerable CPU time because they have to honor a number of
properties that wont be very useful for you in this case;

*Any hash function will give you only one certainty: if the hash values of two files are different, the files are surely different. If, however, their hash values are equal, chances are that the files are also equal, but the only way to tell for sure if this "equality" is not just a hash collision, is to fall back to a binary comparison of the two files.

The conclusion:
In your case I would try a much faster algorithm like CRC32, that has pretty much all the properties you need, and would be capable of handling more than 99.9% of the cases and only resorting to a slower comparison method (like binary comparison) to rule out the false positives. Being a lot faster in the great majority of comparisons would probably compensate for not having an "awesome" uniformity (possibly generating a few more collisions).

A: 128 bits is indeed good enough to detect different files or chunks. The risk of collision is infinitesimal, at least as long as no intentional collision is being attempted.
64 bits can also prove good enough if the number of files or chunks you want to track remain "small enough" (i.e. no more than a few millions ones).
Once settled the size of the hash, you need a hash with some very good distribution properties, such as the ones listed with Q.Score=10 in your link.

A: It kind of depends on how many hashes you are going to compute over in an iteration.
Eg, 64bit hash reaches a collision probability of 1 in 1000000 with 6 million hashes computed.
Refer to : Hash collision probabilities

A: Check out MurmurHash2_160. It's a modification of MurmurHash2 which produces 160-bit output.
It computes 5 unique results of MurmurHash2 in parallel and mixes them thoroughly. The collision probability is equivalent to SHA-1 based on the digest size.
It's still fast, but MurmurHash3_128, SpookyHash128 and MetroHash128 are probably faster, albeit with a higher (but still very unlikely) collision probability. There's also CityHash256 which produces a 256-bit output which should be faster than SHA-1 as well.


text:
Q: How to set legend labels in Google Chart Candlestick How can I set series labels for chart legend in candlestick Google chart?

Code:
var chart_options = {
    legend: {
        position: 'bottom'
    }
};

var chartdata = [
    [new Date(2014, 3, 1), 95,100,98,110, null,null,null,null],
    [new Date(2014, 3, 2), 98,98,102,103, null,null,null,null],
    [new Date(2014, 3, 3), 90,102,95,105, 91,103,96,106],
    [new Date(2014, 3, 4), 93,95,103,103, 94,96,104,104],
    [new Date(2014, 3, 5), 94,103,104,105, 95,104,105,106],
];

chart1 = new google.visualization.CandlestickChart(document.getElementById('chart'));
chart1.draw( google.visualization.arrayToDataTable(chartdata,true), chart_options);

Source: http://jsfiddle.net/martinba/xt7cvv3k/

A: I've found the solution. The key is to use syntax with google.visualization.DataTable:
// this is correct
var chartdata = new google.visualization.DataTable();
chartdata.addColumn( ... );
chartdata.addRows( ... );
chart1.draw(chartdata, chart_options);

instead of google.visualization.arrayToDataTable(...,true):
// this is wrong
var chartdata = [...];
chart1 = new google.visualization.CandlestickChart(document.getElementById('chart'));
chart1.draw( google.visualization.arrayToDataTable(chartdata,true), chart_options);

Full working JS:
var chart_options = {
    legend: {
        position: 'bottom'
    },
    hAxis: {
        //format: "H:mm"
    }
};

var chartdata = new google.visualization.DataTable();
chartdata.addColumn('datetime', 'Datum');
chartdata.addColumn('number', 'label 1');
chartdata.addColumn('number', '');
chartdata.addColumn('number', '');
chartdata.addColumn('number', '');
chartdata.addColumn('number', 'label 2');
chartdata.addColumn('number', '');
chartdata.addColumn('number', '');
chartdata.addColumn('number', '');
chartdata.addRows([
    [new Date(2014, 3, 1), 95,100,98,110, null,null,null,null],
    [new Date(2014, 3, 2), 98,98,102,103, null,null,null,null],
    [new Date(2014, 3, 3), 90,102,95,105, 91,103,96,106],
    [new Date(2014, 3, 4), 93,95,103,103, 94,96,104,104],
    [new Date(2014, 3, 5), 94,103,104,105, 95,104,105,106],
]);

chart1 = new google.visualization.CandlestickChart(document.getElementById('chart'));
chart1.draw(chartdata, chart_options);

jsfiddle: http://jsfiddle.net/martinba/xt7cvv3k/6/

A: You can read datatables and dataview on google
instead of google.visualization.arrayToDataTable(...,true):
use google.visualization.arrayToDataTable(...,false):
the boolean at the end indicates whether first row is data or labels.
f.e:
var data = google.visualization.arrayToDataTable([
       ['Experiment', 'Control','Control1','Control2','Control3','All','All1','All2','All3'],
       ['1236', 90,102,95,105, 91,103,96,106],
        ['1237', 93,95,103,103, 94,96,104,104],
        ['1238', 94,103,104,105, 95,104,105,106]
      ],
      false); // 'false' means that the first row contains labels, not data.

    chart1 = new google.visualization.CandlestickChart(document.getElementById('chart'));
    chart1.draw(data, chart_options);


text:
Q: python import another python script not working I have two python scripts which are in the same directory(C:\\Users\\user1\\general). I want to execute a function in one script from the 2nd second script and so I am trying to import script1 in script2. Here is my script2:
import sys
sys.path.insert(0, 'C:\\Users\\user1\\general')
import script1
from flask import Flask
from flask_socketio import SocketIO, send

app = Flask(__name__)
app.config['SECRET_KEY'] = 'mysecret'
socketio = SocketIO(app)

@socketio.on('message')
def handleMessage(msg):
    print('Message: ' + msg)
    # script1 has function called api_call(id,message)
    messsage = api_call('user1', msg)
    send(messsage, broadcast=True)

if __name__ == '__main__':
    socketio.run(app)

Here is my script1:
import sys

def api_call(Id,message):
    # Code processing

if __name__ == '__main__':

    uId = sys.argv[0]
    message = sys.argv[1]
    api_call(userId,message)

When I execute above script2 I get NameError: name 'api_call' is not defined. It seems somehow the script1 is not getting imported and so the function is not getting through.
Note: Earlier I had tried without using sys.path.insert() and same outcome then also.

A: Try from script1 import api_call: this would allow to import from script1 module the api_call function.

A: Python 2
Create __init__.py in the same folder.
Import using following command
from script1 import api_call

Python 3
Import using following command
from .script1 import api_call


text:
Q: How do I configure traefik w/ docker-compose to route more than one port for a service I would like to configure traefik via docker-compose to expose more than one port of a component service.
For instance, when serving an ember-cli app, how can I expose both the main port and the live-reload port for development?

A: If you need to bind multiple ports of a container, you have to use the traefik..* labels described here in the documentation. For example something like this could be used in docker-compose.yml
  labels:
    - traefik.ember.port=8080
    - traefik.ember.frontend.rule=Host:mydomain.com
    - traefik.reload.port=37531
    - traefik.reload.frontend.rule=Host:mydomain.com;PathPrefixStrip:/reload


text:
Q: Swiper not working in Angular 5 I'm trying to integrate nolimts4web swiper into my Angular 5 project, I used in my index.html file

    ...
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/Swiper/4.2.2/css/swiper.min.css">

    ...

Put this in my HTML file:

Slide 1

Slide 2

Slide 3

And initialised by putting this right before the end of the body tag in index.html:

Whats happening is that it shows the slide 1 in the swiper however clicking next button does nothing and I can't swipe, basically actions are not working.

A: Please use this library to avoid Swiper init before html is loaded.
---- UPDATE 1 ----
in my opinion, your issue is related to the life cycle of your HTML, that means, Swiper is initialize before html are loaded/interpreted by the browser. To avoid this issue, you can use linked library or just create component who looks like :
// Don't forget to declare Global variable related to Swiper.
declare var Swiper: any;

@Component({
  selector: 'swiper',
  template: `

Slide 1

Slide 2

Slide 3

`
})
export class SwiperComponent implements AfterViewInit {
    constructor(
        private elementRef: ElementRef
    ) {}

    //[...]

    ngAfterViewInit() {
        /**
         * - Here you are 100% sure, html is present on DOM, Swiper is initialize and is able to find your DOM element.
         * - Swiper constructor accept DOMElement as parameter, i recommand this approch to optimize DOM parsing.
         * - Because you store Swiper instance as attribute, you will be able to control Swiper by javascript.
        **/
        this.swiper = new Swiper(this.elementRef.nativeElement.querySelector('.swiper-container'), {
            //Here you can provide Swiper config
        });
    }
}

Online sample

A: I've been looking for the answer for a long time.
In my case, I had an outdated swiper package. (https://www.npmjs.com/package/angular2-useful-swiper).
I uninstalled it and installed this npm: https://github.com/JayChase/ngx-useful-swiper (last version) for angular 7 then I followed the examples and now everything's okay.


text:
Q: Docker & Php - .env (оркружающая среда) Хочу передать в php, который находится в контейнере, переменные среды, в которых содержится пароль и данные для подключения к mysql.
Файл среды называется .env. Пробовал вот так:
  php:
    build: ./php
    volumes:
      - ./html/:/var/www/html
    expose:
      - "9000"
    depends_on:
      - mysql
    env_file: .env

И потом в php:
<?php var_dump(getenv('MYSQL_DATABASE'));?>

<?php var_dump(getenv('MYSQL_USER'));?>

<?php var_dump(getenv('MYSQL_PASSWORD'));?>

Вывод:
bool(false)
bool(false)
bool(false)
Запускаю из Dockerfile-а для PHP таким образом:
COPY ./test.php /var/www
RUN php /var/www/test.php

Подскажите, пожалуйста, что не так делаю
.env файл:
MYSQL_DATABASE=opencart
MYSQL_USER=opencart
MYSQL_PASSWORD=password
MYSQL_PORT=3306
MYSQL_ROOT_PASSWORD=root

A: Попробуйте таким образом
version: '2.0'
services:
  ldap_server:
    image: my-image
    container_name: my-image
    restart: unless-stopped
    env_file:
      - .env


text: Q: Android Studio 3 minSdk below 14 I have an old phone running Android 2.3.6 (API 10). It was still supported in Android Studio 2.1.3, which I used for a long time, but in Android Studio 3, the lowest possible sdk is 14. The app I make is only for my personal use. So, is there a way to set minSdk to 10, or should I downgrade Android Studio? If so, which version still supported 2.3.6?


text:
Q: I'm drawing images in visual basic using a loop but only the most recent image is visible First - Some background.
I'm building a pizza ordering app (school assignment) which lets you choose your toppings and then draws those toppings on a pizza when you check a box. I have an array of different pepperoni pictures and when the checkbox is selected I'm randomly drawing 38 pepperonis within the radius of the pizza. (I may have to fine tune this later). I've got it working... but when I draw - Only the last pepperoni is visible. Here's my code:
Public Class ToppingsPage
Private Img1 As Image = Image.FromFile("C:\Users\dunnage\Desktop\Visual Studio School Files\Pizza Images\Toppings\P-1.png")
Private handTossed As Image = Image.FromFile("C:\Users\dunnage\Documents\Visual Studio 2015\Projects\pizzaTest\Images\hand tossed.png")
Private handMade As Image = Image.FromFile("C:\Users\dunnage\Documents\Visual Studio 2015\Projects\pizzaTest\Images\deepdish in pan.png")
Private thinCrust As Image = Image.FromFile("C:\Users\dunnage\Documents\Visual Studio 2015\Projects\pizzaTest\Images\thin.png")
Private brooklynStyle As Image = Image.FromFile("C:\Users\dunnage\Documents\Visual Studio 2015\Projects\pizzaTest\Images\brooklyn style.png")

Private pepperoniOne As Image = Image.FromFile("C:\Users\dunnage\Documents\Visual Studio 2015\Projects\pizzaTest\Images\Toppings\P-1.png")
Private pepperoniTwo As Image = Image.FromFile("C:\Users\dunnage\Documents\Visual Studio 2015\Projects\pizzaTest\Images\Toppings\P-2.png")
Private pepperoniThree As Image = Image.FromFile("C:\Users\dunnage\Documents\Visual Studio 2015\Projects\pizzaTest\Images\Toppings\P-3.png")

Private pTopping As Boolean = False

Private Sub Form1_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles Me.Paint
    If Form1.pizzaType = 1 Then
        e.Graphics.DrawImage(handTossed, 360, 10)
    End If
    If Form1.pizzaType = 2 Then
        e.Graphics.DrawImage(handMade, 360, 10)
    End If
    If Form1.pizzaType = 3 Then
        e.Graphics.DrawImage(thinCrust, 360, 10)
    End If
    If Form1.pizzaType = 4 Then
        e.Graphics.DrawImage(brooklynStyle, 360, 10)
    End If
    If pTopping = True Then
        Dim counter = 0
        Dim imgPic(3) As Image
        imgPic(0) = pepperoniOne
        imgPic(1) = pepperoniTwo
        imgPic(2) = pepperoniThree
        Dim value As Integer = CInt(Int((2 * Rnd()) + 0))
        Dim xCoord As Integer = CInt(Int((500 * Rnd()) + 370))
        Dim yCoord As Integer = CInt(Int((300 * Rnd()) + 20))
        Do Until counter > 38
            Dim i = imgPic(value)
            e.Graphics.DrawImage(i, xCoord, yCoord)
            counter += 1
        Loop
    End If
End Sub

Private Sub CheckBox1_CheckedChanged(sender As Object, e As EventArgs) Handles CheckBox1.CheckedChanged
    pTopping = True
    Me.Refresh()
End Sub

End Class

A: Ahhhh I think i got it. I'm creating my random x,y coordinates outside the loop so the image is being redrawn in the same location over and over and over.
Here's the right code:
If pTopping = True Then
        Dim counter = 0
        Dim imgPic(3) As Image
        imgPic(0) = pepperoniOne
        imgPic(1) = pepperoniTwo
        imgPic(2) = pepperoniThree
        Do Until counter > 38
            Dim value As Integer = CInt(Int((2 * Rnd()) + 0))
            Dim i = imgPic(value)
            Dim xCoord As Integer = CInt(Int((500 * Rnd()) + 370))
            Dim yCoord As Integer = CInt(Int((300 * Rnd()) + 20))
            e.Graphics.DrawImage(i, xCoord, yCoord)
            counter += 1
        Loop
    End If

And here's a picture of the results...

I've got a little fine tuning to do.
Okay... So I'm working the polar coordinate angle (pun intended) and I've got it working but I'm having trouble wrapping my head around how to move the origin. Here's my code:
Public Class polarAndCartesian

Property X As Double
    Property Y As Double
    Sub New(Radius As Double, AngleDegree As Double)
        Dim AngleRadian As Double = AngleDegree * 2 * Math.PI / 360
        X = Radius * Math.Cos(AngleRadian)
        Y = Radius * Math.Sin(AngleRadian)
    End Sub
End Class

Public Class CartesianToPolar
    Property Radius As Double
    Property AngleRadian As Double
    ReadOnly Property AngleDegree As Double
        Get
            Return AngleRadian * 360 / (2 * Math.PI)
        End Get
    End Property

    Sub New(X As Double, Y As Double)
        Radius = (X ^ 2 + Y ^ 2) ^ 0.5
        AngleRadian = Math.Atan2(Y, X)
    End Sub

End Class

And this is how I'm drawing them:
    If pTopping = True Then
        Dim counter = 0
        Dim imgPic(3) As Image
        imgPic(0) = pepperoniOne
        imgPic(1) = pepperoniTwo
        imgPic(2) = pepperoniThree
        Do Until counter > 38
            Dim value As Integer = CInt(Int((3 * Rnd()) + 0))
            Dim i = imgPic(value)
            Dim PTC As New polarAndCartesian(CInt(Int((60 * Rnd()) + 0)), CInt(Int((360 * Rnd()) + 0)))
            e.Graphics.DrawImage(i, CInt(PTC.X), CInt(PTC.Y))
            counter += 1
        Loop
    End If

And this is the end result:


text:
Q: Aliases: difference between .bash_rc, .bash_aliases and /usr/local/bin Playing around with Terminal, I noticed that there are many ways to create permanent aliases.
I'm a Linux newbie, and from what I know, doing:

*

*sudo ln -s /path/to/executable /usr/local/bin/desired_alias

*adding desired_alias = '/path/to/executable' to ~/.bashrc

*uncommenting those lines in ~/.bashrc:
if [ -f ~/.bash_aliases ]; then
    . ~/.bash_aliases
fi

and putting desired_alias = '/path/to/executable' into the ~/.bash_aliases
all have the same effect.
What is the difference between the first and second methods?

A: With the first method you are not creating an alias, you are creating a symlink. Symlinks are short for symbolic links:

Symbolic  links  are files that act as
  pointers to other files. [...] A
  symbolic link is a special type of
  file whose contents are a string that
  is the pathname another file, the file
  to which the link refers.  In other
  words, a symbolic link is a pointer to
  another name, and not to an underlying
  object.

Read more about symlinks here and here.
Only with the second method you are, in fact, creating an alias.

Aliases  allow  a  string  to be
  substituted for a word when it is used
  as the first word of a simple command.
  The shell maintains a list of aliases
  that may be set and unset with the
  alias and unalias builtin commands
  (see SHELL BUILTIN COMMANDS  below).
  The  first  word of each simple
  command, if unquoted, is checked to
  see if it has an alias. If so, that
  word is replaced by the text of the
  alias.

You can define an alias anywhere where you can type a command and have the shell (bash in this case) interpret it, however in order for the alias to be available in other shells it needs to be defined in a file that's interpreted by the shell on startup (shell startup, not computer startup).
For bash these are /etc/bash.bashrc (system wide) and ~/.bashrc. These files are interpreted when the shell starts in interactive mode (like when using Terminal). I'm not going to mention the profile files because they serve a different purpose.
So, you want to add your aliases to ~/.bashrc to have them available in every interactive shell.
The .bash_aliases method accomplishes exactly the same thing as putting the aliases in ~/.bashrc but has the added benefit of being easier to be parsed and manipulated by programs.
The . ~/.bash_aliases means source (load) _~/.bash_aliases_ in the context of the currently running shell.


text:
Q: SwiftUI JSON Decoder not Working (using async await) I am creating a new version of an existing app and want to use the new async await
format for a web request. Placing a break at the JSONDecoder().decode line I see that I do have data -
but the decoding does not work. (The url and my key DO work in the old version)
Here's the JSON format of the web source (shortened - there are many more items in
a fuel_station):
{
   "station_locator_url":"https://afdc.energy.gov/stations/",
   "total_results":110,
   "station_counts":{},
   "fuel_stations":[
      {
         "access_code":"public",
         "access_days_time":"24 hours daily; call 866-809-4869 for Clean Energy card",
         "access_detail_code":"KEY_ALWAYS",
         "cards_accepted":"CleanEnergy",
         "date_last_confirmed":"2021-09-10",
      }
   ]
}

I created the following models from the above:
enum CodingKeys: String, CodingKey {
    case fuelStations = "fuel_stations"
    case accessCode = "access_code"
    case accessDaysTime = "access_days_time"
    case accessDetailCode = "access_detail_code"
    case cardsAccepted = "cards_accepted"
    case dateLastConfirmed = "date_last_confirmed"
}

struct TopLevel: Codable {
    let fuelStations: [FuelStation]
}

struct FuelStation: Codable {
    let accessCode, accessDaysTime, accessDetailCode, cardsAccepted: String
    let dateLastConfirmed: String
    let id: String
}

I put a simplified version of the initial view in one file for testing:
struct SiteListView: View {
    @State private var fuelStations: [FuelStation] = []
    @State private var topLevel: TopLevel = TopLevel(fuelStations: [])

    var body: some View {
        NavigationView {
            VStack {
                List(fuelStations, id: \.id) { item in
                    VStack {
                        Text(item.accessCode)
                        Text(item.accessDaysTime)
                    }
                }
            }
            .navigationTitle("Site List View")
            .task {
                await loadData()
            }
        }//nav
    }

    func loadData() async {

    //I believe the DEMO_KEY in the url will allow limited retrievals
        guard let url = URL(string: "https://developer.nrel.gov/api/alt-fuel-stations/v1.json?api_key=DEMO_KEY") else {
            print("Invalid URL")
            return
        }

        do {
            let (data, response) = try await URLSession.shared.data(from: url)
            guard (response as? HTTPURLResponse)?.statusCode == 200 else { return }
            print("response status code is 200")

            if let decodedResponse = try? JSONDecoder().decode(TopLevel.self, from: data) {
                topLevel = decodedResponse
                print("in decoding: topLevel.fuelStations.count is \(topLevel.fuelStations.count)")
                //I would iterate through topLevel here and add to the fuelStations
                //array but I never get here
            }
        } catch {
            print("Invalid Data")
        }

    }//load data
}//struct

Any guidance would be appreciated. Xcode 13.2.1 iOS 15.2

A: First you should remove ? from try? for the catch to work when there is a problem in decoding like this
func loadData()  async {
   //I believe the DEMO_KEY in the url will allow limited retrievals
   guard let url = URL(string: "https://developer.nrel.gov/api/alt-fuel-stations/v1.json?api_key=DEMO_KEY") else {
       print("Invalid URL")
       return
   }

   do {
       let (data, response) = try await URLSession.shared.data(from: url)
       guard (response as? HTTPURLResponse)?.statusCode == 200 else { return }
       print("response status code is 200")
       let decoder = JSONDecoder()
       decoder.keyDecodingStrategy = .convertFromSnakeCase
       let decodedResponse = try decoder.decode(TopLevel.self, from: data)
       print("in decoding: topLevel.fuelStations.count is \(decodedResponse.fuelStations.count)")
       //I would iterate through topLevel here and add to the fuelStations
       //array but I never get here

   } catch {
       print(error)
   }
}

After you do this , you'll find that some attributes in your struct are coming null in response so you should change string to string? to finally be
struct TopLevel: Codable {
    let fuelStations: [FuelStation]
}

struct FuelStation: Codable {
    let accessCode, accessDaysTime, accessDetailCode, cardsAccepted,dateLastConfirmed: String?
    let id: Int
}

In addition note use of
   let decoder = JSONDecoder()
   decoder.keyDecodingStrategy = .convertFromSnakeCase

instead of hard-coding the enum


text:
Q: compare text and highlight difference I have text in two cells with different text. I'm attempting to identify the diff (difference between the text: text that is added or missing) between the two cells.
Example :

A1:ThisisasystemgeneratedmentanddoesnotrequiresignatureAnyunauthorizedusedisclosuredisseminationoringofthisdocumentisstrictlyprohibitedandmaybeunlawful
B1:Thisisasystemgenerateddocumentanddoesnotrequiresignatureunauthorizedusedisclosuredisseminationorcopyingofthisdocumentisstrictlyprohibitedandmaybeunful

Both cells A1 and B1 should highlight only textual differences. How do I implement this?

A: This is actually a pretty tricky scenario, but here you go:
Public Sub FindDistinctSubstrings()
    Dim a$, b$, i&, k&, rA As Range, rB As Range
    Set rA = [a1]: a = rA
    Set rB = [b1]: b = rB
    k = Len(a): If Len(b) > k Then k = Len(b)
    Do
        i = i + 1
        If Mid$(a, i, 1) <> Mid$(b, i, 1) Then
            Align i, a, b, rA, rB
        End If
        DoEvents
    Loop Until i > k
    k = Len(a): If Len(b) > k Then k = Len(b)
    For i = 1 To k
        If Mid$(a, i, 1) = "." Then rB.Characters(i, 1).Font.Color = vbRed
        If Mid$(b, i, 1) = "." Then rA.Characters(i, 1).Font.Color = vbRed
    Next
    Do
        k = InStr(rA, "."): If k Then rA.Characters(k, 1).Delete
    Loop Until k = 0
    Do
        k = InStr(rB, "."): If k Then rB.Characters(k, 1).Delete
    Loop Until k = 0
End Sub
Private Sub Align(k&, a$, b$, rA As Range, rB As Range)
    Dim i&, iMax&, nI&, nMaxI&, j&, jMax&, nJ&, nMaxJ&
    Const LOOK_AHEAD_BUFFER = 30
    For i = 0 To LOOK_AHEAD_BUFFER
        nI = CountMatches(Space$(i) & Mid$(a, k, LOOK_AHEAD_BUFFER), Mid$(b, k, LOOK_AHEAD_BUFFER))
        If nI > nMaxI Then
            nMaxI = nI: iMax = i
        End If
    Next
    For j = 0 To LOOK_AHEAD_BUFFER
        nJ = CountMatches(Mid$(a, k, LOOK_AHEAD_BUFFER), Space$(j) & Mid$(b, k, LOOK_AHEAD_BUFFER))
        If nJ > nMaxJ Then
            nMaxJ = nJ: jMax = j
        End If
    Next
    If nMaxI > nMaxJ Then
        a = Left$(a, k - 1) & String$(iMax, ".") & Mid$(a, k)
        rA = a: k = k + iMax
    Else
        b = Left$(b, k - 1) & String$(jMax, ".") & Mid$(b, k)
        rB = b: k = k + jMax
    End If
End Sub
Private Function CountMatches(a$, b$) As Long
    Dim i&, k&, c&
    k = Len(a): If Len(b) < k Then k = Len(b)
    For i = 1 To k
        If Mid$(a, i, 1) = Mid$(b, i, 1) Then c = c + 1
    Next
    CountMatches = c
End Function


text:
Q: WPF/MVVM - Is there is any event fired after GUI get updated In my application I used to add a lot of text in Richtextbox. It takes a lot of time, so i have added a progress bar. I need to close that as soon as GUI is updated. Is there is any to to catch after GUI is updated.
I have tried with App.Current.MainWindow.IsLoaded == true, but it seems even the gui is not updated, but MainWindow.IsLoaded property is true for main window.
Herewith the code for the same.
   private void OnWorkerMethodstart()
    {
        pbw = new ProgressBarWindow();
        pbw.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal,
        new Action(
        delegate()
        {
            pbw.ShowDialog();
        }
        ));
    }

private void OnWorkerMethodStart()
    {
        ThreadStart tStart = new ThreadStart(OnWorkerMethodstart);
        t = new Thread(tStart);
        t.SetApartmentState(ApartmentState.STA);
        t.Start();
        this.OpenW();

        BackgroundWorker _BackgroundWorker1 = new BackgroundWorker();
        _BackgroundWorker1.DoWork += new DoWorkEventHandler(
        delegate(object o, DoWorkEventArgs args)
        {
            this.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal,
                new Action(
                delegate()
                {
                    DateTime da = DateTime.Now.AddMinutes(30);
                    MainWindow mw;
                    while (DateTime.Now != da)
                    {

                        mw = new MainWindow();
                        //if (mw.Editor.Workflow.Steps.Count > 1)
                        if (App.Current.MainWindow.IsLoaded == true)
                        {
                            t.Abort();
                            break;
                        }
                        else
                        {
                            //Thread.Sleep(1000);
                        }
                        mw = null;
                    }
                }
                ));
        });

        _BackgroundWorker1.RunWorkerAsync();

    }


text:
Q: How do I make my own alias override a module's alias? I have an alias for touch created in my $profile, however I also use PSCX seems to have it's own touch. When I run touch the PSCX one runs:
$ which touch
Pscx\Set-FileTime

How do I make PowerShell prefer my alias over the modules alias?

A: In your $PROFILE:

*

*First, explicitly import the PSCX module - at that point, that module's touch alias is imported and would replace any existing definition: Import-Module PSCX

*

*Note: Add Import-Module PSCX even if it currently isn't in your $PROFILE; typically, the module is auto-loaded, on demand, by virtue of being located in one of the directories listed in the $env:PSModulePath environment variable.
It is that on-demand importing - whose timing is unpredictable (whenever you first happen to call a command from the module) - that prevents reliable alias replacement; forcing import of the module in your $PROFILE before you define your version of the alias solves that problem.

*Then redefine the alias as needed; e.g.: Set-Alias touch touch.exe

*

*Caveat: If someone forcefully re-imports the  module later with Import-Module -Force PSCX, your alias will again be replaced.

Note: It's not necessary for the specific alias in question, but in order to replace aliases that are defined with -Option AllScope (true for built-in aliases such as dir and select), you're faced with two suboptimal choices:

*

*Either: Redefine it with -Option AllScope, which, however, means that all scopes will see the new definition; e.g., Set-Alias -Option AllScope touch touch.exe.

*Or: Remove the original alias first - e.g., Remove-Item alias:touch (PSv6+: Remove-Alias touch) - and then define it as needed, which, however, means that other scopes will no longer see the original definition.

A: Making this an answer rather than comment so I can type more text.
See https://serverfault.com/questions/452430/how-to-override-the-default-dir-alias-in-powershell
Opinion follows:
However, depending on your usage, I would strongly recommend against using aliases in any script or module as they can be changed and may not perform the actions you want.
If you really want to use an alias, I might just avoid all this and create a non-conflicting alias that still makes sense.  Maybe tf or tfile for TouchFile.


text:
Q: Google reCaptcha reset doesn't work I want to reset Google reCaptcha widget when I submit my form via AJAX and have some input errors or form is sent. I'm using multiple widgets on the same page so I render these widgets explicitly.
My HTML code:

...

Loading widget

After submit form:
var id = $('.g-recaptcha', form).attr('id');
grecaptcha.reset(id);

Form is the instance of the submitted form.
Everything works fine when form is fill correctly. But reCaptcha doesn't reset or reload.
It try this grecaptcha.reset() but no results.
Any idea?

A: The grecaptcha.reset() method accepts an optional widget_id parameter, and  defaults to the first widget created if unspecified. A widget_id is returned from the grecaptcha.render() method for each widget created. So you need to store this id, and use it to reset that specific widget:
var widgetId = grecaptcha.render(container);
grecaptcha.reset(widgetId);

See here.

A: You are passing the wrong id.
$('.g-recaptcha', form).attr('id');
Your selector will capture all 20 reCaptcha widget, but only return a single DOM id (the first reCaptcha). So your code is actually resetting the first recaptcha.

A: Just edited your code to create a dynamic widget.

And after you have successfully completed the above task, change in the AJAX success: response
grecaptcha.reset(widgetId+id);

Here the id would be the same that is generated from the below for Loop.

A: I have two google captcha in same page, two different form
<form id="form1">
<input type="text" name="form1-input">

</form>

and
<form id="form2">
<input type="text" name="form2-input">

</form>

You can reset first captcha by
 grecaptcha.reset(); or grecaptcha.reset(0);

And Second Captcha by index (1)
grecaptcha.reset(1);

A: I had an issue where there were multiple recaptchas on the page, some were hidden. In this case I had to loop through all of them and reset them like this:
                var count = 0;
                $(".g-recaptcha").each(function () {
                    grecaptcha.reset(count);
                    count++;
                });


text:
Q: Indexing a cell in MATLAB with a vector Assume that I am given the cell M, and a vector v, and assume that v holds a correct address for an element in M. Without any apriori knowledge of the structure of M and v, I wish to fetch the element from M that v points to. How can I do this? For instance, M{v} does not quite do what I need:
say M = cell(3,4,5), v = [1,2,3], then doing M{v} produces [M{1}, M{2}, M{3}].
So my question is: how can I encapsulate an address of a cell element into a variable v and later fetch the element at that address from the given cell?
The same question for any array instead of cell.

A: v has to be a cell not a vector, then you can use sub2ind:
v=mat2cell(v(:),ones(numel(v),1))
M(sub2ind(size(M),v{:}))


text:
Q: retorno do firebase Galera, gostaria de ajuda com relação ao retorno do firebase, é o seguinte, no meu projeto angular tenho um componente com alguns campos a serem validados e um serviço somente para validações, estou tendo dificuldade de pegar um retorno como eu preciso, segue o código
meu componente formulario.ts tenho:
nextPage() {
if(this.serviceValidate.validaEmail(this.dataForm.value.gn_email)) {
   return;
 }
}

Em meu serviço de validação tenho ValidaUsuario.service.ts tenho:
  validaEmail(email: string): any {
let valida = /^[a-zA-Z0-9][a-zA-Z0-9\._-]+@([a-zA-Z0-9\._-]+\.)[a-zA-Z-0-9]{2,3}$/;
 //1º validação
if(email == '') {
  this.snackbar.openSnackBar('Campo email obrigatório');
  return false;

//2º validação
} else if(!valida.exec(email)) {
  this.snackbar.openSnackBar('Email não é valido, tento outro!');
  return false;
}

// 3º validação
 var data =  this.db.list(this.PATH,
 ref => ref.orderByChild('gn_email')
           .equalTo(email))
           .valueChanges();
}

Se possível, gostaria de pegar um boolean nesta 3º validação, já testei duas maneiras
assim
var data =  this.db.list(this.PATH,
    ref => ref.orderByChild('gn_email')
               .equalTo(email))
               .valueChanges();

e assim :
   firebase.database().ref(this.PATH)
 .ref.orderByChild('gn_email')
 .equalTo(email)
 .on('child_added', function(snapshot) {
   console.log(snapshot.exists())
   var data = snapshot.exists();
// })

Como pegar o retorno sem fazer o subscribe no component ?


text:
Q: Is it possible to vertically align text in a div with `display: -webkit-box;` I'm working with a div which has the following css attribute assigned to it: display: -webkit-box;.
This div of mine contains text which I'd like to align vertically to the middle. Is this possible without changing the display attribute given to the div?
Additional Info:
I'm using the latest version of Chrome and have tried vertical-align: middle; which failed.

A: There are two cases of -webkit-box-orient depending on it's value:

*

*-webkit-box-orient: vertical: you shoud use -webkit-box-pack: center to vertical align the text.

*-webkit-box-orient: horizontal: you shoud use -webkit-box-align: center to vertical align the text.
All of these cases are similar to the alignment in flexBox.

A: The following statement works for me:
-webkit-box-align: center;

https://jsfiddle.net/awt39v5s/1/
For the "old" flexbox definition, https://www.smashingmagazine.com/2011/09/css3-flexible-box-layout-explained/ is a good resource.

A: The children should be display block.
And use in parent element:
-webkit-box-orient: horizontal;
        -webkit-box-align: end;


text:
Q: How to send an email in Angular I'm interested in sending an email in Agular or in Typescript in such a way that they click on a certain email address and then it will open in Gmail
And can't do it in any way

A: To open an email using the user's preferred email client you can use a normal anchor tag:
Send an email

You can also handle phone numbers and other types this way: Mozilla Docs for Anchor Tags