text:
Q: how to animate two things at the same time in jquery I want to animate 2 things at same time when mouse hovers something.
for example I want to change background color of box1 with id = "box1" and position of box2 with id="box2" when mouse hovers a div with id="trigger".
but I don't want them to animate in a queue, i.e. one after another. I want them to start animating at same time and finish at same time!

A: When the first animation starts, the next line of code executes without waiting for the animation to finish.
So to do two things at once:
$('#trigger').hover(function()
{
    $('#box1').animate({ ... });
    $('#box2').animate({ ... });
});

A: Check out jQuery.animate() docs. There is queue property:

queue: A Boolean indicating whether to place the animation in the effects queue. If false, the animation will begin immediately.

A: While it's true that consecutive calls to animate will give the appearance they are running at the same time, the underlying truth is they're distinct animations running very close to parallel.
To insure the animations are indeed running at the same time use:
$('#trigger').hover(function() {
    $('#box1').animate({..., queue: 'trigger-hover'});
    $('#box2').animate({..., queue: 'trigger-hover'}).dequeue('trigger-hover');
});

Further animations can be added to the 'trigger-hover' queue and all can be initiated provided the last animation dequeue's them.
Cheers,
Anthony

A: You can just run them in a row, like this:
$("#trigger").hover(function() {
   $("#box1").stop().animate({ backgroundColor: '#000000' });
   $("#box2").stop().animate({ top: "-20px" });
}, function() {
   $("#box1").stop().animate({ backgroundColor: '#FFFFFF' }); //set it back
   $("#box2").stop().animate({ top: "0px" });                 //set it back
});

This uses .hover() to animate one way when hovering, and animate them back when leaving.  The .stop() is just to prevent animation queue build-up.  To animate a color, you'll need either the color plugin, or jQuery UI included as well.
Animations in jquery, .animate(), are implemented using setInterval() with a 13ms timer, so they'll happen outside the normal flow...doing them like above doesn't wait for the first to finish, they'll run simultaneously.


text:
Q: Android WebView - Programmatically forcing numeric keyboard on 3rd party webpage's input field? Quick context: We have a pretty unique situation where we're switching to a new HR platform which will only allow our factory employees to timekeep via a timeclock webpage. We already have several Samsung Galaxy Tab A devices positioned throughout our building that serve as timeclock kiosks for the current HR system. Since we can only lock these tablets down to a single app at a time via Knox, a Chrome web browser for example would let employees accidentally navigate off the new platform's timeclock webpage and create issues for others trying to clock-in or out.
SO, we already setup an Android app that implements a basic WebView hard-coded to the timeclock URL the new HR company provided us. HOWEVER, the big problem here is that there's no on-page keyboard and the badge ID field is of type text, which invokes the Android qwerty keyboard for a badge ID PIN that would only ever be all numbers... A 3rd-party company built this webpage for the HR company so I'd be surprised if we could ever get it changed on their end.

Just to show some of our basic boilerplate to achieve the above...
AndroidManifest.xml
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="Paytime Time Clock"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.PaytimeWebpage"
        android:usesCleartextTraffic="true">
        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

MainActivity.java
    public class MainActivity extends AppCompatActivity {
        private WebView webView;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            webView = (WebView) findViewById(R.id.webview);
            webView.setWebViewClient(new WebViewClient());
            webView.setInitialScale(300);
            webView.loadUrl("https://site.time.clock");

            WebSettings webSettings = webView.getSettings();
            webSettings.setJavaScriptEnabled(true);

        }
    }

Activity_Main.xml
    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity">

    <WebView
        android:id="@+id/webview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
    </RelativeLayout>

We've done tons of exhaustive searching and really tried to think outside the box here but as only 2 SysAdmins at a small manufacturer we are by no means seasoned Java devs! We've tried researching and attempting the following ideas:

*

*Event listener for whenever the qwerty keyboard is invoked to then instead invoke the numeric or telephone keyboard

*Get HTML content from WebView, look for the <input type="text"> tag and try to programmatically change it to either number or tel in order to get the right keyboard to show

*Force our app to invoke the numeric keyboard and strictly keep it there above the web page

*We've seen guys mentioning the EditText class for configuring input and keyboard types, but the problem with that is of course that we're not handling the input in question here within our app, it's on someone else's webpage through our WebView

This is of course a very minor edge-case issue that we're forced to come up with a complicated solution to ourselves... We can observe which input types yield which keyboards on any Android device. All we have to do is get a numeric soft-keyboard shown on this WebView'd site within our app such that employees can easily walk up, input their badge and complete their clock action.
I hope this was concise but thorough... There must be a creative solution here, does anybody have any suggestions or recommendations of how we can accomplish this? Even just pointing us in the right direction would be hugely appreciated... THANKS!!

A: In your WebViewClient, override onPageFinished() and do the following in it:
webView.loadUrl("javascript:document.getElementById('FldBadge').getElementsByTagName('input')[0].type='number';");

The idea is to modify the loaded page so that it behaves the way you need.
UPDATE: Full code
        public class MyWebViewClient extends WebViewClient {
          public void onPageFinished (WebView view, String url) {
            if(url.equals("https://my.website.url")) {
webView.loadUrl("javascript:document.getElementById('FldBadge').getElementByTagName('input')[0].type='number';");
            }
          }
        }

Don't forget to change the URL in the code to your own.
In the activity's onCreate:
webview.setWebViewClient(new MyWebViewClient());

redpajama_set_name: RedPajamaStackExchange


text:
Q: Styling the groupers on grouped lists - Sencha Touch 2 Just a quick one. I was wondering what the best way was to style the grouper headers in a grouped list. I want to add a logo to the grouped header along with the standard title it displays. Any ideas?
Thanks in advance.

A: Probably setting $list-header-bg-color. Otherwise, CSS to: .x-list-header div {}
Hope it helps


text:
Q: Magento DevBox Beta Speeds Magento 2 Setup - Container is not working I have installed the docker on Windows 7. It's working fine and run as well.
I installed the Magento site using Varnish and Redis, so works fine.
When I tried to enable the deploy:mode:set to developer mode my container stopped.


text:
Q: String in grails aren't strings? This error has happened to me countless times, and usually I find a way to not use Strings, but it's incredibly frustrating.
Every now and then an error such as this one occurs:

Executing action [edit] of controller
  [edu.drexel.goodwin.events.web.EventController]
  caused exception:
  groovy.lang.MissingMethodException: No
  signature of method:
  grails.plugins.springsecurity.SpringSecurityService.ifAllGranted()
  is applicable for argument types:
  (java.lang.String) values:
  [ROLE_SUPER_ADMIN]"

The code I'm using looks like this:
springSecurityService.ifAllGranted(new String("ROLE_SUPER_ADMIN"))

I've also tried all of the following to no avail:
springSecurityService.ifAllGranted("ROLE_SUPER_ADMIN")
springSecurityService.ifAllGranted("""ROLE_SUPER_ADMIN""")
springSecurityService.ifAllGranted('ROLE_SUPER_ADMIN')
springSecurityService.ifAllGranted('''ROLE_SUPER_ADMIN''')

It's basically as if EVERY string variable is immediately turned into the value stored in the string... but how do you actually use string variables?
Thank you very much for your help,
-Asaf

A: Im pretty sure the issue is not a String issue, its a "using the API incorrectly" issue.  Check the documentation:
http://burtbeckwith.github.com/grails-spring-security-core/docs/manual/index.html
Im not seeing ifAllGranted on the SpringSecurityService class.  I believe it used to be there in older versions of SpringSecurity (i.e. Acegi).
Try using SpringSecurityUtils.ifAllGranted instead of springSecurityService.  If you are interested in how it works, use the source, luke.
/**
     * Check if the current user has all of the specified roles.
     * @param roles  a comma-delimited list of role names
     * @return true if the user is authenticated and has all the roles
     */
    public static boolean ifAllGranted(final String roles) {
        Collection<GrantedAuthority> inferred = findInferredAuthorities(getPrincipalAuthorities());
        return inferred.containsAll(parseAuthoritiesString(roles));
    }


text:
Q: Passing Data through Line of Filters using LINQ I have a list of objects which I want to pass this list through a set of filters, the very important thing here I want to mention is the filtred set from the first filter will be the input set of the second till the last filter.
Here is my filter Function signature:
IEnumerable<string> Filter(IEnumerable<string> data);
I did it with for loop, so I want a result similar to this foreach loop using, but I want to do it in a more declarative way with LINQ:
var filtersList = GetFilteres();
var filteredData = data;
foreach (var filter in filtersList)
{
    filteredData = filter(filteredData);
}

NB: the filtered list is unknown at compile time. it will be populated at runtime.
Example:
Let's assume we have two filter functions, we get those functions at the startup of my application by reading the app.config file.
Filter 01 predicate : x => x > 1 && x < 3
Filter 02 predicate: x => x > 2 < 10
Data: a list of integers: [0,1,2,4,5,6,7]
After passing this list to the first filter the output will be:
[0,1,2]
this output set will be the input of the second filter, So after applying the second filter the outputs will be [0,1]

A: In LINQ there is a where filter so you don't have to write an imperative code
where filter will run a predicate on each item in your Items source and if the predicate return true it will continue in the pipeline and if it returns false it will block this item from continue in the pipeline
// the follwing example will filter list of intgers to return all even nmber less than 6 in the Items
IEnumerable<int> Items = new List<int>(){1,2,3,4,5,6,7,8,9};
IEnumerable<int> filterdItems = Items .Where(element=>element%2==0).Where(element=> element<6);

your question does not tell much on what you need specifically to do, I guess you try to do a projection not a filtration, in this case you have to look at Select Method

A: Combine the sequence of calls to the Where method, to which you pass the predicate Func<T, bool>.
var filters = new List<Func<int, bool>>();

filters.Add(n => n > 30 && n < 70);
filters.Add(n => n % 2 == 0);

var data = Enumerable.Range(0, 100).ToList();
IEnumerable<int> result = data;

foreach (var filter in filters)
{
    result = result.Where(filter);
}

Console.WriteLine(string.Join(", ", data));
Console.WriteLine();
Console.WriteLine(string.Join(", ", result));

A: So you have a sequence of source items, and a sequence of Predicates that filter these source items.
So if your source is of type T, your predicates will all be Func<T, bool>.
You want a method that takes an input source, and returns only those items from the input source where every predicate will return true.
As an extension method (if you are not familiar with extension methods, read extension methods demystified
public static IEnumerable<T> WhereAll<T>(
    this IEnumerable<T> source,
    IEnumerable<Func<T, bool>> predicates)
{
    // TODO: implement
}

Usage:
IEnumerable<Customer> customers = ...

var predicates = new Func<Customer, bool>[]
{
    customer => !customer.IsDeleted,
    customer => customer.City == "New York",
    customer => customer.BirthDate.Year < 1960,
}

var oldNewYorkCustomers = customers.WhereAll(predicates).ToList();

The following implementation uses recursion:
public static IEnumerable<T> WhereAll<T>(
    this IEnumerable<T> source,
    IEnumerable<Func<T, bool>> predicates)
{
    Func<T, bool> firstPredicate = predicates.FirstOrDefault();
    if (firstPredicate != null)
    {
        // filter using the first predicate, and recursively call this method
        // without the first predicate
        return source.Where(firstPredicate)
                     .WhereAll(predicates.Skip(1));
    }
    else
    {
        // no predicates; nothing to filter
        return source;
    }
}

Although this seems a cool method, it has the disadvantage that the sequence of predicates is not enumerated efficiently. First it takes the first Predicate, then it starts again at the first predicate and skips this first element: the sequence of predicates will be enumerated twice.
if you use foreach on the sequence of predicates, instead of recursion with LINQ methods, the sequence of predicates will be enumerated only once:
public static IEnumerable<T> WhereAll<T>(
    this IEnumerable<T> source,
    IEnumerable<Func<T, bool>> predicates)
{
    var returnValue = source;
    foreach (var predicate in predicates)
    {
        returnValue = source.Where(predicate);
    }
    return returnValue;
}

A third method would be to create an enumerator by using yield return: take the first element of the sequence, check if it passes all predicates, and if so, return it:
public static IEnumerable<T> WhereAll<T>(
    this IEnumerable<T> source,
    IEnumerable<Func<T, bool>> predicates)
{
    foreach (var item in source)
    {
        if (predicates.All(predicate => predicate(item))
        {
            yield return item;
        }
    }
}

The nice thing about this method is, that if you only want the first filtered item, all other items of the source are not touched:
var oldNewYorkCustomers = customers.WhereAll(predicates).FirstOrDefault();


text:
Q: I'm getting a unicode error that prevents my code from running I think my problem is Turkish character error in R.
Warning message:
In normalizePath(path.expand(path), winslash, mustWork) : path[1]="C:/Users/sample/OneDrive -  Sa?l?k �r/Belgeler":The filename, directory name, or volume label syntax is incorrect inside batch
How can i fix it?

A: you could try check the encoding using
enc <- Encoding(path)

and then convert it to UTF-8
enc.path <- iconv(path, enc, "UTF-8")

and then use enc.path as the path
Seriously, I don know if this works, but you could try it (it's free!)


text:
Q: Python routine automatization with sublime text I'm using sublime text to make my web-server and i find myself often to write deserrialization from json to objects in a very simillar pattern every time.
db_order = model.objects.create(
           $SOMETHING = request_parsed['$SOMETHING'],
           $SOMETHING_ELSE = request_parsed['$SOMETHING_ELSE'],
            = request_parsed[''],
            = request_parsed[''],
            = request_parsed[''],
            = request_parsed[''],
            = request_parsed[''],
            = request_parsed[''],
            = request_parsed[''],
            = request_parsed[''],
            = request_parsed[''],
            = request_parsed[''],
            = request_parsed[''],
            = request_parsed[''],
            = request_parsed[''],
            # etc....
            )

so, there is a qustion, is there any way to do this any easier?
P.S. without eval()

A: Why not just unpack dict?
db_order = model.objects.create(**request_parsed)


text:
Q: Refer to node into a priority queue (iterator) I'm trying to implement Dijkstra's algorithm with a priority_queue (since I need to keep track of the closest node to the source node).
The problem is: when exploring a node, it might happen that it is linked to another node not yet discovered in the priority queue (i.e. to an element of the priority queue).
It seems priority queue doesn't support iterators, how can I refer to a priority queue element when discovering the node associated with it?

A: std::priority_queue<T> neither supports iterators nor an interface to decrease/increase the priority of a node: merely changing an element's priority wouldn't update the data structure. What you'd need is a node-based version of std::priority_queue<T>. There are priority queues for that purpose in Boost.
Although it wouldn't get the complexity quite right, you can use std::priority_queue<T> for Dijkstra's algorithm: instead of storing nodes you'd store edges from visited nodes to possibly unvisited nodes with the priority being the distance of the target node when using the given edge. When popping an element you'd need to check if the node was visited before. The Complexity would be O(m log m) instead of O(m log n), though (n being number of nodes and m being number of edges).


text:
Q: Invalid Cast error while adding items to a List I have one problem. I'm writing an application in c# using Visual Studio. In application i have dataTable with columns products, price, and quantity. For each column i tried to save all rows from data table in list. For example:
List<string> products = new List<string>();
for (int i = 0; i < dt.Rows.Count; i++)
{
    products.Add(dt.Rows[i]["products"].ToString());
}

This code works fine. Problem is when I try to save data from column price into double list. I tried many ways and none of them are correct. What i tried to do is.
For example
List<double> prices = new List<double>();
for (int i = 0; i < dt.Rows.Count; i++)
{
    prices.Add((double)dt.Rows[i]["price"]);
}

I'm always getting an error saying Specified cast is not valid. I also tried with double parse where it says: input string was not in correct format.
All I want to do is to store data from data table into double list.

A: Try
 using System.Text.RegularExpressions;

then
 prices.Add(Convert.ToDouble(Regex.Match(dt.Rows[i]["price"].ToString().Trim(),
                   @"\d+").Value, CultureInfo.InvariantCulture));;

A: try with Trim, you may have space before or after
prices.Add(Convert.ToDouble(dt.Rows[i]["price"].ToString().Trim(),
          System.Globalization.CultureInfo.InvariantCulture));

using linq you can do this as below ( add using System.Linq;)
List<double> doubles = dt.AsEnumerable()
                            .Select(r => r.Field<double>(1)) // assume price column index is 1
                            .ToList();

you can use Double.Parse Method if you have elements such as white space, thousands separators, and currency symbols in your price
if you have comma in your price, try like below
prices.Add(double.Parse(dt.Rows[i]["price"].ToString(),NumberStyles.AllowThousands, CultureInfo.InvariantCulture));

A: You have to use the Convert.ToDouble function:
prices.Add(Convert.ToDouble(dt.Rows[i]["price"]));

If you still get an error message you possibly got a culture problem.
When your prices are using the decimal seperator "," instead of "." or you have some seperator for thousends (for example "1,523.25") you may have to also define the Culture as a second parameter to Convert.ToDouble


text:
Q: PyTorch second derivative is zero everywhere I'm working on a custom loss function that requires me to compute the trace of the hessian matrix of a neural network with respect to its inputs.
In one dimension, this reduces to the second derivative of the network with respect to its input. Suppose my network is u and my input is x. The problem is completely one-dimensional, so the relationship I'm trying to model is u(x) where u has one input and one output, and x is one-dimensional. However, I'm running with batches, so x "comes in" as a column vector and I'm expecting a column vector as output.
If we label the samples in the batch as x_1, x_2, ..., x_n, I'm thus interested in the following vectors:

In PyTorch, I have tried the following:
u = model(x)
d = grad(u, x, grad_outputs=torch.ones_like(u), create_graph=True)[0]
dd = grad(d, x, grad_outputs=torch.ones_like(d), retain_graph=True, create_graph=False)[0]

This works well for u' but u'' comes out as being zero everywhere:

I'm a bit confused on the whole notion of needing a vector jacobian product here to begin with. Should I view the computation as u mapping from R^n to R^n, where n is the size of my batch?
Any help is appreciated!

A: Toy example
I have tried to devise a toy example for you:
x = torch.rand(3, requires_grad=True).reshape(-1, 1)
u = x ** 2.

# du/dx = 2 * x
dx = torch.autograd.grad(u, x, torch.ones_like(u), retain_graph=True, create_graph=True)[0]

# d^2 u/dx^2 = 2
ddx = torch.autograd.grad(dx, x, torch.ones_like(u))[0]

These are the outputs of x, dx, ddx:
tensor([[0.5217],
        [0.0400],
        [0.5509]], grad_fn=<ReshapeAliasBackward0>)
tensor([[1.0434],
        [0.0800],
        [1.1018]], grad_fn=<MulBackward0>)
tensor([[2.],
        [2.],
        [2.]])

So grad is computing the gradient of x element-wise.
Should I view the computation as u mapping from R^n to R^n, where n is the size of my batch?
My answer is no, otherwise dx should have been a Jacobian matrix instead of a vector.
This works well for u' but u'' comes out as being zero everywhere
Given the limited context, the only thing I can think of is that the second derivative of model(x) with respect to x is zero.


text:
Q: Automatically substituting logos in web images Consider the following task:

*

*Open a given URL

*Find the first image tag in the URL

*Substitute it for an image in your local drive

*Save the resulting webpage as a png

I want to automatize this task with a Python script, and I am unsure of the best approach.
I have been using selenium to convert URLs into screenshots, but I am unsure of how to introduce the part about modifying the first image tag to load a local file.

A: You can use execute_script to replace the image should look something like:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys

browser = webdriver.Firefox()
url = 'https://www.aircanada.com/en/'
browser.get(url)

my_image = browser.find_element_by_xpath('//*[@id="pagePromoBanner-wrapper"]/div/a/img')

# or
# my_image = browser.find_element_by_xpath('any XPath')

link_to_new_image = "https://images.pexels.com/photos/67636/rose-blue-flower-rose-blooms-67636.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260"
# if you are using python 3.6 and up:
browser.execute_script(f"arguments[0].src = '{link_to_new_image}'", my_image )
# else:
# browser.execute_script("arguments[0].src = '"+link_to_new_image+"'", my_image )

Hope this helps you!


text:
Q: Solr: Localities & solr.ICUCollationField usage? I'm learning Solr and have become confused trying to figure out ICUCollation, what it does, what it is for and how to use it. From here. I haven't found any good explanation of this online. The doc appear to be saying that I need to use this ICUCollation and implies that it does magical things for me, but does not seem to explain exactly why or exactly what, and how it integrates with anything else.
Say I have a text field in French and I want stopwords removed, accents, punctuation and case ignored and stemming... how does ICUCollation come into this? Do I set solr.ICUCollationField and locale='fr' and it will do everything else automatically? Or do I set solr.ICUCollationField and then tokenizer and filters on this in addition? Or do I not use solr.ICUCollationField at all because that's for something completely different? And if so, then what?

A: Collation is the organisation of written information into an order - ICUCollactionField (the API documentation also provides a good description) is meant to enable you to provide locale aware sorting, as the sort order is defined by cultural norms and specific language properties. This is useful to allow different sorting based on those rules, such as the difference between Norwegian and Swedish, where a Swede would order Å before Æ/Ä and Ø/Ö, while a Norwegian would order it Æ/Ä, Ø/Ö and then Å.
Since you usually don't want to sort by a tokenized field (exception: KeywordTokenizer) or a multivalued field, these fields are usually not processed any more than allowing for the sorting / collation to be performed.
There is a case to be made for collation filters for searching as well, as search in practice is just comparison. This means that if you're aiming to search for two words that would be identical when compared in the locale provided, it would be a hit. The tokens indexed will not make any sense when inspected, but as long as the values are reduced to the same token both when indexing and searching, it would work. There's an example of this on the wiki under UnicodeCollation.
Collation does not affect stopwords (StopFilterFactory), accents (ICUFoldingFilterFactory), punctuation, case (depending on locale - if the locale for sorting is case aware, then it does not) (LowercaseFilterFactory or ICUNormalizer2FilterFactory) or stemming (SnowballPorterFilterFactory). Have a look at the suggested filters for that. Most filters or tokenizers in Solr does very specific tasks, and try to avoid doing "everything and the kitchen sink" in one single filter.

A: You normally have two or more fields for one text input if you want to do different things like:

*

*search: text analysis

*sort: language sensitive / case insensitive sorting

*facet: string

For search use something like:
<fieldType name="textFR" class="solr.TextField" positionIncrementGap="100">
    <analyzer>
        <tokenizer class="solr.ICUTokenizerFactory"/>
        <filter class="solr.ICUFoldingFilterFactory"/>
        <filter class="solr.ElisionFilterFactory"/>
        <filter class="solr.KeywordRepeatFilterFactory"/>
        <filter class="solr.FrenchLightStemFilterFactory"/>
        <filter class="solr.RemoveDuplicatesTokenFilterFactory"/>
    </analyzer>
</fieldType>

For sorting use:
<fieldType name="textSortFR" class="solr.ICUCollationField"
           locale="fr"
           strength="primary" />

or simply:
<fieldType name="textSort" class="solr.ICUCollationField"
           locale=""
           strength="primary" />

(If you have to support many languages. Should work fine enough in most cases.)
Do make use of the Analysis UI in the SOLR Admin: open the analysis view for your index, select the field type (e.g. your sort field), add a representative input value in the left text area and a test value in the right field (in case of sorting, this right side value is not as interesting as the sort field is not used for matching).
The output will show you whether:

*

*accents are removed

*elisions are removed

*lower casing is applied

etc.
For example, if you see that elisions (l'atelier) are not remove (atelier) but you would like to discard it for sorting you would have to add the elision filter (see example for search field type above).
https://cwiki.apache.org/confluence/display/solr/Language+Analysis


text:
Q: ASP.Net Web Application Deployment to IIS Error Authenticate is not valid I have built a Web Application in ASP.net MVC on my local machine. And it runs correctly and has no issues.
Now when I publish it into a Web Deploy package and then run the installer on the IIS server it installs correctly. Then when I browse to the site the login page allows me to login and everything. But as soon as I try to access a page that requires my SQL connection. I get this error. And I have not been able to figure it out.
Server Error in '/SPBCyberSecurity' Application.

Keyword not supported: 'authentication'.
  Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

 Exception Details: System.ArgumentException: Keyword not supported: 'authentication'.

Source Error:

[ArgumentException: Keyword not supported: 'authentication'.]
   System.Data.Common.DbConnectionOptions.ParseInternal(Hashtable parsetable, String connectionString, Boolean buildChain, Hashtable synonyms, Boolean firstKey) +6667870
   System.Data.Common.DbConnectionOptions..ctor(String connectionString, Hashtable synonyms, Boolean useOdbcRules) +134
   System.Data.SqlClient.SqlConnectionString..ctor(String connectionString) +103
   System.Data.SqlClient.SqlConnectionFactory.CreateConnectionOptions(String connectionString, DbConnectionOptions previous) +35
   System.Data.ProviderBase.DbConnectionFactory.GetConnectionPoolGroup(DbConnectionPoolKey key, DbConnectionPoolGroupOptions poolOptions, DbConnectionOptions& userConnectionOptions) +294
   System.Data.SqlClient.SqlConnection.ConnectionString_Set(DbConnectionPoolKey key) +60
   System.Data.SqlClient.SqlConnection.set_ConnectionString(String value) +89
   System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch(TTarget target, Action`2 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed) +207
   System.Data.Entity.Infrastructure.Interception.DbConnectionDispatcher.SetConnectionString(DbConnection connection, DbConnectionPropertyInterceptionContext`1 interceptionContext) +438
   System.Data.Entity.Core.EntityClient.EntityConnection.ChangeConnectionString(String newConnectionString) +900

[EntityException: The underlying provider failed on ConnectionString.]
   System.Data.Entity.Core.EntityClient.EntityConnection.ChangeConnectionString(String newConnectionString) +1305
   System.Data.Entity.Internal.LazyInternalConnection.InitializeFromConnectionStringSetting(ConnectionStringSettings appConfigConnection) +161
   System.Data.Entity.Internal.LazyInternalConnection.TryInitializeFromAppConfig(String name, AppConfig config) +46
   System.Data.Entity.Internal.LazyInternalConnection.Initialize() +95
   System.Data.Entity.Internal.LazyInternalConnection.CreateObjectContextFromConnectionModel() +16
   System.Data.Entity.Internal.LazyInternalContext.InitializeContext() +340
   System.Data.Entity.Internal.LazyInternalContext.get_ObjectContext() +21
   System.Data.Entity.Internal.InternalContext.ExecuteSqlQuery(String sql, Nullable`1 streaming, Object[] parameters) +124
   System.Data.Entity.Internal.InternalContext.ExecuteSqlQueryAsIEnumerator(String sql, Nullable`1 streaming, Object[] parameters) +92
   System.Data.Entity.Internal.InternalContext.ExecuteSqlQuery(Type elementType, String sql, Nullable`1 streaming, Object[] parameters) +255
   System.Data.Entity.Internal.InternalSqlNonSetQuery.GetEnumerator() +44
   System.Data.Entity.Infrastructure.DbRawSqlQuery`1.GetEnumerator() +48
   System.Collections.Generic.List`1..ctor(IEnumerable`1 collection) +446
   System.Linq.Enumerable.ToList(IEnumerable`1 source) +80
   CyberSecurity.Controllers.OverviewClass.getVulnOverview(String theDate) +347
   CyberSecurity.Controllers.HomeController.Dashboard() +102
   lambda_method(Closure , ControllerBase , Object[] ) +79
   System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +242
   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +39
   System.Web.Mvc.Async.AsyncControllerActionInvoker.<BeginInvokeSynchronousActionMethod>b__39(IAsyncResult asyncResult, ActionInvocation innerInvokeState) +12
   System.Web.Mvc.Async.WrappedAsyncResult`2.CallEndDelegate(IAsyncResult asyncResult) +139
   System.Web.Mvc.Async.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3d() +112
   System.Web.Mvc.Async.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f() +452
   System.Web.Mvc.Async.<>c__DisplayClass33.<BeginInvokeActionMethodWithFilters>b__32(IAsyncResult asyncResult) +15
   System.Web.Mvc.Async.<>c__DisplayClass2b.<BeginInvokeAction>b__1c() +37
   System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult) +241
   System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +29
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +111
   System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +53
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +19
   System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +51
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +111
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +606
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +288

Connection String generated by Publish to web config package
<setParameter name="VulnDBEntities-Web.config Connection String" value="metadata=res://*/VulnsModel.csdl|res://*/VulnsModel.ssdl|res://*/VulnsModel.msl;provider=System.Data.SqlClient;provider connection string='Data Source=devsrv47;Initial Catalog=VulnDB;Persist Security Info=True;User ID=***********;Password=****************;Authentication="Active Directory Password"'" />

A: Based on what you've posted, it looks like you've used the word "authentication" in your connection string, which is not supported.


text:
Q: Solr stopwords issue - documents are not matching I am using solr-3.4, My part of schema looks like,
<fieldType name="text" class="solr.TextField" positionIncrementGap="100" autoGeneratePhraseQueries="true">
    <analyzer type="index">
        <tokenizer class="solr.WhitespaceTokenizerFactory"/>
        <filter class="solr.StopFilterFactory" ignoreCase="true" words="stopwords_en.txt" enablePositionIncrements="true"/>
        <filter class="solr.WordDelimiterFilterFactory" generateWordParts="1" generateNumberParts="1" catenateWords="1" catenateNumbers="1" catenateAll="0" splitOnCaseChange="1"/>
        <filter class="solr.LowerCaseFilterFactory"/>
        <filter class="solr.KeywordMarkerFilterFactory" protected="protwords.txt"/>
        <filter class="solr.PorterStemFilterFactory"/>
    </analyzer>
    <analyzer type="query">
        <tokenizer class="solr.WhitespaceTokenizerFactory"/>
        <filter class="solr.SynonymFilterFactory" synonyms="synonyms.txt" ignoreCase="true" expand="true"/>
        <filter class="solr.StopFilterFactory" ignoreCase="true" words="stopwords_en.txt" enablePositionIncrements="true"/>
        <filter class="solr.WordDelimiterFilterFactory" generateWordParts="1" generateNumberParts="1" catenateWords="0" catenateNumbers="0" catenateAll="0" splitOnCaseChange="1"/>
        <filter class="solr.LowerCaseFilterFactory"/>
        <filter class="solr.KeywordMarkerFilterFactory" protected="protwords.txt"/>
        <filter class="solr.PorterStemFilterFactory"/>
    </analyzer>
</fieldType>

stopwords_en.txt contains
a
an
and
are
as
etc..
Now when I search for "buy house" Solr does not return me the documents with text "buy a house".
Also when I search for "buy a house" Solr does not return me the documents with text "buy house".
A part of debugQuery is
<str name="rawquerystring">cContent:"buy a house"</str>
<str name="querystring">cContent:"buy a house"</str>
<str name="parsedquery">PhraseQuery(cContent:"bui ? hous")</str>
<str name="parsedquery_toString">cContent:"bui ? hous"</str>

Similar (but not exact) question was found here
But there was no satisfactory answer to solve this problem.
Any idea how can I solve this problem? or what is wrong?

A: You are searching with a PhraseQuery so in the first case of "buy house" won't match "buy a house". If you add slop (cContent:"buy house"~2) to the PhraseQuery you will also get matches.
In the second case although the stopword is filtered out it still expects something to be on that position, so "buy a house" will match on "buy one house", but not on "buy house". Maybe slop can fix this too, but I'm not sure.

A: Actually I think your problem is with the PorterStemmer - "house" is being transformed to "hous". Unless you really think you need it, I would turn off the porter stemmer. In my experience, it usually does more harm than good.


text:
Q: how to edit snapshot from a video? I'm loading video from my computer through getUserMedia, I take a snapshot with canvas. But when i try to edit through of code below I can't.
var canvas = document.querySelector("canvas")
var ctx = canvas.getContext('2d');
var sketch = document.getElementById("sketch")
var sketch_style = getComputedStyle(sketch)
canvas.width = parseInt(sketch_style.getPropertyValue('width'))
canvas.height = parseInt(sketch_style.getPropertyValue('height'))
var mouse = {x: 0, y: 0}
var last_mouse = {x: 0, y: 0}

/* Mouse Capturing Work */
canvas.addEventListener('mousemove', function(e) {
    last_mouse.x = mouse.x;
    last_mouse.y = mouse.y;

    mouse.x = e.pageX - this.offsetLeft;
    mouse.y = e.pageY - this.offsetTop;
}, false);

/* Drawing on Paint App */
ctx.lineWidth = 5;
ctx.lineJoin = 'round';
ctx.lineCap = 'round';
/* Posso fazer um switch case aqui pra escolher uma cor */
ctx.strokeStyle = 'blue';

canvas.addEventListener('mousedown', function(e) {
      canvas.addEventListener('mousemove', onPaint, false);
}, false);

canvas.addEventListener('mouseup', function() {
      canvas.removeEventListener('mousemove', onPaint, false);
}, false);

var onPaint = function() {
    ctx.beginPath();
    ctx.moveTo(last_mouse.x, last_mouse.y);
    ctx.lineTo(mouse.x, mouse.y);
    ctx.closePath();
    ctx.stroke();
};
function snapshot() {
    canvas.width = 500;
    canvas.height = 300;
    ctx.drawImage(videoNode, 0, 0, canvas.width, canvas.height);

}
foto.addEventListener('click', snapshot, false);

I can put lines, but they do not change the color, thickness, etc ... I am using the Electron to perform a desktop web application. Can someone help me?? :D
Snapshot on Electron

A: It's because when you set new size -even if it is the same size, the canvas will reset the state. can be fixed by setting line stuff after the new size is set
function snapshot() {
    canvas.width = 500;
    canvas.height = 300;
    ctx.drawImage(videoNode, 0, 0, canvas.width, canvas.height);

    // set line stuff here <=====================
    ctx.lineWidth = 5;
    ctx.lineJoin = 'round';
    ctx.lineCap = 'round';
    /* Posso fazer um switch case aqui pra escolher uma cor */
    ctx.strokeStyle = 'blue';
}


text:
Q: scrapy with django : how to use foreign key I want to use scrapy with django,but I don't know how to deal with django foreignkey
My database is postgreSQL
Please guide me. Thank you.
models.py:
class ShoppingApple(models.Model):
    link        = models.URLField(max_length=255)
    title       = models.CharField(max_length=100)

class ImageApple(models.Model):
    article = models.ForeignKey(ShoppingApple)
    image =models.CharField(max_length=255)

pipelines.py:
class ShopPipeline(object):
    if isinstance(item, Shop_appleItem):
        shopping = item.save(commit=False)
        shopping.save()
        return item

    if isinstance(item, Shop_apple_imgItem):
        shopping = item.save(commit=False)
        shopping.save()
        return item

spider like this:
def parse(self,response):
    item = Shopping_appleItem()
    product = Shopping_apple_imgItem()
    sel = Selector(response)
    item['link'] = sel.css("  ").extract()
    item['title'] = sel.css(" ").extract()
    product['image'] = sel.css(" ").extract()
    yield item
    yield product

When I run my scrapy ,the error is :
    django.db.utils.IntegrityError: null value in column "article_id" violates not-null constraint
DETAIL:  Failing row contains (1, null, http://test...).

A: Have you checked if you have null value somewhere?
Try with setting the default to null just for test.
ALTER TABLE article SET DEFAULT NULL

PostgreSQL ALTER TABLE
Then run again to see if you get the same error.

A: Are you using South or any other tool for migration(or Django 1.7+) ? If so, just update the models to :
class ImageApple(models.Model):
    article = models.ForeignKey(ShoppingApple)
    image =models.CharField(max_length=255, null=True)

generate and run the migration, this should do the trick.

A: What i do is use a regular scrapy item (not a django item, that thing is quite limited) and just create the object manually and add what i need.
class MyItem(scrapy.Item):
    name = scrapy.Field()
    image_url = scrapy.Field()

And handle the download manually and create the objects by myself:
object = Object.objects.create(foo="something")
object.save()
self.image_url = item['image_url']
self.get_remote_image(object)

You can get images easily with urllib:
def get_remote_image(self, object):
if self.image_url:
    myopener = MyOpener()
    page = myopener.retrieve(self.image_url)
    response = page[0]
    image = open(response)

    extension = os.path.splitext(image.name)[1]
    picture = Picture(object=object)
    picture.save()
    picture.picture.save('new' + extension, File(image))

I tried to do that with django items but got tired of trying and found this way. It is not hard to implement and allows way more freedom on how to create your objects.
Don't forget to add django.setup() to your scrapper's settings.py.


text:
Q: Storing multiple checkbutton strings into different variables with python tkinter I'm making a python program using tkinter that will create a folder name based on a string and also create subfolders based on what check box is selected.
i.e. if the "banana" checkbox is selected it will create a banana folder inside that string named folder. This is what I need this to do:

*

*A list of check boxes that the user will check off (these will create subfolders) THIS IS THE PART I'M HAVING TROUBLE WITH

*Browse a directory (this is the path where the parent folder will be created)

*Name a folder (enter in a string and create a folder where all the subfolders will go under)

Here's my code so far. I know there's probably a better way to store all the checked boxes but I don't know how to do that yet:
import tkinter as tk
from tkinter import *
from tkinter.filedialog import askdirectory
import os, sys

def browse():
    dir = askdirectory()
    if dir:
        path.set(dir)

def genAsset():
    assetPath=path.get()
    assetName=asset.get()
    expFold=export.get()
    bakFold=bake.get()
    sceFold=scene.get()
    texFold=texture.get()
    scuFold=sculpt.get()
    refFold=reference.get()
    renFold=render.get()
    engFold=engine.get()
    os.makedirs(assetPath+"/"+assetName+"/")
    os.makedirs(assetPath+"/"+assetName+"/"+expFold+"/")
    os.makedirs(assetPath+"/"+assetName+"/"+bakFold+"/")
    os.makedirs(assetPath+"/"+assetName+"/"+sceFold+"/")
    os.makedirs(assetPath+"/"+assetName+"/"+texFold+"/")
    os.makedirs(assetPath+"/"+assetName+"/"+scuFold+"/")
    os.makedirs(assetPath+"/"+assetName+"/"+refFold+"/")
    os.makedirs(assetPath+"/"+assetName+"/"+renFold+"/")
    os.makedirs(assetPath+"/"+assetName+"/"+engFold+"/")

#create the window and title
window=Tk()
window.title("v1.0")

#define variables and images
path=StringVar()
asset=StringVar()
VMR=PhotoImage(file="VMR.gif")
selectFolders=StringVar()

export=StringVar()
bake=StringVar()
scene=StringVar()
texture=StringVar()
sculpt=StringVar()
reference=StringVar()
render=StringVar()
engine=StringVar()

#define checkbuttons of folders to generate and store textvaiable

expButt=Checkbutton(window, text="export", textvariable=export).pack()
bakButt=Checkbutton(window, text="bake").pack()
sceButt=Checkbutton(window, text="scene").pack()
texButt=Checkbutton(window, text="texture").pack()
scuButt=Checkbutton(window, text="sculpt").pack()
refButt=Checkbutton(window, text="reference").pack()
renButt=Checkbutton(window, text="renders").pack()
engButt=Checkbutton(window, text="engine").pack()

#display the image file
hdrImg=Label(window, image=VMR)
hdrImg.photo=VMR

#select path and define asset name, store strings
lDirec=Label(window, text="Folder Directory:").pack()
ePath=Entry(window, textvariable=path, width=50).pack()
bBrowse=Button(window, text="Browse Path", command=browse).pack()
lAsset=Label(window, text="Asset Name:").pack()
eAsset=Entry(window, textvariable=asset, width=50).pack()
bCreate=Button(window, text="Create Asset", command=genAsset).pack()

window.mainloop()

A: You can create two lists: one for the names of the subdirectories, and another one for storing IntVars to track if each Checkbutton is checked or not. Thus, you can zip both lists in your genAsset function, and then create the subdirectory if the value of the corresponding IntVar is not zero.
This way you can also reduce a lot of code duplication in the callback function and simplify the creation of the widgets.
import tkinter as tk
from tkinter.filedialog import askdirectory
import os, sys

window = tk.Tk()

def browse():
    directory = askdirectory()
    if directory:
        path.set(directory)

def genAsset():
    asset_path = path.get()
    asset_name = asset.get()
    for var, folder in zip(variables, folders):
        folder_path = os.path.join(asset_path, asset_name, folder)
        if var.get() and not os.path.exists(folder_path):
            os.makedirs(folder_path)

path = tk.StringVar()
asset = tk.StringVar()

folders = ["export", "bake", "scene", "texture", "sculpt", "reference", "renders", "engine"]
variables = []
for folder in folders:
    var = tk.IntVar()
    tk.Checkbutton(window, text=folder, variable=var).pack()
    variables.append(var)

dir_label = tk.Label(window, text="Folder Directory:")
path_entry = tk.Entry(window, textvariable=path, width=50)
browse_button = tk.Button(window, text="Browse Path", command=browse)
asset_label = tk.Label(window, text="Asset Name:")
asset_entry = tk.Entry(window, textvariable=asset, width=50)
create_button = tk.Button(window, text="Create Asset", command=genAsset)

dir_label.pack()
path_entry.pack()
browse_button.pack()
asset_label.pack()
asset_entry.pack()
create_button.pack()

window.mainloop()

PS: Keep in mind that pack() returns None, so you shouldn't store the result of calling this function but create the widget first and then call pack().


text:
Q: rollover effect using Jquery Would you please help me in making a rollover effect using jquery, what i want to do is when someone hover over any of the menu items the text slide down and disappear and a picture slides from the top down to the center (e.g. you could see this effect here panda as you can see the picture slide down from the top but the text does not slide down which is not what want).
I know it can be easily done using flash but i don't want my menu in flash as that would be a bad practice.
can you tell me what do i need to change in my menu HTML and what jquery functions should i use.
Thanks So much for your help
P.S. this my menu HTML and you can see my menu here

Home

News

Special offers

Private label

Locations

About us

Jobs

Contact us

Multimedia

MENU:

A: Instead of doing it for you, I'll offer some places to start looking..
Here is an example that could be easily modified to use 'rollover' instead of 'click': http://css-tricks.com/examples/MenuFader/
Details on how the above example was put together (the tutorial):
http://css-tricks.com/learning-jquery-fading-menu-replacing-content/
I found this tutorial by searching on Google for "jquery effects examples":
http://www.google.com/search?hl=en&q=jquery+effects+examples&btnG=Google+Search&aq=f&oq= and clicking on the first and second links.
Good luck with your Jquery project.

A: First things first, you'll really want to give your independent anchor tags ids, as it will make accomplishing what you're wanting much easier.
Look at the slideDown(), and slideToggle() functions, and it would basically require you setting up hidden divs and then on the mouseover event, you would slidetoggle your text out and the hidden image div in, and on mouseout do the opposite.
Good luck, jQuery is a lot of fun to work with.  Play with it and see what you can blow up!


text:
Q: How do I visually format React button components? I'm trying to make a basic calculator with React and am having trouble figuring out how to format the buttons in the typical format (ex: "0 . =" on the bottom row, '1 2 3 +' on on the next row up and so on..) with React and Bootstrap.
I have the functionality working but keep running into errors when I try to use a grid ( etc.). Any recommendations on how to approach this? (New to React)
    render() {
        //object destructuring
        const { onReset, buttons, onPress } = this.props;

        return (
            <div>
                <button
                    onClick={onReset}
                    className='btn btn-primary btn-sm m-2'
                    >
                        Reset
                </button>

                {buttons.map(button => (

                    <Button
                        key={button.id}
                        onPress={onPress}
                        button = {button}
                    />
                ))}
            </div>
        );
    }

Edit in response to @lucasvw 's comment:
I attempted to wrap the .map method in . 'button not defined' was the error.
    {
        <Container>
            <Row>
                buttons.map(button => (

                    <Button
                        key={button.id}
                        onPress={onPress}
                        button = {button}
                    />
                ))
            </Row>
        </Container>
    }

I also attempted to build a for loop to spit on button out at a time. I don't have that code handy, but I believe it was a series of unexpected expression errors.


text:
Q: Есть ли вариант в Golang отработать типы через interface{}? Можно ли как-то в Го операцию сложения сделать одной строкой без определения типа? Понимаю, что нужно a.(uint64) + b.(uint64) указывать, но вдруг есть способ автоопределения типа?
func f (a interface{}, b interface{}) interface{} {
    return a + b
}

a := uint64(100)
b := float64(200)
c := f (a, b)

A: ответ не простой.
в версиях Го до 1.18 нужно кастить в тип данных, что не очень. А вот с 1.18 версии появляются дженерики. Уже вышла версия go1.18rc1
Определяем функицю, параметризованную T, используя constraint для ограничения типов у T
import "constraints"

type Number interface {
    constraints.Integer | constraints.Float
}

func add[T Number](a, b T) T {
    return a + b
}

получается, что

*

*Number - наш тип, аля множество constraints.Integer и constraints.Float

*constraints.Integer - просто целочисленные типы данных

*contraints.Float - с плавающей точкой

Это позволит нам вызывать add с любыми двумя аргументами Number типа. Тогда в теле функции мы сможем использовать любую операцию, которая поддерживается всеми типами. Например, умножение, как в вашем примере
func multiply[T Number](a, b T) T {
    return a * b
}

Конечно, тут тоже есть ограничение: аргументы должны иметь один и тот же тип. Независимо от дженериков, вы не можете использовать разные типы. вот из спецификаций Operators:

[...] the operand types must be identical unless the operation
involves shifts or untyped constants.

то есть следующий пример не будет работать
add(2.5, 2)

потому что компилятор определит тип T из первого аргумента 2.5, который по умолчанию равен float64, а затем не сможет сопоставить тип 2, который по умолчанию равен int.
package main

import (
    "constraints"
    "fmt"
)

type Number interface {
    constraints.Integer | constraints.Float
}

func main() {
    a := 1
    b := 2

    fmt.Println(add(1, 2))     // 3
    fmt.Println(add(a, b))     // 3
    fmt.Println(add(1.5, 3.2)) // 4.7
}

func add[T Number](a, b T) T {
    return a + b
}

A: Нет, в Go такого нет - это не динамический язык..
Можно либо определять тип и приводить его к желаемому через reflection, либо ждать Go 1.18 и реализовать вашу функцию через generic-ки.


text:
Q: TypeError: tls.connect is not a function I keep getting this issue tls.connect is not a function.
I am using nodemailer with my Reactjs and Nextjs application.
sendmail.js?71c0a4a:33 Error: TypeError: tls.connect is not a function
at SMTPConnection.connect (index.js?49b6f52:228)
at getSocket (index.js?55ebb9c:234)
at setImmediate (index.js?55ebb9c:70)
at run (setImmediate.js?d2412a6:40)
at runIfPresent (setImmediate.js?d2412a6:69)
at onGlobalMessage (setImmediate.js?d2412a6:109)

The weird part is if I run the script in the console it will work, but running though the browser I get the tls.connect is not a function error.
const nodemailer = require('nodemailer');

let transporter = nodemailer.createTransport({
    service: 'gmail',
    secure: false,
    port: 465,
    auth: {
        user: '',
        pass: ''
    },
});

class mail {

    options (to, text, subject, html) {
        console.log(to)
        var mailOptions = {
            from: '',
            to: to,
            subject: subject,
            text: text,
            html: html
            }
        return(mailOptions);
    }

    sendMail(mailOptions) {
        console.log(mailOptions)

        transporter.sendMail(mailOptions, (error, info) => {
            if (error) {
                return console.error('Error:', error);
            }
            console.log('Message %s sent: %s', info.messageId, info.response);
        });
    }
}

export default mail;

A: You're using nodemailer inside a bundler, on Client Side,
NodeMailer should only be used at ServerSide.
This issue is environmental and also be aware that even if that was working, you would be exposing that google account and password by using it at client side.
Consider creating a serverside nodejs api to send your emails
issue


text:
Q: Populate new field when query documents I have two schemas (using mongoose) like below:
var PostSchema = new Schema({
    name: String,
    content: String,
    likes: [{
        type: String,
        ref: 'User'
    }],
    ...
 })

 var UserSchema = new Schema({
     name: String,
     pinnedPosts: [{
         type: String,
         ref: 'Post'
     }],
     ...
  })

Now I want to get all posts with two new populated fields: isLiked and isPinned depend on the auth state. If the user hasn't signed in (auth is null) then all these two fields are false. If user has signed in and had liked the post, isLiked is true... Can I do it when I query the post?


text:
Q: Git force merge I am wondering what I am supposed to do in order to force a merge from a dev branch into my master branch? Using 'git merge dev' results in quite a number of conflicts. However, I don't want to handle them individually. Instead, I simply want to use all the files from my dev branch and merge it into master. But this "forced merge" is not as easy as I thought. Can somebody please point me into the right direction?

A:
I simply want to use all the files from my dev branch

If you mean you want to use all the files from your dev branch - i.e. any changes made on the master branch since the branches diverged should be undone - then there are a couple of ways.
merge -s ours
You could
git checkout dev
git merge -s ours master
git checkout master
git merge dev

This is a bit round-about, because there is no "theirs" strategy.  (There is a "theirs" strategy option for the default merge strategy, but it would still try to apply changes from master as long as they don't conflict with changes from dev; if what you want is to just keep the dev versions, that won't work.)  So you use the ours strategy to create a merge commit between master and dev with the dev versions of all files, then fast-forward master onto that merge.
That means the order of parents will be reversed on the merge commit, which is something you usually wouldn't notice, but it could matter in some cases (like if you use --first-parent on logs or something).
commit-tree
If the order of parents matter, you could resort the plumbing command commit-tree
git checkout master
git merge $(git commit-tree dev -p master -p dev -m "merging dev over master")

history rewrite
The potential down-side to the above methods is that they produce a merge commit that may not be intuitive, in that its result ignores the changes from one side of the merge (whereas a merge is expected to combine the changes from both sides).  Because your merge would conflict under the normal strategy, it's not as big a problem as it could be, but still some people would categorize it as an "evil merge".  If you want to avoid that, the other option is to rewrite history.
That has a down side as well, particularly if you use this repo to collaborate with other developers.  You can read about the problem (and generally how to solve it) in the git rebase docs under "recovering from upstream rebase".  (While the docs refer to the problem as "upstream rebase", it really applies to any history rewrite of a shared branch.)
If you decide that a history rewrite makes sense, then the simplest thing is just to move the master branch so that it points to the same commit as dev.
git checkout dev
git branch -f master


text:
Q: Laravel Socialite 2.0 Facebook Authentication only returning id and name I am using Laravel's Socialite package (version 2.0.0). It is working great for google and github but when I try to login with facebook, I get this:
ErrorException in FacebookProvider.php line 89:
Undefined index: first_name

In the FacebookProvider.php the error is from this method:
protected function mapUserToObject(array $user)
{
    return (new User)->setRaw($user)->map([
        'id' => $user['id'], 'nickname' => null, 'name' => $user['first_name'].' '.$user['last_name'],
        'email' => isset($user['email']) ? $user['email'] : null, 'avatar' => $this->graphUrl.'/'.$this->version.'/'.$user['id'].'/picture?type=normal',
    ]);
}

If I dd() the $user param before this mapping. I only get id and the name of the authenticated Facebook user. So, it means that I am not getting the email of the Facebook user. I at least need name and email of the user.
After dd() this method looks like this:
protected function mapUserToObject(array $user)
{
    dd($user);
    return (new User)->setRaw($user)->map([
        'id' => $user['id'], 'nickname' => null, 'name' => $user['first_name'].' '.$user['last_name'],
        'email' => isset($user['email']) ? $user['email'] : null, 'avatar' => $this->graphUrl.'/'.$this->version.'/'.$user['id'].'/picture?type=normal',
    ]);
}

What could be the problem? Please help me.

A: I have the same problem and is a bug! use the new version of file FacebookProvider.php here and work!

A: I updated to the latest version of Socialite. Now it works!

A: For thoose who are confused on how to update into the latest version just
add this into your composer.json file.
"laravel/socialite": "2.*"

and into your terminal composer update
Cheers!


text:
Q: Linear Independence of vectors in relation to the $t$ parameter
Considering the following vectors $u,v,w\in R^5$
$u = (0,1,1,-1,1/2)$ $v = (t,1,1,0,1)$ $w = (1,3,3,-2,-2)$
Then, they are linearly independent:
a) for each value of $t$ b) if and only if $t=0$ c) if $t=1$ d) if and only if $t\neq 1$

I think the best way to solve the exercise, is to find a combination of elements that is equal to the zero vector. So I go on in this way:
$\alpha(0,1,1,-1,1/2)+\beta(t,1,1,0,1)+\gamma(1,3,3,-2,-2) = (0,0,0,0,0)$
finding ways for which $\alpha,\beta,\gamma$ are equal to $0$, but I cannot get the result through the calculations. Any advices?

A: The vectors are linearly independent if and only if the matrix
$$
\begin{bmatrix}
0 & t & 1 \\
1 & 1 & 3 \\
1 & 1 & 3 \\
-1 & 0 & -2 \\
1/2 & 1 & -2
\end{bmatrix}
$$
has rank $3$.
We can do Gaussian elimination: swap the first and second row and eliminate in the first column, getting
$$
\begin{bmatrix}
1 & 1 & 3 \\
0 & t & 1 \\
0 & 0 & 0 \\
0 & 1 & 1 \\
0 & 1/2 & -7/2
\end{bmatrix}
$$
Now swap the second and fourth column; then eliminate in the second column:
$$
\begin{bmatrix}
1 & 1 & 3 \\
0 & 1 & 1 \\
0 & 0 & 0 \\
0 & 0 & 1-t \\
0 & 0 & 4
\end{bmatrix}
$$
Then you have the answer.


text:
Q: Fetch records by interval I have a MySQL table that stores the following data:
id_event INT(10)
start_date DATE()
end_date DATE()

My goal is to show all id_events that are included between the interval betweeb to dates: $start and $sto
I've tried so far:
SELECT * FROM events WHERE $start >= start_date AND $end <= end_date;

But the problem is that it might be some events that start before the input $start, and ends after $end and does not show.
I'm pretty sure that it might be quite easy, but i'm stucked with this for last 2 days
Thanks in advance

A: Try
SELECT * FROM events WHERE start_date >= '$start' AND end_date <= '$end';

A: First off, you need to make sure $start and $end are in the right format.  It should be: 'YYYY-mm-dd', for example: '2013-07-22'.
Second, your logic is flawed.  $start >= start_date is the same as start_date <= $start.  Which means anything on or before the date entered as $start.
Finally, you need to quote your values in your query, your dates should be strings.
SELECT * FROM events WHERE start_date >= '$start' AND end_date <= '$end';

A: Try this:
SELECT * FROM events
WHERE $start <= end_date and $end >= start_date;

A: This very much depends what is in $start and $end.
I assume this comes from PHP, right?
I think you need to convert whatever is in that PHP variable first to SQL DATE type, using STR_TO_DATE function (http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_str-to-date)
Then, having used the correct format, you run something similar to the following:
SELECT * FROM events WHERE STR_TO_DATE('$start','%d-%m-%Y') >= start_date AND STR_TO_DATE('$end','%d-%m-%Y')  <= end_date;


text:
Q: Debug and solve app performance issue related to RAM and CPU usage I was asked a question. Given a graph of CPU and RAM usage for a process. CPU was constant, but RAM was increasing linearly.
How would you debug to find out what the issue could be?
How are you going to solve it?
There is only one thing I could think of. That's a memory leak issue. The application code handles the resource improperly and hence  Garbage Collector can not clear the resource. We should capture the heap size increase and check the details.


text:
Q: Rails polymorphic associations bug? I have the following code:
class Location < ActiveRecord::Base
  has_many :geolocations, :as => :geotaggable, :dependent => :destroy
end

class Geolocation < ActiveRecord::Base
  belongs_to :geotaggable, :polymorphic => true
end

When I do: Location.first.geolocations , my console shows the following SQL:
  ←[1m←[36mGeolocation Load (2.0ms)←[0m  ←[1mSELECT `geolocations`.* FROM `geolo
cations` WHERE `geolocations`.`geotaggable_id` = 1←[0m

Whereas when I do: Location.find(:first, :include => :geolocations), my console shows this SQL:
  ←[1m←[36mGeolocation Load (1.0ms)←[0m  ←[1mSELECT `geolocations`.* FROM `geolo
cations` WHERE `geolocations`.`geotaggable_type` = 'Location' AND (((`geolocatio
ns`.`geotaggable_id` = 1)))←[0m

I checked my project and found out that whenever I have polymorphic associations, the polymorphic type doesn't get included in the SQL query.
Is this the expected behavior or am I missing something?
I am using rails 3.2.0.rc1 and Ruby 1.9.3. I believe I've had this same outcome in rails 3.0.0.


text:
Q: Create Jax2b marshaller Formatted_Output property doesnt work Im trying to create a Marshaller with Jax2b with a formatted output property:
protected static Marshaller createMarshaller() throws AMLParseException {
    final Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
    marshaller.setClassesToBeBound(CAEXFile.class);
    final Map<String, Object> props = new HashMap<>();

    props.put(javax.xml.bind.Marshaller.JAXB_FORMATTED_OUTPUT, true); //:TODO

    //marshaller.setJaxbContextProperties(props);

    return marshaller;
}

If i set the JaxbContextProperties it says "Property "jaxb.formatted.output" is not supported" :
Caused by: javax.xml.bind.JAXBException: Eigenschaft "jaxb.formatted.output" wird nicht unterstützt.
    at com.sun.xml.bind.v2.ContextFactory.createContext(ContextFactory.java:118) ~[jaxb-runtime-2.3.2.jar:2.3.2]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
    at java.base/java.lang.reflect.Method.invoke(Method.java:564) ~[na:na]
    at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:251) ~[jakarta.xml.bind-api-2.3.2.jar:2.3.2]
    at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:240) ~[jakarta.xml.bind-api-2.3.2.jar:2.3.2]
    at javax.xml.bind.ContextFinder.find(ContextFinder.java:363) ~[jakarta.xml.bind-api-2.3.2.jar:2.3.2]
    at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:691) ~[jakarta.xml.bind-api-2.3.2.jar:2.3.2]
    at org.springframework.oxm.jaxb.Jaxb2Marshaller.createJaxbContextFromClasses(Jaxb2Marshaller.java:551) ~[spring-oxm-5.2.4.RELEASE.jar:5.2.4.RELEASE]
    at org.springframework.oxm.jaxb.Jaxb2Marshaller.getJaxbContext(Jaxb2Marshaller.java:503) ~[spring-oxm-5.2.4.RELEASE.jar:5.2.4.RELEASE]

If i dont set the Property it works.
Any clue how to solve this ?

A: You can use
marshaller.setMarshallerProperties(Collections.singletonMap(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE ));


text:
Q: Help with an easy tikzpicture (mathematical proof) I'm completely lost trying to make this (I guess) rather easy picture. Any help would be greatly appreciated

A: With use of TikZ, this could look like the following:
% arara: pdflatex

\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{shapes,positioning,decorations.markings}
\tikzset{%
    ,mynode/.style={circle split,draw, minimum size=2.05cm,text height=\heightof{$f$},text depth=\depthof{g}}
    ,->-/.style={%
        decoration={%
            ,markings
            ,mark=at position #1 with {\arrow{>}}}
        ,postaction={decorate}
        ,shorten >=-3pt,shorten <=-3pt
    }
}

\begin{document}
    \begin{tikzpicture}
    \node [mynode,label=90:$A$] (Anode) {$A-T$ \nodepart{lower} $\vphantom{f(}T$};
    \node [mynode,label=90:$B$,right = of Anode] (Bnode) {$B-f(T)$ \nodepart{lower} $f(T)$};
    \draw[->-=.53] (Anode) to [bend right=20] node[below]{$f$} (Bnode);
    \draw[->-=.53] (Bnode) to [bend right=20] node[above]{$g$} (Anode);
    \end{tikzpicture}
\end{document}

A: \documentclass[tikz,border=2mm]{standalone}

\begin{document}

    \begin{tikzpicture}
        \node[draw,circle,minimum width=2cm] at (0,0) (A) {};
        \node[above] at (A.north) {$A$};
        \draw (A.west) -- (A.east);
        \path (A.center) -- node{$A-T$} (A.north);
        \path (A.center) -- node{$T$} (A.south);

        \node[draw,circle,minimum width=2cm] at (4,0) (B) {};
        \node[above] at (B.north) {$B$};
        \draw (B.west) -- (B.east);
        \path (B.center) -- node{$B-f(T)$} (B.north);
        \path (B.center) -- node{$f(T)$} (B.south);

        \draw[>=latex,->] (B.north west) to [in=20,out=160] node[above] {$g$} (A.north east);
        \draw[>=latex,->] (A.south east) to [in=200,out=340] node[below] {$f$} (B.south west);
    \end{tikzpicture}

\end{document}

EDIT: arrows start and end inside circles and arrowheads are now in the middle
By using the calc library it is possible to calculate start (and end) positions for the arrows. For example ($(B.north east)!.8!(B.north west)$) means: start the arrow at 80% in between (B.north east) and (B.north west)
Using the decorations.markings library makes it possible to change the position of the arrowhead.
\documentclass[tikz,border=2mm]{standalone}
\usetikzlibrary{calc,decorations.markings}

\begin{document}
    \tikzset{->-/.style={decoration={markings,mark=at position #1 with {\arrow{>}}},postaction={decorate}}}
    \begin{tikzpicture}
        \node[draw,circle,minimum width=2cm] at (0,0) (A) {};
        \node[above] at (A.north) {$A$};
        \draw (A.west) -- (A.east);
        \path (A.center) -- node{$A-T$} ($(A.north)!.3!(A.center)$);
        \path (A.center) -- node{$T$} ($(A.south)!.3!(A.center)$);

        \node[draw,circle,minimum width=2cm] at (4,0) (B) {};
        \node[above] at (B.north) {$B$};
        \draw (B.west) -- (B.east);
        \path (B.center) -- node{$B-f(T)$} ($(B.north)!.3!(B.center)$);
        \path (B.center) -- node{$f(T)$} ($(B.south)!.3!(B.center)$);

        \draw[>=latex,->-=.5] ($(B.north east)!.8!(B.north west)$) to [in=20,out=160] node[above] {$g$} ($(A.north east)!.2!(A.north west)$);
        \draw[>=latex,->-=.5] ($(A.south east)!.2!(A.south west)$) to [in=200,out=340] node[below] {$f$} ($(B.south west)!.2!(B.south east)$);
    \end{tikzpicture}

\end{document}


text:
Q: Getting EINVAL when trying to write to mtd device I am referring to the code in this answer.
I added error handling though.
The open() erase and the read() all perform without error and the 20 bytes that I read all are 0xff.
However, when trying to write the 20 bytes from the data[] array, I get an EINVAL errorcode from the write() function.
What could be the cause of the problem? I did erase the memory before trying to write...

A: I have seen your original post.
I have the same problem recently, and I found that the write size is important.
mtd_info_t(struct mtd_info_user) have a variable named writesize
(reference: https://elixir.bootlin.com/linux/v3.2/source/include/mtd/mtd-abi.h#L125)
struct mtd_info_user {
    __u8 type;
    __u32 flags;
    __u32 size; /* Total size of the MTD */
    __u32 erasesize;
    __u32 writesize;
    __u32 oobsize;  /* Amount of OOB data per block (e.g. 16) */
    __u64 padding;  /* Old obsolete field; do not use */
};

when write to the mtd, should notice writesize
#include <fcntl.h>
#include <mtd/mtd-user.h>
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <sys/ioctl.h>

int main(){
    mtd_info_t mtd_info;           // the MTD structure
    erase_info_t ei;               // the erase block structure
    int i;

    unsigned char read_buf[20] = {0x00};                // empty array for reading

    int fd = open("/dev/mtd0", O_RDWR); // open the mtd device for reading and
                                        // writing. Note you want mtd0 not mtdblock0
                                        // also you probably need to open permissions
                                        // to the dev (sudo chmod 777 /dev/mtd0)

    ioctl(fd, MEMGETINFO, &mtd_info);   // get the device info

    // dump it for a sanity check, should match what's in /proc/mtd
    printf("MTD Type: %x\nMTD total size: %x(hex) bytes\nMTD erase size: %x(hex) bytes\nMTD write size: %x(hex) bytes\n",
        mtd_info.type, mtd_info.size, mtd_info.erasesize, mtd_info.writesize);

    ei.length = mtd_info.erasesize;   //set the erase block size
    for(ei.start = 0; ei.start < mtd_info.size; ei.start += ei.length)
    {
        ioctl(fd, MEMUNLOCK, &ei);
        // printf("Eraseing Block %#x\n", ei.start); // show the blocks erasing
                                                  // warning, this prints a lot!
        ioctl(fd, MEMERASE, &ei);
    }

    lseek(fd, 0, SEEK_SET);               // go to the first block
    read(fd, read_buf, sizeof(read_buf)); // read 20 bytes

    // sanity check, should be all 0xFF if erase worked
    for(i = 0; i<20; i++)
        printf("buf[%d] = 0x%02x\n", i, (unsigned int)read_buf[i]);

    /**********************************************************
     *   important part!                                      *
     *   notice the size of data array is mtd_info.writesize  *
     **********************************************************/
    uint32_t write_size = mtd_info.writesize;
    unsigned char data[write_size];//write 0
    bzero(data, write_size);

    lseek(fd, 0, SEEK_SET);        // go back to first block's start
    write(fd, data, sizeof(data)); // write our message

    lseek(fd, 0, SEEK_SET);              // go back to first block's start
    read(fd, read_buf, sizeof(read_buf));// read the data

    // sanity check, now you see the message we wrote!
    for(i = 0; i<20; i++)
        printf("buf[%d] = 0x%02x\n", i, (unsigned int)read_buf[i]);

    close(fd);
    return 0;
}

Hope it can help

A: From ./drivers/mtd/nand/nand_base.c
#define NOTALIGNED(x) ((x & (chip->subpagesize - 1)) != 0)

This is the check performed by driver:

/* Reject writes, which are not page aligned */
if (NOTALIGNED(to) || NOTALIGNED(ops->len)) {
    pr_notice("%s: attempt to write non page aligned data\n",__func__);
return -EINVAL;
}

Both the address you are starting the write and and length of the buffer you are writing must satisfy the macro condition(to be multiple of the subpage size).


text:
Q: Can I make Selenium work with an existing session? (Python) I am currently having a problem with 2FA on a website.. A way to resolve this would be to allow selenium to work with existing sessions; is there a way to allow / make selenium work with existing sessions -- instead of just making an entirely new, fresh one?
Thanks a bunch.


text:
Q: Getting ForbiddenError: invalid csrf token with multer added locally to image upload router I am using csurf as recommended in my Express application to guard against cross sites forgeries. I have registered it globally(illustrated with code below) and so far so good.
Now, I have added multer.js to be able to upload images and as their documentation recommends it, it's more secure to attach multer to each express route where you intend to use.
Now when I do attach multer to my upload routes, I am faced with a 'ForbiddenError: invalid csrf token' and I really don't know why, as my view I am submitting the form from, as a csrf token attached to it.
Below is my code and I would really appreciated any help/suggestions. Thank you all
app.js
const express = require('express');
const csrf = require('csurf');
const csrfProtection = csrf();
const shopRoute = require('../Routes/shop');
const app = express();

app.use(csrfProtection);
app.use(shopRoutes);

routes.js
const express = require('express')
const router = express.Router();

const multer = require('multer');
const controllers = require('../Controllers/shop');

router.post('/upload', multer({storage: multer.memoryStorage(), fileFilter: fileFilter), controller.uploadFunction);

A: I'm guessing the problem is that when you are uploading a file, the content type of the request becomes multipart/form-data, and you cannot simply pass the csrf token to Express in the body anymore.
The API allows to pass it in the URL though. Try passing the token in the _csrf parameter, that I think should solve your issue. So simply post the form to .../?_csrf={your_token}. Note though that this is slightly less secure than passing your csrf token in the request body, and might be flagged as a potential vulnerability in later penetration tests if you ever have one.
Alternatively, for a little more security, you can also pass it as a request header, but that might be a little trickier on the client side. According to the docs, Express will take the token from the following:
req.body._csrf - typically generated by the body-parser module.
req.query._csrf - a built-in from Express.js to read from the URL query string.
req.headers['csrf-token'] - the CSRF-Token HTTP request header.
req.headers['xsrf-token'] - the XSRF-Token HTTP request header.
req.headers['x-csrf-token'] - the X-CSRF-Token HTTP request header.
req.headers['x-xsrf-token'] - the X-XSRF-Token HTTP request header.

So adding a csrf-token header should also work.
Disclaimer: I don't know multer.js at all, and have very little experience with Express.


text:
Q: New-PSSession - WinRM cannot process the request I am trying to list all the websites in IIS on a remote server using PowerShell scripting. Below is how I am trying to connect to the server:
$s = New-PSSession -ComputerName $Server

But when I run the script I am getting the following error:

New-PSSession : [Server] Connecting to remote server Server failed with the
following error message : WinRM cannot process the request. The following error
occurred while using Kerberos authentication: Cannot find the computer Server.
Verify that the computer exists on the network and that the name provided is
spelled correctly. For more information, see the about_Remote_Troubleshooting
Help topic.
At C:\AppServers\Application.ps1:8 char:8
+         $s = New-PSSession -ComputerName Server
+              ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : OpenError: (System.Manageme....RemoteRunspace:RemoteRunspace) [New-PSSession], PSRemotingTransportException
    + FullyQualifiedErrorId : NetworkPathNotFound,PSSessionOpenFailed

The server is already enabled to receive remote requests.

Update:

Below is the full function that i am trying to run:
function audit-servers {
if (Test-path "ApplicationsOnTheServer.txt") {Remove-Item "ApplicationsOnTheServer.txt"}
if (Test-Path "ServersList.txt") {
foreach ($server in Get-Content .\ServersList.txt) {

    "Application Server : $server`n" | out-file -FilePath "ApplicationsOnTheServer.txt" -Append
    "Applications list:" | out-file -FilePath "ApplicationsOnTheServer.txt" -Append
    $s = New-PSSession -ComputerName $server -Credential domainabc\myname
    Invoke-Command -Session $s -ScriptBlock {Import-Module WebAdministration;Get-iissite} | out-file -FilePath "ApplicationsOnTheServer.txt" -Append
}
} else {
    "ServersList.txt file is missing"
     break;
}
"`nAll Done!`n"}

The ServersList.txt has atstappvmabc.tsteag.com

A: The error message clearly states that you wanted to connect to the server named Server not to the server which name is stored in $Server variable (text in bold is actually the name of the server you try to connect to):

New-PSSession : [Server] Connecting to remote server Server failed

If you tried to connect to the server named for example MyServer01.example.com you'd receive the error like below (truncated):
PS C:\> New-PSSession -ComputerName "MyServer01.example.com"

New-PSSession : [MyServer01.example.com] Connecting to remote server MyServer01.example.com failed (...)

Even though you state that you try to execute
$s = New-PSSession -ComputerName $Server

You actually execute (notice missing dollar sign)
$s = New-PSSession -ComputerName Server

The above was also taken from the error message you pasted. I'd suggest to first skip the variable and try to enter server path in the command itself to verify it's working:
$s = New-PSSession -ComputerName "MyServer01.example.com"

And then, if it works, put the path in variable and test again.

A: The error you're receiving FullyQualifiedErrorId : NetworkPathNotFound generally means that the name you're passing to the -ComputerName parameter can't be resolved.
Perhaps try running Test-Connection $Server to troubleshoot what's happening there.

A: Your variable $Server contains wrong value. You have to assign valid computer name to $Server.


text:
Q: Simple Bluetooth device monitor with timestamps I have a Raspberry Pi whatever (yes, with BT) and I'd like it to function as a very simple Bluetooth monitor which records beacons/nearby-device-ids/whatevers that it hears about in a big long text file for later processing.
I have bluez et al. installed, and I can even do a
sudo bluetoothctl -- scan on

to get a nice ANSI-colored output of devices nearby:
[NEW] Device A3:33:00:AB:CC:FF A3-33-00-AB-CC-FF
[CHG] Device A3:33:00:AB:CC:FF RSSI: -72

&c
I can capture this output to a text file using the shell, and, despite the ANSI control character stuff, I'm very very happy.
The only thing I want but don't have is a timestamp against each entry.
OMG I've tried everything. I don't even care about sub-second precision. Pleeeeeease just some timestamps. I will just die if I can't get them.

A: Try the following command:
stdbuf -oL bluetoothctl -- scan on | ts

Explanation:
The ts utility adds a timestamp to the beginning of each line of input. It has many useful options like timestamp format, absolute or relative times (either elapsed time since the start of ts or since the previous line).
However, most programs, including bluetoothctl buffer their output if it is not connected to a terminal. This means that if we pipe the output into ts, nothing will get displayed until the buffer gets full, which means that a lot of lines have to accumulate before they all get flushed at once, defeating the purpose of ts. To work around this, we can use the stdbuf utility to override output buffering to happen line by line, i.e. as soon as a line is output it gets flushed and ts can timestamp and display it.


text:
Q: Why does order of operands matter when adding powershell strings and arrays? In powershell, when I add string + array the result is a string, but when I add array + string the result is an array?  Why is that?

A: PowerShell converts the second operand to the type of the first operand (if it can).


text:
Q: Fisher Information of Multi-taper Spectrum Estimate My question came up while I was reading the book chapter "Multitaper Analysis of Nonstationary and Nonlinear Time Series Data" by David Thomson from the book Nonlinear and Nonstationary Signal Processing, copyright Cambridge University Press, 2000.
In the chapter Thomson describes a weighting function over a frequency interval of width $2W$ given by the current estimate of Fisher information of the spectrum estimator.  If your current estimate of the spectrum is $\hat{S}$, then the estimate of Fisher information is given by:
$$\frac{Q_0(f')}{\hat{S}(f-f')}$$
$f'$ is a dummy variable for a convolution and $Q_0(f')$ is often given by $1 - (f'/W)^2$ , but not necessarily.  I was wondering if anyone could help me with a derivation, because Thomson leaves it out completely.
The weighting function arises in the context of coherent side lobe subtraction.


text:
Q: How to add a text box on google maps route? I need to create a a text box between the route directions like in here :

For start i was thinking to add tooltip...but i can't place them in the middle of the route like in the picture, or set it's position to be relative.

A: You can create a custom overlay as described in the documentation:
https://developers.google.com/maps/documentation/javascript/customoverlays
The sample code snippet might be
function routeOverlay(point, map, content) {
  this._point = point;
  this._map = map;

  this.div_ = null;
  this._cnt = content;

  this.setMap(map);
}
routeOverlay.prototype = new google.maps.OverlayView();

routeOverlay.prototype.onAdd = function () {
  var div = document.createElement('div');
  div.style.borderStyle = 'solid';
  div.style.borderWidth = '1px';
  div.style.backgroundColor = 'white';
  div.style.position = 'absolute';
  div.style.padding = '4px';
  div.style.zIndex = 1000;
  div.innerHTML = this._cnt;

  this.div_ = div;

  // Add the element to the "overlayLayer" pane.
  var panes = this.getPanes();
  panes.overlayLayer.appendChild(div);
}

routeOverlay.prototype.draw = function () {
  var overlayProjection = this.getProjection();
  var p = overlayProjection.fromLatLngToDivPixel(this._point);
  this.div_.style.left = p.x + 'px';
  this.div_.style.top = p.y + 'px';
}

routeOverlay.prototype.onRemove = function () {
  this.div_.parentNode.removeChild(this.div_);
  this.div_ = null;
}

routeOverlay.prototype.hide = function() {
  if (this.div_) {
    // The visibility property must be a string enclosed in quotes.
    this.div_.style.visibility = 'hidden';
  }
};

routeOverlay.prototype.show = function() {
  if (this.div_) {
    this.div_.style.visibility = 'visible';
  }
};

Later in you code you should create this overlay. For example:
if (status == google.maps.DirectionsStatus.OK) {
    directionsDisplay.setDirections(response);
    var ind = (response.routes[0].overview_path.length - response.routes[0].overview_path.length % 2) / 2;
    var rover = new routeOverlay(response.routes[0].overview_path[ind], map, 'Add your HTML here');
    rover.show();
} else {
    window.alert('Directions request failed due to ' + status);
}

I have modified your jsfiddle: http://jsfiddle.net/h54tmmcb/14/

You should create corresponding styles and corresponding content for the overlay.
Hope this helps!


text:
Q: indirection requires pointer operand and expected expression errors I keep getting errors similar to these:
pitstop.cpp:36:23: error: indirection requires pointer operand

        ('double' invalid)

         cost = UNLEADED * gallons;

                          ^ ~~~~~~~

pitstop.cpp:40:14: error: expected expression

                    cost = SUPER * gallons;                               ^

#include <iostream>
#include <iomanip>
using namespace std;

#define UNLEADED 3.45;
#define SUPER {UNLEADED + 0.10};
#define PREMIUM {SUPER + 0.10};

/*
    Author: Zach Stow
    Date:
    Homework
    Objective:
*/

double cost, gallons;
string gasType, finish, stop;

int main()
{
    for(;;)

    {

        cout <<"Hi, welcome to Pitstop.\n";
        cout <<"Enter the type of gas you need:";
        cin >> gasType;
        cout << endl;

        cout <<"Enter the amount of gallons you need:";
        cin >> gallons;
        cout << endl;

        if(gasType == "finish" || gasType == "stop")break;

        else if(gasType == "UNLEADED")
        {
            cost = UNLEADED * gallons;
        }
        else if(gasType == "SUPER")
        {
            cost = SUPER * gallons;
        }
        else if(gasType == "PREMIUM")
        {
            cost = PREMIUM * gallons;
        }

    }
    cout <<"You need to pay:$" << cost << endl;

    return(0);

}

A: Not a c++ expert, but I'm sure that to define a constant you just need to use the #define directive followed by the symbol and by the value you want to assign to it (even if the value itself is an expression, even if such expression is referencing another constant), the braces and the trailing semicolon are excessive:
// [...]

#define UNLEADED 3.45
#define SUPER (UNLEADED + 0.10)
#define PREMIUM (SUPER + 0.10)

//[...]

It compiled at the first attempt with such corrections.

A: The cause of the error is the semi colon at the end of the #define directive.
You have also used the incorrect type of brackets, try this instead:
#define UNLEADED 3.45

#define SUPER (UNLEADED + 0.10)

#define PREMIUM (SUPER + 0.10)

Note that when you use the #define directive whatever follows #define is substituted into your code. In this case after the preprocessor ran your code looked like this:
else if(gasType == "UNLEADED")
{
    cost = UNLEADED 3.45; * gallons;
}
else if(gasType == "SUPER")
{
    cost = {UNLEADED + 0.10}; * gallons;
}
else if(gasType == "PREMIUM")
{
    cost = PREMIUM {SUPER + 0.10}; * gallons;
}
The reason you were getting the indirection requires pointer operand error was the compiler trying to interpret this statement:
* gallons;
Because the * operator only has a single argument it is interpreted as a pointer dereference, luckily for you the gallons variable is not a pointer type. If gallons had been declared as a pointer type i.e. double cost, *gallons; and the cin wasn't there the code would compile but not do what you expect, probably throwing a segfault.
Macros defined with #define can be very powerful and very dangerous. There is usually a better way to achieve things in c++. In this case UNLEADED, SUPER_UNLEADED and PREMIUM could be declared as const double type i.e.
const double unleaded = 3.45;
const double super = unleaded + 0.10;
const double premium = super + 0.10;


text:
Q: How to use List Iterable functions in flutter I found iterable functions, but I am not sure how I can use.
For example, skip, take, map, forEach, fold and join
Could you give me examples how to use?

A: Yes, let's check the following sample code.
List<int> values = [1, 2, 3, 4, 5, 6, 7, 8, 9];

print(values.skip(5).toList());
//[6, 7, 8, 9]

print(values.skip(5).take(3).toList());
//[6, 7, 8]

values.skip(5).take(3).map((e) => e.toString()).forEach((element) {print(element);});
//6 7 8

String str = values.fold("initialValue",
        (previousValue, element) => previousValue + ", " + element.toString());
print(str);
//initialValue, 1, 2, 3, 4, 5, 6, 7, 8, 9

str = values.join(", ");
print(str);
//1, 2, 3, 4, 5, 6, 7, 8, 9

*

*skip(1) skips the first value, 1, in the values list literal.

*take(3) gets the next 3 values 2, 3, and 4 in the values list literal.

*map()   Returns a new lazy [Iterable] with elements that are created by calling f on each element of this Iterable in iteration order.

*fork()  Reduces a collection to a single value by iteratively combining each element of the collection with an existing value

*join()  Converts each element to a [String] and concatenates the strings.

A: Hi Avdienko and welcome to Stack Overflow. I will give you an example for a .forEach iterable function performed on a List.
List<int> listOfIntegers = [1, 2, 3, 4, 5];

listOfIntegers.forEach((element) {
   print(element.toString() + " ");
});

This code will result in printing "1 2 3 4 5 " to the console.


text:
Q: Resize stacklayout scrollview nativescript Hello I am trying to make a stacklayout change its size (heigth) by scrolling up or down is it possible?

A: Yes it is possible. use this way.
<DockLayout stretchLastChild="false" class="page-background">
  <GridLayout rows="30*, 70*">
    <GridLayout row="0" borderBottomWidth="3" borderColor="#af152d" rows="auto" class="logo-container">
        <GridLayout rows="*" row="0" class="image-container"></GridLayout>
    </GridLayout>
    <GridLayout row="1" rows="*" orientation="vertical">
        <ScrollView row="0" orientation="vertical">
            <StackLayout verticalAlignment="top">
            </StackLayout>
        </ScrollView>
    </GridLayout>
  </GridLayout>
</DockLayout>


text:
Q: How to send 404 for routes not defined in predicates path of spring cloud gateway? I have a spring cloud gateway application with following yml config:
spring:
  cloud:
    gateway:
      routes:
        - id: My gateway service
          uri: ${DEMO_URI}
          predicates:
            - Path=/api/demo/**

Now I have also defined security config:-
  @Bean
  public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) {
    log.debug("Configuring tenant web security");

    return http
        .csrf().disable()
        .authorizeExchange()
        .pathMatchers(appProps.getAuthWhitelist().toArray(String[]::new)).permitAll()
        .anyExchange().authenticated()
        .and()
        .addFilterAt(authenticationWebFilter(), SecurityWebFiltersOrder.AUTHENTICATION)
        .addFilterAt(authorizationWebFilter(), SecurityWebFiltersOrder.AUTHORIZATION)
        .build();
  }

Now for the requests for urls that is not defined in the yml is still going through the authentication filter. How can I skip that and send 404 for urls not defined in yml?
One idea I thought of is adding a custom web filter with highest precedence and add it to my security config and that filter will intercept the request and check for the path and return 404 but the problem with this one is how do I get the paths that is defined in yml configs in filter code?

A: Your filter should be called only if URI matches /api/demo/** path based on your given code.
Also if your filter is route specific then you can add that filter in routes definition directly like this.
spring:
  cloud:
    gateway:
      routes:
        - id: My gateway service
          uri: ${DEMO_URI}
          filters:
            - AuthenticationWebFilter
          predicates:
            - Path=/api/demo/**

and remove filter call from SecurityWebFilterChain.


text:
Q: AngularJs-Google-Maps Markers not displaying I'm confused because the AngularJs and HTML code is near exact to a project where this works, but this is also my first time using LAMP instead of MEAN/MERN so maybe it's something to do with that?
my HTML file is:

  <ng-map center="35.5951,-82.5515" zoom="12" on-click="vm.placeCheckpoint(data)">

    <marker id='{{checkpoint._id}}'
      ng-repeat="checkpoint in vm.checkpoints"
      position="{{checkpoint.position}}"
      on-click="vm.showDetail(checkpoint)"
      >
    </marker>

    <marker position="35.5951,-82.5515"></marker>

  </ng-map>

and map-controller.js is:
(function(window, angular, undefined) {
  angular.module('map')
  .controller('map-controller', ['NgMap', '$window', 'mapService',
    function(NgMap, $window, mapService) {

    var vm = this;
    // ==================== Map =====================================

    // Display map
    NgMap.getMap().then(function(map) {
      vm.map = map;
    });

    // Populate map with checkpoints
    mapService.getCheckpoints().then(function(data) {
      vm.checkpoints = data;
      console.log(vm.checkpoints); // logs as a list of objects
    });

  }])
})(window, window.angular);

About the only differences between this the server, variable names, and that Google is making me use an API key for this whereas it wasn't requiring it for the other. They're both hitting the same API to get the data.
Also, if I try adding an  directive, the map disappears.

A: First of all, make sure position property in vm.checkpoints array  has the proper format [lat,lng], for example:
[
    {
        "name": "Oslo",
        "position" : [ 59.923043,10.752839 ]
    },
    {
        "name": "Stockholm",
        "position" : [ 59.339025, 18.065818 ]
    }
]

Secondly, vm.checkpoints is undefined in marker directive, you need to change expression  ng-controller="map-controller" with ng-controller="map-controller as vm"
Example

(function (window, angular, undefined) {
    angular.module('map', ['ngMap'])

        .factory('mapService', function ($rootScope, $http) {
            var mapService = {
                getCheckpoints: function () {
                    return $http.get('https://rawgit.com/vgrem/a171e20cbe9915707e5b94c139105a65/raw/europe.json').then(function (response) {
                        return response.data;
                    });
                }
            }
            return mapService;
        })

        .controller('map-controller', ['NgMap', '$window', 'mapService',
            function (NgMap, $window, mapService) {
                var vm = this;
                vm.checkpoints = [];

                // Display map
                NgMap.getMap().then(function (map) {
                    vm.map = map;

                });
                // Populate map with checkpoints
                mapService.getCheckpoints().then(function (data) {
                    vm.checkpoints = data.map(function(item, idx){
                           var position = [item.position.lat,item.position.lng];
                           item._id = idx;
                           item.position = position;
                           return item;
                    });
                    console.log(vm.checkpoints); // logs as a list of objects
                });

                vm.showDetail = function(){
                    console.log('clicked')
                }

            }])
})(window, window.angular);

  <ng-map center="48.1049441,4.1858258" zoom="4" >

    <marker
      ng-repeat="checkpoint in vm.checkpoints"
      position="{{checkpoint.position}}"
      on-click="vm.showDetail(checkpoint)" >
    </marker>

  </ng-map>


text:
Q: Find a model for the given WFF Find a model for the given WFF:
$\exists xp(x) \rightarrow \forall xp(x)$
I'm interpreting this as saying "There exists an x in the function p(x) which implies For all X in p(x)?
So my solution says that all I have to do is just let Let the Domain D be the set of Natural Numbers, and let $p(x)$ be x equals x + 1...
But I don;t understand how that is a model for the given wff? What is that even implying/saying?

A: Let $\mathbb{N}$ be the set of natural numbers, and let $p(x)$ be the formula $x=x+1$. For any natural number $a$, $p(a)$ is false. So $\exists x p(x)$ is false in the natural numbers, and therefore for any sentence $\varphi$, the sentence $\exists xp(x)\to\varphi$ is true in the natural  numbers. In particular, let $\varphi$ be the sentence $\forall xp(x)$.
Alternately, we could let $p(x)$ be the formula $x=x$. Then $\exists xp(x)\to \forall x p(x)$ is true in the natural numbers. For $\forall xp(x)$ is true, and therefore whatever sentence $\varphi$ we choose, $\varphi\to\forall xp(x)$ will be true.

A: The statement, $\;\exists x\,P(x) \; \to \; \forall x \,P(x)\;$ is "if there is something that satisfies $P$, then all things satisfy $P$".   (This is not a tautology; its truth depends on what $P$ is.)
An equivalent statement is: $\;\forall x\,\neg P(x) \;\vee\; \forall x\,P(x)\;$ "Either no thing satisfies $P$ or all things satisfy $P$".
So you must find an model where predicate $P$, in a domain of discussion, is such that it is either true for all things or false for all things.

All below use the set of natural/integer/rational/real/complex numbers as the domain (pick any one).
$$\exists x\, (x=x+1)\;\to\;\forall x\, (x=x+1)$$
Now the predicate $x=x+1$ is false for all $x$.   Because the antecedent is false, therefore the implication is considered true.   This is a viable model.
$$\exists x\, (x=x+1)\;\to\;\forall x\, (x=x+1)$$
Here the predicate $x=x$ is true for all things. &\nbsp; Because both the antecedent and consequent are true, therefore the implication is validated.   This too is a viable model.
$$\require{cancel}
\color{red}{
 \cancel{
  \color{black}{
   \exists x\, (x=5)\;\to\;\forall x\, (x=5)
  }
 }
}$$
However, the predicate $x=5$ is true for one thing, but not for all things.   Because the antecedent is true but the consequent is false, therefore the implication does not hold.   So this is not a viable model.